public void testRelease() {
    {
      try {
        st.release(new PSI(st, "g1", "i1", 823502L, 10));
      } catch (EmptyStackException e) {
      }
    }
    {
      PSI psi0 = st.getStackItem("g2", "i0");
      PSI psi1 = st.getStackItem("g2", "i1");
      st.getStackItem("g2", "i2");
      PSI psi3 = st.getStackItem("g2", "i3");

      Mockery ctx = new Mockery();
      final Log log = ctx.mock(Log.class);
      LogFactory lf = new ServerImplTest.TestLogFactory(log);
      Api api = new Api();
      api.setIntfImplementor(LogFactory.class, lf);
      ApiStack.pushApi(api);
      try {
        psi3.close();
        ctx.checking(
            new Expectations() {
              {
                one(log).error(with(any(String.class)));
              }
            });
        psi1.close(); // must be error reported
        ctx.assertIsSatisfied();
        psi0.close(); // no errors
      } finally {
        ApiStack.popApi();
      }
    }
  }
Esempio n. 2
0
  @SuppressWarnings("unchecked")
  @Override
  protected void setUp() throws Exception {

    // Build the properties
    props = new HashMap<String, String>();
    props.put("CountryCode", "US");
    props.put("CountryCode3", "USA");
    props.put("CountryName", "United States");
    props.put("Region", "NY");
    props.put("Region2", "New York");
    props.put("City", "New York");
    props.put("PostalCode", "10004");
    props.put("Latitude", "40.6888");
    props.put("Longitude", "74.0203");
    props.put("DmaCode", "501");
    props.put("AreaCode", "212");

    // Build the String
    final String SEPARATOR = "\t";
    final String NEWLINE = "\n";
    String testString = SEPARATOR + NEWLINE;
    for (Map.Entry<String, String> en : props.entrySet()) {
      testString += en.getKey() + SEPARATOR + en.getValue() + NEWLINE;
    }
    testS = testString;

    mockery = new Mockery();
    httpClient = mockery.mock(LimeHttpClient.class);
    geoCodeURL = mockery.mock(Provider.class);
    geo = new GeocoderImpl(geoCodeURL, Providers.of(httpClient));
  }
  @Test
  public void testFlattenSelectionJMock2() throws Exception {
    final IAssetType type1 = mockery.mock(IAssetType.class, "type1");
    final IAssetType type2 = mockery.mock(IAssetType.class, "type2");
    final IAttributeDefinition token0 = mockery.mock(IAttributeDefinition.class, "Token0");
    final IAttributeDefinition token1 = mockery.mock(IAttributeDefinition.class, "Token1");

    List<IAttributeDefinition> orig = new LinkedList<IAttributeDefinition>();
    orig.add(token1);
    mockery.checking(
        new Expectations() {
          {
            allowing(token1).getAssetType();
            will(returnValue(type2));
            one(type2).isA(type1);
            will(returnValue(true));
            one(type1).isA(type1);
            will(returnValue(false));
            one(type1).getAttributeDefinition("Token1");
            will(returnValue(token1));

            allowing(token1).getBase();
            will(returnValue(token0));
            one(token1).getName();
            will(returnValue("Token1"));
            one(token0).getAssetType();
            will(returnValue(type1));
          }
        });

    AttributeSelection res = flattenSelection(type1, orig);

    assertEqualsAsSet(null, res, Arrays.asList(token1));
  }
  @Test
  public void exceptionInProtocolClosesClientSession() throws IOException {
    i = 0;
    final Protocol protocol =
        new Protocol() {
          public void init(ClientSession session) {}

          public void parseFirst(InputStream message) throws IOException {}

          public void parsePacket(InputStream message) throws IOException {
            i++;
            throw new IOException("Test");
          }
        };

    context.checking(
        new Expectations() {
          {
            oneOf(mockedClient).close();
          }
        });

    prot.setCurrentProtocol(protocol);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    CData.writeU16(out, 2);
    CData.writeU16(out, 1337);
    prot.messageReceived(mockedClient, new ByteArrayInputStream(out.toByteArray()));

    assertEquals(1, i);

    context.assertIsSatisfied();
  }
 @SuppressWarnings("unchecked")
 protected ParameterService getParameterService() {
   final ParameterService parameterService = context.mock(ParameterService.class);
   context.checking(
       new Expectations() {
         {
           allowing(parameterService)
               .parameterExists(with(any(Class.class)), with(any(String.class)));
           will(returnValue(true));
           allowing(parameterService)
               .getParameterValueAsBoolean(
                   ProtocolDocument.class, Constants.ENABLE_PROTOCOL_TO_AWARD_LINK);
           will(returnValue(true));
           allowing(parameterService)
               .getParameterValueAsBoolean(
                   ProtocolDocument.class, Constants.ENABLE_PROTOCOL_TO_DEV_PROPOSAL_LINK);
           will(returnValue(true));
           allowing(parameterService)
               .getParameterValueAsBoolean(
                   ProtocolDocument.class, Constants.ENABLE_PROTOCOL_TO_PROPOSAL_LINK);
           will(returnValue(true));
         }
       });
   return parameterService;
 }
  @Test
  public void all_valid_exits_are_retrieveable() {
    final Exit exit1 = mockery.mock(Exit.class, "exit1");
    final Exit exit2 = mockery.mock(Exit.class, "exit2");
    mockery.checking(
        new Expectations() {
          {
            allowing(exit1).visible();
            will(returnValue(true));
            ignoring(exit1);
            allowing(exit2).visible();
            will(returnValue(true));
            ignoring(exit2);
          }
        });
    List<Exit> exits = new ArrayList<Exit>();
    exits.add(exit1);
    exits.add(exit2);

    Location l = createLocation();
    l.addExit(exit1);
    l.addExit(exit2);

    assertEquals(exits, l.visibleExits());
  }
  @Test
  public void available_items_text_includes_only_visible_items() {
    final Item visibleItem = mockery.mock(Item.class, "visible item");
    final Item invisibleItem = mockery.mock(Item.class, "invisible item");
    mockery.checking(
        new Expectations() {
          {
            allowing(visibleItem).visible();
            will(returnValue(true));
            allowing(visibleItem).countableNounPrefix();
            will(returnValue("a"));
            allowing(visibleItem).midSentenceCasedName();
            will(returnValue("visible item"));
            ignoring(visibleItem);
            allowing(invisibleItem).visible();
            will(returnValue(false));
            allowing(invisibleItem).midSentenceCasedName();
            will(returnValue("invisible item"));
            ignoring(invisibleItem);
          }
        });
    Location l = new Location("", "Location description.", null, null);
    l.addItem(visibleItem);
    l.addItem(invisibleItem);

    assertEquals("There is a visible item here.\n", l.availableItemsText());
  }
