Jump to content

User:Fatuglypanda/sandbox

From Wikipedia, the free encyclopedia

FakeWeb is a RubyGems package that helps with the software testing of Ruby projects by faking HTTP requests.[1]. By faking HTTP requests FakeWeb allows users to test a project without connecting to any live service. This allows the user to remove dependencies on third party services and also nullifies network related delays while testing. Fakeweb has many different functionalities. Most of the important functionalities have been mentioned in the examples below.

History

[edit]

Fakeweb is a project that is maintained in the public repository GitHub. This project had contributions from Chris Kampmeier, Blaine Cook and Ben Woosley[2]. The first commit of FakeWeb into GitHub occurred on May 23, 2006[3]. Its latest release version is 1.3.0, which was released on August 23, 2010[2]. Since then the project has been dormant without any active releases.

Installation

[edit]

Below are the steps to install FakeWeb.

Prerequisites

[edit]

The prerequisites to installing FakeWeb are Ruby and RubyGems.

Ruby and RubyGems Installation

[edit]
Microsoft Windows
[edit]

The steps to install Ruby and RubyGems on Microsoft Windows are outlined below.[4][5]

> chdir <Directory of the extracted folder>
> ruby dk.rb init
> ruby dk.rb install
Linux(Ubuntu)
[edit]

Ruby can be installed for Ubuntu in different ways. In order to make sure that the version matches the requirement, the best way to install is to build Ruby from the source.[6]

  • Download the latest stable version of Ruby from here.
  • Extract the TAR file into a directory of your choice.
  • On the Linux Console navigate to the directory into which the above TAR file was extracted.
  • Execute the following commands on the Linux Console to install Ruby:
./configure
make
sudo make intall
  • In order to install RubyGems perform the following steps:
sudo apt-get update
sudo apt-get install gems

FakeWeb Installation

[edit]

To install the latest release of FakeWeb via RubyGems package manager use:

gem install fakeweb

If you are using a gemfile[7] for your Ruby project add the following to your gemfile:

gem "fakeweb", "~ 1.3"

If you are developing your own gem and are using FakeWeb add the following to your gemspec[8]:

spec.add_development_dependency "fakeweb", ["~ 1.3"]

Examples

[edit]

Registering Basic String responses

[edit]

One functionality of FakeWeb is to return responses when a request is made to a URL. The parameters of the FakeWeb's 'register_uri' function can be used to specify the response which is to be returned when a particular HTTP method is used for a specific URL. For example: In order to return a response of "Reached example.com/test1" when a GET request is sent to a URL "http://example.com/test1" the following code can be used:

FakeWeb.register_uri(:get, "http://example.com/test1", :body => "Reached example.com/test1")

In Ruby, Net:HTTP is a module used for HTTP requests.[9] Using this module when the URL is queried for a GET, the following response is recorded:

Net::HTTP.get(URI.parse("http://example.com/test1"))

Response - "Reached example.com/test1"

It is also possible to provide responses for multiple URL's. This can be specified by using a Regular Expression.

FakeWeb.register_uri(:get, %r|http://example\.com/|, :body => "Hello World!") 

Any GET request to a URL which has example.com followed by a specific subpage or link always receives the response of "Hello World!"

Net::HTTP.get(URI.parse("http://example.com/test3"))

Response - "Hello World!"

Replaying a recorded response

[edit]

If the response to an HTTP request to a URL needs to be a pre-recorded response, the response can be stored beforehand and this can be used in the register_uri method to mimic the behaviour of a real page.

actual_response = `curl -is http://www.google.com/`
FakeWeb.register_uri(:get, "http://www.google.com/", :response => actual_response)

The response has been recorded in the actual_response variable. This can be used to replay the recorded response.

Net::HTTP.get(URI.parse("http://www.google.com/"))

Response - the recorded actual_response

Adding custom status and headers to the response

[edit]

In the previous examples, only the body of the response object was being changed. The status and the headers of a response can also be changed by using the following commands:

FakeWeb.register_uri(:get, "http://example.com/hello.txt", :body => "Hello", :status => ["404", "Not Found"]))

or

FakeWeb.register_uri(:get, "http://example.com/hello.txt", :body => "Hello", :content_type => "text/plain")

The response can be viewed by using the following commands:

Net::HTTP.start("example.com") do |req|
  response = req.get("/")
  response.code     # => "404"
  response.message  # => "Not Found"
  response.body     # => "Nothing to be found 'round here"
end

Responding to any HTTP method

[edit]

In the previous examples mostly the HTTP GET method has been used. In order to allow any method to be used as a parameter, use the 'any' parameter as an argument.

FakeWeb.register_uri(:any, "http://example.com", :body => "response for any HTTP method")

Using HTTP basic authentication

[edit]

When performing HTTP requests which need to be secure, authentication is an important concern. The userinfo strings can be added to the register_uri to fake requests which require authentication.

FakeWeb.register_uri(:get, "http://example.com/secret", :body => "Unauthorized", :status => ["401", "Unauthorized"])
FakeWeb.register_uri(:get, "http://user:pass@example.com/secret", :body => "Authorized")
Net::HTTP.start("example.com") do |http|
  req = Net::HTTP::Get.new("/secret")
  http.request(req)  # => "Unauthorized"
  req.basic_auth("user", "pass")
  http.request(req)  # => "Authorized"
end

Clearing registered URIs

[edit]

Fakeweb has a registry which only lasts for the duration of the execution of the program in which it is invoked. Hence in order to clear out the registry, the following command can be used:

Fakeweb.clean_registry

This invokes the clean_registry method of Fakeweb module which cleans the registry of the previous entries.

Blocking all real requests

[edit]

Fakeweb is mainly used while testing and hence, during this phase, if it is required to send the fake requests only to registered URI's and not to the other URI's, this can be done by using the 'allow_net_connect' feature of fakeweb, to prevent sending requests to real URI's. The following example illustrates this functionality:

FakeWeb.allow_net_connect = false
Net::HTTP.get(URI.parse("http://example.com/"))

Result: raises FakeWeb::NetConnectNotAllowedError

FakeWeb.allow_net_connect = true
Net::HTTP.get(URI.parse("http://example.com/"))

Result: FakeWeb is bypassed and the response from the live endpoint is returned.

Checking the last request

[edit]

If the last request needs to be retrieved in order to check for its content, so that the output of the current request can be debugged, the following command can be used:

Net::HTTP.get(URI.parse("http://example.com"))
FakeWeb.last_request  # => Net::HTTP::Get request object

Known Issues

[edit]

Parameters of the HTTP PUT and HTTP POST methods are ignored. If there is a requirement where responses need to be different for different request bodies, it is possible to do so by registering separate URLs and providing different responses to each.

Alternatives

[edit]

There exist a few alternatives to FakeWeb:

  • WebMock has functionalities similar to FakeWeb and is a RubyGem that is used to stub HTTP requests.[10]
  • VCR is another RubyGem that records the HTTP interactions that occur during a testing phase of a Ruby application and later replay them for future test executions.[10]

References

[edit]