Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  // Copyright 2006, 2007, 2008, 2009, 2010 The Apache Software Foundation
  //
  // Licensed under the Apache License, Version 2.0 (the "License");
  // you may not use this file except in compliance with the License.
  // You may obtain a copy of the License at
  //
  // http://www.apache.org/licenses/LICENSE-2.0
  //
  // Unless required by applicable law or agreed to in writing, software
 // distributed under the License is distributed on an "AS IS" BASIS,
 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
 package org.apache.tapestry5.test;
 
 import java.util.Map;
 
This class is used to run a Tapestry app in a single-threaded, in-process testing environment. You can ask it to render a certain page and check the DOM object created. You can also ask it to click on a link element in the DOM object to get the next page. Because no servlet container is required, it is very fast and you can directly debug into your code in your IDE.
 
 public class PageTester
 {
     private final Logger logger = LoggerFactory.getLogger(PageTester.class);
 
     private final Registry registry;
 
     private final TestableRequest request;
 
     private final TestableResponse response;
 
     private final RequestHandler requestHandler;
 
     public static final String DEFAULT_CONTEXT_PATH = "src/main/webapp";
 
     private static final String DEFAULT_SUBMIT_VALUE_ATTRIBUTE = "Submit Query";

    
Initializes a PageTester without overriding any services and assuming that the context root is in src/main/webapp.

 
     public PageTester(String appPackageString appName)
     {
         this(appPackageappName);
     }

    
Initializes a PageTester that acts as a browser and a servlet container to test drive your Tapestry pages.

Parameters:
appPackage The same value you would specify using the tapestry.app-package context parameter. As this testing environment is not run in a servlet container, you need to specify it.
appName The same value you would specify as the filter name. It is used to form the name of the module class for your app. If you don't have one, pass an empty string.
contextPath The path to the context root so that Tapestry can find the templates (if they're put there).
moduleClasses Classes of additional modules to load
 
     public PageTester(String appPackageString appNameString contextPathClass... moduleClasses)
     {
        assert InternalUtils.isNonBlank(appPackage);
        assert appName != null;
        assert InternalUtils.isNonBlank(contextPath);
        TapestryAppInitializer initializer = new TapestryAppInitializer(providerappName,
                .null);
        initializer.addModules(PageTesterModule.class);
        initializer.addModules(moduleClasses);
        initializer.addModules(provideExtraModuleDefs());
         = initializer.createRegistry();
         = .getService(TestableRequest.class);
         = .getService(TestableResponse.class);
        ApplicationGlobals globals = .getObject(ApplicationGlobals.classnull);
        globals.storeContext(new PageTesterContext(contextPath));
         = .getService("RequestHandler"RequestHandler.class);
    }

    
Overridden in subclasses to provide additional module definitions beyond those normally located. This implementation returns an empty array.
    protected ModuleDef[] provideExtraModuleDefs()
    {
        return new ModuleDef[0];
    }

    
Invoke this method when done using the PageTester; it shuts down the internal org.apache.tapestry5.ioc.Registry used by the tester.
    public void shutdown()
    {
        .cleanupThread();
        .shutdown();
    }

    
Returns the Registry that was created for the application.
    public Registry getRegistry()
    {
        return ;
    }

    
Allows a service to be retrieved via its service interface. Use getRegistry() for more complicated queries.

Parameters:
serviceInterface used to select the service
    public <T> T getService(Class<T> serviceInterface)
    {
        return .getService(serviceInterface);
    }

    
Renders a page specified by its name.

Parameters:
pageName The name of the page to be rendered.
Returns:
The DOM created. Typically you will assert against it.
    public Document renderPage(String pageName)
    {
        .clear().setPath("/" + pageName);
        while (true)
        {
            try
            {
                .clear();
                boolean handled = .service();
                if (!handled) { throw new RuntimeException(String.format(
                        "Request was not handled: '%s' may not be a valid page name."pageName)); }
                Link link = .getRedirectLink();
                if (link != null)
                {
                    setupRequestFromLink(link);
                    continue;
                }
                Document result = .getRenderedDocument();
                if (result == null)
                    throw new RuntimeException(String.format("Render of page '%s' did not result in a Document.",
                            pageName));
                return result;
            }
            catch (IOException ex)
            {
                throw new RuntimeException(ex);
            }
            finally
            {
                .cleanupThread();
            }
        }
    }

    
Simulates a click on a link.

Parameters:
linkElement The Link object to be "clicked" on.
Returns:
The DOM created. Typically you will assert against it.
    public Document clickLink(Element linkElement)
    {
        assert linkElement != null;
        validateElementName(linkElement"a");
        String href = extractNonBlank(linkElement"href");
        setupRequestFromURI(href);
        return runComponentEventRequest();
    }
    private String extractNonBlank(Element elementString attributeName)
    {
        String result = element.getAttribute(attributeName);
        if (InternalUtils.isBlank(result))
            throw new RuntimeException(String.format("The %s attribute of the <%s> element was blank or missing.",
                    attributeNameelement.getName()));
        return result;
    }
    private void validateElementName(Element elementString expectedElementName)
    {
        if (!element.getName().equalsIgnoreCase(expectedElementName))
            throw new RuntimeException(String.format("The element must be type '%s', not '%s'."expectedElementName,
                    element.getName()));
    }
    {
        while (true)
        {
            .clear();
            try
            {
                boolean handled = .service();
                if (!handled)
                    throw new RuntimeException(String.format("Request for path '%s' was not handled by Tapestry.",
                            .getPath()));
                Link link = .getRedirectLink();
                if (link != null)
                {
                    setupRequestFromLink(link);
                    continue;
                }
                Document result = .getRenderedDocument();
                if (result == null)
                    throw new RuntimeException(String.format("Render request '%s' did not result in a Document.",
                            .getPath()));
                return result;
            }
            catch (IOException ex)
            {
                throw new RuntimeException(ex);
            }
            finally
            {
                .cleanupThread();
            }
        }
    }
    private void setupRequestFromLink(Link link)
    {
        setupRequestFromURI(link.toRedirectURI());
    }
    private void setupRequestFromURI(String URI)
    {
        String linkPath = stripContextFromPath(URI);
        int comma = linkPath.indexOf('?');
        String path = comma < 0 ? linkPath : linkPath.substring(0, comma);
        .clear().setPath(path);
        if (comma > 0)
            decodeParametersIntoRequest(linkPath.substring(comma + 1));
    }
    private void decodeParametersIntoRequest(String queryString)
    {
        if (InternalUtils.isBlank(queryString))
            return;
        for (String term : queryString.split("&"))
        {
            int eqx = term.indexOf("=");
            String key = term.substring(0, eqx).trim();
            String value = term.substring(eqx + 1).trim();
            .loadParameter(keyvalue);
        }
    }
    private String stripContextFromPath(String path)
    {
        String contextPath = .getContextPath();
        if (contextPath.equals(""))
            return path;
        if (!path.startsWith(contextPath))
            throw new RuntimeException(String.format("Path '%s' does not start with context path '%s'."path,
                    contextPath));
        return path.substring(contextPath.length());
    }

    
Simulates a submission of the form specified. The caller can specify values for the form fields, which act as overrides on the values stored inside the elements.

Parameters:
form the form to be submitted.
parameters the query parameter name/value pairs
Returns:
The DOM created. Typically you will assert against it.
    public Document submitForm(Element formMap<StringStringparameters)
    {
        assert form != null;
        validateElementName(form"form");
        .clear().setPath(stripContextFromPath(extractNonBlank(form"action")));
        pushFieldValuesIntoRequest(form);
        overrideParameters(parameters);
        // addHiddenFormFields(form);
        // ComponentInvocation invocation = getInvocation(form);
        return runComponentEventRequest();
    }
    private void overrideParameters(Map<StringStringfieldValues)
    {
        for (Map.Entry<StringStringe : fieldValues.entrySet())
        {
            .overrideParameter(e.getKey(), e.getValue());
        }
    }
    private void pushFieldValuesIntoRequest(Element form)
    {
        Visitor visitor = new Visitor()
        {
            public void visit(Element element)
            {
                if (InternalUtils.isNonBlank(element.getAttribute("disabled")))
                    return;
                String name = element.getName();
                if (name.equals("input"))
                {
                    String type = extractNonBlank(element"type");
                    if (type.equals("radio") || type.equals("checkbox"))
                    {
                        if (InternalUtils.isBlank(element.getAttribute("checked")))
                            return;
                    }
                    // Assume that, if the element is a button/submit, it wasn't clicked,
                    // and therefore, is not part of the submission.
                    if (type.equals("button") || type.equals("submit"))
                        return;
                    // Handle radio, checkbox, text, radio, hidden
                    String value = element.getAttribute("value");
                    if (InternalUtils.isNonBlank(value))
                        .loadParameter(extractNonBlank(element"name"), value);
                    return;
                }
                if (name.equals("option"))
                {
                    String value = element.getAttribute("value");
                    // TODO: If value is blank do we use the content, or is the content only the
                    // label?
                    if (InternalUtils.isNonBlank(element.getAttribute("selected")))
                    {
                        String selectName = extractNonBlank(findAncestor(element"select"), "name");
                        .loadParameter(selectNamevalue);
                    }
                    return;
                }
                if (name.equals("textarea"))
                {
                    String content = element.getChildMarkup();
                    if (InternalUtils.isNonBlank(content))
                        .loadParameter(extractNonBlank(element"name"), content);
                    return;
                }
            }
        };
        form.visit(visitor);
    }

    
Simulates a submission of the form by clicking the specified submit button. The caller can specify values for the form fields.

Parameters:
submitButton the submit button to be clicked.
fieldValues the field values keyed on field names.
Returns:
The DOM created. Typically you will assert against it.
    public Document clickSubmit(Element submitButtonMap<StringStringfieldValues)
    {
        assert submitButton != null;
        assertIsSubmit(submitButton);
        Element form = getFormAncestor(submitButton);
        .clear().setPath(stripContextFromPath(extractNonBlank(form"action")));
        pushFieldValuesIntoRequest(form);
        overrideParameters(fieldValues);
        String value = submitButton.getAttribute("value");
        if (value == null)
            value = ;
        .overrideParameter(extractNonBlank(submitButton"name"), value);
        return runComponentEventRequest();
    }
    private void assertIsSubmit(Element element)
    {
        if (element.getName().equals("input"))
        {
            String type = element.getAttribute("type");
            if ("submit".equals(type))
                return;
        }
        throw new IllegalArgumentException("The specified element is not a submit button.");
    }
    private Element getFormAncestor(Element element)
    {
        return findAncestor(element"form");
    }
    private Element findAncestor(Element elementString ancestorName)
    {
        Element e = element;
        while (e != null)
        {
            if (e.getName().equalsIgnoreCase(ancestorName))
                return e;
            e = e.getContainer();
        }
        throw new RuntimeException(String.format("Could not locate an ancestor element of type '%s'."ancestorName));
    }

    
Sets the simulated browser's preferred language, i.e., the value returned from org.apache.tapestry5.services.Request.getLocale().

Parameters:
preferedLanguage preferred language setting
    public void setPreferedLanguage(Locale preferedLanguage)
    {
        .setLocale(preferedLanguage);
    }
New to GrepCode? Check out our FAQ X