Esempio n. 8
0
  public void testReadWithNoCharsetAndStreamDoesntSupportMarkAssumesUTF8() throws Exception {
    final byte[] b = new byte[8192];
    final int off = 0;
    final int len = 8192;
    final InputStream stream = context.mock(InputStream.class);
    context.checking(
        new Expectations() {
          {
            oneOf(stream).markSupported();
            will(returnValue(false));

            // Read a single byte/char to check for BOM
            oneOf(stream).read(b, off, len);
            will(returnValue(1));
            oneOf(stream).available();
            will(returnValue(-1));
            // Read content, but return empty
            oneOf(stream).read(b, off, len);
            will(returnValue(-1));
            // Close stream
            oneOf(stream).close();
          }
        });
    String result = IOUtil.read(stream);
    assertNotNull(result);
    // Returned one single 0 byte because we allowed reading of one...
    assertEquals(1, result.length());
    context.assertIsSatisfied();
  }
Esempio n. 9
0
  public void testReadWithNoCharsetAndMarkSupportedSniffsCharset() throws Exception {
    final byte[] b = new byte[8192];
    final int off = 0;
    final int len = 8192;
    final InputStream stream = context.mock(InputStream.class);
    context.checking(
        new Expectations() {
          {
            // charset sniffing
            oneOf(stream).markSupported();
            will(returnValue(true));
            oneOf(stream).mark(8000);
            oneOf(stream).read(new byte[8000], 0, 8000);
            will(returnValue(-1));
            oneOf(stream).reset();
            oneOf(stream).reset();

            // Now do the reading
            oneOf(stream).read(b, off, len);
            // FIXME Read back actual bytes/chars/etc
            will(throwException(new IOException("")));
            oneOf(stream).close();
          }
        });
    IOUtil.read(stream);
    context.assertIsSatisfied();
  }
  @Test
  public void permissions() {
    context.checking(
        new Expectations() {
          {
            one(repository).get(1);
            will(returnValue(new Group()));
            one(roleManager).isAdministrator();
            will(returnValue(true));
            one(categoryRepository).getAllCategories();
            will(returnValue(new ArrayList<Category>()));
            one(repository).getAllGroups();
            will(returnValue(new ArrayList<Group>()));

            one(mockResult).include("group", new Group());
            one(mockResult).include("groups", new ArrayList<Group>());
            one(mockResult).include("categories", new ArrayList<Category>());
            // TODO: fix PermOption				one(mockResult).include("permissions", new
            // PermissionOptions());
          }
        });

    controller.permissions(1);
    context.assertIsSatisfied();
  }
