RCov doesn't work - ruby

I am currently developing a Ruby gem and want to create metrics.
I am using 'metric_fu', but RCov seems to leave my specs.
Here is my metric_fu configuration:
MetricFu::Configuration.run do |config|
config.metrics = [:churn, :saikuro, :flog, :flay, :reek, :roodi, :rcov]
config.graphs = [:flog, :flay, :reek, :roodi, :rcov]
config.flay = { :dirs_to_flay => ['lib'] }
config.flog = { :dirs_to_flog => ['lib'] }
config.reek = { :dirs_to_reek => ['lib'] }
config.roodi = { :dirs_to_roodi => ['lib'] }
config.saikuro = { :output_directory => 'scratch_directory/saikuro',
:input_directory => ['lib'],
:cyclo => "",
:filter_cyclo => "0",
:warn_cyclo => "5",
:error_cyclo => "7",
:formater => "text"} #this needs to be set to "text"
config.churn = { :start_date => "1 year ago", :minimum_churn_count => 10}
config.rcov = { :test_files => ["spec/**/*_spec.rb"],
:rcov_opts => ["--sort coverage",
"--no-html",
"--text-coverage",
"--no-color",
"--profile",
"--spec-only",
"--exclude /gems/,/Library/,spec"]}
end
Do you have some tips?
Best regards

Well this is going to be hard to diagnose without a stack trace but I would suggest changing your config to this:
MetricFu::Configuration.run do |config|
config.metrics = [:rcov]
config.graphs = [:rcov]
config.rcov = { :test_files => ["spec/**/*_spec.rb"],
:rcov_opts => ["--sort coverage",
"--no-html",
"--text-coverage",
"--no-color",
"--profile",
"--spec-only",
"--exclude /gems/,/Library/,spec"]}
end
So you can isolate the problem. Then run 'rake metrics:all --trace' and if you can't figure it out from there, post the results either here or the metric_fu google group: http://groups.google.com/group/metric_fu
You can also try running rcov straight from the command line (which is essentially what metric_fu does).
Hope that helps.

Related

translation from XML to rest-client for POST request

