Generate XML with soap4r without invoking the web service? - ruby

I have set up a soap4r client for a web service, and it's working fairly well. We're using it to send data from one database to another (don't bother asking about that... I know it's not optimal), but we're not entirely sure the mapping is correct, so it's often very handy to get the XML that a particular record would generate.
Of course, that's possible - if you set $DEBUG, soap4r will supply you with a nice dump of the XML going over the wire. You can even set the "device" (file) that you would like to send it to.
However, I'd like to be able to get the XML that it's going to generate without having to actually call the web service.
Is there a way to do this? Grepping around, I've found a variety of obj2soap and similar methods, but none of them seems to be quite the one I want.

An indirect answer: you might want to look at handsoap. It's faster and tries to be more Ruby-like. It uses builder-style XML generation - but you have to generate everything yourself. It's more like a toolbox to write your client in a clean way. This way you know what was generated (and can inspect it easily).
Another option is to set $DEBUG and restore it afterwards:
$REMEMBER_DEBUG_STATE = $DEBUG
$DEBUG = true
# call soap (and have your XML generated)
$DEBUG = $REMEMBER_DEBUG_STATE
This could be extracted to a nice function like this:
def with_debug_output
remember = $DEBUG
$DEBUG = true
yield if block_given?
$DEBUG = remember
end
and then use it:
with_debug_output do
# call soap
end

Related

How do I programmatically set a content_security_policy?

I'm configuring the Content Security Policy for our Rails 5.2 app. I need to whitelist some domains in our CSP. I'd like to put the list of domains elsewhere so I can reference them in other places in the application, then generate the CSP headers programmatically from that list.
Looking at the source code for the Content Security Policy configuration mechanisms in Rails 5, it looks like there's some magic metaprogramming going on, so it's not clear to me how to accomplish what I need to do. It looks like the functions I need to call to set headers might be picky about how exactly they want to be called. In particular, it's not clear to me if I can pass them arrays or safely call them multiple times, or if they do some metaprogramming magic that only works if the domains are passed in as individual function arguments.
Can I pass in an array to the header I want to set, like this?
whitelisted_domains = ['https://example.com', 'self']
Rails.application.configure do
config.content_security_policy do |csp|
csp.child_src whitelisted_domains
end
end
Or can I call the same function multiple times, like this?
whitelisted_domains = ['https://example.com', 'self']
Rails.application.configure do
config.content_security_policy do |csp|
whitelisted_domains.each {|domain| csp.child_src domain}
end
end
If neither of those will work, what's the best way of accomplishing what I want to do?
From what I can tell from sourcecode and documentation, it takes an array. From the edgeguides at rails, posting following
Rails.application.config.content_security_policy do |policy|
policy.default_src :self, :https
...
end
and the sourcecode, using *sources as param; it believe it takes any number of arguments, meaning you could do something along the lines of;
whitelisted_domains = ['https://example.com', 'self']
Rails.application.configure do
config.content_security_policy do |csp|
csp.child_src(*whitelisted_domains)
end
end
https://blog.sqreen.io/integrating-content-security-policy-into-your-rails-applications-4f883eed8f45/
https://edgeguides.rubyonrails.org/security.html#content-security-policy
Sourcecode of define_method for each directive
https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/http/content_security_policy.rb#L151
(note: None of this has been tested in a Rails app, simple looking guides and source code of Rails)

Is it better idea to save elements in yml file?

