/**
   * Simulates the use case when the {@code HttpServletResponse.encodeURL()} changes the context
   * path.
   */
  public void testStripContextPathFromURLWhenOutBoundRewriteRuleChangingContextPath()
      throws Exception {
    this.mockXWiki.stubs().method("getWebAppPath").will(returnValue("xwiki/"));

    Mock xwikiResponse = mock(XWikiResponse.class);
    xwikiResponse.stubs().method("setLocale");
    xwikiResponse
        .stubs()
        .method("encodeURL")
        .will(
            new CustomStub("Implements XWikiResponse.encodeURL") {
              @Override
              public Object invoke(Invocation invocation) throws Throwable {
                return "http://localhost:8080/anothercontext"
                    + ";jsessionid=0AF95AFB8997826B936C0397DF6A0C7F?language=en";
              }
            });
    getContext().setResponse((XWikiResponse) xwikiResponse.proxy());

    // Note: the passed URL to stripContextPathFromURL() has also gone through encodeURL() which is
    // why its
    // context path has been changed from "xwiki" to "anothercontext".
    assertEquals(
        "/something",
        this.authService.stripContextPathFromURL(
            new URL("http://localhost:8080/anothercontext/something"), getContext()));
  }
  /**
   * Test that SomeUser is correctly authenticated as XWiki.SomeUser when xwiki:SomeUser is entered
   * as username.
   */
  public void testLoginWithWikiPrefix() throws Exception {
    // Setup a simple user profile document
    XWikiDocument userDoc = new XWikiDocument("XWiki", "SomeUser");
    // Mock the XWikiUsers object, since a real objects requires more mocking on the XWiki object
    Mock mockUserObj = mock(BaseObject.class, new Class[] {}, new Object[] {});
    mockUserObj.stubs().method("setDocumentReference");
    mockUserObj.stubs().method("setNumber");
    mockUserObj.stubs().method("getStringValue").with(eq("password")).will(returnValue("pass"));
    mockUserObj.stubs().method("setOwnerDocument");
    userDoc.addObject("XWiki.XWikiUsers", (BaseObject) mockUserObj.proxy());

    // Make a simple XWiki.XWikiUsers class that will contain a default password field
    BaseClass userClass = new BaseClass();
    userClass.addPasswordField("password", "Password", 20);
    userClass.setClassName("XWiki.XWikiUsers");

    // Prepare the XWiki mock
    this.mockXWiki
        .stubs()
        .method("getDocument")
        .with(eq("XWiki.SomeUser"), eq(this.getContext()))
        .will(returnValue(userDoc));
    this.mockXWiki
        .stubs()
        .method("getClass")
        .with(eq("XWiki.XWikiUsers"), eq(this.getContext()))
        .will(returnValue(userClass));
    this.mockXWiki.stubs().method("exists").will(returnValue(true));

    // Finally run the test: Using xwiki:Admin should correctly authenticate the Admin user
    Principal principal =
        this.authService.authenticate("xwiki:SomeUser", "pass", this.getContext());
    assertNotNull(principal);
    assertEquals("xwiki:XWiki.SomeUser", principal.getName());
  }
  /** See XWIKI-5277 for details. */
  public void testGetRenderedContentCleansVelocityMacroCache() throws Exception {
    // Make sure we start not in the rendering engine since this is what happens in real: a document
    // is
    // called by a template thus outside of the rendering engine.
    getContext().remove("isInRenderingEngine");

    // We display a text area since we know that rendering a text area will call getRenderedContent
    // inside our top
    // level getRenderedContent call, thus testing that velocity macros are not removed during
    // nested calls to
    // getRenderedContent.
    this.baseObject.setLargeStringValue(
        "area", "{{velocity}}#macro(testmacrocache)ok#end{{/velocity}}");
    this.document.setContent("{{velocity}}$doc.display(\"area\")#testmacrocache{{/velocity}}");
    this.document.setSyntax(Syntax.XWIKI_2_0);

    // We need to put the current doc in the Velocity Context since it's normally set before the
    // rendering is
    // called in the execution flow.
    VelocityManager originalVelocityManager = getComponentManager().lookup(VelocityManager.class);
    VelocityContext vcontext = originalVelocityManager.getVelocityContext();
    vcontext.put("doc", new Document(this.document, getContext()));

    // Register a Mock for the VelocityManager to bypass skin APIs that we would need to mock
    // otherwise.
    Mock mockVelocityManager = registerMockComponent(VelocityManager.class);
    mockVelocityManager.stubs().method("getVelocityContext").will(returnValue(vcontext));

    VelocityEngine vengine =
        getComponentManager()
            .lookup(VelocityFactory.class)
            .createVelocityEngine("default", new Properties());
    // Save the number of cached macro templates in the Velocity engine so that we can compare after
    // the
    // document is rendered.
    JMXVelocityEngineMBean mbean = new JMXVelocityEngine(vengine);
    int cachedMacroNamespaceSize = mbean.getTemplates().values().size();
    assertTrue(cachedMacroNamespaceSize > 0);

    mockVelocityManager.stubs().method("getVelocityEngine").will(returnValue(vengine));

    // $doc.display will ask for the syntax of the current document so we need to mock it.
    this.mockXWiki
        .stubs()
        .method("getCurrentContentSyntaxId")
        .with(eq("xwiki/2.0"), ANYTHING)
        .will(returnValue("xwiki/2.0"));

    // Verify that the macro located inside the TextArea has been taken into account when executing
    // the doc's
    // content.
    assertEquals("<p>ok</p>", this.document.getRenderedContent(getContext()));

    // Now verify that the Velocity Engine doesn't contain any more cached macro namespace to prove
    // that
    // getRenderedContent has correctly cleaned the Velocity macro cache.
    assertEquals(cachedMacroNamespaceSize, mbean.getTemplates().values().size());
  }