The is the XML request via POST I have to make in order to receive a response:
<BackgroundCheck userId="username" password="password">
<BackgroundSearchPackage action="submit" type="demo product">
<ReferenceId>some_id_value</ReferenceId>
<PersonalData>
<PersonName>
<GivenName>John</GivenName>
<MiddleName>Q</MiddleName>
<FamilyName>Test</FamilyName>
</PersonName>
<Aliases>
<PersonName>
<GivenName>Jack</GivenName>
<MiddleName>Quigley</MiddleName>
<FamilyName>Example</FamilyName>
</PersonName>
</Aliases>
<DemographicDetail>
<GovernmentId issuingAuthority="SSN">123456789</GovernmentId>
<DateOfBirth>1973-12-25</DateOfBirth>
</DemographicDetail>
<PostalAddress>
<PostalCode>83201</PostalCode>
<Region>UT</Region>
<Municipality>Salt Lake City</Municipality>
<DeliveryAddress>
<AddressLine>1234</AddressLine>
<StreetName>Main Street</StreetName>
</DeliveryAddress>
</PostalAddress>
<EmailAddress>john#test.com</EmailAddress>
<Telephone>801-789-4229</Telephone>
</PersonalData>
</BackgroundCheck>
</BackgroundSearchPackage>
Using the examples on the rest-client github page I came up with the following translation using rest-client:
response = RestClient.post( 'url',
{
:BackgroundCheck => {
:userID => 'username',
:password => 'password',
},
:BackgroundSearchPackage => {
:action => 'submit',
:type => 'demo'
},
:ReferenceID => 'some_id_value',
:PersonalData => {
:PersonalName => {
:GivenName => 'John',
:MiddleName => 'Q',
:FamilyName => 'Test'
},
:Aliases => {
:GivenName => 'Jack',
:MiddleName => 'Quigly',
:FamilyName => 'Example'
}
},
:DemographicDetail => {
:GovernmentId => {
:issuingAuthority => "SSN"
}, ## where do I enter the SSN?
:DateOfBirth => '1972-12-25'
},
:PostalAddress => {
:PostalCode => '83201',
:Region => 'UT',
:Municipality => 'Salt Lake City',
:DeliveryAddress => {
:AddressLine => '1234',
:StreetName => 'Main Street'
}
},
:EmailAddress => 'john#test.com',
:Telephone => '801-789-4229'
})
Its my first time with XML and the rest-client gem.
My question is did I translate the XML correctly in the POST request?
More specifically how do I handle the GovernmentID and referencing the SSN entry?
First of all, the XML you've provided isn't valid! Your root element starts with BackgroundCheck and ends with BackgroundSearchPackage:
<BackgroundCheck userId="username" password="password">
<BackgroundSearchPackage action="submit" type="demo product">
</BackgroundCheck>
</BackgroundSearchPackage>
In addition, your translation / transformation from XML to Ruby hash is incorrect. If BackgroundCheck is your root element and BackgroundSearchPackage is a child of it, your Ruby hash should look like this (rest-client accepts the string and the symbol notation):
my_xml_hash = {
"BackgroundCheck" => {
"userId"=>"username",
"password"=>"password",
"BackgroundSearchPackage" => {
"action"=>"submit",
"type"=>"demo product",
...
"PersonalData" => { ... },
...
}
}
}
You can access values in a Ruby hash like this:
# string syntax
my_xml_hash['BackgroundCheck']['BackgroundSearchPackage']['PersonalData']['DemographicDetail']['GovernmentId']
=> "123456789"
# symbol syntax
other_xml_hash[:BackgroundCheck][:BackgroundSearchPackage][:PersonalData][:DemographicDetail]['GovernmentId']
=> "123456789"
If I understood you correctly, you want to send XML via a POST request. But if you use the hash syntax, you will not achieve the result, what you probably want, because rest-client will post your data as parameters and not as XML data!
If you need to adjust only GovernmentID and issuingAuthority, I would do it as follows.
require 'rest_client'
# the customized 'GovernmentID'
government_id = '123'
# the customized 'issuingAuthority'
issuing_authority = 'FOO'
xml_template =<<END_OF_XML
<BackgroundCheck userId="username" password="password">
<BackgroundSearchPackage action="submit" type="demo product">
<ReferenceId>some_id_value</ReferenceId>
<PersonalData>
<PersonName>
<GivenName>John</GivenName>
<MiddleName>Q</MiddleName>
<FamilyName>Test</FamilyName>
</PersonName>
<Aliases>
<PersonName>
<GivenName>Jack</GivenName>
<MiddleName>Quigley</MiddleName>
<FamilyName>Example</FamilyName>
</PersonName>
</Aliases>
<DemographicDetail>
<GovernmentId issuingAuthority="#{issuing_authority}">#{government_id}</GovernmentId>
<DateOfBirth>1973-12-25</DateOfBirth>
</DemographicDetail>
<PostalAddress>
<PostalCode>83201</PostalCode>
<Region>UT</Region>
<Municipality>Salt Lake City</Municipality>
<DeliveryAddress>
<AddressLine>1234</AddressLine>
<StreetName>Main Street</StreetName>
</DeliveryAddress>
</PostalAddress>
<EmailAddress>john#test.com</EmailAddress>
<Telephone>801-789-4229</Telephone>
</PersonalData>
</BackgroundSearchPackage>
</BackgroundCheck>
END_OF_XML
# Go to http://requestb.in/ , click on "Create a RequestBin", copy the "Bin URL" and use it for your tests ;-)
response = RestClient.post('http://your.target.tld/your/webservice', xml_template, { content_type: :xml })
puts "Response: #{response.inspect}"
REXML example:
require 'rest_client'
require 'rexml/document'
xml_string =<<END_OF_XML
<BackgroundCheck userId="username" password="password">
<BackgroundSearchPackage action="submit" type="demo product">
<ReferenceId>some_id_value</ReferenceId>
<PersonalData>
<PersonName>
<GivenName>John</GivenName>
<MiddleName>Q</MiddleName>
<FamilyName>Test</FamilyName>
</PersonName>
<Aliases>
<PersonName>
<GivenName>Jack</GivenName>
<MiddleName>Quigley</MiddleName>
<FamilyName>Example</FamilyName>
</PersonName>
</Aliases>
<DemographicDetail>
<GovernmentId issuingAuthority="SSN">123456789</GovernmentId>
<DateOfBirth>1973-12-25</DateOfBirth>
</DemographicDetail>
<PostalAddress>
<PostalCode>83201</PostalCode>
<Region>UT</Region>
<Municipality>Salt Lake City</Municipality>
<DeliveryAddress>
<AddressLine>1234</AddressLine>
<StreetName>Main Street</StreetName>
</DeliveryAddress>
</PostalAddress>
<EmailAddress>john#test.com</EmailAddress>
<Telephone>801-789-4229</Telephone>
</PersonalData>
</BackgroundSearchPackage>
</BackgroundCheck>
END_OF_XML
# Build XML document from string
doc = REXML::Document.new(xml_string)
government_element = REXML::XPath.first(doc, "//GovernmentId")
# Read values:
puts government_element.text
puts government_element.attributes['issuingAuthority']
# OR directly via XPath
puts REXML::XPath.first(doc, "//GovernmentId").text
puts REXML::XPath.first(doc, "//GovernmentId/#issuingAuthority").value
# Write values:
government_element.text = 'my new text value'
government_element.attributes['issuingAuthority'] = 'my new attribute value'
# Go to http://requestb.in/ , click on "Create a RequestBin", copy the "Bin URL" and use it for your tests ;-)
response = RestClient.post('http://your.target.tld/your/webservice', doc.to_s, { content_type: :xml })
puts "Response: #{response.inspect}"
If you need to write complex XML trees, I recommend you to take a look at the following gems:
Nokogiri
LibXml Ruby
XmlSimple
REXML (Ruby built in)
Or use a templating engine like ERB, to simplify it.