Esempio n. 11
0
  @Test
  public void basic() throws IOException {
    final Object[] tst = new Object[] {"test1", "test2"};

    context.checking(
        new Expectations() {
          {
            oneOf(node).getProperty("test");
            will(returnValue(tst));
            oneOf(model).pushNode("test", -1);
            will(returnValue(node));
            oneOf(model).pushNode("0", 0);
            will(returnValue(node));
            oneOf(template).render(model);
            oneOf(model).popNode();
            oneOf(model).pushNode("1", 1);
            will(returnValue(node));
            oneOf(template).render(model);
            oneOf(model).popNode();
            oneOf(model).popNode();
          }
        });

    element = new ArrayElement(property.getName(), template);
    element.render(model);
    context.assertIsSatisfied();
  }
  @Test
  public void testCustomComponentFactoryCanBeSpecified() {
    Reader script =
        new StringReader(
            "A = org.picocontainer.script.testmodel.A\n"
                + "container(:component_adapter_factory => $assembly_scope) {\n"
                + "    component(A)\n"
                + "}");

    final A a = new A();

    final ComponentFactory componentFactory = mockery.mock(ComponentFactory.class);
    mockery.checking(
        new Expectations() {
          {
            one(componentFactory)
                .createComponentAdapter(
                    with(any(ComponentMonitor.class)),
                    with(any(LifecycleStrategy.class)),
                    with(any(Properties.class)),
                    with(same(A.class)),
                    with(same(A.class)),
                    with(aNull(Parameter[].class)));
            will(
                returnValue(
                    new InstanceAdapter<A>(
                        A.class, a, new NullLifecycleStrategy(), new NullComponentMonitor())));
          }
        });

    PicoContainer pico = buildContainer(script, null, componentFactory);
    assertSame(a, pico.getComponent(A.class));
  }
  @Test
  public void shouldReturnBaseSetupWhenProfilingIsNotAllowed() {
    // Given
    final CommandLineSetup baseSetup =
        new CommandLineSetup(
            "someTool",
            Arrays.asList(
                new CommandLineArgument("/arg1", CommandLineArgument.Type.PARAMETER),
                new CommandLineArgument("/arg2", CommandLineArgument.Type.PARAMETER)),
            Collections.singletonList(myCommandLineResource));
    myCtx.checking(
        new Expectations() {
          {
            oneOf(myAssertions).contains(RunnerAssertions.Assertion.PROFILING_IS_NOT_ALLOWED);
            will(returnValue(true));
          }
        });

    final DotTraceSetupBuilder instance = createInstance();

    // When
    final CommandLineSetup setup = instance.build(baseSetup).iterator().next();

    // Then
    myCtx.assertIsSatisfied();
    then(setup).isEqualTo(baseSetup);
  }
  @Test(dataProvider = "runnerParamUseDotTraceCases")
  public void shouldReturnBaseSetupWhenRunnerParamUseDotTraceIsEmptyOrFalse(
      final String useDotTrace) {
    // Given
    final CommandLineSetup baseSetup =
        new CommandLineSetup(
            "someTool",
            Arrays.asList(
                new CommandLineArgument("/arg1", CommandLineArgument.Type.PARAMETER),
                new CommandLineArgument("/arg2", CommandLineArgument.Type.PARAMETER)),
            Collections.singletonList(myCommandLineResource));
    myCtx.checking(
        new Expectations() {
          {
            oneOf(myAssertions).contains(RunnerAssertions.Assertion.PROFILING_IS_NOT_ALLOWED);
            will(returnValue(false));

            oneOf(myRunnerParametersService).tryGetRunnerParameter(Constants.USE_VAR);
            will(returnValue(useDotTrace));
          }
        });

    final DotTraceSetupBuilder instance = createInstance();

    // When
    final CommandLineSetup setup = instance.build(baseSetup).iterator().next();

    // Then
    myCtx.assertIsSatisfied();
    then(setup).isEqualTo(baseSetup);
  }
  @Test
  public void should_send_mail_when_parameters_are_correct() {

    final EmailBuilder email = context.mock(EmailBuilder.class);

    context.checking(
        new Expectations() {
          {
            one(email).from("*****@*****.**");
            will(returnValue(email));

            one(email).to("*****@*****.**");
            will(returnValue(email));

            one(email).withSubject("subject");
            will(returnValue(email));

            one(email).withBody("body");
            will(returnValue(email));

            one(email).withCharset("UTF-8");
            will(returnValue(email));

            one(email).send();
          }
        });

    email
        .from("*****@*****.**")
        .to("*****@*****.**")
        .withSubject("subject")
        .withBody("body")
        .withCharset("UTF-8")
        .send();
  }
  @Test
  public void initializationTest() throws Exception {
    UrlTranslationFilter translationFilter = new UrlTranslationFilter();

    final ServletContext servletContext = filterMockery.mock(ServletContext.class);

    filterConfig = filterMockery.mock(FilterConfig.class);
    filterMockery.checking(
        new Expectations() {
          {
            allowing(filterConfig).getServletContext();
            will(returnValue(servletContext));

            allowing(filterConfig).getInitParameter(UrlTranslationFilter.ENABLED_PARAM_NAME);
            will(returnValue("true"));

            one(filterConfig).getInitParameter(UrlTranslationFilter.CONFIG_RESOURCE_URL_PARAM_NAME);
            will(returnValue("org/xchain/framework/filter/translation-filter-test.xml"));
          }
        });

    translationFilter.init(filterConfig);

    assertTrue(translationFilter.isEnabled());
  }
  /**
   * Tests execute with a notifier exception (for coverage).
   *
   * @throws Exception Shouldn't.
   */
  @Test
  @SuppressWarnings("unchecked")
  public void testExecuteNotifierError() throws Exception {
    final List<Long> recipients = Collections.singletonList(4L);
    final NotificationDTO notification =
        new NotificationDTO(
            recipients, NotificationType.FOLLOW_PERSON, 1L, 2L, EntityType.PERSON, 3L);

    context.checking(
        new Expectations() {
          {
            oneOf(followerTranslator).translate(1, 2, 3);
            will(returnValue(Collections.singletonList(notification)));

            allowing(personMapper).execute(with(equal(4L)));
            will(returnValue(person));

            oneOf(populator).populate(with(same(notification)));

            oneOf(preferencesMapper).execute(with(any(List.class)));
            will(returnValue(new ArrayList<NotificationFilterPreferenceDTO>()));

            oneOf(applicationNotifier).notify(with(any(NotificationDTO.class)));
            will(returnValue(null));
            oneOf(emailNotifier).notify(with(any(NotificationDTO.class)));
            will(throwException(new Exception("BAD")));
          }
        });

    CreateNotificationsRequest request =
        new CreateNotificationsRequest(RequestType.FOLLOWER, 1, 2, 3);
    sut.execute(TestContextCreator.createTaskHandlerAsyncContext(request));
    context.assertIsSatisfied();
  }
  /** Test. */
  @Test
  public void testWithThemeAndGttIds() {
    final Long themeId = 5L;
    final Long gttId = 6L;
    final MembershipCriteriaDTO mcdto = new MembershipCriteriaDTO();
    mcdto.setCriteria(criteria);
    mcdto.setThemeId(themeId);
    mcdto.setGalleryTabTemplateId(gttId);

    context.checking(
        new Expectations() {
          {
            oneOf(ac).getParams();
            will(returnValue(mcdto));

            oneOf(themeProxyMapper).execute(themeId);
            will(returnValue(theme));

            oneOf(galleryTabTemplateProxyMappery).execute(gttId);
            will(returnValue(gtt));
          }
        });

    PersistenceRequest<MembershipCriteria> result = sut.transform(ac);

    assertEquals(criteria, result.getDomainEnity().getCriteria());
    assertNotNull(result.getDomainEnity().getTheme());
    assertNotNull(result.getDomainEnity().getGalleryTabTemplate());

    context.assertIsSatisfied();
  }
  @Test
  public void actions_uses_action_factory_to_create_ExamineAnItem_action_for_all_visible_items() {
    final Item visibleItem = mockery.mock(Item.class, "visible item");
    final Item invisibleItem = mockery.mock(Item.class, "invisible item");
    final ActionFactory actionFactory = mockery.mock(ActionFactory.class);
    final Action examineAnItemAction = mockery.mock(Action.class);
    final List<Item> visibleItems = new ArrayList<Item>();
    visibleItems.add(visibleItem);
    mockery.checking(
        new Expectations() {
          {
            allowing(visibleItem).visible();
            will(returnValue(true));
            ignoring(visibleItem);
            allowing(invisibleItem).visible();
            will(returnValue(false));
            ignoring(invisibleItem);
            oneOf(actionFactory).createExamineAnItemAction(with(equal(visibleItems)));
            will(returnValue(examineAnItemAction));
            ignoring(actionFactory);
          }
        });
    Location l = new Location("", "", null, actionFactory);
    l.addItem(visibleItem);
    l.addItem(invisibleItem);

    List<Action> actions = l.actions();
    assertTrue(actions.size() > 0);
    assertThat(actions.get(0), is(examineAnItemAction));
  }
  @Test
  public void testOneSubscriberReceivesAMessage() {

    final Subscriber subscriber = context.mock(Subscriber.class);
    final String message = "message";
    context.checking(
        new Expectations() {
          {
            // never(subscriber).receive(message);
            oneOf(subscriber).receive(message);
            // exactly(1).of(subscriber).receive(message);
            // atLeast(1).of(subscriber).receive(message);
            // atMost(2).of(subscriber).receive(message);
            // between(1, 5).of(subscriber).receive(message);
            // allowing(subscriber).receive(message);
            will(returnValue("Hello world"));
          }
        });

    Publisher publisher = new Publisher();
    publisher.add(subscriber);
    // execute
    String answer = publisher.publish(message);
    // verify
    context.assertIsSatisfied();
    Assert.assertEquals("Hello world", answer);
  }
 @Test
 public void removing_all_items_from_a_location_removes_TakeAnItem_action_from_action_list() {
   final Item takeableItem = mockery.mock(Item.class);
   final ActionFactory actionFactory = mockery.mock(ActionFactory.class);
   final Location l = new Location("", "", null, actionFactory);
   mockery.checking(
       new Expectations() {
         {
           allowing(takeableItem).visible();
           will(returnValue(true));
           allowing(takeableItem).takeable();
           will(returnValue(true));
           ignoring(takeableItem);
           never(actionFactory)
               .createTakeAnItemAction(
                   with(any(List.class)),
                   with(any(UserInventory.class)),
                   with(any(ModelLocation.class)));
           ignoring(actionFactory);
         }
       });
   l.addItem(takeableItem);
   l.removeItem(takeableItem);
   l.actions();
 }
  /** Test. Put in 3 things, get a count of 3. */
  @Test
  public void execute() {
    final List<Long> activities = Arrays.asList(1L, 2L, 3L);

    sut = new GetActivityCount(getIdsMock);

    final PrincipalActionContext actionContext = context.mock(PrincipalActionContext.class);
    final String request = "{}";
    final Long userId = 1L;

    final Principal principle = context.mock(Principal.class);

    context.checking(
        new Expectations() {
          {
            oneOf(actionContext).getParams();
            will(returnValue(request));

            oneOf(actionContext).getPrincipal();
            will(returnValue(principle));

            oneOf(principle).getId();
            will(returnValue(userId));

            oneOf(getIdsMock).execute(request, userId);
            will(returnValue(activities));
          }
        });

    Integer result = (Integer) sut.execute(actionContext);
    Assert.assertEquals(new Integer(3), result);

    context.assertIsSatisfied();
  }
  @Before
  public void setUp() throws Exception {

    MicroPlatform microPlatform = new MicroPlatform();
    Mockery context = new Mockery();

    Map<String, String> mimeMap = new HashMap<String, String>();
    mimeMap.put("locale", "text/locale");
    microPlatform.defineInstance(NameBaseMimeResolver.class, new NameBaseMimeResolver(mimeMap));

    IPlatformImportMimeResolver nameBaseMimeResolver =
        context.mock(IPlatformImportMimeResolver.class);
    microPlatform.defineInstance(IPlatformImportMimeResolver.class, nameBaseMimeResolver);

    List<String> allowedArtifacts = new ArrayList<String>();
    allowedArtifacts.add("xaction");
    allowedArtifacts.add("url");
    LocaleImportHandler localeImportHandler = new LocaleImportHandler(allowedArtifacts);

    Map<String, IPlatformImportHandler> handlers = new HashMap<String, IPlatformImportHandler>();
    handlers.put("text/locale", localeImportHandler);

    Map<String, String> mimes = new HashMap<String, String>();
    mimes.put("locale", "text/locale");
    importer = new PentahoPlatformImporter(handlers, new NameBaseMimeResolver(mimes));
    importer.setRepositoryImportLogger(new Log4JRepositoryImportLogger());
  }
