/**
   * 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()));
  }
Example #2
0
 public void createUserWithGroup(LdapTest t, final String dn, String group) {
   role.expects(atLeastOnce())
       .method("createGroup")
       .with(t.eq(group), MockObjectSupportTestCase.NULL, t.eq(false))
       .will(returnValue(101L));
   role.expects(once()).method("createExperimenter").will(returnValue(101L));
 }
Example #3
0
 private List extractors(final Mock handler1, final Mock handler2) {
   SAXBasedExtractor[] extractors =
       new SAXBasedExtractor[] {
         (SAXBasedExtractor) handler1.proxy(), (SAXBasedExtractor) handler2.proxy()
       };
   return Arrays.asList(extractors);
 }
 public void testHJBConnectionSetsExceptionListenerOnConstruction() {
   Mock mockConnection = connectionBuilder.createMockConnection();
   registerToVerify(mockConnection);
   mockConnection.stubs().method("setExceptionListener");
   Connection testConnection = (Connection) mockConnection.proxy();
   new HJBConnection(testConnection, 0);
 }
  /**
   * 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());
  }
  public void testApplicationContainerExists() {
    MutablePicoContainer appContainer = new DefaultPicoContainer();
    appContainer.registerComponentInstance(TestService.class, service);

    requestMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.ACTIONS_CONTAINER))
        .will(returnValue(null));
    requestMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.REQUEST_CONTAINER))
        .will(returnValue(null));
    sessionMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.SESSION_CONTAINER))
        .will(returnValue(null));
    servletContextMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.APPLICATION_CONTAINER))
        .will(returnValue(appContainer));
    requestMock
        .expects(once())
        .method("setAttribute")
        .with(eq(KeyConstants.ACTIONS_CONTAINER), isA(MutablePicoContainer.class));

    TestAction action = (TestAction) actionFactory.getAction(request, mapping1, servlet);
    assertNotNull(action);
    assertSame(service, action.getService());
  }
 public void testBuscarClientesPorClave() {
   final String CLAVE = "U050008";
   Mock mockDao = mock(ClienteDao.class);
   mockDao.expects(once()).method("buscarClientesPorClave").with(this.eq(CLAVE));
   manager.setClienteDao((ClienteDao) mockDao.proxy());
   manager.buscarClientesPorClave(CLAVE);
 }
  public void testMakeObjectConnectsAndOtherwiseInitializesConnections()
      throws LDAPException, UnsupportedEncodingException {

    setConnectionManagerConfigExpectations();
    factory.setConnectionManager(connMgr);
    mockConn.expects(once()).method("setConnectionManager").with(same(connMgr));
    mockConn.expects(once()).method("setConstraints").with(NOT_NULL); // TODO make more specific
    mockConn
        .expects(once())
        .method("connect")
        .with(eq(connMgrConfig.getLdapHost()), eq(connMgrConfig.getLdapPort()))
        .after("setConstraints");
    mockConn.expects(once()).method("startTLS").after("connect");
    mockConn
        .expects(once())
        .method("bind")
        .with(
            eq(LDAPConnection.LDAP_V3),
            eq(connMgrConfig.getLdapUser()),
            eq(connMgrConfig.getLdapPassword().getBytes("UTF-8")))
        .after("connect");
    mockConn.expects(once()).method("setBindAttempted").with(eq(false)).after("bind");

    // the actual code exercise
    assertSame(conn, factory.makeObject());

    // TODO how to test socket factory assignment (static call)
  }
  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);
  }
 /**
  * If the client has bound the connection but the factory is not running in auto-bind mode, the
  * connection must be invalidated.
  */
 public void testValidateObjectLowersActiveFlagIfConnectionHasBeenBoundButAutoBindIsNotSet() {
   mockConn.expects(once()).method("isBindAttempted").will(returnValue(true));
   // we assume autoBind defaults to false (we'd rather not go through the
   // whole process of mocking up the connection manager again)
   mockConn.expects(once()).method("setActive").with(eq(false));
   assertFalse(factory.validateObject(conn));
 }
 public void testFiresDialogOpenedEventWhenDialogIsShown() {
   Mock mockWindowContextListener = mock(WindowContextListener.class);
   windowContext.addWindowContextListener(
       (WindowContextListener) mockWindowContextListener.proxy());
   mockWindowContextListener.expects(once()).method("dialogShown");
   windowContext.setActiveWindow(new JDialog((Frame) null, "test"));
 }
 @BeforeMethod
 public void init() {
   mockTester = new DefaultMockTester();
   mock = mockTester.mock(MockedType.class, "mock");
   proxy = (MockedType) mock.proxy();
   mock.expects(exactly(2)).method("m").withNoArguments();
 }
  /** Tests change in processing property when processing starts and finishes. */
  public void testProcessingPC() {
    listener
        .expects(once())
        .method("propertyChanged")
        .with(same(feed), eq(AbstractFeed.PROP_PROCESSING), eq(false), eq(true))
        .id("started");
    listener
        .expects(once())
        .method("propertyChanged")
        .with(same(feed), eq(AbstractFeed.PROP_PROCESSING), eq(true), eq(false))
        .after("started")
        .id("finished");
    listener
        .expects(once())
        .method("propertyChanged")
        .with(same(feed), eq(AbstractFeed.PROP_PROCESSING), eq(true), eq(false))
        .after("finished");

    feed.processingStarted();
    feed.processingStarted();
    feed.processingFinished();
    feed.processingFinished();

    disableLogging();
    feed.processingFinished();
    enableLogging();

    listener.verify();
  }
  public void testActionContainerCreatedOnlyOncePerRequest() {
    MutablePicoContainer requestContainer = new DefaultPicoContainer();
    requestContainer.registerComponentImplementation(TestService.class);
    MutablePicoContainer actionsContainer = new DefaultPicoContainer(requestContainer);

    requestMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.ACTIONS_CONTAINER))
        .will(returnValue(actionsContainer));
    requestMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.ACTIONS_CONTAINER))
        .will(returnValue(actionsContainer));
    requestMock
        .expects(once())
        .method("setAttribute")
        .with(eq(KeyConstants.ACTIONS_CONTAINER), isA(MutablePicoContainer.class));
    requestMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.REQUEST_CONTAINER))
        .will(returnValue(requestContainer));
    requestMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.ACTIONS_CONTAINER))
        .will(returnValue(null));

    actionFactory.getAction(request, mapping1, servlet);
    actionFactory.getAction(request, mapping1, servlet);
    actionFactory.getAction(request, mapping1, servlet);
  }
  public void testNoContainerExists() {
    requestMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.ACTIONS_CONTAINER))
        .will(returnValue(null));
    requestMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.REQUEST_CONTAINER))
        .will(returnValue(null));
    sessionMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.SESSION_CONTAINER))
        .will(returnValue(null));
    servletContextMock
        .expects(once())
        .method("getAttribute")
        .with(eq(KeyConstants.APPLICATION_CONTAINER))
        .will(returnValue(null));

    try {
      actionFactory.getAction(request, mapping1, servlet);
      fail("PicoInitializationException should have been raised");
    } catch (PicoInitializationException e) {
      // expected
    }
  }
 public void testBuscarClientePorNombre() {
   final String NOMBRE = "U050008";
   Mock mockDao = mock(ClienteDao.class);
   mockDao.expects(once()).method("buscarPorNombre").with(this.eq(NOMBRE));
   manager.setClienteDao((ClienteDao) mockDao.proxy());
   manager.buscarClientesPorNombre(NOMBRE);
 }