adding allowDiskUse parameter to db.collection.aggregate() query using Mongoid

I recently updated mongodb from 2.4 to 2.6, and the new memory limit in aggregate() is causing my aggregation to fail with the following error:
Moped::Errors::OperationFailure: The operation: #<Moped::Protocol::Command
#length=251
#request_id=6
#response_to=0
#op_code=2004
#flags=[:slave_ok]
#full_collection_name="items.$cmd"
#skip=0
#limit=-1
#selector={:aggregate=>"items", :pipeline=>[{"$group"=>{"_id"=>"$serial_number", "total"=>{"$sum"=>1}}}, {"$match"=>{"total"=>{"$gte"=>2}}}, {"$sort"=>{"total"=>-1}}, {"$limit"=>750000}]}
#fields=nil>
failed with error 16945: "exception: Exceeded memory limit for $group, but didn't allow external sort. Pass allowDiskUse:true to opt in."
So, I'm trying to pass allowDiskUse: true in the query:
dupes = Item.collection.aggregate([{
'$group' => {'_id' => "$serial_number", 'total' => { "$sum" => 1 } } },
{ '$match' => { 'total' => { '$gte' => 2 } } },
{ '$sort' => {'total' => -1}},
{ '$limit' => 750000 }],
{ 'allowDiskUse' => true })
But this isnt working.... no matter how I try I get this error:
Moped::Errors::OperationFailure: The operation: #<Moped::Protocol::Command
#length=274
#request_id=2
#response_to=0
#op_code=2004
#flags=[:slave_ok]
#full_collection_name="items.$cmd"
#skip=0
#limit=-1
#selector={:aggregate=>"items", :pipeline=>[{"$group"=>{"_id"=>"$serial_number", "total"=>{"$sum"=>1}}}, {"$match"=>{"total"=>{"$gte"=>2}}}, {"$sort"=>{"total"=>-1}}, {"$limit"=>750000}, {"allowDiskUse"=>true}]}
#fields=nil>
failed with error 16436: "exception: Unrecognized pipeline stage name: 'allowDiskUse'"
Does anyone know how I can structure this query appropriately to pass allowDiskUse outside of the pipeline arg?
Follow below syntax for Mongoid 5.0.0
Modelname.collection.aggregate(
[your stages, ... ],
:allow_disk_use => true
)
For instance
group = { "$group" => {"_id" => {"column_xyz"=>"$column_xyz" }, "collection_name" => { "$push" => "$$ROOT" }, "count" => { "$sum" => 1 } }};
Hive.collection.aggregate([group], {:allow_disk_use => true})
ref: MongoDB jira Ruby-1041's comments
The problem is that Moped does not currently permit options for Moped::Collection#aggregate, just a pipeline for args,
as can be seen here: https://github.com/mongoid/moped/blob/master/lib/moped/collection.rb#L146 -
the Mongo Ruby driver supports options for Mongo::Collection#aggregate, but Mongoid 3 uses Moped for its driver.
However, thanks to the dynamic nature of Ruby, you can work around this.
The following test includes a monkey-patch for Moped::Collection#aggregate provided that you supply the pipeline
as an array for the first argument, allowing you to tack on options like allowDiskUse.
Hope that this helps.
test/unit/item_test.rb
require 'test_helper'
module Moped
class Collection
def aggregate(pipeline, opts = {})
database.session.command({aggregate: name, pipeline: pipeline}.merge(opts))["result"]
end
end
end
class ItemTest < ActiveSupport::TestCase
def setup
Item.delete_all
end
test "moped aggregate with allowDiskUse" do
puts "\nMongoid::VERSION:#{Mongoid::VERSION}\nMoped::VERSION:#{Moped::VERSION}"
docs = [
{serial_number: 1},
{serial_number: 2},
{serial_number: 2},
{serial_number: 3},
{serial_number: 3},
{serial_number: 3}
]
Item.create(docs)
assert_equal(docs.count, Item.count)
dups = Item.collection.aggregate(
[{'$group' => {'_id' => "$serial_number", 'total' => {"$sum" => 1}}},
{'$match' => {'total' => {'$gte' => 2}}},
{'$sort' => {'total' => -1}},
{'$limit' => 750000}],
{'allowDiskUse' => true})
p dups
end
end
$ rake test
Run options:
# Running tests:
[1/1] ItemTest#test_moped_aggregate_with_allowDiskUse
Mongoid::VERSION:3.1.6
Moped::VERSION:1.5.2
[{"_id"=>3, "total"=>3}, {"_id"=>2, "total"=>2}]
Finished tests in 0.027865s, 35.8873 tests/s, 35.8873 assertions/s.
1 tests, 1 assertions, 0 failures, 0 errors, 0 skips

