CombinedText stringlengths 4 3.42M |
|---|
require 'formula'
class Jsdoc3 < Formula
homepage 'http://usejsdoc.org/'
url 'https://github.com/jsdoc3/jsdoc/archive/v3.2.0.tar.gz'
sha1 'ac682fd15e6863233835c8969be9e4212dc2e4eb'
head 'https://github.com/jsdoc3/jsdoc.git', :branch => 'master'
def install
libexec.install Dir['*']
bin.install_symlink libexec/'jsdoc'
end
end
jsdoc v3.2.1
Signed-off-by: Adam Vandenberg <34c2b6407fd5a10249a15d699d40f9ed1782e98c@gmail.com>
require 'formula'
class Jsdoc3 < Formula
homepage 'http://usejsdoc.org/'
url 'https://github.com/jsdoc3/jsdoc/archive/v3.2.1.tar.gz'
sha1 '9475bdef742dbdee96e002f000a2d99e05253093'
head 'https://github.com/jsdoc3/jsdoc.git', :branch => 'master'
def install
libexec.install Dir['*']
bin.install_symlink libexec/'jsdoc'
end
end
|
require 'spec_helper'
describe 'elasticsearch', :type => 'class' do
default_params = {
:config => {},
:manage_repo => true,
:repo_version => '1.3',
:version => '1.6.0'
}
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts.merge({ 'scenario' => '', 'common' => '' })
end
let (:params) do
default_params
end
context 'ordered with package pinning' do
let :params do
default_params
end
it { should contain_class(
'elasticsearch::package::pin'
).that_comes_before(
'Class[elasticsearch::repo]'
) }
end
context "Use anchor type for ordering" do
let :params do
default_params
end
it { should contain_class('elasticsearch::repo').that_requires('Anchor[elasticsearch::begin]') }
end
context "Use stage type for ordering" do
let :params do
default_params.merge({
:repo_stage => 'setup'
})
end
it { should contain_stage('setup') }
it { should contain_class('elasticsearch::repo').with(:stage => 'setup') }
end
case facts[:osfamily]
when 'Debian'
context 'has apt repo parts' do
it { should contain_apt__source('elasticsearch').with(:location => 'http://packages.elastic.co/elasticsearch/1.3/debian') }
end
when 'RedHat'
context 'has yum repo parts' do
it { should contain_yumrepo('elasticsearch').with(:baseurl => 'http://packages.elastic.co/elasticsearch/1.3/centos') }
end
when 'Suse'
context 'has zypper repo parts' do
it { should contain_exec('elasticsearch_suse_import_gpg')
.with(:command => 'rpmkeys --import https://artifacts.elastic.co/GPG-KEY-elasticsearch') }
it { should contain_zypprepo('elasticsearch').with(:baseurl => 'http://packages.elastic.co/elasticsearch/1.3/centos') }
it { should contain_exec('elasticsearch_zypper_refresh_elasticsearch') }
end
end
context "Override repo key ID" do
let :params do
default_params.merge({
:repo_key_id => '46095ACC8548582C1A2699A9D27D666CD88E42B4'
})
end
case facts[:osfamily]
when 'Debian'
context 'has override apt key' do
it { is_expected.to contain_apt__source('elasticsearch').with({
:key => {
'id' => '46095ACC8548582C1A2699A9D27D666CD88E42B4',
'source' => 'https://artifacts.elastic.co/GPG-KEY-elasticsearch'
}
})}
end
when 'Suse'
context 'has override yum key' do
it { is_expected.to contain_exec(
'elasticsearch_suse_import_gpg'
).with_unless(
"test $(rpm -qa gpg-pubkey | grep -i 'D88E42B4' | wc -l) -eq 1"
)}
end
end
end
context "Override repo source URL" do
let :params do
default_params.merge({
:repo_key_source => 'http://artifacts.elastic.co/GPG-KEY-elasticsearch'
})
end
case facts[:osfamily]
when 'Debian'
context 'has override apt key source' do
it { is_expected.to contain_apt__source('elasticsearch').with({
:key => {
'id' => '46095ACC8548582C1A2699A9D27D666CD88E42B4',
'source' => 'http://artifacts.elastic.co/GPG-KEY-elasticsearch'
}
})}
end
when 'RedHat'
context 'has override yum key source' do
it { should contain_yumrepo('elasticsearch')
.with(:gpgkey => 'http://artifacts.elastic.co/GPG-KEY-elasticsearch') }
end
when 'Suse'
context 'has override yum key source' do
it { should contain_exec('elasticsearch_suse_import_gpg')
.with(:command => 'rpmkeys --import http://artifacts.elastic.co/GPG-KEY-elasticsearch') }
end
end
end
context "Override repo proxy" do
let :params do
default_params.merge({
:repo_proxy => 'http://proxy.com:8080'
})
end
case facts[:osfamily]
when 'RedHat'
context 'has override repo proxy' do
it { is_expected.to contain_yumrepo('elasticsearch').with_proxy('http://proxy.com:8080') }
end
end
end
describe 'unified release repositories' do
let :params do
default_params.merge({
:repo_version => '5.x',
:version => '5.0.0'
})
end
case facts[:osfamily]
when 'Debian'
it { should contain_apt__source('elasticsearch')
.with_location('https://artifacts.elastic.co/packages/5.x/apt') }
when 'RedHat'
it { should contain_yum__versionlock('0:elasticsearch-5.0.0-1.noarch') }
it { should contain_yumrepo('elasticsearch')
.with_baseurl('https://artifacts.elastic.co/packages/5.x/yum') }
when 'Suse'
it { should contain_zypprepo('elasticsearch')
.with_baseurl('https://artifacts.elastic.co/packages/5.x/yum') }
end
end
end
end
end
remove test for resource chaining
require 'spec_helper'
describe 'elasticsearch', :type => 'class' do
default_params = {
:config => {},
:manage_repo => true,
:repo_version => '1.3',
:version => '1.6.0'
}
on_supported_os.each do |os, facts|
context "on #{os}" do
let(:facts) do
facts.merge({ 'scenario' => '', 'common' => '' })
end
let (:params) do
default_params
end
context "Use anchor type for ordering" do
let :params do
default_params
end
it { should contain_class('elasticsearch::repo').that_requires('Anchor[elasticsearch::begin]') }
end
context "Use stage type for ordering" do
let :params do
default_params.merge({
:repo_stage => 'setup'
})
end
it { should contain_stage('setup') }
it { should contain_class('elasticsearch::repo').with(:stage => 'setup') }
end
case facts[:osfamily]
when 'Debian'
context 'has apt repo parts' do
it { should contain_apt__source('elasticsearch').with(:location => 'http://packages.elastic.co/elasticsearch/1.3/debian') }
end
when 'RedHat'
context 'has yum repo parts' do
it { should contain_yumrepo('elasticsearch').with(:baseurl => 'http://packages.elastic.co/elasticsearch/1.3/centos') }
end
when 'Suse'
context 'has zypper repo parts' do
it { should contain_exec('elasticsearch_suse_import_gpg')
.with(:command => 'rpmkeys --import https://artifacts.elastic.co/GPG-KEY-elasticsearch') }
it { should contain_zypprepo('elasticsearch').with(:baseurl => 'http://packages.elastic.co/elasticsearch/1.3/centos') }
it { should contain_exec('elasticsearch_zypper_refresh_elasticsearch') }
end
end
context "Override repo key ID" do
let :params do
default_params.merge({
:repo_key_id => '46095ACC8548582C1A2699A9D27D666CD88E42B4'
})
end
case facts[:osfamily]
when 'Debian'
context 'has override apt key' do
it { is_expected.to contain_apt__source('elasticsearch').with({
:key => {
'id' => '46095ACC8548582C1A2699A9D27D666CD88E42B4',
'source' => 'https://artifacts.elastic.co/GPG-KEY-elasticsearch'
}
})}
end
when 'Suse'
context 'has override yum key' do
it { is_expected.to contain_exec(
'elasticsearch_suse_import_gpg'
).with_unless(
"test $(rpm -qa gpg-pubkey | grep -i 'D88E42B4' | wc -l) -eq 1"
)}
end
end
end
context "Override repo source URL" do
let :params do
default_params.merge({
:repo_key_source => 'http://artifacts.elastic.co/GPG-KEY-elasticsearch'
})
end
case facts[:osfamily]
when 'Debian'
context 'has override apt key source' do
it { is_expected.to contain_apt__source('elasticsearch').with({
:key => {
'id' => '46095ACC8548582C1A2699A9D27D666CD88E42B4',
'source' => 'http://artifacts.elastic.co/GPG-KEY-elasticsearch'
}
})}
end
when 'RedHat'
context 'has override yum key source' do
it { should contain_yumrepo('elasticsearch')
.with(:gpgkey => 'http://artifacts.elastic.co/GPG-KEY-elasticsearch') }
end
when 'Suse'
context 'has override yum key source' do
it { should contain_exec('elasticsearch_suse_import_gpg')
.with(:command => 'rpmkeys --import http://artifacts.elastic.co/GPG-KEY-elasticsearch') }
end
end
end
context "Override repo proxy" do
let :params do
default_params.merge({
:repo_proxy => 'http://proxy.com:8080'
})
end
case facts[:osfamily]
when 'RedHat'
context 'has override repo proxy' do
it { is_expected.to contain_yumrepo('elasticsearch').with_proxy('http://proxy.com:8080') }
end
end
end
describe 'unified release repositories' do
let :params do
default_params.merge({
:repo_version => '5.x',
:version => '5.0.0'
})
end
case facts[:osfamily]
when 'Debian'
it { should contain_apt__source('elasticsearch')
.with_location('https://artifacts.elastic.co/packages/5.x/apt') }
when 'RedHat'
it { should contain_yum__versionlock('0:elasticsearch-5.0.0-1.noarch') }
it { should contain_yumrepo('elasticsearch')
.with_baseurl('https://artifacts.elastic.co/packages/5.x/yum') }
when 'Suse'
it { should contain_zypprepo('elasticsearch')
.with_baseurl('https://artifacts.elastic.co/packages/5.x/yum') }
end
end
end
end
end
|
class Libgee < Formula
desc "Collection library providing GObject-based interfaces"
homepage "https://wiki.gnome.org/Projects/Libgee"
url "https://download.gnome.org/sources/libgee/0.16/libgee-0.16.0.tar.xz"
sha256 "a26243eac4280f2d2ebd34b377fc5dc7a73633bcc4c339af6162031943d76aae"
bottle do
cellar :any
revision 1
sha1 "d09eb775cbac0b46eb75e548f52026a1395162b7" => :yosemite
sha1 "ac4c971d1f2cb3e72f4670dd87e30447aaf11533" => :mavericks
sha1 "efd2606ad62ff3368e6a72fb1df087a2085ee143" => :mountain_lion
end
depends_on "pkg-config" => :build
depends_on "vala" => :build
depends_on "gobject-introspection"
def install
system "./configure", "--prefix=#{prefix}",
"--disable-dependency-tracking",
"--enable-introspection=yes"
system "make", "install"
end
end
libgee 0.18.0
class Libgee < Formula
desc "Collection library providing GObject-based interfaces"
homepage "https://wiki.gnome.org/Projects/Libgee"
url "https://download.gnome.org/sources/libgee/0.18/libgee-0.18.0.tar.xz"
sha256 "4ad99ef937d071b4883c061df40bfe233f7649d50c354cf81235f180b4244399"
bottle do
cellar :any
revision 1
sha1 "d09eb775cbac0b46eb75e548f52026a1395162b7" => :yosemite
sha1 "ac4c971d1f2cb3e72f4670dd87e30447aaf11533" => :mavericks
sha1 "efd2606ad62ff3368e6a72fb1df087a2085ee143" => :mountain_lion
end
depends_on "pkg-config" => :build
depends_on "vala" => :build
depends_on "gobject-introspection"
def install
# ensures that the gobject-introspection files remain within the keg
inreplace "gee/Makefile.in" do |s|
s.gsub! "@HAVE_INTROSPECTION_TRUE@girdir = @INTROSPECTION_GIRDIR@",
"@HAVE_INTROSPECTION_TRUE@girdir = $(datadir)/gir-1.0"
s.gsub! "@HAVE_INTROSPECTION_TRUE@typelibdir = @INTROSPECTION_TYPELIBDIR@",
"@HAVE_INTROSPECTION_TRUE@typelibdir = $(libdir)/girepository-1.0"
end
system "./configure", "--prefix=#{prefix}",
"--disable-dependency-tracking"
system "make", "install"
end
test do
(testpath/"test.c").write <<-EOS.undent
#include <gee.h>
int main(int argc, char *argv[]) {
GType type = gee_traversable_stream_get_type();
return 0;
}
EOS
gettext = Formula["gettext"]
glib = Formula["glib"]
flags = (ENV.cflags || "").split + (ENV.cppflags || "").split + (ENV.ldflags || "").split
flags += %W[
-I#{gettext.opt_include}
-I#{glib.opt_include}/glib-2.0
-I#{glib.opt_lib}/glib-2.0/include
-I#{include}/gee-0.8
-L#{gettext.opt_lib}
-L#{glib.opt_lib}
-L#{lib}
-lgee-0.8
-lglib-2.0
-lgobject-2.0
-lintl
]
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: eucalyptus 0.2.6 ruby lib
Gem::Specification.new do |s|
s.name = "eucalyptus"
s.version = "0.2.6"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Oguz Huner"]
s.date = "2015-06-26"
s.description = "An easy interface and abstraction to the Facebook Ads API"
s.email = "oguzcanhuner@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md"
]
s.files = [
".document",
".rspec",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.md",
"Rakefile",
"VERSION",
"eucalyptus.gemspec",
"lib/eucalyptus.rb",
"lib/eucalyptus/account.rb",
"lib/eucalyptus/ad.rb",
"lib/eucalyptus/ad_set.rb",
"lib/eucalyptus/campaign.rb",
"lib/eucalyptus/custom_audience.rb",
"lib/eucalyptus/insight.rb",
"lib/eucalyptus/resource.rb",
"lib/eucalyptus/response.rb",
"spec/eucalyptus/account_spec.rb",
"spec/eucalyptus/ad_set_spec.rb",
"spec/eucalyptus/ad_spec.rb",
"spec/eucalyptus/campaign_spec.rb",
"spec/eucalyptus/custom_audience_spec.rb",
"spec/eucalyptus/insight_spec.rb",
"spec/eucalyptus/resource_spec.rb",
"spec/eucalyptus_spec.rb",
"spec/spec_helper.rb"
]
s.homepage = "http://github.com/oguzcanhuner/eucalyptus"
s.licenses = ["MIT"]
s.rubygems_version = "2.4.4"
s.summary = "An easy interface and abstraction to the Facebook Ads API"
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<koala>, [">= 0"])
s.add_development_dependency(%q<rspec>, [">= 0"])
s.add_development_dependency(%q<vcr>, [">= 0"])
s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
s.add_development_dependency(%q<bundler>, ["~> 1.0"])
s.add_development_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_development_dependency(%q<pry>, [">= 0"])
s.add_development_dependency(%q<dotenv>, [">= 0"])
s.add_development_dependency(%q<webmock>, [">= 0"])
else
s.add_dependency(%q<koala>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 0"])
s.add_dependency(%q<vcr>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_dependency(%q<pry>, [">= 0"])
s.add_dependency(%q<dotenv>, [">= 0"])
s.add_dependency(%q<webmock>, [">= 0"])
end
else
s.add_dependency(%q<koala>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 0"])
s.add_dependency(%q<vcr>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_dependency(%q<pry>, [">= 0"])
s.add_dependency(%q<dotenv>, [">= 0"])
s.add_dependency(%q<webmock>, [">= 0"])
end
end
Regenerate gemspec for version 0.2.7
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: eucalyptus 0.2.7 ruby lib
Gem::Specification.new do |s|
s.name = "eucalyptus"
s.version = "0.2.7"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Oguz Huner"]
s.date = "2015-06-28"
s.description = "An easy interface and abstraction to the Facebook Ads API"
s.email = "oguzcanhuner@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md"
]
s.files = [
".document",
".rspec",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.md",
"Rakefile",
"VERSION",
"eucalyptus.gemspec",
"lib/eucalyptus.rb",
"lib/eucalyptus/account.rb",
"lib/eucalyptus/ad.rb",
"lib/eucalyptus/ad_set.rb",
"lib/eucalyptus/campaign.rb",
"lib/eucalyptus/custom_audience.rb",
"lib/eucalyptus/insight.rb",
"lib/eucalyptus/resource.rb",
"lib/eucalyptus/response.rb",
"spec/eucalyptus/account_spec.rb",
"spec/eucalyptus/ad_set_spec.rb",
"spec/eucalyptus/ad_spec.rb",
"spec/eucalyptus/campaign_spec.rb",
"spec/eucalyptus/custom_audience_spec.rb",
"spec/eucalyptus/insight_spec.rb",
"spec/eucalyptus/resource_spec.rb",
"spec/eucalyptus_spec.rb",
"spec/spec_helper.rb"
]
s.homepage = "http://github.com/oguzcanhuner/eucalyptus"
s.licenses = ["MIT"]
s.rubygems_version = "2.4.4"
s.summary = "An easy interface and abstraction to the Facebook Ads API"
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<koala>, [">= 0"])
s.add_development_dependency(%q<rspec>, [">= 0"])
s.add_development_dependency(%q<vcr>, [">= 0"])
s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
s.add_development_dependency(%q<bundler>, ["~> 1.0"])
s.add_development_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_development_dependency(%q<pry>, [">= 0"])
s.add_development_dependency(%q<dotenv>, [">= 0"])
s.add_development_dependency(%q<webmock>, [">= 0"])
else
s.add_dependency(%q<koala>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 0"])
s.add_dependency(%q<vcr>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_dependency(%q<pry>, [">= 0"])
s.add_dependency(%q<dotenv>, [">= 0"])
s.add_dependency(%q<webmock>, [">= 0"])
end
else
s.add_dependency(%q<koala>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 0"])
s.add_dependency(%q<vcr>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_dependency(%q<pry>, [">= 0"])
s.add_dependency(%q<dotenv>, [">= 0"])
s.add_dependency(%q<webmock>, [">= 0"])
end
end
|
require 'rails_helper'
RSpec.describe AnswersController, type: :controller do
let(:question) { create(:question) }
let(:answer) { create(:answer, question: question) }
describe 'GET #new' do
before { get :new, params: { question_id: question } }
it 'assigns a new Answer to @answer' do
expect(assigns(:answer)).to be_a_new(Answer)
end
it 'render new view' do
expect(response).to render_template :new
end
end
describe 'POST #create' do
context 'with valid attributes' do
it 'it saves new answer to db' do
expect { process :create, method: :post, params: {answer: attributes_for(:answer), question_id: question }}
.to change(question.answers, :count).by(1)
end
it 'redirects to @question' do
process :create, method: :post, params: { answer: attributes_for(:answer), question_id: question }
expect(response).to redirect_to question_path(question)
end
end
context 'with invalid attributes' do
it 'does not save new answer to db' do
expect {
process :create, method: :post, params: {
answer: attributes_for(:invalid_answer),
question_id: question
}
}.to_not change(question.answers, :count)
end
it 're-renders new view' do
process :create, method: :post, params: {
answer: attributes_for(:invalid_answer), question_id: question
}
expect(response).to render_template :new
end
end
end
end
Minor fix after review
require 'rails_helper'
RSpec.describe AnswersController, type: :controller do
let(:question) { create(:question) }
let(:answer) { create(:answer, question: question) }
describe 'GET #new' do
before { get :new, params: { question_id: question } }
it 'assigns a new Answer to @answer' do
expect(assigns(:answer)).to be_a_new(Answer)
end
it 'render new view' do
expect(response).to render_template :new
end
end
describe 'POST #create' do
context 'with valid attributes' do
it 'it saves new answer to db' do
expect { process :create, method: :post, params: {answer: attributes_for(:answer), question_id: question }}
.to change(question.answers, :count).by(1)
end
it 'redirects to @question' do
process :create, method: :post, params: { answer: attributes_for(:answer), question_id: question }
expect(response).to redirect_to question_path(question)
end
end
context 'with invalid attributes' do
it 'does not save new answer to db' do
expect {
process :create, method: :post, params: {
answer: attributes_for(:invalid_answer),
question_id: question
}
}.to_not change(Answer, :count)
end
it 're-renders new view' do
process :create, method: :post, params: {
answer: attributes_for(:invalid_answer), question_id: question
}
expect(response).to render_template :new
end
end
end
end |
class Libpst < Formula
desc "Utilities for the PST file format"
homepage "http://www.five-ten-sg.com/libpst/"
url "http://www.five-ten-sg.com/libpst/packages/libpst-0.6.63.tar.gz"
sha256 "5f522606fb7b97d6e31bc2490dcce77b89ec77e12ade4af4551290f953483062"
bottle do
cellar :any
sha1 "9c4d9e444577b05d8fd6fe9759840f29776639de" => :yosemite
sha1 "0b7150bc158799b80cdaf6b5cfdfae740214ee96" => :mavericks
sha1 "f604465213aae3bc5711fa8633cf25e910dd4799" => :mountain_lion
end
option "with-pst2dii", "Build pst2dii using gd"
deprecated_option "pst2dii" => "with-pst2dii"
depends_on :python => :optional
depends_on "pkg-config" => :build
depends_on "gd" if build.with? "pst2dii"
depends_on "boost"
depends_on "gettext"
depends_on "libgsf"
depends_on "boost-python" if build.with? "python"
def install
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
]
args << "--disable-dii" if build.with? "pst2dii"
if build.with? "python"
args << "--enable-python" << "--with-boost-python=mt"
else
args << "--disable-python"
end
system "./configure", *args
system "make"
system "make", "install"
end
test do
system bin/"lspst", "-V"
end
end
libpst 0.6.65
Closes #44165.
Signed-off-by: Dominyk Tiller <53e438f55903875d07efdd98a8aaf887e7208dd3@gmail.com>
class Libpst < Formula
desc "Utilities for the PST file format"
homepage "http://www.five-ten-sg.com/libpst/"
url "http://www.five-ten-sg.com/libpst/packages/libpst-0.6.65.tar.gz"
sha256 "89e895f6d70c125dd9953f42069c1aab601ed305879b5170821e33cee3c94e23"
bottle do
cellar :any
sha1 "9c4d9e444577b05d8fd6fe9759840f29776639de" => :yosemite
sha1 "0b7150bc158799b80cdaf6b5cfdfae740214ee96" => :mavericks
sha1 "f604465213aae3bc5711fa8633cf25e910dd4799" => :mountain_lion
end
option "with-pst2dii", "Build pst2dii using gd"
deprecated_option "pst2dii" => "with-pst2dii"
depends_on :python => :optional
depends_on "pkg-config" => :build
depends_on "gd" if build.with? "pst2dii"
depends_on "boost"
depends_on "gettext"
depends_on "libgsf"
depends_on "boost-python" if build.with? "python"
def install
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
]
args << "--disable-dii" if build.with? "pst2dii"
if build.with? "python"
args << "--enable-python" << "--with-boost-python=mt"
else
args << "--disable-python"
end
system "./configure", *args
system "make"
system "make", "install"
end
test do
system bin/"lspst", "-V"
end
end
|
require 'rails_helper'
RSpec.describe AnswersController, type: :controller do
sign_in_user
let!(:question) { create(:valid_question) }
let(:answer) { create(:valid_answer, question: question ) }
describe 'POST #create' do
context 'with valid attributes' do
it 'save new answer in database' do
expect {
post :create, params: { answer: attributes_for(:valid_answer), question_id: question }
}.to change(question.answers, :count).by(1)
end
it 'redirect to show view' do
post :create, params: { answer: attributes_for(:valid_answer), question_id: question }
expect(response).to redirect_to question_path(assigns(:question))
end
end
context 'with invalid attributes' do
it 'doesnt save new answer in database' do
expect {
post :create, params: { answer: attributes_for(:invalid_answer), question_id: question }
}.to_not change(Answer, :count)
end
it 'renders new view' do
post :create, params: { answer: attributes_for(:invalid_answer), question_id: question }
expect(response).to render_template 'questions/show'
end
end
end
describe 'DELETE #destroy' do
context 'author of the answer' do
let!(:user_answer) { create(:valid_answer, question: question, user: @user) }
it 'can delete the answer' do
expect { delete :destroy, params: { id: user_answer } }.to change(Answer, :count).by(-1)
end
it 'redirect to question page' do
delete :destroy, params: { id: user_answer }
expect(response).to redirect_to user_answer.question
end
end
context 'non author of the answer' do
let(:user) { create(:user) }
let!(:answer) { create(:valid_answer, question: question, user: user) }
it 'cannot delete the answer' do
expect { delete :destroy, params: { id: answer } }.to_not change(Answer, :count)
end
it 're-render question show page' do
delete :destroy, params: { id: answer }
expect(response).to render_template 'questions/show'
end
end
end
end
Add tests to answer controller spec.
require 'rails_helper'
RSpec.describe AnswersController, type: :controller do
let!(:question) { create(:valid_question) }
let(:answer) { create(:valid_answer, question: question) }
describe 'POST #create' do
context 'Authenticate user try create answer' do
sign_in_user
context 'with valid attributes' do
it 'save new answer in database' do
expect {
post :create, params: {
answer: attributes_for(:valid_answer),
question_id: question,
user: @user
}
}.to change(question.answers, :count).by(1)
end
it 'redirect to show view' do
post :create, params: {
answer: attributes_for(:valid_answer),
question_id: question,
user: @user
}
expect(response).to redirect_to question_path(assigns(:question))
end
end
context 'with invalid attributes' do
it 'doesnt save new answer in database' do
expect {
post :create, params: { answer: attributes_for(:invalid_answer), question_id: question }
}.to_not change(Answer, :count)
end
it 'renders new view' do
post :create, params: { answer: attributes_for(:invalid_answer), question_id: question }
expect(response).to render_template 'questions/show'
end
end
end
context 'Non authenticate user try create answer' do
it 'doesnt save new answer in database' do
expect {
post :create, params: { answer: attributes_for(:invalid_answer), question_id: question, user: nil }
}.to_not change(Answer, :count)
end
it 'redirect to sign_in page' do
post :create, params: { answer: attributes_for(:invalid_answer), question_id: question }
expect(response).to redirect_to new_user_session_path
end
end
end
describe 'DELETE #destroy' do
sign_in_user
context 'author of the answer' do
let!(:user_answer) { create(:valid_answer, question: question, user: @user) }
it 'can delete the answer' do
expect { delete :destroy, params: { id: user_answer } }.to change(Answer, :count).by(-1)
end
it 'redirect to question page' do
delete :destroy, params: { id: user_answer }
expect(response).to redirect_to user_answer.question
end
end
context 'non author of the answer' do
let(:user) { create(:user) }
let!(:answer) { create(:valid_answer, question: question, user: user) }
it 'cannot delete the answer' do
expect { delete :destroy, params: { id: answer } }.to_not change(Answer, :count)
end
it 're-render question show page' do
delete :destroy, params: { id: answer }
expect(response).to render_template 'questions/show'
end
end
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'feedjira/opml/version'
Gem::Specification.new do |spec|
spec.name = 'feedjira-opml'
spec.version = Feedjira::OPML::VERSION
spec.authors = ['Chris Kalafarski']
spec.email = ['chris@farski.com']
spec.summary = %q{OPML parsing with Feedjira}
spec.description = %q{Rudimentary OPML parsing classes for Feedjira}
spec.homepage = 'https://github.com/farski/feedjira-opml'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = 'https://rubygems.org'
end
spec.add_development_dependency 'bundler', '~> 1.8'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'minitest', '~> 5.5'
spec.add_development_dependency 'coveralls', '~> 0'
spec.add_runtime_dependency 'feedjira', '~> 2.0'
end
Update Gemspec homepage
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'feedjira/opml/version'
Gem::Specification.new do |spec|
spec.name = 'feedjira-opml'
spec.version = Feedjira::OPML::VERSION
spec.authors = ['Chris Kalafarski']
spec.email = ['chris@farski.com']
spec.summary = %q{OPML parsing with Feedjira}
spec.description = %q{Rudimentary OPML parsing classes for Feedjira}
spec.homepage = 'https://github.com/scour/feedjira-opml'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = 'https://rubygems.org'
end
spec.add_development_dependency 'bundler', '~> 1.8'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'minitest', '~> 5.5'
spec.add_development_dependency 'coveralls', '~> 0'
spec.add_runtime_dependency 'feedjira', '~> 2.0'
end
|
require "formula"
class Libxmp < Formula
homepage "http://xmp.sourceforge.net"
url "https://downloads.sourceforge.net/project/xmp/libxmp/4.3.0/libxmp-4.3.0.tar.gz"
sha1 "7cc6acef4d3b86b9073851649d1b5f6f4a904e43"
bottle do
cellar :any
sha1 "5d838e452561152cbc569996d0b6c721a447bbc3" => :mavericks
sha1 "7ae31575dc3f7e052117a4d274ef65556095f485" => :mountain_lion
sha1 "39a97017b0ee409c2e6fe39a97c2be672393bcff" => :lion
end
head do
url "git://git.code.sf.net/p/xmp/libxmp"
depends_on :autoconf
end
def install
system "autoconf" if build.head?
system "./configure", "--prefix=#{prefix}"
system "make install"
end
end
libxmp: update 4.3.0 bottle.
require "formula"
class Libxmp < Formula
homepage "http://xmp.sourceforge.net"
url "https://downloads.sourceforge.net/project/xmp/libxmp/4.3.0/libxmp-4.3.0.tar.gz"
sha1 "7cc6acef4d3b86b9073851649d1b5f6f4a904e43"
bottle do
cellar :any
revision 1
sha1 "05a81df01e7861ccefd955673bd1a17604bd4100" => :yosemite
sha1 "772668a1ad68de0596a42ee9c75c37b82f5d027f" => :mavericks
end
head do
url "git://git.code.sf.net/p/xmp/libxmp"
depends_on :autoconf
end
def install
system "autoconf" if build.head?
system "./configure", "--prefix=#{prefix}"
system "make install"
end
end
|
# Copyright 2011-2013, The Trustees of Indiana University and Northwestern
# University. 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.
# --- END LICENSE_HEADER BLOCK ---
require 'spec_helper'
describe DropboxController do
before do
# there is no easy way to build objects because of the way roles are set up
# therefore this test could fail in the future if the archivist role doesn't
# have the group admin_policy_object_editor. roles should be refactored into
# a database backed model SOON so testing of permissions/abilities is more granular
login_as :administrator
@temp_files = (0..20).map{|index| { name: "a_movie_#{index}.mov" } }
@dropbox = double(Avalon::Dropbox)
@dropbox.stub(:all).and_return @temp_files
Avalon::Dropbox.stub(:new).and_return(@dropbox)
end
it 'deletes video/audio files' do
@dropbox.should_receive(:delete).exactly(@temp_files.count).times
delete :bulk_delete, { :filenames => @temp_files.map{|f| f[:name] } }
end
end
Supply collection_id in request to dropbox controller
# Copyright 2011-2013, The Trustees of Indiana University and Northwestern
# University. 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.
# --- END LICENSE_HEADER BLOCK ---
require 'spec_helper'
describe DropboxController do
before do
# there is no easy way to build objects because of the way roles are set up
# therefore this test could fail in the future if the archivist role doesn't
# have the group admin_policy_object_editor. roles should be refactored into
# a database backed model SOON so testing of permissions/abilities is more granular
login_as :administrator
@collection = FactoryGirl.create(:collection)
@temp_files = (0..20).map{|index| { name: "a_movie_#{index}.mov" } }
@dropbox = double(Avalon::Dropbox)
@dropbox.stub(:all).and_return @temp_files
Avalon::Dropbox.stub(:new).and_return(@dropbox)
end
it 'deletes video/audio files' do
@dropbox.should_receive(:delete).exactly(@temp_files.count).times
delete :bulk_delete, { :collection_id => @collection.pid, :filenames => @temp_files.map{|f| f[:name] } }
end
end
|
require 'formula'
class Nzbget < Formula
homepage 'http://sourceforge.net/projects/nzbget/'
url 'http://downloads.sourceforge.net/project/nzbget/nzbget-stable/0.8.0/nzbget-0.8.0.tar.gz'
sha1 'a7cf70b58286ff1b552d2564020c1fb9ca6d1af6'
head 'https://nzbget.svn.sourceforge.net/svnroot/nzbget/trunk', :using => :svn
# Also depends on libxml2 but the one in OS X is fine
depends_on 'pkg-config' => :build
depends_on 'libsigc++'
depends_on 'libpar2'
depends_on 'gnutls'
fails_with :clang do
build 318
cause <<-EOS.undent
Configure errors out when testing the libpar2 headers because
Clang does not support flexible arrays of non-POD types.
EOS
end
def install
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make install"
prefix.install 'nzbget.conf.example', 'postprocess-example.conf'
end
end
nzbget: fails with clang build 421
Closes #16094.
Signed-off-by: Jack Nagel <43386ce32af96f5c56f2a88e458cb94cebee3751@gmail.com>
require 'formula'
class Nzbget < Formula
homepage 'http://sourceforge.net/projects/nzbget/'
url 'http://downloads.sourceforge.net/project/nzbget/nzbget-stable/0.8.0/nzbget-0.8.0.tar.gz'
sha1 'a7cf70b58286ff1b552d2564020c1fb9ca6d1af6'
head 'https://nzbget.svn.sourceforge.net/svnroot/nzbget/trunk', :using => :svn
# Also depends on libxml2 but the one in OS X is fine
depends_on 'pkg-config' => :build
depends_on 'libsigc++'
depends_on 'libpar2'
depends_on 'gnutls'
fails_with :clang do
build 421
cause <<-EOS.undent
Configure errors out when testing the libpar2 headers because
Clang does not support flexible arrays of non-POD types.
EOS
end
def install
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make install"
prefix.install 'nzbget.conf.example', 'postprocess-example.conf'
end
end
|
require 'rails_helper'
RSpec.describe LessonsController, type: :controller do
describe "GET #index" do
it "routes correctly" do
user = double('user')
allow_message_expectations_on_nil
allow(request.env['warden']).to receive(:authenticate!) { user }
allow(controller).to receive(:current_user) { user }
get :index
expect(response.status).to eq(200)
end
end
describe "GET #show" do
before(:each) do
user = double('user')
allow_message_expectations_on_nil
allow(request.env['warden']).to receive(:authenticate!) { user }
allow(controller).to receive(:current_user) { user }
end
it "routes correctly" do
l = double('lesson')
expect(Lesson).to receive(:find).with("1") { l }
get :show, id: 1
expect(response.status).to eq(200)
end
it "renders the show template" do
l = double('lesson')
expect(Lesson).to receive(:find).with("1") { l }
get :show, id: 1
expect(response).to render_template(:show)
end
end
describe "POST #submit" do
before(:each) do
@fakeresults = double('lesson1')
@code = "Hello World"
expect(Lesson).to receive_message_chain(:find, :check_submission).and_return(@fakeresults)
end
context "if could not submit code" do
it "should show failure flash message" do
allow(@fakeresults).to receive(:[]).with(:error).and_return("not nil")
post :submit, {:lessonid => 1, :realacesubmit => @code}
expect(response.status).to eq(200)
end
end
context "if code was submitted successfully" do
it "should show success flash message" do
allow(@fakeresults).to receive(:[]).with(:error).and_return(nil)
post :submit, {:lessonid => 1, :realacesubmit => @code}
expect(response.status).to eq(200)
end
end
end
end
fixed minor code quality issue
require 'rails_helper'
RSpec.describe LessonsController, type: :controller do
describe "GET #index" do
it "routes correctly" do
user = double('user')
allow_message_expectations_on_nil
allow(request.env['warden']).to receive(:authenticate!) { user }
allow(controller).to receive(:current_user) { user }
get :index
expect(response.status).to eq(200)
end
end
describe "GET #show" do
before(:each) do
user = double('user')
allow_message_expectations_on_nil
allow(request.env['warden']).to receive(:authenticate!) { user }
allow(controller).to receive(:current_user) { user }
end
it "routes correctly" do
lesson = double('lesson')
expect(Lesson).to receive(:find).with("1") { lesson }
get :show, id: 1
expect(response.status).to eq(200)
end
it "renders the show template" do
lesson = double('lesson')
expect(Lesson).to receive(:find).with("1") { lesson }
get :show, id: 1
expect(response).to render_template(:show)
end
end
describe "POST #submit" do
before(:each) do
@fakeresults = double('lesson1')
@code = "Hello World"
expect(Lesson).to receive_message_chain(:find, :check_submission).and_return(@fakeresults)
end
context "if could not submit code" do
it "should show failure flash message" do
allow(@fakeresults).to receive(:[]).with(:error).and_return("not nil")
post :submit, {:lessonid => 1, :realacesubmit => @code}
expect(response.status).to eq(200)
end
end
context "if code was submitted successfully" do
it "should show success flash message" do
allow(@fakeresults).to receive(:[]).with(:error).and_return(nil)
post :submit, {:lessonid => 1, :realacesubmit => @code}
expect(response.status).to eq(200)
end
end
end
end
|
require 'formula'
class Opencc < Formula
homepage 'https://github.com/BYVoid/OpenCC'
url 'http://dl.bintray.com/byvoid/opencc/opencc-1.0.1.tar.gz'
sha1 'e5cdedef5d9d96f5046a0f44f3004611330ded4a'
bottle do
sha1 "8ccf8db44595debc423220a40f0fe6d715bd60ef" => :yosemite
sha1 "cb24320dd8415a6b06df2e82ae76e05f2e9396d7" => :mavericks
sha1 "98a43a46a22da47a206e0a04ab98e87990c72bbe" => :mountain_lion
end
depends_on 'cmake' => :build
needs :cxx11
def install
ENV.cxx11
args = std_cmake_args
args << '-DBUILD_DOCUMENTATION:BOOL=OFF'
system 'cmake', '.', *args
system 'make'
system 'make install'
end
end
opencc 1.0.2
require "formula"
class Opencc < Formula
homepage "https://github.com/BYVoid/OpenCC"
url "http://dl.bintray.com/byvoid/opencc/opencc-1.0.2.tar.gz"
sha1 "101b9f46aca95d2039a955572c394ca6bdb2d88d"
bottle do
end
depends_on "cmake" => :build
needs :cxx11
def install
ENV.cxx11
system "cmake", ".", "-DBUILD_DOCUMENTATION:BOOL=OFF", *std_cmake_args
system "make"
system "make install"
end
end
|
require 'spec_helper'
describe NoticesController do
it_requires_authentication :for => { :locate => :get }
let(:app) { Fabricate(:app) }
context 'notices API' do
before do
@xml = Rails.root.join('spec','fixtures','hoptoad_test_notice.xml').read
@app = Fabricate(:app_with_watcher)
App.stub(:find_by_api_key!).and_return(@app)
@notice = App.report_error!(@xml)
request.env['Content-type'] = 'text/xml'
request.env['Accept'] = 'text/xml, application/xml'
end
it "generates a notice from xml [POST]" do
App.should_receive(:report_error!).with(@xml).and_return(@notice)
request.should_receive(:raw_post).and_return(@xml)
post :create
response.should be_success
# Same RegExp from Airbrake::UserInformer#replacement (https://github.com/airbrake/airbrake/blob/master/lib/airbrake/user_informer.rb#L8)
# Inspired by https://github.com/airbrake/airbrake/blob/master/test/sender_test.rb
response.body.should match(%r{<id[^>]*>#{@notice.id}</id>})
end
it "generates a notice from xml [GET]" do
App.should_receive(:report_error!).with(@xml).and_return(@notice)
get :create, {:data => @xml}
response.should be_success
response.body.should match(%r{<id[^>]*>#{@notice.id}</id>})
end
it "sends a notification email" do
App.should_receive(:report_error!).with(@xml).and_return(@notice)
request.should_receive(:raw_post).and_return(@xml)
post :create
response.should be_success
response.body.should match(%r{<id[^>]*>#{@notice.id}</id>})
email = ActionMailer::Base.deliveries.last
email.to.should include(@app.watchers.first.email)
email.subject.should include(@notice.message)
email.subject.should include("[#{@app.name}]")
email.subject.should include("[#{@notice.environment_name}]")
end
end
describe "GET /locate/:id" do
context 'when logged in as an admin' do
before(:each) do
@user = Fabricate(:admin)
sign_in @user
end
it "should locate notice and redirect to problem" do
problem = Fabricate(:problem, :app => app, :environment => "production")
notice = Fabricate(:notice, :err => Fabricate(:err, :problem => problem))
get :locate, :id => notice.id
response.should redirect_to(app_err_path(problem.app, problem))
end
end
end
end
Updating comment with right method and URL
require 'spec_helper'
describe NoticesController do
it_requires_authentication :for => { :locate => :get }
let(:app) { Fabricate(:app) }
context 'notices API' do
before do
@xml = Rails.root.join('spec','fixtures','hoptoad_test_notice.xml').read
@app = Fabricate(:app_with_watcher)
App.stub(:find_by_api_key!).and_return(@app)
@notice = App.report_error!(@xml)
request.env['Content-type'] = 'text/xml'
request.env['Accept'] = 'text/xml, application/xml'
end
it "generates a notice from xml [POST]" do
App.should_receive(:report_error!).with(@xml).and_return(@notice)
request.should_receive(:raw_post).and_return(@xml)
post :create
response.should be_success
# Same RegExp from Airbrake::Sender#send_to_airbrake (https://github.com/airbrake/airbrake/blob/master/lib/airbrake/sender.rb#L53)
# Inspired by https://github.com/airbrake/airbrake/blob/master/test/sender_test.rb
response.body.should match(%r{<id[^>]*>#{@notice.id}</id>})
end
it "generates a notice from xml [GET]" do
App.should_receive(:report_error!).with(@xml).and_return(@notice)
get :create, {:data => @xml}
response.should be_success
response.body.should match(%r{<id[^>]*>#{@notice.id}</id>})
end
it "sends a notification email" do
App.should_receive(:report_error!).with(@xml).and_return(@notice)
request.should_receive(:raw_post).and_return(@xml)
post :create
response.should be_success
response.body.should match(%r{<id[^>]*>#{@notice.id}</id>})
email = ActionMailer::Base.deliveries.last
email.to.should include(@app.watchers.first.email)
email.subject.should include(@notice.message)
email.subject.should include("[#{@app.name}]")
email.subject.should include("[#{@notice.environment_name}]")
end
end
describe "GET /locate/:id" do
context 'when logged in as an admin' do
before(:each) do
@user = Fabricate(:admin)
sign_in @user
end
it "should locate notice and redirect to problem" do
problem = Fabricate(:problem, :app => app, :environment => "production")
notice = Fabricate(:notice, :err => Fabricate(:err, :problem => problem))
get :locate, :id => notice.id
response.should redirect_to(app_err_path(problem.app, problem))
end
end
end
end
|
require "language/haskell"
class Pandoc < Formula
include Language::Haskell::Cabal
desc "Swiss-army knife of markup format conversion"
homepage "http://pandoc.org"
url "https://hackage.haskell.org/package/pandoc-1.17.0.2/pandoc-1.17.0.2.tar.gz"
sha256 "f099eecf102cf215741da7a993d90f0ab135d6f84cb23f9da77050bd1c9a9d53"
head "https://github.com/jgm/pandoc.git"
bottle do
sha256 "70efdcd9cd8ceba07810729eaffd24ed7865827517d0f2d78aa84632ecc9c6a3" => :el_capitan
sha256 "dead3ce712405001c9437e6cdd3db44fb507499a10e068198e686f9c58c4bff4" => :yosemite
sha256 "28e8ec96f5037cb6410106bcea83986e2ba7ef22bc0bfc9b152b6732b085fbe2" => :mavericks
end
depends_on "ghc" => :build
depends_on "cabal-install" => :build
depends_on "gmp"
def install
args = []
args << "--constraint=cryptonite -support_aesni" if MacOS.version <= :lion
install_cabal_package *args
(bash_completion/"pandoc").write `#{bin}/pandoc --bash-completion`
end
test do
input_markdown = <<-EOS.undent
# Homebrew
A package manager for humans. Cats should take a look at Tigerbrew.
EOS
expected_html = <<-EOS.undent
<h1 id="homebrew">Homebrew</h1>
<p>A package manager for humans. Cats should take a look at Tigerbrew.</p>
EOS
assert_equal expected_html, pipe_output("#{bin}/pandoc -f markdown -t html5", input_markdown)
end
end
pandoc: update 1.17.0.2 bottle.
require "language/haskell"
class Pandoc < Formula
include Language::Haskell::Cabal
desc "Swiss-army knife of markup format conversion"
homepage "http://pandoc.org"
url "https://hackage.haskell.org/package/pandoc-1.17.0.2/pandoc-1.17.0.2.tar.gz"
sha256 "f099eecf102cf215741da7a993d90f0ab135d6f84cb23f9da77050bd1c9a9d53"
head "https://github.com/jgm/pandoc.git"
bottle do
sha256 "b0af79f5ce1fba4259011cd8445322fdba4b3f7e6cd6a522708c2f1085c044cc" => :el_capitan
sha256 "c9341f2a7825934fca7919cb4dbb2cefb35a4eb9ca8d9a237ef8e78081c8ec6a" => :yosemite
sha256 "e5752c816353dd0cfd8eaf9f2f6cd3c80443af4a97089492bb373ed2b69d4134" => :mavericks
end
depends_on "ghc" => :build
depends_on "cabal-install" => :build
depends_on "gmp"
def install
args = []
args << "--constraint=cryptonite -support_aesni" if MacOS.version <= :lion
install_cabal_package *args
(bash_completion/"pandoc").write `#{bin}/pandoc --bash-completion`
end
test do
input_markdown = <<-EOS.undent
# Homebrew
A package manager for humans. Cats should take a look at Tigerbrew.
EOS
expected_html = <<-EOS.undent
<h1 id="homebrew">Homebrew</h1>
<p>A package manager for humans. Cats should take a look at Tigerbrew.</p>
EOS
assert_equal expected_html, pipe_output("#{bin}/pandoc -f markdown -t html5", input_markdown)
end
end
|
require 'rails_helper'
describe ProfileController, :type => :controller do
def create_service(student, educator)
FactoryBot.create(:service, {
student: student,
recorded_by_educator: educator,
provided_by_educator_name: 'Muraki, Mari'
})
end
def create_event_note(student, educator, params = {})
FactoryBot.create(:event_note, {
student: student,
educator: educator,
}.merge(params))
end
describe '#json' do
let!(:school) { FactoryBot.create(:school) }
let(:educator) { FactoryBot.create(:educator_with_homeroom) }
let(:other_educator) { FactoryBot.create(:educator, full_name: "Teacher, Louis") }
let(:student) { FactoryBot.create(:student, school: school) }
let(:course) { FactoryBot.create(:course, school: school) }
let(:section) { FactoryBot.create(:section, course: course) }
let!(:ssa) { FactoryBot.create(:student_section_assignment, student: student, section: section) }
let!(:esa) { FactoryBot.create(:educator_section_assignment, educator: other_educator, section: section)}
let(:homeroom) { student.homeroom }
def make_request(options = { student_id: nil, format: :html })
request.env['HTTPS'] = 'on'
get :json, params: {
id: options[:student_id],
format: options[:format]
}
end
context 'when educator is not logged in' do
it 'redirects to sign in page' do
make_request({ student_id: student.id, format: :html })
expect(response).to redirect_to(new_educator_session_path)
end
end
context 'when educator is logged in' do
before { sign_in(educator) }
context 'educator has schoolwide access' do
let(:educator) { FactoryBot.create(:educator, :admin, school: school, full_name: "Teacher, Karen") }
let(:serialized_data) { assigns(:serialized_data) }
it 'is successful' do
make_request({ student_id: student.id, format: :html })
expect(response).to be_successful
end
it 'assigns the student\'s serialized data correctly' do
make_request({ student_id: student.id, format: :html })
expect(serialized_data[:current_educator]['id']).to eq educator['id']
expect(serialized_data[:current_educator]['email']).to eq educator['email']
expect(serialized_data[:current_educator]['labels']).to eq []
expect(serialized_data[:student]["id"]).to eq student.id
expect(serialized_data[:student]["restricted_notes_count"]).to eq 0
expect(serialized_data[:dibels]).to eq []
expect(serialized_data[:feed]).to eq ({
event_notes: [],
transition_notes: [],
services: {
active: [],
discontinued: []
},
deprecated: {
interventions: []
}
})
expect(serialized_data[:service_types_index]).to eq({
502 => {:id=>502, :name=>"Attendance Officer"},
503 => {:id=>503, :name=>"Attendance Contract"},
504 => {:id=>504, :name=>"Behavior Contract"},
505 => {:id=>505, :name=>"Counseling, in-house"},
506 => {:id=>506, :name=>"Counseling, outside"},
507 => {:id=>507, :name=>"Reading intervention"},
508 => {:id=>508, :name=>"Math intervention"},
509 => {:id=>509, :name=>"SomerSession"},
510 => {:id=>510, :name=>"Summer Program for English Language Learners"},
511 => {:id=>511, :name=>"Afterschool Tutoring"},
512 => {:id=>512, :name=>"Freedom School"},
513 => {:id=>513, :name=>"Community Schools"},
514 => {:id=>514, :name=>"X-Block"},
})
expect(serialized_data[:educators_index]).to include({
educator.id => {:id=>educator.id, :email=>educator.email, :full_name=> 'Teacher, Karen'}
})
expect(serialized_data[:attendance_data].keys).to eq [
:discipline_incidents, :tardies, :absences
]
expect(serialized_data[:sections].length).to equal(1)
expect(serialized_data[:sections][0]["id"]).to eq(section.id)
expect(serialized_data[:sections][0]["grade_numeric"]).to eq(ssa.grade_numeric)
expect(serialized_data[:sections][0]["educators"][0]["full_name"]).to eq(other_educator.full_name)
expect(serialized_data[:current_educator_allowed_sections]).to include(section.id)
end
context 'student has multiple discipline incidents' do
let!(:student) { FactoryBot.create(:student, school: school) }
let(:most_recent_school_year) { student.most_recent_school_year }
let(:serialized_data) { assigns(:serialized_data) }
let(:attendance_data) { serialized_data[:attendance_data] }
let(:discipline_incidents) { attendance_data[:discipline_incidents] }
let!(:more_recent_incident) {
FactoryBot.create(
:discipline_incident,
student: student,
occurred_at: Time.now - 1.day
)
}
let!(:less_recent_incident) {
FactoryBot.create(
:discipline_incident,
student: student,
occurred_at: Time.now - 2.days
)
}
it 'sets the correct order' do
make_request({ student_id: student.id, format: :html })
expect(discipline_incidents).to eq [more_recent_incident, less_recent_incident]
end
end
end
context 'educator has an associated label' do
let(:educator) { FactoryBot.create(:educator, :admin, school: school) }
let!(:label) { EducatorLabel.create!(label_key: 'k8_counselor', educator: educator) }
let(:serialized_data) { assigns(:serialized_data) }
it 'serializes the educator label correctly' do
make_request({ student_id: student.id, format: :html })
expect(serialized_data[:current_educator]['labels']).to eq ['k8_counselor']
end
end
context 'educator has grade level access' do
let(:educator) { FactoryBot.create(:educator, grade_level_access: [student.grade], school: school )}
it 'is successful' do
make_request({ student_id: student.id, format: :html })
expect(response).to be_successful
end
end
context 'educator has homeroom access' do
let(:educator) { FactoryBot.create(:educator, school: school) }
before { homeroom.update(educator: educator) }
it 'is successful' do
make_request({ student_id: student.id, format: :html })
expect(response).to be_successful
end
end
context 'educator has section access' do
let!(:educator) { FactoryBot.create(:educator, school: school)}
let!(:course) { FactoryBot.create(:course, school: school)}
let!(:section) { FactoryBot.create(:section) }
let!(:esa) { FactoryBot.create(:educator_section_assignment, educator: educator, section: section) }
let!(:section_student) { FactoryBot.create(:student, school: school) }
let!(:ssa) { FactoryBot.create(:student_section_assignment, student: section_student, section: section) }
it 'is successful' do
make_request({ student_id: section_student.id, format: :html })
expect(response).to be_successful
end
end
context 'educator does not have schoolwide, grade level, or homeroom access' do
let(:educator) { FactoryBot.create(:educator, school: school) }
it 'fails' do
make_request({ student_id: student.id, format: :html })
expect(response).to redirect_to(not_authorized_path)
end
end
context 'educator has some grade level access but for the wrong grade' do
let(:student) { FactoryBot.create(:student, grade: '1', school: school) }
let(:educator) { FactoryBot.create(:educator, grade_level_access: ['KF'], school: school) }
it 'fails' do
make_request({ student_id: student.id, format: :html })
expect(response).to redirect_to(not_authorized_path)
end
end
context 'educator access restricted to SPED students' do
let(:educator) { FactoryBot.create(:educator,
grade_level_access: ['1'],
restricted_to_sped_students: true,
school: school )
}
context 'student in SPED' do
let(:student) { FactoryBot.create(:student,
grade: '1',
program_assigned: 'Sp Ed',
school: school)
}
it 'is successful' do
make_request({ student_id: student.id, format: :html })
expect(response).to be_successful
end
end
context 'student in Reg Ed' do
let(:student) { FactoryBot.create(:student,
grade: '1',
program_assigned: 'Reg Ed')
}
it 'fails' do
make_request({ student_id: student.id, format: :html })
expect(response).to redirect_to(not_authorized_path)
end
end
end
context 'educator access restricted to ELL students' do
let(:educator) { FactoryBot.create(:educator,
grade_level_access: ['1'],
restricted_to_english_language_learners: true,
school: school )
}
context 'limited English proficiency' do
let(:student) { FactoryBot.create(:student,
grade: '1',
limited_english_proficiency: 'FLEP',
school: school)
}
it 'is successful' do
make_request({ student_id: student.id, format: :html })
expect(response).to be_successful
end
end
context 'fluent in English' do
let(:student) { FactoryBot.create(:student,
grade: '1',
limited_english_proficiency: 'Fluent')
}
it 'fails' do
make_request({ student_id: student.id, format: :html })
expect(response).to redirect_to(not_authorized_path)
end
end
end
end
end
describe '#serialize_student_for_profile' do
it 'returns a hash with the additional keys that UI code expects' do
student = FactoryBot.create(:student)
serialized_student = controller.send(:serialize_student_for_profile, student)
expect(serialized_student.keys).to include(*[
'absences_count',
'tardies_count',
'school_name',
'homeroom_name',
'house',
'counselor',
'sped_liaison',
'discipline_incidents_count'
])
end
end
describe '#student_feed' do
let(:student) { FactoryBot.create(:student) }
let(:educator) { FactoryBot.create(:educator, :admin) }
let!(:service) { create_service(student, educator) }
let!(:event_note) { create_event_note(student, educator) }
it 'returns services' do
feed = controller.send(:student_feed, student)
expect(feed.keys).to contain_exactly(:event_notes, :services, :deprecated, :transition_notes)
expect(feed[:services].keys).to eq [:active, :discontinued]
expect(feed[:services][:discontinued].first[:id]).to eq service.id
end
it 'returns event notes' do
feed = controller.send(:student_feed, student)
event_notes = feed[:event_notes]
expect(event_notes.size).to eq 1
expect(event_notes.first[:student_id]).to eq(student.id)
expect(event_notes.first[:educator_id]).to eq(educator.id)
end
context 'after service is discontinued' do
it 'filters it' do
feed = controller.send(:student_feed, student)
expect(feed[:services][:active].size).to eq 0
expect(feed[:services][:discontinued].first[:id]).to eq service.id
end
end
end
end
Fixup specs for JSON response
require 'rails_helper'
describe ProfileController, :type => :controller do
def create_service(student, educator)
FactoryBot.create(:service, {
student: student,
recorded_by_educator: educator,
provided_by_educator_name: 'Muraki, Mari'
})
end
def create_event_note(student, educator, params = {})
FactoryBot.create(:event_note, {
student: student,
educator: educator,
}.merge(params))
end
def parse_json(response_body)
JSON.parse(response_body)
end
describe '#json' do
let!(:school) { FactoryBot.create(:school) }
let(:educator) { FactoryBot.create(:educator_with_homeroom) }
let(:other_educator) { FactoryBot.create(:educator, full_name: "Teacher, Louis") }
let(:student) { FactoryBot.create(:student, school: school) }
let(:course) { FactoryBot.create(:course, school: school) }
let(:section) { FactoryBot.create(:section, course: course) }
let!(:ssa) { FactoryBot.create(:student_section_assignment, student: student, section: section) }
let!(:esa) { FactoryBot.create(:educator_section_assignment, educator: other_educator, section: section)}
let(:homeroom) { student.homeroom }
def make_request(educator, student_id)
request.env['HTTPS'] = 'on'
sign_in(educator)
request.env['HTTP_ACCEPT'] = 'application/json'
get :json, params: {
id: student_id,
format: :json
}
end
context 'when educator is not logged in' do
it 'redirects to sign in page' do
make_request(educator, student.id)
expect(response.status).to eq 403
end
end
context 'when educator is logged in' do
before { sign_in(educator) }
context 'educator has schoolwide access' do
let(:educator) { FactoryBot.create(:educator, :admin, school: school, full_name: "Teacher, Karen") }
it 'is successful' do
make_request(educator, student.id)
expect(response).to be_successful
end
it 'assigns the student\'s serialized data correctly' do
make_request(educator, student.id)
json = parse_json(response.body)
expect(json['current_educator']['id']).to eq educator['id']
expect(json['current_educator']['email']).to eq educator['email']
expect(json['current_educator']['labels']).to eq []
expect(json['student']["id"]).to eq student.id
expect(json['student']["restricted_notes_count"]).to eq 0
expect(json['dibels']).to eq []
expect(json['feed']).to eq ({
'event_notes' => [],
'transition_notes' => [],
'services' => {
'active' => [],
'discontinued' => []
},
'deprecated' => {
'interventions' => []
}
})
expect(json['service_types_index']).to eq({
'502' => {'id'=>502, 'name'=>"Attendance Officer"},
'503' => {'id'=>503, 'name'=>"Attendance Contract"},
'504' => {'id'=>504, 'name'=>"Behavior Contract"},
'505' => {'id'=>505, 'name'=>"Counseling, in-house"},
'506' => {'id'=>506, 'name'=>"Counseling, outside"},
'507' => {'id'=>507, 'name'=>"Reading intervention"},
'508' => {'id'=>508, 'name'=>"Math intervention"},
'509' => {'id'=>509, 'name'=>"SomerSession"},
'510' => {'id'=>510, 'name'=>"Summer Program for English Language Learners"},
'511' => {'id'=>511, 'name'=>"Afterschool Tutoring"},
'512' => {'id'=>512, 'name'=>"Freedom School"},
'513' => {'id'=>513, 'name'=>"Community Schools"},
'514' => {'id'=>514, 'name'=>"X-Block"},
})
expect(json['educators_index']).to include({
educator.id.to_s => {
'id'=>educator.id,
'email'=>educator.email,
'full_name'=> 'Teacher, Karen'
}
})
expect(json['attendance_data'].keys).to contain_exactly(*[
'discipline_incidents',
'tardies',
'absences'
])
expect(json['sections'].length).to equal(1)
expect(json['sections'][0]["id"]).to eq(section.id)
expect(json['sections'][0]["grade_numeric"]).to eq(ssa.grade_numeric.to_s)
expect(json['sections'][0]["educators"][0]["full_name"]).to eq(other_educator.full_name)
expect(json['current_educator_allowed_sections']).to include(section.id)
end
context 'student has multiple discipline incidents' do
let!(:student) { FactoryBot.create(:student, school: school) }
let(:most_recent_school_year) { student.most_recent_school_year }
let!(:more_recent_incident) {
FactoryBot.create(
:discipline_incident,
student: student,
occurred_at: Time.now - 1.day
)
}
let!(:less_recent_incident) {
FactoryBot.create(
:discipline_incident,
student: student,
occurred_at: Time.now - 2.days
)
}
it 'sets the correct order' do
make_request(educator, student.id)
json = parse_json(response.body)
discipline_incident_ids = json['attendance_data']['discipline_incidents'].map {|event| event['id'] }
expect(discipline_incident_ids).to eq [
more_recent_incident.id,
less_recent_incident.id
]
end
end
end
context 'educator has an associated label' do
let(:educator) { FactoryBot.create(:educator, :admin, school: school) }
let!(:label) { EducatorLabel.create!(label_key: 'k8_counselor', educator: educator) }
it 'serializes the educator label correctly' do
make_request(educator, student.id)
json = parse_json(response.body)
expect(json['current_educator']['labels']).to eq ['k8_counselor']
end
end
context 'educator has grade level access' do
let(:educator) { FactoryBot.create(:educator, grade_level_access: [student.grade], school: school )}
it 'is successful' do
make_request(educator, student.id)
expect(response).to be_successful
end
end
context 'educator has homeroom access' do
let(:educator) { FactoryBot.create(:educator, school: school) }
before { homeroom.update(educator: educator) }
it 'is successful' do
make_request(educator, student.id)
expect(response).to be_successful
end
end
context 'educator has section access' do
let!(:educator) { FactoryBot.create(:educator, school: school)}
let!(:course) { FactoryBot.create(:course, school: school)}
let!(:section) { FactoryBot.create(:section) }
let!(:esa) { FactoryBot.create(:educator_section_assignment, educator: educator, section: section) }
let!(:section_student) { FactoryBot.create(:student, school: school) }
let!(:ssa) { FactoryBot.create(:student_section_assignment, student: section_student, section: section) }
it 'is successful' do
make_request(educator, section_student.id)
expect(response).to be_successful
end
end
context 'educator does not have schoolwide, grade level, or homeroom access' do
let(:educator) { FactoryBot.create(:educator, school: school) }
it 'fails' do
make_request(educator, student.id)
expect(response.status).to eq 403
end
end
context 'educator has some grade level access but for the wrong grade' do
let(:student) { FactoryBot.create(:student, grade: '1', school: school) }
let(:educator) { FactoryBot.create(:educator, grade_level_access: ['KF'], school: school) }
it 'fails' do
make_request(educator, student.id)
expect(response.status).to eq 403
end
end
context 'educator access restricted to SPED students' do
let(:educator) { FactoryBot.create(:educator,
grade_level_access: ['1'],
restricted_to_sped_students: true,
school: school )
}
context 'student in SPED' do
let(:student) { FactoryBot.create(:student,
grade: '1',
program_assigned: 'Sp Ed',
school: school)
}
it 'is successful' do
make_request(educator, student.id)
expect(response).to be_successful
end
end
context 'student in Reg Ed' do
let(:student) { FactoryBot.create(:student,
grade: '1',
program_assigned: 'Reg Ed')
}
it 'fails' do
make_request(educator, student.id)
expect(response.status).to eq 403
end
end
end
context 'educator access restricted to ELL students' do
let(:educator) { FactoryBot.create(:educator,
grade_level_access: ['1'],
restricted_to_english_language_learners: true,
school: school )
}
context 'limited English proficiency' do
let(:student) { FactoryBot.create(:student,
grade: '1',
limited_english_proficiency: 'FLEP',
school: school)
}
it 'is successful' do
make_request(educator, student.id)
expect(response).to be_successful
end
end
context 'fluent in English' do
let(:student) { FactoryBot.create(:student,
grade: '1',
limited_english_proficiency: 'Fluent')
}
it 'fails' do
make_request(educator, student.id)
expect(response.status).to eq 403
end
end
end
end
end
describe '#serialize_student_for_profile' do
it 'returns a hash with the additional keys that UI code expects' do
student = FactoryBot.create(:student)
serialized_student = controller.send(:serialize_student_for_profile, student)
expect(serialized_student.keys).to include(*[
'absences_count',
'tardies_count',
'school_name',
'homeroom_name',
'house',
'counselor',
'sped_liaison',
'discipline_incidents_count'
])
end
end
describe '#student_feed' do
let(:student) { FactoryBot.create(:student) }
let(:educator) { FactoryBot.create(:educator, :admin) }
let!(:service) { create_service(student, educator) }
let!(:event_note) { create_event_note(student, educator) }
it 'returns services' do
feed = controller.send(:student_feed, student)
expect(feed.keys).to contain_exactly(:event_notes, :services, :deprecated, :transition_notes)
expect(feed[:services].keys).to eq [:active, :discontinued]
expect(feed[:services][:discontinued].first[:id]).to eq service.id
end
it 'returns event notes' do
feed = controller.send(:student_feed, student)
event_notes = feed[:event_notes]
expect(event_notes.size).to eq 1
expect(event_notes.first[:student_id]).to eq(student.id)
expect(event_notes.first[:educator_id]).to eq(educator.id)
end
context 'after service is discontinued' do
it 'filters it' do
feed = controller.send(:student_feed, student)
expect(feed[:services][:active].size).to eq 0
expect(feed[:services][:discontinued].first[:id]).to eq service.id
end
end
end
end
|
Added Formula for pcre++
Signed-off-by: Adam Vandenberg <34c2b6407fd5a10249a15d699d40f9ed1782e98c@gmail.com>
require 'formula'
class Pcrexx <Formula
url 'http://www.daemon.de/idisk/Apps/pcre++/pcre++-0.9.5.tar.gz'
homepage 'http://www.daemon.de/PCRE'
md5 '1fe6ea8e23ece01fde2ce5fb4746acc2'
depends_on 'pcre'
def install
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--prefix=#{prefix}", "--mandir=#{man}"
system "make install"
end
end
|
class Python < Formula
desc "Interpreted, interactive, object-oriented programming language"
homepage "https://www.python.org"
head "https://hg.python.org/cpython", :using => :hg, :branch => "2.7"
url "https://www.python.org/ftp/python/2.7.10/Python-2.7.10.tgz"
sha256 "eda8ce6eec03e74991abb5384170e7c65fcd7522e409b8e83d7e6372add0f12a"
bottle do
revision 1
sha256 "8bfcfa5d07c3a445422a941e16e2f30bc171722df1ebe57d477022b33c862a22" => :leopard_g3
sha256 "99574b0fedfc6c71ab05d9d090014083d5d97767caf5db764d542e04edbfdabd" => :leopard_altivec
end
# Please don't add a wide/ucs4 option as it won't be accepted.
# More details in: https://github.com/Homebrew/homebrew/pull/32368
option :universal
option "with-quicktest", "Run `make quicktest` after the build (for devs; may fail)"
option "with-tcl-tk", "Use Tigerbrew's Tk instead of OS X Tk (has optional Cocoa and threads support)"
option "with-poll", "Enable select.poll, which is not fully implemented on OS X (https://bugs.python.org/issue5154)"
deprecated_option "quicktest" => "with-quicktest"
deprecated_option "with-brewed-tk" => "with-tcl-tk"
depends_on "pkg-config" => :build
depends_on "readline" => :recommended
depends_on "sqlite" => :recommended
depends_on "gdbm" => :recommended
depends_on "openssl"
depends_on "homebrew/dupes/tcl-tk" => :optional
depends_on :x11 if build.with?("tcl-tk") && Tab.for_name("homebrew/dupes/tcl-tk").with?("x11")
skip_clean "bin/pip", "bin/pip-2.7"
skip_clean "bin/easy_install", "bin/easy_install-2.7"
resource "setuptools" do
url "https://pypi.python.org/packages/source/s/setuptools/setuptools-17.1.1.tar.gz"
sha256 "5bf42dbf406fd58a41029f53cffff1c90db5de1c5e0e560b5545cf2ec949c431"
end
resource "pip" do
url "https://pypi.python.org/packages/source/p/pip/pip-7.0.3.tar.gz"
sha256 "b4c598825a6f6dc2cac65968feb28e6be6c1f7f1408493c60a07eaa731a0affd"
end
# Patch for pyport.h macro issue
# https://bugs.python.org/issue10910
# https://trac.macports.org/ticket/44288
patch do
url "https://bugs.python.org/file30805/issue10910-workaround.txt"
sha256 "c075353337f9ff3ccf8091693d278782fcdff62c113245d8de43c5c7acc57daf"
end
# Patch to disable the search for Tk.framework, since Homebrew's Tk is
# a plain unix build. Remove `-lX11`, too because our Tk is "AquaTk".
patch :DATA if build.with? "tcl-tk"
def lib_cellar
prefix/"Frameworks/Python.framework/Versions/2.7/lib/python2.7"
end
def site_packages_cellar
lib_cellar/"site-packages"
end
# The HOMEBREW_PREFIX location of site-packages.
def site_packages
HOMEBREW_PREFIX/"lib/python2.7/site-packages"
end
# setuptools remembers the build flags python is built with and uses them to
# build packages later. Xcode-only systems need different flags.
def pour_bottle?
MacOS::CLT.installed?
end
def install
if build.with? "poll"
opoo "The given option --with-poll enables a somewhat broken poll() on OS X (https://bugs.python.org/issue5154)."
end
# Unset these so that installing pip and setuptools puts them where we want
# and not into some other Python the user has installed.
ENV["PYTHONHOME"] = nil
ENV["PYTHONPATH"] = nil
args = %W[
--prefix=#{prefix}
--enable-ipv6
--datarootdir=#{share}
--datadir=#{share}
--enable-framework=#{frameworks}
]
args << "--without-gcc" if ENV.compiler == :clang
unless MacOS::CLT.installed?
# Help Python's build system (setuptools/pip) to build things on Xcode-only systems
# The setup.py looks at "-isysroot" to get the sysroot (and not at --sysroot)
cflags = "CFLAGS=-isysroot #{MacOS.sdk_path}"
ldflags = "LDFLAGS=-isysroot #{MacOS.sdk_path}"
args << "CPPFLAGS=-I#{MacOS.sdk_path}/usr/include" # find zlib
# For the Xlib.h, Python needs this header dir with the system Tk
if build.without? "tcl-tk"
cflags += " -I#{MacOS.sdk_path}/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers"
end
args << cflags
args << ldflags
end
# Avoid linking to libgcc https://code.activestate.com/lists/python-dev/112195/
args << "MACOSX_DEPLOYMENT_TARGET=#{MacOS.version}"
# We want our readline and openssl! This is just to outsmart the detection code,
# superenv handles that cc finds includes/libs!
inreplace "setup.py" do |s|
s.gsub! "do_readline = self.compiler.find_library_file(lib_dirs, 'readline')",
"do_readline = '#{Formula["readline"].opt_lib}/libhistory.dylib'"
s.gsub! "/usr/local/ssl", Formula["openssl"].opt_prefix
end
if build.universal?
ENV.universal_binary
args << "--enable-universalsdk=/" << "--with-universal-archs=intel"
end
# Allow sqlite3 module to load extensions:
# https://docs.python.org/library/sqlite3.html#f1
if build.with? "sqlite"
inreplace("setup.py", 'sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1"))', "")
end
# Allow python modules to use ctypes.find_library to find homebrew's stuff
# even if homebrew is not a /usr/local/lib. Try this with:
# `brew install enchant && pip install pyenchant`
inreplace "./Lib/ctypes/macholib/dyld.py" do |f|
f.gsub! "DEFAULT_LIBRARY_FALLBACK = [", "DEFAULT_LIBRARY_FALLBACK = [ '#{HOMEBREW_PREFIX}/lib',"
f.gsub! "DEFAULT_FRAMEWORK_FALLBACK = [", "DEFAULT_FRAMEWORK_FALLBACK = [ '#{HOMEBREW_PREFIX}/Frameworks',"
end
if build.with? "tcl-tk"
tcl_tk = Formula["homebrew/dupes/tcl-tk"].opt_prefix
ENV.append "CPPFLAGS", "-I#{tcl_tk}/include"
ENV.append "LDFLAGS", "-L#{tcl_tk}/lib"
end
system "./configure", *args
# HAVE_POLL is "broken" on OS X. See:
# https://trac.macports.org/ticket/18376
# https://bugs.python.org/issue5154
if build.without? "poll"
inreplace "pyconfig.h", /.*?(HAVE_POLL[_A-Z]*).*/, '#undef \1'
end
system "make"
ENV.deparallelize # installs must be serialized
# Tell Python not to install into /Applications
system "make", "install", "PYTHONAPPSDIR=#{prefix}"
# Demos and Tools
system "make", "frameworkinstallextras", "PYTHONAPPSDIR=#{share}/python"
system "make", "quicktest" if build.include? "quicktest"
# Symlink the pkgconfig files into HOMEBREW_PREFIX so they're accessible.
(lib/"pkgconfig").install_symlink Dir["#{frameworks}/Python.framework/Versions/Current/lib/pkgconfig/*"]
# Fixes setting Python build flags for certain software
# See: https://github.com/Homebrew/homebrew/pull/20182
# https://bugs.python.org/issue3588
inreplace lib_cellar/"config/Makefile" do |s|
s.change_make_var! "LINKFORSHARED",
"-u _PyMac_Error $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)"
end
# Remove the site-packages that Python created in its Cellar.
site_packages_cellar.rmtree
(libexec/"setuptools").install resource("setuptools")
(libexec/"pip").install resource("pip")
end
def post_install
# Fix up the site-packages so that user-installed Python software survives
# minor updates, such as going from 2.7.0 to 2.7.1:
# Create a site-packages in HOMEBREW_PREFIX/lib/python2.7/site-packages
site_packages.mkpath
# Symlink the prefix site-packages into the cellar.
site_packages_cellar.unlink if site_packages_cellar.exist?
site_packages_cellar.parent.install_symlink site_packages
# Write our sitecustomize.py
rm_rf Dir["#{site_packages}/sitecustomize.py[co]"]
(site_packages/"sitecustomize.py").atomic_write(sitecustomize)
# Remove old setuptools installations that may still fly around and be
# listed in the easy_install.pth. This can break setuptools build with
# zipimport.ZipImportError: bad local file header
# setuptools-0.9.5-py3.3.egg
rm_rf Dir["#{site_packages}/setuptools*"]
rm_rf Dir["#{site_packages}/distribute*"]
setup_args = ["-s", "setup.py", "--no-user-cfg", "install", "--force",
"--verbose",
"--install-scripts=#{bin}",
"--install-lib=#{site_packages}"]
(libexec/"setuptools").cd { system "#{bin}/python", *setup_args }
(libexec/"pip").cd { system "#{bin}/python", *setup_args }
# When building from source, these symlinks will not exist, since
# post_install happens after linking.
%w[pip pip2 pip2.7 easy_install easy_install-2.7].each do |e|
(HOMEBREW_PREFIX/"bin").install_symlink bin/e
end
# Help distutils find brewed stuff when building extensions
include_dirs = [HOMEBREW_PREFIX/"include", Formula["openssl"].opt_include]
library_dirs = [HOMEBREW_PREFIX/"lib", Formula["openssl"].opt_lib]
if build.with? "sqlite"
include_dirs << Formula["sqlite"].opt_include
library_dirs << Formula["sqlite"].opt_lib
end
if build.with? "tcl-tk"
include_dirs << Formula["homebrew/dupes/tcl-tk"].opt_include
library_dirs << Formula["homebrew/dupes/tcl-tk"].opt_lib
end
cfg = lib_cellar/"distutils/distutils.cfg"
cfg.atomic_write <<-EOF.undent
[global]
verbose=1
[install]
force=1
prefix=#{HOMEBREW_PREFIX}
[build_ext]
include_dirs=#{include_dirs.join ":"}
library_dirs=#{library_dirs.join ":"}
EOF
end
def sitecustomize
<<-EOF.undent
# This file is created by Homebrew and is executed on each python startup.
# Don't print from here, or else python command line scripts may fail!
# <https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Homebrew-and-Python.md>
import re
import os
import sys
if sys.version_info[0] != 2:
# This can only happen if the user has set the PYTHONPATH for 3.x and run Python 2.x or vice versa.
# Every Python looks at the PYTHONPATH variable and we can't fix it here in sitecustomize.py,
# because the PYTHONPATH is evaluated after the sitecustomize.py. Many modules (e.g. PyQt4) are
# built only for a specific version of Python and will fail with cryptic error messages.
# In the end this means: Don't set the PYTHONPATH permanently if you use different Python versions.
exit('Your PYTHONPATH points to a site-packages dir for Python 2.x but you are running Python ' +
str(sys.version_info[0]) + '.x!\\n PYTHONPATH is currently: "' + str(os.environ['PYTHONPATH']) + '"\\n' +
' You should `unset PYTHONPATH` to fix this.')
# Only do this for a brewed python:
if os.path.realpath(sys.executable).startswith('#{rack}'):
# Shuffle /Library site-packages to the end of sys.path and reject
# paths in /System pre-emptively (#14712)
library_site = '/Library/Python/2.7/site-packages'
library_packages = [p for p in sys.path if p.startswith(library_site)]
sys.path = [p for p in sys.path if not p.startswith(library_site) and
not p.startswith('/System')]
# .pth files have already been processed so don't use addsitedir
sys.path.extend(library_packages)
# the Cellar site-packages is a symlink to the HOMEBREW_PREFIX
# site_packages; prefer the shorter paths
long_prefix = re.compile(r'#{rack}/[0-9\._abrc]+/Frameworks/Python\.framework/Versions/2\.7/lib/python2\.7/site-packages')
sys.path = [long_prefix.sub('#{site_packages}', p) for p in sys.path]
# LINKFORSHARED (and python-config --ldflags) return the
# full path to the lib (yes, "Python" is actually the lib, not a
# dir) so that third-party software does not need to add the
# -F/#{HOMEBREW_PREFIX}/Frameworks switch.
try:
from _sysconfigdata import build_time_vars
build_time_vars['LINKFORSHARED'] = '-u _PyMac_Error #{opt_prefix}/Frameworks/Python.framework/Versions/2.7/Python'
except:
pass # remember: don't print here. Better to fail silently.
# Set the sys.executable to use the opt_prefix
sys.executable = '#{opt_bin}/python2.7'
EOF
end
def caveats; <<-EOS.undent
Pip and setuptools have been installed. To update them
pip install --upgrade pip setuptools
You can install Python packages with
pip install <package>
They will install into the site-package directory
#{site_packages}
See: https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Homebrew-and-Python.md
EOS
end
test do
# Check if sqlite is ok, because we build with --enable-loadable-sqlite-extensions
# and it can occur that building sqlite silently fails if OSX's sqlite is used.
system "#{bin}/python", "-c", "import sqlite3"
# Check if some other modules import. Then the linked libs are working.
system "#{bin}/python", "-c", "import Tkinter; root = Tkinter.Tk()"
system bin/"pip", "list"
end
end
__END__
diff --git a/setup.py b/setup.py
index 716f08e..66114ef 100644
--- a/setup.py
+++ b/setup.py
@@ -1810,9 +1810,6 @@ class PyBuildExt(build_ext):
# Rather than complicate the code below, detecting and building
# AquaTk is a separate method. Only one Tkinter will be built on
# Darwin - either AquaTk, if it is found, or X11 based Tk.
- if (host_platform == 'darwin' and
- self.detect_tkinter_darwin(inc_dirs, lib_dirs)):
- return
# Assume we haven't found any of the libraries or include files
# The versions with dots are used on Unix, and the versions without
@@ -1858,21 +1855,6 @@ class PyBuildExt(build_ext):
if dir not in include_dirs:
include_dirs.append(dir)
- # Check for various platform-specific directories
- if host_platform == 'sunos5':
- include_dirs.append('/usr/openwin/include')
- added_lib_dirs.append('/usr/openwin/lib')
- elif os.path.exists('/usr/X11R6/include'):
- include_dirs.append('/usr/X11R6/include')
- added_lib_dirs.append('/usr/X11R6/lib64')
- added_lib_dirs.append('/usr/X11R6/lib')
- elif os.path.exists('/usr/X11R5/include'):
- include_dirs.append('/usr/X11R5/include')
- added_lib_dirs.append('/usr/X11R5/lib')
- else:
- # Assume default location for X11
- include_dirs.append('/usr/X11/include')
- added_lib_dirs.append('/usr/X11/lib')
# If Cygwin, then verify that X is installed before proceeding
if host_platform == 'cygwin':
@@ -1897,9 +1879,6 @@ class PyBuildExt(build_ext):
if host_platform in ['aix3', 'aix4']:
libs.append('ld')
- # Finally, link with the X11 libraries (not appropriate on cygwin)
- if host_platform != "cygwin":
- libs.append('X11')
ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
define_macros=[('WITH_APPINIT', 1)] + defs,
python: add Tiger bottle
class Python < Formula
desc "Interpreted, interactive, object-oriented programming language"
homepage "https://www.python.org"
head "https://hg.python.org/cpython", :using => :hg, :branch => "2.7"
url "https://www.python.org/ftp/python/2.7.10/Python-2.7.10.tgz"
sha256 "eda8ce6eec03e74991abb5384170e7c65fcd7522e409b8e83d7e6372add0f12a"
bottle do
revision 1
sha256 "63bbea5981e623d58c5a7b60d67e8cc429c5a3161cacc183bfcf80b59d4df658" => :tiger_altivec
sha256 "8bfcfa5d07c3a445422a941e16e2f30bc171722df1ebe57d477022b33c862a22" => :leopard_g3
sha256 "99574b0fedfc6c71ab05d9d090014083d5d97767caf5db764d542e04edbfdabd" => :leopard_altivec
end
# Please don't add a wide/ucs4 option as it won't be accepted.
# More details in: https://github.com/Homebrew/homebrew/pull/32368
option :universal
option "with-quicktest", "Run `make quicktest` after the build (for devs; may fail)"
option "with-tcl-tk", "Use Tigerbrew's Tk instead of OS X Tk (has optional Cocoa and threads support)"
option "with-poll", "Enable select.poll, which is not fully implemented on OS X (https://bugs.python.org/issue5154)"
deprecated_option "quicktest" => "with-quicktest"
deprecated_option "with-brewed-tk" => "with-tcl-tk"
depends_on "pkg-config" => :build
depends_on "readline" => :recommended
depends_on "sqlite" => :recommended
depends_on "gdbm" => :recommended
depends_on "openssl"
depends_on "homebrew/dupes/tcl-tk" => :optional
depends_on :x11 if build.with?("tcl-tk") && Tab.for_name("homebrew/dupes/tcl-tk").with?("x11")
skip_clean "bin/pip", "bin/pip-2.7"
skip_clean "bin/easy_install", "bin/easy_install-2.7"
resource "setuptools" do
url "https://pypi.python.org/packages/source/s/setuptools/setuptools-17.1.1.tar.gz"
sha256 "5bf42dbf406fd58a41029f53cffff1c90db5de1c5e0e560b5545cf2ec949c431"
end
resource "pip" do
url "https://pypi.python.org/packages/source/p/pip/pip-7.0.3.tar.gz"
sha256 "b4c598825a6f6dc2cac65968feb28e6be6c1f7f1408493c60a07eaa731a0affd"
end
# Patch for pyport.h macro issue
# https://bugs.python.org/issue10910
# https://trac.macports.org/ticket/44288
patch do
url "https://bugs.python.org/file30805/issue10910-workaround.txt"
sha256 "c075353337f9ff3ccf8091693d278782fcdff62c113245d8de43c5c7acc57daf"
end
# Patch to disable the search for Tk.framework, since Homebrew's Tk is
# a plain unix build. Remove `-lX11`, too because our Tk is "AquaTk".
patch :DATA if build.with? "tcl-tk"
def lib_cellar
prefix/"Frameworks/Python.framework/Versions/2.7/lib/python2.7"
end
def site_packages_cellar
lib_cellar/"site-packages"
end
# The HOMEBREW_PREFIX location of site-packages.
def site_packages
HOMEBREW_PREFIX/"lib/python2.7/site-packages"
end
# setuptools remembers the build flags python is built with and uses them to
# build packages later. Xcode-only systems need different flags.
def pour_bottle?
MacOS::CLT.installed?
end
def install
if build.with? "poll"
opoo "The given option --with-poll enables a somewhat broken poll() on OS X (https://bugs.python.org/issue5154)."
end
# Unset these so that installing pip and setuptools puts them where we want
# and not into some other Python the user has installed.
ENV["PYTHONHOME"] = nil
ENV["PYTHONPATH"] = nil
args = %W[
--prefix=#{prefix}
--enable-ipv6
--datarootdir=#{share}
--datadir=#{share}
--enable-framework=#{frameworks}
]
args << "--without-gcc" if ENV.compiler == :clang
unless MacOS::CLT.installed?
# Help Python's build system (setuptools/pip) to build things on Xcode-only systems
# The setup.py looks at "-isysroot" to get the sysroot (and not at --sysroot)
cflags = "CFLAGS=-isysroot #{MacOS.sdk_path}"
ldflags = "LDFLAGS=-isysroot #{MacOS.sdk_path}"
args << "CPPFLAGS=-I#{MacOS.sdk_path}/usr/include" # find zlib
# For the Xlib.h, Python needs this header dir with the system Tk
if build.without? "tcl-tk"
cflags += " -I#{MacOS.sdk_path}/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers"
end
args << cflags
args << ldflags
end
# Avoid linking to libgcc https://code.activestate.com/lists/python-dev/112195/
args << "MACOSX_DEPLOYMENT_TARGET=#{MacOS.version}"
# We want our readline and openssl! This is just to outsmart the detection code,
# superenv handles that cc finds includes/libs!
inreplace "setup.py" do |s|
s.gsub! "do_readline = self.compiler.find_library_file(lib_dirs, 'readline')",
"do_readline = '#{Formula["readline"].opt_lib}/libhistory.dylib'"
s.gsub! "/usr/local/ssl", Formula["openssl"].opt_prefix
end
if build.universal?
ENV.universal_binary
args << "--enable-universalsdk=/" << "--with-universal-archs=intel"
end
# Allow sqlite3 module to load extensions:
# https://docs.python.org/library/sqlite3.html#f1
if build.with? "sqlite"
inreplace("setup.py", 'sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1"))', "")
end
# Allow python modules to use ctypes.find_library to find homebrew's stuff
# even if homebrew is not a /usr/local/lib. Try this with:
# `brew install enchant && pip install pyenchant`
inreplace "./Lib/ctypes/macholib/dyld.py" do |f|
f.gsub! "DEFAULT_LIBRARY_FALLBACK = [", "DEFAULT_LIBRARY_FALLBACK = [ '#{HOMEBREW_PREFIX}/lib',"
f.gsub! "DEFAULT_FRAMEWORK_FALLBACK = [", "DEFAULT_FRAMEWORK_FALLBACK = [ '#{HOMEBREW_PREFIX}/Frameworks',"
end
if build.with? "tcl-tk"
tcl_tk = Formula["homebrew/dupes/tcl-tk"].opt_prefix
ENV.append "CPPFLAGS", "-I#{tcl_tk}/include"
ENV.append "LDFLAGS", "-L#{tcl_tk}/lib"
end
system "./configure", *args
# HAVE_POLL is "broken" on OS X. See:
# https://trac.macports.org/ticket/18376
# https://bugs.python.org/issue5154
if build.without? "poll"
inreplace "pyconfig.h", /.*?(HAVE_POLL[_A-Z]*).*/, '#undef \1'
end
system "make"
ENV.deparallelize # installs must be serialized
# Tell Python not to install into /Applications
system "make", "install", "PYTHONAPPSDIR=#{prefix}"
# Demos and Tools
system "make", "frameworkinstallextras", "PYTHONAPPSDIR=#{share}/python"
system "make", "quicktest" if build.include? "quicktest"
# Symlink the pkgconfig files into HOMEBREW_PREFIX so they're accessible.
(lib/"pkgconfig").install_symlink Dir["#{frameworks}/Python.framework/Versions/Current/lib/pkgconfig/*"]
# Fixes setting Python build flags for certain software
# See: https://github.com/Homebrew/homebrew/pull/20182
# https://bugs.python.org/issue3588
inreplace lib_cellar/"config/Makefile" do |s|
s.change_make_var! "LINKFORSHARED",
"-u _PyMac_Error $(PYTHONFRAMEWORKINSTALLDIR)/Versions/$(VERSION)/$(PYTHONFRAMEWORK)"
end
# Remove the site-packages that Python created in its Cellar.
site_packages_cellar.rmtree
(libexec/"setuptools").install resource("setuptools")
(libexec/"pip").install resource("pip")
end
def post_install
# Fix up the site-packages so that user-installed Python software survives
# minor updates, such as going from 2.7.0 to 2.7.1:
# Create a site-packages in HOMEBREW_PREFIX/lib/python2.7/site-packages
site_packages.mkpath
# Symlink the prefix site-packages into the cellar.
site_packages_cellar.unlink if site_packages_cellar.exist?
site_packages_cellar.parent.install_symlink site_packages
# Write our sitecustomize.py
rm_rf Dir["#{site_packages}/sitecustomize.py[co]"]
(site_packages/"sitecustomize.py").atomic_write(sitecustomize)
# Remove old setuptools installations that may still fly around and be
# listed in the easy_install.pth. This can break setuptools build with
# zipimport.ZipImportError: bad local file header
# setuptools-0.9.5-py3.3.egg
rm_rf Dir["#{site_packages}/setuptools*"]
rm_rf Dir["#{site_packages}/distribute*"]
setup_args = ["-s", "setup.py", "--no-user-cfg", "install", "--force",
"--verbose",
"--install-scripts=#{bin}",
"--install-lib=#{site_packages}"]
(libexec/"setuptools").cd { system "#{bin}/python", *setup_args }
(libexec/"pip").cd { system "#{bin}/python", *setup_args }
# When building from source, these symlinks will not exist, since
# post_install happens after linking.
%w[pip pip2 pip2.7 easy_install easy_install-2.7].each do |e|
(HOMEBREW_PREFIX/"bin").install_symlink bin/e
end
# Help distutils find brewed stuff when building extensions
include_dirs = [HOMEBREW_PREFIX/"include", Formula["openssl"].opt_include]
library_dirs = [HOMEBREW_PREFIX/"lib", Formula["openssl"].opt_lib]
if build.with? "sqlite"
include_dirs << Formula["sqlite"].opt_include
library_dirs << Formula["sqlite"].opt_lib
end
if build.with? "tcl-tk"
include_dirs << Formula["homebrew/dupes/tcl-tk"].opt_include
library_dirs << Formula["homebrew/dupes/tcl-tk"].opt_lib
end
cfg = lib_cellar/"distutils/distutils.cfg"
cfg.atomic_write <<-EOF.undent
[global]
verbose=1
[install]
force=1
prefix=#{HOMEBREW_PREFIX}
[build_ext]
include_dirs=#{include_dirs.join ":"}
library_dirs=#{library_dirs.join ":"}
EOF
end
def sitecustomize
<<-EOF.undent
# This file is created by Homebrew and is executed on each python startup.
# Don't print from here, or else python command line scripts may fail!
# <https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Homebrew-and-Python.md>
import re
import os
import sys
if sys.version_info[0] != 2:
# This can only happen if the user has set the PYTHONPATH for 3.x and run Python 2.x or vice versa.
# Every Python looks at the PYTHONPATH variable and we can't fix it here in sitecustomize.py,
# because the PYTHONPATH is evaluated after the sitecustomize.py. Many modules (e.g. PyQt4) are
# built only for a specific version of Python and will fail with cryptic error messages.
# In the end this means: Don't set the PYTHONPATH permanently if you use different Python versions.
exit('Your PYTHONPATH points to a site-packages dir for Python 2.x but you are running Python ' +
str(sys.version_info[0]) + '.x!\\n PYTHONPATH is currently: "' + str(os.environ['PYTHONPATH']) + '"\\n' +
' You should `unset PYTHONPATH` to fix this.')
# Only do this for a brewed python:
if os.path.realpath(sys.executable).startswith('#{rack}'):
# Shuffle /Library site-packages to the end of sys.path and reject
# paths in /System pre-emptively (#14712)
library_site = '/Library/Python/2.7/site-packages'
library_packages = [p for p in sys.path if p.startswith(library_site)]
sys.path = [p for p in sys.path if not p.startswith(library_site) and
not p.startswith('/System')]
# .pth files have already been processed so don't use addsitedir
sys.path.extend(library_packages)
# the Cellar site-packages is a symlink to the HOMEBREW_PREFIX
# site_packages; prefer the shorter paths
long_prefix = re.compile(r'#{rack}/[0-9\._abrc]+/Frameworks/Python\.framework/Versions/2\.7/lib/python2\.7/site-packages')
sys.path = [long_prefix.sub('#{site_packages}', p) for p in sys.path]
# LINKFORSHARED (and python-config --ldflags) return the
# full path to the lib (yes, "Python" is actually the lib, not a
# dir) so that third-party software does not need to add the
# -F/#{HOMEBREW_PREFIX}/Frameworks switch.
try:
from _sysconfigdata import build_time_vars
build_time_vars['LINKFORSHARED'] = '-u _PyMac_Error #{opt_prefix}/Frameworks/Python.framework/Versions/2.7/Python'
except:
pass # remember: don't print here. Better to fail silently.
# Set the sys.executable to use the opt_prefix
sys.executable = '#{opt_bin}/python2.7'
EOF
end
def caveats; <<-EOS.undent
Pip and setuptools have been installed. To update them
pip install --upgrade pip setuptools
You can install Python packages with
pip install <package>
They will install into the site-package directory
#{site_packages}
See: https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Homebrew-and-Python.md
EOS
end
test do
# Check if sqlite is ok, because we build with --enable-loadable-sqlite-extensions
# and it can occur that building sqlite silently fails if OSX's sqlite is used.
system "#{bin}/python", "-c", "import sqlite3"
# Check if some other modules import. Then the linked libs are working.
system "#{bin}/python", "-c", "import Tkinter; root = Tkinter.Tk()"
system bin/"pip", "list"
end
end
__END__
diff --git a/setup.py b/setup.py
index 716f08e..66114ef 100644
--- a/setup.py
+++ b/setup.py
@@ -1810,9 +1810,6 @@ class PyBuildExt(build_ext):
# Rather than complicate the code below, detecting and building
# AquaTk is a separate method. Only one Tkinter will be built on
# Darwin - either AquaTk, if it is found, or X11 based Tk.
- if (host_platform == 'darwin' and
- self.detect_tkinter_darwin(inc_dirs, lib_dirs)):
- return
# Assume we haven't found any of the libraries or include files
# The versions with dots are used on Unix, and the versions without
@@ -1858,21 +1855,6 @@ class PyBuildExt(build_ext):
if dir not in include_dirs:
include_dirs.append(dir)
- # Check for various platform-specific directories
- if host_platform == 'sunos5':
- include_dirs.append('/usr/openwin/include')
- added_lib_dirs.append('/usr/openwin/lib')
- elif os.path.exists('/usr/X11R6/include'):
- include_dirs.append('/usr/X11R6/include')
- added_lib_dirs.append('/usr/X11R6/lib64')
- added_lib_dirs.append('/usr/X11R6/lib')
- elif os.path.exists('/usr/X11R5/include'):
- include_dirs.append('/usr/X11R5/include')
- added_lib_dirs.append('/usr/X11R5/lib')
- else:
- # Assume default location for X11
- include_dirs.append('/usr/X11/include')
- added_lib_dirs.append('/usr/X11/lib')
# If Cygwin, then verify that X is installed before proceeding
if host_platform == 'cygwin':
@@ -1897,9 +1879,6 @@ class PyBuildExt(build_ext):
if host_platform in ['aix3', 'aix4']:
libs.append('ld')
- # Finally, link with the X11 libraries (not appropriate on cygwin)
- if host_platform != "cygwin":
- libs.append('X11')
ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
define_macros=[('WITH_APPINIT', 1)] + defs,
|
# -*- coding: utf-8 -*-
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe RequestController, "when listing recent requests" do
before(:each) do
load_raw_emails_data
get_fixtures_xapian_index
end
it "should be successful" do
get :list, :view => 'all'
response.should be_success
end
it "should render with 'list' template" do
get :list, :view => 'all'
response.should render_template('list')
end
it "should filter requests" do
get :list, :view => 'all'
assigns[:list_results].map(&:info_request).should =~ InfoRequest.all
# default sort order is the request with the most recently created event first
assigns[:list_results].map(&:info_request).should == InfoRequest.all(
:order => "(select max(info_request_events.created_at) from info_request_events where info_request_events.info_request_id = info_requests.id) DESC")
get :list, :view => 'successful'
assigns[:list_results].map(&:info_request).should =~ InfoRequest.all(
:conditions => "id in (
select info_request_id
from info_request_events
where not exists (
select *
from info_request_events later_events
where later_events.created_at > info_request_events.created_at
and later_events.info_request_id = info_request_events.info_request_id
and later_events.described_state is not null
)
and info_request_events.described_state in ('successful', 'partially_successful')
)")
end
it "should filter requests by date" do
# The semantics of the search are that it finds any InfoRequest
# that has any InfoRequestEvent created in the specified range
get :list, :view => 'all', :request_date_before => '13/10/2007'
assigns[:list_results].map(&:info_request).should =~ InfoRequest.all(
:conditions => "id in (select info_request_id from info_request_events where created_at < '2007-10-13'::date)")
get :list, :view => 'all', :request_date_after => '13/10/2007'
assigns[:list_results].map(&:info_request).should =~ InfoRequest.all(
:conditions => "id in (select info_request_id from info_request_events where created_at > '2007-10-13'::date)")
get :list, :view => 'all', :request_date_after => '13/10/2007', :request_date_before => '01/11/2007'
assigns[:list_results].map(&:info_request).should =~ InfoRequest.all(
:conditions => "id in (select info_request_id from info_request_events where created_at between '2007-10-13'::date and '2007-11-01'::date)")
end
it "should make a sane-sized cache tag" do
get :list, :view => 'all', :request_date_after => '13/10/2007', :request_date_before => '01/11/2007'
assigns[:cache_tag].size.should <= 32
end
it "should vary the cache tag with locale" do
get :list, :view => 'all', :request_date_after => '13/10/2007', :request_date_before => '01/11/2007'
en_tag = assigns[:cache_tag]
session[:locale] = :es
get :list, :view => 'all', :request_date_after => '13/10/2007', :request_date_before => '01/11/2007'
assigns[:cache_tag].should_not == en_tag
end
it "should list internal_review requests as unresolved ones" do
get :list, :view => 'awaiting'
# This doesn’t precisely duplicate the logic of the actual
# query, but it is close enough to give the same result with
# the current set of test data.
assigns[:list_results].should =~ InfoRequestEvent.all(
:conditions => "described_state in (
'waiting_response', 'waiting_clarification',
'internal_review', 'gone_postal', 'error_message', 'requires_admin'
) and not exists (
select *
from info_request_events later_events
where later_events.created_at > info_request_events.created_at
and later_events.info_request_id = info_request_events.info_request_id
)")
get :list, :view => 'awaiting'
assigns[:list_results].map(&:info_request).include?(info_requests(:fancy_dog_request)).should == false
event = info_request_events(:useless_incoming_message_event)
event.described_state = event.calculated_state = "internal_review"
event.save!
rebuild_xapian_index
get :list, :view => 'awaiting'
assigns[:list_results].map(&:info_request).include?(info_requests(:fancy_dog_request)).should == true
end
it "should assign the first page of results" do
xap_results = mock_model(ActsAsXapian::Search,
:results => (1..25).to_a.map { |m| { :model => m } },
:matches_estimated => 1000000)
InfoRequest.should_receive(:full_search).
with([InfoRequestEvent]," (variety:sent OR variety:followup_sent OR variety:response OR variety:comment)", "created_at", anything, anything, anything, anything).
and_return(xap_results)
get :list, :view => 'all'
assigns[:list_results].size.should == 25
assigns[:show_no_more_than].should == RequestController::MAX_RESULTS
end
it "should return 404 for pages we don't want to serve up" do
xap_results = mock_model(ActsAsXapian::Search,
:results => (1..25).to_a.map { |m| { :model => m } },
:matches_estimated => 1000000)
lambda {
get :list, :view => 'all', :page => 100
}.should raise_error(ActiveRecord::RecordNotFound)
end
it 'should not raise an error for a page param of less than zero, but should treat it as
a param of 1' do
lambda{ get :list, :view => 'all', :page => "-1" }.should_not raise_error
assigns[:page].should == 1
end
end
describe RequestController, "when changing things that appear on the request page" do
integrate_views
it "should purge the downstream cache when mail is received" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-plain.email', ir.incoming_email)
PurgeRequest.all().first.model_id.should == ir.id
end
it "should purge the downstream cache when a comment is added" do
ir = info_requests(:fancy_dog_request)
new_comment = info_requests(:fancy_dog_request).add_comment('I also love making annotations.', users(:bob_smith_user))
PurgeRequest.all().first.model_id.should == ir.id
end
it "should purge the downstream cache when a followup is made" do
session[:user_id] = users(:bob_smith_user).id
ir = info_requests(:fancy_dog_request)
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort' }, :id => ir.id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
PurgeRequest.all().first.model_id.should == ir.id
end
it "should purge the downstream cache when the request is categorised" do
ir = info_requests(:fancy_dog_request)
ir.set_described_state('waiting_clarification')
PurgeRequest.all().first.model_id.should == ir.id
end
it "should purge the downstream cache when the authority data is changed" do
ir = info_requests(:fancy_dog_request)
ir.public_body.name = "Something new"
ir.public_body.save!
PurgeRequest.all().map{|x| x.model_id}.should =~ ir.public_body.info_requests.map{|x| x.id}
end
it "should purge the downstream cache when the user name is changed" do
ir = info_requests(:fancy_dog_request)
ir.user.name = "Something new"
ir.user.save!
PurgeRequest.all().map{|x| x.model_id}.should =~ ir.user.info_requests.map{|x| x.id}
end
it "should not purge the downstream cache when non-visible user details are changed" do
ir = info_requests(:fancy_dog_request)
ir.user.hashed_password = "some old hash"
ir.user.save!
PurgeRequest.all().count.should == 0
end
it "should purge the downstream cache when censor rules have changed" do
# XXX really, CensorRules should execute expiry logic as part
# of the after_save of the model. Currently this is part of
# the AdminCensorRuleController logic, so must be tested from
# there. Leaving this stub test in place as a reminder
end
it "should purge the downstream cache when something is hidden by an admin" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
PurgeRequest.all().first.model_id.should == ir.id
end
it "should not create more than one entry for any given resourcce" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
PurgeRequest.all().count.should == 1
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
PurgeRequest.all().count.should == 1
end
end
describe RequestController, "when showing one request" do
integrate_views
before(:each) do
load_raw_emails_data
FileUtils.rm_rf File.join(File.dirname(__FILE__), "../../cache/zips")
end
it "should be successful" do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should be_success
end
it "should render with 'show' template" do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('show')
end
it "should show the request" do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should be_success
response.body.should include("Why do you have such a fancy dog?")
end
it "should assign the request" do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
assigns[:info_request].should == info_requests(:fancy_dog_request)
end
it "should redirect from a numeric URL to pretty one" do
get :show, :url_title => info_requests(:naughty_chicken_request).id
response.should redirect_to(:action => 'show', :url_title => info_requests(:naughty_chicken_request).url_title)
end
it 'should show actions the request owner can take' do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should have_tag('div#owner_actions')
end
describe 'when the request does allow comments' do
it 'should have a comment link' do
get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' },
{ :user_id => users(:admin_user).id }
response.should have_tag('#anyone_actions', /Add an annotation/)
end
end
describe 'when the request does not allow comments' do
it 'should not have a comment link' do
get :show, { :url_title => 'spam_1' },
{ :user_id => users(:admin_user).id }
response.should_not have_tag('#anyone_actions', /Add an annotation/)
end
end
describe 'when the request is being viewed by an admin' do
describe 'if the request is awaiting description' do
before do
dog_request = info_requests(:fancy_dog_request)
dog_request.awaiting_description = true
dog_request.save!
end
it 'should show the describe state form' do
get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' },
{ :user_id => users(:admin_user).id }
response.should have_tag('div.describe_state_form')
end
it 'should ask the user to use the describe state from' do
get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' },
{ :user_id => users(:admin_user).id }
response.should have_tag('p#request_status', :text => /answer the question above/)
end
end
describe 'if the request is waiting for a response and very overdue' do
before do
dog_request = info_requests(:fancy_dog_request)
dog_request.awaiting_description = false
dog_request.described_state = 'waiting_response'
dog_request.save!
dog_request.calculate_status.should == 'waiting_response_very_overdue'
end
it 'should give a link to requesting an internal review' do
get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' },
{ :user_id => users(:admin_user).id }
response.should have_tag('p#request_status', :text =>/requesting an internal review/)
end
end
describe 'if the request is waiting clarification' do
before do
dog_request = info_requests(:fancy_dog_request)
dog_request.awaiting_description = false
dog_request.described_state = 'waiting_clarification'
dog_request.save!
dog_request.calculate_status.should == 'waiting_clarification'
end
it 'should give a link to make a followup' do
get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' },
{ :user_id => users(:admin_user).id }
response.should have_tag('p#request_status a', :text =>/send a follow up message/)
end
end
end
describe 'when showing an external request' do
describe 'when viewing with no logged in user' do
it 'should be successful' do
get :show, { :url_title => 'balalas' }, { :user_id => nil }
response.should be_success
end
it 'should not display actions the request owner can take' do
get :show, :url_title => 'balalas'
response.should_not have_tag('div#owner_actions')
end
end
describe 'when the request is being viewed by an admin' do
def make_request
get :show, { :url_title => 'balalas' }, { :user_id => users(:admin_user).id }
end
it 'should be successful' do
make_request
response.should be_success
end
describe 'if the request is awaiting description' do
before do
external_request = info_requests(:external_request)
external_request.awaiting_description = true
external_request.save!
end
it 'should not show the describe state form' do
make_request
response.should_not have_tag('div.describe_state_form')
end
it 'should not ask the user to use the describe state form' do
make_request
response.should_not have_tag('p#request_status', :text => /answer the question above/)
end
end
describe 'if the request is waiting for a response and very overdue' do
before do
external_request = info_requests(:external_request)
external_request.awaiting_description = false
external_request.described_state = 'waiting_response'
external_request.save!
external_request.calculate_status.should == 'waiting_response_very_overdue'
end
it 'should not give a link to requesting an internal review' do
make_request
response.should_not have_tag('p#request_status', :text =>/requesting an internal review/)
end
end
describe 'if the request is waiting clarification' do
before do
external_request = info_requests(:external_request)
external_request.awaiting_description = false
external_request.described_state = 'waiting_clarification'
external_request.save!
external_request.calculate_status.should == 'waiting_clarification'
end
it 'should not give a link to make a followup' do
make_request
response.should_not have_tag('p#request_status a', :text =>/send a follow up message/)
end
it 'should not give a link to sign in (in the request status paragraph)' do
make_request
response.should_not have_tag('p#request_status a', :text => /sign in/)
end
end
end
end
describe 'when handling an update_status parameter' do
describe 'when the request is external' do
it 'should assign the "update status" flag to the view as false if the parameter is present' do
get :show, :url_title => 'balalas', :update_status => 1
assigns[:update_status].should be_false
end
it 'should assign the "update status" flag to the view as false if the parameter is not present' do
get :show, :url_title => 'balalas'
assigns[:update_status].should be_false
end
end
it 'should assign the "update status" flag to the view as true if the parameter is present' do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :update_status => 1
assigns[:update_status].should be_true
end
it 'should assign the "update status" flag to the view as false if the parameter is not present' do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
assigns[:update_status].should be_false
end
it 'should require login' do
session[:user_id] = nil
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :update_status => 1
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
end
it 'should work if logged in as the requester' do
session[:user_id] = users(:bob_smith_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :update_status => 1
response.should render_template "request/show"
end
it 'should not work if logged in as not the requester' do
session[:user_id] = users(:silly_name_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :update_status => 1
response.should render_template "user/wrong_user"
end
it 'should work if logged in as an admin user' do
session[:user_id] = users(:admin_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :update_status => 1
response.should render_template "request/show"
end
end
describe 'when handling incoming mail' do
integrate_views
it "should receive incoming messages, send email to creator, and show them" do
ir = info_requests(:fancy_dog_request)
ir.incoming_messages.each { |x| x.parse_raw_email! }
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
size_before = assigns[:info_request_events].size
receive_incoming_mail('incoming-request-plain.email', ir.incoming_email)
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /You have a new response to the Freedom of Information request/
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
(assigns[:info_request_events].size - size_before).should == 1
end
it "should download attachments" do
ir = info_requests(:fancy_dog_request)
ir.incoming_messages.each { |x| x.parse_raw_email!(true) }
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.content_type.should == "text/html"
size_before = assigns[:info_request_events].size
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
(assigns[:info_request_events].size - size_before).should == 1
ir.reload
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1
response.content_type.should == "text/plain"
response.should have_text(/Second hello/)
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 3, :file_name => ['hello.txt'], :skip_cache => 1
response.content_type.should == "text/plain"
response.should have_text(/First hello/)
end
it 'should cache an attachment on a request with normal prominence' do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
@controller.should_receive(:foi_fragment_cache_write)
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id,
:id => ir.id,
:part => 2,
:file_name => ['hello.txt']
end
it "should convert message body to UTF8" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('iso8859_2_raw_email.email', ir.incoming_email)
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should have_text(/tënde/u)
end
it "should generate valid HTML verson of plain text attachments" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
response.content_type.should == "text/html"
response.should have_text(/Second hello/)
end
# This is a regression test for a bug where URLs of this form were causing 500 errors
# instead of 404s.
#
# (Note that in fact only the integer-prefix of the URL part is used, so there are
# *some* “ugly URLs containing a request id that isn't an integer” that actually return
# a 200 response. The point is that IDs of this sort were triggering an error in the
# error-handling path, causing the wrong sort of error response to be returned in the
# case where the integer prefix referred to the wrong request.)
#
# https://github.com/mysociety/alaveteli/issues/351
it "should return 404 for ugly URLs containing a request id that isn't an integer" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
ugly_id = "55195"
lambda {
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ugly_id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
lambda {
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ugly_id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should return 404 when incoming message and request ids don't match" do
ir = info_requests(:fancy_dog_request)
wrong_id = info_requests(:naughty_chicken_request).id
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
lambda {
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => wrong_id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should return 404 for ugly URLs contain a request id that isn't an integer, even if the integer prefix refers to an actual request" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
ugly_id = "%d95" % [info_requests(:naughty_chicken_request).id]
lambda {
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ugly_id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
lambda {
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ugly_id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should return 404 when incoming message and request ids don't match" do
ir = info_requests(:fancy_dog_request)
wrong_id = info_requests(:naughty_chicken_request).id
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
lambda {
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => wrong_id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should generate valid HTML verson of PDF attachments" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-pdf-attachment.email', ir.incoming_email)
ir.reload
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['fs_50379341.pdf.html'], :skip_cache => 1
response.content_type.should == "text/html"
response.should have_text(/Walberswick Parish Council/)
end
it "should not cause a reparsing of the raw email, even when the result would be a 404" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
attachment = IncomingMessage.get_attachment_by_url_part_number(ir.incoming_messages[1].get_attachments_for_display, 2)
attachment.body.should have_text(/Second hello/)
# change the raw_email associated with the message; this only be reparsed when explicitly asked for
ir.incoming_messages[1].raw_email.data = ir.incoming_messages[1].raw_email.data.sub("Second", "Third")
# asking for an attachment by the wrong filename results
# in a 404 for browsing users. This shouldn't cause a
# re-parse...
lambda {
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.baz.html'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
attachment = IncomingMessage.get_attachment_by_url_part_number(ir.incoming_messages[1].get_attachments_for_display, 2)
attachment.body.should have_text(/Second hello/)
# ...nor should asking for it by its correct filename...
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
response.should_not have_text(/Third hello/)
# ...but if we explicitly ask for attachments to be extracted, then they should be
force = true
ir.incoming_messages[1].parse_raw_email!(force)
attachment = IncomingMessage.get_attachment_by_url_part_number(ir.incoming_messages[1].get_attachments_for_display, 2)
attachment.body.should have_text(/Second hello/)
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
response.should have_text(/Third hello/)
end
it "should treat attachments with unknown extensions as binary" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-attachment-unknown-extension.email', ir.incoming_email)
ir.reload
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.qwglhm'], :skip_cache => 1
response.content_type.should == "application/octet-stream"
response.should have_text(/an unusual sort of file/)
end
it "should not download attachments with wrong file name" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
lambda {
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2,
:file_name => ['http://trying.to.hack']
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should censor attachments downloaded as binary" do
ir = info_requests(:fancy_dog_request)
censor_rule = CensorRule.new()
censor_rule.text = "Second"
censor_rule.replacement = "Mouse"
censor_rule.last_edit_editor = "unknown"
censor_rule.last_edit_comment = "none"
ir.censor_rules << censor_rule
begin
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1
response.content_type.should == "text/plain"
response.should have_text(/xxxxxx hello/)
ensure
ir.censor_rules.clear
end
end
it "should censor with rules on the user (rather than the request)" do
ir = info_requests(:fancy_dog_request)
censor_rule = CensorRule.new()
censor_rule.text = "Second"
censor_rule.replacement = "Mouse"
censor_rule.last_edit_editor = "unknown"
censor_rule.last_edit_comment = "none"
ir.user.censor_rules << censor_rule
begin
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1
response.content_type.should == "text/plain"
response.should have_text(/xxxxxx hello/)
ensure
ir.user.censor_rules.clear
end
end
it "should censor attachment names" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
# XXX this is horrid, but don't know a better way. If we
# don't do this, the info_request_event to which the
# info_request is attached still uses the unmodified
# version from the fixture.
#event = info_request_events(:useless_incoming_message_event)
ir.reload
assert ir.info_request_events[3].incoming_message.get_attachments_for_display.count == 2
ir.save!
ir.incoming_messages.last.save!
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
assert assigns[:info_request].info_request_events[3].incoming_message.get_attachments_for_display.count == 2
# the issue is that the info_request_events have got cached on them the old info_requests.
# where i'm at: trying to replace those fields that got re-read from the raw email. however tests are failing in very strange ways. currently I don't appear to be getting any attachments parsed in at all when in the template (see "*****" in _correspondence.rhtml) but do when I'm in the code.
# so at this point, assigns[:info_request].incoming_messages[1].get_attachments_for_display is returning stuff, but the equivalent thing in the template isn't.
# but something odd is that the above is return a whole load of attachments which aren't there in the controller
response.body.should have_tag("p.attachment strong", /hello.txt/m)
censor_rule = CensorRule.new()
censor_rule.text = "hello.txt"
censor_rule.replacement = "goodbye.txt"
censor_rule.last_edit_editor = "unknown"
censor_rule.last_edit_comment = "none"
ir.censor_rules << censor_rule
begin
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.body.should have_tag("p.attachment strong", /goodbye.txt/m)
ensure
ir.censor_rules.clear
end
end
describe 'when making a zipfile available' do
it "should have a different zipfile URL when the request changes" do
title = 'why_do_you_have_such_a_fancy_dog'
ir = info_requests(:fancy_dog_request)
session[:user_id] = ir.user.id # bob_smith_user
get :download_entire_request, :url_title => title
assigns[:url_path].should have_text(/#{title}.zip$/)
old_path = assigns[:url_path]
response.location.should have_text(/#{assigns[:url_path]}$/)
zipfile = Zip::ZipFile.open(File.join(File.dirname(__FILE__), "../../cache/zips", old_path)) { |zipfile|
zipfile.count.should == 1 # just the message
}
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
get :download_entire_request, :url_title => title
assigns[:url_path].should have_text(/#{title}.zip$/)
old_path = assigns[:url_path]
response.location.should have_text(/#{assigns[:url_path]}$/)
zipfile = Zip::ZipFile.open(File.join(File.dirname(__FILE__), "../../cache/zips", old_path)) { |zipfile|
zipfile.count.should == 3 # the message plus two "hello.txt" files
}
# The path of the zip file is based on the hash of the timestamp of the last request
# in the thread, so we wait for a second to make sure this one will have a different
# timestamp than the previous.
sleep 1
receive_incoming_mail('incoming-request-attachment-unknown-extension.email', ir.incoming_email)
get :download_entire_request, :url_title => title
assigns[:url_path].should have_text(/#{title}.zip$/)
assigns[:url_path].should_not == old_path
response.location.should have_text(/#{assigns[:url_path]}/)
zipfile = Zip::ZipFile.open(File.join(File.dirname(__FILE__), "../../cache/zips", assigns[:url_path])) { |zipfile|
zipfile.count.should == 4 # the message, two hello.txt plus the unknown attachment
}
end
it 'should successfully make a zipfile for an external request' do
info_request = info_requests(:external_request)
get :download_entire_request, { :url_title => info_request.url_title },
{ :user_id => users(:bob_smith_user) }
response.location.should have_text(/#{assigns[:url_path]}/)
end
end
end
end
describe RequestController, "when changing prominence of a request" do
before(:each) do
load_raw_emails_data
end
it "should not show hidden requests" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('hidden')
end
it "should not show hidden requests even if logged in as their owner" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
session[:user_id] = ir.user.id # bob_smith_user
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('hidden')
end
it "should show hidden requests if logged in as super user" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
session[:user_id] = users(:admin_user)
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('show')
end
it "should not show requester_only requests if you're not logged in" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'requester_only'
ir.save!
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('hidden')
end
it "should show requester_only requests to requester and admin if logged in" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'requester_only'
ir.save!
session[:user_id] = users(:silly_name_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('hidden')
session[:user_id] = ir.user.id # bob_smith_user
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('show')
session[:user_id] = users(:admin_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('show')
end
it 'should not cache an attachment on a request whose prominence is requester_only when showing
the request to the requester or admin' do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'requester_only'
ir.save!
session[:user_id] = ir.user.id # bob_smith_user
@controller.should_not_receive(:foi_fragment_cache_write)
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
end
it "should not download attachments if hidden" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :skip_cache => 1
response.content_type.should == "text/html"
response.should_not have_text(/Second hello/)
response.should render_template('request/hidden')
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 3, :skip_cache => 1
response.content_type.should == "text/html"
response.should_not have_text(/First hello/)
response.should render_template('request/hidden')
end
it 'should not generate an HTML version of an attachment whose prominence is hidden/requester
only even for the requester or an admin but should return a 404' do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
session[:user_id] = users(:admin_user).id
lambda do
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id,
:id => ir.id,
:part => 2,
:file_name => ['hello.txt']
end.should raise_error(ActiveRecord::RecordNotFound)
end
end
# XXX do this for invalid ids
# it "should render 404 file" do
# response.should render_template("#{Rails.root}/public/404.html")
# response.headers["Status"].should == "404 Not Found"
# end
describe RequestController, "when searching for an authority" do
# Whether or not sign-in is required for this step is configurable,
# so we make sure we're logged in, just in case
before do
@user = users(:bob_smith_user)
end
it "should return nothing for the empty query string" do
session[:user_id] = @user.id
get :select_authority, :query => ""
response.should render_template('select_authority')
assigns[:xapian_requests].should == nil
end
it "should return matching bodies" do
session[:user_id] = @user.id
get :select_authority, :query => "Quango"
response.should render_template('select_authority')
assigns[:xapian_requests].results.size == 1
assigns[:xapian_requests].results[0][:model].name.should == public_bodies(:geraldine_public_body).name
end
it "should not give an error when user users unintended search operators" do
for phrase in ["Marketing/PR activities - Aldborough E-Act Free Schoo",
"Request for communications between DCMS/Ed Vaizey and ICO from Jan 1st 2011 - May ",
"Bellevue Road Ryde Isle of Wight PO33 2AR - what is the",
"NHS Ayrshire & Arran",
" cardiff",
"Foo * bax",
"qux ~ quux"]
lambda {
get :select_authority, :query => phrase
}.should_not raise_error(StandardError)
end
end
end
describe RequestController, "when creating a new request" do
integrate_views
before do
@user = users(:bob_smith_user)
@body = public_bodies(:geraldine_public_body)
end
it "should redirect to front page if no public body specified" do
get :new
response.should redirect_to(:controller => 'general', :action => 'frontpage')
end
it "should redirect to front page if no public body specified, when logged in" do
session[:user_id] = @user.id
get :new
response.should redirect_to(:controller => 'general', :action => 'frontpage')
end
it "should redirect 'bad request' page when a body has no email address" do
@body.request_email = ""
@body.save!
get :new, :public_body_id => @body.id
response.should render_template('new_bad_contact')
end
it "should accept a public body parameter" do
get :new, :public_body_id => @body.id
assigns[:info_request].public_body.should == @body
response.should render_template('new')
end
it "should give an error and render 'new' template when a summary isn't given" do
post :new, :info_request => { :public_body_id => @body.id },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 1
assigns[:info_request].errors[:title].should_not be_nil
response.should render_template('new')
end
it "should redirect to sign in page when input is good and nobody is logged in" do
params = { :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 0
}
post :new, params
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
# post_redirect.post_params.should == params # XXX get this working. there's a : vs '' problem amongst others
end
it "should show preview when input is good" do
session[:user_id] = @user.id
post :new, { :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 1
}
response.should render_template('preview')
end
it "should allow re-editing of a request" do
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 0,
:reedit => "Re-edit this request"
response.should render_template('new')
end
it "should create the request and outgoing message, and send the outgoing message by email, and redirect to request page when input is good and somebody is logged in" do
session[:user_id] = @user.id
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 0
ir_array = InfoRequest.find(:all, :conditions => ["title = ?", "Why is your quango called Geraldine?"])
ir_array.size.should == 1
ir = ir_array[0]
ir.outgoing_messages.size.should == 1
om = ir.outgoing_messages[0]
om.body.should == "This is a silly letter. It is too short to be interesting."
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /This is a silly letter. It is too short to be interesting./
response.should redirect_to(:action => 'show', :url_title => ir.url_title)
# This test uses an explicit path because it's relied in
# Google Analytics goals:
response.redirected_to.should =~ /request\/why_is_your_quango_called_gerald\/new$/
end
it "should give an error if the same request is submitted twice" do
session[:user_id] = @user.id
# We use raw_body here, so white space is the same
post :new, :info_request => { :public_body_id => info_requests(:fancy_dog_request).public_body_id,
:title => info_requests(:fancy_dog_request).title },
:outgoing_message => { :body => info_requests(:fancy_dog_request).outgoing_messages[0].raw_body},
:submitted_new_request => 1, :preview => 0, :mouse_house => 1
response.should render_template('new')
end
it "should let you submit another request with the same title" do
session[:user_id] = @user.id
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 0
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a sensible letter. It is too long to be boring." },
:submitted_new_request => 1, :preview => 0
ir_array = InfoRequest.find(:all, :conditions => ["title = ?", "Why is your quango called Geraldine?"], :order => "id")
ir_array.size.should == 2
ir = ir_array[0]
ir2 = ir_array[1]
ir.url_title.should_not == ir2.url_title
response.should redirect_to(:action => 'show', :url_title => ir2.url_title)
end
it 'should respect the rate limit' do
# Try to create three requests in succession.
# (The limit set in config/test.yml is two.)
session[:user_id] = users(:robin_user)
post :new, :info_request => { :public_body_id => @body.id,
:title => "What is the answer to the ultimate question?", :tag_string => "" },
:outgoing_message => { :body => "Please supply the answer from your files." },
:submitted_new_request => 1, :preview => 0
response.should redirect_to(:action => 'show', :url_title => 'what_is_the_answer_to_the_ultima')
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why did the chicken cross the road?", :tag_string => "" },
:outgoing_message => { :body => "Please send me all the relevant documents you hold." },
:submitted_new_request => 1, :preview => 0
response.should redirect_to(:action => 'show', :url_title => 'why_did_the_chicken_cross_the_ro')
post :new, :info_request => { :public_body_id => @body.id,
:title => "What's black and white and red all over?", :tag_string => "" },
:outgoing_message => { :body => "Please send all minutes of meetings and email records that address this question." },
:submitted_new_request => 1, :preview => 0
response.should render_template('user/rate_limited')
end
it 'should ignore the rate limit for specified users' do
# Try to create three requests in succession.
# (The limit set in config/test.yml is two.)
session[:user_id] = users(:robin_user)
users(:robin_user).no_limit = true
users(:robin_user).save!
post :new, :info_request => { :public_body_id => @body.id,
:title => "What is the answer to the ultimate question?", :tag_string => "" },
:outgoing_message => { :body => "Please supply the answer from your files." },
:submitted_new_request => 1, :preview => 0
response.should redirect_to(:action => 'show', :url_title => 'what_is_the_answer_to_the_ultima')
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why did the chicken cross the road?", :tag_string => "" },
:outgoing_message => { :body => "Please send me all the relevant documents you hold." },
:submitted_new_request => 1, :preview => 0
response.should redirect_to(:action => 'show', :url_title => 'why_did_the_chicken_cross_the_ro')
post :new, :info_request => { :public_body_id => @body.id,
:title => "What's black and white and red all over?", :tag_string => "" },
:outgoing_message => { :body => "Please send all minutes of meetings and email records that address this question." },
:submitted_new_request => 1, :preview => 0
response.should redirect_to(:action => 'show', :url_title => 'whats_black_and_white_and_red_al')
end
end
# These go with the previous set, but use mocks instead of fixtures.
# TODO harmonise these
describe RequestController, "when making a new request" do
before do
@user = mock_model(User, :id => 3481, :name => 'Testy')
@user.stub!(:get_undescribed_requests).and_return([])
@user.stub!(:can_leave_requests_undescribed?).and_return(false)
@user.stub!(:can_file_requests?).and_return(true)
@user.stub!(:locale).and_return("en")
User.stub!(:find).and_return(@user)
@body = mock_model(PublicBody, :id => 314, :eir_only? => false, :is_requestable? => true, :name => "Test Quango")
PublicBody.stub!(:find).and_return(@body)
end
it "should allow you to have one undescribed request" do
@user.stub!(:get_undescribed_requests).and_return([ 1 ])
@user.stub!(:can_leave_requests_undescribed?).and_return(false)
session[:user_id] = @user.id
get :new, :public_body_id => @body.id
response.should render_template('new')
end
it "should fail if more than one request undescribed" do
@user.stub!(:get_undescribed_requests).and_return([ 1, 2 ])
@user.stub!(:can_leave_requests_undescribed?).and_return(false)
session[:user_id] = @user.id
get :new, :public_body_id => @body.id
response.should render_template('new_please_describe')
end
it "should allow you if more than one request undescribed but are allowed to leave requests undescribed" do
@user.stub!(:get_undescribed_requests).and_return([ 1, 2 ])
@user.stub!(:can_leave_requests_undescribed?).and_return(true)
session[:user_id] = @user.id
get :new, :public_body_id => @body.id
response.should render_template('new')
end
it "should fail if user is banned" do
@user.stub!(:can_file_requests?).and_return(false)
@user.stub!(:exceeded_limit?).and_return(false)
@user.should_receive(:can_fail_html).and_return('FAIL!')
session[:user_id] = @user.id
get :new, :public_body_id => @body.id
response.should render_template('user/banned')
end
end
describe RequestController, "when viewing an individual response for reply/followup" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should ask for login if you are logged in as wrong person" do
session[:user_id] = users(:silly_name_user).id
get :show_response, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message)
response.should render_template('user/wrong_user')
end
it "should show the response if you are logged in as right person" do
session[:user_id] = users(:bob_smith_user).id
get :show_response, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message)
response.should render_template('show_response')
end
it "should offer the opportunity to reply to the main address" do
session[:user_id] = users(:bob_smith_user).id
get :show_response, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message)
response.body.should have_tag("div#other_recipients ul li", /the main FOI contact address for/)
end
it "should offer an opportunity to reply to another address" do
session[:user_id] = users(:bob_smith_user).id
ir = info_requests(:fancy_dog_request)
ir.allow_new_responses_from = "anybody"
ir.save!
receive_incoming_mail('incoming-request-plain.email', ir.incoming_email, "Frob <frob@bonce.com>")
get :show_response, :id => ir.id, :incoming_message_id => incoming_messages(:useless_incoming_message)
response.body.should have_tag("div#other_recipients ul li", /Frob/)
end
it "should not show individual responses if request hidden, even if request owner" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
session[:user_id] = users(:bob_smith_user).id
get :show_response, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message)
response.should render_template('request/hidden')
end
describe 'when viewing a response for an external request' do
it 'should show a message saying that external requests cannot be followed up' do
get :show_response, :id => info_requests(:external_request).id
response.should render_template('request/followup_bad')
assigns[:reason].should == 'external'
end
it 'should be successful' do
get :show_response, :id => info_requests(:external_request).id
response.should be_success
end
end
end
describe RequestController, "when classifying an information request" do
describe 'if the request is external' do
before do
@external_request = info_requests(:external_request)
end
it 'should redirect to the request page' do
post :describe_state, :id => @external_request.id,
:submitted_describe_state => 1
response.should redirect_to(:action => 'show',
:controller => 'request',
:url_title => @external_request.url_title)
end
end
describe 'when the request is internal' do
before(:each) do
@dog_request = info_requests(:fancy_dog_request)
@dog_request.stub!(:is_old_unclassified?).and_return(false)
InfoRequest.stub!(:find).and_return(@dog_request)
load_raw_emails_data
end
def post_status(status)
post :describe_state, :incoming_message => { :described_state => status },
:id => @dog_request.id,
:last_info_request_event_id => @dog_request.last_event_id_needing_description,
:submitted_describe_state => 1
end
it "should require login" do
post_status('rejected')
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
end
it 'should ask whether the request is old and unclassified' do
@dog_request.should_receive(:is_old_unclassified?)
post_status('rejected')
end
it "should not classify the request if logged in as the wrong user" do
session[:user_id] = users(:silly_name_user).id
post_status('rejected')
response.should render_template('user/wrong_user')
end
describe 'when the request is old and unclassified' do
before do
@dog_request.stub!(:is_old_unclassified?).and_return(true)
RequestMailer.stub!(:deliver_old_unclassified_updated)
end
describe 'when the user is not logged in' do
it 'should require login' do
session[:user_id] = nil
post_status('rejected')
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
end
end
describe 'when the user is logged in as a different user' do
before do
@other_user = mock_model(User)
session[:user_id] = users(:silly_name_user).id
end
it 'should classify the request' do
@dog_request.stub!(:calculate_status).and_return('rejected')
@dog_request.should_receive(:set_described_state).with('rejected')
post_status('rejected')
end
it 'should log a status update event' do
expected_params = {:user_id => users(:silly_name_user).id,
:old_described_state => 'waiting_response',
:described_state => 'rejected'}
event = mock_model(InfoRequestEvent)
@dog_request.should_receive(:log_event).with("status_update", expected_params).and_return(event)
post_status('rejected')
end
it 'should send an email to the requester letting them know someone has updated the status of their request' do
RequestMailer.should_receive(:deliver_old_unclassified_updated)
post_status('rejected')
end
it 'should redirect to the request page' do
post_status('rejected')
response.should redirect_to(:action => 'show', :controller => 'request', :url_title => @dog_request.url_title)
end
it 'should show a message thanking the user for a good deed' do
post_status('rejected')
flash[:notice].should == 'Thank you for updating this request!'
end
end
end
describe 'when logged in as an admin user who is not the actual requester' do
before do
@admin_user = users(:admin_user)
session[:user_id] = @admin_user.id
@dog_request = info_requests(:fancy_dog_request)
InfoRequest.stub!(:find).and_return(@dog_request)
@dog_request.stub!(:each).and_return([@dog_request])
end
it 'should update the status of the request' do
@dog_request.stub!(:calculate_status).and_return('rejected')
@dog_request.should_receive(:set_described_state).with('rejected')
post_status('rejected')
end
it 'should log a status update event' do
event = mock_model(InfoRequestEvent)
expected_params = {:user_id => @admin_user.id,
:old_described_state => 'waiting_response',
:described_state => 'rejected'}
@dog_request.should_receive(:log_event).with("status_update", expected_params).and_return(event)
post_status('rejected')
end
it 'should record a classification' do
event = mock_model(InfoRequestEvent)
@dog_request.stub!(:log_event).with("status_update", anything()).and_return(event)
RequestClassification.should_receive(:create!).with(:user_id => @admin_user.id,
:info_request_event_id => event.id)
post_status('rejected')
end
it 'should send an email to the requester letting them know someone has updated the status of their request' do
RequestMailer.should_receive(:deliver_old_unclassified_updated)
post_status('rejected')
end
it 'should redirect to the request page' do
post_status('rejected')
response.should redirect_to(:action => 'show', :controller => 'request', :url_title => @dog_request.url_title)
end
it 'should show a message thanking the user for a good deed' do
post_status('rejected')
flash[:notice].should == 'Thank you for updating this request!'
end
end
describe 'when logged in as an admin user who is also the actual requester' do
before do
@admin_user = users(:admin_user)
session[:user_id] = @admin_user.id
@dog_request = info_requests(:fancy_dog_request)
@dog_request.user = @admin_user
@dog_request.save!
InfoRequest.stub!(:find).and_return(@dog_request)
@dog_request.stub!(:each).and_return([@dog_request])
end
it 'should update the status of the request' do
@dog_request.stub!(:calculate_status).and_return('rejected')
@dog_request.should_receive(:set_described_state).with('rejected')
post_status('rejected')
end
it 'should not log a status update event' do
@dog_request.should_not_receive(:log_event)
post_status('rejected')
end
it 'should not send an email to the requester letting them know someone has updated the status of their request' do
RequestMailer.should_not_receive(:deliver_old_unclassified_updated)
post_status('rejected')
end
it 'should say it is showing advice as to what to do next' do
post_status('rejected')
flash[:notice].should match(/Here is what to do now/)
end
it 'should redirect to the unhappy page' do
post_status('rejected')
response.should redirect_to(:controller => 'help', :action => 'unhappy', :url_title => @dog_request.url_title)
end
end
describe 'when logged in as the requestor' do
before do
@request_owner = users(:bob_smith_user)
session[:user_id] = @request_owner.id
@dog_request.awaiting_description.should == true
@dog_request.stub!(:each).and_return([@dog_request])
end
it "should successfully classify response if logged in as user controlling request" do
post_status('rejected')
response.should redirect_to(:controller => 'help', :action => 'unhappy', :url_title => @dog_request.url_title)
@dog_request.reload
@dog_request.awaiting_description.should == false
@dog_request.described_state.should == 'rejected'
@dog_request.get_last_response_event.should == info_request_events(:useless_incoming_message_event)
@dog_request.get_last_response_event.calculated_state.should == 'rejected'
end
it 'should not log a status update event' do
@dog_request.should_not_receive(:log_event)
post_status('rejected')
end
it 'should not send an email to the requester letting them know someone has updated the status of their request' do
RequestMailer.should_not_receive(:deliver_old_unclassified_updated)
post_status('rejected')
end
it "should send email when classified as requires_admin" do
post :describe_state, :incoming_message => { :described_state => "requires_admin" }, :id => @dog_request.id, :incoming_message_id => incoming_messages(:useless_incoming_message), :last_info_request_event_id => @dog_request.last_event_id_needing_description, :submitted_describe_state => 1
response.should redirect_to(:controller => 'help', :action => 'contact')
@dog_request.reload
@dog_request.awaiting_description.should == false
@dog_request.described_state.should == 'requires_admin'
@dog_request.get_last_response_event.calculated_state.should == 'requires_admin'
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /as needing admin/
mail.from_addrs.first.to_s.should == @request_owner.name_and_email
end
it 'should say it is showing advice as to what to do next' do
post_status('rejected')
flash[:notice].should match(/Here is what to do now/)
end
it 'should redirect to the unhappy page' do
post_status('rejected')
response.should redirect_to(:controller => 'help', :action => 'unhappy', :url_title => @dog_request.url_title)
end
it "knows about extended states" do
InfoRequest.send(:require, File.expand_path(File.join(File.dirname(__FILE__), '..', 'models', 'customstates')))
InfoRequest.send(:include, InfoRequestCustomStates)
InfoRequest.class_eval('@@custom_states_loaded = true')
RequestController.send(:require, File.expand_path(File.join(File.dirname(__FILE__), '..', 'models', 'customstates')))
RequestController.send(:include, RequestControllerCustomStates)
RequestController.class_eval('@@custom_states_loaded = true')
Time.stub!(:now).and_return(Time.utc(2007, 11, 10, 00, 01))
post_status('deadline_extended')
flash[:notice].should == 'Authority has requested extension of the deadline.'
end
end
describe 'when redirecting after a successful status update by the request owner' do
before do
@request_owner = users(:bob_smith_user)
session[:user_id] = @request_owner.id
@dog_request = info_requests(:fancy_dog_request)
@dog_request.stub!(:each).and_return([@dog_request])
InfoRequest.stub!(:find).and_return(@dog_request)
@old_filters = ActionController::Routing::Routes.filters
ActionController::Routing::Routes.filters = RoutingFilter::Chain.new
end
after do
ActionController::Routing::Routes.filters = @old_filters
end
def request_url
"request/#{@dog_request.url_title}"
end
def unhappy_url
"help/unhappy/#{@dog_request.url_title}"
end
def expect_redirect(status, redirect_path)
post_status(status)
response.should redirect_to("http://test.host/#{redirect_path}")
end
it 'should redirect to the "request url" with a message in the right tense when status is updated to "waiting response" and the response is not overdue' do
@dog_request.stub!(:date_response_required_by).and_return(Time.now.to_date+1)
@dog_request.stub!(:date_very_overdue_after).and_return(Time.now.to_date+40)
expect_redirect("waiting_response", "request/#{@dog_request.url_title}")
flash[:notice].should match(/should get a response/)
end
it 'should redirect to the "request url" with a message in the right tense when status is updated to "waiting response" and the response is overdue' do
@dog_request.stub!(:date_response_required_by).and_return(Time.now.to_date-1)
@dog_request.stub!(:date_very_overdue_after).and_return(Time.now.to_date+40)
expect_redirect('waiting_response', request_url)
flash[:notice].should match(/should have got a response/)
end
it 'should redirect to the "request url" with a message in the right tense when status is updated to "waiting response" and the response is overdue' do
@dog_request.stub!(:date_response_required_by).and_return(Time.now.to_date-2)
@dog_request.stub!(:date_very_overdue_after).and_return(Time.now.to_date-1)
expect_redirect('waiting_response', unhappy_url)
flash[:notice].should match(/is long overdue/)
flash[:notice].should match(/by more than 40 working days/)
flash[:notice].should match(/within 20 working days/)
end
it 'should redirect to the "request url" when status is updated to "not held"' do
expect_redirect('not_held', request_url)
end
it 'should redirect to the "request url" when status is updated to "successful"' do
expect_redirect('successful', request_url)
end
it 'should redirect to the "unhappy url" when status is updated to "rejected"' do
expect_redirect('rejected', "help/unhappy/#{@dog_request.url_title}")
end
it 'should redirect to the "unhappy url" when status is updated to "partially successful"' do
expect_redirect('partially_successful', "help/unhappy/#{@dog_request.url_title}")
end
it 'should redirect to the "response url" when status is updated to "waiting clarification" and there is a last response' do
incoming_message = mock_model(IncomingMessage)
@dog_request.stub!(:get_last_response).and_return(incoming_message)
expect_redirect('waiting_clarification', "request/#{@dog_request.id}/response/#{incoming_message.id}")
end
it 'should redirect to the "response no followup url" when status is updated to "waiting clarification" and there are no events needing description' do
@dog_request.stub!(:get_last_response).and_return(nil)
expect_redirect('waiting_clarification', "request/#{@dog_request.id}/response")
end
it 'should redirect to the "respond to last url" when status is updated to "gone postal"' do
expect_redirect('gone_postal', "request/#{@dog_request.id}/response/#{@dog_request.get_last_response.id}?gone_postal=1")
end
it 'should redirect to the "request url" when status is updated to "internal review"' do
expect_redirect('internal_review', request_url)
end
it 'should redirect to the "help general url" when status is updated to "requires admin"' do
expect_redirect('requires_admin', "help/contact")
end
it 'should redirect to the "help general url" when status is updated to "error message"' do
expect_redirect('error_message', "help/contact")
end
it 'should redirect to the "respond to last url url" when status is updated to "user_withdrawn"' do
expect_redirect('user_withdrawn', "request/#{@dog_request.id}/response/#{@dog_request.get_last_response.id}")
end
end
end
end
describe RequestController, "when sending a followup message" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should require login" do
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort' }, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
end
it "should not let you if you are logged in as the wrong user" do
session[:user_id] = users(:silly_name_user).id
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort' }, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
response.should render_template('user/wrong_user')
end
it "should give an error and render 'show_response' template when a body isn't given" do
session[:user_id] = users(:bob_smith_user).id
post :show_response, :outgoing_message => { :body => "", :what_doing => 'normal_sort'}, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
# XXX how do I check the error message here?
response.should render_template('show_response')
end
it "should show preview when input is good" do
session[:user_id] = users(:bob_smith_user).id
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort'}, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1, :preview => 1
response.should render_template('followup_preview')
end
it "should allow re-editing of a preview" do
session[:user_id] = users(:bob_smith_user).id
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort'}, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1, :preview => 0, :reedit => "Re-edit this request"
response.should render_template('show_response')
end
it "should send the follow up message if you are the right user" do
# fake that this is a clarification
info_requests(:fancy_dog_request).set_described_state('waiting_clarification')
info_requests(:fancy_dog_request).described_state.should == 'waiting_clarification'
info_requests(:fancy_dog_request).get_last_response_event.calculated_state.should == 'waiting_clarification'
# make the followup
session[:user_id] = users(:bob_smith_user).id
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort' }, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
# check it worked
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /What a useless response! You suck./
mail.to_addrs.first.to_s.should == "FOI Person <foiperson@localhost>"
response.should redirect_to(:action => 'show', :url_title => info_requests(:fancy_dog_request).url_title)
# and that the status changed
info_requests(:fancy_dog_request).reload
info_requests(:fancy_dog_request).described_state.should == 'waiting_response'
info_requests(:fancy_dog_request).get_last_response_event.calculated_state.should == 'waiting_clarification'
end
it "should give an error if the same followup is submitted twice" do
session[:user_id] = users(:bob_smith_user).id
# make the followup once
post :show_response, :outgoing_message => { :body => "Stop repeating yourself!", :what_doing => 'normal_sort' }, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
response.should redirect_to(:action => 'show', :url_title => info_requests(:fancy_dog_request).url_title)
# second time should give an error
post :show_response, :outgoing_message => { :body => "Stop repeating yourself!", :what_doing => 'normal_sort' }, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
# XXX how do I check the error message here?
response.should render_template('show_response')
end
end
# XXX Stuff after here should probably be in request_mailer_spec.rb - but then
# it can't check the URLs in the emails I don't think, ugh.
describe RequestController, "sending overdue request alerts" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should send an overdue alert mail to creators of overdue requests" do
chicken_request = info_requests(:naughty_chicken_request)
chicken_request.outgoing_messages[0].last_sent_at = Time.now() - 30.days
chicken_request.outgoing_messages[0].save!
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
mail = chicken_mails[0]
mail.body.should =~ /promptly, as normally/
mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.name_and_email
mail.body =~ /(http:\/\/.*\/c\/(.*))/
mail_url = $1
mail_token = $2
session[:user_id].should be_nil
controller.test_code_redirect_by_email_token(mail_token, self) # XXX hack to avoid having to call User controller for email link
session[:user_id].should == info_requests(:naughty_chicken_request).user.id
response.should render_template('show_response')
assigns[:info_request].should == info_requests(:naughty_chicken_request)
end
it "should include clause for schools when sending an overdue alert mail to creators of overdue requests" do
chicken_request = info_requests(:naughty_chicken_request)
chicken_request.outgoing_messages[0].last_sent_at = Time.now() - 30.days
chicken_request.outgoing_messages[0].save!
chicken_request.public_body.tag_string = "school"
chicken_request.public_body.save!
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
mail = chicken_mails[0]
mail.body.should =~ /promptly, as normally/
mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.name_and_email
end
it "should send not actually send the overdue alert if the user is banned but should
record it as sent" do
user = info_requests(:naughty_chicken_request).user
user.ban_text = 'Banned'
user.save!
UserInfoRequestSentAlert.find_all_by_user_id(user.id).count.should == 0
RequestMailer.alert_overdue_requests
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 0
UserInfoRequestSentAlert.find_all_by_user_id(user.id).count.should > 0
end
it "should send a very overdue alert mail to creators of very overdue requests" do
chicken_request = info_requests(:naughty_chicken_request)
chicken_request.outgoing_messages[0].last_sent_at = Time.now() - 60.days
chicken_request.outgoing_messages[0].save!
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
mail = chicken_mails[0]
mail.body.should =~ /required by law/
mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.name_and_email
mail.body =~ /(http:\/\/.*\/c\/(.*))/
mail_url = $1
mail_token = $2
session[:user_id].should be_nil
controller.test_code_redirect_by_email_token(mail_token, self) # XXX hack to avoid having to call User controller for email link
session[:user_id].should == info_requests(:naughty_chicken_request).user.id
response.should render_template('show_response')
assigns[:info_request].should == info_requests(:naughty_chicken_request)
end
it "should not resend alerts to people who've already received them" do
chicken_request = info_requests(:naughty_chicken_request)
chicken_request.outgoing_messages[0].last_sent_at = Time.now() - 60.days
chicken_request.outgoing_messages[0].save!
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
end
it 'should send alerts for requests where the last event forming the initial request is a followup
being sent following a request for clarification' do
chicken_request = info_requests(:naughty_chicken_request)
chicken_request.outgoing_messages[0].last_sent_at = Time.now() - 60.days
chicken_request.outgoing_messages[0].save!
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
# Request is waiting clarification
chicken_request.set_described_state('waiting_clarification')
# Followup message is sent
outgoing_message = OutgoingMessage.new(:status => 'ready',
:message_type => 'followup',
:info_request_id => chicken_request.id,
:body => 'Some text',
:what_doing => 'normal_sort')
outgoing_message.send_message
outgoing_message.save!
chicken_request = InfoRequest.find(chicken_request.id)
# Last event forming the request is now the followup
chicken_request.last_event_forming_initial_request.event_type.should == 'followup_sent'
# This isn't overdue, so no email
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
# Make the followup older
outgoing_message.last_sent_at = Time.now() - 60.days
outgoing_message.save!
# Now it should be alerted on
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 2
end
end
describe RequestController, "sending unclassified new response reminder alerts" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should send an alert" do
RequestMailer.alert_new_response_reminders
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 3 # sufficiently late it sends reminders too
mail = deliveries[0]
mail.body.should =~ /To let everyone know/
mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email
mail.body =~ /(http:\/\/.*\/c\/(.*))/
mail_url = $1
mail_token = $2
session[:user_id].should be_nil
controller.test_code_redirect_by_email_token(mail_token, self) # XXX hack to avoid having to call User controller for email link
session[:user_id].should == info_requests(:fancy_dog_request).user.id
response.should render_template('show')
assigns[:info_request].should == info_requests(:fancy_dog_request)
# XXX should check anchor tag here :) that it goes to last new response
end
end
describe RequestController, "clarification required alerts" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should send an alert" do
ir = info_requests(:fancy_dog_request)
ir.set_described_state('waiting_clarification')
# this is pretty horrid, but will do :) need to make it waiting
# clarification more than 3 days ago for the alerts to go out.
ActiveRecord::Base.connection.update "update info_requests set updated_at = '" + (Time.now - 5.days).strftime("%Y-%m-%d %H:%M:%S") + "' where id = " + ir.id.to_s
ir.reload
RequestMailer.alert_not_clarified_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /asked you to explain/
mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email
mail.body =~ /(http:\/\/.*\/c\/(.*))/
mail_url = $1
mail_token = $2
session[:user_id].should be_nil
controller.test_code_redirect_by_email_token(mail_token, self) # XXX hack to avoid having to call User controller for email link
session[:user_id].should == info_requests(:fancy_dog_request).user.id
response.should render_template('show_response')
assigns[:info_request].should == info_requests(:fancy_dog_request)
end
it "should not send an alert if you are banned" do
ir = info_requests(:fancy_dog_request)
ir.set_described_state('waiting_clarification')
ir.user.ban_text = 'Banned'
ir.user.save!
# this is pretty horrid, but will do :) need to make it waiting
# clarification more than 3 days ago for the alerts to go out.
ActiveRecord::Base.connection.update "update info_requests set updated_at = '" + (Time.now - 5.days).strftime("%Y-%m-%d %H:%M:%S") + "' where id = " + ir.id.to_s
ir.reload
RequestMailer.alert_not_clarified_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 0
end
end
describe RequestController, "comment alerts" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should send an alert (once and once only)" do
# delete fixture comment and make new one, so is in last month (as
# alerts are only for comments in last month, see
# RequestMailer.alert_comment_on_request)
existing_comment = info_requests(:fancy_dog_request).comments[0]
existing_comment.info_request_events[0].destroy
existing_comment.destroy
new_comment = info_requests(:fancy_dog_request).add_comment('I really love making annotations.', users(:silly_name_user))
# send comment alert
RequestMailer.alert_comment_on_request
deliveries = ActionMailer::Base.deliveries
mail = deliveries[0]
mail.body.should =~ /has annotated your/
mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email
mail.body =~ /(http:\/\/.*)/
mail_url = $1
mail_url.should match("/request/why_do_you_have_such_a_fancy_dog#comment-#{new_comment.id}")
# check if we send again, no more go out
deliveries.clear
RequestMailer.alert_comment_on_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 0
end
it "should not send an alert when you comment on your own request" do
# delete fixture comment and make new one, so is in last month (as
# alerts are only for comments in last month, see
# RequestMailer.alert_comment_on_request)
existing_comment = info_requests(:fancy_dog_request).comments[0]
existing_comment.info_request_events[0].destroy
existing_comment.destroy
new_comment = info_requests(:fancy_dog_request).add_comment('I also love making annotations.', users(:bob_smith_user))
# try to send comment alert
RequestMailer.alert_comment_on_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 0
end
it 'should not send an alert for a comment on an external request' do
external_request = info_requests(:external_request)
external_request.add_comment("This external request is interesting", users(:silly_name_user))
# try to send comment alert
RequestMailer.alert_comment_on_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 0
end
it "should send an alert when there are two new comments" do
# add two comments - the second one sould be ignored, as is by the user who made the request.
# the new comment here, will cause the one in the fixture to be picked up as a new comment by alert_comment_on_request also.
new_comment = info_requests(:fancy_dog_request).add_comment('Not as daft as this one', users(:silly_name_user))
new_comment = info_requests(:fancy_dog_request).add_comment('Or this one!!!', users(:bob_smith_user))
RequestMailer.alert_comment_on_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /There are 2 new annotations/
mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email
mail.body =~ /(http:\/\/.*)/
mail_url = $1
mail_url.should match("/request/why_do_you_have_such_a_fancy_dog#comment-#{comments(:silly_comment).id}")
end
end
describe RequestController, "when viewing comments" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should link to the user who submitted it" do
session[:user_id] = users(:bob_smith_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.body.should have_tag("div#comment-1 h2", /Silly.*left an annotation/m)
response.body.should_not have_tag("div#comment-1 h2", /You.*left an annotation/m)
end
it "should link to the user who submitted to it, even if it is you" do
session[:user_id] = users(:silly_name_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.body.should have_tag("div#comment-1 h2", /Silly.*left an annotation/m)
response.body.should_not have_tag("div#comment-1 h2", /You.*left an annotation/m)
end
end
describe RequestController, "authority uploads a response from the web interface" do
integrate_views
before(:each) do
# domain after the @ is used for authentication of FOI officers, so to test it
# we need a user which isn't at localhost.
@normal_user = User.new(:name => "Mr. Normal", :email => "normal-user@flourish.org",
:password => PostRedirect.generate_random_token)
@normal_user.save!
@foi_officer_user = User.new(:name => "The Geraldine Quango", :email => "geraldine-requests@localhost",
:password => PostRedirect.generate_random_token)
@foi_officer_user.save!
end
it "should require login to view the form to upload" do
@ir = info_requests(:fancy_dog_request)
@ir.public_body.is_foi_officer?(@normal_user).should == false
session[:user_id] = @normal_user.id
get :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('user/wrong_user')
end
it "should let you view upload form if you are an FOI officer" do
@ir = info_requests(:fancy_dog_request)
@ir.public_body.is_foi_officer?(@foi_officer_user).should == true
session[:user_id] = @foi_officer_user.id
get :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('request/upload_response')
end
it "should prevent uploads if you are not a requester" do
@ir = info_requests(:fancy_dog_request)
incoming_before = @ir.incoming_messages.size
session[:user_id] = @normal_user.id
# post up a photo of the parrot
parrot_upload = fixture_file_upload('files/parrot.png','image/png')
post :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog',
:body => "Find attached a picture of a parrot",
:file_1 => parrot_upload,
:submitted_upload_response => 1
response.should render_template('user/wrong_user')
end
it "should prevent entirely blank uploads" do
session[:user_id] = @foi_officer_user.id
post :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog', :body => "", :submitted_upload_response => 1
response.should render_template('request/upload_response')
flash[:error].should match(/Please type a message/)
end
it 'should 404 for non existent requests' do
lambda{ post :upload_response, :url_title => 'i_dont_exist'}.should raise_error(ActiveRecord::RecordNotFound)
end
# How do I test a file upload in rails?
# http://stackoverflow.com/questions/1178587/how-do-i-test-a-file-upload-in-rails
it "should let the authority upload a file" do
@ir = info_requests(:fancy_dog_request)
incoming_before = @ir.incoming_messages.size
session[:user_id] = @foi_officer_user.id
# post up a photo of the parrot
parrot_upload = fixture_file_upload('files/parrot.png','image/png')
post :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog',
:body => "Find attached a picture of a parrot",
:file_1 => parrot_upload,
:submitted_upload_response => 1
response.should redirect_to(:action => 'show', :url_title => 'why_do_you_have_such_a_fancy_dog')
flash[:notice].should match(/Thank you for responding to this FOI request/)
# check there is a new attachment
incoming_after = @ir.incoming_messages.size
incoming_after.should == incoming_before + 1
# check new attachment looks vaguely OK
new_im = @ir.incoming_messages[-1]
new_im.mail.body.should match(/Find attached a picture of a parrot/)
attachments = new_im.get_attachments_for_display
attachments.size.should == 1
attachments[0].filename.should == "parrot.png"
attachments[0].display_size.should == "94K"
end
end
describe RequestController, "when showing JSON version for API" do
before(:each) do
load_raw_emails_data
end
it "should return data in JSON form" do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :format => 'json'
ir = JSON.parse(response.body)
ir.class.to_s.should == 'Hash'
ir['url_title'].should == 'why_do_you_have_such_a_fancy_dog'
ir['public_body']['url_name'].should == 'tgq'
ir['user']['url_name'].should == 'bob_smith'
end
end
describe RequestController, "when doing type ahead searches" do
integrate_views
it "should return nothing for the empty query string" do
get :search_typeahead, :q => ""
response.should render_template('request/_search_ahead.rhtml')
assigns[:xapian_requests].should be_nil
end
it "should return a request matching the given keyword, but not users with a matching description" do
get :search_typeahead, :q => "chicken"
response.should render_template('request/_search_ahead.rhtml')
assigns[:xapian_requests].results.size.should == 1
assigns[:xapian_requests].results[0][:model].title.should == info_requests(:naughty_chicken_request).title
end
it "should return all requests matching any of the given keywords" do
get :search_typeahead, :q => "money dog"
response.should render_template('request/_search_ahead.rhtml')
assigns[:xapian_requests].results.map{|x|x[:model].info_request}.should =~ [
info_requests(:fancy_dog_request),
info_requests(:naughty_chicken_request),
info_requests(:another_boring_request),
]
end
it "should not return matches for short words" do
get :search_typeahead, :q => "a"
response.should render_template('request/_search_ahead.rhtml')
assigns[:xapian_requests].should be_nil
end
it "should do partial matches for longer words" do
get :search_typeahead, :q => "chick"
response.should render_template('request/_search_ahead.rhtml')
assigns[:xapian_requests].results.size.should ==1
end
it "should not give an error when user users unintended search operators" do
for phrase in ["Marketing/PR activities - Aldborough E-Act Free Schoo",
"Request for communications between DCMS/Ed Vaizey and ICO from Jan 1st 2011 - May ",
"Bellevue Road Ryde Isle of Wight PO33 2AR - what is the",
"NHS Ayrshire & Arran",
"uda ( units of dent",
"frob * baz",
"bar ~ qux"]
lambda {
get :search_typeahead, :q => phrase
}.should_not raise_error(StandardError)
end
end
it "should return all requests matching any of the given keywords" do
get :search_typeahead, :q => "dog -chicken"
assigns[:xapian_requests].results.size.should == 1
end
end
describe RequestController, "when showing similar requests" do
integrate_views
it "should work" do
get :similar, :url_title => info_requests(:badger_request).url_title
response.should render_template("request/similar")
assigns[:info_request].should == info_requests(:badger_request)
end
it "should show similar requests" do
badger_request = info_requests(:badger_request)
get :similar, :url_title => badger_request.url_title
# Xapian seems to think *all* the requests are similar
assigns[:xapian_object].results.map{|x|x[:model].info_request}.should =~ InfoRequest.all.reject {|x| x == badger_request}
end
it "should 404 for non-existent paths" do
lambda {
get :similar, :url_title => "there_is_really_no_such_path_owNAFkHR"
}.should raise_error(ActiveRecord::RecordNotFound)
end
end
describe RequestController, "when reporting a request when not logged in" do
it "should only allow logged-in users to report requests" do
get :report_request, :url_title => info_requests(:badger_request).url_title
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
end
end
describe RequestController, "when reporting a request (logged in)" do
integrate_views
before do
@user = users(:robin_user)
session[:user_id] = @user.id
end
it "should 404 for non-existent requests" do
lambda {
post :report_request, :url_title => "hjksfdhjk_louytu_qqxxx"
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should mark a request as having been reported" do
ir = info_requests(:badger_request)
title = ir.url_title
get :show, :url_title => title
assigns[:info_request].attention_requested.should == false
post :report_request, :url_title => title
response.should redirect_to(:action => :show, :url_title => title)
get :show, :url_title => title
response.should be_success
assigns[:info_request].attention_requested.should == true
assigns[:info_request].described_state.should == "attention_requested"
end
it "should not allow a request to be reported twice" do
title = info_requests(:badger_request).url_title
post :report_request, :url_title => title
response.should redirect_to(:action => :show, :url_title => title)
get :show, :url_title => title
response.should be_success
response.body.should include("has been reported")
post :report_request, :url_title => title
response.should redirect_to(:action => :show, :url_title => title)
get :show, :url_title => title
response.should be_success
response.body.should include("has already been reported")
end
it "should let users know a request has been reported" do
title = info_requests(:badger_request).url_title
get :show, :url_title => title
response.body.should include("Offensive?")
post :report_request, :url_title => title
response.should redirect_to(:action => :show, :url_title => title)
get :show, :url_title => title
response.body.should_not include("Offensive?")
response.body.should include("This request has been reported")
info_requests(:badger_request).set_described_state("successful")
get :show, :url_title => title
response.body.should_not include("This request has been reported")
response.body.should =~ (/the site administrators.*have not hidden it/)
end
it "should send an email from the reporter to admins" do
ir = info_requests(:badger_request)
title = ir.url_title
post :report_request, :url_title => title
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.subject.should =~ /attention_requested/
mail.from.should include(@user.email)
mail.body.should include(@user.name)
end
end
Reformat for line length, add the expected response code.
# -*- coding: utf-8 -*-
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe RequestController, "when listing recent requests" do
before(:each) do
load_raw_emails_data
get_fixtures_xapian_index
end
it "should be successful" do
get :list, :view => 'all'
response.should be_success
end
it "should render with 'list' template" do
get :list, :view => 'all'
response.should render_template('list')
end
it "should filter requests" do
get :list, :view => 'all'
assigns[:list_results].map(&:info_request).should =~ InfoRequest.all
# default sort order is the request with the most recently created event first
assigns[:list_results].map(&:info_request).should == InfoRequest.all(
:order => "(select max(info_request_events.created_at) from info_request_events where info_request_events.info_request_id = info_requests.id) DESC")
get :list, :view => 'successful'
assigns[:list_results].map(&:info_request).should =~ InfoRequest.all(
:conditions => "id in (
select info_request_id
from info_request_events
where not exists (
select *
from info_request_events later_events
where later_events.created_at > info_request_events.created_at
and later_events.info_request_id = info_request_events.info_request_id
and later_events.described_state is not null
)
and info_request_events.described_state in ('successful', 'partially_successful')
)")
end
it "should filter requests by date" do
# The semantics of the search are that it finds any InfoRequest
# that has any InfoRequestEvent created in the specified range
get :list, :view => 'all', :request_date_before => '13/10/2007'
assigns[:list_results].map(&:info_request).should =~ InfoRequest.all(
:conditions => "id in (select info_request_id from info_request_events where created_at < '2007-10-13'::date)")
get :list, :view => 'all', :request_date_after => '13/10/2007'
assigns[:list_results].map(&:info_request).should =~ InfoRequest.all(
:conditions => "id in (select info_request_id from info_request_events where created_at > '2007-10-13'::date)")
get :list, :view => 'all', :request_date_after => '13/10/2007', :request_date_before => '01/11/2007'
assigns[:list_results].map(&:info_request).should =~ InfoRequest.all(
:conditions => "id in (select info_request_id from info_request_events where created_at between '2007-10-13'::date and '2007-11-01'::date)")
end
it "should make a sane-sized cache tag" do
get :list, :view => 'all', :request_date_after => '13/10/2007', :request_date_before => '01/11/2007'
assigns[:cache_tag].size.should <= 32
end
it "should vary the cache tag with locale" do
get :list, :view => 'all', :request_date_after => '13/10/2007', :request_date_before => '01/11/2007'
en_tag = assigns[:cache_tag]
session[:locale] = :es
get :list, :view => 'all', :request_date_after => '13/10/2007', :request_date_before => '01/11/2007'
assigns[:cache_tag].should_not == en_tag
end
it "should list internal_review requests as unresolved ones" do
get :list, :view => 'awaiting'
# This doesn’t precisely duplicate the logic of the actual
# query, but it is close enough to give the same result with
# the current set of test data.
assigns[:list_results].should =~ InfoRequestEvent.all(
:conditions => "described_state in (
'waiting_response', 'waiting_clarification',
'internal_review', 'gone_postal', 'error_message', 'requires_admin'
) and not exists (
select *
from info_request_events later_events
where later_events.created_at > info_request_events.created_at
and later_events.info_request_id = info_request_events.info_request_id
)")
get :list, :view => 'awaiting'
assigns[:list_results].map(&:info_request).include?(info_requests(:fancy_dog_request)).should == false
event = info_request_events(:useless_incoming_message_event)
event.described_state = event.calculated_state = "internal_review"
event.save!
rebuild_xapian_index
get :list, :view => 'awaiting'
assigns[:list_results].map(&:info_request).include?(info_requests(:fancy_dog_request)).should == true
end
it "should assign the first page of results" do
xap_results = mock_model(ActsAsXapian::Search,
:results => (1..25).to_a.map { |m| { :model => m } },
:matches_estimated => 1000000)
InfoRequest.should_receive(:full_search).
with([InfoRequestEvent]," (variety:sent OR variety:followup_sent OR variety:response OR variety:comment)", "created_at", anything, anything, anything, anything).
and_return(xap_results)
get :list, :view => 'all'
assigns[:list_results].size.should == 25
assigns[:show_no_more_than].should == RequestController::MAX_RESULTS
end
it "should return 404 for pages we don't want to serve up" do
xap_results = mock_model(ActsAsXapian::Search,
:results => (1..25).to_a.map { |m| { :model => m } },
:matches_estimated => 1000000)
lambda {
get :list, :view => 'all', :page => 100
}.should raise_error(ActiveRecord::RecordNotFound)
end
it 'should not raise an error for a page param of less than zero, but should treat it as
a param of 1' do
lambda{ get :list, :view => 'all', :page => "-1" }.should_not raise_error
assigns[:page].should == 1
end
end
describe RequestController, "when changing things that appear on the request page" do
integrate_views
it "should purge the downstream cache when mail is received" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-plain.email', ir.incoming_email)
PurgeRequest.all().first.model_id.should == ir.id
end
it "should purge the downstream cache when a comment is added" do
ir = info_requests(:fancy_dog_request)
new_comment = info_requests(:fancy_dog_request).add_comment('I also love making annotations.', users(:bob_smith_user))
PurgeRequest.all().first.model_id.should == ir.id
end
it "should purge the downstream cache when a followup is made" do
session[:user_id] = users(:bob_smith_user).id
ir = info_requests(:fancy_dog_request)
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort' }, :id => ir.id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
PurgeRequest.all().first.model_id.should == ir.id
end
it "should purge the downstream cache when the request is categorised" do
ir = info_requests(:fancy_dog_request)
ir.set_described_state('waiting_clarification')
PurgeRequest.all().first.model_id.should == ir.id
end
it "should purge the downstream cache when the authority data is changed" do
ir = info_requests(:fancy_dog_request)
ir.public_body.name = "Something new"
ir.public_body.save!
PurgeRequest.all().map{|x| x.model_id}.should =~ ir.public_body.info_requests.map{|x| x.id}
end
it "should purge the downstream cache when the user name is changed" do
ir = info_requests(:fancy_dog_request)
ir.user.name = "Something new"
ir.user.save!
PurgeRequest.all().map{|x| x.model_id}.should =~ ir.user.info_requests.map{|x| x.id}
end
it "should not purge the downstream cache when non-visible user details are changed" do
ir = info_requests(:fancy_dog_request)
ir.user.hashed_password = "some old hash"
ir.user.save!
PurgeRequest.all().count.should == 0
end
it "should purge the downstream cache when censor rules have changed" do
# XXX really, CensorRules should execute expiry logic as part
# of the after_save of the model. Currently this is part of
# the AdminCensorRuleController logic, so must be tested from
# there. Leaving this stub test in place as a reminder
end
it "should purge the downstream cache when something is hidden by an admin" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
PurgeRequest.all().first.model_id.should == ir.id
end
it "should not create more than one entry for any given resourcce" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
PurgeRequest.all().count.should == 1
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
PurgeRequest.all().count.should == 1
end
end
describe RequestController, "when showing one request" do
integrate_views
before(:each) do
load_raw_emails_data
FileUtils.rm_rf File.join(File.dirname(__FILE__), "../../cache/zips")
end
it "should be successful" do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should be_success
end
it "should render with 'show' template" do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('show')
end
it "should show the request" do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should be_success
response.body.should include("Why do you have such a fancy dog?")
end
it "should assign the request" do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
assigns[:info_request].should == info_requests(:fancy_dog_request)
end
it "should redirect from a numeric URL to pretty one" do
get :show, :url_title => info_requests(:naughty_chicken_request).id
response.should redirect_to(:action => 'show', :url_title => info_requests(:naughty_chicken_request).url_title)
end
it 'should show actions the request owner can take' do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should have_tag('div#owner_actions')
end
describe 'when the request does allow comments' do
it 'should have a comment link' do
get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' },
{ :user_id => users(:admin_user).id }
response.should have_tag('#anyone_actions', /Add an annotation/)
end
end
describe 'when the request does not allow comments' do
it 'should not have a comment link' do
get :show, { :url_title => 'spam_1' },
{ :user_id => users(:admin_user).id }
response.should_not have_tag('#anyone_actions', /Add an annotation/)
end
end
describe 'when the request is being viewed by an admin' do
describe 'if the request is awaiting description' do
before do
dog_request = info_requests(:fancy_dog_request)
dog_request.awaiting_description = true
dog_request.save!
end
it 'should show the describe state form' do
get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' },
{ :user_id => users(:admin_user).id }
response.should have_tag('div.describe_state_form')
end
it 'should ask the user to use the describe state from' do
get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' },
{ :user_id => users(:admin_user).id }
response.should have_tag('p#request_status', :text => /answer the question above/)
end
end
describe 'if the request is waiting for a response and very overdue' do
before do
dog_request = info_requests(:fancy_dog_request)
dog_request.awaiting_description = false
dog_request.described_state = 'waiting_response'
dog_request.save!
dog_request.calculate_status.should == 'waiting_response_very_overdue'
end
it 'should give a link to requesting an internal review' do
get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' },
{ :user_id => users(:admin_user).id }
response.should have_tag('p#request_status', :text =>/requesting an internal review/)
end
end
describe 'if the request is waiting clarification' do
before do
dog_request = info_requests(:fancy_dog_request)
dog_request.awaiting_description = false
dog_request.described_state = 'waiting_clarification'
dog_request.save!
dog_request.calculate_status.should == 'waiting_clarification'
end
it 'should give a link to make a followup' do
get :show, { :url_title => 'why_do_you_have_such_a_fancy_dog' },
{ :user_id => users(:admin_user).id }
response.should have_tag('p#request_status a', :text =>/send a follow up message/)
end
end
end
describe 'when showing an external request' do
describe 'when viewing with no logged in user' do
it 'should be successful' do
get :show, { :url_title => 'balalas' }, { :user_id => nil }
response.should be_success
end
it 'should not display actions the request owner can take' do
get :show, :url_title => 'balalas'
response.should_not have_tag('div#owner_actions')
end
end
describe 'when the request is being viewed by an admin' do
def make_request
get :show, { :url_title => 'balalas' }, { :user_id => users(:admin_user).id }
end
it 'should be successful' do
make_request
response.should be_success
end
describe 'if the request is awaiting description' do
before do
external_request = info_requests(:external_request)
external_request.awaiting_description = true
external_request.save!
end
it 'should not show the describe state form' do
make_request
response.should_not have_tag('div.describe_state_form')
end
it 'should not ask the user to use the describe state form' do
make_request
response.should_not have_tag('p#request_status', :text => /answer the question above/)
end
end
describe 'if the request is waiting for a response and very overdue' do
before do
external_request = info_requests(:external_request)
external_request.awaiting_description = false
external_request.described_state = 'waiting_response'
external_request.save!
external_request.calculate_status.should == 'waiting_response_very_overdue'
end
it 'should not give a link to requesting an internal review' do
make_request
response.should_not have_tag('p#request_status', :text =>/requesting an internal review/)
end
end
describe 'if the request is waiting clarification' do
before do
external_request = info_requests(:external_request)
external_request.awaiting_description = false
external_request.described_state = 'waiting_clarification'
external_request.save!
external_request.calculate_status.should == 'waiting_clarification'
end
it 'should not give a link to make a followup' do
make_request
response.should_not have_tag('p#request_status a', :text =>/send a follow up message/)
end
it 'should not give a link to sign in (in the request status paragraph)' do
make_request
response.should_not have_tag('p#request_status a', :text => /sign in/)
end
end
end
end
describe 'when handling an update_status parameter' do
describe 'when the request is external' do
it 'should assign the "update status" flag to the view as false if the parameter is present' do
get :show, :url_title => 'balalas', :update_status => 1
assigns[:update_status].should be_false
end
it 'should assign the "update status" flag to the view as false if the parameter is not present' do
get :show, :url_title => 'balalas'
assigns[:update_status].should be_false
end
end
it 'should assign the "update status" flag to the view as true if the parameter is present' do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :update_status => 1
assigns[:update_status].should be_true
end
it 'should assign the "update status" flag to the view as false if the parameter is not present' do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
assigns[:update_status].should be_false
end
it 'should require login' do
session[:user_id] = nil
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :update_status => 1
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
end
it 'should work if logged in as the requester' do
session[:user_id] = users(:bob_smith_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :update_status => 1
response.should render_template "request/show"
end
it 'should not work if logged in as not the requester' do
session[:user_id] = users(:silly_name_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :update_status => 1
response.should render_template "user/wrong_user"
end
it 'should work if logged in as an admin user' do
session[:user_id] = users(:admin_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :update_status => 1
response.should render_template "request/show"
end
end
describe 'when handling incoming mail' do
integrate_views
it "should receive incoming messages, send email to creator, and show them" do
ir = info_requests(:fancy_dog_request)
ir.incoming_messages.each { |x| x.parse_raw_email! }
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
size_before = assigns[:info_request_events].size
receive_incoming_mail('incoming-request-plain.email', ir.incoming_email)
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /You have a new response to the Freedom of Information request/
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
(assigns[:info_request_events].size - size_before).should == 1
end
it "should download attachments" do
ir = info_requests(:fancy_dog_request)
ir.incoming_messages.each { |x| x.parse_raw_email!(true) }
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.content_type.should == "text/html"
size_before = assigns[:info_request_events].size
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
(assigns[:info_request_events].size - size_before).should == 1
ir.reload
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1
response.content_type.should == "text/plain"
response.should have_text(/Second hello/)
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 3, :file_name => ['hello.txt'], :skip_cache => 1
response.content_type.should == "text/plain"
response.should have_text(/First hello/)
end
it 'should cache an attachment on a request with normal prominence' do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
@controller.should_receive(:foi_fragment_cache_write)
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id,
:id => ir.id,
:part => 2,
:file_name => ['hello.txt']
end
it "should convert message body to UTF8" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('iso8859_2_raw_email.email', ir.incoming_email)
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should have_text(/tënde/u)
end
it "should generate valid HTML verson of plain text attachments" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
response.content_type.should == "text/html"
response.should have_text(/Second hello/)
end
# This is a regression test for a bug where URLs of this form were causing 500 errors
# instead of 404s.
#
# (Note that in fact only the integer-prefix of the URL part is used, so there are
# *some* “ugly URLs containing a request id that isn't an integer” that actually return
# a 200 response. The point is that IDs of this sort were triggering an error in the
# error-handling path, causing the wrong sort of error response to be returned in the
# case where the integer prefix referred to the wrong request.)
#
# https://github.com/mysociety/alaveteli/issues/351
it "should return 404 for ugly URLs containing a request id that isn't an integer" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
ugly_id = "55195"
lambda {
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ugly_id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
lambda {
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ugly_id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should return 404 when incoming message and request ids don't match" do
ir = info_requests(:fancy_dog_request)
wrong_id = info_requests(:naughty_chicken_request).id
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
lambda {
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => wrong_id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should return 404 for ugly URLs contain a request id that isn't an integer, even if the integer prefix refers to an actual request" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
ugly_id = "%d95" % [info_requests(:naughty_chicken_request).id]
lambda {
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ugly_id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
lambda {
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ugly_id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should return 404 when incoming message and request ids don't match" do
ir = info_requests(:fancy_dog_request)
wrong_id = info_requests(:naughty_chicken_request).id
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
lambda {
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => wrong_id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should generate valid HTML verson of PDF attachments" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-pdf-attachment.email', ir.incoming_email)
ir.reload
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['fs_50379341.pdf.html'], :skip_cache => 1
response.content_type.should == "text/html"
response.should have_text(/Walberswick Parish Council/)
end
it "should not cause a reparsing of the raw email, even when the result would be a 404" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
attachment = IncomingMessage.get_attachment_by_url_part_number(ir.incoming_messages[1].get_attachments_for_display, 2)
attachment.body.should have_text(/Second hello/)
# change the raw_email associated with the message; this only be reparsed when explicitly asked for
ir.incoming_messages[1].raw_email.data = ir.incoming_messages[1].raw_email.data.sub("Second", "Third")
# asking for an attachment by the wrong filename results
# in a 404 for browsing users. This shouldn't cause a
# re-parse...
lambda {
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.baz.html'], :skip_cache => 1
}.should raise_error(ActiveRecord::RecordNotFound)
attachment = IncomingMessage.get_attachment_by_url_part_number(ir.incoming_messages[1].get_attachments_for_display, 2)
attachment.body.should have_text(/Second hello/)
# ...nor should asking for it by its correct filename...
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
response.should_not have_text(/Third hello/)
# ...but if we explicitly ask for attachments to be extracted, then they should be
force = true
ir.incoming_messages[1].parse_raw_email!(force)
attachment = IncomingMessage.get_attachment_by_url_part_number(ir.incoming_messages[1].get_attachments_for_display, 2)
attachment.body.should have_text(/Second hello/)
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt.html'], :skip_cache => 1
response.should have_text(/Third hello/)
end
it "should treat attachments with unknown extensions as binary" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-attachment-unknown-extension.email', ir.incoming_email)
ir.reload
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.qwglhm'], :skip_cache => 1
response.content_type.should == "application/octet-stream"
response.should have_text(/an unusual sort of file/)
end
it "should not download attachments with wrong file name" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
lambda {
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2,
:file_name => ['http://trying.to.hack']
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should censor attachments downloaded as binary" do
ir = info_requests(:fancy_dog_request)
censor_rule = CensorRule.new()
censor_rule.text = "Second"
censor_rule.replacement = "Mouse"
censor_rule.last_edit_editor = "unknown"
censor_rule.last_edit_comment = "none"
ir.censor_rules << censor_rule
begin
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1
response.content_type.should == "text/plain"
response.should have_text(/xxxxxx hello/)
ensure
ir.censor_rules.clear
end
end
it "should censor with rules on the user (rather than the request)" do
ir = info_requests(:fancy_dog_request)
censor_rule = CensorRule.new()
censor_rule.text = "Second"
censor_rule.replacement = "Mouse"
censor_rule.last_edit_editor = "unknown"
censor_rule.last_edit_comment = "none"
ir.user.censor_rules << censor_rule
begin
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
ir.reload
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id, :id => ir.id, :part => 2, :file_name => ['hello.txt'], :skip_cache => 1
response.content_type.should == "text/plain"
response.should have_text(/xxxxxx hello/)
ensure
ir.user.censor_rules.clear
end
end
it "should censor attachment names" do
ir = info_requests(:fancy_dog_request)
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
# XXX this is horrid, but don't know a better way. If we
# don't do this, the info_request_event to which the
# info_request is attached still uses the unmodified
# version from the fixture.
#event = info_request_events(:useless_incoming_message_event)
ir.reload
assert ir.info_request_events[3].incoming_message.get_attachments_for_display.count == 2
ir.save!
ir.incoming_messages.last.save!
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
assert assigns[:info_request].info_request_events[3].incoming_message.get_attachments_for_display.count == 2
# the issue is that the info_request_events have got cached on them the old info_requests.
# where i'm at: trying to replace those fields that got re-read from the raw email. however tests are failing in very strange ways. currently I don't appear to be getting any attachments parsed in at all when in the template (see "*****" in _correspondence.rhtml) but do when I'm in the code.
# so at this point, assigns[:info_request].incoming_messages[1].get_attachments_for_display is returning stuff, but the equivalent thing in the template isn't.
# but something odd is that the above is return a whole load of attachments which aren't there in the controller
response.body.should have_tag("p.attachment strong", /hello.txt/m)
censor_rule = CensorRule.new()
censor_rule.text = "hello.txt"
censor_rule.replacement = "goodbye.txt"
censor_rule.last_edit_editor = "unknown"
censor_rule.last_edit_comment = "none"
ir.censor_rules << censor_rule
begin
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.body.should have_tag("p.attachment strong", /goodbye.txt/m)
ensure
ir.censor_rules.clear
end
end
describe 'when making a zipfile available' do
it "should have a different zipfile URL when the request changes" do
title = 'why_do_you_have_such_a_fancy_dog'
ir = info_requests(:fancy_dog_request)
session[:user_id] = ir.user.id # bob_smith_user
get :download_entire_request, :url_title => title
assigns[:url_path].should have_text(/#{title}.zip$/)
old_path = assigns[:url_path]
response.location.should have_text(/#{assigns[:url_path]}$/)
zipfile = Zip::ZipFile.open(File.join(File.dirname(__FILE__), "../../cache/zips", old_path)) { |zipfile|
zipfile.count.should == 1 # just the message
}
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
get :download_entire_request, :url_title => title
assigns[:url_path].should have_text(/#{title}.zip$/)
old_path = assigns[:url_path]
response.location.should have_text(/#{assigns[:url_path]}$/)
zipfile = Zip::ZipFile.open(File.join(File.dirname(__FILE__), "../../cache/zips", old_path)) { |zipfile|
zipfile.count.should == 3 # the message plus two "hello.txt" files
}
# The path of the zip file is based on the hash of the timestamp of the last request
# in the thread, so we wait for a second to make sure this one will have a different
# timestamp than the previous.
sleep 1
receive_incoming_mail('incoming-request-attachment-unknown-extension.email', ir.incoming_email)
get :download_entire_request, :url_title => title
assigns[:url_path].should have_text(/#{title}.zip$/)
assigns[:url_path].should_not == old_path
response.location.should have_text(/#{assigns[:url_path]}/)
zipfile = Zip::ZipFile.open(File.join(File.dirname(__FILE__), "../../cache/zips", assigns[:url_path])) { |zipfile|
zipfile.count.should == 4 # the message, two hello.txt plus the unknown attachment
}
end
it 'should successfully make a zipfile for an external request' do
info_request = info_requests(:external_request)
get :download_entire_request, { :url_title => info_request.url_title },
{ :user_id => users(:bob_smith_user) }
response.location.should have_text(/#{assigns[:url_path]}/)
end
end
end
end
describe RequestController, "when changing prominence of a request" do
before(:each) do
load_raw_emails_data
end
it "should not show hidden requests" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('hidden')
end
it "should not show hidden requests even if logged in as their owner" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
session[:user_id] = ir.user.id # bob_smith_user
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('hidden')
end
it "should show hidden requests if logged in as super user" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
session[:user_id] = users(:admin_user)
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('show')
end
it "should not show requester_only requests if you're not logged in" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'requester_only'
ir.save!
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('hidden')
end
it "should show requester_only requests to requester and admin if logged in" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'requester_only'
ir.save!
session[:user_id] = users(:silly_name_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('hidden')
session[:user_id] = ir.user.id # bob_smith_user
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('show')
session[:user_id] = users(:admin_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('show')
end
it 'should not cache an attachment on a request whose prominence is requester_only when showing
the request to the requester or admin' do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'requester_only'
ir.save!
session[:user_id] = ir.user.id # bob_smith_user
@controller.should_not_receive(:foi_fragment_cache_write)
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
end
it "should not download attachments if hidden" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id,
:id => ir.id,
:part => 2,
:skip_cache => 1
response.content_type.should == "text/html"
response.should_not have_text(/Second hello/)
response.should render_template('request/hidden')
get :get_attachment, :incoming_message_id => ir.incoming_messages[1].id,
:id => ir.id,
:part => 3,
:skip_cache => 1
response.content_type.should == "text/html"
response.should_not have_text(/First hello/)
response.should render_template('request/hidden')
response.code.should == '410'
end
it 'should not generate an HTML version of an attachment whose prominence is hidden/requester
only even for the requester or an admin but should return a 404' do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
receive_incoming_mail('incoming-request-two-same-name.email', ir.incoming_email)
session[:user_id] = users(:admin_user).id
lambda do
get :get_attachment_as_html, :incoming_message_id => ir.incoming_messages[1].id,
:id => ir.id,
:part => 2,
:file_name => ['hello.txt']
end.should raise_error(ActiveRecord::RecordNotFound)
end
end
# XXX do this for invalid ids
# it "should render 404 file" do
# response.should render_template("#{Rails.root}/public/404.html")
# response.headers["Status"].should == "404 Not Found"
# end
describe RequestController, "when searching for an authority" do
# Whether or not sign-in is required for this step is configurable,
# so we make sure we're logged in, just in case
before do
@user = users(:bob_smith_user)
end
it "should return nothing for the empty query string" do
session[:user_id] = @user.id
get :select_authority, :query => ""
response.should render_template('select_authority')
assigns[:xapian_requests].should == nil
end
it "should return matching bodies" do
session[:user_id] = @user.id
get :select_authority, :query => "Quango"
response.should render_template('select_authority')
assigns[:xapian_requests].results.size == 1
assigns[:xapian_requests].results[0][:model].name.should == public_bodies(:geraldine_public_body).name
end
it "should not give an error when user users unintended search operators" do
for phrase in ["Marketing/PR activities - Aldborough E-Act Free Schoo",
"Request for communications between DCMS/Ed Vaizey and ICO from Jan 1st 2011 - May ",
"Bellevue Road Ryde Isle of Wight PO33 2AR - what is the",
"NHS Ayrshire & Arran",
" cardiff",
"Foo * bax",
"qux ~ quux"]
lambda {
get :select_authority, :query => phrase
}.should_not raise_error(StandardError)
end
end
end
describe RequestController, "when creating a new request" do
integrate_views
before do
@user = users(:bob_smith_user)
@body = public_bodies(:geraldine_public_body)
end
it "should redirect to front page if no public body specified" do
get :new
response.should redirect_to(:controller => 'general', :action => 'frontpage')
end
it "should redirect to front page if no public body specified, when logged in" do
session[:user_id] = @user.id
get :new
response.should redirect_to(:controller => 'general', :action => 'frontpage')
end
it "should redirect 'bad request' page when a body has no email address" do
@body.request_email = ""
@body.save!
get :new, :public_body_id => @body.id
response.should render_template('new_bad_contact')
end
it "should accept a public body parameter" do
get :new, :public_body_id => @body.id
assigns[:info_request].public_body.should == @body
response.should render_template('new')
end
it "should give an error and render 'new' template when a summary isn't given" do
post :new, :info_request => { :public_body_id => @body.id },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 1
assigns[:info_request].errors[:title].should_not be_nil
response.should render_template('new')
end
it "should redirect to sign in page when input is good and nobody is logged in" do
params = { :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 0
}
post :new, params
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
# post_redirect.post_params.should == params # XXX get this working. there's a : vs '' problem amongst others
end
it "should show preview when input is good" do
session[:user_id] = @user.id
post :new, { :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 1
}
response.should render_template('preview')
end
it "should allow re-editing of a request" do
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 0,
:reedit => "Re-edit this request"
response.should render_template('new')
end
it "should create the request and outgoing message, and send the outgoing message by email, and redirect to request page when input is good and somebody is logged in" do
session[:user_id] = @user.id
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 0
ir_array = InfoRequest.find(:all, :conditions => ["title = ?", "Why is your quango called Geraldine?"])
ir_array.size.should == 1
ir = ir_array[0]
ir.outgoing_messages.size.should == 1
om = ir.outgoing_messages[0]
om.body.should == "This is a silly letter. It is too short to be interesting."
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /This is a silly letter. It is too short to be interesting./
response.should redirect_to(:action => 'show', :url_title => ir.url_title)
# This test uses an explicit path because it's relied in
# Google Analytics goals:
response.redirected_to.should =~ /request\/why_is_your_quango_called_gerald\/new$/
end
it "should give an error if the same request is submitted twice" do
session[:user_id] = @user.id
# We use raw_body here, so white space is the same
post :new, :info_request => { :public_body_id => info_requests(:fancy_dog_request).public_body_id,
:title => info_requests(:fancy_dog_request).title },
:outgoing_message => { :body => info_requests(:fancy_dog_request).outgoing_messages[0].raw_body},
:submitted_new_request => 1, :preview => 0, :mouse_house => 1
response.should render_template('new')
end
it "should let you submit another request with the same title" do
session[:user_id] = @user.id
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a silly letter. It is too short to be interesting." },
:submitted_new_request => 1, :preview => 0
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why is your quango called Geraldine?", :tag_string => "" },
:outgoing_message => { :body => "This is a sensible letter. It is too long to be boring." },
:submitted_new_request => 1, :preview => 0
ir_array = InfoRequest.find(:all, :conditions => ["title = ?", "Why is your quango called Geraldine?"], :order => "id")
ir_array.size.should == 2
ir = ir_array[0]
ir2 = ir_array[1]
ir.url_title.should_not == ir2.url_title
response.should redirect_to(:action => 'show', :url_title => ir2.url_title)
end
it 'should respect the rate limit' do
# Try to create three requests in succession.
# (The limit set in config/test.yml is two.)
session[:user_id] = users(:robin_user)
post :new, :info_request => { :public_body_id => @body.id,
:title => "What is the answer to the ultimate question?", :tag_string => "" },
:outgoing_message => { :body => "Please supply the answer from your files." },
:submitted_new_request => 1, :preview => 0
response.should redirect_to(:action => 'show', :url_title => 'what_is_the_answer_to_the_ultima')
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why did the chicken cross the road?", :tag_string => "" },
:outgoing_message => { :body => "Please send me all the relevant documents you hold." },
:submitted_new_request => 1, :preview => 0
response.should redirect_to(:action => 'show', :url_title => 'why_did_the_chicken_cross_the_ro')
post :new, :info_request => { :public_body_id => @body.id,
:title => "What's black and white and red all over?", :tag_string => "" },
:outgoing_message => { :body => "Please send all minutes of meetings and email records that address this question." },
:submitted_new_request => 1, :preview => 0
response.should render_template('user/rate_limited')
end
it 'should ignore the rate limit for specified users' do
# Try to create three requests in succession.
# (The limit set in config/test.yml is two.)
session[:user_id] = users(:robin_user)
users(:robin_user).no_limit = true
users(:robin_user).save!
post :new, :info_request => { :public_body_id => @body.id,
:title => "What is the answer to the ultimate question?", :tag_string => "" },
:outgoing_message => { :body => "Please supply the answer from your files." },
:submitted_new_request => 1, :preview => 0
response.should redirect_to(:action => 'show', :url_title => 'what_is_the_answer_to_the_ultima')
post :new, :info_request => { :public_body_id => @body.id,
:title => "Why did the chicken cross the road?", :tag_string => "" },
:outgoing_message => { :body => "Please send me all the relevant documents you hold." },
:submitted_new_request => 1, :preview => 0
response.should redirect_to(:action => 'show', :url_title => 'why_did_the_chicken_cross_the_ro')
post :new, :info_request => { :public_body_id => @body.id,
:title => "What's black and white and red all over?", :tag_string => "" },
:outgoing_message => { :body => "Please send all minutes of meetings and email records that address this question." },
:submitted_new_request => 1, :preview => 0
response.should redirect_to(:action => 'show', :url_title => 'whats_black_and_white_and_red_al')
end
end
# These go with the previous set, but use mocks instead of fixtures.
# TODO harmonise these
describe RequestController, "when making a new request" do
before do
@user = mock_model(User, :id => 3481, :name => 'Testy')
@user.stub!(:get_undescribed_requests).and_return([])
@user.stub!(:can_leave_requests_undescribed?).and_return(false)
@user.stub!(:can_file_requests?).and_return(true)
@user.stub!(:locale).and_return("en")
User.stub!(:find).and_return(@user)
@body = mock_model(PublicBody, :id => 314, :eir_only? => false, :is_requestable? => true, :name => "Test Quango")
PublicBody.stub!(:find).and_return(@body)
end
it "should allow you to have one undescribed request" do
@user.stub!(:get_undescribed_requests).and_return([ 1 ])
@user.stub!(:can_leave_requests_undescribed?).and_return(false)
session[:user_id] = @user.id
get :new, :public_body_id => @body.id
response.should render_template('new')
end
it "should fail if more than one request undescribed" do
@user.stub!(:get_undescribed_requests).and_return([ 1, 2 ])
@user.stub!(:can_leave_requests_undescribed?).and_return(false)
session[:user_id] = @user.id
get :new, :public_body_id => @body.id
response.should render_template('new_please_describe')
end
it "should allow you if more than one request undescribed but are allowed to leave requests undescribed" do
@user.stub!(:get_undescribed_requests).and_return([ 1, 2 ])
@user.stub!(:can_leave_requests_undescribed?).and_return(true)
session[:user_id] = @user.id
get :new, :public_body_id => @body.id
response.should render_template('new')
end
it "should fail if user is banned" do
@user.stub!(:can_file_requests?).and_return(false)
@user.stub!(:exceeded_limit?).and_return(false)
@user.should_receive(:can_fail_html).and_return('FAIL!')
session[:user_id] = @user.id
get :new, :public_body_id => @body.id
response.should render_template('user/banned')
end
end
describe RequestController, "when viewing an individual response for reply/followup" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should ask for login if you are logged in as wrong person" do
session[:user_id] = users(:silly_name_user).id
get :show_response, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message)
response.should render_template('user/wrong_user')
end
it "should show the response if you are logged in as right person" do
session[:user_id] = users(:bob_smith_user).id
get :show_response, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message)
response.should render_template('show_response')
end
it "should offer the opportunity to reply to the main address" do
session[:user_id] = users(:bob_smith_user).id
get :show_response, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message)
response.body.should have_tag("div#other_recipients ul li", /the main FOI contact address for/)
end
it "should offer an opportunity to reply to another address" do
session[:user_id] = users(:bob_smith_user).id
ir = info_requests(:fancy_dog_request)
ir.allow_new_responses_from = "anybody"
ir.save!
receive_incoming_mail('incoming-request-plain.email', ir.incoming_email, "Frob <frob@bonce.com>")
get :show_response, :id => ir.id, :incoming_message_id => incoming_messages(:useless_incoming_message)
response.body.should have_tag("div#other_recipients ul li", /Frob/)
end
it "should not show individual responses if request hidden, even if request owner" do
ir = info_requests(:fancy_dog_request)
ir.prominence = 'hidden'
ir.save!
session[:user_id] = users(:bob_smith_user).id
get :show_response, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message)
response.should render_template('request/hidden')
end
describe 'when viewing a response for an external request' do
it 'should show a message saying that external requests cannot be followed up' do
get :show_response, :id => info_requests(:external_request).id
response.should render_template('request/followup_bad')
assigns[:reason].should == 'external'
end
it 'should be successful' do
get :show_response, :id => info_requests(:external_request).id
response.should be_success
end
end
end
describe RequestController, "when classifying an information request" do
describe 'if the request is external' do
before do
@external_request = info_requests(:external_request)
end
it 'should redirect to the request page' do
post :describe_state, :id => @external_request.id,
:submitted_describe_state => 1
response.should redirect_to(:action => 'show',
:controller => 'request',
:url_title => @external_request.url_title)
end
end
describe 'when the request is internal' do
before(:each) do
@dog_request = info_requests(:fancy_dog_request)
@dog_request.stub!(:is_old_unclassified?).and_return(false)
InfoRequest.stub!(:find).and_return(@dog_request)
load_raw_emails_data
end
def post_status(status)
post :describe_state, :incoming_message => { :described_state => status },
:id => @dog_request.id,
:last_info_request_event_id => @dog_request.last_event_id_needing_description,
:submitted_describe_state => 1
end
it "should require login" do
post_status('rejected')
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
end
it 'should ask whether the request is old and unclassified' do
@dog_request.should_receive(:is_old_unclassified?)
post_status('rejected')
end
it "should not classify the request if logged in as the wrong user" do
session[:user_id] = users(:silly_name_user).id
post_status('rejected')
response.should render_template('user/wrong_user')
end
describe 'when the request is old and unclassified' do
before do
@dog_request.stub!(:is_old_unclassified?).and_return(true)
RequestMailer.stub!(:deliver_old_unclassified_updated)
end
describe 'when the user is not logged in' do
it 'should require login' do
session[:user_id] = nil
post_status('rejected')
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
end
end
describe 'when the user is logged in as a different user' do
before do
@other_user = mock_model(User)
session[:user_id] = users(:silly_name_user).id
end
it 'should classify the request' do
@dog_request.stub!(:calculate_status).and_return('rejected')
@dog_request.should_receive(:set_described_state).with('rejected')
post_status('rejected')
end
it 'should log a status update event' do
expected_params = {:user_id => users(:silly_name_user).id,
:old_described_state => 'waiting_response',
:described_state => 'rejected'}
event = mock_model(InfoRequestEvent)
@dog_request.should_receive(:log_event).with("status_update", expected_params).and_return(event)
post_status('rejected')
end
it 'should send an email to the requester letting them know someone has updated the status of their request' do
RequestMailer.should_receive(:deliver_old_unclassified_updated)
post_status('rejected')
end
it 'should redirect to the request page' do
post_status('rejected')
response.should redirect_to(:action => 'show', :controller => 'request', :url_title => @dog_request.url_title)
end
it 'should show a message thanking the user for a good deed' do
post_status('rejected')
flash[:notice].should == 'Thank you for updating this request!'
end
end
end
describe 'when logged in as an admin user who is not the actual requester' do
before do
@admin_user = users(:admin_user)
session[:user_id] = @admin_user.id
@dog_request = info_requests(:fancy_dog_request)
InfoRequest.stub!(:find).and_return(@dog_request)
@dog_request.stub!(:each).and_return([@dog_request])
end
it 'should update the status of the request' do
@dog_request.stub!(:calculate_status).and_return('rejected')
@dog_request.should_receive(:set_described_state).with('rejected')
post_status('rejected')
end
it 'should log a status update event' do
event = mock_model(InfoRequestEvent)
expected_params = {:user_id => @admin_user.id,
:old_described_state => 'waiting_response',
:described_state => 'rejected'}
@dog_request.should_receive(:log_event).with("status_update", expected_params).and_return(event)
post_status('rejected')
end
it 'should record a classification' do
event = mock_model(InfoRequestEvent)
@dog_request.stub!(:log_event).with("status_update", anything()).and_return(event)
RequestClassification.should_receive(:create!).with(:user_id => @admin_user.id,
:info_request_event_id => event.id)
post_status('rejected')
end
it 'should send an email to the requester letting them know someone has updated the status of their request' do
RequestMailer.should_receive(:deliver_old_unclassified_updated)
post_status('rejected')
end
it 'should redirect to the request page' do
post_status('rejected')
response.should redirect_to(:action => 'show', :controller => 'request', :url_title => @dog_request.url_title)
end
it 'should show a message thanking the user for a good deed' do
post_status('rejected')
flash[:notice].should == 'Thank you for updating this request!'
end
end
describe 'when logged in as an admin user who is also the actual requester' do
before do
@admin_user = users(:admin_user)
session[:user_id] = @admin_user.id
@dog_request = info_requests(:fancy_dog_request)
@dog_request.user = @admin_user
@dog_request.save!
InfoRequest.stub!(:find).and_return(@dog_request)
@dog_request.stub!(:each).and_return([@dog_request])
end
it 'should update the status of the request' do
@dog_request.stub!(:calculate_status).and_return('rejected')
@dog_request.should_receive(:set_described_state).with('rejected')
post_status('rejected')
end
it 'should not log a status update event' do
@dog_request.should_not_receive(:log_event)
post_status('rejected')
end
it 'should not send an email to the requester letting them know someone has updated the status of their request' do
RequestMailer.should_not_receive(:deliver_old_unclassified_updated)
post_status('rejected')
end
it 'should say it is showing advice as to what to do next' do
post_status('rejected')
flash[:notice].should match(/Here is what to do now/)
end
it 'should redirect to the unhappy page' do
post_status('rejected')
response.should redirect_to(:controller => 'help', :action => 'unhappy', :url_title => @dog_request.url_title)
end
end
describe 'when logged in as the requestor' do
before do
@request_owner = users(:bob_smith_user)
session[:user_id] = @request_owner.id
@dog_request.awaiting_description.should == true
@dog_request.stub!(:each).and_return([@dog_request])
end
it "should successfully classify response if logged in as user controlling request" do
post_status('rejected')
response.should redirect_to(:controller => 'help', :action => 'unhappy', :url_title => @dog_request.url_title)
@dog_request.reload
@dog_request.awaiting_description.should == false
@dog_request.described_state.should == 'rejected'
@dog_request.get_last_response_event.should == info_request_events(:useless_incoming_message_event)
@dog_request.get_last_response_event.calculated_state.should == 'rejected'
end
it 'should not log a status update event' do
@dog_request.should_not_receive(:log_event)
post_status('rejected')
end
it 'should not send an email to the requester letting them know someone has updated the status of their request' do
RequestMailer.should_not_receive(:deliver_old_unclassified_updated)
post_status('rejected')
end
it "should send email when classified as requires_admin" do
post :describe_state, :incoming_message => { :described_state => "requires_admin" }, :id => @dog_request.id, :incoming_message_id => incoming_messages(:useless_incoming_message), :last_info_request_event_id => @dog_request.last_event_id_needing_description, :submitted_describe_state => 1
response.should redirect_to(:controller => 'help', :action => 'contact')
@dog_request.reload
@dog_request.awaiting_description.should == false
@dog_request.described_state.should == 'requires_admin'
@dog_request.get_last_response_event.calculated_state.should == 'requires_admin'
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /as needing admin/
mail.from_addrs.first.to_s.should == @request_owner.name_and_email
end
it 'should say it is showing advice as to what to do next' do
post_status('rejected')
flash[:notice].should match(/Here is what to do now/)
end
it 'should redirect to the unhappy page' do
post_status('rejected')
response.should redirect_to(:controller => 'help', :action => 'unhappy', :url_title => @dog_request.url_title)
end
it "knows about extended states" do
InfoRequest.send(:require, File.expand_path(File.join(File.dirname(__FILE__), '..', 'models', 'customstates')))
InfoRequest.send(:include, InfoRequestCustomStates)
InfoRequest.class_eval('@@custom_states_loaded = true')
RequestController.send(:require, File.expand_path(File.join(File.dirname(__FILE__), '..', 'models', 'customstates')))
RequestController.send(:include, RequestControllerCustomStates)
RequestController.class_eval('@@custom_states_loaded = true')
Time.stub!(:now).and_return(Time.utc(2007, 11, 10, 00, 01))
post_status('deadline_extended')
flash[:notice].should == 'Authority has requested extension of the deadline.'
end
end
describe 'when redirecting after a successful status update by the request owner' do
before do
@request_owner = users(:bob_smith_user)
session[:user_id] = @request_owner.id
@dog_request = info_requests(:fancy_dog_request)
@dog_request.stub!(:each).and_return([@dog_request])
InfoRequest.stub!(:find).and_return(@dog_request)
@old_filters = ActionController::Routing::Routes.filters
ActionController::Routing::Routes.filters = RoutingFilter::Chain.new
end
after do
ActionController::Routing::Routes.filters = @old_filters
end
def request_url
"request/#{@dog_request.url_title}"
end
def unhappy_url
"help/unhappy/#{@dog_request.url_title}"
end
def expect_redirect(status, redirect_path)
post_status(status)
response.should redirect_to("http://test.host/#{redirect_path}")
end
it 'should redirect to the "request url" with a message in the right tense when status is updated to "waiting response" and the response is not overdue' do
@dog_request.stub!(:date_response_required_by).and_return(Time.now.to_date+1)
@dog_request.stub!(:date_very_overdue_after).and_return(Time.now.to_date+40)
expect_redirect("waiting_response", "request/#{@dog_request.url_title}")
flash[:notice].should match(/should get a response/)
end
it 'should redirect to the "request url" with a message in the right tense when status is updated to "waiting response" and the response is overdue' do
@dog_request.stub!(:date_response_required_by).and_return(Time.now.to_date-1)
@dog_request.stub!(:date_very_overdue_after).and_return(Time.now.to_date+40)
expect_redirect('waiting_response', request_url)
flash[:notice].should match(/should have got a response/)
end
it 'should redirect to the "request url" with a message in the right tense when status is updated to "waiting response" and the response is overdue' do
@dog_request.stub!(:date_response_required_by).and_return(Time.now.to_date-2)
@dog_request.stub!(:date_very_overdue_after).and_return(Time.now.to_date-1)
expect_redirect('waiting_response', unhappy_url)
flash[:notice].should match(/is long overdue/)
flash[:notice].should match(/by more than 40 working days/)
flash[:notice].should match(/within 20 working days/)
end
it 'should redirect to the "request url" when status is updated to "not held"' do
expect_redirect('not_held', request_url)
end
it 'should redirect to the "request url" when status is updated to "successful"' do
expect_redirect('successful', request_url)
end
it 'should redirect to the "unhappy url" when status is updated to "rejected"' do
expect_redirect('rejected', "help/unhappy/#{@dog_request.url_title}")
end
it 'should redirect to the "unhappy url" when status is updated to "partially successful"' do
expect_redirect('partially_successful', "help/unhappy/#{@dog_request.url_title}")
end
it 'should redirect to the "response url" when status is updated to "waiting clarification" and there is a last response' do
incoming_message = mock_model(IncomingMessage)
@dog_request.stub!(:get_last_response).and_return(incoming_message)
expect_redirect('waiting_clarification', "request/#{@dog_request.id}/response/#{incoming_message.id}")
end
it 'should redirect to the "response no followup url" when status is updated to "waiting clarification" and there are no events needing description' do
@dog_request.stub!(:get_last_response).and_return(nil)
expect_redirect('waiting_clarification', "request/#{@dog_request.id}/response")
end
it 'should redirect to the "respond to last url" when status is updated to "gone postal"' do
expect_redirect('gone_postal', "request/#{@dog_request.id}/response/#{@dog_request.get_last_response.id}?gone_postal=1")
end
it 'should redirect to the "request url" when status is updated to "internal review"' do
expect_redirect('internal_review', request_url)
end
it 'should redirect to the "help general url" when status is updated to "requires admin"' do
expect_redirect('requires_admin', "help/contact")
end
it 'should redirect to the "help general url" when status is updated to "error message"' do
expect_redirect('error_message', "help/contact")
end
it 'should redirect to the "respond to last url url" when status is updated to "user_withdrawn"' do
expect_redirect('user_withdrawn', "request/#{@dog_request.id}/response/#{@dog_request.get_last_response.id}")
end
end
end
end
describe RequestController, "when sending a followup message" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should require login" do
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort' }, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
end
it "should not let you if you are logged in as the wrong user" do
session[:user_id] = users(:silly_name_user).id
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort' }, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
response.should render_template('user/wrong_user')
end
it "should give an error and render 'show_response' template when a body isn't given" do
session[:user_id] = users(:bob_smith_user).id
post :show_response, :outgoing_message => { :body => "", :what_doing => 'normal_sort'}, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
# XXX how do I check the error message here?
response.should render_template('show_response')
end
it "should show preview when input is good" do
session[:user_id] = users(:bob_smith_user).id
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort'}, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1, :preview => 1
response.should render_template('followup_preview')
end
it "should allow re-editing of a preview" do
session[:user_id] = users(:bob_smith_user).id
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort'}, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1, :preview => 0, :reedit => "Re-edit this request"
response.should render_template('show_response')
end
it "should send the follow up message if you are the right user" do
# fake that this is a clarification
info_requests(:fancy_dog_request).set_described_state('waiting_clarification')
info_requests(:fancy_dog_request).described_state.should == 'waiting_clarification'
info_requests(:fancy_dog_request).get_last_response_event.calculated_state.should == 'waiting_clarification'
# make the followup
session[:user_id] = users(:bob_smith_user).id
post :show_response, :outgoing_message => { :body => "What a useless response! You suck.", :what_doing => 'normal_sort' }, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
# check it worked
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /What a useless response! You suck./
mail.to_addrs.first.to_s.should == "FOI Person <foiperson@localhost>"
response.should redirect_to(:action => 'show', :url_title => info_requests(:fancy_dog_request).url_title)
# and that the status changed
info_requests(:fancy_dog_request).reload
info_requests(:fancy_dog_request).described_state.should == 'waiting_response'
info_requests(:fancy_dog_request).get_last_response_event.calculated_state.should == 'waiting_clarification'
end
it "should give an error if the same followup is submitted twice" do
session[:user_id] = users(:bob_smith_user).id
# make the followup once
post :show_response, :outgoing_message => { :body => "Stop repeating yourself!", :what_doing => 'normal_sort' }, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
response.should redirect_to(:action => 'show', :url_title => info_requests(:fancy_dog_request).url_title)
# second time should give an error
post :show_response, :outgoing_message => { :body => "Stop repeating yourself!", :what_doing => 'normal_sort' }, :id => info_requests(:fancy_dog_request).id, :incoming_message_id => incoming_messages(:useless_incoming_message), :submitted_followup => 1
# XXX how do I check the error message here?
response.should render_template('show_response')
end
end
# XXX Stuff after here should probably be in request_mailer_spec.rb - but then
# it can't check the URLs in the emails I don't think, ugh.
describe RequestController, "sending overdue request alerts" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should send an overdue alert mail to creators of overdue requests" do
chicken_request = info_requests(:naughty_chicken_request)
chicken_request.outgoing_messages[0].last_sent_at = Time.now() - 30.days
chicken_request.outgoing_messages[0].save!
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
mail = chicken_mails[0]
mail.body.should =~ /promptly, as normally/
mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.name_and_email
mail.body =~ /(http:\/\/.*\/c\/(.*))/
mail_url = $1
mail_token = $2
session[:user_id].should be_nil
controller.test_code_redirect_by_email_token(mail_token, self) # XXX hack to avoid having to call User controller for email link
session[:user_id].should == info_requests(:naughty_chicken_request).user.id
response.should render_template('show_response')
assigns[:info_request].should == info_requests(:naughty_chicken_request)
end
it "should include clause for schools when sending an overdue alert mail to creators of overdue requests" do
chicken_request = info_requests(:naughty_chicken_request)
chicken_request.outgoing_messages[0].last_sent_at = Time.now() - 30.days
chicken_request.outgoing_messages[0].save!
chicken_request.public_body.tag_string = "school"
chicken_request.public_body.save!
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
mail = chicken_mails[0]
mail.body.should =~ /promptly, as normally/
mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.name_and_email
end
it "should send not actually send the overdue alert if the user is banned but should
record it as sent" do
user = info_requests(:naughty_chicken_request).user
user.ban_text = 'Banned'
user.save!
UserInfoRequestSentAlert.find_all_by_user_id(user.id).count.should == 0
RequestMailer.alert_overdue_requests
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 0
UserInfoRequestSentAlert.find_all_by_user_id(user.id).count.should > 0
end
it "should send a very overdue alert mail to creators of very overdue requests" do
chicken_request = info_requests(:naughty_chicken_request)
chicken_request.outgoing_messages[0].last_sent_at = Time.now() - 60.days
chicken_request.outgoing_messages[0].save!
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
mail = chicken_mails[0]
mail.body.should =~ /required by law/
mail.to_addrs.first.to_s.should == info_requests(:naughty_chicken_request).user.name_and_email
mail.body =~ /(http:\/\/.*\/c\/(.*))/
mail_url = $1
mail_token = $2
session[:user_id].should be_nil
controller.test_code_redirect_by_email_token(mail_token, self) # XXX hack to avoid having to call User controller for email link
session[:user_id].should == info_requests(:naughty_chicken_request).user.id
response.should render_template('show_response')
assigns[:info_request].should == info_requests(:naughty_chicken_request)
end
it "should not resend alerts to people who've already received them" do
chicken_request = info_requests(:naughty_chicken_request)
chicken_request.outgoing_messages[0].last_sent_at = Time.now() - 60.days
chicken_request.outgoing_messages[0].save!
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
end
it 'should send alerts for requests where the last event forming the initial request is a followup
being sent following a request for clarification' do
chicken_request = info_requests(:naughty_chicken_request)
chicken_request.outgoing_messages[0].last_sent_at = Time.now() - 60.days
chicken_request.outgoing_messages[0].save!
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
# Request is waiting clarification
chicken_request.set_described_state('waiting_clarification')
# Followup message is sent
outgoing_message = OutgoingMessage.new(:status => 'ready',
:message_type => 'followup',
:info_request_id => chicken_request.id,
:body => 'Some text',
:what_doing => 'normal_sort')
outgoing_message.send_message
outgoing_message.save!
chicken_request = InfoRequest.find(chicken_request.id)
# Last event forming the request is now the followup
chicken_request.last_event_forming_initial_request.event_type.should == 'followup_sent'
# This isn't overdue, so no email
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 1
# Make the followup older
outgoing_message.last_sent_at = Time.now() - 60.days
outgoing_message.save!
# Now it should be alerted on
RequestMailer.alert_overdue_requests
chicken_mails = ActionMailer::Base.deliveries.select{|x| x.body =~ /chickens/}
chicken_mails.size.should == 2
end
end
describe RequestController, "sending unclassified new response reminder alerts" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should send an alert" do
RequestMailer.alert_new_response_reminders
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 3 # sufficiently late it sends reminders too
mail = deliveries[0]
mail.body.should =~ /To let everyone know/
mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email
mail.body =~ /(http:\/\/.*\/c\/(.*))/
mail_url = $1
mail_token = $2
session[:user_id].should be_nil
controller.test_code_redirect_by_email_token(mail_token, self) # XXX hack to avoid having to call User controller for email link
session[:user_id].should == info_requests(:fancy_dog_request).user.id
response.should render_template('show')
assigns[:info_request].should == info_requests(:fancy_dog_request)
# XXX should check anchor tag here :) that it goes to last new response
end
end
describe RequestController, "clarification required alerts" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should send an alert" do
ir = info_requests(:fancy_dog_request)
ir.set_described_state('waiting_clarification')
# this is pretty horrid, but will do :) need to make it waiting
# clarification more than 3 days ago for the alerts to go out.
ActiveRecord::Base.connection.update "update info_requests set updated_at = '" + (Time.now - 5.days).strftime("%Y-%m-%d %H:%M:%S") + "' where id = " + ir.id.to_s
ir.reload
RequestMailer.alert_not_clarified_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /asked you to explain/
mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email
mail.body =~ /(http:\/\/.*\/c\/(.*))/
mail_url = $1
mail_token = $2
session[:user_id].should be_nil
controller.test_code_redirect_by_email_token(mail_token, self) # XXX hack to avoid having to call User controller for email link
session[:user_id].should == info_requests(:fancy_dog_request).user.id
response.should render_template('show_response')
assigns[:info_request].should == info_requests(:fancy_dog_request)
end
it "should not send an alert if you are banned" do
ir = info_requests(:fancy_dog_request)
ir.set_described_state('waiting_clarification')
ir.user.ban_text = 'Banned'
ir.user.save!
# this is pretty horrid, but will do :) need to make it waiting
# clarification more than 3 days ago for the alerts to go out.
ActiveRecord::Base.connection.update "update info_requests set updated_at = '" + (Time.now - 5.days).strftime("%Y-%m-%d %H:%M:%S") + "' where id = " + ir.id.to_s
ir.reload
RequestMailer.alert_not_clarified_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 0
end
end
describe RequestController, "comment alerts" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should send an alert (once and once only)" do
# delete fixture comment and make new one, so is in last month (as
# alerts are only for comments in last month, see
# RequestMailer.alert_comment_on_request)
existing_comment = info_requests(:fancy_dog_request).comments[0]
existing_comment.info_request_events[0].destroy
existing_comment.destroy
new_comment = info_requests(:fancy_dog_request).add_comment('I really love making annotations.', users(:silly_name_user))
# send comment alert
RequestMailer.alert_comment_on_request
deliveries = ActionMailer::Base.deliveries
mail = deliveries[0]
mail.body.should =~ /has annotated your/
mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email
mail.body =~ /(http:\/\/.*)/
mail_url = $1
mail_url.should match("/request/why_do_you_have_such_a_fancy_dog#comment-#{new_comment.id}")
# check if we send again, no more go out
deliveries.clear
RequestMailer.alert_comment_on_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 0
end
it "should not send an alert when you comment on your own request" do
# delete fixture comment and make new one, so is in last month (as
# alerts are only for comments in last month, see
# RequestMailer.alert_comment_on_request)
existing_comment = info_requests(:fancy_dog_request).comments[0]
existing_comment.info_request_events[0].destroy
existing_comment.destroy
new_comment = info_requests(:fancy_dog_request).add_comment('I also love making annotations.', users(:bob_smith_user))
# try to send comment alert
RequestMailer.alert_comment_on_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 0
end
it 'should not send an alert for a comment on an external request' do
external_request = info_requests(:external_request)
external_request.add_comment("This external request is interesting", users(:silly_name_user))
# try to send comment alert
RequestMailer.alert_comment_on_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 0
end
it "should send an alert when there are two new comments" do
# add two comments - the second one sould be ignored, as is by the user who made the request.
# the new comment here, will cause the one in the fixture to be picked up as a new comment by alert_comment_on_request also.
new_comment = info_requests(:fancy_dog_request).add_comment('Not as daft as this one', users(:silly_name_user))
new_comment = info_requests(:fancy_dog_request).add_comment('Or this one!!!', users(:bob_smith_user))
RequestMailer.alert_comment_on_request
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.body.should =~ /There are 2 new annotations/
mail.to_addrs.first.to_s.should == info_requests(:fancy_dog_request).user.name_and_email
mail.body =~ /(http:\/\/.*)/
mail_url = $1
mail_url.should match("/request/why_do_you_have_such_a_fancy_dog#comment-#{comments(:silly_comment).id}")
end
end
describe RequestController, "when viewing comments" do
integrate_views
before(:each) do
load_raw_emails_data
end
it "should link to the user who submitted it" do
session[:user_id] = users(:bob_smith_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.body.should have_tag("div#comment-1 h2", /Silly.*left an annotation/m)
response.body.should_not have_tag("div#comment-1 h2", /You.*left an annotation/m)
end
it "should link to the user who submitted to it, even if it is you" do
session[:user_id] = users(:silly_name_user).id
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.body.should have_tag("div#comment-1 h2", /Silly.*left an annotation/m)
response.body.should_not have_tag("div#comment-1 h2", /You.*left an annotation/m)
end
end
describe RequestController, "authority uploads a response from the web interface" do
integrate_views
before(:each) do
# domain after the @ is used for authentication of FOI officers, so to test it
# we need a user which isn't at localhost.
@normal_user = User.new(:name => "Mr. Normal", :email => "normal-user@flourish.org",
:password => PostRedirect.generate_random_token)
@normal_user.save!
@foi_officer_user = User.new(:name => "The Geraldine Quango", :email => "geraldine-requests@localhost",
:password => PostRedirect.generate_random_token)
@foi_officer_user.save!
end
it "should require login to view the form to upload" do
@ir = info_requests(:fancy_dog_request)
@ir.public_body.is_foi_officer?(@normal_user).should == false
session[:user_id] = @normal_user.id
get :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('user/wrong_user')
end
it "should let you view upload form if you are an FOI officer" do
@ir = info_requests(:fancy_dog_request)
@ir.public_body.is_foi_officer?(@foi_officer_user).should == true
session[:user_id] = @foi_officer_user.id
get :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog'
response.should render_template('request/upload_response')
end
it "should prevent uploads if you are not a requester" do
@ir = info_requests(:fancy_dog_request)
incoming_before = @ir.incoming_messages.size
session[:user_id] = @normal_user.id
# post up a photo of the parrot
parrot_upload = fixture_file_upload('files/parrot.png','image/png')
post :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog',
:body => "Find attached a picture of a parrot",
:file_1 => parrot_upload,
:submitted_upload_response => 1
response.should render_template('user/wrong_user')
end
it "should prevent entirely blank uploads" do
session[:user_id] = @foi_officer_user.id
post :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog', :body => "", :submitted_upload_response => 1
response.should render_template('request/upload_response')
flash[:error].should match(/Please type a message/)
end
it 'should 404 for non existent requests' do
lambda{ post :upload_response, :url_title => 'i_dont_exist'}.should raise_error(ActiveRecord::RecordNotFound)
end
# How do I test a file upload in rails?
# http://stackoverflow.com/questions/1178587/how-do-i-test-a-file-upload-in-rails
it "should let the authority upload a file" do
@ir = info_requests(:fancy_dog_request)
incoming_before = @ir.incoming_messages.size
session[:user_id] = @foi_officer_user.id
# post up a photo of the parrot
parrot_upload = fixture_file_upload('files/parrot.png','image/png')
post :upload_response, :url_title => 'why_do_you_have_such_a_fancy_dog',
:body => "Find attached a picture of a parrot",
:file_1 => parrot_upload,
:submitted_upload_response => 1
response.should redirect_to(:action => 'show', :url_title => 'why_do_you_have_such_a_fancy_dog')
flash[:notice].should match(/Thank you for responding to this FOI request/)
# check there is a new attachment
incoming_after = @ir.incoming_messages.size
incoming_after.should == incoming_before + 1
# check new attachment looks vaguely OK
new_im = @ir.incoming_messages[-1]
new_im.mail.body.should match(/Find attached a picture of a parrot/)
attachments = new_im.get_attachments_for_display
attachments.size.should == 1
attachments[0].filename.should == "parrot.png"
attachments[0].display_size.should == "94K"
end
end
describe RequestController, "when showing JSON version for API" do
before(:each) do
load_raw_emails_data
end
it "should return data in JSON form" do
get :show, :url_title => 'why_do_you_have_such_a_fancy_dog', :format => 'json'
ir = JSON.parse(response.body)
ir.class.to_s.should == 'Hash'
ir['url_title'].should == 'why_do_you_have_such_a_fancy_dog'
ir['public_body']['url_name'].should == 'tgq'
ir['user']['url_name'].should == 'bob_smith'
end
end
describe RequestController, "when doing type ahead searches" do
integrate_views
it "should return nothing for the empty query string" do
get :search_typeahead, :q => ""
response.should render_template('request/_search_ahead.rhtml')
assigns[:xapian_requests].should be_nil
end
it "should return a request matching the given keyword, but not users with a matching description" do
get :search_typeahead, :q => "chicken"
response.should render_template('request/_search_ahead.rhtml')
assigns[:xapian_requests].results.size.should == 1
assigns[:xapian_requests].results[0][:model].title.should == info_requests(:naughty_chicken_request).title
end
it "should return all requests matching any of the given keywords" do
get :search_typeahead, :q => "money dog"
response.should render_template('request/_search_ahead.rhtml')
assigns[:xapian_requests].results.map{|x|x[:model].info_request}.should =~ [
info_requests(:fancy_dog_request),
info_requests(:naughty_chicken_request),
info_requests(:another_boring_request),
]
end
it "should not return matches for short words" do
get :search_typeahead, :q => "a"
response.should render_template('request/_search_ahead.rhtml')
assigns[:xapian_requests].should be_nil
end
it "should do partial matches for longer words" do
get :search_typeahead, :q => "chick"
response.should render_template('request/_search_ahead.rhtml')
assigns[:xapian_requests].results.size.should ==1
end
it "should not give an error when user users unintended search operators" do
for phrase in ["Marketing/PR activities - Aldborough E-Act Free Schoo",
"Request for communications between DCMS/Ed Vaizey and ICO from Jan 1st 2011 - May ",
"Bellevue Road Ryde Isle of Wight PO33 2AR - what is the",
"NHS Ayrshire & Arran",
"uda ( units of dent",
"frob * baz",
"bar ~ qux"]
lambda {
get :search_typeahead, :q => phrase
}.should_not raise_error(StandardError)
end
end
it "should return all requests matching any of the given keywords" do
get :search_typeahead, :q => "dog -chicken"
assigns[:xapian_requests].results.size.should == 1
end
end
describe RequestController, "when showing similar requests" do
integrate_views
it "should work" do
get :similar, :url_title => info_requests(:badger_request).url_title
response.should render_template("request/similar")
assigns[:info_request].should == info_requests(:badger_request)
end
it "should show similar requests" do
badger_request = info_requests(:badger_request)
get :similar, :url_title => badger_request.url_title
# Xapian seems to think *all* the requests are similar
assigns[:xapian_object].results.map{|x|x[:model].info_request}.should =~ InfoRequest.all.reject {|x| x == badger_request}
end
it "should 404 for non-existent paths" do
lambda {
get :similar, :url_title => "there_is_really_no_such_path_owNAFkHR"
}.should raise_error(ActiveRecord::RecordNotFound)
end
end
describe RequestController, "when reporting a request when not logged in" do
it "should only allow logged-in users to report requests" do
get :report_request, :url_title => info_requests(:badger_request).url_title
post_redirect = PostRedirect.get_last_post_redirect
response.should redirect_to(:controller => 'user', :action => 'signin', :token => post_redirect.token)
end
end
describe RequestController, "when reporting a request (logged in)" do
integrate_views
before do
@user = users(:robin_user)
session[:user_id] = @user.id
end
it "should 404 for non-existent requests" do
lambda {
post :report_request, :url_title => "hjksfdhjk_louytu_qqxxx"
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "should mark a request as having been reported" do
ir = info_requests(:badger_request)
title = ir.url_title
get :show, :url_title => title
assigns[:info_request].attention_requested.should == false
post :report_request, :url_title => title
response.should redirect_to(:action => :show, :url_title => title)
get :show, :url_title => title
response.should be_success
assigns[:info_request].attention_requested.should == true
assigns[:info_request].described_state.should == "attention_requested"
end
it "should not allow a request to be reported twice" do
title = info_requests(:badger_request).url_title
post :report_request, :url_title => title
response.should redirect_to(:action => :show, :url_title => title)
get :show, :url_title => title
response.should be_success
response.body.should include("has been reported")
post :report_request, :url_title => title
response.should redirect_to(:action => :show, :url_title => title)
get :show, :url_title => title
response.should be_success
response.body.should include("has already been reported")
end
it "should let users know a request has been reported" do
title = info_requests(:badger_request).url_title
get :show, :url_title => title
response.body.should include("Offensive?")
post :report_request, :url_title => title
response.should redirect_to(:action => :show, :url_title => title)
get :show, :url_title => title
response.body.should_not include("Offensive?")
response.body.should include("This request has been reported")
info_requests(:badger_request).set_described_state("successful")
get :show, :url_title => title
response.body.should_not include("This request has been reported")
response.body.should =~ (/the site administrators.*have not hidden it/)
end
it "should send an email from the reporter to admins" do
ir = info_requests(:badger_request)
title = ir.url_title
post :report_request, :url_title => title
deliveries = ActionMailer::Base.deliveries
deliveries.size.should == 1
mail = deliveries[0]
mail.subject.should =~ /attention_requested/
mail.from.should include(@user.email)
mail.body.should include(@user.name)
end
end
|
class Ratfor < Formula
desc "Rational Fortran"
homepage "http://www.dgate.org/ratfor/"
url "http://www.dgate.org/ratfor/tars/ratfor-1.02.tar.gz"
sha256 "daf2971df48c3b3908c6788c4c6b3cdfb4eaad21ec819eee70a060956736ea1c"
depends_on :fortran
def install
system "./configure", "--prefix=#{prefix}"
system "make", "check"
system "make", "install"
end
test do
(testpath/"test.r").write <<-EOS.undent
integer x,y
x=1; y=2
if(x == y)
write(6,600)
else if(x > y)
write(6,601)
else
write(6,602)
x=1
while(x < 10){
if(y != 2) break
if(y != 2) next
write(6,603)x
x=x+1
}
repeat
x=x-1
until(x == 0)
for(x=0; x < 10; x=x+1)
write(6,604)x
600 format('Wrong, x != y')
601 format('Also wrong, x < y')
602 format('Ok!')
603 format('x = ',i2)
604 format('x = ',i2)
end
EOS
system "#{bin}/ratfor", "-o", "test.f", testpath/"test.r"
ENV.fortran
system ENV.fc, "test.f", "-o", "test"
system "./test"
end
end
ratfor: add 1.02 bottle.
class Ratfor < Formula
desc "Rational Fortran"
homepage "http://www.dgate.org/ratfor/"
url "http://www.dgate.org/ratfor/tars/ratfor-1.02.tar.gz"
sha256 "daf2971df48c3b3908c6788c4c6b3cdfb4eaad21ec819eee70a060956736ea1c"
bottle do
cellar :any_skip_relocation
sha256 "6998ed33f7547a097ced8ce5407756c50145d21ece1c8cd3474e6c9eeefd89c7" => :el_capitan
sha256 "2d368db5719c280340140998d525279a5f5178c0acccdecc7281f38f3d07c563" => :yosemite
sha256 "0544b9e974932e28f090aad1c54dd0c6708ebf1d7a0d3657a150cdb4fdb0cf36" => :mavericks
end
depends_on :fortran
def install
system "./configure", "--prefix=#{prefix}"
system "make", "check"
system "make", "install"
end
test do
(testpath/"test.r").write <<-EOS.undent
integer x,y
x=1; y=2
if(x == y)
write(6,600)
else if(x > y)
write(6,601)
else
write(6,602)
x=1
while(x < 10){
if(y != 2) break
if(y != 2) next
write(6,603)x
x=x+1
}
repeat
x=x-1
until(x == 0)
for(x=0; x < 10; x=x+1)
write(6,604)x
600 format('Wrong, x != y')
601 format('Also wrong, x < y')
602 format('Ok!')
603 format('x = ',i2)
604 format('x = ',i2)
end
EOS
system "#{bin}/ratfor", "-o", "test.f", testpath/"test.r"
ENV.fortran
system ENV.fc, "test.f", "-o", "test"
system "./test"
end
end
|
require 'rails_helper'
RSpec.describe SamplesController, type: :controller do
create_users
# Non-admin, aka Joe, specific behavior
context "Joe" do
before do
sign_in @joe
end
describe "GET raw_results_folder (nonadmin)" do
it "can see raw results on the user's own samples" do
project = create(:project, users: [@joe])
sample = create(:sample, project: project, user: @joe)
get :raw_results_folder, params: { id: sample.id }
expect(response).to have_http_status :success
end
it "cannot see raw results on another user's sample" do
project = create(:project, users: [@joe])
sample = create(:sample, project: project)
get :raw_results_folder, params: { id: sample.id }
expect(response).to have_http_status :unauthorized
end
end
describe "GET results_folder (nonadmin)" do
it "can see raw results on the user's own samples" do
project = create(:project, users: [@joe])
sample = create(:sample, project: project, user: @joe)
get :results_folder, params: { id: sample.id }
expect(response).to have_http_status :success
end
it "can see raw results on the user's own samples with previous pipeline version" do
project = create(:project, users: [@joe])
sample_one = create(:sample, project: project, name: "Test Sample One", user: @joe,
pipeline_runs_data: [
{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.10" },
{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.12" },
])
expect_any_instance_of(Sample).to receive(:results_folder_files).with("3.10").exactly(1).times.and_return({})
get :results_folder, params: { id: sample_one.id, pipeline_version: "3.10" }
expect(response).to have_http_status :success
end
it "can see raw results on another user's sample (if part of that project)" do
project = create(:project, users: [@joe])
sample = create(:sample, project: project)
get :results_folder, params: { id: sample.id }
expect(response).to have_http_status :success
end
end
describe "GET #taxa_with_reads_suggestions" do
before do
@project = create(:project, users: [@joe])
@sample_one = create(:sample, project: @project, name: "Test Sample One",
pipeline_runs_data: [{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.12" }])
@sample_two = create(:sample, project: @project, name: "Test Sample Two",
pipeline_runs_data: [{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.12" }])
@sample_three = create(:sample, project: @project, name: "Test Sample Three",
pipeline_runs_data: [{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.12" }])
end
it "should return taxon list with correct sample counts" do
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_one.first_pipeline_run.id)
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_two.first_pipeline_run.id)
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_three.first_pipeline_run.id)
create(:taxon_count, tax_id: 200, pipeline_run_id: @sample_one.first_pipeline_run.id)
create(:taxon_count, tax_id: 200, pipeline_run_id: @sample_two.first_pipeline_run.id)
create(:taxon_count, tax_id: 300, pipeline_run_id: @sample_one.first_pipeline_run.id)
mock_query = "MOCK_QUERY"
expect(controller).to receive(:taxon_search).with(mock_query, ["species", "genus"], any_args).exactly(1).times
.and_return([
{
"taxid" => 100,
"name" => "Mock Taxa 100",
},
{
"taxid" => 200,
"name" => "Mock Taxa 200",
},
{
"taxid" => 300,
"name" => "Mock Taxa 300",
},
])
get :taxa_with_reads_suggestions, params: { format: "json", sampleIds: [@sample_one.id, @sample_two.id, @sample_three.id], query: mock_query }
expect(response).to have_http_status :success
json_response = JSON.parse(response.body)
expect(json_response).to include_json([
{
"taxid" => 100,
"name" => "Mock Taxa 100",
"sample_count" => 3,
},
{
"taxid" => 200,
"name" => "Mock Taxa 200",
"sample_count" => 2,
},
{
"taxid" => 300,
"name" => "Mock Taxa 300",
"sample_count" => 1,
},
])
end
it "should return unauthorized if user doesn't have access to sample" do
project_admin = create(:project, users: [@admin])
sample_admin = create(:sample, project: project_admin, name: "Test Sample Admin",
pipeline_runs_data: [{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.12" }])
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_one.first_pipeline_run.id)
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_two.first_pipeline_run.id)
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_three.first_pipeline_run.id)
get :taxa_with_reads_suggestions, params: { format: "json", sampleIds: [@sample_one.id, sample_admin.id], query: "MOCK_QUERY" }
expect(response).to have_http_status :unauthorized
end
end
end
describe "GET #uploaded_by_current_user" do
before do
@project = create(:project, users: [@joe, @admin])
@sample_one = create(:sample, project: @project, name: "Test Sample One", user: @joe)
@sample_two = create(:sample, project: @project, name: "Test Sample Two", user: @joe)
@sample_three = create(:sample, project: @project, name: "Test Sample Three", user: @admin)
sign_in @joe
end
it "should return true if all samples were uploaded by user" do
get :uploaded_by_current_user, params: { sampleIds: [@sample_one.id, @sample_two.id] }
json_response = JSON.parse(response.body)
expect(json_response).to include_json(uploaded_by_current_user: true)
end
it "should return false if some samples were not uploaded by user, even if user belongs to the sample's project" do
get :uploaded_by_current_user, params: { sampleIds: [@sample_one.id, @sample_two.id, @sample_three.id] }
json_response = JSON.parse(response.body)
expect(json_response).to include_json(uploaded_by_current_user: false)
end
end
context "User with report_v2 flag" do
before do
sign_in @joe
@joe.add_allowed_feature("report_v2")
@project = create(:project, users: [@joe])
end
describe "GET show_v2" do
it "can see sample report_v2" do
sample = create(:sample, project: @project)
get :show_v2, params: { id: sample.id }
expect(response).to have_http_status :success
end
end
end
context "Admin without report_v2 flag" do
before do
sign_in @admin
@project = create(:project, users: [@admin])
end
describe "GET show_v2" do
it "redirected to home page" do
sample = create(:sample, project: @project)
get :show_v2, params: { id: sample.id }
expect(response).to redirect_to(root_path)
end
end
end
end
Fix typo that was introduced in a test. (#2755)
require 'rails_helper'
RSpec.describe SamplesController, type: :controller do
create_users
# Non-admin, aka Joe, specific behavior
context "Joe" do
before do
sign_in @joe
end
describe "GET raw_results_folder (nonadmin)" do
it "can see raw results on the user's own samples" do
project = create(:project, users: [@joe])
sample = create(:sample, project: project, user: @joe)
get :raw_results_folder, params: { id: sample.id }
expect(response).to have_http_status :success
end
it "cannot see raw results on another user's sample" do
project = create(:project, users: [@joe])
sample = create(:sample, project: project)
get :raw_results_folder, params: { id: sample.id }
expect(response).to have_http_status :unauthorized
end
end
describe "GET results_folder (nonadmin)" do
it "can see results on the user's own samples" do
project = create(:project, users: [@joe])
sample = create(:sample, project: project, user: @joe)
get :results_folder, params: { id: sample.id }
expect(response).to have_http_status :success
end
it "can see results on the user's own samples with previous pipeline version" do
project = create(:project, users: [@joe])
sample_one = create(:sample, project: project, name: "Test Sample One", user: @joe,
pipeline_runs_data: [
{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.10" },
{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.12" },
])
expect_any_instance_of(Sample).to receive(:results_folder_files).with("3.10").exactly(1).times.and_return({})
get :results_folder, params: { id: sample_one.id, pipeline_version: "3.10" }
expect(response).to have_http_status :success
end
it "can see results on another user's sample (if part of that project)" do
project = create(:project, users: [@joe])
sample = create(:sample, project: project)
get :results_folder, params: { id: sample.id }
expect(response).to have_http_status :success
end
end
describe "GET #taxa_with_reads_suggestions" do
before do
@project = create(:project, users: [@joe])
@sample_one = create(:sample, project: @project, name: "Test Sample One",
pipeline_runs_data: [{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.12" }])
@sample_two = create(:sample, project: @project, name: "Test Sample Two",
pipeline_runs_data: [{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.12" }])
@sample_three = create(:sample, project: @project, name: "Test Sample Three",
pipeline_runs_data: [{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.12" }])
end
it "should return taxon list with correct sample counts" do
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_one.first_pipeline_run.id)
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_two.first_pipeline_run.id)
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_three.first_pipeline_run.id)
create(:taxon_count, tax_id: 200, pipeline_run_id: @sample_one.first_pipeline_run.id)
create(:taxon_count, tax_id: 200, pipeline_run_id: @sample_two.first_pipeline_run.id)
create(:taxon_count, tax_id: 300, pipeline_run_id: @sample_one.first_pipeline_run.id)
mock_query = "MOCK_QUERY"
expect(controller).to receive(:taxon_search).with(mock_query, ["species", "genus"], any_args).exactly(1).times
.and_return([
{
"taxid" => 100,
"name" => "Mock Taxa 100",
},
{
"taxid" => 200,
"name" => "Mock Taxa 200",
},
{
"taxid" => 300,
"name" => "Mock Taxa 300",
},
])
get :taxa_with_reads_suggestions, params: { format: "json", sampleIds: [@sample_one.id, @sample_two.id, @sample_three.id], query: mock_query }
expect(response).to have_http_status :success
json_response = JSON.parse(response.body)
expect(json_response).to include_json([
{
"taxid" => 100,
"name" => "Mock Taxa 100",
"sample_count" => 3,
},
{
"taxid" => 200,
"name" => "Mock Taxa 200",
"sample_count" => 2,
},
{
"taxid" => 300,
"name" => "Mock Taxa 300",
"sample_count" => 1,
},
])
end
it "should return unauthorized if user doesn't have access to sample" do
project_admin = create(:project, users: [@admin])
sample_admin = create(:sample, project: project_admin, name: "Test Sample Admin",
pipeline_runs_data: [{ finalized: 1, job_status: PipelineRun::STATUS_CHECKED, pipeline_version: "3.12" }])
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_one.first_pipeline_run.id)
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_two.first_pipeline_run.id)
create(:taxon_count, tax_id: 100, pipeline_run_id: @sample_three.first_pipeline_run.id)
get :taxa_with_reads_suggestions, params: { format: "json", sampleIds: [@sample_one.id, sample_admin.id], query: "MOCK_QUERY" }
expect(response).to have_http_status :unauthorized
end
end
end
describe "GET #uploaded_by_current_user" do
before do
@project = create(:project, users: [@joe, @admin])
@sample_one = create(:sample, project: @project, name: "Test Sample One", user: @joe)
@sample_two = create(:sample, project: @project, name: "Test Sample Two", user: @joe)
@sample_three = create(:sample, project: @project, name: "Test Sample Three", user: @admin)
sign_in @joe
end
it "should return true if all samples were uploaded by user" do
get :uploaded_by_current_user, params: { sampleIds: [@sample_one.id, @sample_two.id] }
json_response = JSON.parse(response.body)
expect(json_response).to include_json(uploaded_by_current_user: true)
end
it "should return false if some samples were not uploaded by user, even if user belongs to the sample's project" do
get :uploaded_by_current_user, params: { sampleIds: [@sample_one.id, @sample_two.id, @sample_three.id] }
json_response = JSON.parse(response.body)
expect(json_response).to include_json(uploaded_by_current_user: false)
end
end
context "User with report_v2 flag" do
before do
sign_in @joe
@joe.add_allowed_feature("report_v2")
@project = create(:project, users: [@joe])
end
describe "GET show_v2" do
it "can see sample report_v2" do
sample = create(:sample, project: @project)
get :show_v2, params: { id: sample.id }
expect(response).to have_http_status :success
end
end
end
context "Admin without report_v2 flag" do
before do
sign_in @admin
@project = create(:project, users: [@admin])
end
describe "GET show_v2" do
it "redirected to home page" do
sample = create(:sample, project: @project)
get :show_v2, params: { id: sample.id }
expect(response).to redirect_to(root_path)
end
end
end
end
|
regldg: 1.0 - a regular expression grammar language dictionary generator
Closes #24452.
Signed-off-by: Adam Vandenberg <34c2b6407fd5a10249a15d699d40f9ed1782e98c@gmail.com>
require 'formula'
class Regldg < Formula
homepage 'http://regldg.com'
url 'http://regldg.com/regldg-1.0.0.tar.gz'
sha1 '1a355c1898f90b6a725e2ddc39b4daa2ce83b856'
def install
system "make"
bin.install "regldg"
end
test do
system "#{bin}/regldg", "test"
end
end
|
require 'rails_helper'
describe "the properties management", :type => :feature do
let!(:user) { create(:lease_holder) }
let!(:property) { create(:property, lease_holder: user) }
before do
login_me(user)
end
#TODO Fix the JS validations
scenario 'Shows the index properties for the leaseholder' do
visit user_properties_path(user.id)
expect(page).to have_content('Propiedades Registradas')
end
scenario 'Shows the properties menu for the leaseholder' do
visit new_user_property_path(user.id)
expect(page).to have_content('Registrar Propiedad')
end
scenario 'shows the property registration form' do
countries = double(CountriesWithCitiesGrouper)
allow(CountriesWithCitiesGrouper).to receive(:new).with('Americas') { countries }
allow(countries).to receive(:cities_for).with('Colombia') { ['Cartagena de Indias'] }
visit new_user_property_path(user.id)
select 'Cartagena de Indias', from: "property_city"
fill_in 'property_neighbor', with: 'Torices'
fill_in 'property_location', with: 'Calle 42 # 14B-2 a 14B-100'
fill_in 'property_area', with: '100'
fill_in 'property_floors_number', with: 1
fill_in 'property_floor', with: 1
fill_in 'property_building_name', with: ''
click_button('Registrar')
expect(Property.last).to_not be_nil
end
end
properties: Add integration spec for edit action.
require 'rails_helper'
describe "the properties management", :type => :feature do
let!(:user) { create(:lease_holder) }
let!(:property) { create(:property, lease_holder: user) }
before do
login_me(user)
end
#TODO Fix the JS validations
scenario 'Shows the index properties for the leaseholder' do
visit user_properties_path(user.id)
expect(page).to have_content('Propiedades Registradas')
end
scenario 'Shows the properties menu for the leaseholder' do
visit new_user_property_path(user.id)
expect(page).to have_content('Registrar Propiedad')
end
scenario 'shows the property registration form' do
countries = double(CountriesWithCitiesGrouper)
allow(CountriesWithCitiesGrouper).to receive(:new).with('Americas') { countries }
allow(countries).to receive(:cities_for).with('Colombia') { ['Cartagena de Indias'] }
visit new_user_property_path(user.id)
select 'Cartagena de Indias', from: "property_city"
fill_in 'property_neighbor', with: 'Torices'
fill_in 'property_location', with: 'Calle 42 # 14B-2 a 14B-100'
fill_in 'property_area', with: '100'
fill_in 'property_floors_number', with: 1
fill_in 'property_floor', with: 1
fill_in 'property_building_name', with: ''
click_button('Registrar')
expect(Property.last).to_not be_nil
end
scenario 'shows the edit property form' do
countries = double(CountriesWithCitiesGrouper)
allow(CountriesWithCitiesGrouper).to receive(:new).with('Americas') { countries }
allow(countries).to receive(:cities_for).with('Colombia') { ['Cartagena de Indias'] }
visit edit_user_property_path(user.id, property.id)
fill_in 'property_area', with: '100'
select 'Vender', from: "property_for_sell"
click_button('Guardar')
expect(Property.last.area).to eq(100)
end
end
|
require "formula"
class MarkdownRequirement < Requirement
fatal true
default_formula "markdown"
satisfy { which "markdown" }
end
class Shocco < Formula
desc "Literate documentation tool for shell scripts (a la Docco)"
homepage "http://rtomayko.github.io/shocco/"
url "https://github.com/rtomayko/shocco/archive/1.0.tar.gz"
sha1 "e29d58fb8109040b4fb4a816f330bb1c67064f6d"
depends_on MarkdownRequirement
resource "pygments" do
url "http://pypi.python.org/packages/source/P/Pygments/Pygments-1.5.tar.gz"
sha1 "4fbd937fd5cebc79fa4b26d4cce0868c4eec5ec5"
end
# Upstream, but not in a release
patch :DATA
def install
libexec.install resource("pygments").files("pygmentize", "pygments")
system "./configure",
"PYGMENTIZE=#{libexec}/pygmentize",
"MARKDOWN=#{HOMEBREW_PREFIX}/bin/markdown",
"--prefix=#{prefix}"
system "make"
system "make", "install"
end
def caveats
<<-EOS.undent
You may also want to install browser:
brew install browser
shocco `which shocco` | browser
EOS
end
end
__END__
diff --git a/configure b/configure
index 2262477..bf0af62 100755
--- a/configure
+++ b/configure
@@ -193,7 +193,7 @@ else stdutil xdg-open XDG_OPEN xdg-open
fi
stdutil ronn RONN ronn
-stdutil markdown MARKDOWN markdown Markdown.pl
+stdutil markdown MARKDOWN markdown Markdown.pl $MARKDOWN
stdutil perl PERL perl
stdutil pygmentize PYGMENTIZE pygmentize $PYGMENTIZE
shocco: fix strict audit.
class MarkdownRequirement < Requirement
fatal true
default_formula "markdown"
satisfy { which "markdown" }
end
class Shocco < Formula
desc "Literate documentation tool for shell scripts (a la Docco)"
homepage "https://rtomayko.github.io/shocco/"
url "https://github.com/rtomayko/shocco/archive/1.0.tar.gz"
sha256 "b3454ca818329955043b166a9808847368fd48dbe94c4b819a9f0c02cf57ce2e"
depends_on MarkdownRequirement
resource "pygments" do
url "http://pypi.python.org/packages/source/P/Pygments/Pygments-1.5.tar.gz"
sha256 "fe183e3886f597e41f8c88d0e53c796cefddc879bfdf45f2915a383060436740"
end
# Upstream, but not in a release
patch :DATA
def install
libexec.install resource("pygments").files("pygmentize", "pygments")
system "./configure",
"PYGMENTIZE=#{libexec}/pygmentize",
"MARKDOWN=#{HOMEBREW_PREFIX}/bin/markdown",
"--prefix=#{prefix}"
system "make"
system "make", "install"
end
def caveats
<<-EOS.undent
You may also want to install browser:
brew install browser
shocco `which shocco` | browser
EOS
end
end
__END__
diff --git a/configure b/configure
index 2262477..bf0af62 100755
--- a/configure
+++ b/configure
@@ -193,7 +193,7 @@ else stdutil xdg-open XDG_OPEN xdg-open
fi
stdutil ronn RONN ronn
-stdutil markdown MARKDOWN markdown Markdown.pl
+stdutil markdown MARKDOWN markdown Markdown.pl $MARKDOWN
stdutil perl PERL perl
stdutil pygmentize PYGMENTIZE pygmentize $PYGMENTIZE
|
require 'spec_helper'
module Donaghy
describe RemoteDistributor do
let(:event_path) { "blah/cool" }
let(:queue) { "testQueue" }
let(:class_name) { "KlassHandler" }
let(:event) { Event.new(path: event_path, payload: true)}
let(:queue_finder) { QueueFinder.new(event_path)}
let(:mock_queue) { mock(:message_queue, publish: true)}
before do
EventSubscriber.new.global_subscribe_to_event(event_path, queue, class_name)
end
it "should distribute work" do
Donaghy.should_receive(:queue_for).with(queue).and_return(mock_queue)
mock_queue.should_receive(:publish).with(an_instance_of(Event)).and_return(true)
RemoteDistributor.new.handle_distribution(event)
end
it "shouldn't error when no subscription" do
Donaghy.storage.flush
->() { RemoteDistributor.new.handle_distribution(event) }.should_not raise_error
end
end
end
Failing spec, showing that when there are more then one listeners in a cluster listening to the same event, then when an event matching those listeners fire, the message will be enqueued once for each listener (not good behavior)
require 'spec_helper'
module Donaghy
describe RemoteDistributor do
let(:event_path) { "blah/cool" }
let(:queue) { "testQueue" }
let(:class_name) { "KlassHandler" }
let(:event) { Event.new(path: event_path, payload: true)}
let(:queue_finder) { QueueFinder.new(event_path)}
let(:mock_queue) { mock(:message_queue, publish: true)}
describe "with a single listener" do
before do
EventSubscriber.new.global_subscribe_to_event(event_path, queue, class_name)
end
it "should distribute work" do
Donaghy.should_receive(:queue_for).with(queue).and_return(mock_queue)
mock_queue.should_receive(:publish).with(an_instance_of(Event)).and_return(true)
RemoteDistributor.new.handle_distribution(event)
end
it "shouldn't error when no subscription" do
Donaghy.storage.flush
->() { RemoteDistributor.new.handle_distribution(event) }.should_not raise_error
end
end
describe "when mulitple classes from the same cluster listen to the same event" do
before do
class ListenerOne
include Donaghy::Service
receives "blah/cool", :handle_shared
end
class ListenerTwo
include Donaghy::Service
receives "blah/cool", :handle_shared
end
EventSubscriber.new.global_subscribe_to_event(event_path, queue, "ListenerOne")
EventSubscriber.new.global_subscribe_to_event(event_path, queue, "ListenerTwo")
end
it "should only send one message from the global queue to the cluster queue" do
Donaghy.stub(:queue_for).and_return(queue)
queue.stub(:publish).and_return(true)
Donaghy.should_receive(:queue_for).with(queue).once
RemoteDistributor.new.handle_distribution(event)
end
end
end
end
|
class Snappy < Formula
homepage "http://snappy.googlecode.com"
url "https://drive.google.com/uc?id=0B0xs9kK-b5nMOWIxWGJhMXd6aGs&export=download"
mirror "https://mirrors.kernel.org/debian/pool/main/s/snappy/snappy_1.1.2.orig.tar.gz"
sha256 "f9d8fe1c85494f62dbfa3efe8e73bc23d8dec7a254ff7fe09ec4b0ebfc586af4"
version "1.1.2"
head do
url "https://github.com/google/snappy.git"
depends_on "automake" => :build
depends_on "autoconf" => :build
depends_on "libtool" => :build
end
bottle do
cellar :any
sha256 "c95c90ea412c185d42346f21637157c82ccfd6cfee7830d3fdf7c7427cc1630f" => :yosemite
sha256 "3237d3ca278cabb40968699b45914fd3468363cb291bfc19e45a265a68a54c28" => :mavericks
sha256 "36ac0b1d4cb6edbe915ba54a79a600674757ce5682fa1389e4a1ef98d7c10884" => :mountain_lion
end
option :universal
depends_on "pkg-config" => :build
def install
ENV.universal_binary if build.universal?
ENV.j1 if build.stable?
if build.head?
# https://github.com/google/snappy/pull/4
inreplace "autogen.sh", "libtoolize", "glibtoolize"
system "./autogen.sh"
end
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.cpp").write <<-EOS.undent
#include <assert.h>
#include <snappy.h>
#include <string>
using namespace std;
using namespace snappy;
int main()
{
string source = "Hello World!";
string compressed, decompressed;
Compress(source.data(), source.size(), &compressed);
Uncompress(compressed.data(), compressed.size(), &decompressed);
assert(source == decompressed);
return 0;
}
EOS
system ENV.cxx, "test.cpp", "-L#{lib}", "-lsnappy", "-o", "test"
system "./test"
end
end
snappy: use SSL/TLS homepage, follow redirect
Closes #39869.
Signed-off-by: Mike McQuaid <a17fed27eaa842282862ff7c1b9c8395a26ac320@mikemcquaid.com>
class Snappy < Formula
homepage "https://code.google.com/p/snappy/"
url "https://drive.google.com/uc?id=0B0xs9kK-b5nMOWIxWGJhMXd6aGs&export=download"
mirror "https://mirrors.kernel.org/debian/pool/main/s/snappy/snappy_1.1.2.orig.tar.gz"
sha256 "f9d8fe1c85494f62dbfa3efe8e73bc23d8dec7a254ff7fe09ec4b0ebfc586af4"
version "1.1.2"
head do
url "https://github.com/google/snappy.git"
depends_on "automake" => :build
depends_on "autoconf" => :build
depends_on "libtool" => :build
end
bottle do
cellar :any
sha256 "c95c90ea412c185d42346f21637157c82ccfd6cfee7830d3fdf7c7427cc1630f" => :yosemite
sha256 "3237d3ca278cabb40968699b45914fd3468363cb291bfc19e45a265a68a54c28" => :mavericks
sha256 "36ac0b1d4cb6edbe915ba54a79a600674757ce5682fa1389e4a1ef98d7c10884" => :mountain_lion
end
option :universal
depends_on "pkg-config" => :build
def install
ENV.universal_binary if build.universal?
ENV.j1 if build.stable?
if build.head?
# https://github.com/google/snappy/pull/4
inreplace "autogen.sh", "libtoolize", "glibtoolize"
system "./autogen.sh"
end
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.cpp").write <<-EOS.undent
#include <assert.h>
#include <snappy.h>
#include <string>
using namespace std;
using namespace snappy;
int main()
{
string source = "Hello World!";
string compressed, decompressed;
Compress(source.data(), source.size(), &compressed);
Uncompress(compressed.data(), compressed.size(), &decompressed);
assert(source == decompressed);
return 0;
}
EOS
system ENV.cxx, "test.cpp", "-L#{lib}", "-lsnappy", "-o", "test"
system "./test"
end
end
|
require 'spec_helper'
describe InsensitiveLoad::Collector do
let(:instance) { described_class.new(path_source) }
shared_context 'relative path in the sample file structure' do
before {
Dir.chdir(File.expand_path('../../../sample', __FILE__))
}
let(:path_source) { 'ext/soFTwaRe/Config.conf' }
end
shared_context 'absolute directory in your system' do
let(:path_source) {
Gem.win_platform? \
? ENV['TEMP'].upcase
: '/uSR/Bin'
}
end
shared_context 'absolute file in your system' do
let(:path_source) {
Gem.win_platform? \
? ENV['ComSpec'].upcase
: '/eTc/HOsTS'
}
end
shared_examples 'to return an instance of Array' do |size|
it 'return an array' do
expect(subject).to \
be_a_kind_of(Array)
end
it 'return an array of proper size' do
expect(subject.size).to \
eq(size)
end
end
describe '.new' do
context 'when passed a relative path of existence' do
subject { described_class.new(path_source) }
include_context \
'relative path in the sample file structure'
it 'create a kind of InsensitiveLoad::Collector' do
is_expected.to \
be_a_kind_of(described_class)
end
end
context 'when passed an instance of InsensitiveLoad::Item' do
let(:item) { InsensitiveLoad::Item.allocate }
subject { described_class.new(item) }
it 'create a kind of InsensitiveLoad::Collector' do
is_expected.to \
be_a_kind_of(described_class)
end
end
context 'when passed an array including Item instances' do
let(:item1) { InsensitiveLoad::Item.allocate }
let(:item2) { InsensitiveLoad::Item.allocate }
subject { described_class.new([item1, item2]) }
it 'create a kind of InsensitiveLoad::Collector' do
is_expected.to \
be_a_kind_of(described_class)
end
end
context 'when passed a nil' do
subject { described_class.new(nil) }
it 'raise SourceError' do
expect { subject }.to \
raise_error(described_class::SourceError)
end
end
context 'when passed a blank string' do
subject { described_class.new('') }
it 'raise ItemError' do
expect { subject }.to \
raise_error(described_class::SourceError)
end
end
end
describe 'methods to add @items' do
describe '#add_item' do
let(:instance) { described_class.allocate }
context 'when passed an instance of InsensitiveLoad::Item' do
let(:item) { InsensitiveLoad::Item.allocate }
subject { instance.add_item(item) }
it 'add @items correctly' do
is_expected.to \
all(be_an_instance_of(InsensitiveLoad::Item))
end
end
context 'when passed an Array including Item instances' do
let(:item1) { InsensitiveLoad::Item.allocate }
let(:item2) { InsensitiveLoad::Item.allocate }
subject { instance.add_item([item1, item2]) }
it 'add @items correctly' do
is_expected.to \
all(be_an_instance_of(InsensitiveLoad::Item))
end
it 'be correct size of the added @items' do
expect(subject.size).to \
eq(2)
end
end
context 'when passed a nil' do
subject { instance.add_item(nil) }
it 'raise ItemError' do
expect { subject }.to \
raise_error(described_class::ItemError)
end
end
end
end
describe 'methods to get @items' do
describe '#items' do
subject { instance.items }
context 'when passed a relative path of existence' do
include_context \
'relative path in the sample file structure'
it_behaves_like \
'to return an instance of Array',
4
it 'return Array filled with instances of InsensitiveLoad::Item' do
is_expected.to \
all(be_an_instance_of(InsensitiveLoad::Item))
end
end
end
end
describe 'methods to get data in @items' do
describe '#values' do
subject { instance.values }
context 'when passed a relative path of existence' do
include_context \
'relative path in the sample file structure'
it_behaves_like \
'to return an instance of Array',
3
it 'return the text in files' do
is_expected.to \
all(match(/\AI am '[^']+'.\z*/))
end
end
end
end
describe 'methods to get path in @items' do
shared_examples 'initialized by absolute path' do |method_name|
let(:returner) { instance.send(method_name).map(&:downcase) }
it 'return the equivalent insensitively' do
expect(returner).to \
all(eq(path_source.downcase))
end
end
shared_examples 'initialized by relative path' do |method_name|
let(:returner) { instance.send(method_name) }
it 'return an array including absolute path' do
returner.each do |path|
matched_head = path.downcase.index(path_source.downcase)
expect(matched_head).to \
be > 1
end
end
end
describe '#pathes' do
subject { instance.pathes }
context 'when passed an absolute path of existence' do
include_context \
'absolute file in your system'
it_behaves_like \
'to return an instance of Array',
1
it_behaves_like \
'initialized by absolute path',
:pathes
end
context 'when passed a relative path of existence' do
include_context \
'relative path in the sample file structure'
it_behaves_like \
'to return an instance of Array',
4
it_behaves_like \
'initialized by relative path',
:pathes
context 'with unreasonable "delimiter" option' do
let(:instance) {
described_class.new(
path_source,
delimiter: 'DELIMITER_STRING')
}
it 'return an empty array' do
expect(subject.size).to \
eq(0)
end
end
end
end
end
describe 'returns a kind of Collector' do
shared_examples 'initialized by absolute path' do |method_name|
let(:returner) { instance.send(method_name).pathes.map(&:downcase) }
it 'return the equivalent insensitively' do
expect(returner).to \
all(eq(path_source.downcase))
end
end
shared_examples 'initialized by relative path' do |method_name|
let(:returner) { instance.send(method_name).pathes }
it 'return an array including absolute path' do
returner.each do |path|
matched_head = path.downcase.index(path_source.downcase)
expect(matched_head).to \
be > 1
end
end
end
shared_examples 'to return a kind of Collector' do |size|
it 'return a kind of Collector' do
expect(subject).to \
be_a_kind_of(InsensitiveLoad::Collector)
end
it 'return an array of proper size' do
expect(subject.items.size).to \
eq(size)
end
end
describe '#dirs' do
subject { instance.dirs }
context 'when passed an absolute path of existence' do
include_context \
'absolute directory in your system'
it_behaves_like \
'to return a kind of Collector',
1
it_behaves_like \
'initialized by absolute path',
:dirs
end
context 'when passed a relative path of existence' do
include_context \
'relative path in the sample file structure'
it_behaves_like \
'to return a kind of Collector',
1
it_behaves_like \
'initialized by relative path',
:dirs
end
end
describe '#files' do
subject { instance.files }
context 'when passed an absolute path of existence' do
include_context \
'absolute file in your system'
it_behaves_like \
'to return a kind of Collector',
1
it_behaves_like \
'initialized by absolute path',
:files
end
context 'when passed a relative path of existence' do
include_context \
'relative path in the sample file structure'
it_behaves_like \
'to return a kind of Collector',
3
it_behaves_like \
'initialized by relative path',
:files
end
end
end
end
Add spec of Collector
spec of InsensitiveLoad::Collector
----
- Add the describe '#add_by_path'.
- In the describe 'methods to add @items'.
- Add the context 'when passed a nil'.
- In the above describe.
require 'spec_helper'
describe InsensitiveLoad::Collector do
let(:instance) { described_class.new(path_source) }
shared_context 'relative path in the sample file structure' do
before {
Dir.chdir(File.expand_path('../../../sample', __FILE__))
}
let(:path_source) { 'ext/soFTwaRe/Config.conf' }
end
shared_context 'absolute directory in your system' do
let(:path_source) {
Gem.win_platform? \
? ENV['TEMP'].upcase
: '/uSR/Bin'
}
end
shared_context 'absolute file in your system' do
let(:path_source) {
Gem.win_platform? \
? ENV['ComSpec'].upcase
: '/eTc/HOsTS'
}
end
shared_examples 'to return an instance of Array' do |size|
it 'return an array' do
expect(subject).to \
be_a_kind_of(Array)
end
it 'return an array of proper size' do
expect(subject.size).to \
eq(size)
end
end
describe '.new' do
context 'when passed a relative path of existence' do
subject { described_class.new(path_source) }
include_context \
'relative path in the sample file structure'
it 'create a kind of InsensitiveLoad::Collector' do
is_expected.to \
be_a_kind_of(described_class)
end
end
context 'when passed an instance of InsensitiveLoad::Item' do
let(:item) { InsensitiveLoad::Item.allocate }
subject { described_class.new(item) }
it 'create a kind of InsensitiveLoad::Collector' do
is_expected.to \
be_a_kind_of(described_class)
end
end
context 'when passed an array including Item instances' do
let(:item1) { InsensitiveLoad::Item.allocate }
let(:item2) { InsensitiveLoad::Item.allocate }
subject { described_class.new([item1, item2]) }
it 'create a kind of InsensitiveLoad::Collector' do
is_expected.to \
be_a_kind_of(described_class)
end
end
context 'when passed a nil' do
subject { described_class.new(nil) }
it 'raise SourceError' do
expect { subject }.to \
raise_error(described_class::SourceError)
end
end
context 'when passed a blank string' do
subject { described_class.new('') }
it 'raise ItemError' do
expect { subject }.to \
raise_error(described_class::SourceError)
end
end
end
describe 'methods to add @items' do
describe '#add_by_path' do
let(:instance) { described_class.allocate }
let(:search_class) { ::InsensitiveLoad::Search }
context 'when passed a nil' do
subject { instance.add_by_path(nil) }
it 'raise PathSourceError' do
expect { subject }.to \
raise_error(search_class::PathSourceError)
end
end
end
describe '#add_item' do
let(:instance) { described_class.allocate }
context 'when passed an instance of InsensitiveLoad::Item' do
let(:item) { InsensitiveLoad::Item.allocate }
subject { instance.add_item(item) }
it 'add @items correctly' do
is_expected.to \
all(be_an_instance_of(InsensitiveLoad::Item))
end
end
context 'when passed an Array including Item instances' do
let(:item1) { InsensitiveLoad::Item.allocate }
let(:item2) { InsensitiveLoad::Item.allocate }
subject { instance.add_item([item1, item2]) }
it 'add @items correctly' do
is_expected.to \
all(be_an_instance_of(InsensitiveLoad::Item))
end
it 'be correct size of the added @items' do
expect(subject.size).to \
eq(2)
end
end
context 'when passed a nil' do
subject { instance.add_item(nil) }
it 'raise ItemError' do
expect { subject }.to \
raise_error(described_class::ItemError)
end
end
end
end
describe 'methods to get @items' do
describe '#items' do
subject { instance.items }
context 'when passed a relative path of existence' do
include_context \
'relative path in the sample file structure'
it_behaves_like \
'to return an instance of Array',
4
it 'return Array filled with instances of InsensitiveLoad::Item' do
is_expected.to \
all(be_an_instance_of(InsensitiveLoad::Item))
end
end
end
end
describe 'methods to get data in @items' do
describe '#values' do
subject { instance.values }
context 'when passed a relative path of existence' do
include_context \
'relative path in the sample file structure'
it_behaves_like \
'to return an instance of Array',
3
it 'return the text in files' do
is_expected.to \
all(match(/\AI am '[^']+'.\z*/))
end
end
end
end
describe 'methods to get path in @items' do
shared_examples 'initialized by absolute path' do |method_name|
let(:returner) { instance.send(method_name).map(&:downcase) }
it 'return the equivalent insensitively' do
expect(returner).to \
all(eq(path_source.downcase))
end
end
shared_examples 'initialized by relative path' do |method_name|
let(:returner) { instance.send(method_name) }
it 'return an array including absolute path' do
returner.each do |path|
matched_head = path.downcase.index(path_source.downcase)
expect(matched_head).to \
be > 1
end
end
end
describe '#pathes' do
subject { instance.pathes }
context 'when passed an absolute path of existence' do
include_context \
'absolute file in your system'
it_behaves_like \
'to return an instance of Array',
1
it_behaves_like \
'initialized by absolute path',
:pathes
end
context 'when passed a relative path of existence' do
include_context \
'relative path in the sample file structure'
it_behaves_like \
'to return an instance of Array',
4
it_behaves_like \
'initialized by relative path',
:pathes
context 'with unreasonable "delimiter" option' do
let(:instance) {
described_class.new(
path_source,
delimiter: 'DELIMITER_STRING')
}
it 'return an empty array' do
expect(subject.size).to \
eq(0)
end
end
end
end
end
describe 'returns a kind of Collector' do
shared_examples 'initialized by absolute path' do |method_name|
let(:returner) { instance.send(method_name).pathes.map(&:downcase) }
it 'return the equivalent insensitively' do
expect(returner).to \
all(eq(path_source.downcase))
end
end
shared_examples 'initialized by relative path' do |method_name|
let(:returner) { instance.send(method_name).pathes }
it 'return an array including absolute path' do
returner.each do |path|
matched_head = path.downcase.index(path_source.downcase)
expect(matched_head).to \
be > 1
end
end
end
shared_examples 'to return a kind of Collector' do |size|
it 'return a kind of Collector' do
expect(subject).to \
be_a_kind_of(InsensitiveLoad::Collector)
end
it 'return an array of proper size' do
expect(subject.items.size).to \
eq(size)
end
end
describe '#dirs' do
subject { instance.dirs }
context 'when passed an absolute path of existence' do
include_context \
'absolute directory in your system'
it_behaves_like \
'to return a kind of Collector',
1
it_behaves_like \
'initialized by absolute path',
:dirs
end
context 'when passed a relative path of existence' do
include_context \
'relative path in the sample file structure'
it_behaves_like \
'to return a kind of Collector',
1
it_behaves_like \
'initialized by relative path',
:dirs
end
end
describe '#files' do
subject { instance.files }
context 'when passed an absolute path of existence' do
include_context \
'absolute file in your system'
it_behaves_like \
'to return a kind of Collector',
1
it_behaves_like \
'initialized by absolute path',
:files
end
context 'when passed a relative path of existence' do
include_context \
'relative path in the sample file structure'
it_behaves_like \
'to return a kind of Collector',
3
it_behaves_like \
'initialized by relative path',
:files
end
end
end
end |
require 'formula'
class Sphinx <Formula
version '0.9.9'
@url='http://www.sphinxsearch.com/downloads/sphinx-0.9.9.tar.gz'
@homepage='http://www.sphinxsearch.com'
@md5='7b9b618cb9b378f949bb1b91ddcc4f54'
depends_on 'mysql'
def install
system "./configure", "--prefix=#{prefix}", "--disable-debug", "--disable-dependency-tracking"
system "make install"
end
end
Fixes #391
require 'formula'
class Sphinx <Formula
version '0.9.9'
@url='http://www.sphinxsearch.com/downloads/sphinx-0.9.9.tar.gz'
@homepage='http://www.sphinxsearch.com'
@md5='7b9b618cb9b378f949bb1b91ddcc4f54'
depends_on 'mysql'
def install
# fails with llvm-gcc:
# ld: rel32 out of range in _GetPrivateProfileString from /usr/lib/libodbc.a(SQLGetPrivateProfileString.o)
ENV.gcc_4_2
system "./configure", "--prefix=#{prefix}", "--disable-debug", "--disable-dependency-tracking"
system "make install"
end
end
|
added test for SubstMixin#exp_replace_qs_tokens
RSpec.describe MiqExpression::SubstMixin do
let(:test_class) { Class.new { include MiqExpression::SubstMixin } }
let(:test_obj) { test_class.new }
describe "#exp_replace_qs_tokens" do
it "removes :token key from passed expression" do
exp = {"=" => {"field" => "Vm-active", "value" => "true"}, :token => 1}
test_obj.exp_replace_qs_tokens(exp, {})
expect(exp).to eq("=" => {"field" => "Vm-active", "value" => "true"})
end
end
end
|
require 'formula'
class SqliteFunctions < Formula
url 'http://www.sqlite.org/contrib/download/extension-functions.c?get=25', :using => NoUnzipCurlDownloadStrategy
md5 '3a32bfeace0d718505af571861724a43'
version '2010-01-06'
end
class Sqlite < Formula
homepage 'http://sqlite.org/'
url 'http://www.sqlite.org/sqlite-autoconf-3070900.tar.gz'
sha1 'a9da98a4bde4d9dae5c29a969455d11a03600e11'
version '3.7.9'
def options
[
["--with-rtree", "Enables the R*Tree index module"],
["--with-fts", "Enables the FTS Module"],
["--universal", "Build a universal binary."],
["--with-functions", "Enables more math and string functions for SQL queries."]
]
end
def install
# O2 and O3 leads to corrupt/invalid rtree indexes
# http://groups.google.com/group/spatialite-users/browse_thread/thread/8e1cfa79f2d02a00#
ENV.Os
ENV.append "CFLAGS", "-DSQLITE_ENABLE_RTREE=1" if ARGV.include? "--with-rtree"
ENV.append "CPPFLAGS","-DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS" if ARGV.include? "--with-fts"
ENV.universal_binary if ARGV.build_universal?
system "./configure", "--prefix=#{prefix}", "--disable-dependency-tracking",
(ARGV.include? "--with-functions") ? "--enable-dynamic-extensions" : ""
system "make install"
if ARGV.include? "--with-functions"
d=Pathname.getwd
SqliteFunctions.new.brew { mv 'extension-functions.c?get=25', d + 'extension-functions.c' }
system ENV.cc, "-fno-common", "-dynamiclib", "extension-functions.c", "-o", "libsqlitefunctions.dylib", *ENV.cflags.split
lib.install "libsqlitefunctions.dylib"
end
end
if ARGV.include? "--with-functions"
def caveats
<<-EOS.undent
Usage instructions for applications calling the sqlite3 API functions:
In your application, call sqlite3_enable_load_extension(db,1) to
allow loading external libraries. Then load the library libsqlitefunctions
using sqlite3_load_extension; the third argument should be 0.
See http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions.
Select statements may now use these functions, as in
SELECT cos(radians(inclination)) FROM satsum WHERE satnum = 25544;
Usage instructions for the sqlite3 program:
If the program is built so that loading extensions is permitted,
the following will work:
sqlite> SELECT load_extension('#{lib}/libsqlitefunctions.dylib');
sqlite> select cos(radians(45));
0.707106781186548
EOS
end
end
end
sqlite: rework compilation options
This enables a couple more compile-time options, along with some minor
style cleanups.
Signed-off-by: Jack Nagel <43386ce32af96f5c56f2a88e458cb94cebee3751@gmail.com>
require 'formula'
class SqliteFunctions < Formula
url 'http://www.sqlite.org/contrib/download/extension-functions.c?get=25', :using => NoUnzipCurlDownloadStrategy
md5 '3a32bfeace0d718505af571861724a43'
version '2010-01-06'
end
class Sqlite < Formula
homepage 'http://sqlite.org/'
url 'http://www.sqlite.org/sqlite-autoconf-3070900.tar.gz'
sha1 'a9da98a4bde4d9dae5c29a969455d11a03600e11'
version '3.7.9'
def options
[
["--with-rtree", "Enable the R*Tree index module"],
["--with-fts", "Enable the FTS Module"],
["--universal", "Build a universal binary"],
["--with-functions", "Enable more math and string functions for SQL queries"]
]
end
def install
# O2 and O3 leads to corrupt/invalid rtree indexes
# http://groups.google.com/group/spatialite-users/browse_thread/thread/8e1cfa79f2d02a00#
ENV.Os
ENV.append 'CPPFLAGS', "-DSQLITE_ENABLE_RTREE" if ARGV.include? "--with-rtree"
ENV.append 'CPPFLAGS', "-DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS" if ARGV.include? "--with-fts"
# enable these options by default
ENV.append 'CPPFLAGS', "-DSQLITE_ENABLE_COLUMN_METADATA"
ENV.append 'CPPFLAGS', "-DSQLITE_ENABLE_STAT3"
ENV.universal_binary if ARGV.build_universal?
system "./configure", "--prefix=#{prefix}", "--disable-dependency-tracking",
(ARGV.include? "--with-functions") ? "--enable-dynamic-extensions" : ""
system "make install"
if ARGV.include? "--with-functions"
d=Pathname.getwd
SqliteFunctions.new.brew { mv 'extension-functions.c?get=25', d + 'extension-functions.c' }
system ENV.cc, "-fno-common", "-dynamiclib", "extension-functions.c", "-o", "libsqlitefunctions.dylib", *ENV.cflags.split
lib.install "libsqlitefunctions.dylib"
end
end
if ARGV.include? "--with-functions"
def caveats
<<-EOS.undent
Usage instructions for applications calling the sqlite3 API functions:
In your application, call sqlite3_enable_load_extension(db,1) to
allow loading external libraries. Then load the library libsqlitefunctions
using sqlite3_load_extension; the third argument should be 0.
See http://www.sqlite.org/cvstrac/wiki?p=LoadableExtensions.
Select statements may now use these functions, as in
SELECT cos(radians(inclination)) FROM satsum WHERE satnum = 25544;
Usage instructions for the sqlite3 program:
If the program is built so that loading extensions is permitted,
the following will work:
sqlite> SELECT load_extension('#{lib}/libsqlitefunctions.dylib');
sqlite> select cos(radians(45));
0.707106781186548
EOS
end
end
end
|
Adding HighGroupList spec
require 'spec_helper'
module SSNFilter
describe HighGroupList do
subject(:high_group_list) { HighGroupList.new('data/april_2004_raw.txt') }
let(:list_data) do
# Data string manually transformed from the actual text file
data = '001 98,002 98,003 98,004 04,005 04,006 04,007 04,008 88,009 86,010 88,011 88,012 88,013 86,014 86,015 86,016 86,017 86,018 86,019 86,020 86,021 86,022 86,023 86,024 86,025 86,026 86,027 86,028 86,029 86,030 86,031 86,032 86,033 86,034 86,035 70,036 70,037 70,038 68,039 68,040 06,041 06,042 06,043 06,044 06,045 06,046 06,047 06,048 04,049 04,050 94,051 94,052 94,053 94,054 94,055 94,056 94,057 94,058 94,059 92,060 92,061 92,062 92,063 92,064 92,065 92,066 92,067 92,068 92,069 92,070 92,071 92,072 92,073 92,074 92,075 92,076 92,077 92,078 92,079 92,080 92,081 92,082 92,083 92,084 92,085 92,086 92,087 92,088 92,089 92,090 92,091 92,092 92,093 92,094 92,095 92,096 92,097 92,098 92,099 92,100 92,101 92,102 92,103 92,104 92,105 92,106 92,107 92,108 92,109 92,110 92,111 92,112 92,113 92,114 92,115 92,116 92,117 92,118 92,119 92,120 92,121 92,122 92,123 92,124 92,125 92,126 92,127 92,128 92,129 92,130 92,131 92,132 92,133 92,134 92,135 13,136 13,137 13,138 13,139 13,140 13,141 13,142 13,143 13,144 13,145 13,146 13,147 13,148 13,149 13,150 13,151 13,152 13,153 13,154 11,155 11,156 11,157 11,158 11,159 82,160 82,161 82,162 82,163 82,164 82,165 82,166 82,167 82,168 82,169 82,170 82,171 80,172 80,173 80,174 80,175 80,176 80,177 80,178 80,179 80,180 80,181 80,182 80,183 80,184 80,185 80,186 80,187 80,188 80,189 80,190 80,191 80,192 80,193 80,194 80,195 80,196 80,197 80,198 80,199 80,200 80,201 80,202 80,203 80,204 80,205 80,206 80,207 80,208 80,209 80,210 80,211 80,212 69,213 69,214 69,215 69,216 67,217 67,218 67,219 67,220 67,221 98,222 98,223 99,224 99,225 97,226 97,227 97,228 97,229 97,230 97,231 97,232 51,233 51,234 49,235 49,236 49,237 99,238 99,239 99,240 99,241 99,242 99,243 99,244 99,245 99,246 99,247 99,248 99,249 99,250 99,251 99,252 99,253 99,254 99,255 99,256 99,257 99,258 99,259 99,260 99,261 99,262 99,263 99,264 99,265 99,266 99,267 99,268 08,269 08,270 08,271 08,272 08,273 08,274 08,275 08,276 08,277 08,278 08,279 08,280 08,281 08,282 08,283 08,284 08,285 08,286 08,287 08,288 08,289 08,290 08,291 08,292 08,293 08,294 08,295 08,296 08,297 06,298 06,299 06,300 06,301 06,302 06,303 27,304 27,305 27,306 27,307 27,308 27,309 27,310 27,311 27,312 27,313 27,314 27,315 25,316 25,317 25,318 02,319 02,320 02,321 02,322 02,323 02,324 02,325 02,326 02,327 02,328 02,329 02,330 02,331 02,332 02,333 02,334 02,335 02,336 02,337 02,338 02,339 02,340 02,341 02,342 02,343 02,344 02,345 02,346 02,347 02,348 02,349 02,350 02,351 02,352 02,353 02,354 02,355 02,356 02,357 02,358 02,359 02,360 98,361 98,362 29,363 29,364 29,365 29,366 29,367 29,368 29,369 29,370 29,371 29,372 29,373 29,374 29,375 29,376 29,377 29,378 29,379 29,380 29,381 29,382 29,383 29,384 29,385 29,386 29,387 25,388 25,389 25,390 25,391 23,392 23,393 23,394 23,395 23,396 23,397 23,398 23,399 23,400 61,401 61,402 61,403 61,404 61,405 61,406 61,407 59,408 97,409 97,410 97,411 97,412 95,413 95,414 95,415 95,416 57,417 57,418 57,419 57,420 55,421 55,422 55,423 55,424 55,425 95,426 95,427 95,428 93,429 99,430 99,431 99,432 99,433 99,434 99,435 99,436 99,437 99,438 99,439 99,440 19,441 19,442 19,443 19,444 17,445 17,446 17,447 17,448 17,449 99,450 99,451 99,452 99,453 99,454 99,455 99,456 99,457 99,458 99,459 99,460 99,461 99,462 99,463 99,464 99,465 99,466 99,467 99,468 45,469 43,470 43,471 43,472 43,473 43,474 43,475 43,476 43,477 43,478 33,479 33,480 33,481 33,482 33,483 33,484 33,485 33,486 21,487 21,488 21,489 21,490 21,491 21,492 21,493 21,494 21,495 19,496 19,497 19,498 19,499 19,500 19,501 29,502 29,503 35,504 35,505 47,506 47,507 47,508 45,509 23,510 23,511 23,512 23,513 23,514 21,515 21,516 39,517 39,518 69,519 67,520 47,521 99,522 99,523 99,524 99,525 99,526 99,527 99,528 99,529 99,530 99,531 53,532 53,533 53,534 53,535 53,536 53,537 53,538 53,539 51,540 67,541 65,542 65,543 65,544 65,545 99,546 99,547 99,548 99,549 99,550 99,551 99,552 99,553 99,554 99,555 99,556 99,557 99,558 99,559 99,560 99,561 99,562 99,563 99,564 99,565 99,566 99,567 99,568 99,569 99,570 99,571 99,572 99,573 99,574 39,575 99,576 97,577 37,578 37,579 35,580 35,581 99,582 99,583 99,584 99,585 99,586 53,587 93,589 99,590 99,591 99,592 99,593 99,594 99,595 99,596 76,597 74,598 74,599 74,600 99,601 99,602 45,603 45,604 43,605 43,606 43,607 43,608 43,609 43,610 43,611 43,612 43,613 43,614 43,615 43,616 43,617 43,618 43,619 43,620 43,621 43,622 43,623 43,624 43,625 43,626 43,627 90,628 90,629 90,630 90,631 90,632 90,633 90,634 90,635 90,636 90,637 90,638 90,639 90,640 90,641 90,642 88,643 88,644 88,645 88,646 74,647 74,648 34,649 32,650 30,651 30,652 30,653 30,654 18,655 16,656 16,657 16,658 16,659 09,660 09,661 09,662 09,663 09,664 07,665 07,667 22,668 22,669 22,670 22,671 20,672 20,673 20,674 20,675 20,676 07,677 07,678 05,679 05,680 56,681 05,682 03,683 03,684 03,685 03,686 03,687 03,688 03,689 03,690 03,700 18,701 18,702 18,703 18,704 18,705 18,706 18,707 18,708 18,709 18,710 18,711 18,712 18,713 18,714 18,715 18,716 18,717 18,718 18,719 18,720 18,721 18,722 18,723 18,724 28,725 18,726 18,727 10,728 14,729 01,730 01,731 01,732 01,733 01,764 40,765 38,766 28,767 28,768 28,769 28,770 28,771 26,772 26'
data.split(/,/).map { |data_pair| data_pair.split(/\s/).map(&:to_i) }
end
it 'should read the correct date' do
expect(high_group_list.date_effective).to eq Date.parse('2004-04-02')
end
it 'should have all of the correct data members' do
high_group_list.all.each_with_index do |data_point, i|
expect(data_point).to eq list_data[i]
end
end
end
end
|
require "language/go"
class Srclib < Formula
desc "Polyglot code analysis library, build for hackability"
homepage "https://srclib.org"
url "https://github.com/sourcegraph/srclib/archive/v0.0.42.tar.gz"
sha256 "de9af74ec0805b0ef4f1c7ddf26c5aef43f84668b12c001f2f413ff20a19ebee"
head "https://github.com/sourcegraph/srclib.git"
bottle do
cellar :any
sha256 "75be0b0fad9f56cd33f7736dc8a5b663a7bf7ace7833ef2c5c00b40ec97b4e84" => :yosemite
sha256 "017a2522e99e6e8f56c39bc9b3fee10ec6622a7d73c2b973a6f7c0b56e6d40ad" => :mavericks
sha256 "00c130e9b76a25e872bcf79b4dc1b83e9679c2dd1f2396f138e2fc24538c57b0" => :mountain_lion
end
conflicts_with "src", :because => "both install a 'src' binary"
depends_on :hg => :build
depends_on "go" => :build
go_resource "code.google.com/p/rog-go" do
url "https://code.google.com/p/rog-go",
:revision => "7088342b70fc1995ada4986ef2d093f340439c78", :using => :hg
end
go_resource "github.com/Sirupsen/logrus" do
url "https://github.com/Sirupsen/logrus",
:revision => "cdd90c38c6e3718c731b555b9c3ed1becebec3ba", :using => :git
end
go_resource "github.com/alecthomas/binary" do
url "https://github.com/alecthomas/binary",
:revision => "21c37b530bec7c512af0208bfb15f34400301682", :using => :git
end
go_resource "github.com/alecthomas/unsafeslice" do
url "https://github.com/alecthomas/unsafeslice",
:revision => "a2ace32dbd4787714f87adb14a8aa369142efac5", :using => :git
end
go_resource "github.com/aybabtme/color" do
url "https://github.com/aybabtme/color",
:revision => "28ad4cc941d69a60df8d0af1233fd5a2793c2801", :using => :git
end
go_resource "github.com/docker/docker" do
url "https://github.com/docker/docker",
:revision => "9c505c906d318df7b5e8652c37e4df06b4f30d56", :using => :git
end
go_resource "github.com/fsouza/go-dockerclient" do
url "https://github.com/fsouza/go-dockerclient",
:revision => "ddb122d10f547ee6cfc4ea7debff407d80abdabc", :using => :git
end
go_resource "github.com/gogo/protobuf" do
url "https://github.com/gogo/protobuf",
:revision => "bc946d07d1016848dfd2507f90f0859c9471681e", :using => :git
end
go_resource "github.com/google/go-querystring" do
url "https://github.com/google/go-querystring",
:revision => "d8840cbb2baa915f4836edda4750050a2c0b7aea", :using => :git
end
go_resource "github.com/gorilla/context" do
url "https://github.com/gorilla/context",
:revision => "215affda49addc4c8ef7e2534915df2c8c35c6cd", :using => :git
end
go_resource "github.com/inconshreveable/go-update" do
url "https://github.com/inconshreveable/go-update",
:revision => "68f5725818189545231c1fd8694793d45f2fc529", :using => :git
end
go_resource "github.com/kardianos/osext" do
url "https://github.com/kardianos/osext",
:revision => "efacde03154693404c65e7aa7d461ac9014acd0c", :using => :git
end
go_resource "github.com/kr/binarydist" do
url "https://github.com/kr/binarydist",
:revision => "9955b0ab8708602d411341e55fffd7e0700f86bd", :using => :git
end
go_resource "github.com/kr/fs" do
url "https://github.com/kr/fs",
:revision => "2788f0dbd16903de03cb8186e5c7d97b69ad387b", :using => :git
end
go_resource "github.com/petar/GoLLRB" do
url "https://github.com/petar/GoLLRB",
:revision => "53be0d36a84c2a886ca057d34b6aa4468df9ccb4", :using => :git
end
go_resource "github.com/peterbourgon/diskv" do
url "https://github.com/peterbourgon/diskv",
:revision => "72aa5da9f7d1125b480b83c6dc5ad09a1f04508c", :using => :git
end
go_resource "github.com/peterh/liner" do
url "https://github.com/peterh/liner",
:revision => "1bb0d1c1a25ed393d8feb09bab039b2b1b1fbced", :using => :git
end
go_resource "github.com/smartystreets/mafsa" do
url "https://github.com/smartystreets/mafsa",
:revision => "ab6b5abc58c9d82560b127e23bfd3e39a25e8f05", :using => :git
end
go_resource "github.com/sourcegraph/go-github" do
url "https://github.com/sourcegraph/go-github",
:revision => "c6edc3e74760ee3c825f46ad9d4eb3e40469cb92", :using => :git
end
go_resource "github.com/sourcegraph/httpcache" do
url "https://github.com/sourcegraph/httpcache",
:revision => "e2fdd7ddabf459df5cd87bd18a4616ae7084763e", :using => :git
end
go_resource "github.com/sourcegraph/mux" do
url "https://github.com/sourcegraph/mux",
:revision => "dd22f369d469f65c3946889f5d8a1fb3933192e9", :using => :git
end
go_resource "github.com/sqs/fileset" do
url "https://github.com/sqs/fileset",
:revision => "4317e899aa9438ba7603a6e322389571cb3ffdff", :using => :git
end
go_resource "golang.org/x/tools" do
url "https://go.googlesource.com/tools",
:revision => "a18bb1d557dac8d19062dd0240b44ab09cfa14fd", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/go-diff" do
url "https://github.com/sourcegraph/go-diff",
:revision => "07d9929e8741ec84aa708aba12a4b1efd3a7a0dd", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/go-flags" do
url "https://github.com/sourcegraph/go-flags",
:revision => "f819544216a8b66157184f0976948f92a8144fe7", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/go-nnz" do
url "https://github.com/sourcegraph/go-nnz",
:revision => "62f271ba06026cf310d94721425eda2ec72f894c", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/go-sourcegraph" do
url "https://github.com/sourcegraph/go-sourcegraph",
:revision => "6f1cd4d2b721cff7913ed2f04bcd820590ce3b94", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/go-vcs" do
url "https://github.com/sourcegraph/go-vcs",
:revision => "1dcc4655df7318c3f105f9212900e1d0c68f7424", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/makex" do
url "https://github.com/sourcegraph/makex",
:revision => "ba5e243479d710a5d378c97d007568a405d04492", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/rwvfs" do
url "https://github.com/sourcegraph/rwvfs",
:revision => "451122bc19b9f1cdfeb2f1fdccadbc33ef5aa9f7", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/vcsstore" do
url "https://github.com/sourcegraph/vcsstore",
:revision => "53d0c58fd11f7dc451456eb983050c58cd005268", :using => :git
end
def install
ENV["GOBIN"] = bin
ENV["GOPATH"] = buildpath
mkdir_p buildpath/"src/sourcegraph.com/sourcegraph"
ln_sf buildpath, buildpath/"src/sourcegraph.com/sourcegraph/srclib"
Language::Go.stage_deps resources, buildpath/"src"
cd "cmd/src" do
system "go", "build", "-o", "src"
bin.install "src"
end
end
# For test
resource "srclib-sample" do
url "https://github.com/sourcegraph/srclib-sample/archive/0.1.tar.gz"
sha256 "7699eea46992c41331daacbff9df05f7aeec841582783ce3ac7e8eef790f1f1d"
end
test do
resource("srclib-sample").stage do
ENV.prepend_path "PATH", bin
system "#{bin}/src", "toolchain", "add", "--force", "sourcegraph.com/sourcegraph/srclib-sample"
result = pipe_output("#{bin}/src api units")
assert result.include?('"Type":"sample"')
end
end
end
srclib: fix no-longer-available revision in go-flags resource
Switches to the latest commit that now appears to have been in effect as of the time
of the srclib 0.0.42 release.
Fixes #44004.
Closes #47870.
Signed-off-by: Andrew Janke <02e0a999c50b1f88df7a8f5a04e1b76b35ea6a88@apjanke.net>
require "language/go"
class Srclib < Formula
desc "Polyglot code analysis library, built for hackability"
homepage "https://srclib.org"
url "https://github.com/sourcegraph/srclib/archive/v0.0.42.tar.gz"
sha256 "de9af74ec0805b0ef4f1c7ddf26c5aef43f84668b12c001f2f413ff20a19ebee"
revision 1
head "https://github.com/sourcegraph/srclib.git"
bottle do
cellar :any
sha256 "75be0b0fad9f56cd33f7736dc8a5b663a7bf7ace7833ef2c5c00b40ec97b4e84" => :yosemite
sha256 "017a2522e99e6e8f56c39bc9b3fee10ec6622a7d73c2b973a6f7c0b56e6d40ad" => :mavericks
sha256 "00c130e9b76a25e872bcf79b4dc1b83e9679c2dd1f2396f138e2fc24538c57b0" => :mountain_lion
end
conflicts_with "src", :because => "both install a 'src' binary"
depends_on :hg => :build
depends_on "go" => :build
go_resource "code.google.com/p/rog-go" do
url "https://code.google.com/p/rog-go",
:revision => "7088342b70fc1995ada4986ef2d093f340439c78", :using => :hg
end
go_resource "github.com/Sirupsen/logrus" do
url "https://github.com/Sirupsen/logrus",
:revision => "cdd90c38c6e3718c731b555b9c3ed1becebec3ba", :using => :git
end
go_resource "github.com/alecthomas/binary" do
url "https://github.com/alecthomas/binary",
:revision => "21c37b530bec7c512af0208bfb15f34400301682", :using => :git
end
go_resource "github.com/alecthomas/unsafeslice" do
url "https://github.com/alecthomas/unsafeslice",
:revision => "a2ace32dbd4787714f87adb14a8aa369142efac5", :using => :git
end
go_resource "github.com/aybabtme/color" do
url "https://github.com/aybabtme/color",
:revision => "28ad4cc941d69a60df8d0af1233fd5a2793c2801", :using => :git
end
go_resource "github.com/docker/docker" do
url "https://github.com/docker/docker",
:revision => "9c505c906d318df7b5e8652c37e4df06b4f30d56", :using => :git
end
go_resource "github.com/fsouza/go-dockerclient" do
url "https://github.com/fsouza/go-dockerclient",
:revision => "ddb122d10f547ee6cfc4ea7debff407d80abdabc", :using => :git
end
go_resource "github.com/gogo/protobuf" do
url "https://github.com/gogo/protobuf",
:revision => "bc946d07d1016848dfd2507f90f0859c9471681e", :using => :git
end
go_resource "github.com/google/go-querystring" do
url "https://github.com/google/go-querystring",
:revision => "d8840cbb2baa915f4836edda4750050a2c0b7aea", :using => :git
end
go_resource "github.com/gorilla/context" do
url "https://github.com/gorilla/context",
:revision => "215affda49addc4c8ef7e2534915df2c8c35c6cd", :using => :git
end
go_resource "github.com/inconshreveable/go-update" do
url "https://github.com/inconshreveable/go-update",
:revision => "68f5725818189545231c1fd8694793d45f2fc529", :using => :git
end
go_resource "github.com/kardianos/osext" do
url "https://github.com/kardianos/osext",
:revision => "efacde03154693404c65e7aa7d461ac9014acd0c", :using => :git
end
go_resource "github.com/kr/binarydist" do
url "https://github.com/kr/binarydist",
:revision => "9955b0ab8708602d411341e55fffd7e0700f86bd", :using => :git
end
go_resource "github.com/kr/fs" do
url "https://github.com/kr/fs",
:revision => "2788f0dbd16903de03cb8186e5c7d97b69ad387b", :using => :git
end
go_resource "github.com/petar/GoLLRB" do
url "https://github.com/petar/GoLLRB",
:revision => "53be0d36a84c2a886ca057d34b6aa4468df9ccb4", :using => :git
end
go_resource "github.com/peterbourgon/diskv" do
url "https://github.com/peterbourgon/diskv",
:revision => "72aa5da9f7d1125b480b83c6dc5ad09a1f04508c", :using => :git
end
go_resource "github.com/peterh/liner" do
url "https://github.com/peterh/liner",
:revision => "1bb0d1c1a25ed393d8feb09bab039b2b1b1fbced", :using => :git
end
go_resource "github.com/smartystreets/mafsa" do
url "https://github.com/smartystreets/mafsa",
:revision => "ab6b5abc58c9d82560b127e23bfd3e39a25e8f05", :using => :git
end
go_resource "github.com/sourcegraph/go-github" do
url "https://github.com/sourcegraph/go-github",
:revision => "c6edc3e74760ee3c825f46ad9d4eb3e40469cb92", :using => :git
end
go_resource "github.com/sourcegraph/httpcache" do
url "https://github.com/sourcegraph/httpcache",
:revision => "e2fdd7ddabf459df5cd87bd18a4616ae7084763e", :using => :git
end
go_resource "github.com/sourcegraph/mux" do
url "https://github.com/sourcegraph/mux",
:revision => "dd22f369d469f65c3946889f5d8a1fb3933192e9", :using => :git
end
go_resource "github.com/sqs/fileset" do
url "https://github.com/sqs/fileset",
:revision => "4317e899aa9438ba7603a6e322389571cb3ffdff", :using => :git
end
go_resource "golang.org/x/tools" do
url "https://go.googlesource.com/tools",
:revision => "a18bb1d557dac8d19062dd0240b44ab09cfa14fd", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/go-diff" do
url "https://github.com/sourcegraph/go-diff",
:revision => "07d9929e8741ec84aa708aba12a4b1efd3a7a0dd", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/go-flags" do
url "https://github.com/sourcegraph/go-flags",
:revision => "f59c328da6215a0b6acf0441ef19e361660ff405", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/go-nnz" do
url "https://github.com/sourcegraph/go-nnz",
:revision => "62f271ba06026cf310d94721425eda2ec72f894c", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/go-sourcegraph" do
url "https://github.com/sourcegraph/go-sourcegraph",
:revision => "6f1cd4d2b721cff7913ed2f04bcd820590ce3b94", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/go-vcs" do
url "https://github.com/sourcegraph/go-vcs",
:revision => "1dcc4655df7318c3f105f9212900e1d0c68f7424", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/makex" do
url "https://github.com/sourcegraph/makex",
:revision => "ba5e243479d710a5d378c97d007568a405d04492", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/rwvfs" do
url "https://github.com/sourcegraph/rwvfs",
:revision => "451122bc19b9f1cdfeb2f1fdccadbc33ef5aa9f7", :using => :git
end
go_resource "sourcegraph.com/sourcegraph/vcsstore" do
url "https://github.com/sourcegraph/vcsstore",
:revision => "53d0c58fd11f7dc451456eb983050c58cd005268", :using => :git
end
def install
ENV["GOBIN"] = bin
ENV["GOPATH"] = buildpath
mkdir_p buildpath/"src/sourcegraph.com/sourcegraph"
ln_sf buildpath, buildpath/"src/sourcegraph.com/sourcegraph/srclib"
Language::Go.stage_deps resources, buildpath/"src"
cd "cmd/src" do
system "go", "build", "-o", "src"
bin.install "src"
end
end
# For test
resource "srclib-sample" do
url "https://github.com/sourcegraph/srclib-sample.git",
:revision => "e753b113784bf383f627394e86e4936629a3b588"
end
test do
resource("srclib-sample").stage do
# Avoid automatic writing to $HOME/.srclib
ENV["SRCLIBPATH"] = testpath
ENV.prepend_path "PATH", bin
system "#{bin}/src", "toolchain", "add", "--force", "sourcegraph.com/sourcegraph/srclib-sample"
result = pipe_output("#{bin}/src api units")
assert_match '"Type":"sample"', result
end
end
end
|
require 'spec_helper'
require 'command'
describe ZendeskAppsTools::Command do
PREFIX = 'https://subdomain.zendesk.com'
before do
@command = ZendeskAppsTools::Command.new
@command.instance_variable_set(:@username, 'username')
@command.instance_variable_set(:@password, 'password')
@command.instance_variable_set(:@subdomain, 'subdomain')
@command.instance_variable_set(:@app_id, '123')
allow(@command).to receive(:fetch_cache)
allow(@command).to receive(:save_cache)
allow(@command).to receive(:clear_cache)
allow(@command).to receive(:options) { { clean: false, path: './' } }
end
describe '#upload' do
context 'when no zipfile is given' do
it 'uploads the newly packaged zipfile and returns an upload id' do
expect(@command).to receive(:package)
allow(@command).to receive(:options) { { zipfile: nil } }
allow(Faraday::UploadIO).to receive(:new)
stub_request(:post, PREFIX + '/api/v2/apps/uploads.json')
.with(headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
.to_return(body: '{ "id": 123 }')
expect(@command.upload('nah')).to eq(123)
end
end
context 'when zipfile is given' do
it 'uploads the given zipfile and returns an upload id' do
allow(@command).to receive(:options) { { zipfile: 'app.zip' } }
expect(::Faraday::UploadIO).to receive(:new).with('app.zip', 'application/zip').and_return(nil)
stub_request(:post, PREFIX + '/api/v2/apps/uploads.json')
.with(headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
.to_return(body: '{ "id": 123 }')
expect(@command.upload('nah')).to eq(123)
end
end
end
describe '#create' do
context 'when no zipfile is given' do
it 'uploads a file and posts build api' do
expect(@command).to receive(:upload).and_return(123)
allow(@command).to receive(:check_status)
expect(File).to receive(:read) { '{ "name": "abc" }' }
stub_request(:post, PREFIX + '/api/v2/apps.json')
.with(body: JSON.generate(name: 'abc', upload_id: '123'),
headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
@command.create
end
end
context 'when zipfile is given' do
it 'uploads the zipfile and posts build api' do
expect(@command).to receive(:upload).and_return(123)
allow(@command).to receive(:check_status)
allow(@command).to receive(:options) { { clean: false, path: './', zipfile: 'abc.zip' } }
expect(@command).to receive(:get_value_from_stdin) { 'abc' }
stub_request(:post, PREFIX + '/api/v2/apps.json')
.with(body: JSON.generate(name: 'abc', upload_id: '123'),
headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
@command.create
end
end
end
describe '#update' do
context 'when app id is in cache' do
it 'uploads a file and puts build api' do
expect(@command).to receive(:upload).and_return(123)
allow(@command).to receive(:check_status)
expect(@command).to receive(:fetch_cache).with('app_id').and_return(456)
stub_request(:put, PREFIX + '/api/v2/apps/456.json')
.with(headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
@command.update
end
end
context 'when app id is not in cache' do
it 'finds the app id first' do
@command.instance_variable_set(:@app_id, nil)
allow(@command).to receive(:get_value_from_stdin).and_return('itsme')
apps = {
apps: [
{ name: 'hello', id: 123 },
{ name: 'world', id: 124 },
{ name: 'itsme', id: 125 }
]
}
stub_request(:get, PREFIX + '/api/v2/apps.json')
.with(headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
.to_return(body: JSON.generate(apps))
expect(@command.send(:find_app_id)).to eq(125)
allow(@command).to receive(:deploy_app)
@command.update
end
end
end
describe '#version' do
context 'when -v is run' do
it 'shows the version' do
old_v = Gem::Version.new '0.0.1'
new_v = nil
expect(@command).to receive(:say) { |arg| new_v = Gem::Version.new arg }
@command.version
expect(old_v).to be < new_v
end
end
end
end
fix tests?
require 'spec_helper'
require 'command'
require 'faraday'
describe ZendeskAppsTools::Command do
PREFIX = 'https://subdomain.zendesk.com'
before do
@command = ZendeskAppsTools::Command.new
@command.instance_variable_set(:@username, 'username')
@command.instance_variable_set(:@password, 'password')
@command.instance_variable_set(:@subdomain, 'subdomain')
@command.instance_variable_set(:@app_id, '123')
allow(@command).to receive(:fetch_cache)
allow(@command).to receive(:save_cache)
allow(@command).to receive(:clear_cache)
allow(@command).to receive(:options) { { clean: false, path: './' } }
end
describe '#upload' do
context 'when no zipfile is given' do
it 'uploads the newly packaged zipfile and returns an upload id' do
expect(@command).to receive(:package)
allow(@command).to receive(:options) { { zipfile: nil } }
allow(Faraday::UploadIO).to receive(:new)
stub_request(:post, PREFIX + '/api/v2/apps/uploads.json')
.with(headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
.to_return(body: '{ "id": 123 }')
expect(@command.upload('nah')).to eq(123)
end
end
context 'when zipfile is given' do
it 'uploads the given zipfile and returns an upload id' do
allow(@command).to receive(:options) { { zipfile: 'app.zip' } }
expect(Faraday::UploadIO).to receive(:new).with('app.zip', 'application/zip').and_return(nil)
stub_request(:post, PREFIX + '/api/v2/apps/uploads.json')
.with(headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
.to_return(body: '{ "id": 123 }')
expect(@command.upload('nah')).to eq(123)
end
end
end
describe '#create' do
context 'when no zipfile is given' do
it 'uploads a file and posts build api' do
expect(@command).to receive(:upload).and_return(123)
allow(@command).to receive(:check_status)
expect(File).to receive(:read) { '{ "name": "abc" }' }
stub_request(:post, PREFIX + '/api/v2/apps.json')
.with(body: JSON.generate(name: 'abc', upload_id: '123'),
headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
@command.create
end
end
context 'when zipfile is given' do
it 'uploads the zipfile and posts build api' do
expect(@command).to receive(:upload).and_return(123)
allow(@command).to receive(:check_status)
allow(@command).to receive(:options) { { clean: false, path: './', zipfile: 'abc.zip' } }
expect(@command).to receive(:get_value_from_stdin) { 'abc' }
stub_request(:post, PREFIX + '/api/v2/apps.json')
.with(body: JSON.generate(name: 'abc', upload_id: '123'),
headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
@command.create
end
end
end
describe '#update' do
context 'when app id is in cache' do
it 'uploads a file and puts build api' do
expect(@command).to receive(:upload).and_return(123)
allow(@command).to receive(:check_status)
expect(@command).to receive(:fetch_cache).with('app_id').and_return(456)
stub_request(:put, PREFIX + '/api/v2/apps/456.json')
.with(headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
@command.update
end
end
context 'when app id is not in cache' do
it 'finds the app id first' do
@command.instance_variable_set(:@app_id, nil)
allow(@command).to receive(:get_value_from_stdin).and_return('itsme')
apps = {
apps: [
{ name: 'hello', id: 123 },
{ name: 'world', id: 124 },
{ name: 'itsme', id: 125 }
]
}
stub_request(:get, PREFIX + '/api/v2/apps.json')
.with(headers: { 'Authorization' => 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' })
.to_return(body: JSON.generate(apps))
expect(@command.send(:find_app_id)).to eq(125)
allow(@command).to receive(:deploy_app)
@command.update
end
end
end
describe '#version' do
context 'when -v is run' do
it 'shows the version' do
old_v = Gem::Version.new '0.0.1'
new_v = nil
expect(@command).to receive(:say) { |arg| new_v = Gem::Version.new arg }
@command.version
expect(old_v).to be < new_v
end
end
end
end
|
class Sslyze < Formula
desc "SSL scanner"
homepage "https://github.com/nabla-c0d3/sslyze"
url "https://github.com/nabla-c0d3/sslyze/archive/release-0.12.tar.gz"
version "0.12.0"
sha256 "5b3220d42cb66067b18d9055a2234252d849090e9fba660af52a3da18fa8a899"
bottle do
cellar :any_skip_relocation
revision 1
sha256 "473288500a16b32e0c5031fcec056c817da68a45cf8821b7ca04fb58ff87c1bc" => :el_capitan
sha256 "762c505503cc5582777d342786a2be10dd020b90de08a4e98cbe0625b74f5d09" => :yosemite
sha256 "0c2e3a2e463652fd2290e00434c4900ca10b5083aefecd2d489e3ccfceb8ac5f" => :mavericks
end
depends_on :arch => :x86_64
depends_on :python if MacOS.version <= :snow_leopard
resource "nassl" do
url "https://github.com/nabla-c0d3/nassl/archive/v0.12.tar.gz"
sha256 "40b3766fe98144e912ea7a8f1c34bf974e76f99ac40f128c3ce50b46b1fe315e"
end
resource "openssl" do
url "https://www.openssl.org/source/openssl-1.0.2d.tar.gz"
sha256 "671c36487785628a703374c652ad2cebea45fa920ae5681515df25d9f2c9a8c8"
end
resource "zlib" do
url "http://zlib.net/zlib-1.2.8.tar.gz"
sha256 "36658cb768a54c1d4dec43c3116c27ed893e88b02ecfcb44f2166f9c0b7f2a0d"
end
def install
# openssl fails on parallel build. Related issues:
# - http://rt.openssl.org/Ticket/Display.html?id=3736
# - http://rt.openssl.org/Ticket/Display.html?id=3737
ENV.deparallelize
resource("openssl").stage do
(buildpath/"nassl/openssl-1.0.2d").install Dir["*"]
end
resource("zlib").stage do
(buildpath/"nassl/zlib-1.2.8").install Dir["*"]
end
resource("nassl").stage do
(buildpath/"nassl").install Dir["*"]
end
cd "nassl" do
system "python", "buildAll_unix.py"
libexec.install "test/nassl"
end
libexec.install %w[plugins utils sslyze.py xml_out.xsd]
bin.install_symlink libexec/"sslyze.py" => "sslyze"
end
test do
assert_equal "0.12.0", shell_output("#{bin}/sslyze --version").strip
assert_match "SCAN COMPLETED", shell_output("#{bin}/sslyze --regular google.com")
end
end
sslyze: update 0.12.0 bottle.
class Sslyze < Formula
desc "SSL scanner"
homepage "https://github.com/nabla-c0d3/sslyze"
url "https://github.com/nabla-c0d3/sslyze/archive/release-0.12.tar.gz"
version "0.12.0"
sha256 "5b3220d42cb66067b18d9055a2234252d849090e9fba660af52a3da18fa8a899"
bottle do
cellar :any_skip_relocation
sha256 "afb0e576d8c7a2243ea746af6259149b32972f739e372d83ef1a025a8b6f2418" => :el_capitan
sha256 "01b9a548c4114b9ea6387ee6bc279e1eadff9326ecf32bcfde66130d4bc3cbe9" => :yosemite
sha256 "0fab1f496b3f52e7637e0ed8ef23d8b435b925150ca15b85899c95cf61084e8b" => :mavericks
end
depends_on :arch => :x86_64
depends_on :python if MacOS.version <= :snow_leopard
resource "nassl" do
url "https://github.com/nabla-c0d3/nassl/archive/v0.12.tar.gz"
sha256 "40b3766fe98144e912ea7a8f1c34bf974e76f99ac40f128c3ce50b46b1fe315e"
end
resource "openssl" do
url "https://www.openssl.org/source/openssl-1.0.2d.tar.gz"
sha256 "671c36487785628a703374c652ad2cebea45fa920ae5681515df25d9f2c9a8c8"
end
resource "zlib" do
url "http://zlib.net/zlib-1.2.8.tar.gz"
sha256 "36658cb768a54c1d4dec43c3116c27ed893e88b02ecfcb44f2166f9c0b7f2a0d"
end
def install
# openssl fails on parallel build. Related issues:
# - http://rt.openssl.org/Ticket/Display.html?id=3736
# - http://rt.openssl.org/Ticket/Display.html?id=3737
ENV.deparallelize
resource("openssl").stage do
(buildpath/"nassl/openssl-1.0.2d").install Dir["*"]
end
resource("zlib").stage do
(buildpath/"nassl/zlib-1.2.8").install Dir["*"]
end
resource("nassl").stage do
(buildpath/"nassl").install Dir["*"]
end
cd "nassl" do
system "python", "buildAll_unix.py"
libexec.install "test/nassl"
end
libexec.install %w[plugins utils sslyze.py xml_out.xsd]
bin.install_symlink libexec/"sslyze.py" => "sslyze"
end
test do
assert_equal "0.12.0", shell_output("#{bin}/sslyze --version").strip
assert_match "SCAN COMPLETED", shell_output("#{bin}/sslyze --regular google.com")
end
end
|
require 'spec_helper'
describe CsvImporterObserverObserver do
pending "add some examples to (or delete) #{__FILE__}"
end
Fix class name in booking_import_observer_spec.
require 'spec_helper'
describe BookingImportObserver do
pending "add some examples to (or delete) #{__FILE__}"
end
|
class Xxhash < Formula
desc "Extremely fast non-cryptographic hash algorithm"
homepage "https://github.com/Cyan4973/xxHash"
url "https://github.com/Cyan4973/xxHash/archive/r42.tar.gz"
version "r42"
sha256 "d21dba3ebf5ea8bf2f587150230189231c8d47e8b63c865c585b08d14c8218b8"
def install
system "make"
bin.install "xxhsum"
end
test do
(testpath/"leaflet.txt").write "No computer should be without one!"
assert_match /^67bc7cc242ebc50a/, shell_output("#{bin}/xxhsum leaflet.txt")
end
end
xxhash: add r42 bottle.
class Xxhash < Formula
desc "Extremely fast non-cryptographic hash algorithm"
homepage "https://github.com/Cyan4973/xxHash"
url "https://github.com/Cyan4973/xxHash/archive/r42.tar.gz"
version "r42"
sha256 "d21dba3ebf5ea8bf2f587150230189231c8d47e8b63c865c585b08d14c8218b8"
bottle do
cellar :any_skip_relocation
sha256 "6edf8933719f867a437b3b99eed77ba7e6207676524ff7bbf9b7dbe4b56af31f" => :el_capitan
sha256 "70786baab2979107795449762885b97df42b412e475b06d3266046339d93023d" => :yosemite
sha256 "c14a9879b1a280788f255714ba2837d605ed00b33c1678f019eaf10007790dd0" => :mavericks
end
def install
system "make"
bin.install "xxhsum"
end
test do
(testpath/"leaflet.txt").write "No computer should be without one!"
assert_match /^67bc7cc242ebc50a/, shell_output("#{bin}/xxhsum leaflet.txt")
end
end
|
require 'spec_helper'
describe Spree::Gateway::RecurlyGateway do
let(:subdomain) { 'mydomain' }
let(:api_key) { 'xjkejid32djio' }
let(:bill_address) {
stub('Spree::Address',
firstname: 'Tom',
lastname: 'Smith',
address1: '123 Happy Road',
address2: 'Apt 303',
city: 'Suzarac',
zipcode: '95671',
state: stub('Spree::State', name: 'Oregon'),
country: stub('Spree::Country', name: 'United States')
)
}
let(:payment) {
stub('Spree::Payment',
source: credit_card,
order: stub('Spree::Order',
email: 'smith@test.com',
bill_address: bill_address,
user: stub('Spree::User', id: 1)
)
)
}
before do
subject.set_preference :subdomain, subdomain
subject.set_preference :api_key, api_key
subject.send(:update_recurly_config)
end
describe '#create_profile' do
let(:credit_card) {
stub('Spree::CreditCard',
gateway_customer_profile_id: nil,
number: '4111-1111-1111-1111',
verification_value: '123',
month: '11',
year: '2015'
).as_null_object
}
context 'with an order that has a bill address' do
it 'stores the bill address with the provider' do
Recurly::Account.should_receive(:create).with({
account_code: 1,
email: 'smith@test.com',
first_name: 'Tom',
last_name: 'Smith',
address: {
address1: '123 Happy Road',
address2: 'Apt 303',
city: 'Suzarac',
zip: '95671',
country: 'United States',
state: 'Oregon'
},
billing_info: {
first_name: 'Tom',
last_name: 'Smith',
address1: '123 Happy Road',
address2: 'Apt 303',
city: 'Suzarac',
zip: '95671',
number: '4111-1111-1111-1111',
month: '11',
year: '2015',
verification_value: '123',
country: 'United States',
state: 'Oregon',
}
}).and_return(stub(account_code: payment.order.user.id, errors: nil))
subject.create_profile payment
end
end
end
context 'with existing account' do
let(:credit_card) {
stub('Spree::CreditCard',
gateway_customer_profile_id: 1,
number: '4111-1111-1111-1111',
verification_value: '123',
month: '11',
year: '2015'
)
}
context 'purchasing' do
it 'should send the payment to the provider' do
account = stub.as_null_object
Recurly::Account.should_receive(:find).with(1).and_return(account)
account.transactions.should_receive(:create).with(
:amount_in_cents => 19.99,
:currency => 'USD'
).and_return(stub.as_null_object)
subject.purchase(19.99, credit_card, {})
end
end
context 'voiding' do
it 'should send the voiding to the provider' do
transaction = stub.as_null_object
Recurly::Transaction.should_receive(:find).with('a13acd8fe4294916b79aec87b7ea441f').and_return(transaction)
transaction.should_receive(:refund).and_return(stub.as_null_object)
subject.void('a13acd8fe4294916b79aec87b7ea441f', credit_card, {})
end
end
context 'creditting' do
it 'should send the creditting to the provider' do
transaction = stub.as_null_object
Recurly::Transaction.should_receive(:find).with('a13acd8fe4294916b79aec87b7ea441f').and_return(transaction)
transaction.should_receive(:refund).with(50).and_return(stub.as_null_object)
subject.credit(50, credit_card, 'a13acd8fe4294916b79aec87b7ea441f', {})
end
end
context 'authorizing' do
it 'should not support authorizing' do
expect { subject.authorize(50, credit_card, {}) }.to raise_error
end
end
context 'capturing' do
it 'should not support capturing' do
expect { subject.capture(payment, credit_card, {}) }.to raise_error
end
end
end
end
Correct typos
require 'spec_helper'
describe Spree::Gateway::RecurlyGateway do
let(:subdomain) { 'mydomain' }
let(:api_key) { 'xjkejid32djio' }
let(:bill_address) {
stub('Spree::Address',
firstname: 'Tom',
lastname: 'Smith',
address1: '123 Happy Road',
address2: 'Apt 303',
city: 'Suzarac',
zipcode: '95671',
state: stub('Spree::State', name: 'Oregon'),
country: stub('Spree::Country', name: 'United States')
)
}
let(:payment) {
stub('Spree::Payment',
source: credit_card,
order: stub('Spree::Order',
email: 'smith@test.com',
bill_address: bill_address,
user: stub('Spree::User', id: 1)
)
)
}
before do
subject.set_preference :subdomain, subdomain
subject.set_preference :api_key, api_key
subject.send(:update_recurly_config)
end
describe '#create_profile' do
let(:credit_card) {
stub('Spree::CreditCard',
gateway_customer_profile_id: nil,
number: '4111-1111-1111-1111',
verification_value: '123',
month: '11',
year: '2015'
).as_null_object
}
context 'with an order that has a bill address' do
it 'stores the bill address with the provider' do
Recurly::Account.should_receive(:create).with({
account_code: 1,
email: 'smith@test.com',
first_name: 'Tom',
last_name: 'Smith',
address: {
address1: '123 Happy Road',
address2: 'Apt 303',
city: 'Suzarac',
zip: '95671',
country: 'United States',
state: 'Oregon'
},
billing_info: {
first_name: 'Tom',
last_name: 'Smith',
address1: '123 Happy Road',
address2: 'Apt 303',
city: 'Suzarac',
zip: '95671',
number: '4111-1111-1111-1111',
month: '11',
year: '2015',
verification_value: '123',
country: 'United States',
state: 'Oregon',
}
}).and_return(stub(account_code: payment.order.user.id, errors: nil))
subject.create_profile payment
end
end
end
context 'with existing account' do
let(:credit_card) {
stub('Spree::CreditCard',
gateway_customer_profile_id: 1,
number: '4111-1111-1111-1111',
verification_value: '123',
month: '11',
year: '2015'
)
}
context 'purchasing' do
it 'should send the payment to the provider' do
account = stub.as_null_object
Recurly::Account.should_receive(:find).with(1).and_return(account)
account.transactions.should_receive(:create).with(
:amount_in_cents => 19.99,
:currency => 'USD'
).and_return(stub.as_null_object)
subject.purchase(19.99, credit_card, {})
end
end
context 'voiding' do
it 'should send the voiding to the provider' do
transaction = stub.as_null_object
Recurly::Transaction.should_receive(:find).with('a13acd8fe4294916b79aec87b7ea441f').and_return(transaction)
transaction.should_receive(:refund).and_return(stub.as_null_object)
subject.void('a13acd8fe4294916b79aec87b7ea441f', credit_card, {})
end
end
context 'crediting' do
it 'should send the crediting to the provider' do
transaction = stub.as_null_object
Recurly::Transaction.should_receive(:find).with('a13acd8fe4294916b79aec87b7ea441f').and_return(transaction)
transaction.should_receive(:refund).with(50).and_return(stub.as_null_object)
subject.credit(50, credit_card, 'a13acd8fe4294916b79aec87b7ea441f', {})
end
end
context 'authorizing' do
it 'should not support authorizing' do
expect { subject.authorize(50, credit_card, {}) }.to raise_error
end
end
context 'capturing' do
it 'should not support capturing' do
expect { subject.capture(payment, credit_card, {}) }.to raise_error
end
end
end
end
|
require 'formula'
class Zeromq < Formula
url 'http://download.zeromq.org/zeromq-2.1.2.tar.gz'
head 'git://github.com/zeromq/zeromq2.git'
homepage 'http://www.zeromq.org/'
md5 'ee0ebe3b9dd6c80941656dd8c755764d'
def options
[['--universal', 'Build as a Universal Intel binary.']]
end
def build_fat
# make 32-bit
arch = "-arch i386"
system "CFLAGS=\"$CFLAGS #{arch}\" CXXFLAGS=\"$CXXFLAGS #{arch}\" ./configure --disable-dependency-tracking --prefix=#{prefix}"
system "make"
system "mv src/.libs src/libs-32"
system "make clean"
# make 64-bit
arch = "-arch x86_64"
system "CFLAGS=\"$CFLAGS #{arch}\" CXXFLAGS=\"$CXXFLAGS #{arch}\" ./configure --disable-dependency-tracking --prefix=#{prefix}"
system "make"
system "mv src/.libs/libzmq.1.dylib src/.libs/libzmq.64.dylib"
# merge UB
system "lipo", "-create", "src/libs-32/libzmq.1.dylib", "src/.libs/libzmq.64.dylib", "-output", "src/.libs/libzmq.1.dylib"
end
def install
fails_with_llvm "Compiling with LLVM gives a segfault while linking."
system "./autogen.sh" if ARGV.build_head?
if ARGV.include? '--universal'
build_fat
else
system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}"
end
system "make install"
end
def caveats; <<-EOS.undent
To install the zmq gem on 10.6 with the system Ruby on a 64-bit machine,
you may need to do:
$ ARCHFLAGS="-arch x86_64" gem install zmq -- --with-zmq-dir=#{HOMEBREW_PREFIX}
If you want to later build the Java bindings from https://github.com/zeromq/jzmq,
you will need to obtain the Java Developer Package from Apple ADC
at http://connect.apple.com/.
EOS
end
end
Updated zeromq to version 2.1.3
Signed-off-by: Adam Vandenberg <34c2b6407fd5a10249a15d699d40f9ed1782e98c@gmail.com>
require 'formula'
class Zeromq < Formula
url 'http://download.zeromq.org/zeromq-2.1.3.tar.gz'
head 'git://github.com/zeromq/zeromq2.git'
homepage 'http://www.zeromq.org/'
md5 'ae681af2df1b7191aeecfcb23bb73864'
def options
[['--universal', 'Build as a Universal Intel binary.']]
end
def build_fat
# make 32-bit
arch = "-arch i386"
system "CFLAGS=\"$CFLAGS #{arch}\" CXXFLAGS=\"$CXXFLAGS #{arch}\" ./configure --disable-dependency-tracking --prefix=#{prefix}"
system "make"
system "mv src/.libs src/libs-32"
system "make clean"
# make 64-bit
arch = "-arch x86_64"
system "CFLAGS=\"$CFLAGS #{arch}\" CXXFLAGS=\"$CXXFLAGS #{arch}\" ./configure --disable-dependency-tracking --prefix=#{prefix}"
system "make"
system "mv src/.libs/libzmq.1.dylib src/.libs/libzmq.64.dylib"
# merge UB
system "lipo", "-create", "src/libs-32/libzmq.1.dylib", "src/.libs/libzmq.64.dylib", "-output", "src/.libs/libzmq.1.dylib"
end
def install
fails_with_llvm "Compiling with LLVM gives a segfault while linking."
system "./autogen.sh" if ARGV.build_head?
if ARGV.include? '--universal'
build_fat
else
system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}"
end
system "make install"
end
def caveats; <<-EOS.undent
To install the zmq gem on 10.6 with the system Ruby on a 64-bit machine,
you may need to do:
$ ARCHFLAGS="-arch x86_64" gem install zmq -- --with-zmq-dir=#{HOMEBREW_PREFIX}
If you want to later build the Java bindings from https://github.com/zeromq/jzmq,
you will need to obtain the Java Developer Package from Apple ADC
at http://connect.apple.com/.
EOS
end
end
|
#coding: utf-8
require 'spec_helper'
require 'raptor-io/socket'
describe RaptorIO::Protocol::HTTP::Client do
before :all do
WebServers.start :client_close_connection
WebServers.start :https
WebServers.start :default
@https_url = WebServers.url_for(:https)
end
before(:each) do
RaptorIO::Protocol::HTTP::Request::Manipulators.reset
RaptorIO::Protocol::HTTP::Request::Manipulators.library = manipulator_fixtures_path
end
let(:url) { WebServers.url_for(:default) }
let(:switch_board) { RaptorIO::Socket::SwitchBoard.new }
let(:options) { {} }
subject(:client) do
described_class.new(
{ switch_board: switch_board }.merge(options)
)
end
describe '#initialize' do
describe :ssl_version do
let(:options) do
{ ssl_version: 'stuff' }
end
it 'sets the SSL version to use' do
client.ssl_version.should == 'stuff'
end
end
describe :ssl_verify_mode do
let(:options) do
{ ssl_verify_mode: 'stuff' }
end
it 'sets the SSL version to use' do
client.ssl_verify_mode.should == 'stuff'
end
end
describe :ssl_context do
let(:options) do
{ ssl_context: 'stuff' }
end
it 'sets the SSL version to use' do
client.ssl_context.should == 'stuff'
end
end
describe :manipulators do
it 'defaults to an empty Hash' do
client.manipulators.should == {}
end
context 'when the options are invalid' do
it 'raises RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions' do
expect do
described_class.new(
switch_board: switch_board,
manipulators: {
options_validator: { mandatory_string: 12 }
}
)
end.to raise_error RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions
end
end
context 'with manipulators' do
let(:manipulators) do
{ 'manifoolators/fooer' => { times: 15 } }
end
let(:options) do
{ manipulators: manipulators }
end
it 'sets the manipulators option' do
client.manipulators.should == manipulators
end
context 'when a request is queued' do
it 'runs the configured manipulators' do
request = RaptorIO::Protocol::HTTP::Request.new(url: "#{url}/")
client.queue(request)
request.url.should == "#{url}/" + ('foo' * 15)
end
end
end
end
describe :timeout do
context 'without a value' do
it 'defaults to 10' do
client.timeout.should == 10
end
end
context 'with a value' do
let(:options) do
{ timeout: 1 }
end
it 'sets the timeout option' do
client.timeout.should == 1
end
context 'when a timeout occurs' do
it 'raises RaptorIO::Error::Timeout', speed: 'slow' do
expect {
client.get("#{url}/long-sleep", mode: :sync)
}.to raise_error RaptorIO::Error::Timeout
end
end
end
end
describe :concurrency do
it 'defaults to 20' do
client.concurrency.should == 20
end
context 'with a value', focus:true do
let(:options) do
{ concurrency: 10 }
end
let(:url) do
WebServers.url_for(:default) + "/sleep"
end
it 'sets the request concurrency option' do
client.concurrency.should == 10
end
it 'is faster with 20 than with 1', speed: 'slow' do
cnt = 0
times = 10
client.concurrency = 1
times.times do
client.get url do |response|
expect(response.error).to be_nil
cnt += 1
end
end
t = Time.now
client.run
runtime_1 = Time.now - t
cnt.should == times
cnt = 0
client.concurrency = 20
times.times do
client.get url do |response|
expect(response.error).to be_nil
cnt += 1
end
end
t = Time.now
client.run
runtime_2 = Time.now - t
cnt.should == times
runtime_1.should > runtime_2
end
end
end
describe :user_agent do
context 'without a value' do
it "defaults to 'RaptorIO::HTTP/#{RaptorIO::VERSION}'" do
client.user_agent.should == "RaptorIO::HTTP/#{RaptorIO::VERSION}"
end
end
context 'with a value' do
let(:ua) { 'Stuff' }
let(:options) do
{ user_agent: ua }
end
it 'sets the user-agent option' do
client.user_agent.should == ua
end
it 'sets the User-Agent for the requests' do
client.request(url).headers['User-Agent'].should == ua
end
end
end
end
describe '#update_manipulators' do
context 'when the options are invalid' do
it 'raises RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions' do
expect do
client.update_manipulators(options_validator: { mandatory_string: 12 })
end.to raise_error RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions
end
end
it 'updates the client-wide manipulators' do
manipulators = { 'manifoolators/fooer' => { times: 16 } }
client.update_manipulators(manipulators)
client.manipulators.should == manipulators
end
end
describe '#datastore' do
it 'returns a hash' do
client.datastore.should == {}
end
it 'has empty hashes as default values' do
client.datastore['stuff'].should == {}
end
end
describe '#concurrency=' do
it 'sets the concurrency option' do
client.concurrency.should_not == 10
client.concurrency = 10
client.concurrency.should == 10
end
end
describe '#user_agent=' do
it 'sets the user_agent option' do
ua = 'stuff'
client.user_agent.should_not == ua
client.user_agent = ua
client.user_agent.should == ua
end
end
describe '#request' do
context "when using SSL" do
let(:options) do
{ ssl_version: :SSLv3 }
end
it 'gets a response' do
res = client.get(@https_url, mode: :sync)
res.should be_kind_of RaptorIO::Protocol::HTTP::Response
res.code.should == 200
res.body.should == 'Stuff...'
end
end
it 'handles responses without body (1xx, 204, 304)' do
client.get("#{url}/204", mode: :sync).should be_kind_of RaptorIO::Protocol::HTTP::Response
end
it 'properly transmits raw binary data' do
client.get("#{url}/echo_body",
raw: true,
mode: :sync,
body: "\ff\ff"
).body.should == "\ff\ff"
end
it 'properly transmits raw multibyte data' do
client.get("#{url}/echo_body",
raw: true,
mode: :sync,
body: 'τεστ'
).body.should == 'τεστ'
end
it 'forwards the given options to the Request object' do
options = { parameters: { 'name' => 'value' }}
client.request('/blah/', options).parameters.should == options[:parameters]
end
context 'when passed a block' do
it 'sets it as a callback' do
passed_response = nil
response = RaptorIO::Protocol::HTTP::Response.new(url: url)
request = client.request('/blah/') { |res| passed_response = res }
request.handle_response(response)
passed_response.should == response
end
end
describe 'option' do
describe :manipulators do
context 'when the options are invalid' do
it 'raises RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions' do
expect do
client.get("#{url}/",
manipulators: { options_validator: { mandatory_string: 12 } }
)
end.to raise_error RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions
end
end
it 'loads and configures the given manipulators' do
request = client.get("#{url}/",
manipulators: {
'manifoolators/fooer' => { times: 10 }
}
)
request.url.should == "#{url}/" + ('foo' * 10)
end
end
describe :cookies do
context Hash do
it 'formats and sets request cookies' do
client.get("#{url}/cookies",
cookies: {
'name' => 'value',
'name2' => 'value2'
},
mode: :sync
).body.should == 'name=value;name2=value2'
end
end
context String do
it 'sets request cookies' do
client.get("#{url}/cookies",
cookies: 'name=value;name2=value2',
mode: :sync
).body.should == 'name=value;name2=value2'
end
end
end
describe :continue do
context 'default' do
it 'handles responses with status "100" automatically' do
body = 'stuff-here'
client.get("#{url}/100",
headers: {
'Expect' => '100-continue'
},
body: body,
mode: :sync
).body.should == body
end
end
context true do
it 'handles responses with status "100" automatically' do
body = 'stuff-here'
client.get("#{url}/100",
headers: {
'Expect' => '100-continue'
},
body: body,
continue: true,
mode: :sync
).body.should == body
end
end
context false do
it 'does not handle responses with status "100" automatically' do
body = 'stuff-here'
client.get("#{url}/100",
headers: {
'Expect' => '100-continue'
},
body: body,
continue: false,
mode: :sync
).code.should == 100
end
end
end
describe :timeout do
it 'handles timeouts progressively and in groups', speed: 'slow' do
2.times do
client.get("#{url}/long-sleep", timeout: 20) do |response|
response.error.should be_nil
end
end
2.times do
client.get("#{url}/long-sleep", timeout: 2) do |response|
response.error.should be_kind_of RaptorIO::Error::Timeout
end
end
2.times do
client.get("#{url}/long-sleep", timeout: 3) do |response|
response.error.should be_kind_of RaptorIO::Error::Timeout
end
end
2.times do
client.get("#{url}/long-sleep", timeout: 7) do |response|
response.error.should be_nil
end
end
2.times do
client.get("#{url}/long-sleep", timeout: 10) do |response|
response.error.should be_nil
end
end
t = Time.now
client.run
runtime = Time.now - t
expect(runtime).to be_between(5.0, 7.0)
end
context 'when a timeout occurs in sync mode' do
let(:options) do
{ timeout: 1 }
end
it 'raises RaptorIO::Error::Timeout', speed: 'slow' do
expect {
client.get("#{url}/long-sleep", mode: :sync)
}.to raise_error RaptorIO::Error::Timeout
end
end
end
describe :mode do
describe :sync do
it 'performs the request synchronously and returns the response' do
options = {
parameters: { 'name' => 'value' },
mode: :sync
}
response = client.request(url, options)
response.should be_kind_of RaptorIO::Protocol::HTTP::Response
response.request.parameters.should == options[:parameters]
end
end
end
end
it 'increments the queue size' do
client.queue_size.should == 0
client.request('/blah/')
client.queue_size.should == 1
end
it 'returns the request' do
client.request('/blah/').should be_kind_of RaptorIO::Protocol::HTTP::Request
end
it 'treats a closed connection as a signal for end of a response' do
url = WebServers.url_for(:client_close_connection)
client.get(url, mode: :sync).body.should == "Success\n.\n"
client.get(url, mode: :sync).body.should == "Success\n.\n"
client.get(url, mode: :sync).body.should == "Success\n.\n"
end
describe 'Content-Encoding' do
it 'supports gzip' do
client.get("#{url}/gzip", mode: :sync).body.should == 'gzip'
end
it 'supports deflate' do
client.get("#{url}/deflate", mode: :sync).body.should == 'deflate'
end
end
describe 'Transfer-Encoding' do
context 'supports' do
it 'chunked' do
res = client.get("#{url}/chunked", mode: :sync)
res.body.should == "foo\rbarz\n#{"asdf"*20}"
res.headers.should_not include 'Transfer-Encoding'
res.headers['Content-Length'].to_i.should == res.body.size
end
end
end
end
describe '#get' do
it 'queues a GET request' do
client.get('/blah/').http_method.should == :get
end
end
describe '#post' do
it 'queues a POST request' do
client.post('/blah/').http_method.should == :post
end
end
describe '#queue_size' do
it 'returns the amount of queued requests' do
client.queue_size.should == 0
10.times { client.request('/') }
client.queue_size.should == 10
end
end
describe '#queue' do
it 'queues a request' do
client.queue_size.should == 0
client.queue(RaptorIO::Protocol::HTTP::Request.new(url: url))
client.queue_size.should == 1
end
it 'returns the queued request' do
request = RaptorIO::Protocol::HTTP::Request.new(url: url)
client.queue(request).should == request
end
describe :manipulators do
context 'when the options are invalid' do
it 'raises RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions' do
expect do
request = RaptorIO::Protocol::HTTP::Request.new(url: "#{url}/")
client.queue(request, options_validator: { mandatory_string: 12 })
end.to raise_error RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions
end
end
it 'loads and configures the given manipulators' do
request = RaptorIO::Protocol::HTTP::Request.new(url: "#{url}/")
client.queue(request, 'manifoolators/fooer' => { times: 10 })
request.url.should == "#{url}/" + ('foo' * 10)
end
end
end
describe '#<<' do
it 'alias of #queue' do
client.queue_size.should == 0
client << RaptorIO::Protocol::HTTP::Request.new(url: url)
client.queue_size.should == 1
end
end
describe '#run' do
it 'runs all the queued requests' do
cnt = 0
times = 2
times.times do
client.get(url) do |r|
cnt += 1
end
end
client.run
cnt.should == times
end
it 'runs requests queued via callbacks' do
called = false
client.get(url) do
client.get(url) do
called = true
end
end
client.run
called.should be_true
end
end
end
Un-focus
#coding: utf-8
require 'spec_helper'
require 'raptor-io/socket'
describe RaptorIO::Protocol::HTTP::Client do
before :all do
WebServers.start :client_close_connection
WebServers.start :https
WebServers.start :default
@https_url = WebServers.url_for(:https)
end
before(:each) do
RaptorIO::Protocol::HTTP::Request::Manipulators.reset
RaptorIO::Protocol::HTTP::Request::Manipulators.library = manipulator_fixtures_path
end
let(:url) { WebServers.url_for(:default) }
let(:switch_board) { RaptorIO::Socket::SwitchBoard.new }
let(:options) { {} }
subject(:client) do
described_class.new(
{ switch_board: switch_board }.merge(options)
)
end
describe '#initialize' do
describe :ssl_version do
let(:options) do
{ ssl_version: 'stuff' }
end
it 'sets the SSL version to use' do
client.ssl_version.should == 'stuff'
end
end
describe :ssl_verify_mode do
let(:options) do
{ ssl_verify_mode: 'stuff' }
end
it 'sets the SSL version to use' do
client.ssl_verify_mode.should == 'stuff'
end
end
describe :ssl_context do
let(:options) do
{ ssl_context: 'stuff' }
end
it 'sets the SSL version to use' do
client.ssl_context.should == 'stuff'
end
end
describe :manipulators do
it 'defaults to an empty Hash' do
client.manipulators.should == {}
end
context 'when the options are invalid' do
it 'raises RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions' do
expect do
described_class.new(
switch_board: switch_board,
manipulators: {
options_validator: { mandatory_string: 12 }
}
)
end.to raise_error RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions
end
end
context 'with manipulators' do
let(:manipulators) do
{ 'manifoolators/fooer' => { times: 15 } }
end
let(:options) do
{ manipulators: manipulators }
end
it 'sets the manipulators option' do
client.manipulators.should == manipulators
end
context 'when a request is queued' do
it 'runs the configured manipulators' do
request = RaptorIO::Protocol::HTTP::Request.new(url: "#{url}/")
client.queue(request)
request.url.should == "#{url}/" + ('foo' * 15)
end
end
end
end
describe :timeout do
context 'without a value' do
it 'defaults to 10' do
client.timeout.should == 10
end
end
context 'with a value' do
let(:options) do
{ timeout: 1 }
end
it 'sets the timeout option' do
client.timeout.should == 1
end
context 'when a timeout occurs' do
it 'raises RaptorIO::Error::Timeout', speed: 'slow' do
expect {
client.get("#{url}/long-sleep", mode: :sync)
}.to raise_error RaptorIO::Error::Timeout
end
end
end
end
describe :concurrency do
it 'defaults to 20' do
client.concurrency.should == 20
end
context 'with a value' do
let(:options) do
{ concurrency: 10 }
end
let(:url) do
WebServers.url_for(:default) + "/sleep"
end
it 'sets the request concurrency option' do
client.concurrency.should == 10
end
it 'is faster with 20 than with 1', speed: 'slow' do
cnt = 0
times = 10
client.concurrency = 1
times.times do
client.get url do |response|
expect(response.error).to be_nil
cnt += 1
end
end
t = Time.now
client.run
runtime_1 = Time.now - t
cnt.should == times
cnt = 0
client.concurrency = 20
times.times do
client.get url do |response|
expect(response.error).to be_nil
cnt += 1
end
end
t = Time.now
client.run
runtime_2 = Time.now - t
cnt.should == times
runtime_1.should > runtime_2
end
end
end
describe :user_agent do
context 'without a value' do
it "defaults to 'RaptorIO::HTTP/#{RaptorIO::VERSION}'" do
client.user_agent.should == "RaptorIO::HTTP/#{RaptorIO::VERSION}"
end
end
context 'with a value' do
let(:ua) { 'Stuff' }
let(:options) do
{ user_agent: ua }
end
it 'sets the user-agent option' do
client.user_agent.should == ua
end
it 'sets the User-Agent for the requests' do
client.request(url).headers['User-Agent'].should == ua
end
end
end
end
describe '#update_manipulators' do
context 'when the options are invalid' do
it 'raises RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions' do
expect do
client.update_manipulators(options_validator: { mandatory_string: 12 })
end.to raise_error RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions
end
end
it 'updates the client-wide manipulators' do
manipulators = { 'manifoolators/fooer' => { times: 16 } }
client.update_manipulators(manipulators)
client.manipulators.should == manipulators
end
end
describe '#datastore' do
it 'returns a hash' do
client.datastore.should == {}
end
it 'has empty hashes as default values' do
client.datastore['stuff'].should == {}
end
end
describe '#concurrency=' do
it 'sets the concurrency option' do
client.concurrency.should_not == 10
client.concurrency = 10
client.concurrency.should == 10
end
end
describe '#user_agent=' do
it 'sets the user_agent option' do
ua = 'stuff'
client.user_agent.should_not == ua
client.user_agent = ua
client.user_agent.should == ua
end
end
describe '#request' do
context "when using SSL" do
let(:options) do
{ ssl_version: :SSLv3 }
end
it 'gets a response' do
res = client.get(@https_url, mode: :sync)
res.should be_kind_of RaptorIO::Protocol::HTTP::Response
res.code.should == 200
res.body.should == 'Stuff...'
end
end
it 'handles responses without body (1xx, 204, 304)' do
client.get("#{url}/204", mode: :sync).should be_kind_of RaptorIO::Protocol::HTTP::Response
end
it 'properly transmits raw binary data' do
client.get("#{url}/echo_body",
raw: true,
mode: :sync,
body: "\ff\ff"
).body.should == "\ff\ff"
end
it 'properly transmits raw multibyte data' do
client.get("#{url}/echo_body",
raw: true,
mode: :sync,
body: 'τεστ'
).body.should == 'τεστ'
end
it 'forwards the given options to the Request object' do
options = { parameters: { 'name' => 'value' }}
client.request('/blah/', options).parameters.should == options[:parameters]
end
context 'when passed a block' do
it 'sets it as a callback' do
passed_response = nil
response = RaptorIO::Protocol::HTTP::Response.new(url: url)
request = client.request('/blah/') { |res| passed_response = res }
request.handle_response(response)
passed_response.should == response
end
end
describe 'option' do
describe :manipulators do
context 'when the options are invalid' do
it 'raises RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions' do
expect do
client.get("#{url}/",
manipulators: { options_validator: { mandatory_string: 12 } }
)
end.to raise_error RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions
end
end
it 'loads and configures the given manipulators' do
request = client.get("#{url}/",
manipulators: {
'manifoolators/fooer' => { times: 10 }
}
)
request.url.should == "#{url}/" + ('foo' * 10)
end
end
describe :cookies do
context Hash do
it 'formats and sets request cookies' do
client.get("#{url}/cookies",
cookies: {
'name' => 'value',
'name2' => 'value2'
},
mode: :sync
).body.should == 'name=value;name2=value2'
end
end
context String do
it 'sets request cookies' do
client.get("#{url}/cookies",
cookies: 'name=value;name2=value2',
mode: :sync
).body.should == 'name=value;name2=value2'
end
end
end
describe :continue do
context 'default' do
it 'handles responses with status "100" automatically' do
body = 'stuff-here'
client.get("#{url}/100",
headers: {
'Expect' => '100-continue'
},
body: body,
mode: :sync
).body.should == body
end
end
context true do
it 'handles responses with status "100" automatically' do
body = 'stuff-here'
client.get("#{url}/100",
headers: {
'Expect' => '100-continue'
},
body: body,
continue: true,
mode: :sync
).body.should == body
end
end
context false do
it 'does not handle responses with status "100" automatically' do
body = 'stuff-here'
client.get("#{url}/100",
headers: {
'Expect' => '100-continue'
},
body: body,
continue: false,
mode: :sync
).code.should == 100
end
end
end
describe :timeout do
it 'handles timeouts progressively and in groups', speed: 'slow' do
2.times do
client.get("#{url}/long-sleep", timeout: 20) do |response|
response.error.should be_nil
end
end
2.times do
client.get("#{url}/long-sleep", timeout: 2) do |response|
response.error.should be_kind_of RaptorIO::Error::Timeout
end
end
2.times do
client.get("#{url}/long-sleep", timeout: 3) do |response|
response.error.should be_kind_of RaptorIO::Error::Timeout
end
end
2.times do
client.get("#{url}/long-sleep", timeout: 7) do |response|
response.error.should be_nil
end
end
2.times do
client.get("#{url}/long-sleep", timeout: 10) do |response|
response.error.should be_nil
end
end
t = Time.now
client.run
runtime = Time.now - t
expect(runtime).to be_between(5.0, 7.0)
end
context 'when a timeout occurs in sync mode' do
let(:options) do
{ timeout: 1 }
end
it 'raises RaptorIO::Error::Timeout', speed: 'slow' do
expect {
client.get("#{url}/long-sleep", mode: :sync)
}.to raise_error RaptorIO::Error::Timeout
end
end
end
describe :mode do
describe :sync do
it 'performs the request synchronously and returns the response' do
options = {
parameters: { 'name' => 'value' },
mode: :sync
}
response = client.request(url, options)
response.should be_kind_of RaptorIO::Protocol::HTTP::Response
response.request.parameters.should == options[:parameters]
end
end
end
end
it 'increments the queue size' do
client.queue_size.should == 0
client.request('/blah/')
client.queue_size.should == 1
end
it 'returns the request' do
client.request('/blah/').should be_kind_of RaptorIO::Protocol::HTTP::Request
end
it 'treats a closed connection as a signal for end of a response' do
url = WebServers.url_for(:client_close_connection)
client.get(url, mode: :sync).body.should == "Success\n.\n"
client.get(url, mode: :sync).body.should == "Success\n.\n"
client.get(url, mode: :sync).body.should == "Success\n.\n"
end
describe 'Content-Encoding' do
it 'supports gzip' do
client.get("#{url}/gzip", mode: :sync).body.should == 'gzip'
end
it 'supports deflate' do
client.get("#{url}/deflate", mode: :sync).body.should == 'deflate'
end
end
describe 'Transfer-Encoding' do
context 'supports' do
it 'chunked' do
res = client.get("#{url}/chunked", mode: :sync)
res.body.should == "foo\rbarz\n#{"asdf"*20}"
res.headers.should_not include 'Transfer-Encoding'
res.headers['Content-Length'].to_i.should == res.body.size
end
end
end
end
describe '#get' do
it 'queues a GET request' do
client.get('/blah/').http_method.should == :get
end
end
describe '#post' do
it 'queues a POST request' do
client.post('/blah/').http_method.should == :post
end
end
describe '#queue_size' do
it 'returns the amount of queued requests' do
client.queue_size.should == 0
10.times { client.request('/') }
client.queue_size.should == 10
end
end
describe '#queue' do
it 'queues a request' do
client.queue_size.should == 0
client.queue(RaptorIO::Protocol::HTTP::Request.new(url: url))
client.queue_size.should == 1
end
it 'returns the queued request' do
request = RaptorIO::Protocol::HTTP::Request.new(url: url)
client.queue(request).should == request
end
describe :manipulators do
context 'when the options are invalid' do
it 'raises RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions' do
expect do
request = RaptorIO::Protocol::HTTP::Request.new(url: "#{url}/")
client.queue(request, options_validator: { mandatory_string: 12 })
end.to raise_error RaptorIO::Protocol::HTTP::Request::Manipulator::Error::InvalidOptions
end
end
it 'loads and configures the given manipulators' do
request = RaptorIO::Protocol::HTTP::Request.new(url: "#{url}/")
client.queue(request, 'manifoolators/fooer' => { times: 10 })
request.url.should == "#{url}/" + ('foo' * 10)
end
end
end
describe '#<<' do
it 'alias of #queue' do
client.queue_size.should == 0
client << RaptorIO::Protocol::HTTP::Request.new(url: url)
client.queue_size.should == 1
end
end
describe '#run' do
it 'runs all the queued requests' do
cnt = 0
times = 2
times.times do
client.get(url) do |r|
cnt += 1
end
end
client.run
cnt.should == times
end
it 'runs requests queued via callbacks' do
called = false
client.get(url) do
client.get(url) do
called = true
end
end
client.run
called.should be_true
end
end
end
|
require 'formula'
class Zopfli < Formula
homepage 'https://code.google.com/p/zopfli/'
url 'https://zopfli.googlecode.com/files/zopfli-1.0.0.zip'
sha1 '98ea00216e296bf3a13e241d7bc69490042ea7ce'
head 'https://code.google.com/p/zopfli/', :using => :git
def install
# Makefile hardcodes gcc
inreplace 'Makefile', 'gcc', ENV.cc
system 'make'
bin.install 'zopfli'
if build.head?
system 'make', 'zopflipng'
bin.install 'zopflipng'
end
end
test do
system "#{bin}/zopfli"
end
end
zopfli: fix non-standard makefile name
Non-standard `makefile` prohibited build on case-sensitive filesystem.
See: https://code.google.com/p/zopfli/source/browse/
Closes #26348.
Signed-off-by: Mike McQuaid <a17fed27eaa842282862ff7c1b9c8395a26ac320@mikemcquaid.com>
require 'formula'
class Zopfli < Formula
homepage 'https://code.google.com/p/zopfli/'
url 'https://zopfli.googlecode.com/files/zopfli-1.0.0.zip'
sha1 '98ea00216e296bf3a13e241d7bc69490042ea7ce'
head 'https://code.google.com/p/zopfli/', :using => :git
def install
# Makefile hardcodes gcc
inreplace 'makefile', 'gcc', ENV.cc
system 'make', '-f', 'makefile'
bin.install 'zopfli'
if build.head?
system 'make', '-f', 'makefile', 'zopflipng'
bin.install 'zopflipng'
end
end
test do
system "#{bin}/zopfli"
end
end
|
# frozen_string_literal: true
require "rails_helper"
describe CharacterShowReflex do
subject { described_class.new(double) }
it { should be_an(ApplicationReflex) }
describe "#update" do
let(:character_id) { "1337512245" }
let(:element) do
StimulusReflex::Element.new("data-reflex" => "click->CharacterShowReflex#update",
"data-id" => "1337512245")
end
subject { described_class.new(double, element: element) }
before do
#
# CharacterImporter.new(character_id).import
#
expect(CharacterImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterSkillsImporter.new(character_id).import
#
expect(CharacterSkillsImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterWalletImporter.new(character_id).import
#
expect(CharacterWalletImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterLocationImporter.new(character_id).import
#
expect(CharacterLocationImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterShipImporter.new(character_id).import
#
expect(CharacterShipImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterAttributesImporter.new(character_id).import
#
expect(CharacterAttributesImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterImplantsImporter.new(character_id).import
#
expect(CharacterImplantsImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
specify { expect { subject.update }.not_to raise_error }
end
end
Fix spec
# frozen_string_literal: true
require "rails_helper"
describe CharacterShowReflex do
subject { described_class.new(double) }
it { should be_an(ApplicationReflex) }
describe "#update" do
let(:character_id) { "1337512245" }
let(:data) do
{
"dataset" => {
"id" => "1337512245"
}
}
end
let(:element) { StimulusReflex::Element.new(data) }
subject { described_class.new(double, element: element) }
before do
#
# CharacterImporter.new(character_id).import
#
expect(CharacterImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterSkillsImporter.new(character_id).import
#
expect(CharacterSkillsImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterWalletImporter.new(character_id).import
#
expect(CharacterWalletImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterLocationImporter.new(character_id).import
#
expect(CharacterLocationImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterShipImporter.new(character_id).import
#
expect(CharacterShipImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterAttributesImporter.new(character_id).import
#
expect(CharacterAttributesImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
before do
#
# CharacterImplantsImporter.new(character_id).import
#
expect(CharacterImplantsImporter).to receive(:new).with(character_id) do
double.tap do |a|
expect(a).to receive(:import)
end
end
end
specify { expect { subject.update }.not_to raise_error }
end
end
|
# This script is loaded by formula_installer as a separate instance.
# Thrown exceptions are propogated back to the parent process over a pipe
old_trap = trap("INT") { exit! 130 }
require "global"
require "cxxstdlib"
require "keg"
require "extend/ENV"
require "debrew" if ARGV.debug?
require "fcntl"
class Build
attr_reader :formula, :deps, :reqs
def initialize(formula)
@formula = formula
if ARGV.ignore_deps?
@deps = []
@reqs = []
else
@deps = expand_deps
@reqs = expand_reqs
end
end
def post_superenv_hacks
# Only allow Homebrew-approved directories into the PATH, unless
# a formula opts-in to allowing the user's path.
if formula.env.userpaths? || reqs.any? { |rq| rq.env.userpaths? }
ENV.userpaths!
end
end
def pre_superenv_hacks
# Allow a formula to opt-in to the std environment.
if (formula.env.std? || deps.any? { |d| d.name == "scons" }) && ARGV.env != "super"
ARGV.unshift "--env=std"
end
end
def effective_build_options_for(dependent)
args = dependent.build.used_options
args |= Tab.for_formula(dependent).used_options
BuildOptions.new(args, dependent.options)
end
def expand_reqs
formula.recursive_requirements do |dependent, req|
build = effective_build_options_for(dependent)
if (req.optional? || req.recommended?) && build.without?(req)
Requirement.prune
elsif req.build? && dependent != formula
Requirement.prune
elsif req.satisfied? && req.default_formula? && (dep = req.to_dependency).installed?
deps << dep
Requirement.prune
end
end
end
def expand_deps
formula.recursive_dependencies do |dependent, dep|
build = effective_build_options_for(dependent)
if (dep.optional? || dep.recommended?) && build.without?(dep)
Dependency.prune
elsif dep.build? && dependent != formula
Dependency.prune
elsif dep.build?
Dependency.keep_but_prune_recursive_deps
end
end
end
def install
keg_only_deps = deps.map(&:to_formula).select(&:keg_only?)
deps.map(&:to_formula).each do |dep|
fixopt(dep) unless dep.opt_prefix.directory?
end
pre_superenv_hacks
ENV.activate_extensions!
if superenv?
ENV.keg_only_deps = keg_only_deps.map(&:name)
ENV.deps = deps.map { |d| d.to_formula.name }
ENV.x11 = reqs.any? { |rq| rq.kind_of?(X11Dependency) }
ENV.setup_build_environment(formula)
post_superenv_hacks
reqs.each(&:modify_build_environment)
deps.each(&:modify_build_environment)
else
ENV.setup_build_environment(formula)
reqs.each(&:modify_build_environment)
deps.each(&:modify_build_environment)
keg_only_deps.each do |dep|
ENV.prepend_path "PATH", dep.opt_bin.to_s
ENV.prepend_path "PKG_CONFIG_PATH", "#{dep.opt_lib}/pkgconfig"
ENV.prepend_path "PKG_CONFIG_PATH", "#{dep.opt_share}/pkgconfig"
ENV.prepend_path "ACLOCAL_PATH", "#{dep.opt_share}/aclocal"
ENV.prepend_path "CMAKE_PREFIX_PATH", dep.opt_prefix.to_s
ENV.prepend "LDFLAGS", "-L#{dep.opt_lib}" if dep.opt_lib.directory?
ENV.prepend "CPPFLAGS", "-I#{dep.opt_include}" if dep.opt_include.directory?
end
end
formula.brew do
if ARGV.flag? '--git'
system "git", "init"
system "git", "add", "-A"
end
if ARGV.interactive?
ohai "Entering interactive mode"
puts "Type `exit' to return and finalize the installation"
puts "Install to this prefix: #{formula.prefix}"
if ARGV.flag? '--git'
puts "This directory is now a git repo. Make your changes and then use:"
puts " git diff | pbcopy"
puts "to copy the diff to the clipboard."
end
interactive_shell(formula)
else
formula.prefix.mkpath
formula.resources.each { |r| r.extend(ResourceDebugger) } if ARGV.debug?
begin
formula.install
rescue Exception => e
if ARGV.debug?
debrew(e, formula)
else
raise
end
end
stdlibs = detect_stdlibs
Tab.create(formula, ENV.compiler, stdlibs.first, formula.build).write
# Find and link metafiles
formula.prefix.install_metafiles Pathname.pwd
end
end
end
def detect_stdlibs
keg = Keg.new(formula.prefix)
CxxStdlib.check_compatibility(formula, deps, keg, ENV.compiler)
# The stdlib recorded in the install receipt is used during dependency
# compatibility checks, so we only care about the stdlib that libraries
# link against.
keg.detect_cxx_stdlibs(:skip_executables => true)
end
def fixopt f
path = if f.linked_keg.directory? and f.linked_keg.symlink?
f.linked_keg.resolved_path
elsif f.prefix.directory?
f.prefix
elsif (kids = f.rack.children).size == 1 and kids.first.directory?
kids.first
else
raise
end
Keg.new(path).optlink
rescue StandardError
raise "#{f.opt_prefix} not present or broken\nPlease reinstall #{f}. Sorry :("
end
end
error_pipe = IO.new(ENV["HOMEBREW_ERROR_PIPE"].to_i, "w")
error_pipe.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
# Invalidate the current sudo timestamp in case a build script calls sudo
system "/usr/bin/sudo", "-k"
trap("INT", old_trap)
begin
Build.new(ARGV.formulae.first).install
rescue Exception => e
e.continuation = nil if ARGV.debug?
Marshal.dump(e, error_pipe)
error_pipe.close
exit! 1
end
Explicitly pass options into the build object
# This script is loaded by formula_installer as a separate instance.
# Thrown exceptions are propogated back to the parent process over a pipe
old_trap = trap("INT") { exit! 130 }
require "global"
require "build_options"
require "cxxstdlib"
require "keg"
require "extend/ENV"
require "debrew" if ARGV.debug?
require "fcntl"
class Build
attr_reader :formula, :deps, :reqs
def initialize(formula, options)
@formula = formula
@formula.build = BuildOptions.new(options, formula.options)
if ARGV.ignore_deps?
@deps = []
@reqs = []
else
@deps = expand_deps
@reqs = expand_reqs
end
end
def post_superenv_hacks
# Only allow Homebrew-approved directories into the PATH, unless
# a formula opts-in to allowing the user's path.
if formula.env.userpaths? || reqs.any? { |rq| rq.env.userpaths? }
ENV.userpaths!
end
end
def pre_superenv_hacks
# Allow a formula to opt-in to the std environment.
if (formula.env.std? || deps.any? { |d| d.name == "scons" }) && ARGV.env != "super"
ARGV.unshift "--env=std"
end
end
def effective_build_options_for(dependent)
args = dependent.build.used_options
args |= Tab.for_formula(dependent).used_options
BuildOptions.new(args, dependent.options)
end
def expand_reqs
formula.recursive_requirements do |dependent, req|
build = effective_build_options_for(dependent)
if (req.optional? || req.recommended?) && build.without?(req)
Requirement.prune
elsif req.build? && dependent != formula
Requirement.prune
elsif req.satisfied? && req.default_formula? && (dep = req.to_dependency).installed?
deps << dep
Requirement.prune
end
end
end
def expand_deps
formula.recursive_dependencies do |dependent, dep|
build = effective_build_options_for(dependent)
if (dep.optional? || dep.recommended?) && build.without?(dep)
Dependency.prune
elsif dep.build? && dependent != formula
Dependency.prune
elsif dep.build?
Dependency.keep_but_prune_recursive_deps
end
end
end
def install
keg_only_deps = deps.map(&:to_formula).select(&:keg_only?)
deps.map(&:to_formula).each do |dep|
fixopt(dep) unless dep.opt_prefix.directory?
end
pre_superenv_hacks
ENV.activate_extensions!
if superenv?
ENV.keg_only_deps = keg_only_deps.map(&:name)
ENV.deps = deps.map { |d| d.to_formula.name }
ENV.x11 = reqs.any? { |rq| rq.kind_of?(X11Dependency) }
ENV.setup_build_environment(formula)
post_superenv_hacks
reqs.each(&:modify_build_environment)
deps.each(&:modify_build_environment)
else
ENV.setup_build_environment(formula)
reqs.each(&:modify_build_environment)
deps.each(&:modify_build_environment)
keg_only_deps.each do |dep|
ENV.prepend_path "PATH", dep.opt_bin.to_s
ENV.prepend_path "PKG_CONFIG_PATH", "#{dep.opt_lib}/pkgconfig"
ENV.prepend_path "PKG_CONFIG_PATH", "#{dep.opt_share}/pkgconfig"
ENV.prepend_path "ACLOCAL_PATH", "#{dep.opt_share}/aclocal"
ENV.prepend_path "CMAKE_PREFIX_PATH", dep.opt_prefix.to_s
ENV.prepend "LDFLAGS", "-L#{dep.opt_lib}" if dep.opt_lib.directory?
ENV.prepend "CPPFLAGS", "-I#{dep.opt_include}" if dep.opt_include.directory?
end
end
formula.brew do
if ARGV.flag? '--git'
system "git", "init"
system "git", "add", "-A"
end
if ARGV.interactive?
ohai "Entering interactive mode"
puts "Type `exit' to return and finalize the installation"
puts "Install to this prefix: #{formula.prefix}"
if ARGV.flag? '--git'
puts "This directory is now a git repo. Make your changes and then use:"
puts " git diff | pbcopy"
puts "to copy the diff to the clipboard."
end
interactive_shell(formula)
else
formula.prefix.mkpath
formula.resources.each { |r| r.extend(ResourceDebugger) } if ARGV.debug?
begin
formula.install
rescue Exception => e
if ARGV.debug?
debrew(e, formula)
else
raise
end
end
stdlibs = detect_stdlibs
Tab.create(formula, ENV.compiler, stdlibs.first, formula.build).write
# Find and link metafiles
formula.prefix.install_metafiles Pathname.pwd
end
end
end
def detect_stdlibs
keg = Keg.new(formula.prefix)
CxxStdlib.check_compatibility(formula, deps, keg, ENV.compiler)
# The stdlib recorded in the install receipt is used during dependency
# compatibility checks, so we only care about the stdlib that libraries
# link against.
keg.detect_cxx_stdlibs(:skip_executables => true)
end
def fixopt f
path = if f.linked_keg.directory? and f.linked_keg.symlink?
f.linked_keg.resolved_path
elsif f.prefix.directory?
f.prefix
elsif (kids = f.rack.children).size == 1 and kids.first.directory?
kids.first
else
raise
end
Keg.new(path).optlink
rescue StandardError
raise "#{f.opt_prefix} not present or broken\nPlease reinstall #{f}. Sorry :("
end
end
error_pipe = IO.new(ENV["HOMEBREW_ERROR_PIPE"].to_i, "w")
error_pipe.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
# Invalidate the current sudo timestamp in case a build script calls sudo
system "/usr/bin/sudo", "-k"
trap("INT", old_trap)
begin
formula = ARGV.formulae.first
options = Options.create(ARGV.options_only)
build = Build.new(formula, options)
build.install
rescue Exception => e
e.continuation = nil if ARGV.debug?
Marshal.dump(e, error_pipe)
error_pipe.close
exit! 1
end
|
Added initial specs for watch areas
# -*- encoding: utf-8 -*-
require 'helper'
describe SeeClickFix::Client::WatchAreas do
before do
@client = SeeClickFix::Client.new
end
end |
#!/usr/bin/ruby
# This script is called by formula_installer as a separate instance.
# Rationale: Formula can use __END__, Formula can change ENV
# Thrown exceptions are propogated back to the parent process over a pipe
ORIGINAL_PATHS = ENV['PATH'].split(':').map{ |p| File.expand_path p }
require 'global'
at_exit do
# the whole of everything must be run in at_exit because the formula has to
# be the run script as __END__ must work for *that* formula.
begin
raise $! if $! # an exception was already thrown when parsing the formula
require 'extend/ENV'
require 'hardware'
require 'keg'
ENV.extend(HomebrewEnvExtension)
ENV.setup_build_environment
# we must do this or tools like pkg-config won't get found by configure scripts etc.
ENV.prepend 'PATH', "#{HOMEBREW_PREFIX}/bin", ':' unless ORIGINAL_PATHS.include? "#{HOMEBREW_PREFIX}/bin"
# this is a safety measure for Xcode 4.3 which started not installing
# dev tools into /usr/bin as a default
ENV.prepend 'PATH', MacOS.dev_tools_path, ':' unless ORIGINAL_PATHS.include? MacOS.dev_tools_path
# Force any future invocations of sudo to require the user's password to be
# re-entered. This is in-case any build script call sudo. Certainly this is
# can be inconvenient for the user. But we need to be safe.
system "/usr/bin/sudo -k"
install(Formula.factory($0))
rescue Exception => e
if ENV['HOMEBREW_ERROR_PIPE']
pipe = IO.new(ENV['HOMEBREW_ERROR_PIPE'].to_i, 'w')
Marshal.dump(e, pipe)
pipe.close
exit! 1
else
onoe e
puts e.backtrace
exit! 2
end
end
end
def install f
f.recursive_deps.uniq.each do |dep|
dep = Formula.factory dep
if dep.keg_only?
ENV.prepend 'LDFLAGS', "-L#{dep.lib}"
ENV.prepend 'CPPFLAGS', "-I#{dep.include}"
ENV.prepend 'PATH', "#{dep.bin}", ':'
pcdir = dep.lib/'pkgconfig'
ENV.prepend 'PKG_CONFIG_PATH', pcdir, ':' if pcdir.directory?
acdir = dep.share/'aclocal'
ENV.prepend 'ACLOCAL_PATH', acdir, ':' if acdir.directory?
end
end
if f.fails_with? ENV.compiler
cs = CompilerSelector.new f
cs.select_compiler
cs.advise
end
f.brew do
if ARGV.flag? '--interactive'
ohai "Entering interactive mode"
puts "Type `exit' to return and finalize the installation"
puts "Install to this prefix: #{f.prefix}"
if ARGV.flag? '--git'
system "git init"
system "git add -A"
puts "This directory is now a git repo. Make your changes and then use:"
puts " git diff | pbcopy"
puts "to copy the diff to the clipboard."
end
interactive_shell f
nil
elsif ARGV.include? '--help'
system './configure --help'
exit $?
else
f.prefix.mkpath
f.install
FORMULA_META_FILES.each do |filename|
next if File.directory? filename
target_file = filename
target_file = "#{filename}.txt" if File.exists? "#{filename}.txt"
# Some software symlinks these files (see help2man.rb)
target_file = Pathname.new(target_file).resolved_path
f.prefix.install target_file => filename rescue nil
(f.prefix+file).chmod 0644 rescue nil
end
end
end
rescue Exception
if f.prefix.directory?
f.prefix.rmtree
f.rack.rmdir_if_possible
end
raise
end
Set close-on-exec on the error pipe
We use a pipe to marshal exceptions from the build script back to the
main Homebrew process; the associated file descriptor is stored in an
environment variable so that the script can figure out which descriptor
to use after being exec'd.
However, any child processes of the build script inherit this
descriptor (i.e. anything spawned via "system" by the formula during
installation). Normally this is not an issue, but if a formula executes
a long-running process such as a daemon, the main Homebrew process will
never see EOF on the error pipe because the daemon still has an open
descriptor.
We can fix this while preserving current behavior by setting the
close-on-exec flag on the build script's error pipe descriptor.
Signed-off-by: Jack Nagel <43386ce32af96f5c56f2a88e458cb94cebee3751@gmail.com>
#!/usr/bin/ruby
# This script is called by formula_installer as a separate instance.
# Rationale: Formula can use __END__, Formula can change ENV
# Thrown exceptions are propogated back to the parent process over a pipe
ORIGINAL_PATHS = ENV['PATH'].split(':').map{ |p| File.expand_path p }
require 'global'
at_exit do
# the whole of everything must be run in at_exit because the formula has to
# be the run script as __END__ must work for *that* formula.
begin
raise $! if $! # an exception was already thrown when parsing the formula
require 'extend/ENV'
require 'hardware'
require 'keg'
ENV.extend(HomebrewEnvExtension)
ENV.setup_build_environment
# we must do this or tools like pkg-config won't get found by configure scripts etc.
ENV.prepend 'PATH', "#{HOMEBREW_PREFIX}/bin", ':' unless ORIGINAL_PATHS.include? "#{HOMEBREW_PREFIX}/bin"
# this is a safety measure for Xcode 4.3 which started not installing
# dev tools into /usr/bin as a default
ENV.prepend 'PATH', MacOS.dev_tools_path, ':' unless ORIGINAL_PATHS.include? MacOS.dev_tools_path
# Force any future invocations of sudo to require the user's password to be
# re-entered. This is in-case any build script call sudo. Certainly this is
# can be inconvenient for the user. But we need to be safe.
system "/usr/bin/sudo -k"
if ENV['HOMEBREW_ERROR_PIPE']
require 'fcntl'
IO.new(ENV['HOMEBREW_ERROR_PIPE'].to_i, 'w').fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
end
install(Formula.factory($0))
rescue Exception => e
if ENV['HOMEBREW_ERROR_PIPE']
pipe = IO.new(ENV['HOMEBREW_ERROR_PIPE'].to_i, 'w')
Marshal.dump(e, pipe)
pipe.close
exit! 1
else
onoe e
puts e.backtrace
exit! 2
end
end
end
def install f
f.recursive_deps.uniq.each do |dep|
dep = Formula.factory dep
if dep.keg_only?
ENV.prepend 'LDFLAGS', "-L#{dep.lib}"
ENV.prepend 'CPPFLAGS', "-I#{dep.include}"
ENV.prepend 'PATH', "#{dep.bin}", ':'
pcdir = dep.lib/'pkgconfig'
ENV.prepend 'PKG_CONFIG_PATH', pcdir, ':' if pcdir.directory?
acdir = dep.share/'aclocal'
ENV.prepend 'ACLOCAL_PATH', acdir, ':' if acdir.directory?
end
end
if f.fails_with? ENV.compiler
cs = CompilerSelector.new f
cs.select_compiler
cs.advise
end
f.brew do
if ARGV.flag? '--interactive'
ohai "Entering interactive mode"
puts "Type `exit' to return and finalize the installation"
puts "Install to this prefix: #{f.prefix}"
if ARGV.flag? '--git'
system "git init"
system "git add -A"
puts "This directory is now a git repo. Make your changes and then use:"
puts " git diff | pbcopy"
puts "to copy the diff to the clipboard."
end
interactive_shell f
nil
elsif ARGV.include? '--help'
system './configure --help'
exit $?
else
f.prefix.mkpath
f.install
FORMULA_META_FILES.each do |filename|
next if File.directory? filename
target_file = filename
target_file = "#{filename}.txt" if File.exists? "#{filename}.txt"
# Some software symlinks these files (see help2man.rb)
target_file = Pathname.new(target_file).resolved_path
f.prefix.install target_file => filename rescue nil
(f.prefix+file).chmod 0644 rescue nil
end
end
end
rescue Exception
if f.prefix.directory?
f.prefix.rmtree
f.rack.rmdir_if_possible
end
raise
end
|
Specs for new EmbeddedPageService
require 'spec_helper'
describe EmbeddedPageService do
let(:enterprise_slug) { 'test-enterprise' }
let(:params) { { controller: 'enterprises', action: 'shop', id: enterprise_slug, embedded_shopfront: true } }
let(:session) { {} }
let(:request) { ActionController::TestRequest.new('HTTP_HOST' => 'ofn-instance.com', 'HTTP_REFERER' => 'https://embedding-enterprise.com') }
let(:response) { ActionController::TestResponse.new(200, 'X-Frame-Options' => 'DENY', 'Content-Security-Policy' => "frame-ancestors 'none'") }
let(:service) { EmbeddedPageService.new(params, session, request, response) }
before do
Spree::Config.set(
enable_embedded_shopfronts: true,
embedded_shopfronts_whitelist: 'embedding-enterprise.com example.com'
)
end
describe "#embed!" do
context "when the request's referer is in the whitelist" do
before { service.embed! }
it "sets the response headers to enables embedding requests from the embedding site" do
expect(response.headers).to_not include 'X-Frame-Options' => 'DENY'
expect(response.headers).to include 'Content-Security-Policy' => "frame-ancestors 'self' embedding-enterprise.com"
end
it "sets session variables" do
expect(session[:embedded_shopfront]).to eq true
expect(session[:embedding_domain]).to eq 'embedding-enterprise.com'
expect(session[:shopfront_redirect]).to eq '/' + enterprise_slug + '/shop?embedded_shopfront=true'
end
end
context "when embedding is enabled for a different site in the current session" do
before do
session[:embedding_domain] = 'another-enterprise.com'
session[:shopfront_redirect] = '/another-enterprise/shop?embedded_shopfront=true'
service.embed!
end
it "resets the session variables for the new request" do
expect(session[:embedded_shopfront]).to eq true
expect(session[:embedding_domain]).to eq 'embedding-enterprise.com'
expect(session[:shopfront_redirect]).to eq '/' + enterprise_slug + '/shop?embedded_shopfront=true'
end
end
context "when the request's referer is not in the whitelist" do
before do
Spree::Config.set(embedded_shopfronts_whitelist: 'example.com')
service.embed!
end
it "does not enable embedding" do
expect(response.headers['X-Frame-Options']).to eq 'DENY'
end
end
end
end
|
module MacOS extend self
MDITEM_BUNDLE_ID_KEY = "kMDItemCFBundleIdentifier"
def version
MACOS_VERSION
end
def cat
if mountain_lion?
:mountainlion
elsif lion?
:lion
elsif snow_leopard?
:snowleopard
elsif leopard?
:leopard
else
nil
end
end
def locate tool
# Don't call tools (cc, make, strip, etc.) directly!
# Give the name of the binary you look for as a string to this method
# in order to get the full path back as a Pathname.
tool = tool.to_s
@locate_cache ||= {}
return @locate_cache[tool] if @locate_cache.has_key? tool
if File.executable? "/usr/bin/#{tool}"
path = Pathname.new "/usr/bin/#{tool}"
else
# Xcrun was provided first with Xcode 4.3 and allows us to proxy
# tool usage thus avoiding various bugs.
p = `/usr/bin/xcrun -find #{tool} 2>/dev/null`.chomp unless Xcode.bad_xcode_select_path?
if !p.nil? and !p.empty? and File.executable? p
path = Pathname.new p
else
# This is for the use-case where xcode-select is not set up correctly
# with Xcode 4.3+. The tools in Xcode 4.3+ are split over two locations,
# usually xcrun would figure that out for us, but it won't work if
# xcode-select is not configured properly.
p = "#{dev_tools_path}/#{tool}"
if File.executable? p
path = Pathname.new p
else
# Otherwise lets look in the second location.
p = "#{xctoolchain_path}/usr/bin/#{tool}"
if File.executable? p
path = Pathname.new p
else
# We digged so deep but all is lost now.
path = nil
end
end
end
end
@locate_cache[tool] = path
return path
end
def dev_tools_path
@dev_tools_path ||= if File.exist? "/usr/bin/cc" and File.exist? "/usr/bin/make"
# probably a safe enough assumption (the unix way)
Pathname.new "/usr/bin"
# Note that the exit status of system "xcrun foo" isn't always accurate
elsif not Xcode.bad_xcode_select_path? and not `/usr/bin/xcrun -find make 2>/dev/null`.empty?
# Wherever "make" is there are the dev tools.
Pathname.new(`/usr/bin/xcrun -find make`.chomp).dirname
elsif File.exist? "#{Xcode.prefix}/usr/bin/make"
# cc stopped existing with Xcode 4.3, there are c89 and c99 options though
Pathname.new "#{Xcode.prefix}/usr/bin"
else
# Since we are pretty unrelenting in finding Xcode no matter where
# it hides, we can now throw in the towel.
opoo "You really should consult the `brew doctor`!"
""
end
end
def xctoolchain_path
# As of Xcode 4.3, some tools are located in the "xctoolchain" directory
@xctoolchain_path ||= begin
path = Pathname.new("#{Xcode.prefix}/Toolchains/XcodeDefault.xctoolchain")
# If only the CLT are installed, all tools will be under dev_tools_path,
# this path won't exist, and xctoolchain_path will be nil.
path if path.exist?
end
end
def sdk_path v=version
@sdk_path ||= {}
@sdk_path[v.to_s] ||= begin
path = if not Xcode.bad_xcode_select_path? and File.executable? "#{Xcode.folder}/usr/bin/make"
`#{locate('xcodebuild')} -version -sdk macosx#{v} Path 2>/dev/null`.strip
elsif File.directory? "/Developer/SDKs/MacOS#{v}.sdk"
# the old default (or wild wild west style)
"/Developer/SDKs/MacOS#{v}.sdk"
elsif File.directory? "#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX#{v}.sdk"
# Xcode.prefix is pretty smart, so lets look inside to find the sdk
"#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX#{v}.sdk"
end
Pathname.new(path) unless path.nil? or path.empty? or not File.directory? path
end
end
def default_cc
cc = locate 'cc'
Pathname.new(cc).realpath.basename.to_s rescue nil
end
def default_compiler
case default_cc
when /^gcc/ then :gcc
when /^llvm/ then :llvm
when "clang" then :clang
else
# guess :(
if Xcode.version >= "4.3"
:clang
elsif Xcode.version >= "4.2"
:llvm
else
:gcc
end
end
end
def gcc_40_build_version
@gcc_40_build_version ||= if locate("gcc-4.0")
`#{locate("gcc-4.0")} --version` =~ /build (\d{4,})/
$1.to_i
end
end
def gcc_42_build_version
@gcc_42_build_version ||= if locate("gcc-4.2") \
and not locate("gcc-4.2").realpath.basename.to_s =~ /^llvm/
`#{locate("gcc-4.2")} --version` =~ /build (\d{4,})/
$1.to_i
end
end
def llvm_build_version
# for Xcode 3 on OS X 10.5 this will not exist
# NOTE may not be true anymore but we can't test
@llvm_build_version ||= if locate("llvm-gcc")
`#{locate("llvm-gcc")} --version` =~ /LLVM build (\d{4,})/
$1.to_i
end
end
def clang_version
@clang_version ||= if locate("clang")
`#{locate("clang")} --version` =~ /clang version (\d\.\d)/
$1
end
end
def clang_build_version
@clang_build_version ||= if locate("clang")
`#{locate("clang")} --version` =~ %r[tags/Apple/clang-(\d{2,})]
$1.to_i
end
end
def macports_or_fink_installed?
# See these issues for some history:
# http://github.com/mxcl/homebrew/issues/#issue/13
# http://github.com/mxcl/homebrew/issues/#issue/41
# http://github.com/mxcl/homebrew/issues/#issue/48
return false unless MACOS
%w[port fink].each do |ponk|
path = which(ponk)
return ponk unless path.nil?
end
# we do the above check because macports can be relocated and fink may be
# able to be relocated in the future. This following check is because if
# fink and macports are not in the PATH but are still installed it can
# *still* break the build -- because some build scripts hardcode these paths:
%w[/sw/bin/fink /opt/local/bin/port].each do |ponk|
return ponk if File.exist? ponk
end
# finally, sometimes people make their MacPorts or Fink read-only so they
# can quickly test Homebrew out, but still in theory obey the README's
# advise to rename the root directory. This doesn't work, many build scripts
# error out when they try to read from these now unreadable directories.
%w[/sw /opt/local].each do |path|
path = Pathname.new(path)
return path if path.exist? and not path.readable?
end
false
end
def leopard?
10.5 == MACOS_VERSION
end
def snow_leopard?
10.6 <= MACOS_VERSION # Actually Snow Leopard or newer
end
alias :snow_leopard_or_newer? :snow_leopard?
def lion?
10.7 <= MACOS_VERSION # Actually Lion or newer
end
alias :lion_or_newer? :lion?
def mountain_lion?
10.8 <= MACOS_VERSION # Actually Mountain Lion or newer
end
alias :mountain_lion_or_newer? :mountain_lion?
def prefer_64_bit?
Hardware.is_64_bit? and not leopard?
end
StandardCompilers = {
"3.1.4" => {:gcc_40_build_version=>5493, :gcc_42_build_version=>5577},
"3.2.6" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"1.7", :clang_build_version=>77},
"4.0" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"2.0", :clang_build_version=>137},
"4.0.1" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"2.0", :clang_build_version=>137},
"4.0.2" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"2.0", :clang_build_version=>137},
"4.2" => {:llvm_build_version=>2336, :clang_version=>"3.0", :clang_build_version=>211},
"4.3" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318},
"4.3.1" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318},
"4.3.2" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318},
"4.3.3" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318},
"4.4" => {:llvm_build_version=>2336, :clang_version=>"4.0", :clang_build_version=>421}
}
def compilers_standard?
xcode = Xcode.version
# Assume compilers are okay if Xcode version not in hash
return true unless StandardCompilers.keys.include? xcode
StandardCompilers[xcode].all? {|k,v| MacOS.send(k) == v}
end
def app_with_bundle_id id
mdfind(MDITEM_BUNDLE_ID_KEY, id)
end
def mdfind attribute, id
path = `mdfind "#{attribute} == '#{id}'"`.split("\n").first
Pathname.new(path) unless path.nil? or path.empty?
end
def pkgutil_info id
`pkgutil --pkg-info #{id} 2>/dev/null`.strip
end
end
require 'macos/xcode'
require 'macos/xquartz'
Add Xcode 4.4.1 to standard compilers map
Signed-off-by: Jack Nagel <43386ce32af96f5c56f2a88e458cb94cebee3751@gmail.com>
module MacOS extend self
MDITEM_BUNDLE_ID_KEY = "kMDItemCFBundleIdentifier"
def version
MACOS_VERSION
end
def cat
if mountain_lion?
:mountainlion
elsif lion?
:lion
elsif snow_leopard?
:snowleopard
elsif leopard?
:leopard
else
nil
end
end
def locate tool
# Don't call tools (cc, make, strip, etc.) directly!
# Give the name of the binary you look for as a string to this method
# in order to get the full path back as a Pathname.
tool = tool.to_s
@locate_cache ||= {}
return @locate_cache[tool] if @locate_cache.has_key? tool
if File.executable? "/usr/bin/#{tool}"
path = Pathname.new "/usr/bin/#{tool}"
else
# Xcrun was provided first with Xcode 4.3 and allows us to proxy
# tool usage thus avoiding various bugs.
p = `/usr/bin/xcrun -find #{tool} 2>/dev/null`.chomp unless Xcode.bad_xcode_select_path?
if !p.nil? and !p.empty? and File.executable? p
path = Pathname.new p
else
# This is for the use-case where xcode-select is not set up correctly
# with Xcode 4.3+. The tools in Xcode 4.3+ are split over two locations,
# usually xcrun would figure that out for us, but it won't work if
# xcode-select is not configured properly.
p = "#{dev_tools_path}/#{tool}"
if File.executable? p
path = Pathname.new p
else
# Otherwise lets look in the second location.
p = "#{xctoolchain_path}/usr/bin/#{tool}"
if File.executable? p
path = Pathname.new p
else
# We digged so deep but all is lost now.
path = nil
end
end
end
end
@locate_cache[tool] = path
return path
end
def dev_tools_path
@dev_tools_path ||= if File.exist? "/usr/bin/cc" and File.exist? "/usr/bin/make"
# probably a safe enough assumption (the unix way)
Pathname.new "/usr/bin"
# Note that the exit status of system "xcrun foo" isn't always accurate
elsif not Xcode.bad_xcode_select_path? and not `/usr/bin/xcrun -find make 2>/dev/null`.empty?
# Wherever "make" is there are the dev tools.
Pathname.new(`/usr/bin/xcrun -find make`.chomp).dirname
elsif File.exist? "#{Xcode.prefix}/usr/bin/make"
# cc stopped existing with Xcode 4.3, there are c89 and c99 options though
Pathname.new "#{Xcode.prefix}/usr/bin"
else
# Since we are pretty unrelenting in finding Xcode no matter where
# it hides, we can now throw in the towel.
opoo "You really should consult the `brew doctor`!"
""
end
end
def xctoolchain_path
# As of Xcode 4.3, some tools are located in the "xctoolchain" directory
@xctoolchain_path ||= begin
path = Pathname.new("#{Xcode.prefix}/Toolchains/XcodeDefault.xctoolchain")
# If only the CLT are installed, all tools will be under dev_tools_path,
# this path won't exist, and xctoolchain_path will be nil.
path if path.exist?
end
end
def sdk_path v=version
@sdk_path ||= {}
@sdk_path[v.to_s] ||= begin
path = if not Xcode.bad_xcode_select_path? and File.executable? "#{Xcode.folder}/usr/bin/make"
`#{locate('xcodebuild')} -version -sdk macosx#{v} Path 2>/dev/null`.strip
elsif File.directory? "/Developer/SDKs/MacOS#{v}.sdk"
# the old default (or wild wild west style)
"/Developer/SDKs/MacOS#{v}.sdk"
elsif File.directory? "#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX#{v}.sdk"
# Xcode.prefix is pretty smart, so lets look inside to find the sdk
"#{Xcode.prefix}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX#{v}.sdk"
end
Pathname.new(path) unless path.nil? or path.empty? or not File.directory? path
end
end
def default_cc
cc = locate 'cc'
Pathname.new(cc).realpath.basename.to_s rescue nil
end
def default_compiler
case default_cc
when /^gcc/ then :gcc
when /^llvm/ then :llvm
when "clang" then :clang
else
# guess :(
if Xcode.version >= "4.3"
:clang
elsif Xcode.version >= "4.2"
:llvm
else
:gcc
end
end
end
def gcc_40_build_version
@gcc_40_build_version ||= if locate("gcc-4.0")
`#{locate("gcc-4.0")} --version` =~ /build (\d{4,})/
$1.to_i
end
end
def gcc_42_build_version
@gcc_42_build_version ||= if locate("gcc-4.2") \
and not locate("gcc-4.2").realpath.basename.to_s =~ /^llvm/
`#{locate("gcc-4.2")} --version` =~ /build (\d{4,})/
$1.to_i
end
end
def llvm_build_version
# for Xcode 3 on OS X 10.5 this will not exist
# NOTE may not be true anymore but we can't test
@llvm_build_version ||= if locate("llvm-gcc")
`#{locate("llvm-gcc")} --version` =~ /LLVM build (\d{4,})/
$1.to_i
end
end
def clang_version
@clang_version ||= if locate("clang")
`#{locate("clang")} --version` =~ /clang version (\d\.\d)/
$1
end
end
def clang_build_version
@clang_build_version ||= if locate("clang")
`#{locate("clang")} --version` =~ %r[tags/Apple/clang-(\d{2,})]
$1.to_i
end
end
def macports_or_fink_installed?
# See these issues for some history:
# http://github.com/mxcl/homebrew/issues/#issue/13
# http://github.com/mxcl/homebrew/issues/#issue/41
# http://github.com/mxcl/homebrew/issues/#issue/48
return false unless MACOS
%w[port fink].each do |ponk|
path = which(ponk)
return ponk unless path.nil?
end
# we do the above check because macports can be relocated and fink may be
# able to be relocated in the future. This following check is because if
# fink and macports are not in the PATH but are still installed it can
# *still* break the build -- because some build scripts hardcode these paths:
%w[/sw/bin/fink /opt/local/bin/port].each do |ponk|
return ponk if File.exist? ponk
end
# finally, sometimes people make their MacPorts or Fink read-only so they
# can quickly test Homebrew out, but still in theory obey the README's
# advise to rename the root directory. This doesn't work, many build scripts
# error out when they try to read from these now unreadable directories.
%w[/sw /opt/local].each do |path|
path = Pathname.new(path)
return path if path.exist? and not path.readable?
end
false
end
def leopard?
10.5 == MACOS_VERSION
end
def snow_leopard?
10.6 <= MACOS_VERSION # Actually Snow Leopard or newer
end
alias :snow_leopard_or_newer? :snow_leopard?
def lion?
10.7 <= MACOS_VERSION # Actually Lion or newer
end
alias :lion_or_newer? :lion?
def mountain_lion?
10.8 <= MACOS_VERSION # Actually Mountain Lion or newer
end
alias :mountain_lion_or_newer? :mountain_lion?
def prefer_64_bit?
Hardware.is_64_bit? and not leopard?
end
StandardCompilers = {
"3.1.4" => {:gcc_40_build_version=>5493, :gcc_42_build_version=>5577},
"3.2.6" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"1.7", :clang_build_version=>77},
"4.0" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"2.0", :clang_build_version=>137},
"4.0.1" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"2.0", :clang_build_version=>137},
"4.0.2" => {:gcc_40_build_version=>5494, :gcc_42_build_version=>5666, :llvm_build_version=>2335, :clang_version=>"2.0", :clang_build_version=>137},
"4.2" => {:llvm_build_version=>2336, :clang_version=>"3.0", :clang_build_version=>211},
"4.3" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318},
"4.3.1" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318},
"4.3.2" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318},
"4.3.3" => {:llvm_build_version=>2336, :clang_version=>"3.1", :clang_build_version=>318},
"4.4" => {:llvm_build_version=>2336, :clang_version=>"4.0", :clang_build_version=>421},
"4.4.1" => {:llvm_build_version=>2336, :clang_version=>"4.0", :clang_build_version=>421}
}
def compilers_standard?
xcode = Xcode.version
# Assume compilers are okay if Xcode version not in hash
return true unless StandardCompilers.keys.include? xcode
StandardCompilers[xcode].all? {|k,v| MacOS.send(k) == v}
end
def app_with_bundle_id id
mdfind(MDITEM_BUNDLE_ID_KEY, id)
end
def mdfind attribute, id
path = `mdfind "#{attribute} == '#{id}'"`.split("\n").first
Pathname.new(path) unless path.nil? or path.empty?
end
def pkgutil_info id
`pkgutil --pkg-info #{id} 2>/dev/null`.strip
end
end
require 'macos/xcode'
require 'macos/xquartz'
|
# frozen_string_literal: true
require "system_helper"
describe "As a consumer, I want to checkout my order", js: true do
include ShopWorkflow
include SplitCheckoutHelper
let!(:zone) { create(:zone_with_member) }
let(:supplier) { create(:supplier_enterprise) }
let(:distributor) { create(:distributor_enterprise, charges_sales_tax: true) }
let(:product) {
create(:taxed_product, supplier: supplier, price: 10, zone: zone, tax_rate_amount: 0.1)
}
let(:variant) { product.variants.first }
let!(:order_cycle) {
create(:simple_order_cycle, suppliers: [supplier], distributors: [distributor],
coordinator: create(:distributor_enterprise), variants: [variant])
}
let(:order) {
create(:order, order_cycle: order_cycle, distributor: distributor, bill_address_id: nil,
ship_address_id: nil, state: "cart")
}
let(:fee_tax_rate) { create(:tax_rate, amount: 0.10, zone: zone, included_in_price: true) }
let(:fee_tax_category) { create(:tax_category, tax_rates: [fee_tax_rate]) }
let(:enterprise_fee) { create(:enterprise_fee, amount: 1.23, tax_category: fee_tax_category) }
let(:free_shipping) {
create(:shipping_method, require_ship_address: false, name: "Free Shipping", description: "yellow",
calculator: Calculator::FlatRate.new(preferred_amount: 0.00))
}
let(:shipping_tax_rate) { create(:tax_rate, amount: 0.25, zone: zone, included_in_price: true) }
let(:shipping_tax_category) { create(:tax_category, tax_rates: [shipping_tax_rate]) }
let(:shipping_with_fee) {
create(:shipping_method, require_ship_address: true, tax_category: shipping_tax_category,
name: "Shipping with Fee", description: "blue",
calculator: Calculator::FlatRate.new(preferred_amount: 4.56))
}
let!(:payment_method) { create(:payment_method, distributors: [distributor]) }
before do
allow(Flipper).to receive(:enabled?).with(:split_checkout).and_return(true)
allow(Flipper).to receive(:enabled?).with(:split_checkout, anything).and_return(true)
add_enterprise_fee enterprise_fee
set_order order
add_product_to_cart order, product
distributor.shipping_methods << free_shipping
distributor.shipping_methods << shipping_with_fee
end
context "guest checkout when distributor doesn't allow guest orders" do
before do
distributor.update_columns allow_guest_orders: false
visit checkout_step_path(:details)
end
it "should display the split checkout login page" do
expect(page).to have_content("Ok, ready to checkout?")
expect(page).to have_content("Login")
expect(page).to have_no_content("Checkout as guest")
end
it "should show the login modal when clicking the login button" do
click_on "Login"
expect(page).to have_selector ".login-modal"
end
end
context "as a guest user" do
before do
visit checkout_path
end
it "should display the split checkout login/guest form" do
expect(page).to have_content distributor.name
expect(page).to have_content("Ok, ready to checkout?")
expect(page).to have_content("Login")
expect(page).to have_content("Checkout as guest")
end
it "should display the split checkout details page" do
click_on "Checkout as guest"
expect(page).to have_content distributor.name
expect(page).to have_content("1 - Your details")
expect(page).to have_selector("div.checkout-tab.selected", text: "1 - Your details")
expect(page).to have_content("2 - Payment method")
expect(page).to have_content("3 - Order summary")
end
it "should display error when fields are empty" do
click_on "Checkout as guest"
click_button "Next - Payment method"
expect(page).to have_content("Saving failed, please update the highlighted fields")
expect(page).to have_css 'span.field_with_errors label', count: 6
expect(page).to have_css 'span.field_with_errors input', count: 6
expect(page).to have_css 'span.formError', count: 7
end
it "should validate once each needed field is filled" do
click_on "Checkout as guest"
fill_in "First Name", with: "Jane"
fill_in "Last Name", with: "Doe"
fill_in "Phone number", with: "07987654321"
fill_in "Address (Street + House Number)", with: "Flat 1 Elm apartments"
fill_in "City", with: "London"
fill_in "Postcode", with: "SW1A 1AA"
choose free_shipping.name
click_button "Next - Payment method"
expect(page).to have_button("Next - Order summary")
end
context "when order is state: 'payment'" do
it "should allow visit '/checkout/details'" do
order.update(state: "payment")
visit checkout_step_path(:details)
expect(page).to have_current_path("/checkout/details")
end
end
end
context "as a logged in user" do
let(:user) { create(:user) }
before do
login_as(user)
visit checkout_path
end
describe "filling out delivery details" do
before do
fill_out_details
fill_out_billing_address
end
describe "selecting a pick-up shipping method and submiting the form" do
before do
choose free_shipping.name
end
it "redirects the user to the Payment Method step" do
fill_notes("SpEcIaL NoTeS")
proceed_to_payment
end
end
describe "selecting a delivery method" do
before do
choose shipping_with_fee.name
end
context "with same shipping and billing address" do
before do
check "ship_address_same_as_billing"
end
it "does not display the shipping address form" do
expect(page).not_to have_field "order_ship_address_attributes_address1"
end
it "redirects the user to the Payment Method step, when submiting the form" do
proceed_to_payment
# asserts whether shipping and billing addresses are the same
ship_add_id = order.reload.ship_address_id
bill_add_id = order.reload.bill_address_id
expect(Spree::Address.where(id: bill_add_id).pluck(:address1) ==
Spree::Address.where(id: ship_add_id).pluck(:address1)).to be true
end
end
context "with different shipping and billing address" do
before do
uncheck "ship_address_same_as_billing"
end
it "displays the shipping address form and the option to save it as default" do
expect(page).to have_field "order_ship_address_attributes_address1"
end
it "displays error messages when submitting incomplete billing address" do
click_button "Next - Payment method"
expect(page).to have_content "Saving failed, please update the highlighted fields."
expect(page).to have_field("Address", with: "")
expect(page).to have_field("City", with: "")
expect(page).to have_field("Postcode", with: "")
expect(page).to have_content("can't be blank", count: 3)
end
it "fills in shipping details and redirects the user to the Payment Method step,
when submiting the form" do
fill_out_shipping_address
fill_notes("SpEcIaL NoTeS")
proceed_to_payment
# asserts whether shipping and billing addresses are the same
ship_add_id = Spree::Order.first.ship_address_id
bill_add_id = Spree::Order.first.bill_address_id
expect(Spree::Address.where(id: bill_add_id).pluck(:address1) ==
Spree::Address.where(id: ship_add_id).pluck(:address1)).to be false
end
end
end
end
describe "not filling out delivery details" do
before do
fill_in "Email", with: ""
end
it "should display error when fields are empty" do
click_button "Next - Payment method"
expect(page).to have_content("Saving failed, please update the highlighted fields")
expect(page).to have_field("First Name", with: "")
expect(page).to have_field("Last Name", with: "")
expect(page).to have_field("Email", with: "")
expect(page).to have_content("is invalid")
expect(page).to have_field("Phone number", with: "")
expect(page).to have_field("Address", with: "")
expect(page).to have_field("City", with: "")
expect(page).to have_field("Postcode", with: "")
expect(page).to have_content("can't be blank", count: 7)
expect(page).to have_content("Select a shipping method")
end
end
end
context "when I have an out of stock product in my cart" do
before do
variant.update!(on_demand: false, on_hand: 0)
end
it "returns me to the cart with an error message" do
visit checkout_path
expect(page).not_to have_selector 'closing', text: "Checkout now"
expect(page).to have_selector 'closing', text: "Your shopping cart"
expect(page).to have_content "An item in your cart has become unavailable"
end
end
end
Increase flexibility in test setup
# frozen_string_literal: true
require "system_helper"
describe "As a consumer, I want to checkout my order", js: true do
include ShopWorkflow
include SplitCheckoutHelper
let!(:zone) { create(:zone_with_member) }
let(:supplier) { create(:supplier_enterprise) }
let(:distributor) { create(:distributor_enterprise, charges_sales_tax: true) }
let(:product) {
create(:taxed_product, supplier: supplier, price: 10, zone: zone, tax_rate_amount: 0.1)
}
let(:variant) { product.variants.first }
let!(:order_cycle) {
create(:simple_order_cycle, suppliers: [supplier], distributors: [distributor],
coordinator: create(:distributor_enterprise), variants: [variant])
}
let(:order) {
create(:order, order_cycle: order_cycle, distributor: distributor, bill_address_id: nil,
ship_address_id: nil, state: "cart",
line_items: [create(:line_item, variant: variant)])
}
let(:fee_tax_rate) { create(:tax_rate, amount: 0.10, zone: zone, included_in_price: true) }
let(:fee_tax_category) { create(:tax_category, tax_rates: [fee_tax_rate]) }
let(:enterprise_fee) { create(:enterprise_fee, amount: 1.23, tax_category: fee_tax_category) }
let(:free_shipping) {
create(:shipping_method, require_ship_address: false, name: "Free Shipping", description: "yellow",
calculator: Calculator::FlatRate.new(preferred_amount: 0.00))
}
let(:shipping_tax_rate) { create(:tax_rate, amount: 0.25, zone: zone, included_in_price: true) }
let(:shipping_tax_category) { create(:tax_category, tax_rates: [shipping_tax_rate]) }
let(:shipping_with_fee) {
create(:shipping_method, require_ship_address: true, tax_category: shipping_tax_category,
name: "Shipping with Fee", description: "blue",
calculator: Calculator::FlatRate.new(preferred_amount: 4.56))
}
let!(:payment_method) { create(:payment_method, distributors: [distributor]) }
before do
allow(Flipper).to receive(:enabled?).with(:split_checkout).and_return(true)
allow(Flipper).to receive(:enabled?).with(:split_checkout, anything).and_return(true)
add_enterprise_fee enterprise_fee
set_order order
distributor.shipping_methods << free_shipping
distributor.shipping_methods << shipping_with_fee
end
context "guest checkout when distributor doesn't allow guest orders" do
before do
distributor.update_columns allow_guest_orders: false
visit checkout_step_path(:details)
end
it "should display the split checkout login page" do
expect(page).to have_content("Ok, ready to checkout?")
expect(page).to have_content("Login")
expect(page).to have_no_content("Checkout as guest")
end
it "should show the login modal when clicking the login button" do
click_on "Login"
expect(page).to have_selector ".login-modal"
end
end
context "as a guest user" do
before do
visit checkout_path
end
it "should display the split checkout login/guest form" do
expect(page).to have_content distributor.name
expect(page).to have_content("Ok, ready to checkout?")
expect(page).to have_content("Login")
expect(page).to have_content("Checkout as guest")
end
it "should display the split checkout details page" do
click_on "Checkout as guest"
expect(page).to have_content distributor.name
expect(page).to have_content("1 - Your details")
expect(page).to have_selector("div.checkout-tab.selected", text: "1 - Your details")
expect(page).to have_content("2 - Payment method")
expect(page).to have_content("3 - Order summary")
end
it "should display error when fields are empty" do
click_on "Checkout as guest"
click_button "Next - Payment method"
expect(page).to have_content("Saving failed, please update the highlighted fields")
expect(page).to have_css 'span.field_with_errors label', count: 6
expect(page).to have_css 'span.field_with_errors input', count: 6
expect(page).to have_css 'span.formError', count: 7
end
it "should validate once each needed field is filled" do
click_on "Checkout as guest"
fill_in "First Name", with: "Jane"
fill_in "Last Name", with: "Doe"
fill_in "Phone number", with: "07987654321"
fill_in "Address (Street + House Number)", with: "Flat 1 Elm apartments"
fill_in "City", with: "London"
fill_in "Postcode", with: "SW1A 1AA"
choose free_shipping.name
click_button "Next - Payment method"
expect(page).to have_button("Next - Order summary")
end
context "when order is state: 'payment'" do
it "should allow visit '/checkout/details'" do
order.update(state: "payment")
visit checkout_step_path(:details)
expect(page).to have_current_path("/checkout/details")
end
end
end
context "as a logged in user" do
let(:user) { create(:user) }
before do
login_as(user)
visit checkout_path
end
describe "filling out delivery details" do
before do
fill_out_details
fill_out_billing_address
end
describe "selecting a pick-up shipping method and submiting the form" do
before do
choose free_shipping.name
end
it "redirects the user to the Payment Method step" do
fill_notes("SpEcIaL NoTeS")
proceed_to_payment
end
end
describe "selecting a delivery method" do
before do
choose shipping_with_fee.name
end
context "with same shipping and billing address" do
before do
check "ship_address_same_as_billing"
end
it "does not display the shipping address form" do
expect(page).not_to have_field "order_ship_address_attributes_address1"
end
it "redirects the user to the Payment Method step, when submiting the form" do
proceed_to_payment
# asserts whether shipping and billing addresses are the same
ship_add_id = order.reload.ship_address_id
bill_add_id = order.reload.bill_address_id
expect(Spree::Address.where(id: bill_add_id).pluck(:address1) ==
Spree::Address.where(id: ship_add_id).pluck(:address1)).to be true
end
end
context "with different shipping and billing address" do
before do
uncheck "ship_address_same_as_billing"
end
it "displays the shipping address form and the option to save it as default" do
expect(page).to have_field "order_ship_address_attributes_address1"
end
it "displays error messages when submitting incomplete billing address" do
click_button "Next - Payment method"
expect(page).to have_content "Saving failed, please update the highlighted fields."
expect(page).to have_field("Address", with: "")
expect(page).to have_field("City", with: "")
expect(page).to have_field("Postcode", with: "")
expect(page).to have_content("can't be blank", count: 3)
end
it "fills in shipping details and redirects the user to the Payment Method step,
when submiting the form" do
fill_out_shipping_address
fill_notes("SpEcIaL NoTeS")
proceed_to_payment
# asserts whether shipping and billing addresses are the same
ship_add_id = Spree::Order.first.ship_address_id
bill_add_id = Spree::Order.first.bill_address_id
expect(Spree::Address.where(id: bill_add_id).pluck(:address1) ==
Spree::Address.where(id: ship_add_id).pluck(:address1)).to be false
end
end
end
end
describe "not filling out delivery details" do
before do
fill_in "Email", with: ""
end
it "should display error when fields are empty" do
click_button "Next - Payment method"
expect(page).to have_content("Saving failed, please update the highlighted fields")
expect(page).to have_field("First Name", with: "")
expect(page).to have_field("Last Name", with: "")
expect(page).to have_field("Email", with: "")
expect(page).to have_content("is invalid")
expect(page).to have_field("Phone number", with: "")
expect(page).to have_field("Address", with: "")
expect(page).to have_field("City", with: "")
expect(page).to have_field("Postcode", with: "")
expect(page).to have_content("can't be blank", count: 7)
expect(page).to have_content("Select a shipping method")
end
end
end
context "when I have an out of stock product in my cart" do
before do
variant.update!(on_demand: false, on_hand: 0)
end
it "returns me to the cart with an error message" do
visit checkout_path
expect(page).not_to have_selector 'closing', text: "Checkout now"
expect(page).to have_selector 'closing', text: "Your shopping cart"
expect(page).to have_content "An item in your cart has become unavailable"
end
end
end
|
require "pathname"
require "exceptions"
require "os/mac"
require "utils/json"
require "utils/inreplace"
require "utils/popen"
require "utils/fork"
require "utils/git"
require "open-uri"
class Tty
class << self
def blue
bold 34
end
def white
bold 39
end
def red
underline 31
end
def yellow
underline 33
end
def reset
escape 0
end
def em
underline 39
end
def green
bold 32
end
def gray
bold 30
end
def width
`/usr/bin/tput cols`.strip.to_i
end
def truncate(str)
str.to_s[0, width - 4]
end
private
def color(n)
escape "0;#{n}"
end
def bold(n)
escape "1;#{n}"
end
def underline(n)
escape "4;#{n}"
end
def escape(n)
"\033[#{n}m" if $stdout.tty?
end
end
end
def ohai(title, *sput)
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.blue}==>#{Tty.white} #{title}#{Tty.reset}"
puts sput
end
def oh1(title)
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.green}==>#{Tty.white} #{title}#{Tty.reset}"
end
# Print a warning (do this rarely)
def opoo(warning)
$stderr.puts "#{Tty.yellow}Warning#{Tty.reset}: #{warning}"
end
def onoe(error)
$stderr.puts "#{Tty.red}Error#{Tty.reset}: #{error}"
end
def ofail(error)
onoe error
Homebrew.failed = true
end
def odie(error)
onoe error
exit 1
end
def pretty_duration(s)
return "2 seconds" if s < 3 # avoids the plural problem ;)
return "#{s.to_i} seconds" if s < 120
"%.1f minutes" % (s/60)
end
def plural(n, s = "s")
(n == 1) ? "" : s
end
def interactive_shell(f = nil)
unless f.nil?
ENV["HOMEBREW_DEBUG_PREFIX"] = f.prefix
ENV["HOMEBREW_DEBUG_INSTALL"] = f.full_name
end
if ENV["SHELL"].include?("zsh") && ENV["HOME"].start_with?(HOMEBREW_TEMP.resolved_path.to_s)
FileUtils.touch "#{ENV["HOME"]}/.zshrc"
end
Process.wait fork { exec ENV["SHELL"] }
if $?.success?
return
elsif $?.exited?
puts "Aborting due to non-zero exit status"
exit $?.exitstatus
else
raise $?.inspect
end
end
module Homebrew
def self._system(cmd, *args)
pid = fork do
yield if block_given?
args.collect!(&:to_s)
exec(cmd, *args) rescue nil
exit! 1 # never gets here unless exec failed
end
Process.wait(pid)
$?.success?
end
def self.system(cmd, *args)
puts "#{cmd} #{args*" "}" if ARGV.verbose?
_system(cmd, *args)
end
def self.git_origin
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git config --get remote.origin.url 2>/dev/null`.chuzzle }
end
def self.git_head
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git rev-parse --verify -q HEAD 2>/dev/null`.chuzzle }
end
def self.git_short_head
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git rev-parse --short=4 --verify -q HEAD 2>/dev/null`.chuzzle }
end
def self.git_last_commit
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git show -s --format="%cr" HEAD 2>/dev/null`.chuzzle }
end
def self.git_last_commit_date
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git show -s --format="%cd" --date=short HEAD 2>/dev/null`.chuzzle }
end
def self.homebrew_version_string
if pretty_revision = git_short_head
last_commit = git_last_commit_date
"#{HOMEBREW_VERSION} (git revision #{pretty_revision}; last commit #{last_commit})"
else
"#{HOMEBREW_VERSION} (no git repository)"
end
end
def self.install_gem_setup_path!(gem, version = nil, executable = gem)
require "rubygems"
ENV["PATH"] = "#{Gem.user_dir}/bin:#{ENV["PATH"]}"
args = [gem]
args << "-v" << version if version
unless quiet_system "gem", "list", "--installed", *args
safe_system "gem", "install", "--no-ri", "--no-rdoc",
"--user-install", *args
end
unless which executable
odie <<-EOS.undent
The '#{gem}' gem is installed but couldn't find '#{executable}' in the PATH:
#{ENV["PATH"]}
EOS
end
end
end
def with_system_path
old_path = ENV["PATH"]
ENV["PATH"] = "/usr/bin:/bin"
yield
ensure
ENV["PATH"] = old_path
end
def run_as_not_developer(&_block)
old = ENV.delete "HOMEBREW_DEVELOPER"
yield
ensure
ENV["HOMEBREW_DEVELOPER"] = old
end
# Kernel.system but with exceptions
def safe_system(cmd, *args)
Homebrew.system(cmd, *args) || raise(ErrorDuringExecution.new(cmd, args))
end
# prints no output
def quiet_system(cmd, *args)
Homebrew._system(cmd, *args) do
# Redirect output streams to `/dev/null` instead of closing as some programs
# will fail to execute if they can't write to an open stream.
$stdout.reopen("/dev/null")
$stderr.reopen("/dev/null")
end
end
def curl(*args)
brewed_curl = HOMEBREW_PREFIX/"opt/curl/bin/curl"
curl = if MacOS.version <= "10.6" && brewed_curl.exist?
brewed_curl
else
Pathname.new "/usr/bin/curl"
end
raise "#{curl} is not executable" unless curl.exist? && curl.executable?
flags = HOMEBREW_CURL_ARGS
flags = flags.delete("#") if ARGV.verbose?
args = [flags, HOMEBREW_USER_AGENT, *args]
args << "--verbose" if ENV["HOMEBREW_CURL_VERBOSE"]
args << "--silent" unless $stdout.tty?
safe_system curl, *args
end
def puts_columns(items, star_items = [])
return if items.empty?
if star_items && star_items.any?
items = items.map { |item| star_items.include?(item) ? "#{item}*" : item }
end
unless $stdout.tty?
puts items
return
end
# TTY case: If possible, output using multiple columns.
console_width = Tty.width
console_width = 80 if console_width <= 0
max_len = items.max_by(&:length).length
col_gap = 2 # number of spaces between columns
gap_str = " " * col_gap
cols = (console_width + col_gap) / (max_len + col_gap)
cols = 1 if cols < 1
rows = (items.size + cols - 1) / cols
cols = (items.size + rows - 1) / rows # avoid empty trailing columns
if cols >= 2
col_width = (console_width + col_gap) / cols - col_gap
items = items.map { |item| item.ljust(col_width) }
end
if cols == 1
puts items
else
rows.times do |row_index|
item_indices_for_row = row_index.step(items.size - 1, rows).to_a
puts items.values_at(*item_indices_for_row).join(gap_str)
end
end
end
def which(cmd, path = ENV["PATH"])
path.split(File::PATH_SEPARATOR).each do |p|
begin
pcmd = File.expand_path(cmd, p)
rescue ArgumentError
# File.expand_path will raise an ArgumentError if the path is malformed.
# See https://github.com/Homebrew/homebrew/issues/32789
next
end
return Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd)
end
nil
end
def which_editor
editor = ENV.values_at("HOMEBREW_EDITOR", "VISUAL", "EDITOR").compact.first
return editor unless editor.nil?
# Find Textmate
editor = "mate" if which "mate"
# Find BBEdit / TextWrangler
editor ||= "edit" if which "edit"
# Find vim
editor ||= "vim" if which "vim"
# Default to standard vim
editor ||= "/usr/bin/vim"
opoo <<-EOS.undent
Using #{editor} because no editor was set in the environment.
This may change in the future, so we recommend setting EDITOR, VISUAL,
or HOMEBREW_EDITOR to your preferred text editor.
EOS
editor
end
def exec_editor(*args)
safe_exec(which_editor, *args)
end
def exec_browser(*args)
browser = ENV["HOMEBREW_BROWSER"] || ENV["BROWSER"] || OS::PATH_OPEN
safe_exec(browser, *args)
end
def safe_exec(cmd, *args)
# This buys us proper argument quoting and evaluation
# of environment variables in the cmd parameter.
exec "/bin/sh", "-c", "#{cmd} \"$@\"", "--", *args
end
# GZips the given paths, and returns the gzipped paths
def gzip(*paths)
paths.collect do |path|
with_system_path { safe_system "gzip", path }
Pathname.new("#{path}.gz")
end
end
# Returns array of architectures that the given command or library is built for.
def archs_for_command(cmd)
cmd = which(cmd) unless Pathname.new(cmd).absolute?
Pathname.new(cmd).archs
end
def ignore_interrupts(opt = nil)
std_trap = trap("INT") do
puts "One sec, just cleaning up" unless opt == :quietly
end
yield
ensure
trap("INT", std_trap)
end
def nostdout
if ARGV.verbose?
yield
else
begin
out = $stdout.dup
$stdout.reopen("/dev/null")
yield
ensure
$stdout.reopen(out)
out.close
end
end
end
def paths
@paths ||= ENV["PATH"].split(File::PATH_SEPARATOR).collect do |p|
begin
File.expand_path(p).chomp("/")
rescue ArgumentError
onoe "The following PATH component is invalid: #{p}"
end
end.uniq.compact
end
# return the shell profile file based on users' preference shell
def shell_profile
case ENV["SHELL"]
when %r{/(ba)?sh} then "~/.bash_profile"
when %r{/zsh} then "~/.zshrc"
when %r{/ksh} then "~/.kshrc"
else "~/.bash_profile"
end
end
module GitHub
extend self
ISSUES_URI = URI.parse("https://api.github.com/search/issues")
Error = Class.new(RuntimeError)
HTTPNotFoundError = Class.new(Error)
class RateLimitExceededError < Error
def initialize(reset, error)
super <<-EOS.undent
GitHub #{error}
Try again in #{pretty_ratelimit_reset(reset)}, or create an personal access token:
https://github.com/settings/tokens
and then set the token as: HOMEBREW_GITHUB_API_TOKEN
EOS
end
def pretty_ratelimit_reset(reset)
if (seconds = Time.at(reset) - Time.now) > 180
"%d minutes %d seconds" % [seconds / 60, seconds % 60]
else
"#{seconds} seconds"
end
end
end
class AuthenticationFailedError < Error
def initialize(error)
super <<-EOS.undent
GitHub #{error}
HOMEBREW_GITHUB_API_TOKEN may be invalid or expired, check:
https://github.com/settings/tokens
EOS
end
end
def open(url, &_block)
# This is a no-op if the user is opting out of using the GitHub API.
return if ENV["HOMEBREW_NO_GITHUB_API"]
require "net/https"
headers = {
"User-Agent" => HOMEBREW_USER_AGENT,
"Accept" => "application/vnd.github.v3+json"
}
headers["Authorization"] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN
begin
Kernel.open(url, headers) { |f| yield Utils::JSON.load(f.read) }
rescue OpenURI::HTTPError => e
handle_api_error(e)
rescue EOFError, SocketError, OpenSSL::SSL::SSLError => e
raise Error, "Failed to connect to: #{url}\n#{e.message}", e.backtrace
rescue Utils::JSON::Error => e
raise Error, "Failed to parse JSON response\n#{e.message}", e.backtrace
end
end
def handle_api_error(e)
if e.io.meta["x-ratelimit-remaining"].to_i <= 0
reset = e.io.meta.fetch("x-ratelimit-reset").to_i
error = Utils::JSON.load(e.io.read)["message"]
raise RateLimitExceededError.new(reset, error)
end
case e.io.status.first
when "401", "403"
raise AuthenticationFailedError.new(e.message)
when "404"
raise HTTPNotFoundError, e.message, e.backtrace
else
raise Error, e.message, e.backtrace
end
end
def issues_matching(query, qualifiers = {})
uri = ISSUES_URI.dup
uri.query = build_query_string(query, qualifiers)
open(uri) { |json| json["items"] }
end
def repository(user, repo)
open(URI.parse("https://api.github.com/repos/#{user}/#{repo}")) { |j| j }
end
def build_query_string(query, qualifiers)
s = "q=#{uri_escape(query)}+"
s << build_search_qualifier_string(qualifiers)
s << "&per_page=100"
end
def build_search_qualifier_string(qualifiers)
{
:repo => "Homebrew/homebrew",
:in => "title"
}.update(qualifiers).map do |qualifier, value|
"#{qualifier}:#{value}"
end.join("+")
end
def uri_escape(query)
if URI.respond_to?(:encode_www_form_component)
URI.encode_www_form_component(query)
else
require "erb"
ERB::Util.url_encode(query)
end
end
def issues_for_formula(name)
issues_matching(name, :state => "open")
end
def print_pull_requests_matching(query)
return [] if ENV["HOMEBREW_NO_GITHUB_API"]
ohai "Searching pull requests..."
open_or_closed_prs = issues_matching(query, :type => "pr")
open_prs = open_or_closed_prs.select { |i| i["state"] == "open" }
if open_prs.any?
puts "Open pull requests:"
prs = open_prs
elsif open_or_closed_prs.any?
puts "Closed pull requests:"
prs = open_or_closed_prs
else
return
end
prs.each { |i| puts "#{i["title"]} (#{i["html_url"]})" }
end
def private_repo?(user, repo)
uri = URI.parse("https://api.github.com/repos/#{user}/#{repo}")
open(uri) { |json| json["private"] }
end
end
utils: highlight items in column-wise output
Closes #44343.
Signed-off-by: Mike McQuaid <a17fed27eaa842282862ff7c1b9c8395a26ac320@mikemcquaid.com>
require "pathname"
require "exceptions"
require "os/mac"
require "utils/json"
require "utils/inreplace"
require "utils/popen"
require "utils/fork"
require "utils/git"
require "open-uri"
class Tty
class << self
def blue
bold 34
end
def white
bold 39
end
def red
underline 31
end
def yellow
underline 33
end
def reset
escape 0
end
def em
underline 39
end
def green
bold 32
end
def gray
bold 30
end
def highlight
bold 43
end
def width
`/usr/bin/tput cols`.strip.to_i
end
def truncate(str)
str.to_s[0, width - 4]
end
private
def color(n)
escape "0;#{n}"
end
def bold(n)
escape "1;#{n}"
end
def underline(n)
escape "4;#{n}"
end
def escape(n)
"\033[#{n}m" if $stdout.tty?
end
end
end
def ohai(title, *sput)
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.blue}==>#{Tty.white} #{title}#{Tty.reset}"
puts sput
end
def oh1(title)
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.green}==>#{Tty.white} #{title}#{Tty.reset}"
end
# Print a warning (do this rarely)
def opoo(warning)
$stderr.puts "#{Tty.yellow}Warning#{Tty.reset}: #{warning}"
end
def onoe(error)
$stderr.puts "#{Tty.red}Error#{Tty.reset}: #{error}"
end
def ofail(error)
onoe error
Homebrew.failed = true
end
def odie(error)
onoe error
exit 1
end
def pretty_duration(s)
return "2 seconds" if s < 3 # avoids the plural problem ;)
return "#{s.to_i} seconds" if s < 120
"%.1f minutes" % (s/60)
end
def plural(n, s = "s")
(n == 1) ? "" : s
end
def interactive_shell(f = nil)
unless f.nil?
ENV["HOMEBREW_DEBUG_PREFIX"] = f.prefix
ENV["HOMEBREW_DEBUG_INSTALL"] = f.full_name
end
if ENV["SHELL"].include?("zsh") && ENV["HOME"].start_with?(HOMEBREW_TEMP.resolved_path.to_s)
FileUtils.touch "#{ENV["HOME"]}/.zshrc"
end
Process.wait fork { exec ENV["SHELL"] }
if $?.success?
return
elsif $?.exited?
puts "Aborting due to non-zero exit status"
exit $?.exitstatus
else
raise $?.inspect
end
end
module Homebrew
def self._system(cmd, *args)
pid = fork do
yield if block_given?
args.collect!(&:to_s)
exec(cmd, *args) rescue nil
exit! 1 # never gets here unless exec failed
end
Process.wait(pid)
$?.success?
end
def self.system(cmd, *args)
puts "#{cmd} #{args*" "}" if ARGV.verbose?
_system(cmd, *args)
end
def self.git_origin
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git config --get remote.origin.url 2>/dev/null`.chuzzle }
end
def self.git_head
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git rev-parse --verify -q HEAD 2>/dev/null`.chuzzle }
end
def self.git_short_head
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git rev-parse --short=4 --verify -q HEAD 2>/dev/null`.chuzzle }
end
def self.git_last_commit
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git show -s --format="%cr" HEAD 2>/dev/null`.chuzzle }
end
def self.git_last_commit_date
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd { `git show -s --format="%cd" --date=short HEAD 2>/dev/null`.chuzzle }
end
def self.homebrew_version_string
if pretty_revision = git_short_head
last_commit = git_last_commit_date
"#{HOMEBREW_VERSION} (git revision #{pretty_revision}; last commit #{last_commit})"
else
"#{HOMEBREW_VERSION} (no git repository)"
end
end
def self.install_gem_setup_path!(gem, version = nil, executable = gem)
require "rubygems"
ENV["PATH"] = "#{Gem.user_dir}/bin:#{ENV["PATH"]}"
args = [gem]
args << "-v" << version if version
unless quiet_system "gem", "list", "--installed", *args
safe_system "gem", "install", "--no-ri", "--no-rdoc",
"--user-install", *args
end
unless which executable
odie <<-EOS.undent
The '#{gem}' gem is installed but couldn't find '#{executable}' in the PATH:
#{ENV["PATH"]}
EOS
end
end
end
def with_system_path
old_path = ENV["PATH"]
ENV["PATH"] = "/usr/bin:/bin"
yield
ensure
ENV["PATH"] = old_path
end
def run_as_not_developer(&_block)
old = ENV.delete "HOMEBREW_DEVELOPER"
yield
ensure
ENV["HOMEBREW_DEVELOPER"] = old
end
# Kernel.system but with exceptions
def safe_system(cmd, *args)
Homebrew.system(cmd, *args) || raise(ErrorDuringExecution.new(cmd, args))
end
# prints no output
def quiet_system(cmd, *args)
Homebrew._system(cmd, *args) do
# Redirect output streams to `/dev/null` instead of closing as some programs
# will fail to execute if they can't write to an open stream.
$stdout.reopen("/dev/null")
$stderr.reopen("/dev/null")
end
end
def curl(*args)
brewed_curl = HOMEBREW_PREFIX/"opt/curl/bin/curl"
curl = if MacOS.version <= "10.6" && brewed_curl.exist?
brewed_curl
else
Pathname.new "/usr/bin/curl"
end
raise "#{curl} is not executable" unless curl.exist? && curl.executable?
flags = HOMEBREW_CURL_ARGS
flags = flags.delete("#") if ARGV.verbose?
args = [flags, HOMEBREW_USER_AGENT, *args]
args << "--verbose" if ENV["HOMEBREW_CURL_VERBOSE"]
args << "--silent" unless $stdout.tty?
safe_system curl, *args
end
def puts_columns(items, highlight = [])
return if items.empty?
unless $stdout.tty?
puts items
return
end
# TTY case: If possible, output using multiple columns.
console_width = Tty.width
console_width = 80 if console_width <= 0
max_len = items.max_by(&:length).length
col_gap = 2 # number of spaces between columns
gap_str = " " * col_gap
cols = (console_width + col_gap) / (max_len + col_gap)
cols = 1 if cols < 1
rows = (items.size + cols - 1) / cols
cols = (items.size + rows - 1) / rows # avoid empty trailing columns
plain_item_lengths = items.map(&:length) if cols >= 2
if highlight && highlight.any?
items = items.map do |item|
highlight.include?(item) ? "#{Tty.highlight}#{item}#{Tty.reset}" : item
end
end
if cols >= 2
col_width = (console_width + col_gap) / cols - col_gap
items = items.each_with_index.map do |item, index|
item + "".ljust(col_width - plain_item_lengths[index])
end
end
if cols == 1
puts items
else
rows.times do |row_index|
item_indices_for_row = row_index.step(items.size - 1, rows).to_a
puts items.values_at(*item_indices_for_row).join(gap_str)
end
end
end
def which(cmd, path = ENV["PATH"])
path.split(File::PATH_SEPARATOR).each do |p|
begin
pcmd = File.expand_path(cmd, p)
rescue ArgumentError
# File.expand_path will raise an ArgumentError if the path is malformed.
# See https://github.com/Homebrew/homebrew/issues/32789
next
end
return Pathname.new(pcmd) if File.file?(pcmd) && File.executable?(pcmd)
end
nil
end
def which_editor
editor = ENV.values_at("HOMEBREW_EDITOR", "VISUAL", "EDITOR").compact.first
return editor unless editor.nil?
# Find Textmate
editor = "mate" if which "mate"
# Find BBEdit / TextWrangler
editor ||= "edit" if which "edit"
# Find vim
editor ||= "vim" if which "vim"
# Default to standard vim
editor ||= "/usr/bin/vim"
opoo <<-EOS.undent
Using #{editor} because no editor was set in the environment.
This may change in the future, so we recommend setting EDITOR, VISUAL,
or HOMEBREW_EDITOR to your preferred text editor.
EOS
editor
end
def exec_editor(*args)
safe_exec(which_editor, *args)
end
def exec_browser(*args)
browser = ENV["HOMEBREW_BROWSER"] || ENV["BROWSER"] || OS::PATH_OPEN
safe_exec(browser, *args)
end
def safe_exec(cmd, *args)
# This buys us proper argument quoting and evaluation
# of environment variables in the cmd parameter.
exec "/bin/sh", "-c", "#{cmd} \"$@\"", "--", *args
end
# GZips the given paths, and returns the gzipped paths
def gzip(*paths)
paths.collect do |path|
with_system_path { safe_system "gzip", path }
Pathname.new("#{path}.gz")
end
end
# Returns array of architectures that the given command or library is built for.
def archs_for_command(cmd)
cmd = which(cmd) unless Pathname.new(cmd).absolute?
Pathname.new(cmd).archs
end
def ignore_interrupts(opt = nil)
std_trap = trap("INT") do
puts "One sec, just cleaning up" unless opt == :quietly
end
yield
ensure
trap("INT", std_trap)
end
def nostdout
if ARGV.verbose?
yield
else
begin
out = $stdout.dup
$stdout.reopen("/dev/null")
yield
ensure
$stdout.reopen(out)
out.close
end
end
end
def paths
@paths ||= ENV["PATH"].split(File::PATH_SEPARATOR).collect do |p|
begin
File.expand_path(p).chomp("/")
rescue ArgumentError
onoe "The following PATH component is invalid: #{p}"
end
end.uniq.compact
end
# return the shell profile file based on users' preference shell
def shell_profile
case ENV["SHELL"]
when %r{/(ba)?sh} then "~/.bash_profile"
when %r{/zsh} then "~/.zshrc"
when %r{/ksh} then "~/.kshrc"
else "~/.bash_profile"
end
end
module GitHub
extend self
ISSUES_URI = URI.parse("https://api.github.com/search/issues")
Error = Class.new(RuntimeError)
HTTPNotFoundError = Class.new(Error)
class RateLimitExceededError < Error
def initialize(reset, error)
super <<-EOS.undent
GitHub #{error}
Try again in #{pretty_ratelimit_reset(reset)}, or create an personal access token:
https://github.com/settings/tokens
and then set the token as: HOMEBREW_GITHUB_API_TOKEN
EOS
end
def pretty_ratelimit_reset(reset)
if (seconds = Time.at(reset) - Time.now) > 180
"%d minutes %d seconds" % [seconds / 60, seconds % 60]
else
"#{seconds} seconds"
end
end
end
class AuthenticationFailedError < Error
def initialize(error)
super <<-EOS.undent
GitHub #{error}
HOMEBREW_GITHUB_API_TOKEN may be invalid or expired, check:
https://github.com/settings/tokens
EOS
end
end
def open(url, &_block)
# This is a no-op if the user is opting out of using the GitHub API.
return if ENV["HOMEBREW_NO_GITHUB_API"]
require "net/https"
headers = {
"User-Agent" => HOMEBREW_USER_AGENT,
"Accept" => "application/vnd.github.v3+json"
}
headers["Authorization"] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN
begin
Kernel.open(url, headers) { |f| yield Utils::JSON.load(f.read) }
rescue OpenURI::HTTPError => e
handle_api_error(e)
rescue EOFError, SocketError, OpenSSL::SSL::SSLError => e
raise Error, "Failed to connect to: #{url}\n#{e.message}", e.backtrace
rescue Utils::JSON::Error => e
raise Error, "Failed to parse JSON response\n#{e.message}", e.backtrace
end
end
def handle_api_error(e)
if e.io.meta["x-ratelimit-remaining"].to_i <= 0
reset = e.io.meta.fetch("x-ratelimit-reset").to_i
error = Utils::JSON.load(e.io.read)["message"]
raise RateLimitExceededError.new(reset, error)
end
case e.io.status.first
when "401", "403"
raise AuthenticationFailedError.new(e.message)
when "404"
raise HTTPNotFoundError, e.message, e.backtrace
else
raise Error, e.message, e.backtrace
end
end
def issues_matching(query, qualifiers = {})
uri = ISSUES_URI.dup
uri.query = build_query_string(query, qualifiers)
open(uri) { |json| json["items"] }
end
def repository(user, repo)
open(URI.parse("https://api.github.com/repos/#{user}/#{repo}")) { |j| j }
end
def build_query_string(query, qualifiers)
s = "q=#{uri_escape(query)}+"
s << build_search_qualifier_string(qualifiers)
s << "&per_page=100"
end
def build_search_qualifier_string(qualifiers)
{
:repo => "Homebrew/homebrew",
:in => "title"
}.update(qualifiers).map do |qualifier, value|
"#{qualifier}:#{value}"
end.join("+")
end
def uri_escape(query)
if URI.respond_to?(:encode_www_form_component)
URI.encode_www_form_component(query)
else
require "erb"
ERB::Util.url_encode(query)
end
end
def issues_for_formula(name)
issues_matching(name, :state => "open")
end
def print_pull_requests_matching(query)
return [] if ENV["HOMEBREW_NO_GITHUB_API"]
ohai "Searching pull requests..."
open_or_closed_prs = issues_matching(query, :type => "pr")
open_prs = open_or_closed_prs.select { |i| i["state"] == "open" }
if open_prs.any?
puts "Open pull requests:"
prs = open_prs
elsif open_or_closed_prs.any?
puts "Closed pull requests:"
prs = open_or_closed_prs
else
return
end
prs.each { |i| puts "#{i["title"]} (#{i["html_url"]})" }
end
def private_repo?(user, repo)
uri = URI.parse("https://api.github.com/repos/#{user}/#{repo}")
open(uri) { |json| json["private"] }
end
end
|
#
# Author:: Lamont Granquist (<lamont@opscode.com>)
# Copyright:: Copyright (c) 2013 Lamont Granquist
# 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 'spec_helper'
describe Chef::Provider::RemoteFile::HTTP do
let(:uri) { URI.parse("http://opscode.com/seattle.txt") }
let(:existing_file_source) { nil }
let(:current_resource) do
current_resource = Chef::Resource::RemoteFile.new("/tmp/foo.txt")
current_resource.source(existing_file_source) if existing_file_source
current_resource.last_modified(Time.new)
current_resource.etag(nil)
current_resource
end
let(:new_resource) do
new_resource = Chef::Resource::RemoteFile.new("/tmp/foo.txt")
new_resource.headers({})
new_resource
end
describe "when contructing the object" do
describe "when the current resource has no source" do
it "stores the uri it is passed" do
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.uri.should == uri
end
it "stores any headers it is passed" do
headers = { "foo" => "foo", "bar" => "bar", "baz" => "baz" }
new_resource.headers(headers)
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.headers.should == headers
end
end
context "when the current file was fetched from the current URI" do
let(:existing_file_source) { ["http://opscode.com/seattle.txt"] }
it "stores the last_modified string in the headers when we are using last_modified headers and the uri matches the cache" do
new_resource.use_last_modified(true)
current_resource.last_modified(Time.new)
current_resource.etag(nil)
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.headers['if-modified-since'].should == current_resource.last_modified.strftime("%a, %d %b %Y %H:%M:%S %Z")
fetcher.headers.should_not have_key('if-none-match')
end
it "stores the etag string in the headers when we are using etag headers and the uri matches the cache" do
new_resource.use_etag(true)
new_resource.use_last_modified(false)
current_resource.last_modified(Time.new)
current_resource.etag("a_unique_identifier")
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.headers['if-none-match'].should == "\"#{current_resource.etag}\""
fetcher.headers.should_not have_key('if-modified-since')
end
end
describe "when use_last_modified is disabled in the new_resource" do
it "stores nil for the last_modified date" do
current_resource.stub!(:source).and_return(["http://opscode.com/seattle.txt"])
new_resource.should_receive(:use_last_modified).and_return(false)
current_resource.stub!(:last_modified).and_return(Time.new)
current_resource.stub!(:etag).and_return(nil)
Chef::Provider::RemoteFile::Util.should_receive(:uri_matches_string?).with(uri, current_resource.source[0]).and_return(true)
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.headers.should_not have_key('if-modified-since')
fetcher.headers.should_not have_key('if-none-match')
end
end
end
describe "when fetching the uri" do
let(:fetcher) do
Chef::Provider::RemoteFile::Util.should_receive(:uri_matches_string?).with(uri, current_resource.source[0]).and_return(true)
Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
end
let(:expected_http_opts) { {} }
let(:expected_http_args) { [uri, nil, nil, expected_http_opts] }
let(:tempfile) { mock(Tempfile) }
let(:last_response) { {} }
let(:rest) do
rest = mock(Chef::REST)
rest.stub!(:streaming_request).and_return(tempfile)
rest.stub!(:last_response).and_return(last_response)
rest
end
before do
new_resource.should_receive(:headers).and_return({})
new_resource.should_receive(:use_last_modified).and_return(false)
Chef::REST.should_receive(:new).with(*expected_http_args).and_return(rest)
end
it "should return a result" do
result = fetcher.fetch
result.should be_a_kind_of(Chef::Provider::RemoteFile::Result)
result.raw_file.should == tempfile
end
it "should propagate non-304 exceptions to the caller" do
r = Net::HTTPBadRequest.new("one", "two", "three")
e = Net::HTTPServerException.new("fake exception", r)
rest.stub!(:streaming_request).and_raise(e)
lambda { fetcher.fetch }.should raise_error(Net::HTTPServerException)
end
it "should return HTTPRetriableError when Chef::REST returns a 301" do
r = Net::HTTPMovedPermanently.new("one", "two", "three")
e = Net::HTTPRetriableError.new("301", r)
rest.stub!(:streaming_request).and_raise(e)
lambda { fetcher.fetch }.should raise_error(Net::HTTPRetriableError)
end
it "should return a nil tempfile for a 304 HTTPNotModifed" do
r = Net::HTTPNotModified.new("one", "two", "three")
e = Net::HTTPRetriableError.new("304", r)
rest.stub!(:streaming_request).and_raise(e)
result = fetcher.fetch
result.raw_file.should be_nil
end
context "and the response does not contain an etag" do
let(:last_response) { {"etag" => nil} }
it "does not include an etag in the result" do
result = fetcher.fetch
result.should be_a_kind_of(Chef::Provider::RemoteFile::Result)
result.etag.should be_nil
end
end
context "and the response has an etag header" do
let(:last_response) { {"etag" => "abc123"} }
it "includes the etag value in the response" do
result = fetcher.fetch
result.raw_file.should == tempfile
result.etag.should == "abc123"
end
end
context "and the response has no Date or Last-Modified header" do
let(:last_response) { {"date" => nil, "last_modified" => nil} }
it "does not set an mtime in the result" do
# RFC 2616 suggests that servers that do not set a Date header do not
# have a reliable clock, so no use in making them deal with dates.
result = fetcher.fetch
result.should be_a_kind_of(Chef::Provider::RemoteFile::Result)
result.mtime.should be_nil
end
end
context "and the response has a Last-Modified header" do
let(:last_response) do
# Last-Modified should be preferred to Date if both are set
{"date" => "Fri, 17 May 2013 23:23:23 GMT", "last_modified" => "Fri, 17 May 2013 11:11:11 GMT"}
end
it "sets the mtime to the Last-Modified time in the response" do
result = fetcher.fetch
result.should be_a_kind_of(Chef::Provider::RemoteFile::Result)
result.mtime.should == Time.at(1368789071).utc
end
end
context "and the response has a Date header but no Last-Modified header" do
let(:last_response) do
{"date" => "Fri, 17 May 2013 23:23:23 GMT", "last_modified" => nil}
end
it "sets the mtime to the Date in the response" do
result = fetcher.fetch
result.should be_a_kind_of(Chef::Provider::RemoteFile::Result)
result.mtime.should == Time.at(1368833003).utc
end
end
context "and the target file is a tarball [CHEF-3140]" do
let(:uri) { URI.parse("http://opscode.com/tarball.tgz") }
let(:expected_http_opts) { {:disable_gzip => true} }
# CHEF-3140
# Some servers return tarballs as content type tar and encoding gzip, which
# is totally wrong. When this happens and gzip isn't disabled, Chef::REST
# will decompress the file for you, which is not at all what you expected
# to happen (you end up with an uncomressed tar archive instead of the
# gzipped tar archive you expected). To work around this behavior, we
# detect when users are fetching gzipped files and turn off gzip in
# Chef::REST.
it "should disable gzip compression in the client" do
# Before block in the parent context has set an expectation on
# Chef::REST.new() being called with expected arguments. Here we fufil
# that expectation, so that we can explicitly set it for this test.
# This is intended to provide insurance that refactoring of the parent
# context does not negate the value of this particular example.
Chef::REST.new(*expected_http_args)
Chef::REST.should_receive(:new).once.with(*expected_http_args).and_return(rest)
fetcher.fetch
end
end
end
end
Add test coverage for updated URI case
Add assertions that etag and If-Modified-Since are not used when
fetching from a URI other than the one used to fetch the file
previously.
Additionally mark tests as pending for etag/last modified. According to
RFC, BOTH should be sent if available, but this is not current behavior.
#
# Author:: Lamont Granquist (<lamont@opscode.com>)
# Copyright:: Copyright (c) 2013 Lamont Granquist
# 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 'spec_helper'
describe Chef::Provider::RemoteFile::HTTP do
let(:uri) { URI.parse("http://opscode.com/seattle.txt") }
let(:existing_file_source) { nil }
let(:current_resource) do
current_resource = Chef::Resource::RemoteFile.new("/tmp/foo.txt")
current_resource.source(existing_file_source) if existing_file_source
current_resource.last_modified(Time.new)
current_resource.etag(nil)
current_resource
end
let(:new_resource) do
new_resource = Chef::Resource::RemoteFile.new("/tmp/foo.txt")
new_resource.headers({})
new_resource
end
def use_last_modified!
new_resource.use_last_modified(true)
current_resource.last_modified(Time.new)
current_resource.etag(nil)
end
def use_etags!
new_resource.use_etag(true)
new_resource.use_last_modified(false)
current_resource.last_modified(Time.new)
current_resource.etag("a_unique_identifier")
end
describe "when contructing the object" do
describe "when the current resource has no source" do
it "stores the uri it is passed" do
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.uri.should == uri
end
it "stores any headers it is passed" do
headers = { "foo" => "foo", "bar" => "bar", "baz" => "baz" }
new_resource.headers(headers)
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.headers.should == headers
end
end
context "when the existing file was fetched from a different URI" do
let(:existing_file_source) { ["http://opscode.com/tukwila.txt"] }
it "does not set a last modified header" do
use_last_modified!
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.headers.should_not have_key('if-none-match')
fetcher.headers.should_not have_key('if-modified-since')
end
it "does not set an etag header" do
use_etags!
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.headers.should_not have_key('if-none-match')
fetcher.headers.should_not have_key('if-modified-since')
end
end
context "when the current file was fetched from the current URI" do
let(:existing_file_source) { ["http://opscode.com/seattle.txt"] }
context "and using If-Modified-Since" do
before do
use_last_modified!
end
it "stores the last_modified string in the headers" do
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.headers['if-modified-since'].should == current_resource.last_modified.strftime("%a, %d %b %Y %H:%M:%S %Z")
fetcher.headers.should_not have_key('if-none-match')
pending("http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.4")
end
end
context "and using etags" do
before do
use_etags!
end
it "stores the etag string in the headers" do
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.headers['if-none-match'].should == "\"#{current_resource.etag}\""
fetcher.headers.should_not have_key('if-modified-since')
pending("http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.4")
end
end
end
describe "when use_last_modified is disabled in the new_resource" do
it "stores nil for the last_modified date" do
current_resource.stub!(:source).and_return(["http://opscode.com/seattle.txt"])
new_resource.should_receive(:use_last_modified).and_return(false)
current_resource.stub!(:last_modified).and_return(Time.new)
current_resource.stub!(:etag).and_return(nil)
Chef::Provider::RemoteFile::Util.should_receive(:uri_matches_string?).with(uri, current_resource.source[0]).and_return(true)
fetcher = Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
fetcher.headers.should_not have_key('if-modified-since')
fetcher.headers.should_not have_key('if-none-match')
end
end
end
describe "when fetching the uri" do
let(:fetcher) do
Chef::Provider::RemoteFile::Util.should_receive(:uri_matches_string?).with(uri, current_resource.source[0]).and_return(true)
Chef::Provider::RemoteFile::HTTP.new(uri, new_resource, current_resource)
end
let(:expected_http_opts) { {} }
let(:expected_http_args) { [uri, nil, nil, expected_http_opts] }
let(:tempfile) { mock(Tempfile) }
let(:last_response) { {} }
let(:rest) do
rest = mock(Chef::REST)
rest.stub!(:streaming_request).and_return(tempfile)
rest.stub!(:last_response).and_return(last_response)
rest
end
before do
new_resource.should_receive(:headers).and_return({})
new_resource.should_receive(:use_last_modified).and_return(false)
Chef::REST.should_receive(:new).with(*expected_http_args).and_return(rest)
end
it "should return a result" do
result = fetcher.fetch
result.should be_a_kind_of(Chef::Provider::RemoteFile::Result)
result.raw_file.should == tempfile
end
it "should propagate non-304 exceptions to the caller" do
r = Net::HTTPBadRequest.new("one", "two", "three")
e = Net::HTTPServerException.new("fake exception", r)
rest.stub!(:streaming_request).and_raise(e)
lambda { fetcher.fetch }.should raise_error(Net::HTTPServerException)
end
it "should return HTTPRetriableError when Chef::REST returns a 301" do
r = Net::HTTPMovedPermanently.new("one", "two", "three")
e = Net::HTTPRetriableError.new("301", r)
rest.stub!(:streaming_request).and_raise(e)
lambda { fetcher.fetch }.should raise_error(Net::HTTPRetriableError)
end
it "should return a nil tempfile for a 304 HTTPNotModifed" do
r = Net::HTTPNotModified.new("one", "two", "three")
e = Net::HTTPRetriableError.new("304", r)
rest.stub!(:streaming_request).and_raise(e)
result = fetcher.fetch
result.raw_file.should be_nil
end
context "and the response does not contain an etag" do
let(:last_response) { {"etag" => nil} }
it "does not include an etag in the result" do
result = fetcher.fetch
result.should be_a_kind_of(Chef::Provider::RemoteFile::Result)
result.etag.should be_nil
end
end
context "and the response has an etag header" do
let(:last_response) { {"etag" => "abc123"} }
it "includes the etag value in the response" do
result = fetcher.fetch
result.raw_file.should == tempfile
result.etag.should == "abc123"
end
end
context "and the response has no Date or Last-Modified header" do
let(:last_response) { {"date" => nil, "last_modified" => nil} }
it "does not set an mtime in the result" do
# RFC 2616 suggests that servers that do not set a Date header do not
# have a reliable clock, so no use in making them deal with dates.
result = fetcher.fetch
result.should be_a_kind_of(Chef::Provider::RemoteFile::Result)
result.mtime.should be_nil
end
end
context "and the response has a Last-Modified header" do
let(:last_response) do
# Last-Modified should be preferred to Date if both are set
{"date" => "Fri, 17 May 2013 23:23:23 GMT", "last_modified" => "Fri, 17 May 2013 11:11:11 GMT"}
end
it "sets the mtime to the Last-Modified time in the response" do
result = fetcher.fetch
result.should be_a_kind_of(Chef::Provider::RemoteFile::Result)
result.mtime.should == Time.at(1368789071).utc
end
end
context "and the response has a Date header but no Last-Modified header" do
let(:last_response) do
{"date" => "Fri, 17 May 2013 23:23:23 GMT", "last_modified" => nil}
end
it "sets the mtime to the Date in the response" do
result = fetcher.fetch
result.should be_a_kind_of(Chef::Provider::RemoteFile::Result)
result.mtime.should == Time.at(1368833003).utc
end
end
context "and the target file is a tarball [CHEF-3140]" do
let(:uri) { URI.parse("http://opscode.com/tarball.tgz") }
let(:expected_http_opts) { {:disable_gzip => true} }
# CHEF-3140
# Some servers return tarballs as content type tar and encoding gzip, which
# is totally wrong. When this happens and gzip isn't disabled, Chef::REST
# will decompress the file for you, which is not at all what you expected
# to happen (you end up with an uncomressed tar archive instead of the
# gzipped tar archive you expected). To work around this behavior, we
# detect when users are fetching gzipped files and turn off gzip in
# Chef::REST.
it "should disable gzip compression in the client" do
# Before block in the parent context has set an expectation on
# Chef::REST.new() being called with expected arguments. Here we fufil
# that expectation, so that we can explicitly set it for this test.
# This is intended to provide insurance that refactoring of the parent
# context does not negate the value of this particular example.
Chef::REST.new(*expected_http_args)
Chef::REST.should_receive(:new).once.with(*expected_http_args).and_return(rest)
fetcher.fetch
end
end
end
end
|
class Tty
class <<self
def blue; bold 34; end
def white; bold 39; end
def red; underline 31; end
def yellow; underline 33 ; end
def reset; escape 0; end
def em; underline 39; end
private
def color n
escape "0;#{n}"
end
def bold n
escape "1;#{n}"
end
def underline n
escape "4;#{n}"
end
def escape n
"\033[#{n}m" if $stdout.tty?
end
end
end
# args are additional inputs to puts until a nil arg is encountered
def ohai title, *sput
title = title.to_s[0, `/usr/bin/tput cols`.strip.to_i-4] unless ARGV.verbose?
puts "#{Tty.blue}==>#{Tty.white} #{title}#{Tty.reset}"
puts *sput unless sput.empty?
end
def opoo warning
puts "#{Tty.red}Warning#{Tty.reset}: #{warning}"
end
def onoe error
lines = error.to_s.split'\n'
puts "#{Tty.red}Error#{Tty.reset}: #{lines.shift}"
puts *lines unless lines.empty?
end
def pretty_duration s
return "2 seconds" if s < 3 # avoids the plural problem ;)
return "#{s.to_i} seconds" if s < 120
return "%.1f minutes" % (s/60)
end
def interactive_shell
fork do
# TODO make the PS1 var change pls
#brown="\[\033[0;33m\]"
#reset="\[\033[0m\]"
#ENV['PS1']="Homebrew-#{HOMEBREW_VERSION} #{brown}\W#{reset}\$ "
exec ENV['SHELL']
end
Process.wait
unless $?.success?
puts "Aborting due to non-zero exit status"
exit $?
end
end
module Homebrew
def self.system cmd, *args
puts "#{cmd} #{args*' '}" if ARGV.verbose?
fork do
yield if block_given?
args.collect!{|arg| arg.to_s}
exec(cmd, *args) rescue nil
exit! 1 # never gets here unless exec failed
end
Process.wait
$?.success?
end
end
# Kernel.system but with exceptions
def safe_system cmd, *args
raise ExecutionError.new(cmd, args, $?) unless Homebrew.system(cmd, *args)
end
# prints no output
def quiet_system cmd, *args
Homebrew.system(cmd, *args) do
$stdout.close
$stderr.close
end
end
def curl *args
safe_system 'curl', '-f#LA', HOMEBREW_USER_AGENT, *args unless args.empty?
end
def puts_columns items, cols = 4
return if items.empty?
if $stdout.tty?
# determine the best width to display for different console sizes
console_width = `/bin/stty size`.chomp.split(" ").last.to_i
console_width = 80 if console_width <= 0
longest = items.sort_by { |item| item.length }.last
optimal_col_width = (console_width.to_f / (longest.length + 2).to_f).floor
cols = optimal_col_width > 1 ? optimal_col_width : 1
IO.popen("/usr/bin/pr -#{cols} -t -w#{console_width}", "w"){|io| io.puts(items) }
else
puts *items
end
end
def exec_editor *args
editor=ENV['EDITOR']
if editor.nil?
if system "/usr/bin/which -s mate"
editor='mate'
else
editor='/usr/bin/vim'
end
end
# we split the editor because especially on mac "mate -w" is common
# but we still want to use the comma-delimited version of exec because then
# we don't have to escape args, and escaping 100% is tricky
exec *(editor.split+args)
end
# GZips the given path, and returns the gzipped file
def gzip path
system "/usr/bin/gzip", path
return Pathname.new(path+".gz")
end
# returns array of architectures suitable for -arch gcc flag
def archs_for_command cmd
cmd = cmd.to_s # If we were passed a Pathname, turn it into a string.
cmd = `/usr/bin/which #{cmd}` unless Pathname.new(cmd).absolute?
cmd.gsub! ' ', '\\ ' # Escape spaces in the filename.
IO.popen("/usr/bin/file #{cmd}").readlines.inject(%w[]) do |archs, line|
case line
when /Mach-O executable ppc/
archs << :ppc7400
when /Mach-O 64-bit executable ppc64/
archs << :ppc64
when /Mach-O executable i386/
archs << :i386
when /Mach-O 64-bit executable x86_64/
archs << :x86_64
else
archs
end
end
end
# String extensions added by inreplace below.
module HomebrewInreplaceExtension
# Looks for Makefile style variable defintions and replaces the
# value with "new_value", or removes the definition entirely.
def change_make_var! flag, new_value
new_value = "#{flag}=#{new_value}"
gsub! Regexp.new("^#{flag}[ \\t]*=[ \\t]*(.*)$"), new_value
end
# Removes variable assignments completely.
def remove_make_var! flags
flags.each do |flag|
# Also remove trailing \n, if present.
gsub! Regexp.new("^#{flag}[ \\t]*=(.*)$\n?"), ""
end
end
# Finds the specified variable
def get_make_var flag
m = match Regexp.new("^#{flag}[ \\t]*=[ \\t]*(.*)$")
return m[1] if m
return nil
end
end
def inreplace path, before=nil, after=nil
[*path].each do |path|
f = File.open(path, 'r')
s = f.read
if before == nil and after == nil
s.extend(HomebrewInreplaceExtension)
yield s
else
s.gsub!(before, after)
end
f.reopen(path, 'w').write(s)
f.close
end
end
def ignore_interrupts
std_trap = trap("INT") {}
yield
ensure
trap("INT", std_trap)
end
def nostdout
if ARGV.verbose?
yield
else
begin
require 'stringio'
real_stdout = $stdout
$stdout = StringIO.new
yield
ensure
$stdout = real_stdout
end
end
end
Make mod_wsgi and mod_python arch code more similar.
class Tty
class <<self
def blue; bold 34; end
def white; bold 39; end
def red; underline 31; end
def yellow; underline 33 ; end
def reset; escape 0; end
def em; underline 39; end
private
def color n
escape "0;#{n}"
end
def bold n
escape "1;#{n}"
end
def underline n
escape "4;#{n}"
end
def escape n
"\033[#{n}m" if $stdout.tty?
end
end
end
# args are additional inputs to puts until a nil arg is encountered
def ohai title, *sput
title = title.to_s[0, `/usr/bin/tput cols`.strip.to_i-4] unless ARGV.verbose?
puts "#{Tty.blue}==>#{Tty.white} #{title}#{Tty.reset}"
puts *sput unless sput.empty?
end
def opoo warning
puts "#{Tty.red}Warning#{Tty.reset}: #{warning}"
end
def onoe error
lines = error.to_s.split'\n'
puts "#{Tty.red}Error#{Tty.reset}: #{lines.shift}"
puts *lines unless lines.empty?
end
def pretty_duration s
return "2 seconds" if s < 3 # avoids the plural problem ;)
return "#{s.to_i} seconds" if s < 120
return "%.1f minutes" % (s/60)
end
def interactive_shell
fork do
# TODO make the PS1 var change pls
#brown="\[\033[0;33m\]"
#reset="\[\033[0m\]"
#ENV['PS1']="Homebrew-#{HOMEBREW_VERSION} #{brown}\W#{reset}\$ "
exec ENV['SHELL']
end
Process.wait
unless $?.success?
puts "Aborting due to non-zero exit status"
exit $?
end
end
module Homebrew
def self.system cmd, *args
puts "#{cmd} #{args*' '}" if ARGV.verbose?
fork do
yield if block_given?
args.collect!{|arg| arg.to_s}
exec(cmd, *args) rescue nil
exit! 1 # never gets here unless exec failed
end
Process.wait
$?.success?
end
end
# Kernel.system but with exceptions
def safe_system cmd, *args
raise ExecutionError.new(cmd, args, $?) unless Homebrew.system(cmd, *args)
end
# prints no output
def quiet_system cmd, *args
Homebrew.system(cmd, *args) do
$stdout.close
$stderr.close
end
end
def curl *args
safe_system 'curl', '-f#LA', HOMEBREW_USER_AGENT, *args unless args.empty?
end
def puts_columns items, cols = 4
return if items.empty?
if $stdout.tty?
# determine the best width to display for different console sizes
console_width = `/bin/stty size`.chomp.split(" ").last.to_i
console_width = 80 if console_width <= 0
longest = items.sort_by { |item| item.length }.last
optimal_col_width = (console_width.to_f / (longest.length + 2).to_f).floor
cols = optimal_col_width > 1 ? optimal_col_width : 1
IO.popen("/usr/bin/pr -#{cols} -t -w#{console_width}", "w"){|io| io.puts(items) }
else
puts *items
end
end
def exec_editor *args
editor=ENV['EDITOR']
if editor.nil?
if system "/usr/bin/which -s mate"
editor='mate'
else
editor='/usr/bin/vim'
end
end
# we split the editor because especially on mac "mate -w" is common
# but we still want to use the comma-delimited version of exec because then
# we don't have to escape args, and escaping 100% is tricky
exec *(editor.split+args)
end
# GZips the given path, and returns the gzipped file
def gzip path
system "/usr/bin/gzip", path
return Pathname.new(path+".gz")
end
# Returns array of architectures that the given command is built for.
def archs_for_command cmd
cmd = cmd.to_s # If we were passed a Pathname, turn it into a string.
cmd = `/usr/bin/which #{cmd}` unless Pathname.new(cmd).absolute?
cmd.gsub! ' ', '\\ ' # Escape spaces in the filename.
IO.popen("/usr/bin/file #{cmd}").readlines.inject(%w[]) do |archs, line|
case line
when /Mach-O executable ppc/
archs << :ppc7400
when /Mach-O 64-bit executable ppc64/
archs << :ppc64
when /Mach-O executable i386/
archs << :i386
when /Mach-O 64-bit executable x86_64/
archs << :x86_64
else
archs
end
end
end
# String extensions added by inreplace below.
module HomebrewInreplaceExtension
# Looks for Makefile style variable defintions and replaces the
# value with "new_value", or removes the definition entirely.
def change_make_var! flag, new_value
new_value = "#{flag}=#{new_value}"
gsub! Regexp.new("^#{flag}[ \\t]*=[ \\t]*(.*)$"), new_value
end
# Removes variable assignments completely.
def remove_make_var! flags
flags.each do |flag|
# Also remove trailing \n, if present.
gsub! Regexp.new("^#{flag}[ \\t]*=(.*)$\n?"), ""
end
end
# Finds the specified variable
def get_make_var flag
m = match Regexp.new("^#{flag}[ \\t]*=[ \\t]*(.*)$")
return m[1] if m
return nil
end
end
def inreplace path, before=nil, after=nil
[*path].each do |path|
f = File.open(path, 'r')
s = f.read
if before == nil and after == nil
s.extend(HomebrewInreplaceExtension)
yield s
else
s.gsub!(before, after)
end
f.reopen(path, 'w').write(s)
f.close
end
end
def ignore_interrupts
std_trap = trap("INT") {}
yield
ensure
trap("INT", std_trap)
end
def nostdout
if ARGV.verbose?
yield
else
begin
require 'stringio'
real_stdout = $stdout
$stdout = StringIO.new
yield
ensure
$stdout = real_stdout
end
end
end
|
require 'spec_helper'
# this hack is required for now to ensure that the path is set up correctly
# to retrive the parent provider
$LOAD_PATH.push(
File.join(
File.dirname(__FILE__),
'..',
'..',
'fixtures',
'modules',
'inifile',
'lib')
)
require 'puppet/type/ironic_api_paste_ini'
describe 'Puppet::Type.type(:ironic_api_paste_ini)' do
before :each do
@ironic_api_paste_ini = Puppet::Type.type(:ironic_api_paste_ini).new(:name => 'DEFAULT/foo', :value => 'bar')
end
it 'should accept a valid value' do
@ironic_api_paste_ini[:value] = 'bar'
expect(@ironic_api_paste_ini[:value]).to eq('bar')
end
it 'should autorequire the package that install the file' do
catalog = Puppet::Resource::Catalog.new
package = Puppet::Type.type(:package).new(:name => 'ironic')
catalog.add_resource package, @ironic_api_paste_ini
dependency = @ironic_api_paste_ini.autorequire
expect(dependency.size).to eq(1)
expect(dependency[0].target).to eq(@ironic_api_paste_ini)
expect(dependency[0].source).to eq(package)
end
end
Fix typo in ironic_api_paste_ini_spec.rb
TrivialFix
Change-Id: I1f5431536c65d40ed116bb9c988761aa9eeafcac
require 'spec_helper'
# this hack is required for now to ensure that the path is set up correctly
# to retrieve the parent provider
$LOAD_PATH.push(
File.join(
File.dirname(__FILE__),
'..',
'..',
'fixtures',
'modules',
'inifile',
'lib')
)
require 'puppet/type/ironic_api_paste_ini'
describe 'Puppet::Type.type(:ironic_api_paste_ini)' do
before :each do
@ironic_api_paste_ini = Puppet::Type.type(:ironic_api_paste_ini).new(:name => 'DEFAULT/foo', :value => 'bar')
end
it 'should accept a valid value' do
@ironic_api_paste_ini[:value] = 'bar'
expect(@ironic_api_paste_ini[:value]).to eq('bar')
end
it 'should autorequire the package that install the file' do
catalog = Puppet::Resource::Catalog.new
package = Puppet::Type.type(:package).new(:name => 'ironic')
catalog.add_resource package, @ironic_api_paste_ini
dependency = @ironic_api_paste_ini.autorequire
expect(dependency.size).to eq(1)
expect(dependency[0].target).to eq(@ironic_api_paste_ini)
expect(dependency[0].source).to eq(package)
end
end
|
require 'pathname'
require 'exceptions'
require 'os/mac'
require 'utils/json'
require 'utils/inreplace'
require 'open-uri'
class Tty
class << self
def blue; bold 34; end
def white; bold 39; end
def red; underline 31; end
def yellow; underline 33 ; end
def reset; escape 0; end
def em; underline 39; end
def green; color 92 end
def gray; bold 30 end
def width
`/usr/bin/tput cols`.strip.to_i
end
def truncate(str)
str.to_s[0, width - 4]
end
private
def color n
escape "0;#{n}"
end
def bold n
escape "1;#{n}"
end
def underline n
escape "4;#{n}"
end
def escape n
"\033[#{n}m" if $stdout.tty?
end
end
end
def ohai title, *sput
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.blue}==>#{Tty.white} #{title}#{Tty.reset}"
puts sput unless sput.empty?
end
def oh1 title
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.green}==>#{Tty.white} #{title}#{Tty.reset}"
end
def opoo warning
STDERR.puts "#{Tty.red}Warning#{Tty.reset}: #{warning}"
end
def onoe error
lines = error.to_s.split("\n")
STDERR.puts "#{Tty.red}Error#{Tty.reset}: #{lines.shift}"
STDERR.puts lines unless lines.empty?
end
def ofail error
onoe error
Homebrew.failed = true
end
def odie error
onoe error
exit 1
end
def pretty_duration s
return "2 seconds" if s < 3 # avoids the plural problem ;)
return "#{s.to_i} seconds" if s < 120
return "%.1f minutes" % (s/60)
end
def interactive_shell f=nil
unless f.nil?
ENV['HOMEBREW_DEBUG_PREFIX'] = f.prefix
ENV['HOMEBREW_DEBUG_INSTALL'] = f.name
end
fork {exec ENV['SHELL'] }
Process.wait
unless $?.success?
puts "Aborting due to non-zero exit status"
exit $?
end
end
module Homebrew
def self.system cmd, *args
puts "#{cmd} #{args*' '}" if ARGV.verbose?
fork do
yield if block_given?
args.collect!{|arg| arg.to_s}
exec(cmd.to_s, *args) rescue nil
exit! 1 # never gets here unless exec failed
end
Process.wait
$?.success?
end
end
def with_system_path
old_path = ENV['PATH']
ENV['PATH'] = '/usr/bin:/bin'
yield
ensure
ENV['PATH'] = old_path
end
# Kernel.system but with exceptions
def safe_system cmd, *args
unless Homebrew.system cmd, *args
args = args.map{ |arg| arg.to_s.gsub " ", "\\ " } * " "
raise ErrorDuringExecution, "Failure while executing: #{cmd} #{args}"
end
end
# prints no output
def quiet_system cmd, *args
Homebrew.system(cmd, *args) do
# Redirect output streams to `/dev/null` instead of closing as some programs
# will fail to execute if they can't write to an open stream.
$stdout.reopen('/dev/null')
$stderr.reopen('/dev/null')
end
end
def curl *args
curl = Pathname.new '/usr/bin/curl'
raise "#{curl} is not executable" unless curl.exist? and curl.executable?
args = [HOMEBREW_CURL_ARGS, HOMEBREW_USER_AGENT, *args]
# See https://github.com/Homebrew/homebrew/issues/6103
args << "--insecure" if MacOS.version < "10.6"
args << "--verbose" if ENV['HOMEBREW_CURL_VERBOSE']
args << "--silent" unless $stdout.tty?
safe_system curl, *args
end
def puts_columns items, star_items=[]
return if items.empty?
if star_items && star_items.any?
items = items.map{|item| star_items.include?(item) ? "#{item}*" : item}
end
if $stdout.tty?
# determine the best width to display for different console sizes
console_width = `/bin/stty size`.chomp.split(" ").last.to_i
console_width = 80 if console_width <= 0
longest = items.sort_by { |item| item.length }.last
optimal_col_width = (console_width.to_f / (longest.length + 2).to_f).floor
cols = optimal_col_width > 1 ? optimal_col_width : 1
IO.popen("/usr/bin/pr -#{cols} -t -w#{console_width}", "w"){|io| io.puts(items) }
else
puts items
end
end
def which cmd, path=ENV['PATH']
dir = path.split(File::PATH_SEPARATOR).find {|p| File.executable? File.join(p, cmd)}
Pathname.new(File.join(dir, cmd)) unless dir.nil?
end
def which_editor
editor = ENV.values_at('HOMEBREW_EDITOR', 'VISUAL', 'EDITOR').compact.first
# If an editor wasn't set, try to pick a sane default
return editor unless editor.nil?
# Find Textmate
return 'mate' if which "mate"
# Find BBEdit / TextWrangler
return 'edit' if which "edit"
# Default to vim
return '/usr/bin/vim'
end
def exec_editor *args
return if args.to_s.empty?
safe_exec(which_editor, *args)
end
def exec_browser *args
browser = ENV['HOMEBREW_BROWSER'] || ENV['BROWSER'] || "open"
safe_exec(browser, *args)
end
def safe_exec cmd, *args
# This buys us proper argument quoting and evaluation
# of environment variables in the cmd parameter.
exec "/bin/sh", "-i", "-c", cmd + ' "$@"', "--", *args
end
# GZips the given paths, and returns the gzipped paths
def gzip *paths
paths.collect do |path|
with_system_path { safe_system 'gzip', path }
Pathname.new("#{path}.gz")
end
end
# Returns array of architectures that the given command or library is built for.
def archs_for_command cmd
cmd = which(cmd) unless Pathname.new(cmd).absolute?
Pathname.new(cmd).archs
end
def ignore_interrupts(opt = nil)
std_trap = trap("INT") do
puts "One sec, just cleaning up" unless opt == :quietly
end
yield
ensure
trap("INT", std_trap)
end
def nostdout
if ARGV.verbose?
yield
else
begin
require 'stringio'
real_stdout = $stdout
$stdout = StringIO.new
yield
ensure
$stdout = real_stdout
end
end
end
def paths
@paths ||= ENV['PATH'].split(File::PATH_SEPARATOR).collect do |p|
begin
File.expand_path(p).chomp('/')
rescue ArgumentError
onoe "The following PATH component is invalid: #{p}"
end
end.uniq.compact
end
module GitHub extend self
ISSUES_URI = URI.parse("https://api.github.com/search/issues")
Error = Class.new(StandardError)
RateLimitExceededError = Class.new(Error)
HTTPNotFoundError = Class.new(Error)
def open url, headers={}, &block
# This is a no-op if the user is opting out of using the GitHub API.
return if ENV['HOMEBREW_NO_GITHUB_API']
require 'net/https' # for exception classes below
default_headers = {
"User-Agent" => HOMEBREW_USER_AGENT,
"Accept" => "application/vnd.github.v3+json",
}
default_headers['Authorization'] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN
Kernel.open(url, default_headers.merge(headers)) do |f|
yield Utils::JSON.load(f.read)
end
rescue OpenURI::HTTPError => e
if e.io.meta['x-ratelimit-remaining'].to_i <= 0
raise RateLimitExceededError, <<-EOS.undent, e.backtrace
GitHub #{Utils::JSON.load(e.io.read)['message']}
You may want to create an API token: https://github.com/settings/applications
and then set HOMEBREW_GITHUB_API_TOKEN.
EOS
elsif e.io.status.first == "404"
raise HTTPNotFoundError, e.message, e.backtrace
else
raise Error, e.message, e.backtrace
end
rescue SocketError, OpenSSL::SSL::SSLError => e
raise Error, "Failed to connect to: #{url}\n#{e.message}", e.backtrace
rescue Utils::JSON::Error => e
raise Error, "Failed to parse JSON response\n#{e.message}", e.backtrace
end
def issues_matching(query, qualifiers={})
uri = ISSUES_URI.dup
uri.query = build_query_string(query, qualifiers)
open(uri) { |json| json["items"] }
end
def build_query_string(query, qualifiers)
s = "q=#{uri_escape(query)}+"
s << build_search_qualifier_string(qualifiers)
s << "&per_page=100"
end
def build_search_qualifier_string(qualifiers)
{
:repo => "Homebrew/homebrew",
:in => "title",
}.update(qualifiers).map { |qualifier, value|
"#{qualifier}:#{value}"
}.join("+")
end
def uri_escape(query)
if URI.respond_to?(:encode_www_form_component)
URI.encode_www_form_component(query)
else
require "erb"
ERB::Util.url_encode(query)
end
end
def issues_for_formula name
# don't include issues that just refer to the tool in their body
issues_matching(name).select { |issue| issue["state"] == "open" }
end
def find_pull_requests query
return if ENV['HOMEBREW_NO_GITHUB_API']
puts "Searching pull requests..."
open_or_closed_prs = issues_matching(query).select do |issue|
issue["pull_request"]["html_url"]
end
open_prs = open_or_closed_prs.select {|i| i["state"] == "open" }
if open_prs.any?
puts "Open pull requests:"
prs = open_prs
elsif open_or_closed_prs.any?
puts "Closed pull requests:"
prs = open_or_closed_prs
else
return
end
prs.each {|i| yield "#{i["title"]} (#{i["pull_request"]["html_url"]})" }
end
def private_repo?(user, repo)
uri = URI.parse("https://api.github.com/repos/#{user}/#{repo}")
open(uri) { |json| json["private"] }
end
end
Offload more filtering to the search API
require 'pathname'
require 'exceptions'
require 'os/mac'
require 'utils/json'
require 'utils/inreplace'
require 'open-uri'
class Tty
class << self
def blue; bold 34; end
def white; bold 39; end
def red; underline 31; end
def yellow; underline 33 ; end
def reset; escape 0; end
def em; underline 39; end
def green; color 92 end
def gray; bold 30 end
def width
`/usr/bin/tput cols`.strip.to_i
end
def truncate(str)
str.to_s[0, width - 4]
end
private
def color n
escape "0;#{n}"
end
def bold n
escape "1;#{n}"
end
def underline n
escape "4;#{n}"
end
def escape n
"\033[#{n}m" if $stdout.tty?
end
end
end
def ohai title, *sput
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.blue}==>#{Tty.white} #{title}#{Tty.reset}"
puts sput unless sput.empty?
end
def oh1 title
title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
puts "#{Tty.green}==>#{Tty.white} #{title}#{Tty.reset}"
end
def opoo warning
STDERR.puts "#{Tty.red}Warning#{Tty.reset}: #{warning}"
end
def onoe error
lines = error.to_s.split("\n")
STDERR.puts "#{Tty.red}Error#{Tty.reset}: #{lines.shift}"
STDERR.puts lines unless lines.empty?
end
def ofail error
onoe error
Homebrew.failed = true
end
def odie error
onoe error
exit 1
end
def pretty_duration s
return "2 seconds" if s < 3 # avoids the plural problem ;)
return "#{s.to_i} seconds" if s < 120
return "%.1f minutes" % (s/60)
end
def interactive_shell f=nil
unless f.nil?
ENV['HOMEBREW_DEBUG_PREFIX'] = f.prefix
ENV['HOMEBREW_DEBUG_INSTALL'] = f.name
end
fork {exec ENV['SHELL'] }
Process.wait
unless $?.success?
puts "Aborting due to non-zero exit status"
exit $?
end
end
module Homebrew
def self.system cmd, *args
puts "#{cmd} #{args*' '}" if ARGV.verbose?
fork do
yield if block_given?
args.collect!{|arg| arg.to_s}
exec(cmd.to_s, *args) rescue nil
exit! 1 # never gets here unless exec failed
end
Process.wait
$?.success?
end
end
def with_system_path
old_path = ENV['PATH']
ENV['PATH'] = '/usr/bin:/bin'
yield
ensure
ENV['PATH'] = old_path
end
# Kernel.system but with exceptions
def safe_system cmd, *args
unless Homebrew.system cmd, *args
args = args.map{ |arg| arg.to_s.gsub " ", "\\ " } * " "
raise ErrorDuringExecution, "Failure while executing: #{cmd} #{args}"
end
end
# prints no output
def quiet_system cmd, *args
Homebrew.system(cmd, *args) do
# Redirect output streams to `/dev/null` instead of closing as some programs
# will fail to execute if they can't write to an open stream.
$stdout.reopen('/dev/null')
$stderr.reopen('/dev/null')
end
end
def curl *args
curl = Pathname.new '/usr/bin/curl'
raise "#{curl} is not executable" unless curl.exist? and curl.executable?
args = [HOMEBREW_CURL_ARGS, HOMEBREW_USER_AGENT, *args]
# See https://github.com/Homebrew/homebrew/issues/6103
args << "--insecure" if MacOS.version < "10.6"
args << "--verbose" if ENV['HOMEBREW_CURL_VERBOSE']
args << "--silent" unless $stdout.tty?
safe_system curl, *args
end
def puts_columns items, star_items=[]
return if items.empty?
if star_items && star_items.any?
items = items.map{|item| star_items.include?(item) ? "#{item}*" : item}
end
if $stdout.tty?
# determine the best width to display for different console sizes
console_width = `/bin/stty size`.chomp.split(" ").last.to_i
console_width = 80 if console_width <= 0
longest = items.sort_by { |item| item.length }.last
optimal_col_width = (console_width.to_f / (longest.length + 2).to_f).floor
cols = optimal_col_width > 1 ? optimal_col_width : 1
IO.popen("/usr/bin/pr -#{cols} -t -w#{console_width}", "w"){|io| io.puts(items) }
else
puts items
end
end
def which cmd, path=ENV['PATH']
dir = path.split(File::PATH_SEPARATOR).find {|p| File.executable? File.join(p, cmd)}
Pathname.new(File.join(dir, cmd)) unless dir.nil?
end
def which_editor
editor = ENV.values_at('HOMEBREW_EDITOR', 'VISUAL', 'EDITOR').compact.first
# If an editor wasn't set, try to pick a sane default
return editor unless editor.nil?
# Find Textmate
return 'mate' if which "mate"
# Find BBEdit / TextWrangler
return 'edit' if which "edit"
# Default to vim
return '/usr/bin/vim'
end
def exec_editor *args
return if args.to_s.empty?
safe_exec(which_editor, *args)
end
def exec_browser *args
browser = ENV['HOMEBREW_BROWSER'] || ENV['BROWSER'] || "open"
safe_exec(browser, *args)
end
def safe_exec cmd, *args
# This buys us proper argument quoting and evaluation
# of environment variables in the cmd parameter.
exec "/bin/sh", "-i", "-c", cmd + ' "$@"', "--", *args
end
# GZips the given paths, and returns the gzipped paths
def gzip *paths
paths.collect do |path|
with_system_path { safe_system 'gzip', path }
Pathname.new("#{path}.gz")
end
end
# Returns array of architectures that the given command or library is built for.
def archs_for_command cmd
cmd = which(cmd) unless Pathname.new(cmd).absolute?
Pathname.new(cmd).archs
end
def ignore_interrupts(opt = nil)
std_trap = trap("INT") do
puts "One sec, just cleaning up" unless opt == :quietly
end
yield
ensure
trap("INT", std_trap)
end
def nostdout
if ARGV.verbose?
yield
else
begin
require 'stringio'
real_stdout = $stdout
$stdout = StringIO.new
yield
ensure
$stdout = real_stdout
end
end
end
def paths
@paths ||= ENV['PATH'].split(File::PATH_SEPARATOR).collect do |p|
begin
File.expand_path(p).chomp('/')
rescue ArgumentError
onoe "The following PATH component is invalid: #{p}"
end
end.uniq.compact
end
module GitHub extend self
ISSUES_URI = URI.parse("https://api.github.com/search/issues")
Error = Class.new(StandardError)
RateLimitExceededError = Class.new(Error)
HTTPNotFoundError = Class.new(Error)
def open url, headers={}, &block
# This is a no-op if the user is opting out of using the GitHub API.
return if ENV['HOMEBREW_NO_GITHUB_API']
require 'net/https' # for exception classes below
default_headers = {
"User-Agent" => HOMEBREW_USER_AGENT,
"Accept" => "application/vnd.github.v3+json",
}
default_headers['Authorization'] = "token #{HOMEBREW_GITHUB_API_TOKEN}" if HOMEBREW_GITHUB_API_TOKEN
Kernel.open(url, default_headers.merge(headers)) do |f|
yield Utils::JSON.load(f.read)
end
rescue OpenURI::HTTPError => e
if e.io.meta['x-ratelimit-remaining'].to_i <= 0
raise RateLimitExceededError, <<-EOS.undent, e.backtrace
GitHub #{Utils::JSON.load(e.io.read)['message']}
You may want to create an API token: https://github.com/settings/applications
and then set HOMEBREW_GITHUB_API_TOKEN.
EOS
elsif e.io.status.first == "404"
raise HTTPNotFoundError, e.message, e.backtrace
else
raise Error, e.message, e.backtrace
end
rescue SocketError, OpenSSL::SSL::SSLError => e
raise Error, "Failed to connect to: #{url}\n#{e.message}", e.backtrace
rescue Utils::JSON::Error => e
raise Error, "Failed to parse JSON response\n#{e.message}", e.backtrace
end
def issues_matching(query, qualifiers={})
uri = ISSUES_URI.dup
uri.query = build_query_string(query, qualifiers)
open(uri) { |json| json["items"] }
end
def build_query_string(query, qualifiers)
s = "q=#{uri_escape(query)}+"
s << build_search_qualifier_string(qualifiers)
s << "&per_page=100"
end
def build_search_qualifier_string(qualifiers)
{
:repo => "Homebrew/homebrew",
:in => "title",
}.update(qualifiers).map { |qualifier, value|
"#{qualifier}:#{value}"
}.join("+")
end
def uri_escape(query)
if URI.respond_to?(:encode_www_form_component)
URI.encode_www_form_component(query)
else
require "erb"
ERB::Util.url_encode(query)
end
end
def issues_for_formula name
# don't include issues that just refer to the tool in their body
issues_matching(name, :state => "open")
end
def find_pull_requests query
return if ENV['HOMEBREW_NO_GITHUB_API']
puts "Searching pull requests..."
open_or_closed_prs = issues_matching(query, :type => "pr")
open_prs = open_or_closed_prs.select {|i| i["state"] == "open" }
if open_prs.any?
puts "Open pull requests:"
prs = open_prs
elsif open_or_closed_prs.any?
puts "Closed pull requests:"
prs = open_or_closed_prs
else
return
end
prs.each {|i| yield "#{i["title"]} (#{i["pull_request"]["html_url"]})" }
end
def private_repo?(user, repo)
uri = URI.parse("https://api.github.com/repos/#{user}/#{repo}")
open(uri) { |json| json["private"] }
end
end
|
require 'spec_helper'
RSpec.describe 'dwp_checks/new.html.slim', type: :view do
include Devise::TestHelpers
let(:user) { FactoryGirl.create :user }
let(:check) { FactoryGirl.build :dwp_check }
it 'contain the required fields' do
sign_in user
@dwp_checker = check
render
assert_select 'form label', text: 'Last Name'.to_s, count: 1
assert_select 'form label', text: 'Date of Birth'.to_s, count: 1
assert_select 'form label', text: 'NI Number'.to_s, count: 1
assert_select 'form label', text: 'Date fee paid'.to_s, count: 1
end
end
Updated spec to match loacle labels
require 'spec_helper'
RSpec.describe 'dwp_checks/new.html.slim', type: :view do
include Devise::TestHelpers
let(:user) { FactoryGirl.create :user }
let(:check) { FactoryGirl.build :dwp_check }
it 'contain the required fields' do
sign_in user
@dwp_checker = check
render
assert_select 'form label', text: t('activerecord.attributes.dwp_check.last_name').to_s, count: 1
assert_select 'form label', text: t('activerecord.attributes.dwp_check.dob').to_s, count: 1
assert_select 'form label', text: t('activerecord.attributes.dwp_check.ni_number').to_s, count: 1
assert_select 'form label', text: t('activerecord.attributes.dwp_check.date_to_check').to_s, count: 1
end
end
|
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'filentory/version'
Gem::Specification.new do |gem|
gem.name = "filentory-cli"
gem.version = Filentory::VERSION
gem.authors = ["Johnny Graber"]
gem.email = ["jg@jgraber.ch"]
gem.description = "A tool to create an filentory-cli of a storage medium"
gem.summary = "Filentory-cli is a first step to get order in a chaotic collection of storage medias."
gem.homepage = "https://github.com/jgraber/filentory-cli"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_development_dependency('rdoc')
gem.add_development_dependency('aruba')
gem.add_development_dependency('rake', '~> 10.1.1')
gem.add_dependency('methadone', '~> 1.3.1')
gem.add_dependency('oj', '~> 2.5.3')
gem.add_dependency('json_spec', '~> 1.1.1')
gem.add_dependency('exifr', '~> 1.1.3')
gem.add_dependency('xmp', '~> 0.2.0')
gem.add_dependency('streamio-ffmpeg', '~> 1.0.0')
end
fix description
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'filentory/version'
Gem::Specification.new do |gem|
gem.name = "filentory-cli"
gem.version = Filentory::VERSION
gem.authors = ["Johnny Graber"]
gem.email = ["jg@jgraber.ch"]
gem.description = "A tool to create an inventory of a storage medium"
gem.summary = "Filentory-cli is a first step to get order in a chaotic collection of storage medias."
gem.homepage = "https://github.com/jgraber/filentory-cli"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_development_dependency('rdoc')
gem.add_development_dependency('aruba')
gem.add_development_dependency('rake', '~> 10.1.1')
gem.add_dependency('methadone', '~> 1.3.1')
gem.add_dependency('oj', '~> 2.5.3')
gem.add_dependency('json_spec', '~> 1.1.1')
gem.add_dependency('exifr', '~> 1.1.3')
gem.add_dependency('xmp', '~> 0.2.0')
gem.add_dependency('streamio-ffmpeg', '~> 1.0.0')
end
|
#!/usr/bin/env ruby
#--
# Copyright 2004 by Jim Weirich (jim@weirichhouse.org).
# All rights reserved.
# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++
module Builder
# BlankSlate provides an abstract base class with no predefined
# methods (except for <tt>\_\_send__</tt> and <tt>\_\_id__</tt>).
# BlankSlate is useful as a base class when writing classes that
# depend upon <tt>method_missing</tt> (e.g. dynamic proxies).
class BlankSlate
class << self
def hide(name)
undef_method name unless name =~ /^(__|instance_eval)/
end
end
instance_methods.each { |m| hide(m) }
end
end
# Since Ruby is very dynamic, methods added to the ancestors of
# BlankSlate <em>after BlankSlate is defined</em> will show up in the
# list of available BlankSlate methods. We handle this by defining a hook in the Object and Kernel classes that will hide any defined
module Kernel
class << self
alias_method :blank_slate_method_added, :method_added
def method_added(name)
blank_slate_method_added(name)
return if self != Kernel
Builder::BlankSlate.hide(name)
end
end
end
class Object
class << self
alias_method :blank_slate_method_added, :method_added
def method_added(name)
blank_slate_method_added(name)
return if self != Object
Builder::BlankSlate.hide(name)
end
end
end
In BlankSlate, only remove if the method is actually an instance method.
git-svn-id: 5676d7e4220d6df15a2ea86614bcde0195e025e0@35 b15df707-ad1a-0410-81b8-e991873a3486
#!/usr/bin/env ruby
#--
# Copyright 2004 by Jim Weirich (jim@weirichhouse.org).
# All rights reserved.
# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.
#++
module Builder
# BlankSlate provides an abstract base class with no predefined
# methods (except for <tt>\_\_send__</tt> and <tt>\_\_id__</tt>).
# BlankSlate is useful as a base class when writing classes that
# depend upon <tt>method_missing</tt> (e.g. dynamic proxies).
class BlankSlate
class << self
def hide(name)
undef_method name if
instance_methods.include?(name.to_s) and
name !~ /^(__|instance_eval)/
end
end
instance_methods.each { |m| hide(m) }
end
end
# Since Ruby is very dynamic, methods added to the ancestors of
# BlankSlate <em>after BlankSlate is defined</em> will show up in the
# list of available BlankSlate methods. We handle this by defining a hook in the Object and Kernel classes that will hide any defined
module Kernel
class << self
alias_method :blank_slate_method_added, :method_added
def method_added(name)
blank_slate_method_added(name)
return if self != Kernel
Builder::BlankSlate.hide(name)
end
end
end
class Object
class << self
alias_method :blank_slate_method_added, :method_added
def method_added(name)
blank_slate_method_added(name)
return if self != Object
Builder::BlankSlate.hide(name)
end
end
end
|
Pod::Spec.new do |s|
s.name = 'MCTDataStructures'
s.version = '0.10.0'
s.license = 'MIT'
s.summary = 'Common data structures in Swift'
s.homepage = 'https://github.com/aamct2/MCTDataStructures'
s.authors = { 'Aaron McTavish' => 'aaron@mctavishsolutions.com' }
s.source = { :git => 'https://github.com/aamct2/MCTDataStructures.git', :tag => s.version }
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.11'
s.source_files = 'MCTDataStructures/*.swift'
s.requires_arc = true
end
Update MCTDataStructures.podspec
Update to Version 0.10.1
Pod::Spec.new do |s|
s.name = 'MCTDataStructures'
s.version = '0.10.1'
s.license = 'MIT'
s.summary = 'Common data structures in Swift'
s.homepage = 'https://github.com/aamct2/MCTDataStructures'
s.authors = { 'Aaron McTavish' => 'aaron@mctavishsolutions.com' }
s.source = { :git => 'https://github.com/aamct2/MCTDataStructures.git', :tag => s.version }
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.11'
s.source_files = 'MCTDataStructures/*.swift'
s.requires_arc = true
end
|
Pod::Spec.new do |s|
s.name = "MDFFontDiskLoader"
s.summary = "MDFFontDiskLoader"
s.version = "1.0.0"
s.authors = "The Material Foundation Authors"
s.license = "Apache 2.0"
s.homepage = "https://github.com/material-foundation/material-font-disk-loader-ios"
s.source = { :git => "https://github.com/material-foundation/material-font-disk-loader-ios.git", :tag => "v" + s.version.to_s }
s.platform = :ios, "8.0"
s.requires_arc = true
s.public_header_files = "src/*.h"
s.source_files = "src/*.{h,m,mm}", "src/private/*.{h,m,mm}"
end
changed min os to 7
Pod::Spec.new do |s|
s.name = "MDFFontDiskLoader"
s.summary = "MDFFontDiskLoader"
s.version = "1.0.0"
s.authors = "The Material Foundation Authors"
s.license = "Apache 2.0"
s.homepage = "https://github.com/material-foundation/material-font-disk-loader-ios"
s.source = { :git => "https://github.com/material-foundation/material-font-disk-loader-ios.git", :tag => "v" + s.version.to_s }
s.platform = :ios, "7.0"
s.requires_arc = true
s.public_header_files = "src/*.h"
s.source_files = "src/*.{h,m,mm}", "src/private/*.{h,m,mm}"
end
|
修复图片浏览器导航条
#
# Be sure to run `pod lib lint MUKit.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
# 先修改podspec文件,然后pod spec lint/pod lib lint验证通过后再git打标签,否则容易出错
# pod lib lint --allow-warnings --use-libraries
# 包含第三方库时使用pod repo push MUKit MUKit.podspec --allow-warnings --use-libraries验证
# 注册pod trunk register 392071745@qq.com 'Jekity' --verbose
# 发布到cocoapods pod trunk push MUKit.podspec --use-libraries --allow-warnings
# 在podfile文件中加入inhibit_all_warnings!可以消除pod库警告
Pod::Spec.new do |s|
s.name = 'MUKit'
s.version = '1.4.2'
s.summary = 'UITableView、UICollectionView、Signal、UINavigation、AliPay、weChatPay、Shared、Popup、Networking,runtime、Carousel、QRCode,Block,ScrollView、嵌套滚动 、MVVM、delegate、Refresh、route、路由、CheckBox、popupView 一款提高iOS开发效率的工具包MUKit'
s.description = <<-DESC
一款提高iOS开发效率的组件框架,涉及UITableView、UICollectionView、Signal、UINavigation、AliPay、weChatPay、Shared、Popup、Networking,runtime、Carousel、QRCode,Block,ScrollView、嵌套滚动 、MVVM、delegate、Refresh内容
DESC
s.homepage = 'https://github.com/Jeykit/MUKit'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Jeykit' => '392071745@qq.com' }
s.source = { :git => 'https://github.com/Jeykit/MUKit.git', :tag => s.version }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
#s.ios.deployment_target = '8.0'
#s.source_files = 'MUKit/Classes/**/*'
s.source_files = 'MUKit/Classes/MUKit.h'
s.public_header_files = 'MUKit/Classes/MUKit.h'
s.ios.deployment_target = '8.0'
#s.platform = :ios, '8.0' #支持的系统
s.subspec 'Normal' do |ss|
ss.source_files = 'MUKit/Classes/MUNormal/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUNormal/UIView+MUNormal.h'
end
s.subspec 'TipsView' do |ss|
ss.source_files = 'MUKit/Classes/MUTipsView/*.{h,m}'
end
s.subspec 'Public' do |ss|
ss.source_files = 'MUKit/Classes/Public/*.{h,m}'
end
s.subspec 'Image' do |ss|
ss.source_files = 'MUKit/Classes/UIImage/*.{h,m}'
end
s.subspec 'Color' do |ss|
ss.source_files = 'MUKit/Classes/UIColor/*.{h,m}'
end
s.subspec 'Refresh' do |ss|
ss.source_files = 'MUKit/Classes/Refresh/*.{h,m}'
ss.dependency 'MUKit/Normal'
end
s.subspec 'Signal' do |ss|
ss.source_files = 'MUKit/Classes/MUSignal/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUSignal/{MUSignal,UIView+MUSignal}.h'
end
s.subspec 'Carousel' do |ss|
ss.source_files = 'MUKit/Classes/Carousel/MUCarouselView.{h,m}'
ss.dependency 'SDWebImage'
end
s.subspec 'AdaptiveView' do |ss|
ss.source_files = 'MUKit/Classes/MUAdaptiveView/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUAdaptiveView/MUAdaptiveView.h'
ss.dependency 'SDWebImage'
end
s.subspec 'Navigation' do |ss|
ss.source_files = 'MUKit/Classes/MUNavigationController/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUNavigationController/MUNavigation.h'
ss.dependency 'YYModel'
end
s.subspec 'TableViewManager' do |ss|
ss.source_files = 'MUKit/Classes/MUTableViewManager/*.{h,m}'
ss.dependency 'MUKit/TipsView'
ss.dependency 'MUKit/Refresh'
ss.dependency 'MUKit/Public'
ss.dependency 'YYModel'
end
s.subspec 'PaperView' do |ss|
ss.source_files = 'MUKit/Classes/MUPaperView/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUPaperView/MUPaperView.h'
end
s.subspec 'Shared' do |ss|
ss.source_files = 'MUKit/Classes/MUShared/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUShared/MUShared{Manager,Object}.h'
#ss.dependency 'AliPay'
ss.dependency 'WeChat_SDK'
ss.dependency 'WeiboSDK'
ss.dependency 'TencentOpenApiSDK'
ss.dependency 'MUKit/Public'
end
s.subspec 'EPaymentManager' do |ss|
ss.source_files = 'MUKit/Classes/MUEPaymentManager/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUEPaymentManager/MUEPaymentManager.h'
ss.dependency 'MUKit/Public'
ss.dependency 'AliPay'
ss.dependency 'WeChat_SDK'
end
s.subspec 'PopupController' do |ss|
ss.source_files = 'MUKit/Classes/MUPopupController/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUPopupController/{MUPopup,MUPopupController,UIViewController+MUPopup}.h'
ss.dependency 'MUKit/Public'
end
s.subspec 'Encryption' do |ss|
ss.source_files = 'MUKit/Classes/MUEncryption/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUEncryption/MUEncryptionUtil.h'
ss.frameworks = 'Security'
end
s.subspec 'CollectionViewManager' do |ss|
ss.source_files = 'MUKit/Classes/MUCollectionViewManager/*.{h,m}'
ss.dependency 'YYModel'
ss.dependency 'MUKit/TipsView'
ss.dependency 'MUKit/Refresh'
ss.dependency 'MUKit/Public'
end
s.subspec 'QRCodeManager' do |ss|
ss.source_files = 'MUKit/Classes/QRCodeScan/{MUQRCodeManager,MU_Scan_Success}.{h,m,wav}'
end
s.subspec 'Networking' do |ss|
ss.source_files = 'MUKit/Classes/Networking/*.{h,m}'
ss.dependency 'YYModel'
ss.dependency 'AFNetworking'
end
s.subspec 'ScrollManager' do |ss|
ss.source_files = 'MUKit/Classes/MUScrollManager/*.{h,m}'
ss.dependency 'MUKit/Public'
end
s.subspec 'Checkbox' do |ss|
ss.source_files = 'MUKit/Classes/Checkbox/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/Checkbox/MUCheckbox.h'
end
s.subspec 'popupView' do |ss|
ss.source_files = 'MUKit/Classes/MUPopupView/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUPopupView/MUPopupView.h'
end
s.subspec 'ImagePickerManager' do |ss|
ss.source_files = 'MUKit/Classes/MUImagePickerManager/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUImagePickerManager/MUImagePickerManager.h'
ss.dependency 'MUKit/PhotoPreview'
end
s.subspec 'PhotoPreview' do |ss|
ss.source_files = 'MUKit/Classes/MUPhotoPreview/*.{h,m}'
ss.public_header_files = 'MUKit/Classes/MUPhotoPreview/MUPhotoPreviewController.h'
end
end
|
Pod::Spec.new do |s|
s.name = "MZDownloadManager"
s.version = "3.4"
s.summary = "NSURLSession based download manager."
s.description = <<-DESC
Download large files even in background, download multiple files, resume interrupted downloads.
DESC
s.homepage = "https://github.com/mzeeshanid/MZDownloadManager"
s.screenshots = "https://cloud.githubusercontent.com/assets/2767152/3459842/0c40fe66-0211-11e4-90d8-d8942c8f8651.png"
s.license = 'BSD'
s.author = { "Muhammad Zeeshan" => "mzeeshanid@yahoo.com" }
s.source = { :git => "https://github.com/mzeeshanid/MZDownloadManager.git", :tag => s.version }
s.social_media_url = 'https://twitter.com/mzeeshanid'
s.ios.deployment_target = '9.0'
s.source_files = 'MZDownloadManager/Classes/**/*'
s.frameworks = 'UIKit', 'Foundation'
end
swift version added in podspec
Pod::Spec.new do |s|
s.name = "MZDownloadManager"
s.version = "3.4"
s.summary = "NSURLSession based download manager."
s.description = <<-DESC
Download large files even in background, download multiple files, resume interrupted downloads.
DESC
s.homepage = "https://github.com/mzeeshanid/MZDownloadManager"
s.screenshots = "https://cloud.githubusercontent.com/assets/2767152/3459842/0c40fe66-0211-11e4-90d8-d8942c8f8651.png"
s.license = 'BSD'
s.author = { "Muhammad Zeeshan" => "mzeeshanid@yahoo.com" }
s.source = { :git => "https://github.com/mzeeshanid/MZDownloadManager.git", :tag => s.version }
s.social_media_url = 'https://twitter.com/mzeeshanid'
s.ios.deployment_target = '9.0'
s.source_files = 'MZDownloadManager/Classes/**/*'
s.frameworks = 'UIKit', 'Foundation'
s.swift_version = '4.0'
end
|
added CocoaPods support
Pod::Spec.new do |s|
s.name = "MultiToggleButton"
s.version = "1.0.0"
s.summary = "Multiple state tap to toggle UIButton in Swift"
s.description = <<-DESC
A UIButton subclass that implements tap-to-toggle button text. (Like the camera flash and timer buttons)
DESC
s.homepage = "https://github.com/yonat/MultiToggleButton"
s.screenshots = "https://raw.githubusercontent.com/yonat/MultiToggleButton/master/screenshots/toggle.gif"
s.license = { :type => "MIT", :file => "LICENSE.txt" }
s.author = { "Yonat Sharon" => "yonat@ootips.org" }
s.social_media_url = "http://twitter.com/yonatsharon"
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/yonat/MultiToggleButton.git", :tag => "1.0.0" }
s.source_files = "ToggleButton.swift"
s.requires_arc = true
end
|
Gem::Specification.new do |s|
s.name = 'gem-gratitude'
s.version = '0.1'
s.date = '2014-12-01'
s.summary = "Show all open GitHub issues for gems you require in your projects"
s.description = "Give back to gems you depend on! Show all open GitHub issues for gems you require in your projects"
s.authors = ["Dan Bartlett"]
s.email = 'danbartlett@gmail.com'
s.files = ["lib/gem-gratitude.rb", "bin/gem-gratitude"]
s.executables << 'gem-gratitude'
s.homepage = 'http://rubygems.org/gems/gem-gratitude'
s.license = 'MIT'
end
Add dependencies to .gemspec
Gem::Specification.new do |s|
s.name = 'gem-gratitude'
s.version = '0.1'
s.date = '2014-12-01'
s.summary = "Show all open GitHub issues for gems you require in your projects"
s.description = "Give back to gems you depend on! Show all open GitHub issues for gems you require in your projects"
s.authors = ["Dan Bartlett"]
s.email = 'danbartlett@gmail.com'
s.files = ["lib/gem-gratitude.rb", "bin/gem-gratitude"]
s.executables << 'gem-gratitude'
s.add_runtime_dependency "httparty"
s.add_runtime_dependency "redcarpet"
s.homepage = 'http://rubygems.org/gems/gem-gratitude'
s.license = 'MIT'
end |
Conductor::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)))'
resource :user_session
match 'login', :to => 'user_sessions#new', :as => 'login'
match 'logout', :to => 'user_sessions#destroy', :as => 'logout'
match 'register', :to => 'users#new', :as => 'register'
resource 'account', :to => 'users'
resources :users, :instances, :templates, :builds
resources :permissions, :collection => { :list => :get}
resources :settings do
collection do
get :self_service
get :general_settings
end
end
resources :pools do
get :hardware_profiles
get :realms
end
resources :pools, :collection => { :multi_destroy => :delete }
resources :deployments do
collection do
get 'multi_stop'
get 'launch_new'
get 'check_name'
end
end
resources :instances do
collection do
get 'start'
get 'multi_stop'
get 'remove_failed'
get 'can_start'
get 'can_create'
end
get 'key', :on => :member
end
#map.can_start_instance '/instances/:instance_id/can_start/:provider_account_id', :controller => 'instances', :action => 'can_start', :conditions => { :method => :get }
#map.can_create_instance '/instances/:instance_id/can_create/:provider_account_id', :controller => 'instances', :action => 'can_create', :conditions => { :method => :get }
resources :image_imports
resources :hardware_profiles do
delete 'multi_destroy', :on => :collection
end
resources :providers do
delete 'multi_destroy', :on => :collection
end
resources :provider_types, :only => :index
resources :users do
delete 'multi_destroy', :on => :collection
end
resources :provider_accounts do
collection do
delete 'multi_destroy'
get 'set_selected_provider'
end
end
resources :roles do
delete 'multi_destroy', :on => :collection
end
resources :settings do
collection do
get 'self_service'
get 'general_settings'
end
end
resources :pool_families do
collection do
delete 'multi_destroy'
post 'add_provider_account'
delete 'multi_destroy_provider_accounts'
end
end
resources :realms do
delete 'multi_destroy', :on => :collection
end
resources :realm_mappings do
delete 'multi_destroy', :on => :collection
end
resources :suggested_deployables do
delete 'multi_destroy', :on => :collection
end
#match 'matching_profiles', :to => '/hardware_profiles/matching_profiles/:hardware_profile_id/provider/:provider_id', :controller => 'hardware_profiles', :action => 'matching_profiles', :conditions => { :method => :get }, :as =>'matching_profiles'
match 'dashboard', :to => 'dashboard', :as => 'dashboard'
root :to => "pools#index"
match '/:controller(/:action(/:id))'
end
Fix duplicate Pool resource line in routes.rb
Resolves "undefined local variable or method `multi_destroy_pools_path'" error
Conductor::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)))'
resource :user_session
match 'login', :to => 'user_sessions#new', :as => 'login'
match 'logout', :to => 'user_sessions#destroy', :as => 'logout'
match 'register', :to => 'users#new', :as => 'register'
resource 'account', :to => 'users'
resources :users, :instances, :templates, :builds
resources :permissions, :collection => { :list => :get}
resources :settings do
collection do
get :self_service
get :general_settings
end
end
resources :pools do
get :hardware_profiles
get :realms
delete :multi_destroy, :on => :collection
end
resources :deployments do
collection do
get 'multi_stop'
get 'launch_new'
get 'check_name'
end
end
resources :instances do
collection do
get 'start'
get 'multi_stop'
get 'remove_failed'
get 'can_start'
get 'can_create'
end
get 'key', :on => :member
end
#map.can_start_instance '/instances/:instance_id/can_start/:provider_account_id', :controller => 'instances', :action => 'can_start', :conditions => { :method => :get }
#map.can_create_instance '/instances/:instance_id/can_create/:provider_account_id', :controller => 'instances', :action => 'can_create', :conditions => { :method => :get }
resources :image_imports
resources :hardware_profiles do
delete 'multi_destroy', :on => :collection
end
resources :providers do
delete 'multi_destroy', :on => :collection
end
resources :provider_types, :only => :index
resources :users do
delete 'multi_destroy', :on => :collection
end
resources :provider_accounts do
collection do
delete 'multi_destroy'
get 'set_selected_provider'
end
end
resources :roles do
delete 'multi_destroy', :on => :collection
end
resources :settings do
collection do
get 'self_service'
get 'general_settings'
end
end
resources :pool_families do
collection do
delete 'multi_destroy'
post 'add_provider_account'
delete 'multi_destroy_provider_accounts'
end
end
resources :realms do
delete 'multi_destroy', :on => :collection
end
resources :realm_mappings do
delete 'multi_destroy', :on => :collection
end
resources :suggested_deployables do
delete 'multi_destroy', :on => :collection
end
#match 'matching_profiles', :to => '/hardware_profiles/matching_profiles/:hardware_profile_id/provider/:provider_id', :controller => 'hardware_profiles', :action => 'matching_profiles', :conditions => { :method => :get }, :as =>'matching_profiles'
match 'dashboard', :to => 'dashboard', :as => 'dashboard'
root :to => "pools#index"
match '/:controller(/:action(/:id))'
end
|
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/geomock/rails/version', __FILE__)
Gem::Specification.new do |s|
s.name = "geomock-rails"
s.version = GeoMock::Rails::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Nikita Fedyashev"]
s.email = ["loci.master@gmail.com"]
s.homepage = "http://rubygems.org/gems/geomock-rails"
s.summary = "Use GeoMock with Rails 3"
s.description = "This gem provides geomock for your Rails 3 application."
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "geomock-rails"
s.add_dependency "railties", ">= 3.2.0.beta", "< 5.0"
s.add_dependency "thor", "~> 0.14"
s.files = `git ls-files`.split("\n")
s.executables = `git ls-files`.split("\n").select{|f| f =~ /^bin/}
s.require_path = 'lib'
end
be tolerant to old railties
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/geomock/rails/version', __FILE__)
Gem::Specification.new do |s|
s.name = "geomock-rails"
s.version = GeoMock::Rails::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Nikita Fedyashev"]
s.email = ["loci.master@gmail.com"]
s.homepage = "http://rubygems.org/gems/geomock-rails"
s.summary = "Use GeoMock with Rails 3"
s.description = "This gem provides geomock for your Rails 3 application."
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "geomock-rails"
s.add_dependency "railties", "~> 3.0", "< 5.0"
s.add_dependency "thor", "~> 0.14"
s.files = `git ls-files`.split("\n")
s.executables = `git ls-files`.split("\n").select{|f| f =~ /^bin/}
s.require_path = 'lib'
end
|
#
# Copyright 2011 Red Hat, Inc.
#
# 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.
#
class InstancesController < ApplicationController
before_filter :require_user
before_filter :load_instance, :only => [:show, :key, :edit, :update, :stop, :reboot]
before_filter :set_view_vars, :only => [:show, :index, :export_events]
before_filter :check_inaccessible_instances, :only => [:stop, :multi_stop]
def index
@params = params
@title = t("instances.instances.other")
save_breadcrumb(instances_path(:viewstate => viewstate_id))
load_instances
respond_to do |format|
format.html
format.js { render :partial => 'list' }
format.json { render :json => @instances.map{ |instance| view_context.instance_for_mustache(instance) } }
end
end
def new
respond_to do |format|
format.js
format.json
end
end
def create
end
def show
load_instances
save_breadcrumb(instance_path(@instance), @instance.name)
@events = @instance.events.paginate(:page => params[:page] || 1)
@view = params[:details_tab].blank? ? 'properties' : params[:details_tab]
@details_tab = 'properties' unless ['properties', 'history',
'parameters', 'permissions'].include?(@details_tab)
@tabs = [
{:name => t('properties'), :view => @view, :id => 'properties'},
{:name => t('instances.parameters.config_parameters'), :view => 'parameters', :id => 'parameters'},
{:name => t('history'), :view => 'history', :id => 'history'}
]
@details_tab = @tabs.find {|t| t[:view] == @view}
respond_to do |format|
format.html { render :action => 'show'}
format.js do
if params.delete :details_pane
render :partial => 'layouts/details_pane' and return
end
render :partial => @details_tab[:view] and return
end
format.json { render :json => @instance }
end
end
def edit
require_privilege(Privilege::MODIFY, @instance)
respond_to do |format|
format.html
format.js { render :partial => 'edit', :id => @instance.id }
format.json { render :json => @instance }
end
end
def update
# TODO - This USER_MUTABLE_ATTRS business is because what a user and app components can do
# will be greatly different. (e.g., a user shouldn't be able to change an instance's pool,
# since it won't do what they expect). As we build this out, this logic will become more complex.
attrs = {}
params[:instance].each_pair{|k,v| attrs[k] = v if Instance::USER_MUTABLE_ATTRS.include?(k)}
respond_to do |format|
if check_privilege(Privilege::MODIFY, @instance) and @instance.update_attributes(attrs)
flash[:success] = t('instances.flash.success.updated', :count => 1, :list => @instance.name)
format.html { redirect_to @instance }
format.js { render :partial => 'properties' }
format.json { render :json => @instance }
else
flash[:error] = t('instances.flash.error.not_updated', :count =>1, :list => @instance.name)
format.html { render :action => :edit }
format.js { render :partial => 'edit' }
format.json { render :json => @instance.errors, :status => :unprocessable_entity }
end
end
end
def destroy
destroyed = []
failed = []
Instance.find(ids_list).each do |instance|
if check_privilege(Privilege::MODIFY, instance) && instance.destroyable?
instance.destroy
destroyed << instance.name
else
failed << instance.name
end
end
flash[:success] = t('instances.flash.success.deleted', :list => destroyed.to_sentence, :count => destroyed.size) if destroyed.present?
flash[:error] = t('instances.flash.error.not_deleted', :list => failed.to_sentence, :count => failed.size) if failed.present?
respond_to do |format|
# FIXME: _list does not show flash messages, but I'm not sure that showing _list is proper anyway
format.html { render :action => :show }
format.js do
set_view_vars
load_instances
render :partial => 'list'
end
format.json { render :json => {:success => destroyed, :errors => failed} }
end
end
def key
respond_to do |format|
if @instance.instance_key.nil?
flash[:warning] = t "instances.flash.warning.ssh_key_not_found"
format.html { redirect_to instance_path(@instance) }
format.js { render :partial => 'properties' }
format.json { render :json => flash[:warning], :status => :not_found }
else
format.html { send_data @instance.instance_key.pem,
:filename => "#{@instance.instance_key.name}.pem",
:type => "text/plain" }
format.js do
send_data @instance.instance_key.pem,
:filename => "#{@instance.instance_key.name}.pem",
:type => "text/plain"
end
format.json { render :json => {:key => @instance.instance_key.pem,
:filename => "#{@instance.instance_key.name}.pem",
:type => "text/plain" } }
end
end
end
def multi_stop
notices = []
errors = []
@instances_to_stop.each do |instance|
begin
require_privilege(Privilege::USE,instance)
if @inaccessible_instances.include?(instance)
instance.forced_stop(current_user)
notices << "#{instance.name}: #{t('instances.flash.notice.forced_stop')}"
else
instance.stop(current_user)
notices << "#{instance.name}: #{t('instances.flash.notice.stop')}"
end
rescue Exception => err
errors << "#{instance.name}: " + err
logger.error err.message
logger.error err.backtrace.join("\n ")
end
end
errors = t('instances.none_selected') if errors.blank? && notices.blank?
flash[:notice] = notices unless notices.blank?
flash[:error] = errors unless errors.blank?
respond_to do |format|
format.html { redirect_to params[:backlink] || pools_path(:view => 'filter', :details_tab => 'instances') }
format.json { render :json => {:success => notices, :errors => errors} }
end
end
def export_events
send_data(Instance.csv_export(load_instances),
:type => 'text/csv; charset=utf-8; header=present',
:filename => "export.csv")
end
def stop
if @inaccessible_instances.include?(@instance)
do_operation(:forced_stop)
else
do_operation(:stop)
end
end
def reboot
do_operation(:reboot)
end
def multi_reboot
notices = []
errors = []
Instance.find(params[:instance_selected] || []).each do |instance|
begin
require_privilege(Privilege::USE,instance)
instance.reboot(current_user)
notices << "#{instance.name}: #{t('instances.flash.notice.reboot', :name => instance.name)}"
rescue Exception => err
errors << "#{instance.name}: " + err
logger.error err.message
logger.error err.backtrace.join("\n ")
end
end
# If nothing is selected, display an error message:
errors = t('instances.none_selected_to_reboot') if errors.blank? && notices.blank?
flash[:notice] = notices unless notices.blank?
flash[:error] = errors unless errors.blank?
respond_to do |format|
format.html { redirect_to params[:backlink] || pools_path(:view => 'filter', :details_tab => 'instances') }
format.json { render :json => {:success => notices, :errors => errors} }
end
end
def filter
redirect_to_original({"instances_preset_filter" => params[:instances_preset_filter], "instances_search" => params[:instances_search]})
end
private
def load_instance
@instance = Instance.find(Array(params[:id]).first)
require_privilege(Privilege::USE,@instance)
end
def init_new_instance_attrs
@pools = Pool.list_for_user(current_session, current_user,
Privilege::CREATE, Instance).
where(:enabled => true)
@realms = FrontendRealm.all
@hardware_profiles = HardwareProfile.all(
:include => :architecture,
:conditions => {
:provider_id => nil
#FIXME arch?
}
)
end
def set_view_vars
@header = [
{:name => t('instances.headers.vm_name'), :sort_attr => 'name'},
{:name => t('instances.headers.status'), :sortable => false},
{:name => t('instances.headers.public_address'), :sort_attr => 'public_addresses'},
{:name => t('instances.headers.provider'), :sortable => false},
{:name => t('instances.headers.created_by'), :sort_attr => 'users.last_name'},
]
@pools = Pool.list_for_user(current_session, current_user,
Privilege::CREATE, Instance)
end
def load_instances
if params[:deployment_id].blank?
@instances = paginate_collection(
Instance.includes(:owner).
apply_filters(:preset_filter_id => params[:instances_preset_filter],
:search_filter => params[:instances_search]).
list_for_user(current_session, current_user, Privilege::VIEW).
list(sort_column(Instance), sort_direction).
where("instances.pool_id" => @pools),
params[:page], PER_PAGE)
else
@instances = paginate_collection(
Instance.includes(:owner).
apply_filters(:preset_filter_id => params[:instances_preset_filter],
:search_filter => params[:instances_search]).
list(sort_column(Instance), sort_direction).
list_for_user(current_session, current_user, Privilege::VIEW).
where("instances.pool_id" => @pools,
"instances.deployment_id" => params[:deployment_id]),
params[:page], PER_PAGE)
end
end
def check_inaccessible_instances
# @instance is set only on stop action
@instances_to_stop = @instance ? @instance.to_a : Instance.find(params[:instance_selected].to_a)
@inaccessible_instances = Instance.stoppable_inaccessible_instances(@instances_to_stop)
if params[:terminate].blank? and @inaccessible_instances.any?
respond_to do |format|
format.html { render :action => :confirm_terminate }
format.json { render :json => {:inaccessbile_instances => @inaccessible_instances}, :status => :unprocessable_entity }
end
return false
end
return true
end
def do_operation(operation)
begin
@instance.send(operation, current_user)
flash[:notice] = t("instances.flash.notice.#{operation}", :name => @instance.name)
rescue Exception => err
flash[:error] = t("instances.flash.error.#{operation}", :name => @instance.name, :err => err)
end
respond_to do |format|
format.html { redirect_to deployment_path(@instance.deployment, :details_tab => 'instances') }
end
end
end
remove unused methods
#
# Copyright 2011 Red Hat, Inc.
#
# 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.
#
class InstancesController < ApplicationController
before_filter :require_user
before_filter :load_instance, :only => [:show, :key, :edit, :update, :stop, :reboot]
before_filter :set_view_vars, :only => [:show, :index, :export_events]
before_filter :check_inaccessible_instances, :only => [:stop, :multi_stop]
def index
@params = params
@title = t("instances.instances.other")
save_breadcrumb(instances_path(:viewstate => viewstate_id))
load_instances
respond_to do |format|
format.html
format.js { render :partial => 'list' }
format.json { render :json => @instances.map{ |instance| view_context.instance_for_mustache(instance) } }
end
end
def show
load_instances
save_breadcrumb(instance_path(@instance), @instance.name)
@events = @instance.events.paginate(:page => params[:page] || 1)
@view = params[:details_tab].blank? ? 'properties' : params[:details_tab]
@details_tab = 'properties' unless ['properties', 'history',
'parameters', 'permissions'].include?(@details_tab)
@tabs = [
{:name => t('properties'), :view => @view, :id => 'properties'},
{:name => t('instances.parameters.config_parameters'), :view => 'parameters', :id => 'parameters'},
{:name => t('history'), :view => 'history', :id => 'history'}
]
@details_tab = @tabs.find {|t| t[:view] == @view}
respond_to do |format|
format.html { render :action => 'show'}
format.js do
if params.delete :details_pane
render :partial => 'layouts/details_pane' and return
end
render :partial => @details_tab[:view] and return
end
format.json { render :json => @instance }
end
end
def edit
require_privilege(Privilege::MODIFY, @instance)
respond_to do |format|
format.html
format.js { render :partial => 'edit', :id => @instance.id }
format.json { render :json => @instance }
end
end
def update
# TODO - This USER_MUTABLE_ATTRS business is because what a user and app components can do
# will be greatly different. (e.g., a user shouldn't be able to change an instance's pool,
# since it won't do what they expect). As we build this out, this logic will become more complex.
attrs = {}
params[:instance].each_pair{|k,v| attrs[k] = v if Instance::USER_MUTABLE_ATTRS.include?(k)}
respond_to do |format|
if check_privilege(Privilege::MODIFY, @instance) and @instance.update_attributes(attrs)
flash[:success] = t('instances.flash.success.updated', :count => 1, :list => @instance.name)
format.html { redirect_to @instance }
format.js { render :partial => 'properties' }
format.json { render :json => @instance }
else
flash[:error] = t('instances.flash.error.not_updated', :count =>1, :list => @instance.name)
format.html { render :action => :edit }
format.js { render :partial => 'edit' }
format.json { render :json => @instance.errors, :status => :unprocessable_entity }
end
end
end
def destroy
destroyed = []
failed = []
Instance.find(ids_list).each do |instance|
if check_privilege(Privilege::MODIFY, instance) && instance.destroyable?
instance.destroy
destroyed << instance.name
else
failed << instance.name
end
end
flash[:success] = t('instances.flash.success.deleted', :list => destroyed.to_sentence, :count => destroyed.size) if destroyed.present?
flash[:error] = t('instances.flash.error.not_deleted', :list => failed.to_sentence, :count => failed.size) if failed.present?
respond_to do |format|
# FIXME: _list does not show flash messages, but I'm not sure that showing _list is proper anyway
format.html { render :action => :show }
format.js do
set_view_vars
load_instances
render :partial => 'list'
end
format.json { render :json => {:success => destroyed, :errors => failed} }
end
end
def key
respond_to do |format|
if @instance.instance_key.nil?
flash[:warning] = t "instances.flash.warning.ssh_key_not_found"
format.html { redirect_to instance_path(@instance) }
format.js { render :partial => 'properties' }
format.json { render :json => flash[:warning], :status => :not_found }
else
format.html { send_data @instance.instance_key.pem,
:filename => "#{@instance.instance_key.name}.pem",
:type => "text/plain" }
format.js do
send_data @instance.instance_key.pem,
:filename => "#{@instance.instance_key.name}.pem",
:type => "text/plain"
end
format.json { render :json => {:key => @instance.instance_key.pem,
:filename => "#{@instance.instance_key.name}.pem",
:type => "text/plain" } }
end
end
end
def multi_stop
notices = []
errors = []
@instances_to_stop.each do |instance|
begin
require_privilege(Privilege::USE,instance)
if @inaccessible_instances.include?(instance)
instance.forced_stop(current_user)
notices << "#{instance.name}: #{t('instances.flash.notice.forced_stop')}"
else
instance.stop(current_user)
notices << "#{instance.name}: #{t('instances.flash.notice.stop')}"
end
rescue Exception => err
errors << "#{instance.name}: " + err
logger.error err.message
logger.error err.backtrace.join("\n ")
end
end
errors = t('instances.none_selected') if errors.blank? && notices.blank?
flash[:notice] = notices unless notices.blank?
flash[:error] = errors unless errors.blank?
respond_to do |format|
format.html { redirect_to params[:backlink] || pools_path(:view => 'filter', :details_tab => 'instances') }
format.json { render :json => {:success => notices, :errors => errors} }
end
end
def export_events
send_data(Instance.csv_export(load_instances),
:type => 'text/csv; charset=utf-8; header=present',
:filename => "export.csv")
end
def stop
if @inaccessible_instances.include?(@instance)
do_operation(:forced_stop)
else
do_operation(:stop)
end
end
def reboot
do_operation(:reboot)
end
def multi_reboot
notices = []
errors = []
Instance.find(params[:instance_selected] || []).each do |instance|
begin
require_privilege(Privilege::USE,instance)
instance.reboot(current_user)
notices << "#{instance.name}: #{t('instances.flash.notice.reboot', :name => instance.name)}"
rescue Exception => err
errors << "#{instance.name}: " + err
logger.error err.message
logger.error err.backtrace.join("\n ")
end
end
# If nothing is selected, display an error message:
errors = t('instances.none_selected_to_reboot') if errors.blank? && notices.blank?
flash[:notice] = notices unless notices.blank?
flash[:error] = errors unless errors.blank?
respond_to do |format|
format.html { redirect_to params[:backlink] || pools_path(:view => 'filter', :details_tab => 'instances') }
format.json { render :json => {:success => notices, :errors => errors} }
end
end
def filter
redirect_to_original({"instances_preset_filter" => params[:instances_preset_filter], "instances_search" => params[:instances_search]})
end
private
def load_instance
@instance = Instance.find(Array(params[:id]).first)
require_privilege(Privilege::USE,@instance)
end
def init_new_instance_attrs
@pools = Pool.list_for_user(current_session, current_user,
Privilege::CREATE, Instance).
where(:enabled => true)
@realms = FrontendRealm.all
@hardware_profiles = HardwareProfile.all(
:include => :architecture,
:conditions => {
:provider_id => nil
#FIXME arch?
}
)
end
def set_view_vars
@header = [
{:name => t('instances.headers.vm_name'), :sort_attr => 'name'},
{:name => t('instances.headers.status'), :sortable => false},
{:name => t('instances.headers.public_address'), :sort_attr => 'public_addresses'},
{:name => t('instances.headers.provider'), :sortable => false},
{:name => t('instances.headers.created_by'), :sort_attr => 'users.last_name'},
]
@pools = Pool.list_for_user(current_session, current_user,
Privilege::CREATE, Instance)
end
def load_instances
if params[:deployment_id].blank?
@instances = paginate_collection(
Instance.includes(:owner).
apply_filters(:preset_filter_id => params[:instances_preset_filter],
:search_filter => params[:instances_search]).
list_for_user(current_session, current_user, Privilege::VIEW).
list(sort_column(Instance), sort_direction).
where("instances.pool_id" => @pools),
params[:page], PER_PAGE)
else
@instances = paginate_collection(
Instance.includes(:owner).
apply_filters(:preset_filter_id => params[:instances_preset_filter],
:search_filter => params[:instances_search]).
list(sort_column(Instance), sort_direction).
list_for_user(current_session, current_user, Privilege::VIEW).
where("instances.pool_id" => @pools,
"instances.deployment_id" => params[:deployment_id]),
params[:page], PER_PAGE)
end
end
def check_inaccessible_instances
# @instance is set only on stop action
@instances_to_stop = @instance ? @instance.to_a : Instance.find(params[:instance_selected].to_a)
@inaccessible_instances = Instance.stoppable_inaccessible_instances(@instances_to_stop)
if params[:terminate].blank? and @inaccessible_instances.any?
respond_to do |format|
format.html { render :action => :confirm_terminate }
format.json { render :json => {:inaccessbile_instances => @inaccessible_instances}, :status => :unprocessable_entity }
end
return false
end
return true
end
def do_operation(operation)
begin
@instance.send(operation, current_user)
flash[:notice] = t("instances.flash.notice.#{operation}", :name => @instance.name)
rescue Exception => err
flash[:error] = t("instances.flash.error.#{operation}", :name => @instance.name, :err => err)
end
respond_to do |format|
format.html { redirect_to deployment_path(@instance.deployment, :details_tab => 'instances') }
end
end
end
|
require 'util/repository_manager'
class TemplatesController < ApplicationController
before_filter :require_user
before_filter :check_permission, :except => [:index, :builds]
def section_id
'build'
end
def index
# TODO: add template permission check
require_privilege(Privilege::IMAGE_VIEW)
@order_dir = params[:order_dir] == 'desc' ? 'desc' : 'asc'
@order_field = params[:order_field] || 'name'
@templates = Template.find(
:all,
:include => :images,
:order => @order_field + ' ' + @order_dir
)
end
def action
if params[:new_template]
redirect_to :action => 'new'
elsif params[:assembly]
redirect_to :action => 'assembly'
elsif params[:deployment_definition]
redirect_to :action => 'deployment_definition'
elsif params[:delete]
redirect_to :action => 'delete', :ids => params[:ids].to_a
elsif params[:edit]
redirect_to :action => 'new', :id => get_selected_id
elsif params[:build]
redirect_to :action => 'build_form', 'image[template_id]' => get_selected_id
else
raise "Unknown action"
end
end
def new
# can't use @template variable - is used by compass (or something other)
@tpl = Template.find_or_create(params[:id])
@repository_manager = RepositoryManager.new
@groups = @repository_manager.all_groups(params[:repository])
end
#def select_package
# update_group_or_package(:add_package, params[:package], params[:group])
# render :action => 'new'
#end
#def remove_package
# update_group_or_package(:remove_package, params[:package], params[:group])
# render :action => 'new'
#end
def create
@tpl = (params[:tpl] && !params[:tpl][:id].to_s.empty?) ? Template.find(params[:tpl][:id]) : Template.new(params[:tpl])
# this is crazy, but we have most attrs in xml and also in model,
# synchronize it at first to xml
@tpl.update_xml_attributes!(params[:tpl])
# if remove pkg, we only update xml and render 'new' template
# again
params.keys.each do |param|
if param =~ /^remove_package_(.*)$/
update_group_or_package(:remove_package, $1, nil)
render :action => 'new'
return
end
end
if params[:add_software_form]
@repository_manager = RepositoryManager.new
@groups = @repository_manager.all_groups_with_tagged_selected_packages(@tpl.xml.packages, params[:repository])
render :action => 'add_software_form'
return
end
if @tpl.save
flash[:notice] = "Template saved."
@tpl.set_complete
redirect_to :action => 'index'
else
@repository_manager = RepositoryManager.new
@groups = @repository_manager.all_groups(params[:repository])
render :action => 'new'
end
end
def add_software
@tpl = params[:template_id].to_s.empty? ? Template.new : Template.find(params[:template_id])
@repository_manager = RepositoryManager.new
@groups = @repository_manager.all_groups(params[:repository])
if params[:add_selected]
params[:groups].to_a.each { |group| @tpl.xml.add_group(group) }
params[:packages].to_a.each { |pkg| @tpl.xml.add_package(pkg, nil) }
@tpl.save_xml!
end
if params[:ajax]
render :partial => 'managed_content'
else
render :action => 'new'
end
end
def build_form
raise "select template to build" unless params[:image] and params[:image][:template_id]
@image = Image.new(params[:image])
@all_targets = Image.available_targets
end
def build
if params[:cancel]
redirect_to :action => 'index'
return
end
#FIXME: The following functionality needs to come out of the controller
@image = Image.new(params[:image])
@image.template.upload_template unless @image.template.uploaded
# FIXME: this will need to re-render build with error messages,
# just fails right now if anything is wrong (like no target selected).
params[:targets].each do |target|
i = Image.new_if_not_exists(
:name => "#{@image.template.xml.name}/#{target}",
:target => target,
:template_id => @image.template_id,
:status => Image::STATE_QUEUED
)
# FIXME: This will need to be enhanced to handle multiple
# providers of same type, only one is supported right now
if i
image = Image.find_by_template_id(params[:image][:template_id],
:conditions => {:target => target})
ReplicatedImage.create!(
:image_id => image.id,
:provider_id => Provider.find_by_cloud_type(target)
)
end
end
redirect_to :action => 'builds'
end
def builds
@running_images = Image.all(:include => :template, :conditions => ['status IN (?)', Image::ACTIVE_STATES])
@completed_images = Image.all(:include => :template, :conditions => {:status => Image::STATE_COMPLETE})
require_privilege(Privilege::IMAGE_VIEW)
end
def delete
Template.destroy(params[:ids].to_a)
redirect_to :action => 'index'
end
def assembly
end
def deployment_definition
@all_targets = Image.available_targets
end
private
def update_group_or_package(method, *args)
@repository_manager = RepositoryManager.new
@groups = @repository_manager.all_groups(params[:repository])
@tpl.xml.send(method, *args)
# we save template w/o validation (we can add package before name,... is
# set)
@tpl.save_xml!
end
def check_permission
require_privilege(Privilege::IMAGE_MODIFY)
end
def get_selected_id
ids = params[:ids].to_a
if ids.size != 1
raise "No template is selected" if ids.empty?
raise "You can select only one template" if ids.size > 1
end
return ids.first
end
end
Multiple templates were created when adding packages
require 'util/repository_manager'
class TemplatesController < ApplicationController
before_filter :require_user
before_filter :check_permission, :except => [:index, :builds]
def section_id
'build'
end
def index
# TODO: add template permission check
require_privilege(Privilege::IMAGE_VIEW)
@order_dir = params[:order_dir] == 'desc' ? 'desc' : 'asc'
@order_field = params[:order_field] || 'name'
@templates = Template.find(
:all,
:include => :images,
:order => @order_field + ' ' + @order_dir
)
end
def action
if params[:new_template]
redirect_to :action => 'new'
elsif params[:assembly]
redirect_to :action => 'assembly'
elsif params[:deployment_definition]
redirect_to :action => 'deployment_definition'
elsif params[:delete]
redirect_to :action => 'delete', :ids => params[:ids].to_a
elsif params[:edit]
redirect_to :action => 'new', :id => get_selected_id
elsif params[:build]
redirect_to :action => 'build_form', 'image[template_id]' => get_selected_id
else
raise "Unknown action"
end
end
def new
# can't use @template variable - is used by compass (or something other)
@tpl = Template.find_or_create(params[:id])
@repository_manager = RepositoryManager.new
@groups = @repository_manager.all_groups(params[:repository])
end
#def select_package
# update_group_or_package(:add_package, params[:package], params[:group])
# render :action => 'new'
#end
#def remove_package
# update_group_or_package(:remove_package, params[:package], params[:group])
# render :action => 'new'
#end
def create
if params[:cancel]
redirect_to :action => 'index'
return
end
@tpl = (params[:tpl] && !params[:tpl][:id].to_s.empty?) ? Template.find(params[:tpl][:id]) : Template.new(params[:tpl])
unless params[:add_software_form] and request.xhr?
# this is crazy, but we have most attrs in xml and also in model,
# synchronize it at first to xml
@tpl.update_xml_attributes!(params[:tpl])
end
# if remove pkg, we only update xml and render 'new' template
# again
params.keys.each do |param|
if param =~ /^remove_package_(.*)$/
update_group_or_package(:remove_package, $1, nil)
render :action => 'new'
return
end
end
if params[:add_software_form]
@repository_manager = RepositoryManager.new
@groups = @repository_manager.all_groups_with_tagged_selected_packages(@tpl.xml.packages, params[:repository])
render :action => 'add_software_form'
return
end
if @tpl.save
flash[:notice] = "Template saved."
@tpl.set_complete
redirect_to :action => 'index'
else
@repository_manager = RepositoryManager.new
@groups = @repository_manager.all_groups(params[:repository])
render :action => 'new'
end
end
def add_software
@tpl = params[:template_id].to_s.empty? ? Template.new : Template.find(params[:template_id])
@repository_manager = RepositoryManager.new
@groups = @repository_manager.all_groups(params[:repository])
if params[:add_selected]
params[:groups].to_a.each { |group| @tpl.xml.add_group(group) }
params[:packages].to_a.each { |pkg| @tpl.xml.add_package(pkg, nil) }
@tpl.save_xml!
end
if params[:ajax]
render :partial => 'managed_content'
else
render :action => 'new'
end
end
def build_form
raise "select template to build" unless params[:image] and params[:image][:template_id]
@image = Image.new(params[:image])
@all_targets = Image.available_targets
end
def build
if params[:cancel]
redirect_to :action => 'index'
return
end
#FIXME: The following functionality needs to come out of the controller
@image = Image.new(params[:image])
@image.template.upload_template unless @image.template.uploaded
# FIXME: this will need to re-render build with error messages,
# just fails right now if anything is wrong (like no target selected).
params[:targets].each do |target|
i = Image.new_if_not_exists(
:name => "#{@image.template.xml.name}/#{target}",
:target => target,
:template_id => @image.template_id,
:status => Image::STATE_QUEUED
)
# FIXME: This will need to be enhanced to handle multiple
# providers of same type, only one is supported right now
if i
image = Image.find_by_template_id(params[:image][:template_id],
:conditions => {:target => target})
ReplicatedImage.create!(
:image_id => image.id,
:provider_id => Provider.find_by_cloud_type(target)
)
end
end
redirect_to :action => 'builds'
end
def builds
@running_images = Image.all(:include => :template, :conditions => ['status IN (?)', Image::ACTIVE_STATES])
@completed_images = Image.all(:include => :template, :conditions => {:status => Image::STATE_COMPLETE})
require_privilege(Privilege::IMAGE_VIEW)
end
def delete
Template.destroy(params[:ids].to_a)
redirect_to :action => 'index'
end
def assembly
end
def deployment_definition
@all_targets = Image.available_targets
end
private
def update_group_or_package(method, *args)
@repository_manager = RepositoryManager.new
@groups = @repository_manager.all_groups(params[:repository])
@tpl.xml.send(method, *args)
# we save template w/o validation (we can add package before name,... is
# set)
@tpl.save_xml!
end
def check_permission
require_privilege(Privilege::IMAGE_MODIFY)
end
def get_selected_id
ids = params[:ids].to_a
if ids.size != 1
raise "No template is selected" if ids.empty?
raise "You can select only one template" if ids.size > 1
end
return ids.first
end
end
|
#!/usr/bin/ruby -w
#-----------------------------------------------------------------------------
# Name : ghetto-timemachine.rb
# Author : Mike Hanby <mhanby@uab.edu>
# Organization: University of Alabama at Birmingham
# Description : This script is used for backing up a *NIX workstation using the
# classic Rsync using Hardlinks rotation technique described at this URL:
# http://www.mikerubel.org/computers/rsync_snapshots/
#
# Usage : $0 --src ~/Documents --dest /backups/userA --excludes \*.iso,.svn
# Date : 2012-03-20 10:30:19
# Type : Utility
#
#-----------------------------------------------------------------------------
# History
# 20120328 - mhanby - I've moved much of the file and directory operations into
# methods so that the method handles all of the local / remote file system
# specific code
# * mkdir(dir, ssh)
# * rmdir(dir, ssh)
# * mvdir(src, dest, ssh)
# * soft_link(dir, link, ssh)
# * hard_link(src, dest, ssh)
# * disk_free(path, ssh)
# * run_rsync(opts, src, dest, ssh)
# * update_mtime(dest, ssh)
#
# 20120327 - mhanby - I originally intended to use net-ssh for remote commands
# and net-sftp for directory operations (create, delete, rename) thinking sftp
# was better suited for that. Based on testing, it's much easier doing all of
# the remote operations using net-ssh.
#
# 20120324 - mhanby - adding support for backing up to remote storage over SSH
# using net-ssh and net-sftp gems
# Notes on installing and using gems:
# 1. Add the following to ~/.bashrc
# export GEM_HOME=$HOME/.ruby/lib/ruby/gems/1.8
# export RUBYLIB=$HOME/.ruby/lib:$HOME/.ruby/lib/site_ruby/1.8:$RUBYLIB
# 2. Install rubygems package (alternatively, download and stall it manually
# 3. Install the gems
# gem install net-ssh
# gem install net-sftp
#
# 20120323 - mhanby - Fixed bug in the summary report, needed a new time object
# to display the finish time, report was displaying start time twice
#
# 20120322 - mhanby - Created new hard_link method that runs the cp -al system
# command, replaced all refernces with the new method call hard_link(src, dest)
#
# Added code to handle spaces in the paths
#
# 20120322 - mhanby - Initial version, ported code from my Perl script of the
# same name as an exercise in Ruby
#
#-----------------------------------------------------------------------------
# Todo / Things that don't work
# FIXED - 1. Source and Dest with spaces in the path don't currently work.
# This is tricky because some commands expect spaces to be escaped (system
# commands), where as Ruby FileUtils expect non escaped
# WONTFIX - 2. SAMBA / CIFS
# a. CIFS/SMB doesn't appear to support creation of hard links. I've only tested
# this on nas-02, so I'm not sure yet if this is a global SMB thing, or can
# be modified in smb.conf
# Thus, the script doesn't currently support SMB and will fail with messages
# similar to
# cp: cannot create link `/media/cifs/backup/daily/monday': Function not
# implemented
# b. If we resolve #2 above, may need to add switch to support destinations
# that don't support setting permissions and time,
# example "rsync -a" to a CIFS mount will produce a number of
# errors. Rsync options
# -a, --archive archive mode; same as -rlptgoD (no -H)
# --no-OPTION turn off an implied OPTION (e.g. --no-D)
# -O, --omit-dir-times omit directories from --times
# -r, --recursive recurse into directories
# Possibly use "rsync -a --no-p --no-t"
# c. Current testing unable to copy .files to the SMB mount (i.e. .bashrc)
# FIXED - 4. Figure out a way to allow this script to write to a remote --dest that is
# accessible via ssh (sftp, rsync -e ssh, etc...)
#-----------------------------------------------------------------------------
require 'optparse' # CLI Option Parser
require 'fileutils' # allow recursive deletion of directory
copywrite = "Copyright (c) 2012 Mike Hanby, University of Alabama at Birmingham IT Research Computing."
options = Hash.new # Hash to hold all options parsed from CLI
optparse = OptionParser.new() do |opts|
# Help screen banner
opts.banner = "#{copywrite}
Backs up the provided SRC to DEST using rsync and hardlinks to provide
an incremental backup solution without duplicating consumption of storage
for unmodified files.
Usage: #{$0} [options] --src PATH --dest PATH"
# Define the options and what they do
# debug
options[:debug] = nil
opts.on('-v', '--debug', 'Script Debugging Output') do
options[:debug] = true
end
# source directory
options[:source] = nil
opts.on('-s', '--src', '--source FILE', 'Local source directory') do |src|
options[:source] = src
end
# destination directory
options[:dest] = nil
opts.on('-d', '--dest FILE', 'Local or remote destination directory\nFor remote use syntax: user@host:/PATH') do |dst|
options[:dest] = dst
end
# Files or directories to exclude
options[:excludes] = nil
opts.on('-e', '--excludes Pattern1,Pattern2,PatternN', Array, 'Can specify multiple patterns to exclude separated by commas. See man rsync for PATTERN details') do |exc|
options[:excludes] = exc
end
# help
options[:help] = false
opts.on('-?', '-h', '--help', 'Display this help screen') do
puts opts
exit
end
end
# parse! removes the processed args from ARGV
optparse.parse!
raise "\nMandatory argument --src is missing, see --help for details\n" if options[:source].nil?
raise "\nMandatory argument --dest is missing, see --help for details\n" if options[:dest].nil?
# variables
debug = options[:debug]
source = options[:source]
dest = options[:dest] # will get trimmed to only include the path
full_dest = dest # this var will contain full unaltered dest, including user, srv, path
local_dest = 'yes' # Assume dest is local by default
rem_user = nil
rem_srv = nil
ssh = nil # if dest is remote, this will be the Net:SSH.start object
#sftp = nil # if dest is remote, this will be the Net:SFTP.start object
dailydir = 'daily'
weeklydir = 'weekly'
monthlydir = 'monthly'
backup_name = "#{source} Daily Backup"
step = 0 # counter used when printing steps
rsync_opts = '-a --one-file-system --delete --delete-excluded' # default rsync options
#rsync_opts += ' -v' if options[:verbose]
options[:excludes].each { |exc| rsync_opts += " --exclude='#{exc}'" }
# Time and Day related variables
time = Time.new
starttime = time.inspect
months = %w(january february march april may june july august september october november december)
weekdays = %w(sunday monday tuesday wednesday thursday friday saturday)
dailydirs = weekdays.map do |day|
"daily/#{day}"
end
weeklydirs = Array.new # Stores relative path and dir name for the weekly directories
1.upto(4) { |i| weeklydirs << "weekly/week#{i}" }
monthlydirs = months.map do |month|
"monthly/#{month}"
end
# Process dest to see if hostname and optionally user name are provided
# ex: --dest joeblow@nas-01:/backups/joeblow
if dest =~ /:/
local_dest = nil # dest is remote
require 'rubygems'
require 'net/ssh'
#require 'net/sftp'
rem_srv = dest.match(/^(.*):.*$/)[1]
rem_srv.sub!(/^.*@/, '')
rem_user = dest.match(/(^.*)@(.*):.*$/)[1] if dest =~ /@/
dest = dest.match(/^.*:(.*)$/)[1]
ssh = Net::SSH.start(rem_srv, rem_user)
#sftp = Net::SFTP.start(rem_srv, rem_user)
end
# create directory method, supports local and remote
def mkdir(dir, ssh)
if ssh
# the stat command will result in stderr stream if file doesn't exist
ssh.exec!("stat #{dir.gsub(/\s+/, '\ ')}") do |ch, stream, data|
if stream == :stderr # Directory doesn't exist, create it
puts "\tCreating remote #{dir}"
ssh.exec!("mkdir #{dir.gsub(/\s+/, '\ ')}") do |ch, stream, data|
if stream == :stderr
raise "Failed to create #{dir}:\n #{data}"
end
end
end
end
else
unless File.directory?(dir)
puts "\tCreating local #{dir}"
Dir.mkdir(dir)
end
end
end
# remove directory, supports local and remote
def rmdir(dir, ssh)
if ssh
ssh.exec!("stat #{dir.gsub(/\s+/, '\ ')}") do |ch, stream, data|
unless stream == :stderr # Directory exist, delete it
puts "\tDeleting remote #{dir}"
ssh.exec!("rm -rf #{dir.gsub(/\s+/, '\ ')}") do |ch, stream, data|
if stream == :stderr
raise "Failed to delete #{dir}:\n #{data}"
end
end
end
end
else
if File.directory?(dir)
puts "\tDeleting local #{dir}"
FileUtils.rm_rf(dir)
end
end
end
# move directory, supports local and remote
def mvdir(src, dest, ssh)
if ssh
ssh.exec!("stat #{src.gsub(/\s+/, '\ ')}") do |ch, stream, data|
unless stream == :stderr # Directory exist, move it
puts "\t#{src} => #{dest}"
ssh.exec!("mv #{src.gsub(/\s+/, '\ ')} #{dest.gsub(/\s+/, '\ ')}") do |ch, stream, data|
if stream == :stderr
raise "Failed to move #{src}:\n #{data}"
end
end
end
end
else
if File.directory?(src)
puts "\t#{src} => #{dest}"
FileUtils.mv(src, dest)
end
end
end
# Create symlink to latest snapshot
def soft_link(dir, link, ssh)
if ssh
# Can't get "ln -sf" to consistently remove old link, so manually removing it first
ssh.exec!("if [ -L #{link.gsub(/\s+/, '\ ')} ]; then rm #{link.gsub(/\s+/, '\ ')}; fi")
ssh.exec!("ln -sf #{dir} #{link.gsub(/\s+/, '\ ')}") do |ch, stream, data|
if stream == :stderr
warn "\tFailed to create symlink: #{link}"
end
end
else
File.unlink(link) if File.symlink?(link)
File.symlink(dir, link)
end
end
# call this method like this to support spaces in the path
# disk_free(dest.gsub(/\s+/, '\ '), ssh)
def disk_free(path, ssh)
cmd = "df -Ph #{path.gsub(/\s+/, '\ ')} | grep -vi ^filesystem | awk '{print \$3 \" of \" \$2}'"
if ssh
result = ssh.exec!(cmd)
result.chomp
else
%x[#{cmd}].chomp
end
end
def hard_link(src, dest, ssh)
if ssh
#result = ssh.exec!("cp -al #{src} #{dest}")
ssh.exec!("cp -al #{src.gsub(/\s+/, '\ ')} #{dest.gsub(/\s+/, '\ ')}") do |ch, stream, data|
raise "Hard link copy failed #{src} => #{dest}:\n #{data}" if stream == :stderr
end
else
system("cp -al #{src.gsub(/\s+/, '\ ')} #{dest.gsub(/\s+/, '\ ')}")
raise "Hard link copy failed #{src} => #{dest}:\n #{$?.exitstatus}" if $?.exitstatus != 0
end
end
# rsync method
def run_rsync(opts, src, dest, ssh)
puts "\trsync #{opts} #{src.gsub(/\s+/, '\ ')} #{dest.gsub(/\s+/, '\ ')}"
system("rsync #{opts} #{src.gsub(/\s+/, '\ ')} #{dest.gsub(/\s+/, '\ ')}")
raise "Rsync failed to sync: " if $?.exitstatus != 0
end
# updates the mtime of dest to current time
def update_mtime(dest, ssh)
if ssh
ssh.exec!("/bin/touch #{dest.gsub(/\s+/, '\ ')}")
else
system("/bin/touch #{dest.gsub(/\s+/, '\ ')}")
end
end
# escape any spaces in the path before sending it to the df system command
du_pre = disk_free(dest.gsub(/\s+/, '\ '), ssh) # Store disk usage prior to running backup
print <<EOF
======================== BACKUP REPORT ==============================
| Date - #{starttime}
| Run by - #{ENV['USER']}
| Host - #{ENV['HOSTNAME']}
| Source - #{source}
| Destination - #{dest}
EOF
puts "| Remote User - #{rem_user}" if rem_user
puts "| Remote Server - #{rem_srv}" if rem_srv
print <<EOF
|
| Disk Usage Before Backup: #{du_pre}
=====================================================================
EOF
# Create the base level directory tree
puts "#{step += 1}. Checking for missing base level directories"
for dir in %w(daily weekly monthly)
mkdir("#{dest}/#{dir}", ssh)
end
# Create daily directories if they don't exist
puts "#{step += 1}. Checking for missing daily snapshot directories"
dailydirs.each do |dir|
mkdir("#{dest}/#{dir}", ssh)
end
# Delete current days snapshot (should be a week old by now)
puts "#{step += 1}. Removing old daily snapshot"
rmdir("#{dest}/#{dailydirs[time.wday]}", ssh)
# Create hard link copy of yesterday's snapshot to today's directory
puts "#{step += 1}. Creating a hard linked snapshot as the base of today's incremental backup:"
puts "\t#{dailydirs[time.wday - 1]} => #{dailydirs[time.wday]}"
# using full paths will allow the command to work for local and remote destinations
hard_link("#{dest}/#{dailydirs[time.wday - 1]}", "#{dest}/#{dailydirs[time.wday]}", ssh)
# Backup the source using Rsync into today's snapshot directory, end result
# only changed files will consume new disk space in the daily snapshot
# unchanged files will remain hard links
puts "#{step += 1}. Running the rsync command using:"
# use full_dest instead of dest since it will contain user, server and path if dest is remote
run_rsync("#{rsync_opts}", "#{source}", "#{full_dest}/#{dailydirs[time.wday]}", ssh)
# Update the mtime on the current snapshot directory
puts "#{step += 1}. Updating the mtime on #{dest}/#{dailydirs[time.wday]}"
update_mtime("#{dest}/#{dailydirs[time.wday]}", ssh)
# Create a symlink "latest" pointing to the current snapshot
# so that the most current backup can be accessed using a common name
puts "#{step += 1}. Creating symbolic link pointing 'latest' to '#{dailydirs[time.wday]}'"
soft_link("#{dailydirs[time.wday]}", "#{dest}/latest", ssh)
# If it's Sunday, create a snapshot into weekly/weekly1
if time.wday == 0
substep = 0
puts "#{step += 1}. Creating weekly snapshot"
puts " #{step}.#{substep += 1}. Checking for missing weekly directories"
weeklydirs.each do |dir|
mkdir("#{dest}/#{dir}", ssh)
end
puts " #{step}.#{substep += 1}. Removing oldest weekly snapshot"
rmdir("#{dest}/#{weeklydirs[-1]}", ssh)
puts " #{step}.#{substep += 1}. Rotating weekly snapshot directories"
i = weeklydirs.size - 2 # minus 1 is index of last element, we want 2nd to last
while i >= 0
# i.e. say weekly4 is last (deleted in prev step), move weekly3 => weekly4
# weekly2 => weekly3, weekly1 => weekly2
mvdir("#{dest}/#{weeklydirs[i]}", "#{dest}/#{weeklydirs[i + 1]}", ssh)
i -= 1
end
puts " #{step}.#{substep += 1}. Snapshotting #{dailydirs[time.wday - 1]} => #{weeklydirs[0]}"
hard_link("#{dest}/#{dailydirs[time.wday - 1]}", "#{dest}/#{weeklydirs[0]}", ssh)
else
puts "#{step += 1}. Weekly snapshot is only created on Sunday, skipping"
end
# If it's the first day of the month, create the monthly/<month name> snapshot
if time.day == 1
substep = 0
# subtract 2 from time.month since monthdirs is 0 based and we want last month, not current
puts "#{step += 1}. Creating monthly snapshot for #{months[time.month - 2]}"
puts " #{step}.#{substep += 1}. Checking for missing monthly directories"
monthlydirs.each do |dir|
puts " DEBUG:\tEvaluating #{dir}" if debug
puts "\tmkdir(\"#{dest}/#{dir}\", ssh)" if debug
mkdir("#{dest}/#{dir}", ssh)
end
puts " #{step}.#{substep += 1}. Removing prior snapshot for last month: #{monthlydirs[time.month - 2]}"
puts "DEBUG:\trmdir(\"#{dest}/#{monthlydirs[time.month - 2]}\", ssh)" if debug
rmdir("#{dest}/#{monthlydirs[time.month - 2]}", ssh)
puts " #{step}.#{substep += 1}. Snapshotting #{dailydirs[time.wday - 1]} => #{monthlydirs[time.month - 2]}"
puts "DEBUG:\thard_link(\"#{dest}/#{dailydirs[time.wday - 1]}\", \"#{dest}/#{monthlydirs[time.month - 2]}\", ssh)" if debug
hard_link("#{dest}/#{dailydirs[time.wday - 1]}", "#{dest}/#{monthlydirs[time.month - 2]}", ssh)
else
puts "#{step += 1}. Monthly snapshot is only created on the first day of the month, skipping"
end
du_post = disk_free(dest.gsub(/\s+/, '\ '), ssh) # du post running the backup
time2 = Time.new
print <<EOF
============================= SUMMARY ===============================
| The Disk Usage for the backup device before and after the run
| Before: #{du_pre}
| After: #{du_post}
|
| Script Started: #{starttime}
| Script Finished: #{time2.inspect}
=====================================================================
EOF
unless local_dest
ssh.close
#sftp.close
end
fixed small bug where script wasn't able to create net/ssh object
if user didn't specify a remote user in the destination (user@srv:/path)
The script will now use the current shell account if it's not specified in the dest
#!/usr/bin/ruby -w
#-----------------------------------------------------------------------------
# Name : ghetto-timemachine.rb
# Author : Mike Hanby < mhanby at uab.edu >
# Organization: University of Alabama at Birmingham
# Description : This script is used for backing up a *NIX workstation using the
# classic Rsync using Hardlinks rotation technique described at this URL:
# http://www.mikerubel.org/computers/rsync_snapshots/
#
# Usage : $0 --src ~/Documents --dest /backups/userA --excludes \*.iso,.svn
# Date : 2012-03-20 10:30:19
# Type : Utility
#
#-----------------------------------------------------------------------------
# History
# 20120329 - mhanby - fixed small bug where script wasn't able to create net/ssh object
# if user didn't specify a remote user in the destination (user@srv:/path)
# The script will now use the current shell account if it's not specified in the dest
# 20120328 - mhanby - I've moved much of the file and directory operations into
# methods so that the method handles all of the local / remote file system
# specific code
# * mkdir(dir, ssh)
# * rmdir(dir, ssh)
# * mvdir(src, dest, ssh)
# * soft_link(dir, link, ssh)
# * hard_link(src, dest, ssh)
# * disk_free(path, ssh)
# * run_rsync(opts, src, dest, ssh)
# * update_mtime(dest, ssh)
#
# 20120327 - mhanby - I originally intended to use net-ssh for remote commands
# and net-sftp for directory operations (create, delete, rename) thinking sftp
# was better suited for that. Based on testing, it's much easier doing all of
# the remote operations using net-ssh.
#
# 20120324 - mhanby - adding support for backing up to remote storage over SSH
# using net-ssh and net-sftp gems
# Notes on installing and using gems:
# 1. Add the following to ~/.bashrc
# export GEM_HOME=$HOME/.ruby/lib/ruby/gems/1.8
# export RUBYLIB=$HOME/.ruby/lib:$HOME/.ruby/lib/site_ruby/1.8:$RUBYLIB
# 2. Install rubygems package (alternatively, download and stall it manually
# 3. Install the gems
# gem install net-ssh
# gem install net-sftp
#
# 20120323 - mhanby - Fixed bug in the summary report, needed a new time object
# to display the finish time, report was displaying start time twice
#
# 20120322 - mhanby - Created new hard_link method that runs the cp -al system
# command, replaced all refernces with the new method call hard_link(src, dest)
#
# Added code to handle spaces in the paths
#
# 20120322 - mhanby - Initial version, ported code from my Perl script of the
# same name as an exercise in Ruby
#
#-----------------------------------------------------------------------------
# Todo / Things that don't work
# FIXED - 1. Source and Dest with spaces in the path don't currently work.
# This is tricky because some commands expect spaces to be escaped (system
# commands), where as Ruby FileUtils expect non escaped
# WONTFIX - 2. SAMBA / CIFS
# a. CIFS/SMB doesn't appear to support creation of hard links. I've only tested
# this on nas-02, so I'm not sure yet if this is a global SMB thing, or can
# be modified in smb.conf
# Thus, the script doesn't currently support SMB and will fail with messages
# similar to
# cp: cannot create link `/media/cifs/backup/daily/monday': Function not
# implemented
# b. If we resolve #2 above, may need to add switch to support destinations
# that don't support setting permissions and time,
# example "rsync -a" to a CIFS mount will produce a number of
# errors. Rsync options
# -a, --archive archive mode; same as -rlptgoD (no -H)
# --no-OPTION turn off an implied OPTION (e.g. --no-D)
# -O, --omit-dir-times omit directories from --times
# -r, --recursive recurse into directories
# Possibly use "rsync -a --no-p --no-t"
# c. Current testing unable to copy .files to the SMB mount (i.e. .bashrc)
# FIXED - 4. Figure out a way to allow this script to write to a remote --dest that is
# accessible via ssh (sftp, rsync -e ssh, etc...)
#-----------------------------------------------------------------------------
require 'optparse' # CLI Option Parser
require 'fileutils' # allow recursive deletion of directory
copywrite = "Copyright (c) 2012 Mike Hanby, University of Alabama at Birmingham IT Research Computing."
options = Hash.new # Hash to hold all options parsed from CLI
optparse = OptionParser.new() do |opts|
# Help screen banner
opts.banner = "#{copywrite}
Backs up the provided SRC to DEST using rsync and hardlinks to provide
an incremental backup solution without duplicating consumption of storage
for unmodified files.
Usage: #{$0} [options] --src PATH --dest PATH"
# Define the options and what they do
# debug
options[:debug] = nil
opts.on('-v', '--debug', 'Script Debugging Output') do
options[:debug] = true
end
# source directory
options[:source] = nil
opts.on('-s', '--src', '--source FILE', 'Local source directory') do |src|
options[:source] = src
end
# destination directory
options[:dest] = nil
opts.on('-d', '--dest FILE', 'Local or remote destination directory\nFor remote use syntax: user@host:/PATH') do |dst|
options[:dest] = dst
end
# Files or directories to exclude
options[:excludes] = nil
opts.on('-e', '--excludes Pattern1,Pattern2,PatternN', Array, 'Can specify multiple patterns to exclude separated by commas. See man rsync for PATTERN details') do |exc|
options[:excludes] = exc
end
# help
options[:help] = false
opts.on('-?', '-h', '--help', 'Display this help screen') do
puts opts
exit
end
end
# parse! removes the processed args from ARGV
optparse.parse!
raise "\nMandatory argument --src is missing, see --help for details\n" if options[:source].nil?
raise "\nMandatory argument --dest is missing, see --help for details\n" if options[:dest].nil?
# variables
debug = options[:debug]
source = options[:source]
dest = options[:dest] # will get trimmed to only include the path
full_dest = dest # this var will contain full unaltered dest, including user, srv, path
local_dest = 'yes' # Assume dest is local by default
rem_user = nil
rem_srv = nil
ssh = nil # if dest is remote, this will be the Net:SSH.start object
#sftp = nil # if dest is remote, this will be the Net:SFTP.start object
dailydir = 'daily'
weeklydir = 'weekly'
monthlydir = 'monthly'
backup_name = "#{source} Daily Backup"
step = 0 # counter used when printing steps
rsync_opts = '-a --one-file-system --delete --delete-excluded' # default rsync options
#rsync_opts += ' -v' if options[:verbose]
options[:excludes].each { |exc| rsync_opts += " --exclude='#{exc}'" }
# Time and Day related variables
time = Time.new
starttime = time.inspect
months = %w(january february march april may june july august september october november december)
weekdays = %w(sunday monday tuesday wednesday thursday friday saturday)
dailydirs = weekdays.map do |day|
"daily/#{day}"
end
weeklydirs = Array.new # Stores relative path and dir name for the weekly directories
1.upto(4) { |i| weeklydirs << "weekly/week#{i}" }
monthlydirs = months.map do |month|
"monthly/#{month}"
end
# Process dest to see if hostname and optionally user name are provided
# ex: --dest joeblow@nas-01:/backups/joeblow
if dest =~ /:/
local_dest = nil # dest is remote
require 'rubygems'
require 'net/ssh'
#require 'net/sftp'
rem_srv = dest.match(/^(.*):.*$/)[1]
rem_srv.sub!(/^.*@/, '')
if dest =~ /@/
rem_user = dest.match(/(^.*)@(.*):.*$/)[1]
else
rem_user = ENV['USER']
end
dest = dest.match(/^.*:(.*)$/)[1]
ssh = Net::SSH.start(rem_srv, rem_user)
#sftp = Net::SFTP.start(rem_srv, rem_user)
end
# create directory method, supports local and remote
def mkdir(dir, ssh)
if ssh
# the stat command will result in stderr stream if file doesn't exist
ssh.exec!("stat #{dir.gsub(/\s+/, '\ ')}") do |ch, stream, data|
if stream == :stderr # Directory doesn't exist, create it
puts "\tCreating remote #{dir}"
ssh.exec!("mkdir #{dir.gsub(/\s+/, '\ ')}") do |ch, stream, data|
if stream == :stderr
raise "Failed to create #{dir}:\n #{data}"
end
end
end
end
else
unless File.directory?(dir)
puts "\tCreating local #{dir}"
Dir.mkdir(dir)
end
end
end
# remove directory, supports local and remote
def rmdir(dir, ssh)
if ssh
ssh.exec!("stat #{dir.gsub(/\s+/, '\ ')}") do |ch, stream, data|
unless stream == :stderr # Directory exist, delete it
puts "\tDeleting remote #{dir}"
ssh.exec!("rm -rf #{dir.gsub(/\s+/, '\ ')}") do |ch, stream, data|
if stream == :stderr
raise "Failed to delete #{dir}:\n #{data}"
end
end
end
end
else
if File.directory?(dir)
puts "\tDeleting local #{dir}"
FileUtils.rm_rf(dir)
end
end
end
# move directory, supports local and remote
def mvdir(src, dest, ssh)
if ssh
ssh.exec!("stat #{src.gsub(/\s+/, '\ ')}") do |ch, stream, data|
unless stream == :stderr # Directory exist, move it
puts "\t#{src} => #{dest}"
ssh.exec!("mv #{src.gsub(/\s+/, '\ ')} #{dest.gsub(/\s+/, '\ ')}") do |ch, stream, data|
if stream == :stderr
raise "Failed to move #{src}:\n #{data}"
end
end
end
end
else
if File.directory?(src)
puts "\t#{src} => #{dest}"
FileUtils.mv(src, dest)
end
end
end
# Create symlink to latest snapshot
def soft_link(dir, link, ssh)
if ssh
# Can't get "ln -sf" to consistently remove old link, so manually removing it first
ssh.exec!("if [ -L #{link.gsub(/\s+/, '\ ')} ]; then rm #{link.gsub(/\s+/, '\ ')}; fi")
ssh.exec!("ln -sf #{dir} #{link.gsub(/\s+/, '\ ')}") do |ch, stream, data|
if stream == :stderr
warn "\tFailed to create symlink: #{link}"
end
end
else
File.unlink(link) if File.symlink?(link)
File.symlink(dir, link)
end
end
# call this method like this to support spaces in the path
# disk_free(dest.gsub(/\s+/, '\ '), ssh)
def disk_free(path, ssh)
cmd = "df -Ph #{path.gsub(/\s+/, '\ ')} | grep -vi ^filesystem | awk '{print \$3 \" of \" \$2}'"
if ssh
result = ssh.exec!(cmd)
result.chomp
else
%x[#{cmd}].chomp
end
end
def hard_link(src, dest, ssh)
if ssh
#result = ssh.exec!("cp -al #{src} #{dest}")
ssh.exec!("cp -al #{src.gsub(/\s+/, '\ ')} #{dest.gsub(/\s+/, '\ ')}") do |ch, stream, data|
raise "Hard link copy failed #{src} => #{dest}:\n #{data}" if stream == :stderr
end
else
system("cp -al #{src.gsub(/\s+/, '\ ')} #{dest.gsub(/\s+/, '\ ')}")
raise "Hard link copy failed #{src} => #{dest}:\n #{$?.exitstatus}" if $?.exitstatus != 0
end
end
# rsync method
def run_rsync(opts, src, dest, ssh)
puts "\trsync #{opts} #{src.gsub(/\s+/, '\ ')} #{dest.gsub(/\s+/, '\ ')}"
system("rsync #{opts} #{src.gsub(/\s+/, '\ ')} #{dest.gsub(/\s+/, '\ ')}")
raise "Rsync failed to sync: " if $?.exitstatus != 0
end
# updates the mtime of dest to current time
def update_mtime(dest, ssh)
if ssh
ssh.exec!("/bin/touch #{dest.gsub(/\s+/, '\ ')}")
else
system("/bin/touch #{dest.gsub(/\s+/, '\ ')}")
end
end
# escape any spaces in the path before sending it to the df system command
du_pre = disk_free(dest.gsub(/\s+/, '\ '), ssh) # Store disk usage prior to running backup
print <<EOF
======================== BACKUP REPORT ==============================
| Date - #{starttime}
| Run by - #{ENV['USER']}
| Host - #{ENV['HOSTNAME']}
| Source - #{source}
| Destination - #{dest}
EOF
puts "| Remote User - #{rem_user}" if rem_user
puts "| Remote Server - #{rem_srv}" if rem_srv
print <<EOF
|
| Disk Usage Before Backup: #{du_pre}
=====================================================================
EOF
# Create the base level directory tree
puts "#{step += 1}. Checking for missing base level directories"
for dir in %w(daily weekly monthly)
mkdir("#{dest}/#{dir}", ssh)
end
# Create daily directories if they don't exist
puts "#{step += 1}. Checking for missing daily snapshot directories"
dailydirs.each do |dir|
mkdir("#{dest}/#{dir}", ssh)
end
# Delete current days snapshot (should be a week old by now)
puts "#{step += 1}. Removing old daily snapshot"
rmdir("#{dest}/#{dailydirs[time.wday]}", ssh)
# Create hard link copy of yesterday's snapshot to today's directory
puts "#{step += 1}. Creating a hard linked snapshot as the base of today's incremental backup:"
puts "\t#{dailydirs[time.wday - 1]} => #{dailydirs[time.wday]}"
# using full paths will allow the command to work for local and remote destinations
hard_link("#{dest}/#{dailydirs[time.wday - 1]}", "#{dest}/#{dailydirs[time.wday]}", ssh)
# Backup the source using Rsync into today's snapshot directory, end result
# only changed files will consume new disk space in the daily snapshot
# unchanged files will remain hard links
puts "#{step += 1}. Running the rsync command using:"
# use full_dest instead of dest since it will contain user, server and path if dest is remote
run_rsync("#{rsync_opts}", "#{source}", "#{full_dest}/#{dailydirs[time.wday]}", ssh)
# Update the mtime on the current snapshot directory
puts "#{step += 1}. Updating the mtime on #{dest}/#{dailydirs[time.wday]}"
update_mtime("#{dest}/#{dailydirs[time.wday]}", ssh)
# Create a symlink "latest" pointing to the current snapshot
# so that the most current backup can be accessed using a common name
puts "#{step += 1}. Creating symbolic link pointing 'latest' to '#{dailydirs[time.wday]}'"
soft_link("#{dailydirs[time.wday]}", "#{dest}/latest", ssh)
# If it's Sunday, create a snapshot into weekly/weekly1
if time.wday == 0
substep = 0
puts "#{step += 1}. Creating weekly snapshot"
puts " #{step}.#{substep += 1}. Checking for missing weekly directories"
weeklydirs.each do |dir|
mkdir("#{dest}/#{dir}", ssh)
end
puts " #{step}.#{substep += 1}. Removing oldest weekly snapshot"
rmdir("#{dest}/#{weeklydirs[-1]}", ssh)
puts " #{step}.#{substep += 1}. Rotating weekly snapshot directories"
i = weeklydirs.size - 2 # minus 1 is index of last element, we want 2nd to last
while i >= 0
# i.e. say weekly4 is last (deleted in prev step), move weekly3 => weekly4
# weekly2 => weekly3, weekly1 => weekly2
mvdir("#{dest}/#{weeklydirs[i]}", "#{dest}/#{weeklydirs[i + 1]}", ssh)
i -= 1
end
puts " #{step}.#{substep += 1}. Snapshotting #{dailydirs[time.wday - 1]} => #{weeklydirs[0]}"
hard_link("#{dest}/#{dailydirs[time.wday - 1]}", "#{dest}/#{weeklydirs[0]}", ssh)
else
puts "#{step += 1}. Weekly snapshot is only created on Sunday, skipping"
end
# If it's the first day of the month, create the monthly/<month name> snapshot
if time.day == 1
substep = 0
# subtract 2 from time.month since monthdirs is 0 based and we want last month, not current
puts "#{step += 1}. Creating monthly snapshot for #{months[time.month - 2]}"
puts " #{step}.#{substep += 1}. Checking for missing monthly directories"
monthlydirs.each do |dir|
puts " DEBUG:\tEvaluating #{dir}" if debug
puts "\tmkdir(\"#{dest}/#{dir}\", ssh)" if debug
mkdir("#{dest}/#{dir}", ssh)
end
puts " #{step}.#{substep += 1}. Removing prior snapshot for last month: #{monthlydirs[time.month - 2]}"
puts "DEBUG:\trmdir(\"#{dest}/#{monthlydirs[time.month - 2]}\", ssh)" if debug
rmdir("#{dest}/#{monthlydirs[time.month - 2]}", ssh)
puts " #{step}.#{substep += 1}. Snapshotting #{dailydirs[time.wday - 1]} => #{monthlydirs[time.month - 2]}"
puts "DEBUG:\thard_link(\"#{dest}/#{dailydirs[time.wday - 1]}\", \"#{dest}/#{monthlydirs[time.month - 2]}\", ssh)" if debug
hard_link("#{dest}/#{dailydirs[time.wday - 1]}", "#{dest}/#{monthlydirs[time.month - 2]}", ssh)
else
puts "#{step += 1}. Monthly snapshot is only created on the first day of the month, skipping"
end
du_post = disk_free(dest.gsub(/\s+/, '\ '), ssh) # du post running the backup
time2 = Time.new
print <<EOF
============================= SUMMARY ===============================
| The Disk Usage for the backup device before and after the run
| Before: #{du_pre}
| After: #{du_post}
|
| Script Started: #{starttime}
| Script Finished: #{time2.inspect}
=====================================================================
EOF
unless local_dest
ssh.close
#sftp.close
end
|
# frozen_string_literal: true
Gem::Specification.new do |s|
s.name = 'gir_ffi-cairo'
s.version = '0.0.9'
s.summary = 'GirFFI-based bindings for Cairo'
s.description = 'Bindings for Cairo generated by GirFFI, with overrides.'
s.required_ruby_version = '>= 2.3.0'
s.license = 'LGPL-2.1'
s.authors = ['Matijs van Zuijlen']
s.email = ['matijs@matijs.net']
s.homepage = 'http://www.github.com/mvz/gir_ffi-cairo'
s.files = Dir['{lib,test}/**/*.rb', 'README.md', 'Rakefile', 'COPYING.LIB']
s.test_files = Dir['test/**/*.rb']
s.add_runtime_dependency('gir_ffi', ['~> 0.11.0'])
s.add_development_dependency('minitest', ['~> 5.0'])
s.add_development_dependency('rake', ['~> 12.0'])
s.require_paths = ['lib']
end
Update to gir_ffi 0.12.0
# frozen_string_literal: true
Gem::Specification.new do |s|
s.name = 'gir_ffi-cairo'
s.version = '0.0.9'
s.summary = 'GirFFI-based bindings for Cairo'
s.description = 'Bindings for Cairo generated by GirFFI, with overrides.'
s.required_ruby_version = '>= 2.3.0'
s.license = 'LGPL-2.1'
s.authors = ['Matijs van Zuijlen']
s.email = ['matijs@matijs.net']
s.homepage = 'http://www.github.com/mvz/gir_ffi-cairo'
s.files = Dir['{lib,test}/**/*.rb', 'README.md', 'Rakefile', 'COPYING.LIB']
s.test_files = Dir['test/**/*.rb']
s.add_runtime_dependency('gir_ffi', ['~> 0.12.0'])
s.add_development_dependency('minitest', ['~> 5.0'])
s.add_development_dependency('rake', ['~> 12.0'])
s.require_paths = ['lib']
end
|
require File.expand_path("../lib/github-markup", __FILE__)
Gem::Specification.new do |s|
s.name = "github-markup"
s.version = GitHub::Markup::VERSION
s.summary = "The code GitHub uses to render README.markup"
s.description = "This gem is used by GitHub to render any fancy markup such " +
"as Markdown, Textile, Org-Mode, etc. Fork it and add your own!"
s.authors = ["Chris Wanstrath"]
s.email = "chris@ozmm.org"
s.homepage = "https://github.com/github/markup"
s.license = "MIT"
s.files = `git ls-files`.split($\)
s.files += Dir['vendor/**/*']
s.executables = s.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.require_paths = %w[lib]
s.add_development_dependency 'rake', '~> 12'
s.add_development_dependency 'activesupport', '~> 4.0'
s.add_development_dependency 'minitest', '~> 5.4', '>= 5.4.3'
s.add_development_dependency 'html-pipeline', '~> 1.0'
s.add_development_dependency 'sanitize', '~> 2.1', '>= 2.1.0'
s.add_development_dependency 'nokogiri', '~> 1.8.1'
s.add_development_dependency 'nokogiri-diff', '~> 0.2.0'
s.add_development_dependency "github-linguist", ">= 7.1.3"
end
use modern sanitize in tests
(Vulnerability alert doesn't exactly apply as it's never used in actual
execution, but that's okay.)
require File.expand_path("../lib/github-markup", __FILE__)
Gem::Specification.new do |s|
s.name = "github-markup"
s.version = GitHub::Markup::VERSION
s.summary = "The code GitHub uses to render README.markup"
s.description = "This gem is used by GitHub to render any fancy markup such " +
"as Markdown, Textile, Org-Mode, etc. Fork it and add your own!"
s.authors = ["Chris Wanstrath"]
s.email = "chris@ozmm.org"
s.homepage = "https://github.com/github/markup"
s.license = "MIT"
s.files = `git ls-files`.split($\)
s.files += Dir['vendor/**/*']
s.executables = s.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.require_paths = %w[lib]
s.add_development_dependency 'rake', '~> 12'
s.add_development_dependency 'activesupport', '~> 4.0'
s.add_development_dependency 'minitest', '~> 5.4', '>= 5.4.3'
s.add_development_dependency 'html-pipeline', '~> 1.0'
s.add_development_dependency 'sanitize', '>= 4.6.3'
s.add_development_dependency 'nokogiri', '~> 1.8.1'
s.add_development_dependency 'nokogiri-diff', '~> 0.2.0'
s.add_development_dependency "github-linguist", ">= 7.1.3"
end
|
require 'helper/mappings'
class LogicalElement
attr_accessor :doctype,
:id,
:dmdid,
:admid,
:order,
:start_page_index,
:end_page_index,
:part_product,
:part_work,
:part_key,
:level,
:parentdoc_work,
:parentdoc_label,
:parentdoc_type,
:dmdsec_meta, # :label, :type, :volume_uri
:isLog_part
def initialize
@isLog_part = false
end
def label=(label)
l = Mappings.strctype_label(label)
l = label if l == nil
@label = l
end
def label
@label
end
def type=(type)
t = Mappings.strctype_type(type)
t = type if t == nil
@type = t
end
def type
@type
end
end
Remove label mapping
Mapping no longer desired
require 'helper/mappings'
class LogicalElement
attr_accessor :doctype,
:id,
:dmdid,
:admid,
:order,
:start_page_index,
:end_page_index,
:part_product,
:part_work,
:part_key,
:level,
:parentdoc_work,
:parentdoc_label,
:parentdoc_type,
:dmdsec_meta, # :label, :type, :volume_uri
:isLog_part
def initialize
@isLog_part = false
end
def label=(label)
# Mapping no longer desired
# l = Mappings.strctype_label(label)
# l = label if l == nil
l = label
@label = l
end
def label
@label
end
def type=(type)
t = Mappings.strctype_type(type)
t = type if t == nil
@type = t
end
def type
@type
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'guard/rubocop/version'
Gem::Specification.new do |spec|
spec.name = "guard-rubocop"
spec.version = Guard::RubocopVersion::VERSION
spec.authors = ["Yuji Nakayama"]
spec.email = ["nkymyj@gmail.com"]
spec.summary = "Guard plugin for RuboCop"
spec.description = "Guard::Rubocop allows you to automatically check Ruby code style with RuboCop when files are modified."
spec.homepage = "https://github.com/yujinakayama/guard-rubocop"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "guard", "~> 1.8"
spec.add_runtime_dependency "rubocop", [">= 0.6.1", "< 1.0.0"]
spec.add_runtime_dependency "childprocess", "~> 0.3"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 2.13"
spec.add_development_dependency "simplecov", "~> 0.7"
spec.add_development_dependency "guard-rspec", ">= 2.5.4"
spec.add_development_dependency "ruby_gntp", ">= 0.3"
end
Replace double quotes with single quotes in gemspec
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'guard/rubocop/version'
Gem::Specification.new do |spec|
spec.name = 'guard-rubocop'
spec.version = Guard::RubocopVersion::VERSION
spec.authors = ['Yuji Nakayama']
spec.email = ['nkymyj@gmail.com']
spec.summary = 'Guard plugin for RuboCop'
spec.description = 'Guard::Rubocop allows you to automatically check Ruby code style with RuboCop when files are modified.'
spec.homepage = 'https://github.com/yujinakayama/guard-rubocop'
spec.license = 'MIT'
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_runtime_dependency 'guard', '~> 1.8'
spec.add_runtime_dependency 'rubocop', ['>= 0.6.1', '< 1.0.0']
spec.add_runtime_dependency 'childprocess', '~> 0.3'
spec.add_development_dependency 'bundler', '~> 1.3'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 2.13'
spec.add_development_dependency 'simplecov', '~> 0.7'
spec.add_development_dependency 'guard-rspec', '>= 2.5.4'
spec.add_development_dependency 'ruby_gntp', '>= 0.3'
end
|
lib = File.expand_path('../lib/', __FILE__)
$LOAD_PATH.unshift lib unless $LOAD_PATH.include?(lib)
require 'neo4j/version'
Gem::Specification.new do |s|
s.name = 'neo4j'
s.version = Neo4j::VERSION
s.required_ruby_version = '>= 1.9.3'
s.authors = 'Andreas Ronge, Brian Underwood, Chris Grigg'
s.email = 'andreas.ronge@gmail.com, brian@brian-underwood.codes, chris@subvertallmedia.com'
s.homepage = 'https://github.com/neo4jrb/neo4j/'
s.rubyforge_project = 'neo4j'
s.summary = 'A graph database for Ruby'
s.license = 'MIT'
s.description = <<-EOF
A Neo4j OGM (Object-Graph-Mapper) for use in Ruby on Rails and Rack frameworks heavily inspired by ActiveRecord.
EOF
s.require_path = 'lib'
s.files = Dir.glob('{bin,lib,config}/**/*') + %w(README.md CHANGELOG.md CONTRIBUTORS Gemfile neo4j.gemspec)
s.executables = ['neo4j-jars']
s.has_rdoc = true
s.extra_rdoc_files = %w( README.md )
s.rdoc_options = ['--quiet', '--title', 'Neo4j.rb', '--line-numbers', '--main', 'README.rdoc', '--inline-source']
s.add_dependency('orm_adapter', '~> 0.5.0')
s.add_dependency('activemodel', '~> 4')
s.add_dependency('activesupport', '~> 4')
s.add_dependency('active_attr', '~> 0.8')
s.add_dependency('neo4j-core', '~> 6.0.0.rc.1')
s.add_dependency('neo4j-community', '~> 2.0') if RUBY_PLATFORM =~ /java/
s.add_development_dependency('railties', '~> 4')
s.add_development_dependency('pry')
s.add_development_dependency('os')
s.add_development_dependency('rake')
s.add_development_dependency('yard')
s.add_development_dependency('guard')
s.add_development_dependency('guard-rubocop')
s.add_development_dependency('guard-rspec')
s.add_development_dependency('rubocop', '~> 0.34.0')
end
Any version above 6.0.0 should be fine
lib = File.expand_path('../lib/', __FILE__)
$LOAD_PATH.unshift lib unless $LOAD_PATH.include?(lib)
require 'neo4j/version'
Gem::Specification.new do |s|
s.name = 'neo4j'
s.version = Neo4j::VERSION
s.required_ruby_version = '>= 1.9.3'
s.authors = 'Andreas Ronge, Brian Underwood, Chris Grigg'
s.email = 'andreas.ronge@gmail.com, brian@brian-underwood.codes, chris@subvertallmedia.com'
s.homepage = 'https://github.com/neo4jrb/neo4j/'
s.rubyforge_project = 'neo4j'
s.summary = 'A graph database for Ruby'
s.license = 'MIT'
s.description = <<-EOF
A Neo4j OGM (Object-Graph-Mapper) for use in Ruby on Rails and Rack frameworks heavily inspired by ActiveRecord.
EOF
s.require_path = 'lib'
s.files = Dir.glob('{bin,lib,config}/**/*') + %w(README.md CHANGELOG.md CONTRIBUTORS Gemfile neo4j.gemspec)
s.executables = ['neo4j-jars']
s.has_rdoc = true
s.extra_rdoc_files = %w( README.md )
s.rdoc_options = ['--quiet', '--title', 'Neo4j.rb', '--line-numbers', '--main', 'README.rdoc', '--inline-source']
s.add_dependency('orm_adapter', '~> 0.5.0')
s.add_dependency('activemodel', '~> 4')
s.add_dependency('activesupport', '~> 4')
s.add_dependency('active_attr', '~> 0.8')
s.add_dependency('neo4j-core', '>= 6.0.0')
s.add_dependency('neo4j-community', '~> 2.0') if RUBY_PLATFORM =~ /java/
s.add_development_dependency('railties', '~> 4')
s.add_development_dependency('pry')
s.add_development_dependency('os')
s.add_development_dependency('rake')
s.add_development_dependency('yard')
s.add_development_dependency('guard')
s.add_development_dependency('guard-rubocop')
s.add_development_dependency('guard-rspec')
s.add_development_dependency('rubocop', '~> 0.34.0')
end
|
Gem::Specification.new do |s|
s.name = "http-protocol"
s.version = "0.1.0"
s.licenses = ["MIT"]
s.summary = "HTTP protocol library designed to facilitate custom HTTP clients"
s.description = "HTTP protocol library designed to facilitate custom HTTP clients. Does not handle connections, sessions; it's just the protocol"
s.authors = ["Nathan Ladd"]
s.email = "nathanladd+github@gmail.com"
s.files = Dir["lib/**/*.rb"]
s.homepage = "https://github.com/obsidian-btc/http-protocol"
s.executables = []
end
Gem name is underscored, and the gemspec reflects the generalizations we have in-effect
Gem::Specification.new do |s|
s.name = "http_protocol"
s.version = '0.0.0'
s.summary = "HTTP protocol library designed to facilitate custom HTTP clients"
s.authors = ['']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'poro_validator/version'
Gem::Specification.new do |spec|
spec.name = "poro_validator"
spec.version = PoroValidator::VERSION
spec.authors = ["Kareem Gan"]
spec.email = ["kareemgan@gmail.com"]
spec.summary = %q{A PORO (Plain Old Ruby Object) validator.}
spec.description = %q{Validations for ruby objects or POROs.}
spec.homepage = "https://github.com/magicalbanana/poro_validator"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "https://rubygems.org"
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 = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency("bundler")
spec.add_development_dependency("rake")
spec.add_development_dependency("rspec")
spec.add_development_dependency('simplecov')
spec.add_development_dependency('coveralls')
spec.add_development_dependency('recursive-open-struct')
spec.add_development_dependency('nyan-cat-formatter')
# = MANIFEST =
spec.files = %w[
CODE_OF_CONDUCT.md
Gemfile
LICENSE.txt
README.md
Rakefile
lib/poro_validator.rb
lib/poro_validator/configuration.rb
lib/poro_validator/error_store.rb
lib/poro_validator/errors.rb
lib/poro_validator/exceptions.rb
lib/poro_validator/utils/deep_fetch.rb
lib/poro_validator/validator.rb
lib/poro_validator/validator/base_class.rb
lib/poro_validator/validator/conditions.rb
lib/poro_validator/validator/context.rb
lib/poro_validator/validator/factory.rb
lib/poro_validator/validator/validation.rb
lib/poro_validator/validator/validations.rb
lib/poro_validator/validators/base_class.rb
lib/poro_validator/validators/exclusion_validator.rb
lib/poro_validator/validators/float_validator.rb
lib/poro_validator/validators/format_validator.rb
lib/poro_validator/validators/inclusion_validator.rb
lib/poro_validator/validators/integer_validator.rb
lib/poro_validator/validators/length_validator.rb
lib/poro_validator/validators/numeric_validator.rb
lib/poro_validator/validators/presence_validator.rb
lib/poro_validator/validators/range_array_validator.rb
lib/poro_validator/validators/with_validator.rb
lib/poro_validator/version.rb
poro_validator.gemspec
spec/features/composable_validations_spec.rb
spec/features/inheritable_spec.rb
spec/features/nested_validations_spec.rb
spec/features/validate_hash_object_spec.rb
spec/lib/poro_validator/configuration_spec.rb
spec/lib/poro_validator/error_store_spec.rb
spec/lib/poro_validator/errors_spec.rb
spec/lib/poro_validator/utils/deep_fetch_spec.rb
spec/lib/poro_validator/validator/base_class_spec.rb
spec/lib/poro_validator/validator/conditions_spec.rb
spec/lib/poro_validator/validator/factory_spec.rb
spec/lib/poro_validator/validator/validation_spec.rb
spec/lib/poro_validator/validator/validations_spec.rb
spec/lib/poro_validator/validator_spec.rb
spec/lib/poro_validator/validators/base_class_spec.rb
spec/lib/poro_validator/validators/exclusion_validator_spec.rb
spec/lib/poro_validator/validators/float_validator_spec.rb
spec/lib/poro_validator/validators/format_validator_spec.rb
spec/lib/poro_validator/validators/inclusion_validator_spec.rb
spec/lib/poro_validator/validators/integer_validator_spec.rb
spec/lib/poro_validator/validators/length_validator_spec.rb
spec/lib/poro_validator/validators/numeric_validator_spec.rb
spec/lib/poro_validator/validators/presence_validator_spec.rb
spec/lib/poro_validator/validators/with_validator_spec.rb
spec/poro_validator_spec.rb
spec/spec_helper.rb
spec/support/spec_helpers/concerns.rb
spec/support/spec_helpers/validator_test_macros.rb
]
# = MANIFEST =
end
Release 0.2.0
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'poro_validator/version'
Gem::Specification.new do |spec|
spec.name = "poro_validator"
spec.version = PoroValidator::VERSION
spec.authors = ["Kareem Gan"]
spec.email = ["kareemgan@gmail.com"]
spec.summary = %q{A PORO (Plain Old Ruby Object) validator.}
spec.description = %q{Validations for ruby objects or POROs.}
spec.homepage = "https://github.com/magicalbanana/poro_validator"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "https://rubygems.org"
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 = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency("bundler")
spec.add_development_dependency("rake")
spec.add_development_dependency("rspec")
spec.add_development_dependency('simplecov')
spec.add_development_dependency('coveralls')
spec.add_development_dependency('recursive-open-struct')
spec.add_development_dependency('nyan-cat-formatter')
# = MANIFEST =
spec.files = %w[
CODE_OF_CONDUCT.md
Gemfile
LICENSE.txt
README.md
Rakefile
lib/poro_validator.rb
lib/poro_validator/configuration.rb
lib/poro_validator/error_store.rb
lib/poro_validator/errors.rb
lib/poro_validator/exceptions.rb
lib/poro_validator/utils/deep_fetch.rb
lib/poro_validator/validator.rb
lib/poro_validator/validator/base_class.rb
lib/poro_validator/validator/conditions.rb
lib/poro_validator/validator/context.rb
lib/poro_validator/validator/factory.rb
lib/poro_validator/validator/validation.rb
lib/poro_validator/validator/validations.rb
lib/poro_validator/validators/base_class.rb
lib/poro_validator/validators/exclusion_validator.rb
lib/poro_validator/validators/float_validator.rb
lib/poro_validator/validators/format_validator.rb
lib/poro_validator/validators/inclusion_validator.rb
lib/poro_validator/validators/integer_validator.rb
lib/poro_validator/validators/length_validator.rb
lib/poro_validator/validators/numeric_validator.rb
lib/poro_validator/validators/presence_validator.rb
lib/poro_validator/validators/range_array_validator.rb
lib/poro_validator/validators/with_validator.rb
lib/poro_validator/version.rb
poro_validator.gemspec
spec/features/composable_validations_spec.rb
spec/features/configurable_error_messages_spec.rb
spec/features/inheritable_spec.rb
spec/features/nested_validations_spec.rb
spec/features/validate_hash_object_spec.rb
spec/lib/poro_validator/configuration_spec.rb
spec/lib/poro_validator/error_store_spec.rb
spec/lib/poro_validator/errors_spec.rb
spec/lib/poro_validator/utils/deep_fetch_spec.rb
spec/lib/poro_validator/validator/base_class_spec.rb
spec/lib/poro_validator/validator/conditions_spec.rb
spec/lib/poro_validator/validator/factory_spec.rb
spec/lib/poro_validator/validator/validation_spec.rb
spec/lib/poro_validator/validator/validations_spec.rb
spec/lib/poro_validator/validator_spec.rb
spec/lib/poro_validator/validators/base_class_spec.rb
spec/lib/poro_validator/validators/exclusion_validator_spec.rb
spec/lib/poro_validator/validators/float_validator_spec.rb
spec/lib/poro_validator/validators/format_validator_spec.rb
spec/lib/poro_validator/validators/inclusion_validator_spec.rb
spec/lib/poro_validator/validators/integer_validator_spec.rb
spec/lib/poro_validator/validators/length_validator_spec.rb
spec/lib/poro_validator/validators/numeric_validator_spec.rb
spec/lib/poro_validator/validators/presence_validator_spec.rb
spec/lib/poro_validator/validators/with_validator_spec.rb
spec/poro_validator_spec.rb
spec/spec_helper.rb
spec/support/spec_helpers/concerns.rb
spec/support/spec_helpers/validator_test_macros.rb
]
# = MANIFEST =
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "serializable"
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Mikhail Kochegarov"]
s.date = "2012-10-09"
s.description = "TODO: longer description of your gem"
s.email = "nexo.michael@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"lib/serializable.rb",
"test/helper.rb",
"test/test_serializable.rb"
]
s.homepage = "http://github.com/NexoMichael/serializable"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.24"
s.summary = "TODO: one-line summary of your gem"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
s.add_development_dependency(%q<bundler>, ["~> 1.2.1"])
s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"])
else
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.2.1"])
s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
end
else
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.2.1"])
s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
end
end
Regenerate gemspec for version 0.1.0
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "serializable"
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Mikhail Kochegarov"]
s.date = "2012-10-09"
s.description = "Replacement of standart ActiveRecord serialize functionality"
s.email = "nexo.michael@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"lib/serializable.rb",
"serializable.gemspec",
"test/helper.rb",
"test/test_serializable.rb"
]
s.homepage = "http://github.com/NexoMichael/serializable"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.24"
s.summary = "Replacement of standart ActiveRecord serialize functionality"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<bundler>, ["~> 1.2.1"])
s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"])
else
s.add_dependency(%q<bundler>, ["~> 1.2.1"])
s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
end
else
s.add_dependency(%q<bundler>, ["~> 1.2.1"])
s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
end
end
|
fix unsubmit which was broken by public caching and the lack of authenticity tokens
|
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/flipper/adapters/redis/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["John Nunemaker"]
gem.email = ["nunemaker@gmail.com"]
gem.description = %q{Redis adapter for Flipper}
gem.summary = %q{Redis adapter for Flipper}
gem.homepage = "http://jnunemaker.github.com/flipper-redis"
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.name = "flipper-redis"
gem.require_paths = ["lib"]
gem.version = Flipper::Adapters::Redis::VERSION
gem.add_dependency 'flipper', '>= 0.2.0'
end
Lock down flipper dependency some more.
# -*- encoding: utf-8 -*-
require File.expand_path('../lib/flipper/adapters/redis/version', __FILE__)
Gem::Specification.new do |gem|
gem.authors = ["John Nunemaker"]
gem.email = ["nunemaker@gmail.com"]
gem.description = %q{Redis adapter for Flipper}
gem.summary = %q{Redis adapter for Flipper}
gem.homepage = "http://jnunemaker.github.com/flipper-redis"
gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
gem.files = `git ls-files`.split("\n")
gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
gem.name = "flipper-redis"
gem.require_paths = ["lib"]
gem.version = Flipper::Adapters::Redis::VERSION
gem.add_dependency 'flipper', '~> 0.3.0'
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'cocoapods_acknowledgements/version.rb'
Gem::Specification.new do |spec|
spec.name = "cocoapods-acknowledgements"
spec.version = CocoaPodsAcknowledgements::VERSION
spec.authors = ["Fabio Pelosin", "Orta Therox", "Marcelo Fabri"]
spec.summary = %q{CocoaPods plugin that generates an acknowledgements plist to make it easy to create tools to use in apps.}
spec.homepage = "https://github.com/CocoaPods/cocoapods-acknowledgements"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "redcarpet", "~> 3.3"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
end
[Gemspec] Pin activesupport version
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'cocoapods_acknowledgements/version.rb'
Gem::Specification.new do |spec|
spec.name = "cocoapods-acknowledgements"
spec.version = CocoaPodsAcknowledgements::VERSION
spec.authors = ["Fabio Pelosin", "Orta Therox", "Marcelo Fabri"]
spec.summary = %q{CocoaPods plugin that generates an acknowledgements plist to make it easy to create tools to use in apps.}
spec.homepage = "https://github.com/CocoaPods/cocoapods-acknowledgements"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
# Version 5 needs Ruby 2.2, so we specify an upper bound to stay compatible with system ruby
spec.add_runtime_dependency 'activesupport', '>= 4.0.2', '< 5'
spec.add_dependency "redcarpet", "~> 3.3"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
end
|
#!/usr/bin/env ruby
require 'spec/spec_helper'
# The document `pita.xml` contains both a default namespace and the 'georss'
# namespace (for the 'point' xml_reader).
module PITA
class Base
include ROXML
xml_convention :camelcase
end
class Item < Base
xml_reader :asin, :from => 'ASIN'
xml_reader :detail_page_url, :from => 'DetailPageURL'
xml_reader :manufacturer, :in => './'
# this is the only xml_reader that exists in a different namespace, so it
# must be explicitly specified
xml_reader :point, :from => 'georss:point'
end
class ItemSearchResponse < Base
xml_reader :total_results, :as => Integer, :in => 'Items'
xml_reader :total_pages, :as => Integer, :in => 'Items'
xml_reader :items, :as => [Item]
end
end
unless defined?(Spec)
item = PITA::ItemSearchResponse.from_xml(xml_for('amazon'))
item.items.each do |i|
puts i.asin, i.detail_page_url, i.manufacturer, ''
end
end
With some namespace adjustment, Amazon spec passes in Nokogiri. Need some work though to remain user-friendly.
#!/usr/bin/env ruby
require 'spec/spec_helper'
# The document `pita.xml` contains both a default namespace and the 'georss'
# namespace (for the 'point' xml_reader).
module PITA
class Base
include ROXML
xml_convention :camelcase
xml_namespace :xmlns
end
class Item < Base
xml_reader :asin, :from => 'xmlns:ASIN'
xml_reader :detail_page_url, :from => 'xmlns:DetailPageURL'
xml_reader :manufacturer, :in => 'xmlns:ItemAttributes'
# this is the only xml_reader that exists in a different namespace, so it
# must be explicitly specified
xml_reader :point, :from => 'georss:point'
end
class ItemSearchResponse < Base
xml_reader :total_results, :as => Integer, :in => 'xmlns:Items'
xml_reader :total_pages, :as => Integer, :in => 'xmlns:Items'
xml_reader :items, :as => [Item]
end
end
unless defined?(Spec)
response = PITA::ItemSearchResponse.from_xml(xml_for('amazon'))
p response.total_results
p response.total_pages
response.items.each do |i|
puts i.asin, i.detail_page_url, i.manufacturer, i.point, ''
end
end |
Pod::Spec.new do |s|
s.name = "PMAlertController"
s.version = "1.0.2"
s.summary = "PMAlertController is a great and customizable substitute to UIAlertController"
s.description = <<-DESC
PMAlertController is a small library that allows you to substitute the uncustomizable UIAlertController of Apple, with a beautiful and totally customizable alert that you can use in your iOS app. Enjoy!
DESC
s.homepage = "https://github.com/Codeido/PMAlertController"
s.screenshots = "https://raw.githubusercontent.com/Codeido/PMAlertController/master/preview_pmalertacontroller.jpg"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Paolo Musolino" => "info@codeido.com" }
s.social_media_url = "http://twitter.com/pmusolino"
s.platform = :ios, "9.0"
s.source = { :git => "https://github.com/Codeido/PMAlertController.git", :tag => s.version }
s.source_files = "Library/**/*"
s.resource_bundles = {
'PMAlertController' => ['Library/Resources/*.png', 'Library/**/*.xib']
}
s.framework = "UIKit"
s.requires_arc = true
end
Update podspec
Pod::Spec.new do |s|
s.name = "PMAlertController"
s.version = "1.0.3"
s.summary = "PMAlertController is a great and customizable substitute to UIAlertController"
s.description = <<-DESC
PMAlertController is a small library that allows you to substitute the uncustomizable UIAlertController of Apple, with a beautiful and totally customizable alert that you can use in your iOS app. Enjoy!
DESC
s.homepage = "https://github.com/Codeido/PMAlertController"
s.screenshots = "https://raw.githubusercontent.com/Codeido/PMAlertController/master/preview_pmalertacontroller.jpg"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Paolo Musolino" => "info@codeido.com" }
s.social_media_url = "http://twitter.com/pmusolino"
s.platform = :ios, "9.0"
s.source = { :git => "https://github.com/Codeido/PMAlertController.git", :tag => s.version }
s.source_files = "Library/**/*"
s.resource_bundles = {
'PMAlertController' => ['Library/Resources/*.png', 'Library/**/*.xib']
}
s.framework = "UIKit"
s.requires_arc = true
end
|
Pod::Spec.new do |spec|
spec.name = 'PXLMenuController'
spec.version = '1.0.1'
spec.summary = 'An easy way to present your users with a menu controller.'
spec.homepage = 'https://github.com/jasonsilberman/PXLMenuController'
spec.author = { 'Jason Silberman' => 'j@j99.co' }
spec.source = { :git => 'https://github.com/jasonsilberman/PXLMenuController.git', :tag => "v#{spec.version}" }
spec.requires_arc = true
spec.license = { :type => 'MIT', :file => 'LICENSE' }
spec.frameworks = 'Foundation', 'UIKit'
spec.platform = :ios, '7.0'
spec.ios.deployment_target = '7.0'
spec.source_files = 'PXLMenuController/*.{h,m}'
end
Version 1.0.2
Pod::Spec.new do |spec|
spec.name = 'PXLMenuController'
spec.version = '1.0.2'
spec.summary = 'An easy way to present your users with a menu controller.'
spec.homepage = 'https://github.com/jasonsilberman/PXLMenuController'
spec.author = { 'Jason Silberman' => 'j@j99.co' }
spec.source = { :git => 'https://github.com/jasonsilberman/PXLMenuController.git', :tag => "v#{spec.version}" }
spec.requires_arc = true
spec.license = { :type => 'MIT', :file => 'LICENSE' }
spec.frameworks = 'Foundation', 'UIKit'
spec.platform = :ios, '7.0'
spec.ios.deployment_target = '7.0'
spec.source_files = 'PXLMenuController/*.{h,m}'
end
|
Pod::Spec.new do |s|
s.name = "PactConsumerSwift"
s.module_name = "PactConsumerSwift"
s.version = "0.5.0"
s.summary = "A Swift / ObjeciveC DSL for creating pacts."
s.license = { :type => 'MIT' }
s.description = <<-DESC
This library provides a Swift / Objective C DSL for creating Consumer [Pacts](http://pact.io).
Implements [Pact Specification v2](https://github.com/pact-foundation/pact-specification/tree/version-2),
including [flexible matching](http://docs.pact.io/documentation/matching.html).
DESC
s.homepage = "https://github.com/DiUS/pact-consumer-swift"
s.author = { "andrewspinks" => "andrewspinks@gmail.com", "markojustinek" => "mjustinek@dius.com.au" }
s.ios.deployment_target = '9.0'
s.tvos.deployment_target = '9.0'
s.osx.deployment_target = '10.10'
s.source = { :git => "https://github.com/DiUS/pact-consumer-swift.git", :tag => "v#{s.version}" }
s.source_files = 'Sources/**/*.swift'
s.resources = 'scripts/start_server.sh', 'scripts/stop_server.sh'
s.requires_arc = true
s.frameworks = 'XCTest'
s.dependency 'Alamofire', '~> 4.5'
s.dependency 'BrightFutures', '~> 6.0'
s.dependency 'Nimble', '~> 7.0'
s.dependency 'Quick', '~> 1.1'
end
Update cocopods version number
Pod::Spec.new do |s|
s.name = "PactConsumerSwift"
s.module_name = "PactConsumerSwift"
s.version = "0.5.1"
s.summary = "A Swift / ObjeciveC DSL for creating pacts."
s.license = { :type => 'MIT' }
s.description = <<-DESC
This library provides a Swift / Objective C DSL for creating Consumer [Pacts](http://pact.io).
Implements [Pact Specification v2](https://github.com/pact-foundation/pact-specification/tree/version-2),
including [flexible matching](http://docs.pact.io/documentation/matching.html).
DESC
s.homepage = "https://github.com/DiUS/pact-consumer-swift"
s.author = { "andrewspinks" => "andrewspinks@gmail.com", "markojustinek" => "mjustinek@dius.com.au" }
s.ios.deployment_target = '9.0'
s.tvos.deployment_target = '9.0'
s.osx.deployment_target = '10.10'
s.source = { :git => "https://github.com/DiUS/pact-consumer-swift.git", :tag => "v#{s.version}" }
s.source_files = 'Sources/**/*.swift'
s.resources = 'scripts/start_server.sh', 'scripts/stop_server.sh'
s.requires_arc = true
s.frameworks = 'XCTest'
s.dependency 'Alamofire', '~> 4.5'
s.dependency 'BrightFutures', '~> 6.0'
s.dependency 'Nimble', '~> 7.0'
s.dependency 'Quick', '~> 1.1'
end
|
#!/usr/bin/env ruby
require 'test/unit'
require 'qpid_proton'
class InteropTest < Test::Unit::TestCase
Data = Qpid::Proton::Data
Type = Data::Type
Message = Qpid::Proton::Message
def setup
@data = Data.new
@message = Message.new
end
# Walk up the directory tree to find the tests directory.
def get_data(name)
path = File.absolute_path(__FILE__)
while path and File.basename(path) != "tests" do path = File.dirname(path); end
path = File.join(path,"interop")
raise "Can't find test/interop directory from #{__FILE__}" unless File.directory?(path)
path = File.join(path,"#{name}.amqp")
File.open(path, "rb") { |f| f.read }
end
# Decode encoded bytes as a Data object
def decode_data(encoded)
buffer = encoded
while buffer.size > 0
n = @data.decode(buffer)
buffer = buffer[n..-1]
end
@data.rewind
reencoded = @data.encode
# Test the round-trip re-encoding gives the same result.
assert_equal(encoded, reencoded)
end
def decode_data_file(name) decode_data(get_data(name)); end
def decode_message_file(name)
message = Message.new()
message.decode(self.get_data(name))
self.decode_data(message.content)
end
def assert_next(type, value)
assert @data.next
assert_equal(type, @data.type)
assert_equal(value, type.get(@data))
end
def test_message
decode_message_file("message")
assert_next(Data::STRING, "hello")
assert !@data.next()
end
def test_primitives
decode_data_file("primitives")
assert_next(Data::BOOL, true)
assert_next(Data::BOOL, false)
assert_next(Data::UBYTE, 42)
assert_next(Data::USHORT, 42)
assert_next(Data::SHORT, -42)
assert_next(Data::UINT, 12345)
assert_next(Data::INT, -12345)
assert_next(Data::ULONG, 12345)
assert_next(Data::LONG, -12345)
assert_next(Data::FLOAT, 0.125)
assert_next(Data::DOUBLE, 0.125)
assert !@data.next()
end
def test_strings
decode_data_file("strings")
assert_next(Data::BINARY, "abc\0defg")
assert_next(Data::STRING, "abcdefg")
assert_next(Data::SYMBOL, "abcdefg")
assert_next(Data::BINARY, "")
assert_next(Data::STRING, "")
assert_next(Data::SYMBOL, "")
assert !@data.next()
end
def test_described
decode_data_file("described")
assert_next(Data::DESCRIBED, Data::Described.new("foo-descriptor", "foo-value"))
assert(@data.described?)
assert_next(Data::DESCRIBED, Data::Described.new(12, 13))
assert(@data.described?)
assert !@data.next
end
def test_described_array
decode_data_file("described_array")
assert_next(Data::ARRAY, Data::Array.new("int-array", Data::INT, 0...10))
end
def test_arrays
decode_data_file("arrays")
assert_next(Data::ARRAY, Data::Array.new(false, Data::INT, 0...100))
assert_next(Data::ARRAY, Data::Array.new(false, Data::STRING, ["a", "b", "c"]))
assert_next(Data::ARRAY, Data::Array.new(false, Data::INT))
assert !@data.next
end
def test_lists
decode_data_file("lists")
assert_next(Data::LIST, [32, "foo", true])
assert_next(Data::LIST, [])
assert !@data.next
end
def test_maps
decode_data_file("maps")
assert_next(Data::MAP, {"one" => 1, "two" => 2, "three" => 3 })
assert_next(Data::MAP, {1 => "one", 2 => "two", 3 => "three"})
assert_next(Data::MAP, {})
assert !@data.next()
end
end
added backwards compatibility code for File.absolute_path
git-svn-id: 33ed6c3feaacb64944efc691d1ae8e09b17f2bf9@1494259 13f79535-47bb-0310-9956-ffa450edef68
#!/usr/bin/env ruby
require 'test/unit'
require 'qpid_proton'
if ((RUBY_VERSION.split(".").map {|x| x.to_i} <=> [1, 9]) < 0)
require 'pathname'
class File
def self.absolute_path(name)
return Pathname.new(name).realpath
end
end
end
class InteropTest < Test::Unit::TestCase
Data = Qpid::Proton::Data
Message = Qpid::Proton::Message
def setup
@data = Data.new
@message = Message.new
end
# Walk up the directory tree to find the tests directory.
def get_data(name)
path = File.absolute_path(__FILE__)
while path and File.basename(path) != "tests" do path = File.dirname(path); end
path = File.join(path,"interop")
raise "Can't find test/interop directory from #{__FILE__}" unless File.directory?(path)
path = File.join(path,"#{name}.amqp")
File.open(path, "rb") { |f| f.read }
end
# Decode encoded bytes as a Data object
def decode_data(encoded)
buffer = encoded
while buffer.size > 0
n = @data.decode(buffer)
buffer = buffer[n..-1]
end
@data.rewind
reencoded = @data.encode
# Test the round-trip re-encoding gives the same result.
assert_equal(encoded, reencoded)
end
def decode_data_file(name) decode_data(get_data(name)); end
def decode_message_file(name)
message = Message.new()
message.decode(self.get_data(name))
self.decode_data(message.content)
end
def assert_next(type, value)
assert @data.next
assert_equal(type, @data.type)
assert_equal(value, type.get(@data))
end
def test_message
decode_message_file("message")
assert_next(Data::STRING, "hello")
assert !@data.next()
end
def test_primitives
decode_data_file("primitives")
assert_next(Data::BOOL, true)
assert_next(Data::BOOL, false)
assert_next(Data::UBYTE, 42)
assert_next(Data::USHORT, 42)
assert_next(Data::SHORT, -42)
assert_next(Data::UINT, 12345)
assert_next(Data::INT, -12345)
assert_next(Data::ULONG, 12345)
assert_next(Data::LONG, -12345)
assert_next(Data::FLOAT, 0.125)
assert_next(Data::DOUBLE, 0.125)
assert !@data.next()
end
def test_strings
decode_data_file("strings")
assert_next(Data::BINARY, "abc\0defg")
assert_next(Data::STRING, "abcdefg")
assert_next(Data::SYMBOL, "abcdefg")
assert_next(Data::BINARY, "")
assert_next(Data::STRING, "")
assert_next(Data::SYMBOL, "")
assert !@data.next()
end
def test_described
decode_data_file("described")
assert_next(Data::DESCRIBED, Data::Described.new("foo-descriptor", "foo-value"))
assert(@data.described?)
assert_next(Data::DESCRIBED, Data::Described.new(12, 13))
assert(@data.described?)
assert !@data.next
end
def test_described_array
decode_data_file("described_array")
assert_next(Data::ARRAY, Data::Array.new("int-array", Data::INT, 0...10))
end
def test_arrays
decode_data_file("arrays")
assert_next(Data::ARRAY, Data::Array.new(false, Data::INT, 0...100))
assert_next(Data::ARRAY, Data::Array.new(false, Data::STRING, ["a", "b", "c"]))
assert_next(Data::ARRAY, Data::Array.new(false, Data::INT))
assert !@data.next
end
def test_lists
decode_data_file("lists")
assert_next(Data::LIST, [32, "foo", true])
assert_next(Data::LIST, [])
assert !@data.next
end
def test_maps
decode_data_file("maps")
assert_next(Data::MAP, {"one" => 1, "two" => 2, "three" => 3 })
assert_next(Data::MAP, {1 => "one", 2 => "two", 3 => "three"})
assert_next(Data::MAP, {})
assert !@data.next()
end
end
|
Shindo.tests('AWS::ELB | models', ['aws', 'elb']) do
@availability_zones = Fog::Compute[:aws].describe_availability_zones('state' => 'available').body['availabilityZoneInfo'].collect{ |az| az['zoneName'] }
tests('success') do
tests('load_balancers') do
tests('getting a missing elb') do
returns(nil) { AWS[:elb].load_balancers.get('no-such-elb') }
end
end
tests('listeners') do
tests("default attributes") do
listener = AWS[:elb].listeners.new
tests('instance_port is 80').returns(80) { listener.instance_port }
tests('lb_port is 80').returns(80) { listener.lb_port }
tests('protocol is HTTP').returns('HTTP') { listener.protocol }
tests('policy_names is empty').returns([]) { listener.policy_names }
end
tests("specifying attributes") do
attributes = {:instance_port => 2000, :lb_port => 2001, :protocol => 'SSL', :policy_names => ['fake'] }
listener = AWS[:elb].listeners.new(attributes)
tests('instance_port is 2000').returns(2000) { listener.instance_port }
tests('lb_port is 2001').returns(2001) { listener.lb_port }
tests('protocol is SSL').returns('SSL') { listener.protocol }
tests('policy_names is [ fake ]').returns(['fake']) { listener.policy_names }
end
end
elb = nil
elb_id = 'fog-test'
tests('create') do
tests('without availability zones') do
elb = AWS[:elb].load_balancers.create(:id => elb_id)
tests("availability zones are correct").returns(@availability_zones) { elb.availability_zones }
tests("dns names is set").returns(true) { elb.dns_name.is_a?(String) }
tests("created_at is set").returns(true) { Time === elb.created_at }
tests("policies is empty").returns([]) { elb.policies }
tests("default listener") do
tests("1 listener").returns(1) { elb.listeners.size }
tests("params").returns(AWS[:elb].listeners.new.to_params) { elb.listeners.first.to_params }
end
end
tests('with availability zones') do
azs = @availability_zones[1..-1]
elb2 = AWS[:elb].load_balancers.create(:id => "#{elb_id}-2", :availability_zones => azs)
tests("availability zones are correct").returns(azs) { elb2.availability_zones }
elb2.destroy
end
end
tests('all') do
elb_ids = AWS[:elb].load_balancers.all.map{|e| e.id}
tests("contains elb").returns(true) { elb_ids.include? elb_id }
end
tests('get') do
elb_get = AWS[:elb].load_balancers.get(elb_id)
tests('ids match').returns(elb_id) { elb_get.id }
end
tests('creating a duplicate elb') do
raises(Fog::AWS::ELB::IdentifierTaken) do
AWS[:elb].load_balancers.create(:id => elb_id, :availability_zones => ['us-east-1d'])
end
end
tests('registering an invalid instance') do
raises(Fog::AWS::ELB::InvalidInstance) { elb.register_instances('i-00000000') }
end
tests('deregistering an invalid instance') do
raises(Fog::AWS::ELB::InvalidInstance) { elb.deregister_instances('i-00000000') }
end
server = Fog::Compute[:aws].servers.create
tests('register instance') do
begin
elb.register_instances(server.id)
rescue Fog::AWS::ELB::InvalidInstance
# It may take a moment for a newly created instances to be visible to ELB requests
raise if @retried_registered_instance
@retried_registered_instance = true
sleep 1
retry
end
returns([server.id]) { elb.instances }
end
tests('instance_health') do
returns('OutOfService') do
elb.instance_health.detect{|hash| hash['InstanceId'] == server.id}['State']
end
returns([server.id]) { elb.instances_out_of_service }
end
tests('deregister instance') do
elb.deregister_instances(server.id)
returns([]) { elb.instances }
end
server.destroy
tests('disable_availability_zones') do
elb.disable_availability_zones(@availability_zones[1..-1])
returns(@availability_zones[0..0]) { elb.availability_zones.sort }
end
tests('enable_availability_zones') do
elb.enable_availability_zones(@availability_zones[1..-1])
returns(@availability_zones) { elb.availability_zones.sort }
end
tests('default health check') do
default_health_check = {
"HealthyThreshold"=>10,
"Timeout"=>5,
"UnhealthyThreshold"=>2,
"Interval"=>30,
"Target"=>"TCP:80"
}
returns(default_health_check) { elb.health_check }
end
tests('configure_health_check') do
new_health_check = {
"HealthyThreshold"=>5,
"Timeout"=>10,
"UnhealthyThreshold"=>3,
"Interval"=>15,
"Target"=>"HTTP:80/index.html"
}
elb.configure_health_check(new_health_check)
returns(new_health_check) { elb.health_check }
end
tests('listeners') do
tests('default') do
returns(1) { elb.listeners.size }
listener = elb.listeners.first
returns([80,80,'HTTP', []]) { [listener.instance_port, listener.lb_port, listener.protocol, listener.policy_names] }
end
tests('#get') do
returns(80) { elb.listeners.get(80).lb_port }
end
tests('create') do
new_listener = { 'InstancePort' => 443, 'LoadBalancerPort' => 443, 'Protocol' => 'TCP'}
elb.listeners.create(:instance_port => 443, :lb_port => 443, :protocol => 'TCP')
returns(2) { elb.listeners.size }
returns(443) { elb.listeners.get(443).lb_port }
end
tests('destroy') do
elb.listeners.get(443).destroy
returns(nil) { elb.listeners.get(443) }
end
end
tests('policies') do
app_policy_id = 'my-app-policy'
tests 'are empty' do
returns([]) { elb.policies.to_a }
end
tests('#all') do
returns([]) { elb.policies.all.to_a }
end
tests('create app policy') do
elb.policies.create(:id => app_policy_id, :cookie => 'my-app-cookie', :cookie_stickiness => :app)
returns(app_policy_id) { elb.policies.first.id }
end
tests('get policy') do
returns(app_policy_id) { elb.policies.get(app_policy_id).id }
end
tests('destroy app policy') do
elb.policies.first.destroy
returns([]) { elb.policies.to_a }
end
lb_policy_id = 'my-lb-policy'
tests('create lb policy') do
elb.policies.create(:id => lb_policy_id, :expiration => 600, :cookie_stickiness => :lb)
returns(lb_policy_id) { elb.policies.first.id }
end
tests('setting a listener policy') do
elb.set_listener_policy(80, lb_policy_id)
returns([lb_policy_id]) { elb.listeners.get(80).policy_names }
end
tests('unsetting a listener policy') do
elb.unset_listener_policy(80)
returns([]) { elb.listeners.get(80).policy_names }
end
tests('a malformed policy') do
raises(ArgumentError) { elb.policies.create(:id => 'foo', :cookie_stickiness => 'invalid stickiness') }
end
end
tests('destroy') do
elb.destroy
end
end
end
[aws|elb] add test to verify that ListenerDescriptions work when creating an ELB
Shindo.tests('AWS::ELB | models', ['aws', 'elb']) do
@availability_zones = Fog::Compute[:aws].describe_availability_zones('state' => 'available').body['availabilityZoneInfo'].collect{ |az| az['zoneName'] }
tests('success') do
tests('load_balancers') do
tests('getting a missing elb') do
returns(nil) { AWS[:elb].load_balancers.get('no-such-elb') }
end
end
tests('listeners') do
tests("default attributes") do
listener = AWS[:elb].listeners.new
tests('instance_port is 80').returns(80) { listener.instance_port }
tests('lb_port is 80').returns(80) { listener.lb_port }
tests('protocol is HTTP').returns('HTTP') { listener.protocol }
tests('policy_names is empty').returns([]) { listener.policy_names }
end
tests("specifying attributes") do
attributes = {:instance_port => 2000, :lb_port => 2001, :protocol => 'SSL', :policy_names => ['fake'] }
listener = AWS[:elb].listeners.new(attributes)
tests('instance_port is 2000').returns(2000) { listener.instance_port }
tests('lb_port is 2001').returns(2001) { listener.lb_port }
tests('protocol is SSL').returns('SSL') { listener.protocol }
tests('policy_names is [ fake ]').returns(['fake']) { listener.policy_names }
end
end
elb = nil
elb_id = 'fog-test'
tests('create') do
tests('without availability zones') do
elb = AWS[:elb].load_balancers.create(:id => elb_id)
tests("availability zones are correct").returns(@availability_zones) { elb.availability_zones }
tests("dns names is set").returns(true) { elb.dns_name.is_a?(String) }
tests("created_at is set").returns(true) { Time === elb.created_at }
tests("policies is empty").returns([]) { elb.policies }
tests("default listener") do
tests("1 listener").returns(1) { elb.listeners.size }
tests("params").returns(AWS[:elb].listeners.new.to_params) { elb.listeners.first.to_params }
end
end
tests('with availability zones') do
azs = @availability_zones[1..-1]
elb2 = AWS[:elb].load_balancers.create(:id => "#{elb_id}-2", :availability_zones => azs)
tests("availability zones are correct").returns(azs) { elb2.availability_zones }
elb2.destroy
end
tests('with ListenerDescriptions') do
listeners = [{
'Listener' => {'LoadBalancerPort' => 2030, 'InstancePort' => 2030, 'Protocol' => 'HTTP'},
'PolicyNames' => []
}, {
'Listener' => {'LoadBalancerPort' => 443, 'InstancePort' => 443, 'Protocol' => 'HTTPS'},
'PolicyNames' => []
}]
elb3 = AWS[:elb].load_balancers.create(:id => "#{elb_id}-3", 'ListenerDescriptions' => listeners)
tests('there are 2 listeners').returns(2) { elb3.listeners.count }
tests('instance_port is 2030').returns(2030) { elb3.listeners.first.instance_port }
tests('lb_port is 2030').returns(2030) { elb3.listeners.first.lb_port }
tests('protocol is HTTP').returns('HTTP') { elb3.listeners.first.protocol }
tests('protocol is HTTPS').returns('HTTPS') { elb3.listeners.last.protocol }
elb3.destroy
end
end
tests('all') do
elb_ids = AWS[:elb].load_balancers.all.map{|e| e.id}
tests("contains elb").returns(true) { elb_ids.include? elb_id }
end
tests('get') do
elb_get = AWS[:elb].load_balancers.get(elb_id)
tests('ids match').returns(elb_id) { elb_get.id }
end
tests('creating a duplicate elb') do
raises(Fog::AWS::ELB::IdentifierTaken) do
AWS[:elb].load_balancers.create(:id => elb_id, :availability_zones => ['us-east-1d'])
end
end
tests('registering an invalid instance') do
raises(Fog::AWS::ELB::InvalidInstance) { elb.register_instances('i-00000000') }
end
tests('deregistering an invalid instance') do
raises(Fog::AWS::ELB::InvalidInstance) { elb.deregister_instances('i-00000000') }
end
server = Fog::Compute[:aws].servers.create
tests('register instance') do
begin
elb.register_instances(server.id)
rescue Fog::AWS::ELB::InvalidInstance
# It may take a moment for a newly created instances to be visible to ELB requests
raise if @retried_registered_instance
@retried_registered_instance = true
sleep 1
retry
end
returns([server.id]) { elb.instances }
end
tests('instance_health') do
returns('OutOfService') do
elb.instance_health.detect{|hash| hash['InstanceId'] == server.id}['State']
end
returns([server.id]) { elb.instances_out_of_service }
end
tests('deregister instance') do
elb.deregister_instances(server.id)
returns([]) { elb.instances }
end
server.destroy
tests('disable_availability_zones') do
elb.disable_availability_zones(@availability_zones[1..-1])
returns(@availability_zones[0..0]) { elb.availability_zones.sort }
end
tests('enable_availability_zones') do
elb.enable_availability_zones(@availability_zones[1..-1])
returns(@availability_zones) { elb.availability_zones.sort }
end
tests('default health check') do
default_health_check = {
"HealthyThreshold"=>10,
"Timeout"=>5,
"UnhealthyThreshold"=>2,
"Interval"=>30,
"Target"=>"TCP:80"
}
returns(default_health_check) { elb.health_check }
end
tests('configure_health_check') do
new_health_check = {
"HealthyThreshold"=>5,
"Timeout"=>10,
"UnhealthyThreshold"=>3,
"Interval"=>15,
"Target"=>"HTTP:80/index.html"
}
elb.configure_health_check(new_health_check)
returns(new_health_check) { elb.health_check }
end
tests('listeners') do
tests('default') do
returns(1) { elb.listeners.size }
listener = elb.listeners.first
returns([80,80,'HTTP', []]) { [listener.instance_port, listener.lb_port, listener.protocol, listener.policy_names] }
end
tests('#get') do
returns(80) { elb.listeners.get(80).lb_port }
end
tests('create') do
new_listener = { 'InstancePort' => 443, 'LoadBalancerPort' => 443, 'Protocol' => 'TCP'}
elb.listeners.create(:instance_port => 443, :lb_port => 443, :protocol => 'TCP')
returns(2) { elb.listeners.size }
returns(443) { elb.listeners.get(443).lb_port }
end
tests('destroy') do
elb.listeners.get(443).destroy
returns(nil) { elb.listeners.get(443) }
end
end
tests('policies') do
app_policy_id = 'my-app-policy'
tests 'are empty' do
returns([]) { elb.policies.to_a }
end
tests('#all') do
returns([]) { elb.policies.all.to_a }
end
tests('create app policy') do
elb.policies.create(:id => app_policy_id, :cookie => 'my-app-cookie', :cookie_stickiness => :app)
returns(app_policy_id) { elb.policies.first.id }
end
tests('get policy') do
returns(app_policy_id) { elb.policies.get(app_policy_id).id }
end
tests('destroy app policy') do
elb.policies.first.destroy
returns([]) { elb.policies.to_a }
end
lb_policy_id = 'my-lb-policy'
tests('create lb policy') do
elb.policies.create(:id => lb_policy_id, :expiration => 600, :cookie_stickiness => :lb)
returns(lb_policy_id) { elb.policies.first.id }
end
tests('setting a listener policy') do
elb.set_listener_policy(80, lb_policy_id)
returns([lb_policy_id]) { elb.listeners.get(80).policy_names }
end
tests('unsetting a listener policy') do
elb.unset_listener_policy(80)
returns([]) { elb.listeners.get(80).policy_names }
end
tests('a malformed policy') do
raises(ArgumentError) { elb.policies.create(:id => 'foo', :cookie_stickiness => 'invalid stickiness') }
end
end
tests('destroy') do
elb.destroy
end
end
end
|
Regenerate gemspec for version 0.1.0
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{forgetful-web}
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Jonathan Palardy"]
s.date = %q{2011-05-14}
s.default_executable = %q{forgetful-web}
s.description = %q{A sinatra front-end for the forgetful gem}
s.email = %q{jonathan.palardy@gmail.com}
s.executables = ["forgetful-web"]
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"bin/forgetful-web",
"lib/forgetful-web.rb",
"public/css/main.css",
"public/index.html",
"public/js/app.js",
"public/js/jquery-1.5.min.js",
"public/js/jquery.tmpl.min.js"
]
s.homepage = %q{http://github.com/jpalardy/forgetful-web}
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{A sinatra front-end for the forgetful gem}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<vegas>, [">= 0"])
s.add_runtime_dependency(%q<sinatra>, [">= 0"])
s.add_runtime_dependency(%q<json>, [">= 0"])
s.add_runtime_dependency(%q<forgetful>, [">= 0.5"])
s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"])
else
s.add_dependency(%q<vegas>, [">= 0"])
s.add_dependency(%q<sinatra>, [">= 0"])
s.add_dependency(%q<json>, [">= 0"])
s.add_dependency(%q<forgetful>, [">= 0.5"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.5.2"])
end
else
s.add_dependency(%q<vegas>, [">= 0"])
s.add_dependency(%q<sinatra>, [">= 0"])
s.add_dependency(%q<json>, [">= 0"])
s.add_dependency(%q<forgetful>, [">= 0.5"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.5.2"])
end
end
|
# pushover.rb
# rubocop:disable Style/LineLength, Style/GlobalVars
#
# Copyright (c) 2014 Les Aker <me@lesaker.org>
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Changelog:
# 0.0.1 - Initial functionality
require 'net/https'
DEFAULTS = {
userkey: nil,
appkey: nil,
devicename: nil,
interval: '10', # seconds
pm_priority: '1',
hilight_priority: '1',
onlywhenaway: '0',
enabled: '1'
}
URL = URI.parse('https://api.pushover.net/1/messages.json')
##
# API rate limit calculator
class RateCalc
def initialize(resp, interval)
seconds_left = resp['X-Limit-App-Reset'].to_i - Time.now.to_i
@potential = seconds_left / interval.to_i
@remaining = resp['X-Limit-App-Remaining'].to_i
end
def value
@remaining - @potential
end
end
##
# Handler for Pushover API
class PushoverClient
attr_reader :client
def initialize(params)
create_template params
create_client
end
def send(params)
data = @template.dup
data.merge! params
req = Net::HTTP::Post.new URL.path
req.set_form_data data
@client.request req
end
def close
@client.finish
end
private
def create_template(params)
@template = {
token: params[:appkey],
user: params[:userkey]
}
@template[:device] = params[:device] if params[:device]
end
def create_client
@client = Net::HTTP.new URL.host, URL.port
@client.use_ssl = true
@client.verify_mode = OpenSSL::SSL::VERIFY_PEER
@client.start
end
end
##
# Message object
class PushoverMessage
attr_reader :title, :text, :is_pm
def initialize(buffer, nick, text)
@title, @is_pm = PushoverMessage.parse_buffer buffer
@text = "#{"<#{nick}> " unless @is_pm}#{text}"
trim!
end
private
def trim!
@text = "#{text.slice(0, 497 - @title.length)}..." if @text.length > 500
end
class << self
def parse_buffer(buffer)
name = Weechat.buffer_get_string(buffer, 'full_name').split('.').last
type = Weechat.buffer_get_string(buffer, 'localvar_type')
[name, (type == 'private')]
end
end
end
##
# Coalesced message, used to conserve API requests
class PushoverMessageBundle < PushoverMessage
def initialize(messages)
@is_pm = messages.any? { |x| x.is_pm }
if messages.map(&:title).uniq.size == 1
parse_single_author
else
parse_multi_author
end
trim!
end
private
def parse_single_author
@title = messages.first.title
@text = messages.map(&:text).join(' || ')
end
def parse_multi_author
@title = 'Messages from multiple sources'
counts = Hash[messages.group_by(&:title).map { |k, v| [k, v.size] }]
counts.sort!
@text = counts.reduce('') { |a, (k, v)| a << "#{k} (#{v}), " }[0..-3]
end
end
##
# Handles message queue and configuration
class PushoverConfig
def initialize
@queue = []
@health_check = 200
@rate_calc = 0
load_options
load_hooks
end
def command_hook(_, _, args)
case args
when 'enable' then enable!
when 'disable' then disable!
when /^set (?<option>\w+) (?<value>[\w]+)/
set Regexp.last_match['option'], Regexp.last_match['value']
else
Weechat.print('', "Syntax: #{completion_text}")
end
Weechat::WEECHAT_RC_OK
end
def message_hook(*args)
buffer, nick, text = args.values_at(1, 6, 7)
if Weechat.config_string_to_boolean(@options[:enabled]).to_i.zero?
return Weechat::WEECHAT_RC_OK
end
unless Weechat.config_string_to_boolean(@options[:onlywhenaway]).to_i.zero?
away_msg = Weechat.buffer_get_string buffer, 'localvar_away'
return Weechat::WEECHAT_RC_OK if away_msg && away_msg.length > 0
end
@queue << PushoverMessage.new(buffer, nick, text)
Weechat::WEECHAT_RC_OK
end
def timer_hook(*_)
return Weechat::WEECHAT_RC_OK if @queue.empty?
if @health_check < 0
@health_check += 1
return Weechat::WEECHAT_RC_OK
end
coalesce_messages if @rate_calc < 0
send_messages
Weechat::WEECHAT_RC_OK
end
private
def coalesce_messages
# Dummy method for now
end
def send_messages
client = PushoverClient.new @options
@queue = @queue.drop_while do |message|
resp = client.send(
title: message.buffer,
message: message.clean_text,
priority: @options[message.is_pm ? :pm_priority : :hilight_priority]
)
parse_response resp
end
end
def parse_response(resp)
case resp.code
when /200/
@rate_calc = RateCalc.new(resp, @options[:interval]).value
when /429/
disable! 'Pushover message limit exceeded'
when /4\d\d/
disable! "Pushover error: #{resp.body}"
else
server_failure!
end
end
def disable!(reason)
Weechat.print '', reason
Weechat.print '', 'Disabling Pushover notifications'
@options[:enabled] = '0'
@queue.clear
false
end
def server_failure!
Weechat.print '', 'Pushover server error detected, delaying notifications'
@health_check -= 5
false
end
def set(option, value)
if @options.keys.include? option.to_sym
@options[option.to_sym] = value
Weechat.config_set_plugin option, value
Weechat.print '', "Pushover: set #{option} to #{value}"
load_hooks if [:interval].include? option.to_sym
else
Weechat.print '', "Available options: #{@options.keys.join ', '}"
end
end
def load_options
@options = DEFAULTS.dup
@options.each_key do |key|
value = Weechat.config_get_plugin key.to_s
@options[key] = value if value
Weechat.config_set_plugin key.to_s, @options[key]
end
end
def load_hooks
@hooks.each_value { |x| Weechat.unhook x } if @hooks
@hooks = {
command: Weechat.hook_command(
'pushover', 'Control Pushover options',
'set OPTION VALUE', '', "#{completion_text}",
'command_hook', ''
),
message: Weechat.hook_print('', 'irc_privmsg', '', 1, 'message_hook', ''),
timer: Weechat.hook_timer(@options[:interval].to_i * 1000, 0, 0, 'timer_hook', '')
}
end
def completion_text
"set #{@options.keys.join '|'}"
end
end
def weechat_init
Weechat.register(
'pushover', 'Les Aker <me@lesaker.org>',
'0.0.1', 'MIT',
'Send hilight notifications via Pushover',
'', ''
)
$Pushover = PushoverConfig.new
Weechat::WEECHAT_RC_OK
end
require 'forwardable'
extend Forwardable
def_delegators :$Pushover, :message_hook, :command_hook, :timer_hook
fix bugs
# pushover.rb
# rubocop:disable Style/LineLength, Style/GlobalVars
#
# Copyright (c) 2014 Les Aker <me@lesaker.org>
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Changelog:
# 0.0.1 - Initial functionality
require 'net/https'
DEFAULTS = {
userkey: nil,
appkey: nil,
devicename: nil,
interval: '10', # seconds
pm_priority: '1',
hilight_priority: '1',
onlywhenaway: '0',
enabled: '1'
}
URL = URI.parse('https://api.pushover.net/1/messages.json')
##
# API rate limit calculator
class RateCalc
def initialize(resp, interval)
seconds_left = resp['X-Limit-App-Reset'].to_i - Time.now.to_i
@potential = seconds_left / interval.to_i
@remaining = resp['X-Limit-App-Remaining'].to_i
end
def value
@remaining - @potential
end
end
##
# Handler for Pushover API
class PushoverClient
attr_reader :client
def initialize(params)
create_template params
create_client
end
def send(params)
data = @template.dup
data.merge! params
req = Net::HTTP::Post.new URL.path
req.set_form_data data
@client.request req
end
def close
@client.finish
end
private
def create_template(params)
@template = {
token: params[:appkey],
user: params[:userkey]
}
@template[:device] = params[:device] if params[:device]
end
def create_client
@client = Net::HTTP.new URL.host, URL.port
@client.use_ssl = true
@client.verify_mode = OpenSSL::SSL::VERIFY_PEER
@client.start
end
end
##
# Message object
class PushoverMessage
attr_reader :title, :text, :is_pm
def initialize(buffer, nick, text)
@title, @is_pm = PushoverMessage.parse_buffer buffer
@text = "#{"<#{nick}> " unless @is_pm}#{text}"
trim!
end
private
def trim!
@text = "#{text.slice(0, 497 - @title.length)}..." if @text.length > 500
end
class << self
def parse_buffer(buffer)
name = Weechat.buffer_get_string(buffer, 'full_name').split('.').last
type = Weechat.buffer_get_string(buffer, 'localvar_type')
[name, (type == 'private')]
end
end
end
##
# Coalesced message, used to conserve API requests
class PushoverMessageBundle < PushoverMessage
def initialize(messages)
@is_pm = messages.any? { |x| x.is_pm }
if messages.map(&:title).uniq.size == 1
parse_single_author
else
parse_multi_author
end
trim!
end
private
def parse_single_author
@title = messages.first.title
@text = messages.map(&:text).join(' || ')
end
def parse_multi_author
@title = 'Messages from multiple sources'
counts = Hash[messages.group_by(&:title).map { |k, v| [k, v.size] }]
counts.sort!
@text = counts.reduce('') { |a, (k, v)| a << "#{k} (#{v}), " }[0..-3]
end
end
##
# Handles message queue and configuration
class PushoverConfig
def initialize
@queue = []
@health_check = 200
@rate_calc = 0
load_options
load_hooks
end
def command_hook(_, _, args)
case args
when 'enable' then enable!
when 'disable' then disable!
when /^set (?<option>\w+) (?<value>[\w]+)/
set Regexp.last_match['option'], Regexp.last_match['value']
else
Weechat.print('', "Syntax: #{completion_text}")
end
Weechat::WEECHAT_RC_OK
end
def message_hook(*args)
buffer, is_highlight, nick, text = args.values_at(1, 5, 6, 7)
is_pm = (Weechat.buffer_get_string(buffer, 'localvar_type') == 'private')
return Weechat::WEECHAT_RC_OK if is_highlight.to_i.zero? && !is_pm
if Weechat.config_string_to_boolean(@options[:enabled]).to_i.zero?
return Weechat::WEECHAT_RC_OK
end
unless Weechat.config_string_to_boolean(@options[:onlywhenaway]).to_i.zero?
away_msg = Weechat.buffer_get_string buffer, 'localvar_away'
return Weechat::WEECHAT_RC_OK unless away_msg && away_msg.length > 0
end
@queue << PushoverMessage.new(buffer, nick, text)
Weechat::WEECHAT_RC_OK
end
def timer_hook(*_)
return Weechat::WEECHAT_RC_OK if @queue.empty?
if @health_check < 0
@health_check += 1
return Weechat::WEECHAT_RC_OK
end
coalesce_messages if @rate_calc < 0
send_messages
Weechat::WEECHAT_RC_OK
end
private
def coalesce_messages
# Dummy method for now
end
def send_messages
client = PushoverClient.new @options
@queue = @queue.drop_while do |message|
resp = client.send(
title: message.title,
message: message.text,
priority: @options[message.is_pm ? :pm_priority : :hilight_priority]
)
parse_response resp
end
end
def parse_response(resp)
case resp.code
when /200/
@rate_calc = RateCalc.new(resp, @options[:interval]).value
when /429/
disable! 'Pushover message limit exceeded'
when /4\d\d/
disable! "Pushover error: #{resp.body}"
else
server_failure!
end
end
def disable!(reason)
Weechat.print '', reason
Weechat.print '', 'Disabling Pushover notifications'
@options[:enabled] = '0'
@queue.clear
false
end
def server_failure!
Weechat.print '', 'Pushover server error detected, delaying notifications'
@health_check -= 5
false
end
def set(option, value)
if @options.keys.include? option.to_sym
@options[option.to_sym] = value
Weechat.config_set_plugin option, value
Weechat.print '', "Pushover: set #{option} to #{value}"
load_hooks if [:interval].include? option.to_sym
else
Weechat.print '', "Available options: #{@options.keys.join ', '}"
end
end
def load_options
@options = DEFAULTS.dup
@options.each_key do |key|
value = Weechat.config_get_plugin key.to_s
@options[key] = value if value
Weechat.config_set_plugin key.to_s, @options[key]
end
end
def load_hooks
tags = 'notify_message,notify_private,notify_highlight'
@hooks.each_value { |x| Weechat.unhook x } if @hooks
@hooks = {
command: Weechat.hook_command(
'pushover', 'Control Pushover options',
'set OPTION VALUE', '', "#{completion_text}",
'command_hook', ''
),
message: Weechat.hook_print('', tags, '', 1, 'message_hook', ''),
timer: Weechat.hook_timer(@options[:interval].to_i * 1000, 0, 0, 'timer_hook', '')
}
end
def completion_text
"set #{@options.keys.join '|'}"
end
end
def weechat_init
Weechat.register(
'pushover', 'Les Aker <me@lesaker.org>',
'0.0.1', 'MIT',
'Send hilight notifications via Pushover',
'', ''
)
$Pushover = PushoverConfig.new
Weechat::WEECHAT_RC_OK
end
require 'forwardable'
extend Forwardable
def_delegators :$Pushover, :message_hook, :command_hook, :timer_hook
|
#!/usr/bin/env ruby
# encoding: utf-8
require 'open3'
require 'fileutils'
puts "Buildpack name: #{ENV['BUILDPACK_NAME']}\n"
_, status = Open3.capture2e('cf', 'api', ENV['CF_API'])
raise 'cf target failed' unless status.success?
_, status = Open3.capture2e('cf','auth', ENV['USERNAME'], ENV['PASSWORD'])
raise 'cf auth failed' unless status.success?
puts "Original Buildpacks\n==================="
system('cf', 'buildpacks')
stacks = ENV['STACKS'].split(' ')
stacks.each do |stack|
if ENV['BUILDPACK_NAME'] == 'java'
orig_filename = Dir.glob("pivnet-production/#{ENV['BUILDPACK_NAME']}-buildpack-offline*.zip").first
File.write('manifest.yml',"stack: #{stack}")
system(<<~EOF)
zip #{orig_filename} manifest.yml
EOF
filename = orig_filename.gsub(/-offline/,"-offline-#{stack}")
FileUtils.cp(orig_filename, filename)
else
orig_filename = Dir.glob("pivotal-buildpack-cached-#{stack}/#{ENV['BUILDPACK_NAME']}*.zip").first
filename = orig_filename.gsub(/\+\d+\.zip$/, '.zip')
FileUtils.mv(orig_filename, filename)
end
stack = '' if stack == 'any'
buildpack_name = ENV['BUILDPACK_NAME'] != 'dotnet-core' ? ENV['BUILDPACK_NAME'] + '_buildpack' : 'dotnet_core_buildpack'
puts "\ncf create-buildpack #{buildpack_name} #{filename} 0"
out, status = Open3.capture2e('cf', 'create-buildpack', "#{buildpack_name}", "#{filename}", '0')
raise "cf create-buildpack failed: #{out}" unless status.success?
if out.include?('already exists')
puts "\n#{buildpack_name} already exists with stack #{stack}; updating buildpack instead."
puts "\ncf update-buildpack #{buildpack_name} -p #{filename} -s #{stack}"
out, status = Open3.capture2e('cf', 'update-buildpack', "#{buildpack_name}", '-p', "#{filename}", '-s', "#{stack}")
raise "cf update-buildpack failed: #{out}" unless status.success?
else
puts "\nSkipping update because #{buildpack_name} with #{stack} was newly created."
end
end
Use cf curl to ascertain presence of bp name/stack combo [#160271913]
#!/usr/bin/env ruby
# encoding: utf-8
require 'open3'
require 'fileutils'
require 'json'
puts "Buildpack name: #{ENV['BUILDPACK_NAME']}\n"
_, status = Open3.capture2e('cf', 'api', ENV['CF_API'])
raise 'cf target failed' unless status.success?
_, status = Open3.capture2e('cf','auth', ENV['USERNAME'], ENV['PASSWORD'])
raise 'cf auth failed' unless status.success?
puts "Original Buildpacks\n==================="
system('cf', 'buildpacks')
stacks = ENV['STACKS'].split(' ')
stacks.each do |stack|
if ENV['BUILDPACK_NAME'] == 'java'
orig_filename = Dir.glob("pivnet-production/#{ENV['BUILDPACK_NAME']}-buildpack-offline*.zip").first
File.write('manifest.yml',"stack: #{stack}")
system(<<~EOF)
zip #{orig_filename} manifest.yml
EOF
filename = orig_filename.gsub(/-offline/,"-offline-#{stack}")
FileUtils.cp(orig_filename, filename)
else
orig_filename = Dir.glob("pivotal-buildpack-cached-#{stack}/#{ENV['BUILDPACK_NAME']}*.zip").first
filename = orig_filename.gsub(/\+\d+\.zip$/, '.zip')
FileUtils.mv(orig_filename, filename)
end
stack = '' if stack == 'any'
buildpack_name = ENV['BUILDPACK_NAME'] != 'dotnet-core' ? ENV['BUILDPACK_NAME'] + '_buildpack' : 'dotnet_core_buildpack'
if buildpack_exists(buildpack_name, stack)
puts "\n#{buildpack_name} already exists with stack #{stack}; updating buildpack."
puts "\ncf update-buildpack #{buildpack_name} -p #{filename} -s #{stack}"
out, status = Open3.capture2e('cf', 'update-buildpack', "#{buildpack_name}", '-p', "#{filename}", '-s', "#{stack}")
raise "cf update-buildpack failed: #{out}" unless status.success?
else
puts "\n#{buildpack_name} with #{stack} does not exist; creating buildpack."
puts "\ncf create-buildpack #{buildpack_name} #{filename} 0"
out, status = Open3.capture2e('cf', 'create-buildpack', "#{buildpack_name}", "#{filename}", '0')
raise "cf create-buildpack failed: #{out}" unless status.success?
end
end
def buildpack_exists(name, stack)
out, status = Open3.capture2e('cf', 'curl', "/v2/buildpacks")
raise "curling cf v2 buildpack failed: #{out}" unless status.success?
response = JSON.parse(out)
response["resources"].each do |resource|
if resource["entity"]["name"] == name && resource["entity"]["stack"] == stack_mapping(stack)
return true
end
end
false
end
def stack_mapping(stack)
return stack == '' ? nil : stack
end
|
Added index on issues.state
This field is queried when filtering issues and due to the lack of an
index would end up triggering a sequence scan.
class AddIssuesStateIndex < ActiveRecord::Migration
def change
add_index :issues, :state
end
end
|
class QuestionsController < ApplicationController
def index
@question = Question.new
@questions = Question.all
end
def new
@question = Question.new(params[:question][:body])
end
def show
@question = Question.find(params[:id])
@answers = @question.answers
@comments
end
def create
@question = Question.create(body: params[:question][:body])
redirect_to root_path
end
def edit
end
def update
end
def delete
end
end
commented out Questions#new because new question is created from the index page and does not require it's own route
class QuestionsController < ApplicationController
def index
@question = Question.new
@questions = Question.all
end
# def new
# @question = Question.new(params[:question][:body])
# end
def show
@question = Question.find(params[:id])
@answers = @question.answers
@comments
end
def create
@question = Question.create(body: params[:question][:body])
redirect_to root_path
end
def edit
end
def update
end
def delete
end
end |
module ChefResource
VERSION = '0.2.1'
end
Bump revision to 0.2.2
module ChefResource
VERSION = '0.2.2'
end
|
Regenerate gemspec for version 1.0.0
|
#
# Be sure to run `pod spec lint iOSCommon.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "PagerView"
s.version = "0.0.2"
s.summary = "The PagerView is compatible with AutoLayout and iDevice Rotation"
s.description = <<-DESC
A longer description of iOSCommon in Markdown format.
* Think: Why did you write this? What is the focus? What does it do?
* CocoaPods will be using this to generate tags, and improve search results.
* Try to keep it short, snappy and to the point.
* Finally, don't worry about the indent, CocoaPods strips it!
DESC
s.homepage = "https://github.com/xiachufang/PagerView"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
s.license = "MIT"
# s.license = { :type => "MIT", :file => "LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "cikelengfeng" => "cikelengfeng@gmail.com" }
# Or just: s.author = ""
# s.authors = { "" => "" }
# s.social_media_url = "http://twitter.com/"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
# s.platform = :ios
s.platform = :ios, "5.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "git@github.com:xiachufang/PagerView.git", :tag => "0.0.2" }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any h, m, mm, c & cpp files. For header
# files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "Classes/**/*.{h,m}"
s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
s.frameworks = "Foundation", "UIKit"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
[MOD] update pod spec
#
# Be sure to run `pod spec lint iOSCommon.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "PagerView"
s.version = "0.0.3"
s.summary = "The PagerView is compatible with AutoLayout and iDevice Rotation"
s.description = <<-DESC
A longer description of iOSCommon in Markdown format.
* Think: Why did you write this? What is the focus? What does it do?
* CocoaPods will be using this to generate tags, and improve search results.
* Try to keep it short, snappy and to the point.
* Finally, don't worry about the indent, CocoaPods strips it!
DESC
s.homepage = "https://github.com/xiachufang/PagerView"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
s.license = "MIT"
# s.license = { :type => "MIT", :file => "LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "cikelengfeng" => "cikelengfeng@gmail.com" }
# Or just: s.author = ""
# s.authors = { "" => "" }
# s.social_media_url = "http://twitter.com/"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
# s.platform = :ios
s.platform = :ios, "5.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "git@github.com:xiachufang/PagerView.git", :tag => "0.0.3" }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any h, m, mm, c & cpp files. For header
# files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "Classes/**/*.{h,m}"
s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
s.frameworks = "Foundation", "UIKit"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
end
|
Pod::Spec.new do |s|
s.name = 'PredictionBuilder'
s.version = '1.0.2'
s.homepage = 'https://github.com/denissimon/prediction-builder-swift'
s.authors = {
'Denis Simon' => 'denis.v.simon@gmail.com'
}
s.summary = 'A library for machine learning that builds predictions using a linear regression.'
s.license = { :type => 'MIT' }
s.source = {
:git => 'https://github.com/denissimon/prediction-builder-swift.git',
:tag => 'v'+s.version.to_s
}
s.source_files = 'Sources/PredictionBuilder.swift'
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.9"
s.watchos.deployment_target = "2.0"
s.tvos.deployment_target = "9.0"
end
Update PredictionBuilder.podspec
Pod::Spec.new do |s|
s.name = 'PredictionBuilder'
s.version = '1.1.0'
s.homepage = 'https://github.com/denissimon/prediction-builder-swift'
s.author = { 'Denis Simon' => 'denis.v.simon@gmail.com' }
s.summary = 'A library for machine learning that builds predictions using a linear regression.'
s.license = { :type => 'MIT' }
s.swift_version = "4.2"
s.ios.deployment_target = "8.0"
s.osx.deployment_target = "10.9"
s.watchos.deployment_target = "2.0"
s.tvos.deployment_target = "9.0"
s.source = { :git => 'https://github.com/denissimon/prediction-builder-swift.git', :tag => 'v'+s.version.to_s }
s.source_files = 'Sources/**/*.swift'
s.frameworks = "Foundation"
end
|
Pod::Spec.new do |s|
s.name = "Overline"
s.version = "0.1.4"
s.summary = "Objective-C utilities and shorthands."
s.homepage = "https://github.com/yaakaito/Overline"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.platform = :ios
s.author = { "KAZUMA Ukyo" => "yaakaito@gmail.com" }
s.source = { :git => "https://github.com/yaakaito/Overline.git", :tag => "0.1.4" }
s.source_files = 'Overline', 'Overline/**/*.{h,m}'
s.public_header_files = 'Overline/**/*.h'
s.requires_arc = true
end
updated podspec
Pod::Spec.new do |s|
s.name = "Overline"
s.version = "0.1.5"
s.summary = "Objective-C utilities and shorthands."
s.homepage = "https://github.com/yaakaito/Overline"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.platform = :ios
s.author = { "KAZUMA Ukyo" => "yaakaito@gmail.com" }
s.source = { :git => "https://github.com/yaakaito/Overline.git", :tag => "0.1.5" }
s.source_files = 'Overline', 'Overline/**/*.{h,m}'
s.public_header_files = 'Overline/**/*.h'
s.requires_arc = true
end
|
require "cases/helper"
require "models/developer"
class PreparedStatementsTest < ActiveRecord::PostgreSQLTestCase
fixtures :developers
def setup
@default_prepared_statements = Developer.connection_config[:prepared_statements]
Developer.connection_config[:prepared_statements] = false
end
def teardown
Developer.connection_config[:prepared_statements] = @default_prepared_statements
end
def nothing_raised_with_falsy_prepared_statements
assert_nothing_raised do
Developer.where(id: 1)
end
end
end
Fix PG prepared statement test
require "cases/helper"
require "models/computer"
require "models/developer"
class PreparedStatementsTest < ActiveRecord::PostgreSQLTestCase
fixtures :developers
def setup
@default_prepared_statements = Developer.connection_config[:prepared_statements]
Developer.connection_config[:prepared_statements] = false
end
def teardown
Developer.connection_config[:prepared_statements] = @default_prepared_statements
end
def test_nothing_raised_with_falsy_prepared_statements
assert_nothing_raised do
Developer.where(id: 1)
end
end
end
|
Gem::Specification.new do |s|
s.name = 'chef-handler-elapsed-time'
s.version = '0.1.2'
s.platform = Gem::Platform::RUBY
s.summary = "Chef report handler to graphically display time spend in each resource during the Chef Run"
s.description = "Chef report handler to graphically display time spend in each resource during the Chef Run. Outputs the time as ASCII bar chart at end of run."
s.author = "James Casey"
s.email = "jamesc.000@gmail.com"
s.homepage = "https://github.com/jamesc/chef-handler-elapsed-time"
s.require_path = 'lib'
s.files = %w(LICENSE README.md) + Dir.glob("lib/**/*")
end
Tagging 0.1.3
Gem::Specification.new do |s|
s.name = 'chef-handler-elapsed-time'
s.version = '0.1.3'
s.platform = Gem::Platform::RUBY
s.summary = "Chef report handler to graphically display time spend in each resource during the Chef Run"
s.description = "Chef report handler to graphically display time spend in each resource during the Chef Run. Outputs the time as ASCII bar chart at end of run."
s.author = "James Casey"
s.email = "jamesc.000@gmail.com"
s.homepage = "https://github.com/jamesc/chef-handler-elapsed-time"
s.require_path = 'lib'
s.files = %w(LICENSE README.md) + Dir.glob("lib/**/*")
end
|
# frozen_string_literal: true
require 'spec_helper'
require_relative 'command_line_interface'
describe Que::CommandLineInterface do
LOADED_FILES = {}
around do |&block|
super() do
# Let the CLI set the logger if it needs to.
Que.logger = nil
block.call
$stop_que_executable = nil
LOADED_FILES.clear
written_files.each { |name| File.delete("#{name}.rb") }
end
end
let(:written_files) { [] }
let :output do
o = Object.new
def o.puts(arg)
messages << arg
end
def o.messages
@messages ||= []
end
o
end
def assert_successful_invocation(
command,
queue_name: 'default',
default_require_file: Que::CommandLineInterface::RAILS_ENVIRONMENT_FILE
)
BlockJob.enqueue(queue: queue_name)
thread =
Thread.new do
execute(
command,
default_require_file: default_require_file,
)
end
unless sleep_until { !$q1.empty? }
puts "CLI invocation thread hung!"
thread.join
end
$q1.pop
@que_locker = DB[:que_lockers].first
yield if block_given?
$stop_que_executable = true
$q2.push nil
assert_equal 0, thread.value
end
def execute(
text,
default_require_file: Que::CommandLineInterface::RAILS_ENVIRONMENT_FILE
)
Que::CommandLineInterface.parse(
args: text.split(/\s/),
output: output,
default_require_file: default_require_file,
)
end
def write_file
# On CircleCI we run the spec suite in parallel, and writing/deleting the
# same files will result in spec failures. So instead just generate a new
# file name for each spec to write/delete.
name = "spec/temp/file_#{Digest::MD5.hexdigest(rand.to_s)}"
written_files << name
File.open("#{name}.rb", 'w') { |f| f.puts %(LOADED_FILES["#{name}"] = true) }
name
end
["-h", "--help"].each do |command|
it "when invoked with #{command} should print help text" do
code = execute(command)
assert_equal 0, code
assert_equal 1, output.messages.length
assert_match %r(usage: que \[options\] \[file/to/require\]), output.messages.first.to_s
end
end
["-v", "--version"].each do |command|
it "when invoked with #{command} should print the version" do
code = execute(command)
assert_equal 0, code
assert_equal 1, output.messages.length
assert_equal "Que version #{Que::VERSION}", output.messages.first.to_s
end
end
describe "when requiring files" do
it "should infer the default require file if it exists" do
filename = write_file
assert_successful_invocation "", default_require_file: "./#{filename}.rb"
assert_equal(
{filename => true},
LOADED_FILES
)
end
it "should output an error message if no files are specified and the rails config file doesn't exist" do
code = execute("")
assert_equal 1, code
assert_equal 1, output.messages.length
assert_equal <<-MSG, output.messages.first.to_s
You didn't include any Ruby files to require!
Que needs to be able to load your application before it can process jobs.
(Or use `que -h` for a list of options)
MSG
end
it "should be able to require multiple files" do
files = 2.times.map { write_file }
assert_successful_invocation "./#{files[0]} ./#{files[1]}"
assert_equal(
[
"",
"Finishing Que's current jobs before exiting...",
"Que's jobs finished, exiting...",
],
output.messages,
)
assert_equal(
{
files[0] => true,
files[1] => true,
},
LOADED_FILES,
)
end
it "should raise an error if any of the files don't exist" do
name = write_file
code = execute "./#{name} ./nonexistent_file"
assert_equal 1, code
assert_equal ["Could not load file './nonexistent_file'"], output.messages
assert_equal(
{name => true},
LOADED_FILES
)
end
end
describe "should start up a locker" do
let(:filename) { write_file }
before { filename }
after do
assert_equal(
{filename => true},
LOADED_FILES
)
end
def assert_locker_instantiated(
worker_priorities: [10, 30, 50],
poll_interval: 5,
wait_period: 50,
queues: ['default'],
minimum_queue_size: 2,
maximum_queue_size: 8
)
locker_instantiates = internal_messages(event: 'locker_instantiate')
assert_equal 1, locker_instantiates.length
locker_instantiate = locker_instantiates.first
assert_equal true, locker_instantiate[:listen]
assert_equal true, locker_instantiate[:poll]
assert_equal queues, locker_instantiate[:queues]
assert_equal poll_interval, locker_instantiate[:poll_interval]
assert_equal wait_period, locker_instantiate[:wait_period]
assert_equal minimum_queue_size, locker_instantiate[:minimum_queue_size]
assert_equal maximum_queue_size, locker_instantiate[:maximum_queue_size]
assert_equal worker_priorities, locker_instantiate[:worker_priorities]
end
def assert_locker_started(
worker_priorities: [10, 30, 50, nil, nil, nil]
)
locker_starts = internal_messages(event: 'locker_start')
assert_equal 1, locker_starts.length
locker_start = locker_starts.first
assert_equal worker_priorities, locker_start[:worker_priorities]
assert_equal @que_locker[:pid], locker_start[:backend_pid]
end
it "that can shut down gracefully" do
assert_successful_invocation "./#{filename}"
assert_locker_started
end
["-w", "--worker-count"].each do |command|
it "with #{command} to configure the worker count" do
assert_successful_invocation "./#{filename} #{command} 10"
assert_locker_instantiated
assert_locker_started(
worker_priorities: [10, 30, 50, nil, nil, nil, nil, nil, nil, nil],
)
end
end
["-i", "--poll-interval"].each do |command|
it "with #{command} to configure the poll interval" do
assert_successful_invocation "./#{filename} #{command} 10"
assert_locker_instantiated(poll_interval: 10)
assert_locker_started
end
end
it "with --wait-period to configure the wait period" do
assert_successful_invocation "./#{filename} --wait-period 200"
assert_locker_instantiated(
wait_period: 200,
)
end
["-q", "--queue-name"].each do |command|
it "with #{command} to configure the queue being worked" do
assert_successful_invocation "./#{filename} #{command} my_queue", queue_name: 'my_queue'
assert_locker_instantiated(
queues: {my_queue: 5}
)
end
end
it "should support using multiple arguments to specify multiple queues" do
queues = ['queue_1', 'queue_2', 'queue_3', 'queue_4']
assert_successful_invocation \
"./#{filename} -q queue_1 --queue-name queue_2 -q queue_3 --queue-name queue_4",
queue_name: queues.sample # Shouldn't matter.
assert_locker_instantiated(
queues: {queue_1: 5, queue_2: 5, queue_3: 5, queue_4: 5}
)
end
it "should support specifying poll intervals for individual queues" do
assert_successful_invocation \
"./#{filename} --poll-interval 4 -q queue_1=6 --queue-name queue_2 -q queue_3 --queue-name queue_4=7",
queue_name: 'queue_3'
assert_locker_instantiated(
queues: {queue_1: 6, queue_2: 4, queue_3: 4, queue_4: 7},
poll_interval: 4,
)
poller_instantiations = internal_messages(event: 'poller_instantiate')
assert_equal(
[["queue_1", 6.0], ["queue_2", 4.0], ["queue_3", 4.0], ["queue_4", 7.0]],
poller_instantiations.map{|p| p.values_at(:queue, :poll_interval)}
)
end
it "with a configurable local queue size" do
assert_successful_invocation \
"./#{filename} --minimum-queue-size 8 --maximum-queue-size 20"
assert_locker_instantiated(
minimum_queue_size: 8,
maximum_queue_size: 20,
)
end
it "should raise an error if the minimum_queue_size is above the maximum_queue_size" do
code = execute("./#{filename} --minimum-queue-size 10")
assert_equal 1, code
assert_equal 1, output.messages.length
assert_equal \
"minimum queue size (10) is greater than the maximum queue size (8)!",
output.messages.first.to_s
end
it "with a configurable log level" do
assert_successful_invocation("./#{filename} --log-level=warn") do
logger = Que.logger
assert_instance_of Logger, logger
assert_equal logger.level, Logger::WARN
end
end
it "when passing a nonexistent log level should raise an error" do
code = execute("./#{filename} --log-level=warning")
assert_equal 1, code
assert_equal 1, output.messages.length
assert_equal \
"Unsupported logging level: warning (try debug, info, warn, error, or fatal)",
output.messages.first.to_s
end
describe "--connection-url" do
it "should specify a database url for the locker" do
assert_successful_invocation("./#{filename} --connection-url #{QUE_URL}") do
refute_includes DEFAULT_QUE_POOL.instance_variable_get(:@checked_out), @que_locker[:pid]
end
end
it "when omitted should use a connection from the connection pool" do
assert_successful_invocation("./#{filename}") do
assert_includes DEFAULT_QUE_POOL.instance_variable_get(:@checked_out), @que_locker[:pid]
end
end
end
it "when passing --log-internals should output Que's internal logs" do
Que.internal_logger = nil
assert_successful_invocation("./#{filename} --log-internals --log-level=warn") do
logger = Que.logger
assert_instance_of Logger, logger
assert_equal logger.level, Logger::WARN
assert_equal logger.object_id, Que.internal_logger.object_id
end
end
it "when passing --worker-priorities to specify worker priorities" do
assert_successful_invocation("./#{filename} --worker-priorities 10,15,20,25")
assert_locker_started(
worker_priorities: [10, 15, 20, 25, nil, nil],
)
end
end
end
Try to report better when a CLI spec hangs.
# frozen_string_literal: true
require 'spec_helper'
require_relative 'command_line_interface'
describe Que::CommandLineInterface do
LOADED_FILES = {}
around do |&block|
super() do
# Let the CLI set the logger if it needs to.
Que.logger = nil
block.call
$stop_que_executable = nil
LOADED_FILES.clear
written_files.each { |name| File.delete("#{name}.rb") }
end
end
let(:written_files) { [] }
let :output do
o = Object.new
def o.puts(arg)
messages << arg
end
def o.messages
@messages ||= []
end
o
end
def assert_successful_invocation(
command,
queue_name: 'default',
default_require_file: Que::CommandLineInterface::RAILS_ENVIRONMENT_FILE
)
BlockJob.enqueue(queue: queue_name)
thread =
Thread.new do
execute(
command,
default_require_file: default_require_file,
)
end
unless sleep_until { !$q1.empty? }
puts "CLI invocation thread hung!"
thread.join
end
$q1.pop
@que_locker = DB[:que_lockers].first
yield if block_given?
$stop_que_executable = true
$q2.push nil
assert_equal 0, thread.value
ensure
unless thread.status == false
puts "CLI invocation thread status: #{thread.status.inspect}"
puts thread.backtrace
end
end
def execute(
text,
default_require_file: Que::CommandLineInterface::RAILS_ENVIRONMENT_FILE
)
Que::CommandLineInterface.parse(
args: text.split(/\s/),
output: output,
default_require_file: default_require_file,
)
end
def write_file
# On CircleCI we run the spec suite in parallel, and writing/deleting the
# same files will result in spec failures. So instead just generate a new
# file name for each spec to write/delete.
name = "spec/temp/file_#{Digest::MD5.hexdigest(rand.to_s)}"
written_files << name
File.open("#{name}.rb", 'w') { |f| f.puts %(LOADED_FILES["#{name}"] = true) }
name
end
["-h", "--help"].each do |command|
it "when invoked with #{command} should print help text" do
code = execute(command)
assert_equal 0, code
assert_equal 1, output.messages.length
assert_match %r(usage: que \[options\] \[file/to/require\]), output.messages.first.to_s
end
end
["-v", "--version"].each do |command|
it "when invoked with #{command} should print the version" do
code = execute(command)
assert_equal 0, code
assert_equal 1, output.messages.length
assert_equal "Que version #{Que::VERSION}", output.messages.first.to_s
end
end
describe "when requiring files" do
it "should infer the default require file if it exists" do
filename = write_file
assert_successful_invocation "", default_require_file: "./#{filename}.rb"
assert_equal(
{filename => true},
LOADED_FILES
)
end
it "should output an error message if no files are specified and the rails config file doesn't exist" do
code = execute("")
assert_equal 1, code
assert_equal 1, output.messages.length
assert_equal <<-MSG, output.messages.first.to_s
You didn't include any Ruby files to require!
Que needs to be able to load your application before it can process jobs.
(Or use `que -h` for a list of options)
MSG
end
it "should be able to require multiple files" do
files = 2.times.map { write_file }
assert_successful_invocation "./#{files[0]} ./#{files[1]}"
assert_equal(
[
"",
"Finishing Que's current jobs before exiting...",
"Que's jobs finished, exiting...",
],
output.messages,
)
assert_equal(
{
files[0] => true,
files[1] => true,
},
LOADED_FILES,
)
end
it "should raise an error if any of the files don't exist" do
name = write_file
code = execute "./#{name} ./nonexistent_file"
assert_equal 1, code
assert_equal ["Could not load file './nonexistent_file'"], output.messages
assert_equal(
{name => true},
LOADED_FILES
)
end
end
describe "should start up a locker" do
let(:filename) { write_file }
before { filename }
after do
assert_equal(
{filename => true},
LOADED_FILES
)
end
def assert_locker_instantiated(
worker_priorities: [10, 30, 50],
poll_interval: 5,
wait_period: 50,
queues: ['default'],
minimum_queue_size: 2,
maximum_queue_size: 8
)
locker_instantiates = internal_messages(event: 'locker_instantiate')
assert_equal 1, locker_instantiates.length
locker_instantiate = locker_instantiates.first
assert_equal true, locker_instantiate[:listen]
assert_equal true, locker_instantiate[:poll]
assert_equal queues, locker_instantiate[:queues]
assert_equal poll_interval, locker_instantiate[:poll_interval]
assert_equal wait_period, locker_instantiate[:wait_period]
assert_equal minimum_queue_size, locker_instantiate[:minimum_queue_size]
assert_equal maximum_queue_size, locker_instantiate[:maximum_queue_size]
assert_equal worker_priorities, locker_instantiate[:worker_priorities]
end
def assert_locker_started(
worker_priorities: [10, 30, 50, nil, nil, nil]
)
locker_starts = internal_messages(event: 'locker_start')
assert_equal 1, locker_starts.length
locker_start = locker_starts.first
assert_equal worker_priorities, locker_start[:worker_priorities]
assert_equal @que_locker[:pid], locker_start[:backend_pid]
end
it "that can shut down gracefully" do
assert_successful_invocation "./#{filename}"
assert_locker_started
end
["-w", "--worker-count"].each do |command|
it "with #{command} to configure the worker count" do
assert_successful_invocation "./#{filename} #{command} 10"
assert_locker_instantiated
assert_locker_started(
worker_priorities: [10, 30, 50, nil, nil, nil, nil, nil, nil, nil],
)
end
end
["-i", "--poll-interval"].each do |command|
it "with #{command} to configure the poll interval" do
assert_successful_invocation "./#{filename} #{command} 10"
assert_locker_instantiated(poll_interval: 10)
assert_locker_started
end
end
it "with --wait-period to configure the wait period" do
assert_successful_invocation "./#{filename} --wait-period 200"
assert_locker_instantiated(
wait_period: 200,
)
end
["-q", "--queue-name"].each do |command|
it "with #{command} to configure the queue being worked" do
assert_successful_invocation "./#{filename} #{command} my_queue", queue_name: 'my_queue'
assert_locker_instantiated(
queues: {my_queue: 5}
)
end
end
it "should support using multiple arguments to specify multiple queues" do
queues = ['queue_1', 'queue_2', 'queue_3', 'queue_4']
assert_successful_invocation \
"./#{filename} -q queue_1 --queue-name queue_2 -q queue_3 --queue-name queue_4",
queue_name: queues.sample # Shouldn't matter.
assert_locker_instantiated(
queues: {queue_1: 5, queue_2: 5, queue_3: 5, queue_4: 5}
)
end
it "should support specifying poll intervals for individual queues" do
assert_successful_invocation \
"./#{filename} --poll-interval 4 -q queue_1=6 --queue-name queue_2 -q queue_3 --queue-name queue_4=7",
queue_name: 'queue_3'
assert_locker_instantiated(
queues: {queue_1: 6, queue_2: 4, queue_3: 4, queue_4: 7},
poll_interval: 4,
)
poller_instantiations = internal_messages(event: 'poller_instantiate')
assert_equal(
[["queue_1", 6.0], ["queue_2", 4.0], ["queue_3", 4.0], ["queue_4", 7.0]],
poller_instantiations.map{|p| p.values_at(:queue, :poll_interval)}
)
end
it "with a configurable local queue size" do
assert_successful_invocation \
"./#{filename} --minimum-queue-size 8 --maximum-queue-size 20"
assert_locker_instantiated(
minimum_queue_size: 8,
maximum_queue_size: 20,
)
end
it "should raise an error if the minimum_queue_size is above the maximum_queue_size" do
code = execute("./#{filename} --minimum-queue-size 10")
assert_equal 1, code
assert_equal 1, output.messages.length
assert_equal \
"minimum queue size (10) is greater than the maximum queue size (8)!",
output.messages.first.to_s
end
it "with a configurable log level" do
assert_successful_invocation("./#{filename} --log-level=warn") do
logger = Que.logger
assert_instance_of Logger, logger
assert_equal logger.level, Logger::WARN
end
end
it "when passing a nonexistent log level should raise an error" do
code = execute("./#{filename} --log-level=warning")
assert_equal 1, code
assert_equal 1, output.messages.length
assert_equal \
"Unsupported logging level: warning (try debug, info, warn, error, or fatal)",
output.messages.first.to_s
end
describe "--connection-url" do
it "should specify a database url for the locker" do
assert_successful_invocation("./#{filename} --connection-url #{QUE_URL}") do
refute_includes DEFAULT_QUE_POOL.instance_variable_get(:@checked_out), @que_locker[:pid]
end
end
it "when omitted should use a connection from the connection pool" do
assert_successful_invocation("./#{filename}") do
assert_includes DEFAULT_QUE_POOL.instance_variable_get(:@checked_out), @que_locker[:pid]
end
end
end
it "when passing --log-internals should output Que's internal logs" do
Que.internal_logger = nil
assert_successful_invocation("./#{filename} --log-internals --log-level=warn") do
logger = Que.logger
assert_instance_of Logger, logger
assert_equal logger.level, Logger::WARN
assert_equal logger.object_id, Que.internal_logger.object_id
end
end
it "when passing --worker-priorities to specify worker priorities" do
assert_successful_invocation("./#{filename} --worker-priorities 10,15,20,25")
assert_locker_started(
worker_priorities: [10, 15, 20, 25, nil, nil],
)
end
end
end
|
Pod::Spec.new do |s|
s.name = "PPpdf417"
s.version = "4.1.1"
s.summary = "A delightful component for barcode scanning"
s.homepage = "http://pdf417.mobi"
s.description = <<-DESC
PDF417.mobi SDK is a delightful component for quick and easy scanning of PDF417, and many other types of 1D and 2D barcodes.
The SDK offers:
- world leading technology for scanning **PDF417 barcodes**
- fast, accurate and robust scanning for all other barcode formats
- integrated camera management
- layered API, allowing everything from simple integration to complex UX customizations.
- lightweight and no internet connection required
- enteprise-level security standards
- data parsing from **US Drivers licenses**
DESC
s.screenshots = [
"http://a2.mzstatic.com/us/r1000/041/Purple6/v4/72/86/bd/7286bde4-911d-0561-4934-7e7fbb5d2033/mzl.zajzkcwv.320x480-75.jpg",
"http://a4.mzstatic.com/us/r1000/010/Purple4/v4/a7/0f/90/a70f90ae-8c70-4709-9292-9ce0299fd712/mzl.jjhpudai.320x480-75.jpg",
"http://a4.mzstatic.com/us/r1000/055/Purple6/v4/f1/ce/f5/f1cef57c-ad99-886a-f3b8-643428136ef7/mzl.mjottsci.320x480-75.jpg"
]
s.license = {
:type => 'commercial',
:text => <<-LICENSE
© 2013-2015 MicroBlink Ltd. All rights reserved.
For full license text, visit http://pdf417.mobi/doc/PDF417license.pdf
LICENSE
}
s.authors = {
"MicroBlink" => "info@microblink.com",
"Jurica Cerovec" => "jurica.cerovec@microblink.com"
}
s.source = {
:git => 'https://github.com/PDF417/pdf417-ios.git',
:tag => 'v4.1.1'
}
s.preserve_paths = 'MicroBlink.embeddedframework/*'
s.platform = :ios
# ――― MULTI-PLATFORM VALUES ――――――――――――――――――――――――――――――――――――――――――――――――― #
s.ios.deployment_target = '6.0.0'
s.ios.source_files = 'MicroBlink.embeddedframework/MicroBlink.framework/Versions/A/Headers/*.{h}'
s.ios.header_dir = 'MicroBlink'
s.ios.public_header_files = "MicroBlink.embeddedframework/MicroBlink.framework/Versions/A/Headers/*.h"
s.ios.resources = "MicroBlink.embeddedframework/MicroBlink.framework/Versions/A/Resources/*.{strings,wav,png}"
s.ios.requires_arc = false
s.ios.xcconfig = {
'FRAMEWORK_SEARCH_PATHS' => '"$(PODS_ROOT)/PPpdf417/MicroBlink.embeddedframework"'
}
s.ios.frameworks = 'MicroBlink', 'AVFoundation', 'AudioToolbox', 'CoreMedia'
s.ios.libraries = 'iconv', 'c++'
end
Fixed podspec for new Cocoapods version
Pod::Spec.new do |s|
s.name = "PPpdf417"
s.version = "4.1.1"
s.summary = "A delightful component for barcode scanning"
s.homepage = "http://pdf417.mobi"
s.description = <<-DESC
PDF417.mobi SDK is a delightful component for quick and easy scanning of PDF417, and many other types of 1D and 2D barcodes.
The SDK offers:
- world leading technology for scanning **PDF417 barcodes**
- fast, accurate and robust scanning for all other barcode formats
- integrated camera management
- layered API, allowing everything from simple integration to complex UX customizations.
- lightweight and no internet connection required
- enteprise-level security standards
- data parsing from **US Drivers licenses**
DESC
s.screenshots = [
"http://a2.mzstatic.com/us/r1000/041/Purple6/v4/72/86/bd/7286bde4-911d-0561-4934-7e7fbb5d2033/mzl.zajzkcwv.320x480-75.jpg",
"http://a4.mzstatic.com/us/r1000/010/Purple4/v4/a7/0f/90/a70f90ae-8c70-4709-9292-9ce0299fd712/mzl.jjhpudai.320x480-75.jpg",
"http://a4.mzstatic.com/us/r1000/055/Purple6/v4/f1/ce/f5/f1cef57c-ad99-886a-f3b8-643428136ef7/mzl.mjottsci.320x480-75.jpg"
]
s.license = {
:type => 'commercial',
:text => <<-LICENSE
© 2013-2015 MicroBlink Ltd. All rights reserved.
For full license text, visit http://pdf417.mobi/doc/PDF417license.pdf
LICENSE
}
s.authors = {
"MicroBlink" => "info@microblink.com",
"Jurica Cerovec" => "jurica.cerovec@microblink.com"
}
s.source = {
:git => 'https://github.com/PDF417/pdf417-ios.git',
:tag => 'v4.1.1'
}
s.preserve_paths = 'MicroBlink.embeddedframework/*'
s.platform = :ios
# ――― MULTI-PLATFORM VALUES ――――――――――――――――――――――――――――――――――――――――――――――――― #
s.ios.deployment_target = '6.0'
s.ios.source_files = 'MicroBlink.embeddedframework/MicroBlink.framework/Versions/A/Headers/*.{h}'
s.ios.header_dir = 'MicroBlink'
s.ios.public_header_files = "MicroBlink.embeddedframework/MicroBlink.framework/Versions/A/Headers/*.h"
s.ios.resources = "MicroBlink.embeddedframework/MicroBlink.framework/Versions/A/Resources/*.{strings,wav,png}"
s.ios.requires_arc = false
s.ios.xcconfig = {
'FRAMEWORK_SEARCH_PATHS' => '"$(PODS_ROOT)/PPpdf417/MicroBlink.embeddedframework"'
}
s.ios.frameworks = 'MicroBlink', 'AVFoundation', 'AudioToolbox', 'CoreMedia'
s.ios.libraries = 'iconv', 'c++'
end
|
require 'securerandom'
# Similar to https://en.wikipedia.org/wiki/Base58
# o) includes the digits zero and one.
# o) excludes the letter IO (India,Oscar) both lowercase and uppercase
class Base58
def self.string(size)
size.times.map{ letter }.join
end
def self.string?(s)
s.is_a?(String) && s.chars.all?{ |char| letter?(char) }
end
private_class_method
def self.letter
alphabet[index]
end
private_class_method
def self.index
SecureRandom.random_number(alphabet.size)
end
private_class_method
def self.letter?(char)
alphabet.include?(char)
end
private_class_method
def self.alphabet
@@ALPHABET
end
@@ALPHABET = %w{
0 1 2 3 4 5 6 7 8 9
A B C D E F G H J K L M N P Q R S T U V W X Y Z
a b c d e f g h j k l m n p q r s t u v w x y z
}.join
end
refactoring; to get rid of private class warnings
require 'securerandom'
# Similar to https://en.wikipedia.org/wiki/Base58
# o) includes the digits zero and one.
# o) excludes the letter IO (India,Oscar) both lowercase and uppercase
class Base58
def self.string(size)
size.times.map{ letter }.join
end
def self.string?(s)
s.is_a?(String) && s.chars.all?{ |char| letter?(char) }
end
private
def self.letter
alphabet[index]
end
def self.index
SecureRandom.random_number(alphabet.size)
end
def self.letter?(char)
alphabet.include?(char)
end
def self.alphabet
@@ALPHABET
end
@@ALPHABET = %w{
0 1 2 3 4 5 6 7 8 9
A B C D E F G H J K L M N P Q R S T U V W X Y Z
a b c d e f g h j k l m n p q r s t u v w x y z
}.join
end
|
#
# Author:: Seth Chisamore <schisamo@opscode.com>
# Cookbook Name:: chef_handler
# Provider:: default
#
# Copyright:: 2011, Opscode, Inc <legal@opscode.com>
#
# 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.
#
action :enable do
require @new_resource.source
klass = @new_resource.class_name.split('::').inject(Kernel) {|scope, const_name| scope.const_get(const_name)}
handler = klass.send(:new, *collect_args(@new_resource.arguments))
@new_resource.supports.each_key do |type|
# we have to re-enable the handler every chef run
# to ensure daemonized Chef always has the latest
# handler code. TODO: add a :reload action
Chef::Log.info("Enabling #{@new_resource} as a #{type} handler")
Chef::Config.send("#{type.to_s}_handlers").delete_if {|v| v.class.to_s.include? @new_resource.class_name}
Chef::Config.send("#{type.to_s}_handlers") << handler
new_resource.updated_by_last_action(true)
end
end
action :disable do
@new_resource.supports.each_key do |type|
if enabled?(type)
Chef::Log.info("Disabling #{@new_resource} as a #{type} handler")
Chef::Config.send("#{type.to_s}_handlers").delete_if {|v| v.class.to_s.include? @new_resource.class_name}
new_resource.updated_by_last_action(true)
end
end
end
def load_current_resource
@current_resource = Chef::Resource::ChefHandler.new(@new_resource.name)
@current_resource.class_name(@new_resource.class_name)
@current_resource.source(@new_resource.source)
@current_resource
end
private
def enabled?(type)
Chef::Config.send("#{type.to_s}_handlers").select do |handler|
handler.class.to_s.include? @new_resource.class_name
end.size >= 1
end
def collect_args(resource_args = [])
if resource_args.is_a? Array
resource_args
else
[resource_args]
end
end
[COOK-620] ensure handler code is reloaded during daemonized chef runs
#
# Author:: Seth Chisamore <schisamo@opscode.com>
# Cookbook Name:: chef_handler
# Provider:: default
#
# Copyright:: 2011, Opscode, Inc <legal@opscode.com>
#
# 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.
#
action :enable do
klass = @new_resource.class_name.split('::').inject(Kernel) {|scope, const_name| scope.const_get(const_name)}
# use load instead of require to ensure the handler file
# is reloaded into memory each chef run. fixes COOK-620
Object.send(:remove_const, klass) rescue Chef::Log.debug("#{klass} has not been loaded")
GC.start
file_name = @new_resource.source
file_name << ".rb" unless file_name =~ /.*\.rb$/
load file_name
handler = klass.send(:new, *collect_args(@new_resource.arguments))
@new_resource.supports.each do |type, enable|
unless enable
# we have to re-enable the handler every chef run
# to ensure daemonized Chef always has the latest
# handler code. TODO: add a :reload action
Chef::Log.info("Enabling #{@new_resource} as a #{type} handler")
Chef::Config.send("#{type.to_s}_handlers").delete_if {|v| v.class.to_s.include? @new_resource.class_name}
Chef::Config.send("#{type.to_s}_handlers") << handler
new_resource.updated_by_last_action(true)
end
end
end
action :disable do
@new_resource.supports.each_key do |type|
if enabled?(type)
Chef::Log.info("Disabling #{@new_resource} as a #{type} handler")
Chef::Config.send("#{type.to_s}_handlers").delete_if {|v| v.class.to_s.include? @new_resource.class_name}
new_resource.updated_by_last_action(true)
end
end
end
def load_current_resource
@current_resource = Chef::Resource::ChefHandler.new(@new_resource.name)
@current_resource.class_name(@new_resource.class_name)
@current_resource.source(@new_resource.source)
@current_resource
end
private
def enabled?(type)
Chef::Config.send("#{type.to_s}_handlers").select do |handler|
handler.class.to_s.include? @new_resource.class_name
end.size >= 1
end
def collect_args(resource_args = [])
if resource_args.is_a? Array
resource_args
else
[resource_args]
end
end
|
#!/usr/bin/env ruby
require 'net/http'
require 'json'
require 'cgi'
class ScreenshotUpdater
#Uses https://circleci.com/docs/api
CIRCLE_BASE_URI = 'https://circleci.com/api/v1/project/Factlink/factlink/'
def run
get_lastest_screenshot_uris.each do |screenshot_uri|
filename = local_screenshot_path + local_filename_from_uri(screenshot_uri)
system "curl -o #{filename} #{screenshot_uri}"
end
end
def local_filename_from_uri uri
File.basename(URI.parse(uri).path)
end
def local_screenshot_path
local_repo_path + '/core/spec/screenshots/screenshots/'
end
def local_repo_path
@local_repo_path ||= begin
File.dirname(__FILE__) + '/..'
end
end
def get_lastest_screenshot_uris
build_num = get_latest_build_num
screenshot_infos =
get_json(ci_artifacts_uri(build_num))
.select{|artifact| artifact['pretty_path'].match(/^\$CIRCLE_ARTIFACTS\/capybara_output\//)}
screenshot_infos
.map{|artifact| artifact['url']}
.select{|url| url.end_with?('.png') && ! url.end_with?('-diff.png')}
.map{|url| url + circle_token_query}
end
def get_latest_build_num
recent_builds = get_recent_builds
raise "No branch #{current_git_branch} found." unless recent_builds && recent_builds[0]
build_info = recent_builds[0]
raise "No recent build for branch #{current_git_branch}." unless build_info
build_info['build_num']
end
def get_recent_builds
get_json(ci_current_branch_builds_uri)
end
def ci_artifacts_uri(build_num)
URI.parse("#{CIRCLE_BASE_URI}#{build_num}/artifacts#{circle_token_query}")
end
def ci_current_branch_builds_uri
URI.parse("#{CIRCLE_BASE_URI}tree/#{CGI.escape(current_git_branch)}#{circle_token_query}")
end
def circle_token_query
"?circle-token=#{circle_token}"
end
def circle_token
@circle_token ||= begin
ENV['CIRCLE_CI_TOKEN'] or
fail '''
ENV variable CIRCLE_CI_TOKEN is missing.
You should create an api token @ https://circleci.com/account/api and
insert it in your `.bash_profile` for OS X, `.zshrc` for zsh, and `.bashrc` for non-mac bash.
For example:
export CIRCLE_CI_TOKEN="<your-40-char-hexadecimal-token>"
'''
end
end
def current_git_branch
`git symbolic-ref HEAD`.sub(/^refs\/heads\//,'').strip
end
# HTTP helpers:
def get_json(uri)
JSON.parse(make_http_request(uri, Net::HTTP::Get))
end
def make_http_request(uri, requestClass)
while true
request = requestClass.new uri
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
http.request request
end
if %w(301 302).include? response.code
uri = URI.parse(response['location'])
elsif response.code == '200'
break
else
raise "Failed to request #{uri}; response code #{response.code}"
end
end
response.body
end
end
ScreenshotUpdater.new.run
minor: whitespace
#!/usr/bin/env ruby
require 'net/http'
require 'json'
require 'cgi'
class ScreenshotUpdater
#Uses https://circleci.com/docs/api
CIRCLE_BASE_URI = 'https://circleci.com/api/v1/project/Factlink/factlink/'
def run
get_lastest_screenshot_uris.each do |screenshot_uri|
filename = local_screenshot_path + local_filename_from_uri(screenshot_uri)
system "curl -o #{filename} #{screenshot_uri}"
end
end
def local_filename_from_uri uri
File.basename(URI.parse(uri).path)
end
def local_screenshot_path
local_repo_path + '/core/spec/screenshots/screenshots/'
end
def local_repo_path
@local_repo_path ||= begin
File.dirname(__FILE__) + '/..'
end
end
def get_lastest_screenshot_uris
build_num = get_latest_build_num
screenshot_infos =
get_json(ci_artifacts_uri(build_num))
.select{|artifact| artifact['pretty_path'].match(/^\$CIRCLE_ARTIFACTS\/capybara_output\//)}
screenshot_infos
.map{|artifact| artifact['url']}
.select{|url| url.end_with?('.png') && !url.end_with?('-diff.png')}
.map{|url| url + circle_token_query}
end
def get_latest_build_num
recent_builds = get_recent_builds
raise "No branch #{current_git_branch} found." unless recent_builds && recent_builds[0]
build_info = recent_builds[0]
raise "No recent build for branch #{current_git_branch}." unless build_info
build_info['build_num']
end
def get_recent_builds
get_json(ci_current_branch_builds_uri)
end
def ci_artifacts_uri(build_num)
URI.parse("#{CIRCLE_BASE_URI}#{build_num}/artifacts#{circle_token_query}")
end
def ci_current_branch_builds_uri
URI.parse("#{CIRCLE_BASE_URI}tree/#{CGI.escape(current_git_branch)}#{circle_token_query}")
end
def circle_token_query
"?circle-token=#{circle_token}"
end
def circle_token
@circle_token ||= begin
ENV['CIRCLE_CI_TOKEN'] or
fail '''
ENV variable CIRCLE_CI_TOKEN is missing.
You should create an api token @ https://circleci.com/account/api and
insert it in your `.bash_profile` for OS X, `.zshrc` for zsh, and `.bashrc` for non-mac bash.
For example:
export CIRCLE_CI_TOKEN="<your-40-char-hexadecimal-token>"
'''
end
end
def current_git_branch
`git symbolic-ref HEAD`.sub(/^refs\/heads\//,'').strip
end
# HTTP helpers:
def get_json(uri)
JSON.parse(make_http_request(uri, Net::HTTP::Get))
end
def make_http_request(uri, requestClass)
while true
request = requestClass.new uri
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
http.request request
end
if %w(301 302).include? response.code
uri = URI.parse(response['location'])
elsif response.code == '200'
break
else
raise "Failed to request #{uri}; response code #{response.code}"
end
end
response.body
end
end
ScreenshotUpdater.new.run
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.