trying to POST with ruby mechanize - ruby

I've captured the login HTTP headers using firefox plugin LiveHTTPheaders.
I've found the following url and variables.
POST /login
email=myemail%40gmail.com&password=something&remember=1&loginSubmit=Login
And here's the code I am running:
require 'rubygems'
require 'mechanize'
browser = Mechanize.new
browser.post('http://www.mysite.com/login',
[
["email","myemail%40gmail.com"],
["password","something"],
["remember","1"],
["loginSubmit","Login"],
["url"=>""]
]
) do |page|
puts page.body
end
However, this gives me nothing ! is something wrong with my post parameters ?

post() doesn't take a block. Try this:
page = browser.post('http://www.mysite.com/login', {
"email" => "myemail%40gmail.com",
"password" => "something",
"remember" => "1",
"loginSubmit" => "Login",
"url" => ""
})
edit: changed for accuracy

Related

HTTParty headers not working in ruby script

I am trying to get the following curl command (which works) replicated in some Ruby code, however the 'Customer-Id' header part seems to not get sent/picked up by the API.
The curl command is:
curl -u ‘me#mydomain.com’ -H ‘Customer-Id: 243’ https://192.168.50.50/api/customers
which returns info on that customer. However in Ruby, the following is not working:
auth = {
username: “me#mydomain.com”,
password: "#{pass}"
}
#result = HTTParty.get("https://192.168.50.50/api/customers",:basic_auth => auth, :headers => { ‘Customer-Id: 243’ } ).parsed_response
puts #result
If anyone has any ideas what I am doing wrong here, it would be appreciated!
Looking at your code, there is an error:
:headers => { ‘Customer-Id: 243’ }
Try this way:
:headers => {'Customer-Id' => 243}

Soundcloud - Ruby creating a Playlist getting 422 (#soundcloud-ruby)

I suspect something at Soundcloud has changed because my code has not been altered and worked fine last year.
I see:
Error: HTTP status: 422 Unprocessable Entity, Status Code: 422, playlist_struct:{:title=>"Y11 - REVO - Sop", :description=>"Y11 - REVO - Sop newchoir", :tag_list=>"Sop", :tracks=>"219269586", :format=>"json", :oauth_token=>"..."}
My oauth_token works fine.
I call:
new_playlist = #client.post('/playlists', playlist_struct)
Where #client is defined using https://github.com/soundcloud/soundcloud-ruby as:
#client = SoundCloud.new({
:client_id => clientId,
:client_secret => clientSecret,
:username => email,
:password => password
})
And playlist_struct is per the error message.
Thoughts appreciated!
Regards, M.
Full code:
require 'rubygems'
require 'soundcloud'
require 'pp'
require 'logger'
def login
# http://soundcloud.com/you/apps
clientId = '...'
clientSecret = '...'
email = '...'
password = '...'
# register a new client, which will exchange the username, password for an access_token
# NOTE: the SoundCloud API Docs advise not to use the user credentials flow in a web app.
# In any case, never store the password of a user.
#client = SoundCloud.new({
:client_id => clientId,
:client_secret => clientSecret,
:username => email,
:password => password
})
# print logged in username
puts"h1. Logged in as " + #client.get('/me').username
# updating the users profile description
end
login()
playlist_struct = {
:title => "Hello"
}
new_playlist = #client.post('/playlists', playlist_struct)
#log.info ' OK: '+new_playlist.permalink_url
Looks like the playlist_struct now needs to include
playlist: {
...
}
Around the content.
As the code worked for a couple of years before hand I'd venture this is a silent change to the API.

Mocking methods in Puppet rspec tests

