@Test public void shouldUseTheDefaultLocale() throws ParseException { mockery.checking( new Expectations() { { one(request).getAttribute("javax.servlet.jsp.jstl.fmt.locale.request"); will(returnValue(null)); one(request).getSession(); will(returnValue(session)); one(session).getAttribute("javax.servlet.jsp.jstl.fmt.locale.session"); will(returnValue(null)); one(context).getAttribute("javax.servlet.jsp.jstl.fmt.locale.application"); will(returnValue(null)); one(context).getInitParameter("javax.servlet.jsp.jstl.fmt.locale"); will(returnValue(null)); one(request).getLocale(); will(returnValue(Locale.getDefault())); } }); DecimalFormat fmt = new DecimalFormat("##0,00"); fmt.setMinimumFractionDigits(2); double theValue = 10.00d; String formattedValue = fmt.format(theValue); assertThat( (Double) converter.convert(formattedValue, double.class, bundle), is(equalTo(theValue))); mockery.assertIsSatisfied(); }
/** 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(); }
@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(); }
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(); }
/** 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 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 public void whenValueIsAValidDateShouldGetCorrespondingDate() throws Exception { givenLocaleIs(Locale.ENGLISH); LocalDate date = converter.convert("10/29/2009", LocalDate.class, null); assertThat(date, is(new LocalDate(2009, 10, 29))); mockery.assertIsSatisfied(); }
public void testDoesNotAssignPassiveLeafIfDisabled() throws Exception { ConnectionSettings.EVER_ACCEPTED_INCOMING.setValue(true); DHTSettings.ENABLE_PASSIVE_LEAF_DHT_MODE.setValue(false); long startTime = System.currentTimeMillis() - DHTSettings.MIN_PASSIVE_LEAF_DHT_INITIAL_UPTIME.getValue(); PrivilegedAccessor.setValue(nodeAssigner, "startTime", new Long(startTime)); mockery.checking(buildBandwdithExpectations(true)); mockery.checking( buildDHTExpectations( DHTMode.INACTIVE, true, true, false, // can't receive unsolicited DHTSettings.MIN_PASSIVE_LEAF_DHT_AVERAGE_UPTIME.getValue() + 1, false, false)); mockery.checking( new Expectations() { { never(dhtManager).start(with(Matchers.any(DHTMode.class))); } }); assignerRunnable.run(); mockery.assertIsSatisfied(); }
/** * Test failed consumer start. * * @throws SchedulerException */ @Test(expected = RuntimeException.class) public void test_failed_start_due_to_parserException() throws SchedulerException { final JobKey jobKey = new JobKey("flowName", "moduleName"); // expectations mockery.checking( new Expectations() { { // get flow and module name from the job exactly(1).of(mockJobDetail).getKey(); will(returnValue(jobKey)); // access configuration for details exactly(1).of(consumerConfiguration).getCronExpression(); will(returnValue("* * * * ? ?")); // schedule the job exactly(1).of(scheduler).scheduleJob(mockJobDetail, trigger); will(throwException(new ParseException("test", 0))); } }); ScheduledConsumer scheduledConsumer = new StubbedScheduledConsumer(scheduler); scheduledConsumer.setConfiguration(consumerConfiguration); scheduledConsumer.start(); mockery.assertIsSatisfied(); }
public void testPassiveLeafDoesNotNeedHardCore() throws Exception { // not accepted incoming previously therefore not hardcore long startTime = System.currentTimeMillis() - DHTSettings.MIN_PASSIVE_LEAF_DHT_INITIAL_UPTIME.getValue(); PrivilegedAccessor.setValue(nodeAssigner, "startTime", new Long(startTime)); mockery.checking(buildBandwdithExpectations(true)); mockery.checking( buildDHTExpectations( DHTMode.INACTIVE, true, true, false, // can't receive unsolicited DHTSettings.MIN_PASSIVE_LEAF_DHT_AVERAGE_UPTIME.getValue() + 1, false, false)); mockery.checking( new Expectations() { { one(dhtManager).start(DHTMode.PASSIVE_LEAF); } }); assignerRunnable.run(); mockery.assertIsSatisfied(); }
public void testStopsDHTWhenDisabled() throws Exception { ConnectionSettings.EVER_ACCEPTED_INCOMING.setValue(true); long startTime = System.currentTimeMillis() - DHTSettings.MIN_ACTIVE_DHT_INITIAL_UPTIME.getValue(); PrivilegedAccessor.setValue(nodeAssigner, "startTime", new Long(startTime)); mockery.checking(buildBandwdithExpectations(true)); mockery.checking( buildDHTExpectations( DHTMode.ACTIVE, false, true, true, DHTSettings.MIN_ACTIVE_DHT_AVERAGE_UPTIME.getValue() + 1, false, false)); mockery.checking( new Expectations() { { one(dhtManager).stop(); } }); assignerRunnable.run(); mockery.assertIsSatisfied(); }
public void testDoesNotAssignLowAverageUptime() throws Exception { ConnectionSettings.EVER_ACCEPTED_INCOMING.setValue(true); long startTime = System.currentTimeMillis() - DHTSettings.MIN_ACTIVE_DHT_INITIAL_UPTIME.getValue(); PrivilegedAccessor.setValue(nodeAssigner, "startTime", new Long(startTime)); mockery.checking(buildBandwdithExpectations(true)); mockery.checking( buildDHTExpectations( DHTMode.INACTIVE, true, true, true, 0, // no average uptime false, false)); mockery.checking( new Expectations() { { never(dhtManager).start(with(Matchers.any(DHTMode.class))); } }); assignerRunnable.run(); mockery.assertIsSatisfied(); }
public void testDoesNotAssignLowInitialUptime() throws Exception { ConnectionSettings.EVER_ACCEPTED_INCOMING.setValue(true); // no initial uptime mockery.checking(buildBandwdithExpectations(true)); mockery.checking( buildDHTExpectations( DHTMode.INACTIVE, true, true, true, DHTSettings.MIN_ACTIVE_DHT_AVERAGE_UPTIME.getValue() + 1, false, false)); mockery.checking( new Expectations() { { never(dhtManager).start(with(Matchers.any(DHTMode.class))); } }); assignerRunnable.run(); mockery.assertIsSatisfied(); }
/** * Test DELETE. * * @throws ResourceException error. * @throws IOException error. */ @Test public void removeRepresentations() throws ResourceException, IOException { final Person me = context.mock(Person.class); final List<Task> tasks = new LinkedList<Task>(); final Task task1 = context.mock(Task.class); final Task task2 = context.mock(Task.class, "t2"); final GadgetDefinition gadgetDef = context.mock(GadgetDefinition.class); tasks.add(task1); tasks.add(task2); context.checking( new Expectations() { { oneOf(mapper).findByOpenSocialId("7"); will(returnValue(me)); allowing(me).getCompletedTasks(); will(returnValue(tasks)); oneOf(task2).getName(); will(returnValue("deleteMe")); oneOf(task2).getGadgetDefinition(); will(returnValue(gadgetDef)); oneOf(gadgetDef).getId(); will(returnValue(1L)); oneOf(mapper).flush(); } }); sut.removeRepresentations(); context.assertIsSatisfied(); }
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(); } } }
/** * Test successful consumer stop. * * @throws SchedulerException */ @Test public void test_successful_stop() throws SchedulerException { final JobKey jobKey = new JobKey("flowName", "moduleName"); // expectations mockery.checking( new Expectations() { { exactly(1).of(mockJobDetail).getKey(); will(returnValue(jobKey)); // unschedule the job exactly(1).of(scheduler).checkExists(jobKey); will(returnValue(Boolean.TRUE)); exactly(1).of(scheduler).deleteJob(jobKey); } }); ScheduledConsumer scheduledConsumer = new StubbedScheduledConsumer(scheduler); scheduledConsumer.setConfiguration(consumerConfiguration); scheduledConsumer.setJobDetail(mockJobDetail); scheduledConsumer.stop(); mockery.assertIsSatisfied(); }
@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 failed consumer stop due to scheduler exception. * * @throws SchedulerException */ @Test(expected = RuntimeException.class) public void test_failed_stop_due_to_schedulerException() throws SchedulerException { final JobKey jobKey = new JobKey("flowName", "moduleName"); // expectations mockery.checking( new Expectations() { { // get flow and module name from the job exactly(1).of(mockJobDetail).getKey(); will(returnValue(jobKey)); // unschedule the job exactly(1).of(scheduler).checkExists(jobKey); will(returnValue(Boolean.TRUE)); exactly(1).of(scheduler).deleteJob(jobKey); will(throwException(new SchedulerException())); } }); ScheduledConsumer scheduledConsumer = new StubbedScheduledConsumer(scheduler); scheduledConsumer.setConfiguration(consumerConfiguration); scheduledConsumer.stop(); mockery.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(); }
@Test public void merge() { Map<String, Object> props = new HashMap<String, Object>(); props.put("description", "Merge This"); props.put("stockLevel", (int) 27); final ObjexObj obj = context.mock(ObjexObj.class); final MapObjectReader underTest = new MapObjectReader(); underTest.setBehaviourOn(ObjectReaderBehaviour.MERGE); context.checking( new Expectations() { { oneOf(obj).acceptReader(underTest); } }); underTest.readObject(props, obj); Assert.assertEquals( "Something", underTest.read("name", "Something", String.class, ObjexFieldType.STRING, true)); Assert.assertEquals( "Merge This", underTest.read("description", "Something", String.class, ObjexFieldType.STRING, true)); Assert.assertEquals( (int) 27, (int) underTest.read("stockLevel", 15, Integer.class, ObjexFieldType.NUMBER, true)); Assert.assertEquals( 18.0, underTest.read("price", 18.0, Double.class, ObjexFieldType.NUMBER, true)); context.assertIsSatisfied(); }
@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 the execution of the ServiceActionController with just a service Action and fail on * authorization. */ @Test(expected = AuthorizationException.class) public void testExecuteWithServiceActionAuthorizationFailure() { Serializable params = null; final ServiceActionContext serviceActionContext = new ServiceActionContext(params, principalMock); transDef.setReadOnly(true); expectServiceAction(); mockery.checking( new Expectations() { { allowing(serviceActionMock).isReadOnly(); will(returnValue(true)); oneOf(transMgrMock).getTransaction(transDef); will(returnValue(transStatus)); oneOf(validationStrategy).validate(serviceActionContext); oneOf(authorizationStrategy).authorize(serviceActionContext); will(throwException(new AuthorizationException())); oneOf(transStatus).isCompleted(); will(returnValue(false)); oneOf(transMgrMock).rollback(transStatus); } }); sut.execute(serviceActionContext, serviceActionMock); mockery.assertIsSatisfied(); }
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 the failure path of the {@link TaskHandlerAction}. * * @throws Exception on error. */ @Test(expected = GeneralException.class) public void testExecuteWithQueueServiceActionFailure() throws Exception { final ServiceActionContext serviceActionContext = mockery.mock(ServiceActionContext.class); transDef.setReadOnly(false); final List<UserActionRequest> requests = new ArrayList<UserActionRequest>(); requests.add(userActionRequest); final TaskHandlerActionContext<ServiceActionContext> taskHandlerActionContextMock = mockery.mock(TaskHandlerActionContext.class); setupTaskHandlerTransactionContext(false, taskHandlerActionContextMock, true); mockery.checking( new Expectations() { { oneOf(transStatus).isCompleted(); will(returnValue(false)); oneOf(transMgrMock).rollback(transStatus); } }); sut.execute(serviceActionContext, queueSubmitterActionMock); mockery.assertIsSatisfied(); }
@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 the validation failure path of the {@link TaskHandlerAction}. * * @throws Exception on error. */ @Test(expected = AuthorizationException.class) public void testExecuteWithQueueServiceActionAuthorizationFailure() throws Exception { final ServiceActionContext serviceActionContext = mockery.mock(ServiceActionContext.class); transDef.setReadOnly(false); final List<UserActionRequest> requests = new ArrayList<UserActionRequest>(); requests.add(userActionRequest); expectTaskHandlerServiceAction(); mockery.checking( new Expectations() { { allowing(queueSubmitterActionMock).isReadOnly(); will(returnValue(false)); oneOf(transMgrMock).getTransaction(transDef); will(returnValue(transStatus)); oneOf(validationStrategy).validate(with(any(ServiceActionContext.class))); oneOf(authorizationStrategy).authorize(with(any(ServiceActionContext.class))); will(throwException(new AuthorizationException())); oneOf(transStatus).isCompleted(); will(returnValue(false)); oneOf(transMgrMock).rollback(transStatus); } }); sut.execute(serviceActionContext, queueSubmitterActionMock); mockery.assertIsSatisfied(); }
/** * 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(expected = InvalidActionException.class) public void testExecuteMissingAuthorization() { ServiceAction action = new ServiceAction(validationStrategy, null, executionStrategy, false); final ServiceActionContext context = new ServiceActionContext(null, principalMock); sut.execute(context, action); mockery.assertIsSatisfied(); }
@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 testRedirectWithSamlIdp() throws Exception { String idplist = Base64.encodeBytes("http://idp1.com".getBytes()) + " " + Base64.encodeBytes("http://idp2.com".getBytes()); final Cookie[] c = new Cookie[] {new Cookie("_saml_idp", URLEncoder.encode(idplist, "UTF-8"))}; c[0].setSecure(true); c[0].setPath("/"); final StringWriter sw = new StringWriter(); context.checking( new Expectations() { { atLeast(1).of(req).getParameter(DiscoveryServlet.REFERER_PARAMETER); will(returnValue("http://localhost")); one(req).getCookies(); will(returnValue(c)); one(res).getWriter(); will(returnValue(new PrintWriter(sw))); one(res).setContentType("text/html"); } }); servlet.doGet(req, res); assertTrue( sw.toString() .indexOf( "0;url=http://localhost?_saml_idp=" + Base64.encodeBytes(URLEncoder.encode(idplist, "UTF-8").getBytes())) > -1); context.assertIsSatisfied(); }