Sahi Pro - URL Mock APIs


Mocks are used to mock out responses to urls which match a particular pattern.

_addMock

Since Sahi Pro: 3.5
Since Sahi OS: 2

_addMock($pattern[, $class_method])

Arguments
$patternstring URL regex pattern as a string.
$class_methodstring optional Combination of class and method names which will process this URL pattern.

Details

Forces the proxy to process certain patterns of urls differently.
If class_method is not specified, sends back a simple HTML blank page.

_mockImage

Since Sahi Pro: 3.5
Since Sahi OS: 2

_mockImage($pattern[, $class_method])

Arguments
$patternstring URL regex pattern as a string.
$class_methodstring optional Combination of class and method names which will process this URL pattern.

Details

Similar to _addMock, but by default sends back an image.

_removeMock

Since Sahi Pro: 3.5
Since Sahi OS: 2

_removeMock($pattern)

Arguments
$patternstring URL regex pattern as a string.
Removes the mock behavior added via _addMock or _mockImage for that pattern.

Details


Example:
A web page has embedded advertisements in an iframe
and we do not wish to test these advertisements everytime we test our web page.

We can add a mock by specifying
_addMock("www[.]adserver[.]com", "sahi.ext.MyCustomMock_filterAds");
to our script.

Whenever Sahi encounters a URL request which matches www[.]adserver[.]com
It will delegate the response handling to sahi.ext.MyCustomMock's filterAds method.
One can call any class's any method, as long as the method has one of these two signatures.

public net.sf.sahi.response.HttpResponse methodName (net.sf.sahi.request.HttpRequest request);
public void methodName(net.sf.sahi.request.HttpRequest request);

If _addMock("pattern") is called without a second parameter,
net.sf.sahi.command.MockResponder.simple(HttpRequest) is used to process the request.
This response uses template at sahi/htdocs/spr/simpleMock.htm.
One can modify this to show a generic mock response.
By default this response just shows the mocked url.

For images, one can use _mockImage, which is the same as _addMock except that it by default calls
net.sf.sahi.command.MockResponder.mockImage(HttpRequest) which returns
a simple image at sahi/htdocs/spr/mock.gif

This script may explain mocks better:

_navigateTo("http://sahi.co.in/demo/index.htm");
// assert a particular link exists on that page
_assertNotNull(_link("Link Test"));
// --
// add mock
_addMock(".*sahi[.]co[.]in.*");
// --
_navigateTo("http://sahi.co.in/demo/index.htm", true);
// link should not exist
_assertNull(_link("Link Test"));
// Instead the page contains the mocked url
_assert(_containsText(document.body, "http://sahi.co.in/demo/index.htm"));
// --
// remove mock
_removeMock(".*sahi[.]co[.]in.*");
// --
_navigateTo("http://sahi.co.in/demo/index.htm", true);
// Mock removed. The link is visible again on the page.
_assertNotNull(_link("Link Test"));