Running parallel_tests for Ruby-Capybara not working - ruby

Running a simple login automation test using Capybara. No database is used.
I am trying to use parallel_test gem to invoke multiple test sessions at the same time (chrome browser) using the following command
parallel_rspec -n 2
two browsers are invoked but only the first one is launched with the correct URL and the second one is simply blank. Also, the login and password values are concatenated twice (data collision) in the first browser input fields.
Framework - Non-rails. Ruby with capybara
config/database.yml
test: &TEST
adapter: postgresql
host: localhost
database: test_db<%= ENV['TEST_ENV_NUMBER'] %>
encoding: utf8
username: postgres
password: postgres
spec_file - 1
describe '' do
it '' do
ENV['TEST_ENV_NUMBER'] = ''
end
end
spec_file - 2
describe '' do
it '' do
ENV['TEST_ENV_NUMBER'] = '2'
end
end
both spec files are in the same folder
There is very little guidance for nonrails setup. Any help would be much appreciated.

Related

How to run a SQL file in Ruby

I have multiple .sql files which might consists of multiple Alter table statements or view definitions or plsql function definitions. I want to apply complete sql file on PostgreSQL DB. It should be something similar like
psql -h "HostName" -p "Port" -U "userName" -d "pwd" -f "Sql file location"
I have tried doing PG.connect.execute and that way I need to load the file and execute each statement separately. Is there a way I can execute entire sql file in Ruby?
There are two APIs for communicating with a PostgreSQL database, and both are
available as gems. The pg gem provides a pure Ruby binding to Postgres.
Exemple:
This code assumes you’re accessing the database through TCP/IP on port 5432 of
your local machine:
gem 'pg'
require 'pg'
def with_db
db = PG.connect(
dbname: 'dbname',
user: 'user',
password: 'password'
)
begin
yield db
ensure
db.close
end
end
sql = File.open('path/to/your_sql.sql', 'rb') { |file| file.read }
with_db do |db|
begin
db.exec(sql)
rescue PG::Error
#####
end
end
For more information check this

How to set Chef Vault variable in recipe

Below is the command used to create the vault
knife vault create ldapuser user1 -A "admin,chef1.example.com" -J password.json -M client
Below is the command that shows content of the vault
knife vault show ldapuser user1
id: user1
password: secretp#ssword
username: james
Below is my recipe which includes the following at the very top
chef_gem 'chef-vault' do
compile_time true if respond_to?(:compile_time)
action :install
end
require 'chef-vault'
item = ChefVault::Item.load("ldapuser","user1")
execute 'setup ldap' do
command '/opt/ldap/bin/setup --hostname localhost --port 389 --bindDN cn="Directory Manager" --bindPassword item[password] --ldapport 389 --baseDN "dc=example,dc=com" --addBaseEntry --doNotStart --acceptLicense`
end
execute 'run ldap' do
command '/opt/ldap/bin/ldapmodify --hostname localhost --port 389 --bindDN cn="Directory Manager" --bindPassword item[password] --filename /opt/ldap.ldif
end
Unfortunately once setup is complete and i try to log into my ldap server, i get an invalid credentials error message.
I assume it has to do with how the variable for the bindPassword is defined in the execute block. I even tried logging in using item['password'] and that didnt work. However when i hard code the password (instead of using the vault) into my recipe, i am able to login without any issues.
I have searched everywhere and can't seem to find a solution that works. Please help!
String interpolation in Ruby looks like this: "something #{item['key']} else".
Important bits: use double quotes not single, put #{} around the expression, and make sure you correctly format the expression inside the #{}.
In this example I'm populating a auth.properties and a pem file from secrets from the chef-vault.
Full YouTube Demo Here: How to Create and use Chef-Vault
Default.rb recipe
chef_gem 'chef-vault' do
compile_time true if respond_to?(:compile_time)
end
require 'chef-vault'
secrets = ChefVault::Item.load("vault_demo", "dev_secrets" )
directory "/opt/your_project" do
action :create
end
template '/opt/your_project/auth.properties' do
source "auth.properties.erb"
variables({
sql_password: secrets['sql_password'],
application_password: secrets['application_password']
})
action :create
end
template '/opt/your_project/server.pem' do
source "server.pem.erb"
variables({
ssl_cert: Base64.decode64(secrets['ssl_cert'])
})
action :create
end
Here are the templates:
auth.properties.erb
ssl_password:<%= #sql_password %>
application_password:<%= #application_password %>
server.pem.erb
<%= #ssl_cert %>
Note that the pem file is being base64 decoded in the recipe because it has to be encoded to store in the vault

Programmatically get access_token from OAuth - Using JIRA-Ruby gem