Esempio n. 24
0
 /**
  * Returns:
  *
  * <ul>
  *   <li>{@code null} if this engine is marked as closed, or if current action is not one of
  *       {@link HandshakeAction#NEED_TASK NEED_TASK}, {@link HandshakeAction#NEED_FAULTY_TASK
  *       NEED_FAULTY_TASK}.
  *   <li>a task mock if current action is {@link HandshakeAction#NEED_TASK NEED_TASK}. The mock
  *       expects to have its method {@code run()} invoked exactly once by client
  *   <li>a task mock whose {@code run()} method will throw an exception, if current action is
  *       {@link HandshakeAction#NEED_FAULTY_TASK NEED_FAULTY_TASK}. The mock expects to have its
  *       method {@code run()} invoked exactly once.
  * </ul>
  */
 @SuppressWarnings("incomplete-switch")
 @Override
 public synchronized Runnable getDelegatedTask() {
   if (!closed && actionIndex < actions.length) {
     switch (actions[actionIndex]) {
       case NEED_TASK:
         {
           actionIndex++;
           synchronized (mockery) {
             final Runnable task = mockery.mock(Runnable.class, "RunnableMock" + taskCount++);
             mockery.checking(
                 new Expectations() {
                   {
                     oneOf(task).run();
                   }
                 });
             return task;
           }
         }
       case NEED_FAULTY_TASK:
         synchronized (mockery) {
           final Runnable task = mockery.mock(Runnable.class, "RunnableFaultyMock" + taskCount++);
           mockery.checking(
               new Expectations() {
                 {
                   oneOf(task).run();
                   will(throwException(new RuntimeException()));
                 }
               });
           return task;
         }
     }
   }
   return null;
 }
  protected FundingSourceTypeService getFundingSourceTypeService() {
    final FundingSourceTypeService service = context.mock(FundingSourceTypeService.class);
    context.checking(
        new Expectations() {
          {
            allowing(service).getFundingSourceType(SPONSOR_SOURCE_TYPE_ID);
            will(returnValue(fundingSponsorSourceType));

            allowing(service).getFundingSourceType(UNIT_SOURCE_TYPE_ID);
            will(returnValue(fundingUnitSourceType));

            allowing(service).getFundingSourceType(OTHER_SOURCE_TYPE_ID);
            will(returnValue(fundingOtherSourceType));

            allowing(service).getFundingSourceType(DEVELOPMENT_PROP_SOURCE_TYPE_ID);
            will(returnValue(fundingDevProposalSourceType));

            allowing(service).getFundingSourceType(INSTITUTE_PROP_SOURCE_TYPE_ID);
            will(returnValue(fundingInstProposalSourceType));

            allowing(service).getFundingSourceType(AWARD_SOURCE_TYPE_ID);
            will(returnValue(fundingAwardSourceType));
          }
        });
    return service;
  }