예제 #4
0
  protected void setUp() throws Exception {
    super.setUp();

    mockRequest = mock(HttpServletRequest.class);

    mockRequest
        .stubs()
        .method("getParameterNames")
        .will(returnValue(new Vector<String>().elements()));
    mockRequest.stubs().method("getRequestURI").will(returnValue("/YourRhn.do"));
  }
  @Override
  protected void registerComponents() throws Exception {
    super.registerComponents();

    // Setup display configuration.
    Mock mockDisplayConfiguration = registerMockComponent(DisplayConfiguration.class);
    mockDisplayConfiguration
        .stubs()
        .method("getDocumentDisplayerHint")
        .will(returnValue("default"));
    mockDisplayConfiguration.stubs().method("getTitleHeadingDepth").will(returnValue(2));
  }
  protected void setUp() throws Exception {
    super.setUp();

    getContext().setDoc(new XWikiDocument());

    XWiki xwiki = new XWiki();

    Mock mockXWikiStore =
        mock(
            XWikiHibernateStore.class,
            new Class[] {XWiki.class, XWikiContext.class},
            new Object[] {xwiki, getContext()});
    xwiki.setStore((XWikiStoreInterface) mockXWikiStore.proxy());

    Mock mockXWikiRenderingEngine = mock(XWikiRenderingEngine.class);
    mockXWikiRenderingEngine
        .stubs()
        .method("interpretText")
        .will(
            new CustomStub("Implements XWikiRenderingEngine.interpretText") {
              public Object invoke(Invocation invocation) throws Throwable {
                return invocation.parameterValues.get(0);
              }
            });

    xwiki.setRenderingEngine((XWikiRenderingEngine) mockXWikiRenderingEngine.proxy());

    getContext().setWiki(xwiki);
  }
 public void testHJBConnectionSetsExceptionListenerOnConstruction() {
   Mock mockConnection = connectionBuilder.createMockConnection();
   registerToVerify(mockConnection);
   mockConnection.stubs().method("setExceptionListener");
   Connection testConnection = (Connection) mockConnection.proxy();
   new HJBConnection(testConnection, 0);
 }
  public void testGetActionWhenActionsContainerAlreadyExists() {
    MutablePicoContainer requestContainer = new DefaultPicoContainer();
    requestContainer.registerComponentInstance(TestService.class, service);
    MutablePicoContainer actionsContainer = new DefaultPicoContainer(requestContainer);

    requestMock
        .stubs()
        .method("getAttribute")
        .with(eq(KeyConstants.ACTIONS_CONTAINER))
        .will(returnValue(actionsContainer));

    StrutsTestAction action1 =
        (StrutsTestAction) actionFactory.getAction(request, mapping1, servlet);
    StrutsTestAction action2 =
        (StrutsTestAction) actionFactory.getAction(request, mapping2, servlet);
    TestAction action3 = (TestAction) actionFactory.getAction(request, mapping1, servlet);
    TestAction action4 = (TestAction) actionFactory.getAction(request, mapping2, servlet);

    assertNotNull(action1);
    assertNotNull(action2);
    assertNotSame(action1, action2);
    assertSame(action1, action3);
    assertSame(action2, action4);

    assertSame(action1, actionsContainer.getComponentInstance("/myPath1"));
    assertSame(action2, actionsContainer.getComponentInstance("/myPath2"));

    assertSame(service, action1.getService());
    assertSame(service, action2.getService());

    assertNotNull(action1.getServlet());
    assertNotNull(action2.getServlet());
    assertSame(servlet, action1.getServlet());
    assertSame(servlet, action2.getServlet());
  }
  protected void setUp() {
    String actionType = StrutsTestAction.class.getName();

    mapping1 = new ActionMapping();
    mapping1.setPath("/myPath1");
    mapping1.setType(actionType);

    mapping2 = new ActionMapping();
    mapping2.setPath("/myPath2");
    mapping2.setType(actionType);

    requestMock.stubs().method("getSession").will(returnValue(session));
    sessionMock.stubs().method("getServletContext").will(returnValue(servletContext));

    actionFactory = new ActionFactory();
    service = new TestService();
  }
  public void testMBeanInfoIsDeterminedIfKeyIsType() {
    final PersonMBean person = new OtherPerson();

    final Mock mockComponentAdapter = mock(ComponentAdapter.class);
    mockComponentAdapter.stubs().method("getComponentKey").will(returnValue(Person.class));
    mockComponentAdapter
        .stubs()
        .method("getComponentImplementation")
        .will(returnValue(person.getClass()));

    pico.addAdapter((ComponentAdapter) mockComponentAdapter.proxy());
    pico.addComponent(Person.class.getName() + "MBeanInfo", Person.createMBeanInfo());

    final MBeanInfo info =
        mBeanProvider.provide(pico, (ComponentAdapter) mockComponentAdapter.proxy());
    assertNotNull(info);
    assertEquals(Person.createMBeanInfo().getDescription(), info.getDescription());
  }
  public void testStopInvokesDecorateeConnection() throws Exception {
    Mock mockConnection = connectionBuilder.createMockConnection();
    registerToVerify(mockConnection);
    mockConnection.stubs().method("setExceptionListener");
    mockConnection.expects(once()).method("stop");
    Connection testConnection = (Connection) mockConnection.proxy();

    HJBConnection h = new HJBConnection(testConnection, 0);
    h.stop();
  }
 private void injectMockAppContextTo(KeywordBeanLoader beanLoader) {
   appContext.stubs();
   appContext.expects(once()).method("refresh");
   appContext
       .expects(once())
       .method("getBeansOfType")
       .with(eq(Object.class))
       .will(returnValue(keywordBeans));
   beanLoader.context = (GenericApplicationContext) appContext.proxy();
 }
  public void testCreateSessionInvokesDecorateeConnection() {
    Mock mockConnection = connectionBuilder.createMockConnection();
    registerToVerify(mockConnection);
    mockConnection.stubs().method("setExceptionListener");
    mockConnection.expects(once()).method("createSession");
    Connection testConnection = (Connection) mockConnection.proxy();

    HJBConnection h = new HJBConnection(testConnection, 0);
    h.createSession(true, 1);
  }
  public void testSetExceptionListenerNeverInvokesDecorateeConnection() {
    Mock mockConnection = connectionBuilder.createMockConnection();
    registerToVerify(mockConnection);
    mockConnection.stubs().method("setExceptionListener");
    Connection testConnection = (Connection) mockConnection.proxy();

    HJBConnection h = new HJBConnection(testConnection, 0);
    h.setExceptionListener(null);
    h.setExceptionListener(null);
  }
