In a cookbook I have the following in my attributes/default.rb:
default.ark.packages = [
{
'name' => 'optipng',
'url' => 'http://squirrelyjim.cloudfront.net/heroes/optipng-0.7.5.tar.gz',
'version' => '0.7.5'
},
{
'name' => 'imagemagick',
'url' => 'http://squirrelyjim.cloudfront.net/heroes/ImageMagick-6.9.0-4.tar.gz',
'version' => '6.9.0-4'
},
{
'name' => 'jpegoptim',
'url' => 'http://squirrelyjim.cloudfront.net/heroes/jpegoptim-1.4.1.tar.gz',
'version' => '1.4.1'
}
]
I then call those values using the ark resource as follows:
node.ark.packages.each do |pkg|
ark pkg['name'] do
url pkg['url']
version pkg['version']
action :install_with_make
notifies :run, "execute[ldconfig]", :immediately
end
end
This works great but I would like to somehow get the version to automatically get called at the end of the url, instead of typing it out twice. Is there a way to get a value in a hash updated with another value from the same hash, similar to:
http://squirrelyjim.cloudfront.net/heroes/optipng-#{version}.tar.gz
Dynamically build the URL inside the loop:
node.ark.packages.each do |pkg|
url = "http://squirrelyjim.cloudfront.net/heroes/#{pkg['name']}-#{pkg['version']}.tar.gz"
ark pkg['name'] do
url url
version pkg['version']
action :install_with_make
notifies :run, "execute[ldconfig]", :immediately
end
end
Related
I read previous possible questions that may have the answer but that not what I asked for.
First of all I am start to use test. However I already successful setup Omniauth-facebook for my App but still like to go back and test.
-sessions_controller.rb
class SessionsController < ApplicationController
def new
#title= 'Sign In'
end
def create
auth = request.env["omniauth.auth"]
user = User.from_omniauth(auth)
session[:user_id] = user.id
if params.permit[:remember_me]
cookies.permanent[:auth_token] = user.auth_token
else
cookies[:auth_token] = user.auth_token
end
refresh_to root_path, :ma_notice => "Logged in"
rescue
redirect_to root_path, :alert=> "Authentication failed, please try again."
end
def destroy
#session[:user_id] = nil
cookies.delete(:auth_token)
refresh_to root_path, :ma_notice => "Logged Out"
end
def failure
ma_log "Authentication failed, please try again."
redirect_to root_path, :alert=> "Authentication failed, please try again."
end
end
-app/models/user.rb
class User
....
....
def self.from_omniauth(auth)
where(auth.slice(:uid, :provider, :email)).first_or_create do |user|
case auth.provider
when 'identity'
identity = Identity.find auth.uid
user.code = identity.code
user.email = identity.email
else
user.email = auth.info.email
user.uid = auth.uid
user.provider = auth.provider
user.code = auth.info.name
user.role = "M"
end
end
end
def send_password_reset
generate_token(:password_reset_token)
self.password_reset_sent_at = Time.zone.now
save!
UserMailer.password_reset(self).deliver
end
So what I did
Test routes (Its seem simple but sometime I might forgot because I changing from dynamic route to fixed route as required in rails 5.2)
-test/integration/authen_test.rb
require 'test_helper'
class RoutesTest < ActionController::TestCase
test 'facebook login' do
assert_routing '/auth/facebook/callback', {controller: 'sessions', action: 'create',provider: 'facebook'}
end
test 'facebook login post' do
assert_routing({path: '/auth/facebook/callback', method: 'post'},{controller: 'sessions', action: 'create' ,provider: 'facebook'})
end
end
I want to test if facebook accept login and return call back.
-test/models/user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "Facebook validation" do
auth = {provider: :facebook, FACEBOOK_API: "111111111111111", FACEBOOK_KEY: "11111111111111111111111111111111"}
user = User.from_omniauth(auth)
puts user
assert_not nil
end
end
Problem: It's always green even change FACEBOOK_API. I found the user from puts as well. It's seem like user.from _omniauth already gone to facebook and get info using FACEBOOK_API from .env not one I provided. Then how I can test if it really connected with facebook.
The same with this related test. It's always green in any FACEBOOI_API. That won't work as well.
View Test. I like to test if no facebook login the system or not. The login would display accordingly. Still have no idea as stuck with Q.2 perhap someone could share how you do the test.
To Setup Integration Testing-Omniauth as documented
You can turn on "test mode" for OmniAuth like so:
OmniAuth.config.test_mode = true Once you have enabled test mode, all
requests to OmniAuth will be short circuited to use the mock
authentication hash as described below. A request to /auth/provider
will redirect immediately to /auth/provider/callback.
Then said
OmniAuth.config.add_mock(:twitter, {:uid => '12345'})
OK but where to put that code to turn on
so I assumed the only one is
-config/initializer/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :identity,
:fields => [:code, :email],
:on_failed_registration=> lambda { |env|
IdentitiesController.action(:new).call(env)
}
provider :facebook, ENV['FACEBOOK_API'], ENV['FACEBOOK_KEY']
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:facebook] = :invalid_credentials
end
Here I used test from related question but used my method :create.
It didn't do anything than green, even changed .test_mode = false
-test/integration/sessions_controller_test.rb
require 'test_helper'
class SessionsControllerTest < ActionController::TestCase
test '#signup_success' do
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new({
'provider' => 'facebook',
'uid' => '123451234512345',
'info' => {'email' => 'testuser#testmail.com', 'name' => 'test', 'image' => ''}
})
request.env['omniauth.env'] = OmniAuth.config.mock_auth[:facebook]
get :create
end
end
You can use omniauth test helpers. Here is the link:
https://github.com/omniauth/omniauth/wiki/Integration-Testing
Setup Mock Auth:
OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new({
:provider => 'facebook',
:uid => '123545'
# etc.
})
What i did and what worked for me was setting up mocks in my spec_helper file for various scenarios.
OmniAuth.config.test_mode = true
omniauth_hash = { 'provider' => 'twitter',
'uid' => '12345',
'info' => {
'name' => 'test',
'email' => 'test#test.com',
'nickname' => 'testnick'
},
'extra' => {
'raw_info' =>
{
'location' => 'Coralvilleo'
}
}
}
omniauth_hash_fb = { 'provider' => 'facebook',
'uid' => '12345',
'info' => {
'name' => 'test',
'email' => 'test#testsomething.com'
},
'extra' => {'raw_info' =>
{ 'location' => 'Chicago'
}
}
}
omniauth_hash_fail = { 'provider' => 'facebook',
'uid' => '12345',
'info' => {
},
'extra' => {'raw_info' =>
{ 'location' => 'Chicago'
}
}
}
omniauth_hash_fail_2 = { 'provider' => 'facebook',
'uid' => '12345',
'info' => {
},
'extra' => {'raw_info' =>
{ 'location' => 'Chicago'
}
}
}
omniauth_hash_fail_complete = { 'provider' => 'twitter'}
OmniAuth.config.add_mock(:twitter, omniauth_hash)
OmniAuth.config.add_mock(:facebook, omniauth_hash_fb)
OmniAuth.config.add_mock(:facebook_fail, omniauth_hash_fail)
OmniAuth.config.add_mock(:twitter_fail, omniauth_hash_fail_2)
Then using these methods in my rspec tests for controller like so.
it 'should successfully create a user with twitter' do
request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:twitter]
expect {
post :twitter, provider: :twitter
}.to change{ User.count }.by(1)
end
it 'should redirect the user to the root url with twitter' do
request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:twitter]
post :twitter, provider: :twitter
response.should redirect_to root_path
end
name of the mocks to be specified and linked to what we specified in the helper.
OmniAuth.config.mock_auth[name of the mock you specified in spec helper].
I need to define a factory for a database table which contains column named 'method'.
I've tried something like this:
FactoryGirl.define do
factory :notification_baby_offset, class:'NotificationTemplate' do
...
method {{ 'email' => false, 'notification' => true }}
...
end
end
But, when I tried to build it, I got an error saying:
`method': wrong number of arguments (0 for 1) (ArgumentError)
It appears to identify 'method' as a function rather than a database column. I tried to emphasize this by :method or "method", but that didn't work.
So, I have to build this factory like this for it to work:
FactoryGirl.create(:notification_baby_offset, method: { 'email' => false, 'notification' => true })
Is where a way to avoid this hack and define this column properly in a factory?
Try this:
FactoryGirl.define do
factory :notification_baby_offset, class:'NotificationTemplate' do
...
after(:build) do |notification|
notification.method = { 'email' => false, 'notification' => true }
end
...
end
end
Or even (if your new supports passing attributes):
FactoryGirl.define do
factory :notification_baby_offset, class:'NotificationTemplate' do
...
initialize_with { new(method: { 'email' => false, 'notification' => true }) }
...
end
end
I'm trying to write test for my costume routes, along with non existing routes.
For the examples down here I have two problems:
It matches the actions that don't exist on my controller, so it doesn't really match to see if my controller have those actions, it just matches the syntax
the should_not be_routable doesn't work, which kind of goes back to the above problem of it doesn't check against my controller or the routes.rb file to see if the route should exist.
This one passes and is all good:
it "should route to method1" do
{ :get => '/my_controller/method1' }.should route_to(:controller => 'my_controller',
:action => 'method1')
end
this one fails, so it doesn't even check to see if I have a method zz defined in my controller or routes file.
it "should not route to zz" do
{ :get => '/my_controller/zz' }.should_not be_routable
end
the error I get is:
MyController routing zz should route to rescan
Failure/Error: { :get => '/my_controller/zz' }.should_not be_routable
expected {:get=>"/client_rescan/zz"} not to be routable, but it routes to {:controller=>"my_controller", :action=>"zz"}
So it obviously doesn't look at my routes file at all...
This is another example of it doesn't look at my routes file, in my routes I have ' resources :client_rescan, :only => [:index] ' and when I do rake routes it doesn't show delete as expected, but the test doesn't look at those:
it "should not have route to delete" do
{ :delete => '/my_controller/1'}.should_not be_routable
end
The Failure I get is the following. Which looks like it doesn't even see the delete function:
Failure/Error: { :delete => '/my_controller/1'}.should_not be_routable
expected {:delete=>"/my_controller/1"} not to be routable, but it routes to {:controller=>"my_controller", :action=>"1"}
Another problem is my post routes to index in the test:
it "should not have route to post" do
{ :post => '/my_controller' }.should_not be_routable
end
The Failure I get is:
Failure/Error: { :post => '/my_controller' }.should_not be_routable
expected {:post=>"/my_controller"} not to be routable, but it routes to {:controller=>"my_controller", :action=>"index"}
this is content of my routes.rb file
require 'resque/server'
require 'resque_scheduler'
Cdc::Application.routes.draw do
mount Resque::Server.new, :at => 'resque'
Resque.schedule = YAML.load_file(File.join(File.dirname(__FILE__), 'resque_schedule.yml')) # load the schedule
devise_for :users, :controllers => { :sessions => "sessions", :registrations => "registrations" }
[:assessments, :security_assessments, :privacy_assessments].each do |assessment_type|
resources assessment_type, :controller => :assessments do
resources :rsz do
post 'review', :on => :member
get 'judgement', :on => :member
end
get :judgement, :on => :member
resources :samples do
get 'download', :on => :member
end
resources :asm_reviews do
post :request_review, :on => :collection
end
end
end
resources :account_creator
match "/images/captcha/*file_name" => "captcha#show"
## this is where my route is!! :)
resources :my_controller, :only => [:index] do
collection do
get :rescan
get :cancel
end
end
match "alert_queue/words" => "alert_queue#words"
resources :alert_queue
match "calls_to_action/start/:id" => "calls_to_action#start", :id => /\d+/
match "calls_to_action/close/:id" => "calls_to_action#close", :id => /\d+/
match "calls_to_action/comment/:id" => "calls_to_action#comment", :id => /\d+/
match "calls_to_action/multiclose" => "calls_to_action#multiclose"
match "calls_to_action/multiscan" => "calls_to_action#multiscan"
match "application_instances/multiclose" => "application_instances#multiclose"
match "application_instances/multiscan" => "application_instances#multiscan"
resources :code_categories do
resources :code_families do
resources :code_family_versions
end
end
resources :code_policy_items
resources :application_instances do
collection do
post :resque_statuses
end
resources :code_indices
resources :application_analysis
get "smali/:smali_path", :as => :smali, :on => :member, :action => :smali, :smali_path => /.*/
member do
get :file
get :strings
get :dump
get :alerts
get :correlations
get :signers
get :icon
get :resque_status
get :assets
get :new_code_index
get :class_list
get :heuristic_hits
get :engine_artifacts
post :rescan
post :attach_artifact
post :engine_artifact, :action => :attach_engine_artifact
resources :alerts
end
post "multiscan", :on => :collection, :action => :multiscan
post "multiclose", :on => :collection, :action=> :multiclose
post "engines/:engine_name/:engine_version/assertions/:cookie",
:on => :member, :action => :register_assertion_set, :as => :register_assertion_set,
:engine_name => /[^\/]+/, :engine_version => /[^\/]+/, :cookie => /[^\/]+/
post "engines/:engine_name/:engine_version/network_data",
:on => :member, :action => :register_network_data, :as => :register_network_data,
:engine_name => /[^\/]+/, :engine_version => /[^\/]+/
post "assets", :on => :member, :action => :register_asset_set, :as => :register_asset_set
end
# index gets the list of families, show gets the assertion types for that family
resources :assertion_families
resources :artifacts
resources :dashboard do
collection do
get :last_app_instance
end
end
match '/direct_downloads/' => 'direct_downloads#index'
root :to => "stats#index"
match '/' => 'stats#index'
match 'explorer/query/:format' => 'explorer#query'
match '/:controller(/:action(/:id))'
end
The problem is this line of routes.rb:
match '/:controller(/:action(/:id))'
This is a catch all route, and will match for example /abc/xyz to controller abc, and action xyz.
It's best really not to use catch all routes, in favour of exposing only the functionality you want.
I'm using Typhoeus to post a hash to my API url. It's actually an array containing a set of hashes. Here's effectively what I'm doing:
companies = Array.new
company = { 'name' => 'Company 1' , 'company_url' => 'http://company.com' }
companies.push(company)
company2 = {'name' => 'Company 2' , 'company_url' => 'http://company2.com' }
companies.push(company2)
request = Typhoeus::Request.post("http://myapi.com/1.0/startups/create_batch",
:username => 'user',
:password => 'password',
:auth_method => :basic,
:params => {'companies' => companies} )
print "Create_batch response "+request.body
Once I run the script I get the output which states "Create_batch response Disallowed Key Characters.". I'm not sure what it's referencing at this point. I've looked over the text output of what print companies shows up but I don't see any strange code.
Anybody have any insights on what I should do?
Can I somehow use this
settings = {
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
in a external file as settings?
How can I include this into my script?
The most common way to store configuration data in Ruby is to use YAML:
settings.yml
user1:
path: /
days: 5
user2:
path: /tmp/
days: 3
Then load it in your code like this:
require 'yaml'
settings = YAML::load_file "settings.yml"
puts settings.inspect
You can create the YAML file using to_yaml:
File.open("settings.yml", "w") do |file|
file.write settings.to_yaml
end
That said, you can include straight Ruby code also, using load:
load "settings.rb"
However, you can't access local variables outside the file, so you would have to change your code to use an instance variable or a global variable:
settings.rb
SETTINGS = {
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
#settings = { 'foo' => 1, 'bar' => 2 }
Then load it thus:
load "settings.rb"
puts SETTINGS.inspect
puts #settings.inspect
you can also use Marshal
settings = {
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
data=Marshal.dump(settings)
open('output', 'wb') { |f| f.puts data }
data=File.read("output")
p Marshal.load(data)
A really simple one is to use eval.
config.txt
{
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
program.rb
configuration = eval(File.read("./config.txt"))
puts configuration['user1']