I've implemented a custom Puppet function that queries a Keystone server for information. The module that defines this function includes some helper methods that perform the actual work of querying keystone. Broadly, the structure looks like this:
def authenticate(auth_url, username, password)
...
end
def list_tenants(auth_url, token)
...
end
module Puppet::Parser::Functions
newfunction(:lookup_tenant, :type => :rvalue) do |args|
...
end
end
I would like to mock out the authenticate and list_tenants methods
during testing so that I can test the rest of the Puppet module in the
absence of an actual Keystone server.
I haven't previously worked with either Ruby or Rpsec before, and I'm
having a hard time finding examples of how to provide stubs for these
internal methods.
So far I have a stub rspec file that simply verified the existence of
the function:
require 'spec_helper'
describe 'lookup_tenant' do
it "should exist" do
Puppet::Parser::Functions.function("lookup_tenant").should == "function_lookup_tenant"
end
# This will fail because there is no keystone server.
it "should fail" do
should run.with_params(
'http://127.0.0.1:35357/v2.0',
'admin_user',
'admin_password',
'admin_tenant_name',
'target_tenant_name'
).and_raise_error(KeystoneError)
end
end
I would like to be able to provide custom returns from the
authenticate and list_tenants methods (or even raise exceptions
from inside these methods) so that I can test the behavior of the
lookup_tenant function in different failure scenarios.
WebMock could be used for simulating the http requests as stubs. Here is the link to the github repo: https://github.com/bblimke/webmock
For folks who haven't seen webmock before, I wanted to leave some information here about why it's particularly awesome.
So, I have in my module some code that makes an http request:
url = URI.parse("#{auth_url}/tokens")
req = Net::HTTP::Post.new url.path
req['content-type'] = 'application/json'
req.body = JSON.generate(post_args)
begin
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
if res.code != '200'
raise KeystoneError, "Failed to authenticate to Keystone server at #{auth_url} as user #{username}."
end
rescue Errno::ECONNREFUSED
raise KeystoneError, "Failed to connect to Keystone server at #{auth_url}."
end
By simply adding a require to the start of the spec file:
require `webmock`
Attempts to open a connection will result in:
WebMock::NetConnectNotAllowedError:
Real HTTP connections are disabled. Unregistered request: POST http://127.0.0.1:35357/v2.0/tokens with body '{"auth":{"passwordCredentials":{"username":"admin_user","password":"admin_password"},"tenantName":"admin_tenant"}}' with headers {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type'=>'application/json', 'User-Agent'=>'Ruby'}
You can stub this request with the following snippet:
stub_request(:post, "http://127.0.0.1:35357/v2.0/tokens").
with(:body => "{\"auth\":{\"passwordCredentials\":{\"username\":\"admin_user\",\"password\":\"admin_password\"},\"tenantName\":\"admin_tenant\"}}",
:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type'=>'application/json', 'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => "", :headers => {})
And that's just about all the information you need to stub out the
call. You can make the stubs as granular as necessary; I ended up
using something like:
good_auth_request = {
'auth' => {
'passwordCredentials' => {
'username' => 'admin_user',
'password' => 'admin_password',
},
'tenantName' => 'admin_tenant',
}
}
auth_response = {
'access' => {
'token' => {
'id' => 'TOKEN',
}
}
}
stub_request(:post, "http://127.0.0.1:35357/v2.0/tokens").
with(:body => good_auth_request.to_json).
to_return(:status => 200, :body => auth_response.to_json, :headers => {})
And now I can test my module when there is no Keystone server
available.

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
}

HTTParty options parameter not functioning properly

I'm setting up an application which can make LastFM API Requests.
These are simple get requests and I'm using the HTTParty gem.
My function is as follows:
def get_albums
self.class.base_uri "http://ws.audioscrobbler.com/2.0/"
options = {
:user => "Gerard1992",
:method => "user.gettopalbums",
:api_key => Constants::LASTFM_API_KEY,
:format => "json"
}
puts options.to_query
self.class.get "/?#{options.to_query}", {} #options don't work
end
This piece of code that's shown above works. The get request returns a set of JSON. My problem is that this /?#{options.to_query} doesn't look that neat. And neither does the actual (now empty {}) options parameter. How do I get the HTTParty options parameter to work like it should?
This is what I've tried, but both cases failed:
self.class.get "/", options
self.class.get "/", options => options
I appreciate the help.
The correct option for query parameters in HTTParty is :query, so what you want is:
self.class.get "/", query: options
You can see all the available parameters in the docs.
Send :verify => false in options hash

Resources