I'm writing automated tests using Selenium WebDriver with Ruby. So, I'm thinking to keep elements in another file and actual code in another file. And for Ruby, I found yaml gem which allows to store data and access it. Hence I stored elements in lib.yml and test code in test.rb as following:
lib/lib.yml
homepage:
frame: 'mainPage'
email: 'loginPage-email'
password: 'loginPage-password'
login_button: 'btnLogin'
tests/test.rb
require 'selenium-webdriver'
require 'yaml'
driver = Selenium::WebDriver.for :firefox
driver.get 'http://www.abc.com'
config = YAML.load_file('./lib/lib.yml')
driver.switch_to.frame(config['homepage']['frame'])
email = driver.find_element(:id, config['homepage']['email'])
password = driver.find_element(:id, config['homepage']['password'])
email.clear
email.send_keys 'abc#gmail.com'
password.clear
password.send_keys 'password'
driver.find_element(:id, config['homepage']['login_button']).click
driver.quit
This way maintenance becomes easier. I just want to make sure if doing so is a good way or not. I'm asking because I'm trying this first time and don't know what difficulties I'll run into if I choose this for larger project.
I know, using Page object model, we can achieve same thing. But I don't know about Page object. So should I avoid using yml gem and directly go for page object gem?
Also, can someone explain how using yml will not be good idea(if it's not)?
Note:
In above code, config['homepage']['something'] is repetitive code. I'll write method to avoid repetition for that.
Yeah this definitely is useful... It keeps the changes to minimum when there is UI change in future.. You always have just one place to edit... Is there any data you have to pass to your code? How are storing the automation data passed to your test.. The only concern might be you might end up with too many yaml files which could be difficult to keep track...
In your specific case I don't see how this adds much value. Half of the settings (frame, login_button) won't change for your tests, so I suggest leaving them directly in the code where they are used. The html structure is not something that usually changes.
The other two values (email, password) seem like they might change when you want to try out different users (i.e. different cases). If you have one test with several example inputs then I suggest using a more readable solution as Cucumber.
(I'd suggest using capybara anyway for testing browser interaction, as it abstracts away many details of the underlying driver)
Apart from that, yaml is usually the ruby way for storing configuration.
I added one more step: Declared locator (id, name etc) in the yaml itself.
Ex:(yaml)
Declared env.rb which load the environment from yaml files
env.yml:
LOGIN:
UserName: {id: UserName}
Password: {id: Password}
RememberME: {id: RememberMe}
Submit: {xpath: "//input[#value='Log On']"}
Then added "pages\Login.rb"
#Loads all objects from yaml
def get_objects
username=#browser.find_element( $object_array['LOGIN']['UserName'])
password=#browser.find_element( $object_array['LOGIN']['Password'])
remember_me=#browser.find_element( $object_array['LOGIN']['RememberME'])
submit= #browser.find_element($object_array['LOGIN']['Submit'])
end
#Added methods in this class like
def loginas(uname,pass)
username.send_keys uname
password.send_keys pass
remember_me.click
submit.click
end #loginas_siteadmin
Created Tests file Login_tests.rb
lp=LoginPage::new(#browser)
lp.navigate
lp.loginas('SiteAdmin','password123')
This way your scripts and maintainable and most importantly you are free of any other external gem or dependency.

Passing options and parameters to Test/Unit via Rake::TestTask

So I've been trying to figure this out, and the best solution I can came up with his global variables - but that seems so dirty and 1974 - Am I missing a feature of Rake/ Test::Unit?
I have a Rake file in which I'm running tests:
Rake::TestTask.new(:test) do |t|
t.test_files = FileList['test_*.rb']
end
and test_1.rb has something like this:
require "test/unit"
class TestStuff < Test::Unit::TestCase
def setup
#thingy = Thing.New(parameter1, parameter2)
end
def test_this_thing
#thing.do()
end
end
My problem is, Thing.new() requires arguments, and those arguments are specific to my environment. In reality, I'm running Selenium-WebDriver, and I want to pass in a browser type, and a url, etc... sometimes I want ff, othertimes I want chrome... sometimes this URL, sometimes that... depending on the day, etc.
The simplest thing seems to do something like:
#all that rake stuff
$parameter1 = x
$parameter2 = y
and then make Thing.new() look up my global vars:
#thingy = Thing.New($parameter1, $parameter2)
This seems sloppy.. and it just doesn't feel right to me. I'm still trying to get this 'test harness' up and running, and want to do it right the first time. That's why I chose Rake, based on a lot of other feedback.
Keep in mind, I'll probably have 100's of tests, ultimately, and they'll all need to do get this information... I thought Rake was good at making sure all of this was easy, but it doesn't seem to be.
Where did I go wrong?
I have used YAML files to store my configuration (browser config, environments including URLs, etc).
You can also use an environmental variable to define simple configurations. You can access environmental variables via ENV['foobar'] in Ruby.
So, for example, my browser call might look like this inside my setup method:
driver = Selenium::WebDriver.for (ENV['SWD_BROWSER'] || "firefox").to_sym
and in my Rake file (or in the shell console) define the environmental variable to use.

How to record/playback in different cassettes split by host?

In the project I am working on, we use VCR to store cassettes for both local and external services. The local ones are micro services that are constantly modified while the external ones are hardly modified.
Due this reason and plus that the external services takes a long time to be re-record, makes sense for us re-record just the local cassettes most of the time.
In order to solve that we tried to separate the cassettes in different folders (cassettes/localhost and cassettes/external/sample.com).
Then we came up with:
VCR.configure do |config|
config.around_http_request do |request|
host = URI(request.uri).host
vcr_name = VCR.current_cassette.name
folder = host
folder = "external/#{folder}" if host != 'localhost'
VCR.use_cassette("#{folder}/#{vcr_name}", &request)
end
[...]
end
But the problem is that we have some tests that need to make repeated requests (exactly the same request) where the server returns different results. So, using the code above makes the cassettes be reset for each http call. The first request is recorded, and the second is a playback of the first, even if the response was expected to be different.
Then we tried a different approach using tags and nested cassettes:
RSpec.configure do |config|
config.around(:each) do |spec|
name = spec.metadata[:full_description]
VCR.use_cassette "external/#{name}", tag: :external do
VCR.use_cassette "local/#{name}", tag: :internal do
spec.call
end
end
end
[...]
end
VCR.configure do |config|
config.before_record(:external) do |i|
i.ignore! if URI(i.request.uri).host == 'localhost'
end
config.before_record(:internal) do |i|
i.ignore! if URI(i.request.uri).host != 'localhost'
end
[...]
end
But also this doesn't work. The outcome was that all localhost requests were recorded on the internal cassette. The rest of the requests were ignored by VCR.
So do you have any suggestion to solve this?
Then we tried a different approach using tags and nested cassettes...But also this doesn't work.
Yeah, I didn't design cassette nesting with this kind of use case in mind. HTTP interactions are always recorded to the innermost cassette, but can be played back from any level of nesting (it tries the innermost cassette first, then searches up the parent chain). The main use case I had in mind for nesting cassettes was for cucumber: you may want to use a single cassette for an entire scenario, but then you may want to use a particular cassette for an individual step definition (i.e. for any scenario that uses that step). The inner cassette "takes over" while it is in use, but the outer cassette is still there to be available for when the inner cassette is ejected.
This is an interesting use case, though...if you think VCR should work that way, please consider opening a github issue for it and we can discuss it more.
As for your original question: I think #operand's answer will work.
I think you want to look into using the :match_requests_on setting. Read the docs here: https://www.relishapp.com/myronmarston/vcr/v/2-3-0/docs/request-matching
This should allow you to record multiple requests to the same URL but have them replayed in sequence.
In addition to that, I think your method of splitting up the cassettes into different directories sounds good. One thing I've done in the past to force re-recording of specific cassettes, is to just delete the cassettes themselves before rerunning the specs. In your case that should be easy since you've separated them nicely.
Instead of or in addition to that, you could possibly use the :all record setting when you know it's a local request, and patch that into your configure block. Something like:
VCR.configure do |config|
config.around_http_request do |request|
host = URI(request.uri).host
vcr_name = VCR.current_cassette.name
folder = host
if host != 'localhost'
folder = "external/#{folder}"
record_mode = :once
else
record_mode = :all
end
VCR.use_cassette("#{folder}/#{vcr_name}", :record => record_mode, &request)
end
[...]
end
Note, I haven't tested this, so please double check me on that. Of course, you'd also want to not use the :all record setting when you just want to play things back. Maybe you can develop a switch somehow when you invoke the tests.
It's not a complete answer, but I hope this helps.

SOAP::RPC::Driver formatting problems. How can I change it?

I'm dealing with a SOAP webservice call from a server that is expecting to receive method calls with the paramaters in the format of:
<urn:offeringId> 354 </urn:offeringId>
But SOAP::RPC::Driver is generating messages in the form of:
<offeringId xsi:type = "xsd:int">354</offeringId>
The server keeps erroring when it gets these messages (especially since it's expecting offeringId to be a custom type internal to itself, not an int).
Is there anyway to configure the driver to format things the way the server is expecting it. Is the server even doing SOAP? I'm having trouble finding reference to that style of formating for SOAP (I know it DOES work though, because SOAPUI works just fine with that type of message).
-Jenny
Edit: I've got at least part of it solved. the RPC::Driver (obviously) uses the RPC standard, whereas apparently the server I'm trying to talk to is doing "document". Now, when I look at RPC::Driver's API, I'm seeing a method named "add_document_method". That SOUNDS to me like it might be what I want, but I can't figure out what paramaters to give it. The examples I've seen around the net don't make much sense to me, things like:
def GetNamePair(response)
response.account.each do |x|
class << x
attr :configuration, true
end
x.configuration = Hash[*x.a.map do |y|
[y.__xmlattr[XSD::QName.new(nil, 'n')], String.new(y)]
end.flatten]
end
end
mNS = 'urn:zimbraAdmin'
drv.add_document_method('GetAllAdminAccountsRequest', mNS, [XSD::QName.new(mNS, 'GetAllAdminAccountsRequest')],
[XSD::QName.new(mNS, 'GetAllAdminAccountsResponse')] )
puts YAML.dump(GetNamePair(drv.GetAllAdminAccountsRequest([]))
All I really know is that I have a method that takes in certain parameters.... I really don't get why, if this method does what I think it does, it has to be more complicated. Isn't this just a matter of taking the exact same data and formating it differently? I'm so confused....
Okay, what I ended up doing was using SOAP:RPC:Drivers add_document_method, which requires me to give it the wsdl, namespace, etc, and then give it the attributes later as a single input hash thingy (and gives me the output in a similar format). It worked, it just wasn't as clean as add_rpc_method (which is waht add_method defaults to)
-Jenny

Resources