예제 #15
0
  public final void testExecuteWhenRequestHasNoParams() throws Exception {
    mockRequest
        .stubs()
        .method("getParameterNames")
        .will(returnValue(new Vector<String>().elements()));

    CreateRedirectURI command = new CreateRedirectURI();
    String redirectUrl = command.execute(getMockRequest());

    assertEquals("/YourRhn.do?", redirectUrl);
  }
예제 #16
0
  public final void testExecuteWhenRedirectURIExceedsMaxLength() throws Exception {
    String url =
        StringUtils.rightPad("/YourRhn.do", (int) CreateRedirectURI.MAX_URL_LENGTH + 1, "x");

    mockRequest.stubs().method("getRequestURI").will(returnValue(url));

    CreateRedirectURI command = new CreateRedirectURI();
    String redirectUrl = command.execute(getMockRequest());

    assertEquals(LoginAction.DEFAULT_URL_BOUNCE, redirectUrl);
  }
 public void testAutomaticallyNamesTextFieldWithoutName() {
   textField.setName(null);
   new JFrame().getContentPane().add(textField);
   mockRecorder
       .expects(once())
       .method("record")
       .with(eq(new EnterTextEvent("JTextField_1", "abc")));
   recorder.componentShown(textField);
   mockVisibility.stubs().method("isShowingAndHasFocus").will(returnValue(true));
   textField.setText("abc");
 }
  public void testGetSessions() {
    Mock mockConnection = connectionBuilder.createMockConnection();
    registerToVerify(mockConnection);
    mockConnection.stubs().method("setExceptionListener");
    mockConnection.expects(atLeastOnce()).method("createSession");
    Connection testConnection = (Connection) mockConnection.proxy();

    HJBConnection h = new HJBConnection(testConnection, 0);
    h.createSession(true, 1);
    assertEquals("1 session should have been added", 1, h.getActiveSessions().size());
    h.createSession(true, 1);
    assertEquals("2 sessions should have been added", 2, h.getActiveSessions().size());
  }
  public void testCreateDurableConnectionConsumerAlwaysThrowsHJBException() {
    Mock mockConnection = connectionBuilder.createMockConnection();
    registerToVerify(mockConnection);
    mockConnection.stubs().method("setExceptionListener");
    mockConnection.expects(never()).method("createDurableConnectionConsumer");
    Connection testConnection = (Connection) mockConnection.proxy();

    HJBConnection h = new HJBConnection(testConnection, 0);
    try {
      h.createDurableConnectionConsumer(null, null, null, null, 0);
      fail("An HJBException should have been thrown");
    } catch (HJBException e) {
    }
  }
  @Test
  public void pluginRegistersWithServer() {
    Mock mockServer = mock(SBuildServer.class);
    mockServer.expects(once()).method("addListener");
    Mock mockPluginDescriptor = mock(PluginDescriptor.class);
    mockPluginDescriptor.stubs();
    SBuildServer server = (SBuildServer) mockServer.proxy();
    PluginDescriptor descriptor = (PluginDescriptor) mockPluginDescriptor.proxy();

    ExampleServerPlugin plugin = new ExampleServerPlugin(server, descriptor);
    plugin.register();

    verify();
  }
 public void testEnteringTextPostsEnterEvent() {
   mockRecorder
       .expects(once())
       .method("record")
       .with(eq(new EnterTextEvent("testTextField", "abc")));
   recorder.componentShown(textField);
   mockVisibility.stubs().method("isShowingAndHasFocus").will(returnValue(true));
   textField.setText("abc");
   mockRecorder.expects(once()).method("record").with(eq(new EnterTextEvent("testTextField", "")));
   mockRecorder
       .expects(once())
       .method("record")
       .with(eq(new EnterTextEvent("testTextField", "def")));
   textField.setText("def");
 }
  public void testBadActionType() {
    MutablePicoContainer actionsContainer = new DefaultPicoContainer();
    requestMock
        .stubs()
        .method("getAttribute")
        .with(eq(KeyConstants.ACTIONS_CONTAINER))
        .will(returnValue(actionsContainer));

    mapping1.setType("/i/made/a/typo");
    try {
      actionFactory.getAction(request, mapping1, servlet);
      fail("PicoIntrospectionException should have been raised");
    } catch (PicoIntrospectionException e) {
      // expected
    }
  }