Esempio n. 26
0
 @Override
 public SSLSession getSession() {
   synchronized (mockery) {
     final SSLSession sessionMock = mockery.mock(SSLSession.class, "Session" + sessionCount++);
     if (sessionCount == 1) {
       mockery.checking(
           new Expectations() {
             {
               oneOf(sessionMock).getPacketBufferSize();
               will(returnValue(16916));
               oneOf(sessionMock).getApplicationBufferSize();
               will(returnValue(16921));
             }
           });
     } else {
       mockery.checking(
           new Expectations() {
             {
               allowing(sessionMock).getPacketBufferSize();
               will(returnValue(16916));
               allowing(sessionMock).getApplicationBufferSize();
               will(returnValue(16921));
             }
           });
     }
     return sessionMock;
   }
 }
Esempio n. 27
0
  @Test
  public void deleteExpectSuccess() {
    context.checking(
        new Expectations() {
          {
            Avatar s1 = new Avatar();
            s1.setId(1);
            s1.setFileName(Long.toString(System.currentTimeMillis()));
            Avatar s2 = new Avatar();
            s2.setId(2);
            s2.setFileName(Long.toString(System.currentTimeMillis()));

            String applicationPath =
                new File(this.getClass().getResource("").getFile()).getParent();

            atLeast(1).of(config).getApplicationPath();
            will(returnValue(applicationPath));
            atLeast(1).of(config).getValue(ConfigKeys.AVATAR_GALLERY_DIR);
            will(returnValue(""));

            one(repository).get(1);
            will(returnValue(s1));
            one(repository).remove(s1);

            one(repository).get(2);
            will(returnValue(s2));
            one(repository).remove(s2);
          }
        });

    service.delete(1, 2);
    context.assertIsSatisfied();
  }
  @Test
  public void testCompareByName() throws Exception {

    final Category cat1 = context.mock(Category.class, "cat1");
    final Category cat2 = context.mock(Category.class, "cat2");

    context.checking(
        new Expectations() {
          {
            allowing(cat1).getRank();
            will(returnValue(0));
            allowing(cat1).getName();
            will(returnValue("name 2"));
            allowing(cat1).getCategoryId();
            will(returnValue(1L));
            allowing(cat2).getRank();
            will(returnValue(0));
            allowing(cat2).getName();
            will(returnValue("name 1"));
          }
        });

    final SortedSet<Category> set = new TreeSet<Category>(new CategoryRankNameComparator());
    set.addAll(Arrays.asList(cat1, cat2));

    final List<Category> list = new ArrayList<Category>(set);
    assertTrue(cat2 == list.get(0));
    assertTrue(cat1 == list.get(1));
  }