How to convert the data to the yml file

I have a Ruby file, "one.rb":
require 'yaml'
e = { "names"=>{"first_name" => "shaik", "last_name" => "farooq"} }
puts e.to_yaml
When I run this it gets executed successfully in the console and outputs:
---
names:
first_name: shaik
last_name: farooq
I want to store the executed data in a file with a "yml" extension. How can I do this from the above file (test.rb)?
It's really simple:
require 'yaml'
e = { "names"=>{"first_name" => "shaik", "last_name" => "farooq"} }
File.write('test.yaml', e.to_yaml)
After running that, a file called "test.yaml" will exist in the current directory that contains:
---
names:
first_name: shaik
last_name: farooq
You can reload that data easily also:
new_e = YAML.load_file('test.yaml')
# => {"names"=>{"first_name"=>"shaik", "last_name"=>"farooq"}}
You can write the yaml to file with:
require 'yaml'
e = { "names"=>{"first_name" => "shaik", "last_name" => "farooq"} }
File.open('your_file_name.yml', 'w') { |f| f.write(e.to_yaml) }

Create a domain-specific ".site.com" cookie with Ruby's selenium-webdriver [duplicate]

This question already has answers here:
How to set a cookie for another domain
(11 answers)
Closed 9 years ago.
I am trying to create a cookie with domain, not host, or entire website.
I have this code now
driver.manage.add_cookie(:name => 'test', :value => 'testvalue', :path => '/', :secure => false)
I want something like this
name=test
value=testvalue
domain=.site.com
path=/
I am getting such result in a firefox cookie dialog
while I want something like this
You can see Host: is empty in my case and in another case it is replaced with Domain: and this is what I want to achieve, to set a cookie domain to .mydomain.com
I want to achieve this for JavaScript to be able to read domain-specific cookies as it can not read what's outside of current domain scope.
Try following:
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.get('http://eu.httpbin.org') # <-- required.
driver.manage.add_cookie(name: 'test', value: 'testvalue', path: '/', domain: '.httpbin.org')
driver.get('http://eu.httpbin.org/cookies') # eu.httpbin.org
puts driver.page_source
# => ...
# {
# "cookies": {
# "test": "testvalue"
# }
# }
# ...
driver.get('http://httpbin.org/cookies') # httpbin.org
puts driver.page_source
# => ...
# {
# "cookies": {
# "test": "testvalue"
# }
# }
# ...
NOTE: You have to go to the same domain page (html page) before adding cookie.
You can do as below using JavaScript :
require "selenium-webdriver"
require "awesome_print"
driver = Selenium::WebDriver.for :firefox
driver.navigate.to "http://example.com"
COOKIE_DOMAIN = <<-eotl
var cookieName = arguments[0];
var cookieValue = arguments[1];
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + encodeURIComponent(cookieValue)
+ ";expires=" + myDate
+ ";domain=.example.com;path=/";
eotl
driver.execute_script(COOKIE_DOMAIN,'test','testvalue')
ap driver.manage.cookie_named('test')
output
{
:name => "test",
:value => "testvalue",
:path => "/",
:domain => ".example.com",
:expires => #<DateTime: 2014-09-09T07:43:12+00:00 ((2456910j,27792s,999999924n),+0s,2299161j)>,
:secure => false
}

