cancel
Showing results for 
Search instead for 
Did you mean: 
resplin
Elite Collaborator
Elite Collaborator

Obsolete Pages{{Obsolete}}

The official documentation is at: http://docs.alfresco.com



Back to Web Scripts.

NOTE: This document describes features found in Alfresco v3 onwards (Older versions: v2)

NOTE: This document does not cover 3.4 changes. 3.4 introduces considerable changes with regard to packages, in particular the use of Spring Surf

NOTE: This whole section should now be considered EOLd


Introduction


This page describes various tools for testing Web Scripts.


Standalone Test Server


Web Scripts naturally live within a web server. This can hamper testing, in particular, the development of unit tests, or the testing of advanced Java Web Scripts.

To ease testing (and also to remove lengthy web application build/deploy times), the following standalone test harnesses are provided


Presentation Web Scripts: org.alfresco.web.scripts.TestWebScriptServer

Repository Web Scripts: org.alfresco.web.scripts.TestWebScriptRepoServer

Both support two modes of operation:


  • Mock Web Server (interactive testing)
  • Helper methods for executing web script requests (automated testing)

Mock Web Server


Just start the TestWebScriptServer or TestWebScriptRepoServer application (both support a main entry point) and interact with it via the one of the following commands:

   ##
   ##  Meta commands
   ##
  
   ok> help
  
       List this help.
  
   ok> r
  
       Repeat last command.
  
   ok> user [<userName>]
  
       Switch to specified <userName>.  If <userName> is omitted, the currently
       selected user is shown.
      
       A ticket may be specified instead of username.
  
   ok> quit | exit
  
       Quit this Web Script server.
  
   ##
   ##  HTTP Requests
   ##
  
   ok> get <path>
  
       Issue a HTTP GET request to the Web Script located at <path>.  The response
       is dumped to the console.
      
       <path> URL relative to /alfresco/service
      
       e.g. get /sample/blog/search?q=tutorial
  
   ok> put <path>
  
       Issue a HTTP PUT request to the Web Script located at <path>.  The response
       is dumped to the console.
      
       <path> URL relative to /alfresco/service
      
   ok> post <path>
  
       Issue a HTTP POST request to the Web Script located at <path>.  The response
       is dumped to the console.
      
       <path> URL relative to /alfresco/service
  
   ok> delete <path>
  
       Issue a HTTP DELETE request to the Web Script located at <path>.  The response
       is dumped to the console.
      
       <path> URL relative to /alfresco/service
      
   ok> tunnel <encoding> <method> <path>
  
       Tunnel a request via POST.
      
       The actual <method> is encoded as either the URL parameter named alf:method or
       the request header named X-HTTP-Method-Override as specified via the <encoding>
       parameter:
      
       param - encode method as URL parameter
       header - encode method in Request Header
      
       e.g. to tunnel 'get /index' via post (where method is encoded in header) issue
      
       tunnel header get /index
     
   ##
   ##  Request Header Commands
   ##
  
   ok> header
  
       Show all defined headers.
  
   ok> var <headerName>=<headerValue>
  
       Define or update a header value.
  
       <headerName> header name
       <headerValue> header value
  
       e.g.
  
       header alf-force-success=true
  
   ok> header <headerName>=
  
       Delete an existing header value.
  
       <headerName> header name
      
   ##
   ##  end
   ##

For example (to invoke our example blog search Web Script):

 ok> get /sample/helloworld?to=fred
TODO: update result
   <html>
    <body>
      <img src='/alfresco/images/logo/AlfrescoLogo32.png' alt='Alfresco' />
      Blog search: tutorial
      <br>
      <table>
       <tr>
         <td><img src='/alfresco/images/filetypes/_default.gif'/>
         <td><a href='/alfresco/download/direct/workspace/SpacesStore/d0ea49aa-cda3-11db-a118-718e716a085b/Alfresco-Tutorial.pdf'>Alfresco-Tutorial.pdf</a>
       </tr>
      </table>
    </body>
  </html>
78ms

Running Mock Test Server


As mentioned above, the Mock Test Server has a main method.  The easiest way to run it is through Eclipse, if you already have it setup for development.  Just use a RunAs Java Application and run TestWebScriptServer or TestWebScriptRepoServer.  You'll need to point your repository and a database at an existing repository.

Another way is to create a script that includes all the jars in WEB-INF\lib in the classpath, and starts up the server. 


Unit Test Helper Methods


Within a unit test, the following pattern may be used:

// retrieve an instance of the presentation test server
TestWebScriptServer server = TestWebScriptServer.getTestServer();

// or, retrieve an instance of the repository test server
// TestWebScriptServer server = TestWebScriptRepoServer.getTestServer();

// submit a request
MockHttpServletResponse res = server.submitRequest('get', '/sample/helloworld?to=fred');

// process response
byte[] content = res.getContentAsByteArray();
String contentAsString = res.getContentAsString();

Unit Testing a Web Script


When you write a data Web Script, it is recommended that you also write a corresponding unit test. This ensures that all elements of the script are working as expected. Re-running the test periodically also ensures that functionality and features do not regress as development progresses.