I'm trying to write a JIRA-ruby script (only be used from command-line) to mark some JIRA issue closed automatically.
I borrow an example from here because I'm using 'jira-ruby' gem.
This works however it will pop-up a browser asking you to click "Allow" to get the access_token. I would like to do this programmatically, but I don't think the API was built for this purpose. As access_token changes every time, and this script will run periodically in a cronjob, so we need to have a way to do this. Any idea what other ways we can do this?
require 'jira'
#jira = JIRA::Client.new({:site => 'http://localhost:2990', :context_path => '/jira', :consumer_key => 'test-jira', :private_key_file => "rsakey.pem"})
if ARGV.length == 0
# If not passed any command line arguments, open a browser and prompt the
# user for the OAuth verifier.
request_token = #jira.request_token
puts "Opening #{request_token.authorize_url}"
system "open #{request_token.authorize_url}"
puts "Enter the oauth_verifier: "
oauth_verifier = gets.strip
access_token = #jira.init_access_token(:oauth_verifier => oauth_verifier)
puts "Access token: #{access_token.token} secret: #{access_token.secret}"
elsif ARGV.length == 2
# Otherwise assume the arguments are a previous access token and secret.
access_token = #jira.set_access_token(ARGV[0], ARGV[1])
else
# Script must be passed 0 or 2 arguments
raise "Usage: #{$0} [ token secret ]"
end
# Show all projects
projects = #jira.Project.all
projects.each do |project|
puts "Project -> key: #{project.key}, name: #{project.name}"
end
issue = #jira.Issue.find('DEMO-1')
puts issue
I know there's a way to use long-life access tokens, but not really use if Jira supports it.
I was using the jira-ruby gem at first but I found the performance terrible. I ended up just going with curl instead as I only needed to require the JSON gem which is less bloated. Have your Jira administrators create a user that will never have the password change with admin access and then do the following to find "DEMO-1"
require 'json'
username = "admin"
password = "abc123"
issue = JSON.parse(%x[curl -u #{username}:#{password} \"http://jira/rest/api/latest/issue/DEMO-1\"])
Here is a link to the Jira REST API documentation, just choose the same version of Jira you are using. This will bypass any issues with oauth and the pop-up.

Change Process Priority of a browser created by Watir Webdriver in ruby

I have this in ruby mine on a windows computer:
require 'watir-webdriver'
Before do
#browser = Watir::Browser.new :ie
end
I need to change #browser to run at a higher priority because of some time out issues that I get that are caused when other programs are running at the same time. I know how to increase the amount of time allowed for time out, but after some testing I found I would have to set time out higher than I find to be acceptable.
I have found that you can actually find the webdriven browser's PID from deep inside the #browser object (reading all protected and private components), and then renice it with a negative number to increase priority, which might require sudo to be allowed by a non-root user.
I've explored exporting this object to an ASCII form for storage, which actually works, though importing it back was the subject of another question. Try this (I do it just for fun every time my code fires up a new Watir::Browser):
require "yaml"
File.open("browserObj.yaml", 'w').write YAML::dump($browser)
Then when you peek inside this file browserObj.yaml, it gives you all sorts of interesting info, like:
server_url: !ruby/object:URI::HTTP
fragment:
host: 127.0.0.1
opaque:
parser:
password:
path: /hub/
port: 7055
query:
registry:
scheme: http
user:
timeout:
launcher: !ruby/object:Selenium::WebDriver::Firefox::Launcher
binary: !ruby/object:Selenium::WebDriver::Firefox::Binary
process: !ruby/object:ChildProcess::Unix::ForkExecProcess
args:
- ./firefox.sh
- -no-remote
- -foreground
detach: false
duplex: false
environment: {}
exit_code:
io:
pid: 6114
started: true
Notice the PID in the 2nd last line, which your code can easily detect and do whatever with at this point.
That is even safer than simply parsing the hierarchical process tree with eg. pstree -panu $PPID to find child browser processes.
In my own stuff I actually don't bother (eg. when I need to kill the proper Firefox process and not others) because I go by DISPLAY. All my desktop/interactive user stuff happens on DISPLAY :0, while my Watir Webdriver stuff happens on DISPLAY :99 hosted by Xvfb or Xephyr, which I can more selectively kill/xkill with the help of tools like xprop and xwininfo.
EDIT
For completeness, here's the Unix/Cygwin command I use to send a kill command to the watir-webdriver browser's pid if I need to:
awk '/pid:/ {print $2;}' browserObj.yaml |xargs -rt kill
Browsing the docs and code I didn't see any ready way to find the process id of the IE that the driver uses. You might try using system tools to discover what process is listening on the webdriver port (default 5555) and nicing that process. On posix you could try lsof or netstat to find processes using a specific port, I have no idea how to help you on windows.
Of course if this is a resource competition issue, why don't you just give your watir tests a better controlled environment which doesn't have other stuff preventing it from running at the speeds you desire.

firefox not opening - cron, ruby, firewatir

I have written a ruby script which opens up dlink admin page in firefox and does a ADSL connection or disconnection.
I could run this script in the terminal without any problem. But if I put it as cron job, it doesn't fire up firefox.
This is the entry I have in crontab
# connect to dataone
55 17 * * * ruby /home/raguanu/Dropbox/nettie.rb >> /tmp/cron_test
I see the following entries in /tmp/cron_test. So it looks like the script indeed ran.
PROFILE:
i486-linux
/usr/bin/firefox -jssh
But I couldn't figure out why I didn't see firefox opening up, for this automation to work. Here is /home/raguanu/Dropbox/nettie.rb
#!/usr/bin/ruby -w
require 'rubygems'
require 'firewatir'
require 'optiflag'
module Options extend OptiFlagSet
character_flag :d do
long_form 'disconnect'
description 'Mention this flag if you want to disconnect dataone'
end
flag :l do
optional
long_form 'admin_link'
default 'http://192.168.1.1'
description 'Dlink web administration link. Defaults to http://192.168.1.1'
end
flag :u do
optional
long_form 'user'
default 'admin'
description 'Dlink administrator user name. Defaults to "admin"'
end
flag :p do
optional
long_form 'password'
default 'admin'
description 'Dlink administrator password. Defaults to "admin"'
end
flag :c do
optional
long_form 'connection_name'
default 'bsnl'
description 'Dataone connection name. Defaults to "bsnl"'
end
extended_help_flag :h do
long_form 'help'
end
and_process!
end
class DlinkAdmin
include FireWatir
def initialize(admin_link = "http://192.168.1.1", user = 'admin', pwd = 'admin')
#admin_link, #user, #pwd = admin_link, user, pwd
end
def connect( connection_name = 'bsnl' )
goto_connection_page connection_name
# disconnect prior to connection
#browser.button(:value, 'Disconnect').click
# connect
#browser.button(:value, 'Connect').click
# done!
#browser.close
end
def disconnect( connection_name = 'bsnl' )
goto_connection_page connection_name
# disconnect
#browser.button(:value, 'Disconnect').click
# done!
#browser.close
end
private
def goto_connection_page( connection_name = 'bsnl')
#browser ||= Firefox.new
#browser.goto(#admin_link)
# login
#browser.text_field(:name, 'uiViewUserName').set(#user)
#browser.text_field(:name, 'uiViewPassword').set(#pwd)
#browser.button(:value,'Log In').click
# setup > dataone
#browser.image(:alt, 'Setup').click
#browser.link(:text, connection_name).click
end
end
admin = DlinkAdmin.new(Options.flags.l, Options.flags.u, Options.flags.p)
unless Options.flags.d?
admin.connect( Options.flags.c )
else
admin.disconnect( Options.flags.c )
end
Any help is appreciated.
You need to have a DISPLAY environment pointing at a valid X-server. This could either involve setting it to the value ":0.0" (without quotes), such that it refers to your local standard DISPLAY.
There's a few things to keep in mind though:
You could run an X virtual frame buffer (xvfb), so that Firefox simply uses that as it's display. This would mean that Firefox would be able to do all its graphical operations, but that it would be independent of your standard graphical environment. You'll have to set the DISPLAY variable appropriately so that it points to the xvfb instance. For instance, if you invoke xvfb as follows:
Xvfb :1 -screen 0 1600x1200x32
Then you'll be able to use this by setting the DISPLAY variable to :1
You're starting a full-blown firefox instance to simply connect or disconnect your modem. You would most likely be able to use "curl" to send the appropriate HTTP requests to the server, such that it performs a connect or disconnect for you. One way to trivially see what you should recreate would be to install a Firefox plugin such as LiveHTTPHeaders and note down the most important HTTP requests as you perform the actions manually.
There's even a ruby binding for curl:
libcurl for Ruby. The resulting script should be much smaller than your current script.
Programs run from cron don't have your interactive environment. Therefore they don't have and DISPLAY variable, and so you can't run any X (graphical) programs, e.g. Firefox.
I would suggest doing the HTTP connections yourself, in ruby, rather than trying to automate Firefox.
the crontab entry is wrong
it is like
#min hour day month dow user command
55 17 * * * ur_user_is_missing ruby /home/raguanu/Dropbox/nettie.rb >> /tmp/cron_test

Resources