Mocking methods in google ruby api client - ruby

I am trying to mock some methods that use the google-api-ruby-client to make some testing without actually calling the api. Authentication and client and activities methods are taken from the example found on the github page (see link above), which is why I skipped it here.
The method from the example is the following:
def activities
result = client.execute(
:api_method => plus.activities.list,
:parameters => {'collection' => 'public', 'userId' => 'me'}
)
return result.data
end
I previously tried to stub the client (even chained with the execute) methods, however this results in authorization requests for oauth, which the gem uses underneath followed by mocks for the plus.activities.list methods. Is there a way to directly mock client.exectute to return something useful while skipping the whole chain?

I am not sure that I understand your problem correctly, but maybe something a little bit crazy will work
I assume that your method is in Client model so maybe something like that will work
Client.stub_chain(:client, :execute).and_return(true)
Of course if you model have different name you have to adjust. I am not sure but you can give it a try

Checkout their spec helper:
https://github.com/google/google-api-ruby-client/blob/master/spec/spec_helper.rb
And how they do the tests:
https://github.com/google/google-api-ruby-client/blob/master/spec/google/api_client_spec.rb

Related

Trouble faking a Laravel HttpClient response

I am trying to test the following bit of code:
DimonaClient is just a simple wrapper around a Laravel HttpClient; simplified function here:
The getDeclaration() response is a \Illuminate\Http\Client\Response
What I am trying to do in my test is:
Mock the DimonaClient class so I don't create an actual api call
"Mock" (use Laravel's Http::response()) the response I want so that I can test that a 200 w/ certain statuses dispatches the appropriate event (also mocked, but not relevant here)
My test code looks like this:
My issue(s) seem to be:
the getDeclaration() has an expectation of Illuminate\Http\Client\Response but I can't seem to create anything that will satisfy that (a new Response wants a MessageInterface, etc, etc... )
I don't actually need getDeclaration() to return anything for my testing, so I wonder if I should be mocking this differently in any case (I base this assumption on Http::response handling the internal code I'm testing for things like $response->ok(), instead of a Mockery expectation)
I feel like I'm one small step away from making this work, but going round in circles trying to hook it up correctly.
TIA!
If you are using Http Facade, you don't need to mock DimonaCient. You are nearly there with your test, but let me show you what you would have done:
/** #test */
public function it_can_handle_an_approved_submission(): void
{
Http::fake([
'*' => Http::response([
'declarationStatus' => [
'result' => DimonaDeclarationStatus::ACCEPTED,
'dimonaPeriodId' => $this->faker->numerify('############'),
],
],
]);
$dimonaDeclarationId = $this->faker->numerify('############');
// Do your normal call, and then assertions
}
Doing this, you will tell Http to fake any URL, because we are using *. I would recommend you use $this->endpoint/$declarationId so if it does not match, you will also know you did not hit the right endpoint.
I am not sure what Laravel you are using but this is available since Laravel 6+, check Http fake URLs.

What's the best way to stub out network calls with Faraday in the Balanced Ruby client?

I'm not particularly familiar with Faraday's stubbing API, but from a casual inspection of that and the source of Balanced::Client, it looks like I'd need to be able to provide my own value for Balanced::Client.conn.
This is a step towards supporting for a stubbed connection mode by a configuration option in library, whereas flipping on that toggle, I could just use Balanced::Client.conn as a handle for stubbing whatever requests I expect to occur during my test.
It would also be super useful to have example response bodies for the various Balanced API calls and/or some builtin stub responses to use as templates for my own stubs.
Does this seem like a reasonable plan, or am I heading in the wrong direction? How do I go about doing this?
I recommend taking a look at how the unit tests for the balanced-ruby library are written. They use VCR to record and replay network calls.
While not pertinent to your exact question, you can also create one-off instances of objects by using the construct_from_response method on any object that inherits from the Resource class in resource.rb. This allows you to create a single instance of an object like so:
1.9.3p194 :034 > payload = {:name"=>"Bob", :uri=>"/v1/marketplaces/M123/accounts/fake"}
1.9.3p194 :035 > account = Balanced::Account.construct_from_response payload
1.9.3p194 :036 > account.name
=> "Bob"
Note that the uri param in the payload is required or else the library will go and try to look the object up from the server.
Can do something like this. Use the gem webmock https://github.com/bblimke/webmock
And stub requests yourself:
stub_request(:get,"https://<your secret key>:#api.balancedpayments.com/v1/customers email=#<test email>")
.with(:headers => {'Accept'=>'*/*',
'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'User-Agent'=>'balanced-ruby/0.7.4'})
.to_return(:status => 200, :body => "", :headers => {})

What would be a convenient way to count the number of HTTP requests made by a block of code?

Suppose I want to be able to write a test like this:
lambda {
do_something_involving_web_requests
}.should make(1).http_requests
It seems to me there would be several possible ways to implement this kind of functionality; however, it also seems that:
Someone might have already done so (in which case I want to look into their solution); or
Someone on StackOverflow might have an idea I haven't thought of.
So, has this been done already? And/or what are your ideas?
If you're interested in more granular testing of how your app responds to specific HTTP responses, rather than simply counting requests, you can use mocks. Here's how to use RSpec's mocks to test http requests:
#mock_http = mock("http")
Net::HTTP.stub!(:start).and_yield #mock_http
#mock_http.should_receive(:get).with("/")
One library I use is Fakeweb. Fakeweb does what #Joe mentions: it hooks into Net::HTTP and can be configured to return a canned response from a given URL. Many other HTTP libs depend on Net::HTTP so this technique has broad compatibility. Fakeweb example from its docs:
FakeWeb.register_uri(:get, "http://example.com/test1", :body => "Hello World!")
Net::HTTP.get(URI.parse("http://example.com/test1"))
=> "Hello World!"
Neither of these methods have a simple access count though, if you want that you can use rspec-mocks which has the following method count functionality (these can be used on stubs or test doubles):
double.should_receive(:msg).once
double.should_receive(:msg).twice
double.should_receive(:msg).exactly(n).times
double.should_receive(:msg).at_least(:once)
double.should_receive(:msg).at_least(:twice)
double.should_receive(:msg).at_least(n).times
double.should_receive(:msg).at_most(:once)
double.should_receive(:msg).at_most(:twice)
double.should_receive(:msg).at_most(n).times
double.should_receive(:msg).any_number_of_times

Padrino model from json data

I have been looking at Padrino for a project I am working on, and it seems a great fit, as I would ideally be wanting to support data being sent and received as json.
However I am wondering if there is any automated helper or functionality built in to take data from a post request (or other request) and put that data into the model without having to write custom logic for each model to process the data?
In the Blog example they briefly skim over this but just seem to pass the parameter data into the initilizer of their Post model, making me assume that it just magically knows what to do with everything... Not sure if this is the case, and if so is it Padrino functionality or ActiveRecord (as thats what they seem to use in the example).
I know I can use ActiveSupport for JSON based encoding/decoding but this just gives me a raw object, and as the storage concerns for each model reside within the main model class I would need to use a mixin or something to achieve this, which seems nasty.
Are there any good patterns/functionality around doing this already?
Yep, you can use provides and each response object will call to_json i.e:
get :action, :provides => :json do
#colletion = MyCollection.all
render #collection # will call #collection.to_json
end
Here an example of an ugly code that fills certain models.
# Gemfile
gem 'json' # note that there are better and faster gems like yajl
# controller
post "/update/:model/:id", :provides => :json do
if %w(Account Post Category).include?(params[:model])
klass = params[:model].constantize
klass.find(params[:id])
klass.update_attributes(JSON.parse(params[:attributes]))
end
end
Finally if you POST a request like:
attributes = { :name => "Foo", :category_id => 2 }.to_json
http://localhost:3000/Account/12?attributes=#{attributes}
You'll be able to update record 12 of the Account Model.

Generate an HTTP response in Ruby

I'm working on an application that reaches out to a web service. I'd like to develop a proxy class that returns a fake response from the service, so I don't have to constantly be hitting it with requests while I'm developing/testing other parts of the app.
My application is expecting a response generated via Net::HTTP.
response = Net::HTTP.get(URI.parse('http://foo.com'))
case response
when Net::HTTPOK
# do something fun
when Net::HTTPUnauthorized
# you get the idea
How can I manufacture a response object, give it all the right headers, return a body string, etc?
response = ProxyClass.response_object
case response
when Net::HTTPOk
# my app doesn't know it's being lied to
Thanks.
It's actually not that hard to roll your own fake responses directly with Net::HTTP. Here's a simple 200 OK with a cookie header:
def fake_response
net_http_resp = Net::HTTPResponse.new(1.0, 200, "OK")
net_http_resp.add_field 'Set-Cookie', 'Monster'
RestClient::Response.create("Body goes here", net_http_resp, nil)
end
Since few of us are using raw Net::HTTP anymore, the (optional) last line wraps it up as a RestClient::Response, which can then be stubbed into RestClient:
stub(RestClient).post(anything) { fake_response }
I would start with FakeWeb and see if that meets your needs. If it doesn't you can probably gut whatever you need out of the internals and create your own solution.
I know this post is old, but instead of FakeWeb which seems to be largely dead, try webmock. It seems to be more full-featured and very active.
I would look into a mocking library like mocha.
Then you should be able to setup a mock object to help test:
Then following example is from Tim Stephenson's RaddOnline blog, which also includes a more complete tutorial:
def setup
#http_mock = mock('Net::HTTPResponse')
#http_mock .stubs(:code => '200', :message => "OK", :content_type => > "text/html", :body => '<title>Test</title><body>Body of the page</body>')
end
For testing a web service client, we use Sinatra, a lovely little lightweight web framework that lets you get something up and running very quickly and easily. Check out the home page; it has an entire Hello World app in 5 lines of code, and two commands to install and run the whole thing.
I ended up using a Struct.
FakeHttpResponse = Struct.new(:status, :body)
http = FakeHttpResponse.new('success', 'body goes here')
http['status'] # = 'success'
http.body # = 'body goes here'
The drawback is that .status and ['body'] are also valid, but I don't think that matters much.
I would either use FakeWeb as mentioned above, or have my rake test task start a Webrick instance to a little sinatra app which mocks the various test responses you're hoping to see.
You could look into using Rack for this which should allow you to do everything you need.

Resources