How to setup a mail interceptor in rails 3.0.3?

I am using rails 3.0.3, ruby 1.9.2-p180, mail (2.2.13). I m trying to setup a mail interceptor but I am getting the following error
/home/abhimanyu/Aptana_Studio_3_Workspace/delivery_health_dashboard_03/config/initializers/mailer_config.rb:16:in `<top (required)>': uninitialized constant DevelopmentMailInterceptor (NameError)
How do i fix it?
The code I am using is shown below:
config/initializer/mailer_config.rb
ActionMailer::Base.default_charset = "utf-8"
ActionMailer::Base.default_content_type = "text/html"
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:enable_starttls_auto => true,
:address => "secure.emailsrvr.com",
:port => '25',
:domain => "domain",
:user_name => "user_name",
:password => "password",
:authentication => :plain
}
ActionMailer::Base.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development?
lib/development_mail_interceptor.rb
class DevelopmentMailInterceptor
def self.delivering_email(message)
message.to = "email"
end
end
Thanks in advance.
require 'development_mail_interceptor' #add this line
ActionMailer::Base.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development?
I found it easier to install the mailcatcher gem. Then in development.rb:
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "`localhost`",
:port => 1025
}
Then just run "mailcatcher" and hit http://localhost:1080/ in a browser. It runs in the background, but can be quit directly from the browser. Gives you text+html views, source, and analysis with fractal, if you swing that way. Super-clean.

Resources