Esempio n. 29
0
  private ProtocolSubmitAction getMockSubmitAction() {
    final ProtocolSubmitAction action = context.mock(ProtocolSubmitAction.class);

    context.checking(
        new Expectations() {
          {
            allowing(action).getSubmissionTypeCode();
            will(returnValue(ProtocolSubmissionType.INITIAL_SUBMISSION));

            allowing(action).getProtocolReviewTypeCode();
            will(returnValue(ProtocolReviewType.FULL_TYPE_CODE));

            allowing(action).getSubmissionQualifierTypeCode();
            will(returnValue(ProtocolSubmissionQualifierType.ANNUAL_SCHEDULED_BY_IRB));

            allowing(action).getNewCommitteeId();
            will(returnValue(Constants.EMPTY_STRING));

            allowing(action).getNewScheduleId();
            will(returnValue(Constants.EMPTY_STRING));

            allowing(action).getReviewers();
            will(returnValue(new ArrayList<ProtocolReviewerBean>()));
          }
        });

    return action;
  }
Esempio n. 30
0
public abstract class AbstractControllerTest {

  static {
    System.setProperty(
        "org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
    System.setProperty("log4j.configuration", "log4j.test.xml");
  }

  protected Mockery context = new JUnit4Mockery();
  protected final HttpServletRequest mockRequest = context.mock(HttpServletRequest.class);
  protected final HttpServletResponse mockResponse = context.mock(HttpServletResponse.class);
  protected final Service mockService = context.mock(Service.class);
  protected final Repository mockRepository = context.mock(Repository.class);

  public void setUp() throws Exception {
    BaseContext.pushContext();
    SecurityContext securityContext = new SecurityContext(null, null);
    SecurityContext.setSecurityContext(securityContext);
    RequestContext requestContext =
        new RequestContext(
            mockRequest,
            securityContext,
            mockService,
            null,
            getRequestPath(),
            null,
            false,
            false,
            true,
            mockRepository);
    RequestContext.setRequestContext(requestContext);
  }

  protected abstract Path getRequestPath();
}