Example #17
0
  public void testShouldCallGetNextIdOnSequenceDao() {

    Mock seqDao = mock(SequenceDao.class);
    seqDao.expects(once()).method("getNextId").with(NOT_NULL).will(returnValue(1));

    OrderService service = new OrderService(null, null, null, (SequenceDao) seqDao.proxy());
    service.getNextId("ordernum");
  }
 public void testListenerIsNotNotifiedWhenRemoved() {
   Mock mockWindowContextListener = mock(WindowContextListener.class);
   WindowContextListener listener = (WindowContextListener) mockWindowContextListener.proxy();
   windowContext.addWindowContextListener(listener);
   windowContext.removeWindowContextListener(listener);
   mockWindowContextListener.expects(never()).method("dialogShown");
   windowContext.setActiveWindow(new JDialog((Frame) null, "test"));
 }
  /** 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());
  }
  /**
   * Verifies that {@link PooledLDAPConnectionFactory#validateObject(Object)} does not adjust a
   * {@link PooledLDAPConnection}'s active flag if the connection appears to be "alive". Probably
   * overkill, but we've had problems that we think may be related to stale connections being
   * returned to the pool, so we want to be sure the validate operation is doing exactly what we
   * think it should be doing. Also verifies that a {@link PooledLDAPConnection}'s search method
   * returns a LDAPEntry.
   *
   * @throws LDAPException
   */
  public void testValidateObjectKeepsActiveFlagUpIfConnectionIsAlive() throws LDAPException {

    // will fail if the factory attempts to monkey with the active flag
    factory.setConnectionLivenessValidator(livenessValidator);
    mockConn.expects(once()).method("isBindAttempted").will(returnValue(false));
    mockLivenessValidator.expects(once()).method("isConnectionAlive").will(returnValue(true));

    assertTrue(factory.validateObject(conn));
  }
 private Mock createMockBeanDefinitionReader(String keywordPattern) {
   Mock beanDefinitionReader = mock(IKeywordBeanDefintionReader.class);
   beanDefinitionReader
       .expects(once())
       .method("loadBeanDefinitions")
       .with(eq(keywordPattern), same(classFilter))
       .will(returnValue(3));
   return beanDefinitionReader;
 }
  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 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();
  }
  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);
  }
 /*
  * Call reset() in the catch blocks for these two methods,
  * otherwise the MockObjectTestCase infrastructure picks up
  * the errors and rethrows the exception.
  */
 public void testFailsWhenCalledFewerThanTheExactNumberOfTimes() {
   proxy.m();
   try {
     mock.verify();
   } catch (AssertionFailedError err) {
     mock.reset();
     return;
   }
   fail("Should have failed");
 }