A Web Script unit test can be created by extending the base class org.alfresco.repo.web.scripts.BaseWebScriptTest. This base TestCase encapsulates a reference to an initialized TestWebScriptServer, which can be accessed and used to execute web scripts.

Within the TestWebScriptServer, the method protected Response sendRequest(Request req, int expectedStatus) is used to send a request taking a subclass of Request, validating the expected return status (i.e. 200 (ok)) and return a Response object. The subclasses of Request include:


  • GetRequest for the get verb
  • PostRequest for the post verb
  • PutRequest for the put verb
  • DeleteRequest for the delete verb

Each Request subclass indicates which HTTP method will be used when the request is submitted. The URL argument contains the URL of the web script that is to be submitted to the test web script server. The URL should not be fully qualified, instead it should start after the /alfresco/service part of a standard URL. For example /api/sites.

The expected status argument indicates the expected status code of the resulting response. If the actual status code resulting from the request is different from the expected code, an assert failure will be raised and the unit test will fail. If the received status code is 500 (internal error), the associated stack trace will be outputted to standard out for information.

The post and put methods also take a body and content type arguments. The body string makes up the body of the request that is sent to the test server, whilst the content type is set on the contentType header value. For example, application/json.

Example

   package org.someco;
  
   import org.alfresco.repo.security.authentication.AuthenticationComponent;
   import org.alfresco.repo.site.SiteModel;
   import org.alfresco.service.cmr.site.SiteService;
   import org.alfresco.repo.web.scripts.BaseWebScriptTest;
   import org.alfresco.util.GUID;
   import org.alfresco.web.scripts.TestWebScriptServer.GetRequest;
   import org.alfresco.web.scripts.TestWebScriptServer.PostRequest;
   import org.alfresco.web.scripts.TestWebScriptServer.Response;
   import org.json.JSONArray;
   import org.json.JSONObject;
  
   public class SiteServiceTest extends BaseWebScriptTest {
       private static final String URL_SITES = '/api/sites';
       private static final String URL_MEMBERSHIPS = '/memberships';
       private static final String USER_TWO = 'UserTwo';
       private static final String USER_ONE = 'UserOne';
       private static final String USER_ADMIN = 'admin';
       private SiteService siteService;
       private AuthenticationComponent authenticationComponent;
  
       public void setUp() throws Exception {
           super.setUp();
           this.siteService = (SiteService) getServer().getApplicationContext()
               .getBean('SiteService');
           this.authenticationComponent = (AuthenticationComponent) getServer()
               .getApplicationContext().getBean('authenticationComponent');
  
           // Authenticate as user
           this.authenticationComponent.setCurrentUser(USER_ADMIN);
       }
  
       public void testPostMemberships() throws Exception {
  
           // Create a site
           String shortName = GUID.generate();
           siteService.createSite('myPreset', shortName, 'myTitle',
                   'myDescription', true);
  
           // Build the JSON membership object
           JSONObject membership = new JSONObject();
           membership.put('role', SiteModel.SITE_CONSUMER);
           JSONObject person = new JSONObject();
           person.put('userName', USER_TWO);
           membership.put('person', person);
  
           // Post the memebership
           Response response = sendRequest(new PostRequest(URL_SITES + '/'
                   + shortName + URL_MEMBERSHIPS, membership.toString(),
                   'application/json'), 200);
           JSONObject result = new JSONObject(response.getContentAsString());
  
           // Check the result
           assertEquals(SiteModel.SITE_CONSUMER, membership.get('role'));
           assertEquals(USER_TWO, membership.getJSONObject('person').get(
                   'userName'));
  
           // Get the membership list
           response = sendRequest(new GetRequest(URL_SITES + '/' + shortName
               + URL_MEMBERSHIPS), 200);
           JSONArray result2 = new JSONArray(response.getContentAsString());
           assertNotNull(result2);
           assertEquals(2, result2.length());
       }
  
       public void testGetMembership() throws Exception {
  
           // Create a site
           String shortName = GUID.generate();
           siteService.createSite('myPreset', shortName, 'myTitle',
               'myDescription', true);
  
           // Test error conditions
           sendRequest(new GetRequest(URL_SITES + '/badsite' + URL_MEMBERSHIPS
               + '/' + USER_ONE), 404);
           sendRequest(new GetRequest(URL_SITES + '/' + shortName
               + URL_MEMBERSHIPS + '/baduser'), 404);
           sendRequest(new GetRequest(URL_SITES + '/' + shortName
               + URL_MEMBERSHIPS + '/' + USER_TWO), 404);
  
           // Test GET Membership
           Response response = sendRequest(new GetRequest(URL_SITES + '/'
               + shortName + URL_MEMBERSHIPS + '/' + USER_ONE), 200);
           JSONObject result = new JSONObject(response.getContentAsString());
           // Check the result
           assertEquals(SiteModel.SITE_MANAGER, result.get('role'));
           assertEquals(USER_ONE, result.getJSONObject('person').get('userName'));
       }
   }

Web Scripts
3.0
Testing