예제 #23
0
  public final void testExecuteWhenRequestHasParams() throws Exception {
    String paramName = "foo";
    String paramValue = "param value = bar#$%!";

    String expected = "/YourRhn.do?foo=" + URLEncoder.encode(paramValue, "UTF-8") + "&";

    Vector<String> paramNames = new Vector<String>();
    paramNames.add(paramName);

    mockRequest.stubs().method("getParameterNames").will(returnValue(paramNames.elements()));
    mockRequest.stubs().method("getParameter").with(eq(paramName)).will(returnValue(paramValue));

    CreateRedirectURI command = new CreateRedirectURI();
    String redirectURI = command.execute(getMockRequest());

    assertEquals(expected, redirectURI);
  }
  public void testClosePropagatesJMSException() throws Exception {
    Mock mockConnection = connectionBuilder.createMockConnection();
    registerToVerify(mockConnection);
    mockConnection.stubs().method("setExceptionListener");
    mockConnection
        .expects(once())
        .method("close")
        .will(throwException(new JMSException("thrown as test")));
    Connection testConnection = (Connection) mockConnection.proxy();

    HJBConnection h = new HJBConnection(testConnection, 0);
    try {
      h.close();
      fail("A JMSException should have been thrown");
    } catch (JMSException e) {
    }
  }
  public void testCreateSessionThrowsHJBExceptionOnJMSException() {
    Mock mockConnection = connectionBuilder.createMockConnection();
    registerToVerify(mockConnection);
    mockConnection.stubs().method("setExceptionListener");
    mockConnection
        .expects(once())
        .method("createSession")
        .will(throwException(new JMSException("thrown as a test")));
    Connection testConnection = (Connection) mockConnection.proxy();

    try {
      HJBConnection h = new HJBConnection(testConnection, 0);
      h.createSession(true, 1);
      fail("An HJBException should have been thrown");
    } catch (HJBException e) {
    }
  }
  public void testStripContextPathFromURLWhenRootWebAppAndJSessionId() throws Exception {
    this.mockXWiki.stubs().method("getWebAppPath").will(returnValue(""));

    // Simulate a rewrite filter that would add a jsession id and add a leading slash!
    Mock xwikiResponse = mock(XWikiResponse.class);
    xwikiResponse
        .stubs()
        .method("encodeURL")
        .with(eq("http://localhost:8080"))
        .will(
            new CustomStub("Implements XWikiResponse.encodeURL") {
              @Override
              public Object invoke(Invocation invocation) throws Throwable {
                return "http://localhost:8080/;jsessionid=0AF95AFB8997826B936C0397DF6A0C7F";
              }
            });
    getContext().setResponse((XWikiResponse) xwikiResponse.proxy());

    assertEquals(
        "/something",
        this.authService.stripContextPathFromURL(
            new URL("http://localhost:8080/something"), getContext()));
  }
  public void testCreateSessionAddsANewCommandRunner() {
    Mock mockConnection = connectionBuilder.createMockConnection();
    Connection testConnection = (Connection) mockConnection.proxy();
    registerToVerify(mockConnection);
    mockConnection.stubs().method("setExceptionListener");
    mockConnection.expects(once()).method("createSession");

    HJBConnection h = new HJBConnection(testConnection, 0);
    try {
      h.getSessionCommandRunner(0);
      fail("should throw exception");
    } catch (IndexOutOfBoundsException e) {
    }
    h.createSession(true, 1);
    assertNotNull("should exist", h.getSessionCommandRunner(0));
    try {
      h.getSessionCommandRunner(1);
      fail("should throw exception");
    } catch (IndexOutOfBoundsException e) {
    }
    h.createSession(true, 1);
    assertNotNull("should exist", h.getSessionCommandRunner(1));
  }
  /**
   * {@inheritDoc}
   *
   * @see junit.framework.TestCase#setUp()
   */
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    this.databases.put(MAIN_WIKI_NAME, new HashMap<String, XWikiDocument>());

    XWiki xwiki =
        new XWiki() {
          public XWikiDocument getDocument(String fullname, XWikiContext context)
              throws XWikiException {
            return XWikiServletURLFactoryTest.this.getDocument(
                Utils.getComponent(DocumentReferenceResolver.class, "currentmixed")
                    .resolve(fullname));
          }

          public XWikiDocument getDocument(
              DocumentReference documentReference, XWikiContext context) throws XWikiException {
            return XWikiServletURLFactoryTest.this.getDocument(documentReference);
          }

          public String getXWikiPreference(
              String prefname, String defaultValue, XWikiContext context) {
            return defaultValue;
          }

          protected void registerWikiMacros() {}
        };
    xwiki.setConfig((this.config = new XWikiConfig()));
    xwiki.setDatabase(getContext().getDatabase());

    Mock mockXWikiRequest = mock(XWikiRequest.class, new Class[] {}, new Object[] {});
    mockXWikiRequest.stubs().method("getScheme").will(returnValue("http"));
    mockXWikiRequest
        .stubs()
        .method("isSecure")
        .will(
            new CustomStub("Implements ServletRequest.isSecure") {
              public Object invoke(Invocation invocation) throws Throwable {
                return secure;
              }
            });
    mockXWikiRequest.stubs().method("getServletPath").will(returnValue(""));
    mockXWikiRequest.stubs().method("getContextPath").will(returnValue("/xwiki"));
    mockXWikiRequest
        .stubs()
        .method("getHeader")
        .will(
            new CustomStub("Implements HttpServletRequest.getHeader") {
              public Object invoke(Invocation invocation) throws Throwable {
                String headerName = (String) invocation.parameterValues.get(0);
                return httpHeaders.get(headerName);
              }
            });

    getContext().setWiki(xwiki);
    getContext().setRequest((XWikiRequest) mockXWikiRequest.proxy());

    // Create sub-wikis.
    createWiki("wiki1");
    createWiki("wiki2");

    getContext().setURL(new URL("http://127.0.0.1/xwiki/view/InitialSpace/InitialPage"));

    this.urlFactory.init(getContext());
  }
  /**
   * {@inheritDoc}
   *
   * @see com.xpn.xwiki.test.AbstractBridgedXWikiComponentTestCase#setUp()
   */
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    XWikiConfig config = new XWikiConfig();

    Mock mockServletContext = mock(ServletContext.class);
    ByteArrayInputStream bais =
        new ByteArrayInputStream("code=wiki:code:type:content".getBytes("UTF-8"));
    mockServletContext
        .stubs()
        .method("getResourceAsStream")
        .with(eq("/templates/macros.txt"))
        .will(returnValue(bais));
    mockServletContext
        .stubs()
        .method("getResourceAsStream")
        .with(eq("/WEB-INF/oscache.properties"))
        .will(returnValue(new ByteArrayInputStream("".getBytes("UTF-8"))));
    mockServletContext
        .stubs()
        .method("getResourceAsStream")
        .with(eq("/WEB-INF/oscache-local.properties"))
        .will(returnValue(new ByteArrayInputStream("".getBytes("UTF-8"))));
    XWikiServletContext engineContext =
        new XWikiServletContext((ServletContext) mockServletContext.proxy());

    xwiki =
        new XWiki(config, getContext(), engineContext, false) {
          public String getSkin(XWikiContext context) {
            return "skin";
          }

          public String getXWikiPreference(
              String prefname, String defaultValue, XWikiContext context) {
            return defaultValue;
          }

          public String getSpacePreference(
              String prefname, String defaultValue, XWikiContext context) {
            return defaultValue;
          }

          protected void registerWikiMacros() {}

          public XWikiRightService getRightService() {
            return new XWikiRightServiceImpl() {
              public boolean hasProgrammingRights(XWikiDocument doc, XWikiContext context) {
                return true;
              }
            };
          }
        };
    xwiki.setVersion("1.0");

    // Ensure that no Velocity Templates are going to be used when executing Velocity since
    // otherwise
    // the Velocity init would fail (since by default the macros.vm templates wouldn't be found as
    // we're
    // not providing it in our unit test resources).
    xwiki.getConfig().setProperty("xwiki.render.velocity.macrolist", "");

    this.engine = (DefaultXWikiRenderingEngine) xwiki.getRenderingEngine();

    // Make sure the wiki in the context will say that we have programming permission.
    getContext().setWiki(this.xwiki);
  }