Example #26
0
  public void test_readRecord_FileIsEmpty() throws IOException {
    fileUtil
        .expects(once())
        .method("channel")
        .with(eq(FILE))
        .will(returnValue(new ByteArrayChannel("".getBytes())));
    fileUtil.expects(once()).method("length").with(eq(FILE)).will(returnValue(0L));

    assertNull(reader.readRecord());
  }
Example #27
0
 public void testShouldCallGetOrdersByUsernameOnOrderDao() {
   Mock orderDao = mock(OrderDao.class);
   orderDao
       .expects(once())
       .method("getOrdersByUsername")
       .with(NOT_NULL)
       .will(returnValue(new PaginatedArrayList(5)));
   OrderService service = new OrderService(null, null, (OrderDao) orderDao.proxy(), null);
   service.getOrdersByUsername("j2ee");
 }
 public void testShouldInvokeTheTimeConverter() throws Exception {
   Mock timeConverterMock = mock(TimeConverter.class);
   BuildDetail laterBuild =
       new BuildDetail(
           new LogFile("log21111209122103.xml"),
           new HashMap(),
           (TimeConverter) timeConverterMock.proxy());
   timeConverterMock.expects(once()).method("getConvertedTime");
   laterBuild.getConvertedTime();
 }
 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 testSaveServiceLevelAgreement() throws Exception {
    // set expected behavior on dao
    serviceLevelAgreementDAO
        .expects(once())
        .method("saveServiceLevelAgreement")
        .with(same(serviceLevelAgreement))
        .isVoid();

    serviceLevelAgreementManager.saveServiceLevelAgreement(serviceLevelAgreement);
    serviceLevelAgreementDAO.verify();
  }