Java Code Examples for org.easymock.IAnswer

The following are top voted examples for showing how to use org.easymock.IAnswer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSourceTaskTest.java   Source Code and License 6 votes vote down vote up
private CountDownLatch expectPolls(int minimum, final AtomicInteger count) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(minimum);
    // Note that we stub these to allow any number of calls because the thread will continue to
    // run. The count passed in + latch returned just makes sure we get *at least* that number of
    // calls
    EasyMock.expect(sourceTask.poll())
            .andStubAnswer(new IAnswer<List<SourceRecord>>() {
                @Override
                public List<SourceRecord> answer() throws Throwable {
                    count.incrementAndGet();
                    latch.countDown();
                    return RECORDS;
                }
            });
    // Fallout of the poll() call
    expectSendRecordAnyTimes();
    return latch;
}
 
Example 2
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSourceTaskTest.java   Source Code and License 6 votes vote down vote up
private void expectApplyTransformationChain(boolean anyTimes) {
    final Capture<SourceRecord> recordCapture = EasyMock.newCapture();
    IExpectationSetters<SourceRecord> convertKeyExpect = EasyMock.expect(transformationChain.apply(EasyMock.capture(recordCapture)));
    if (anyTimes)
        convertKeyExpect.andStubAnswer(new IAnswer<SourceRecord>() {
            @Override
            public SourceRecord answer() {
                return recordCapture.getValue();
            }
        });
    else
        convertKeyExpect.andAnswer(new IAnswer<SourceRecord>() {
            @Override
            public SourceRecord answer() {
                return recordCapture.getValue();
            }
        });
}
 
Example 3
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSinkTaskTest.java   Source Code and License 6 votes vote down vote up
private void expectRebalanceAssignmentError(RuntimeException e) {
    final List<TopicPartition> partitions = asList(TOPIC_PARTITION, TOPIC_PARTITION2);

    sinkTask.close(new HashSet<>(partitions));
    EasyMock.expectLastCall();

    sinkTask.preCommit(EasyMock.<Map<TopicPartition, OffsetAndMetadata>>anyObject());
    EasyMock.expectLastCall().andReturn(Collections.emptyMap());

    EasyMock.expect(consumer.position(TOPIC_PARTITION)).andReturn(FIRST_OFFSET);
    EasyMock.expect(consumer.position(TOPIC_PARTITION2)).andReturn(FIRST_OFFSET);

    sinkTask.open(partitions);
    EasyMock.expectLastCall().andThrow(e);

    EasyMock.expect(consumer.poll(EasyMock.anyLong())).andAnswer(
            new IAnswer<ConsumerRecords<byte[], byte[]>>() {
                @Override
                public ConsumerRecords<byte[], byte[]> answer() throws Throwable {
                    rebalanceListener.getValue().onPartitionsRevoked(partitions);
                    rebalanceListener.getValue().onPartitionsAssigned(partitions);
                    return ConsumerRecords.empty();
                }
            });
}
 
Example 4
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSinkTaskTest.java   Source Code and License 6 votes vote down vote up
private void expectPollInitialAssignment() {
    final List<TopicPartition> partitions = asList(TOPIC_PARTITION, TOPIC_PARTITION2);

    sinkTask.open(partitions);
    EasyMock.expectLastCall();

    EasyMock.expect(consumer.poll(EasyMock.anyLong())).andAnswer(new IAnswer<ConsumerRecords<byte[], byte[]>>() {
        @Override
        public ConsumerRecords<byte[], byte[]> answer() throws Throwable {
            rebalanceListener.getValue().onPartitionsAssigned(partitions);
            return ConsumerRecords.empty();
        }
    });
    EasyMock.expect(consumer.position(TOPIC_PARTITION)).andReturn(FIRST_OFFSET);
    EasyMock.expect(consumer.position(TOPIC_PARTITION2)).andReturn(FIRST_OFFSET);

    sinkTask.put(Collections.<SinkRecord>emptyList());
    EasyMock.expectLastCall();
}
 
Example 5
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSinkTaskTest.java   Source Code and License 6 votes vote down vote up
private void expectConsumerPoll(final int numMessages, final long timestamp, final TimestampType timestampType) {
    EasyMock.expect(consumer.poll(EasyMock.anyLong())).andAnswer(
            new IAnswer<ConsumerRecords<byte[], byte[]>>() {
                @Override
                public ConsumerRecords<byte[], byte[]> answer() throws Throwable {
                    List<ConsumerRecord<byte[], byte[]>> records = new ArrayList<>();
                    for (int i = 0; i < numMessages; i++)
                        records.add(new ConsumerRecord<>(TOPIC, PARTITION, FIRST_OFFSET + recordsReturned + i, timestamp, timestampType, 0L, 0, 0, RAW_KEY, RAW_VALUE));
                    recordsReturned += numMessages;
                    return new ConsumerRecords<>(
                            numMessages > 0 ?
                                    Collections.singletonMap(new TopicPartition(TOPIC, PARTITION), records) :
                                    Collections.<TopicPartition, List<ConsumerRecord<byte[], byte[]>>>emptyMap()
                    );
                }
            });
}
 
Example 6
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSinkTaskThreadedTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRewindOnRebalanceDuringPoll() throws Exception {
    expectInitializeTask();
    expectPollInitialAssignment();

    expectRebalanceDuringPoll().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            Map<TopicPartition, Long> offsets = sinkTaskContext.getValue().offsets();
            assertEquals(0, offsets.size());
            return null;
        }
    });

    expectStopTask();
    PowerMock.replayAll();

    workerTask.initialize(TASK_CONFIG);
    workerTask.initializeAndStart();
    workerTask.iteration();
    workerTask.iteration();
    workerTask.stop();
    workerTask.close();

    PowerMock.verifyAll();
}
 
Example 7
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSinkTaskThreadedTest.java   Source Code and License 6 votes vote down vote up
private void expectPollInitialAssignment() throws Exception {
    final List<TopicPartition> partitions = Arrays.asList(TOPIC_PARTITION, TOPIC_PARTITION2, TOPIC_PARTITION3);

    sinkTask.open(partitions);
    EasyMock.expectLastCall();

    EasyMock.expect(consumer.poll(EasyMock.anyLong())).andAnswer(new IAnswer<ConsumerRecords<byte[], byte[]>>() {
        @Override
        public ConsumerRecords<byte[], byte[]> answer() throws Throwable {
            rebalanceListener.getValue().onPartitionsAssigned(partitions);
            return ConsumerRecords.empty();
        }
    });
    EasyMock.expect(consumer.position(TOPIC_PARTITION)).andReturn(FIRST_OFFSET);
    EasyMock.expect(consumer.position(TOPIC_PARTITION2)).andReturn(FIRST_OFFSET);
    EasyMock.expect(consumer.position(TOPIC_PARTITION3)).andReturn(FIRST_OFFSET);

    sinkTask.put(Collections.<SinkRecord>emptyList());
    EasyMock.expectLastCall();
}
 
Example 8
Project: kafka-0.11.0.0-src-with-comment   File: WorkerSinkTaskThreadedTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private IExpectationSetters<Object> expectOnePoll() {
    // Currently the SinkTask's put() method will not be invoked unless we provide some data, so instead of
    // returning empty data, we return one record. The expectation is that the data will be ignored by the
    // response behavior specified using the return value of this method.
    EasyMock.expect(consumer.poll(EasyMock.anyLong())).andAnswer(
            new IAnswer<ConsumerRecords<byte[], byte[]>>() {
                @Override
                public ConsumerRecords<byte[], byte[]> answer() throws Throwable {
                    // "Sleep" so time will progress
                    time.sleep(1L);
                    ConsumerRecords<byte[], byte[]> records = new ConsumerRecords<>(
                            Collections.singletonMap(
                                    new TopicPartition(TOPIC, PARTITION),
                                    Arrays.asList(
                                            new ConsumerRecord<>(TOPIC, PARTITION, FIRST_OFFSET + recordsReturned, TIMESTAMP, TIMESTAMP_TYPE, 0L, 0, 0, RAW_KEY, RAW_VALUE)
                                    )));
                    recordsReturned++;
                    return records;
                }
            });
    EasyMock.expect(keyConverter.toConnectData(TOPIC, RAW_KEY)).andReturn(new SchemaAndValue(KEY_SCHEMA, KEY));
    EasyMock.expect(valueConverter.toConnectData(TOPIC, RAW_VALUE)).andReturn(new SchemaAndValue(VALUE_SCHEMA, VALUE));
    sinkTask.put(EasyMock.anyObject(Collection.class));
    return EasyMock.expectLastCall();
}
 
Example 9
Project: kafka-0.11.0.0-src-with-comment   File: KafkaConfigBackingStoreTest.java   Source Code and License 6 votes vote down vote up
private void expectStart(final List<ConsumerRecord<String, byte[]>> preexistingRecords,
                         final Map<byte[], Struct> deserializations) throws Exception {
    storeLog.start();
    PowerMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            for (ConsumerRecord<String, byte[]> rec : preexistingRecords)
                capturedConsumedCallback.getValue().onCompletion(null, rec);
            return null;
        }
    });
    for (Map.Entry<byte[], Struct> deserializationEntry : deserializations.entrySet()) {
        // Note null schema because default settings for internal serialization are schema-less
        EasyMock.expect(converter.toConnectData(EasyMock.eq(TOPIC), EasyMock.aryEq(deserializationEntry.getKey())))
                .andReturn(new SchemaAndValue(null, structToMap(deserializationEntry.getValue())));
    }
}
 
Example 10
Project: kafka-0.11.0.0-src-with-comment   File: KafkaConfigBackingStoreTest.java   Source Code and License 6 votes vote down vote up
private void expectConvertWriteRead(final String configKey, final Schema valueSchema, final byte[] serialized,
                                    final String dataFieldName, final Object dataFieldValue) {
    final Capture<Struct> capturedRecord = EasyMock.newCapture();
    if (serialized != null)
        EasyMock.expect(converter.fromConnectData(EasyMock.eq(TOPIC), EasyMock.eq(valueSchema), EasyMock.capture(capturedRecord)))
                .andReturn(serialized);
    storeLog.send(EasyMock.eq(configKey), EasyMock.aryEq(serialized));
    PowerMock.expectLastCall();
    EasyMock.expect(converter.toConnectData(EasyMock.eq(TOPIC), EasyMock.aryEq(serialized)))
            .andAnswer(new IAnswer<SchemaAndValue>() {
                @Override
                public SchemaAndValue answer() throws Throwable {
                    if (dataFieldName != null)
                        assertEquals(dataFieldValue, capturedRecord.getValue().get(dataFieldName));
                    // Note null schema because default settings for internal serialization are schema-less
                    return new SchemaAndValue(null, serialized == null ? null : structToMap(capturedRecord.getValue()));
                }
            });
}
 
Example 11
Project: kafka-0.11.0.0-src-with-comment   File: UtilsTest.java   Source Code and License 6 votes vote down vote up
/**
 * Expectation setter for multiple reads where each one reads random bytes to the buffer.
 *
 * @param channelMock           The mocked FileChannel object
 * @param expectedBufferContent buffer that will be updated to contain the expected buffer content after each
 *                              `FileChannel.read` invocation
 * @param bufferSize            The buffer size
 * @throws IOException          If an I/O error occurs
 */
private void fileChannelMockExpectReadWithRandomBytes(final FileChannel channelMock,
                                                      final StringBuilder expectedBufferContent,
                                                      final int bufferSize) throws IOException {
    final int step = 20;
    final Random random = new Random();
    int remainingBytes = bufferSize;
    while (remainingBytes > 0) {
        final int mockedBytesRead = remainingBytes < step ? remainingBytes : random.nextInt(step);
        final StringBuilder sb = new StringBuilder();
        EasyMock.expect(channelMock.read(EasyMock.anyObject(ByteBuffer.class), EasyMock.anyInt())).andAnswer(new IAnswer<Integer>() {
            @Override
            public Integer answer() throws Throwable {
                ByteBuffer buffer = (ByteBuffer) EasyMock.getCurrentArguments()[0];
                for (int i = 0; i < mockedBytesRead; i++)
                    sb.append("a");
                buffer.put(sb.toString().getBytes());
                expectedBufferContent.append(sb);
                return mockedBytesRead;
            }
        });
        remainingBytes -= mockedBytesRead;
    }
}
 
Example 12
Project: Mastering-Mesos   File: FakeScheduledExecutor.java   Source Code and License 6 votes vote down vote up
private static IAnswer<ScheduledFuture<?>> answerScheduleAtFixedRate(
    FakeScheduledExecutor executor,
    int workCount) {

  return () -> {
    Object[] args = EasyMock.getCurrentArguments();
    Runnable work = (Runnable) args[0];
    long initialDelay = (Long) args[1];
    long period = (Long) args[2];
    TimeUnit unit = (TimeUnit) args[3];
    for (int i = 0; i <= workCount; i++) {
      addDelayedWork(executor, toMillis(initialDelay, unit) + i * toMillis(period, unit), work);
    }
    return null;
  };
}
 
Example 13
Project: aries-rsa   File: RemoteServiceAdminCoreTest.java   Source Code and License 6 votes vote down vote up
private ServiceReference mockServiceReference(final Map<String, Object> sProps) throws ClassNotFoundException {
    BundleContext bc = EasyMock.createNiceMock(BundleContext.class);

    Bundle b = EasyMock.createNiceMock(Bundle.class);
    EasyMock.expect(b.getBundleContext()).andReturn(bc).anyTimes();
    EasyMock.expect((Class)b.loadClass(Runnable.class.getName())).andReturn(Runnable.class);
    EasyMock.replay(b);

    EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes();
    EasyMock.replay(bc);

    ServiceReference sref = EasyMock.createNiceMock(ServiceReference.class);
    EasyMock.expect(sref.getBundle()).andReturn(b).anyTimes();
    EasyMock.expect(sref.getPropertyKeys()).andReturn(sProps.keySet().toArray(new String[] {})).anyTimes();
    EasyMock.expect(sref.getProperty((String) EasyMock.anyObject())).andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            return sProps.get(EasyMock.getCurrentArguments()[0]);
        }
    }).anyTimes();
    EasyMock.replay(sref);
    return sref;
}
 
Example 14
Project: aries-rsa   File: LengthPrefixedCodecTest.java   Source Code and License 6 votes vote down vote up
@Test(expected=ProtocolException.class)
public void testReadEvilPackage() throws Exception {

    expect(readableByteChannel.read(EasyMock.anyObject())).andAnswer(new IAnswer<Integer>() {

        @Override
        public Integer answer() throws Throwable {
            ByteBuffer buffer = (ByteBuffer)EasyMock.getCurrentArguments()[0];
            // an attacker could do that to provoke out of memory
            buffer.putInt(Integer.MAX_VALUE-1);
            return 1;
        }
    });
    replay(readableByteChannel);
    codec.read();
}
 
Example 15
Project: communote-server   File: FavoriteMatcherTest.java   Source Code and License 6 votes vote down vote up
/**
 * The test.
 */
@Test
public void testMatches() {
    NoteData note = new NoteData();
    note.setId(0L);
    FavoriteManagement favoriteManagement = EasyMock.createMock(FavoriteManagement.class);
    EasyMock.expect(favoriteManagement.isFavorite(EasyMock.anyLong())).andAnswer(
            new IAnswer<Boolean>() {
                @Override
                public Boolean answer() throws Throwable {
                    return EasyMock.getCurrentArguments()[0].equals(1L);
                }
            }).anyTimes();
    EasyMock.replay(favoriteManagement);

    Matcher<NoteData> matcher = new FavoriteMatcher(favoriteManagement);
    Assert.assertFalse(matcher.matches(note));

    note.setId(1L);
    Assert.assertTrue(matcher.matches(note));
}
 
Example 16
Project: communote-server   File: ADTrackingIncrementalRepositoryChangeTrackerTest.java   Source Code and License 6 votes vote down vote up
/**
 * Method to setup the group dao.
 */
@BeforeMethod
public void setupExternalUserGroupDao() {
    externalUserGroupDao = EasyMock.createMock(ExternalUserGroupDao.class);
    IAnswer<ExternalUserGroup> answer = new IAnswer<ExternalUserGroup>() {
        @Override
        public ExternalUserGroup answer() throws Throwable {
            ExternalUserGroup group = ExternalUserGroup.Factory.newInstance();
            group.setId(externalUsersCounter++);
            group.setAlias(String.valueOf(EasyMock.getCurrentArguments()[0]));
            return group;
        }
    };
    EasyMock.expect(
            externalUserGroupDao.findByExternalId(EasyMock.anyObject(String.class),
                    EasyMock.anyObject(String.class))).andAnswer(answer).anyTimes();
    EasyMock.replay(externalUserGroupDao);
}
 
Example 17
Project: communote-server   File: ADTrackingIncrementalRepositoryChangeTrackerTest.java   Source Code and License 6 votes vote down vote up
/**
 * Setups the {@link UserManagement}.
 */
@BeforeMethod
public void setupUserManagement() {
    userManagement = EasyMock.createMock(UserManagement.class);
    IAnswer<User> answer = new IAnswer<User>() {
        @Override
        public User answer() throws Throwable {
            User user = User.Factory.newInstance();
            user.setId(externalUsersCounter++);
            user.setAlias(EasyMock.getCurrentArguments()[0].toString());
            user.setEmail(EasyMock.getCurrentArguments()[0] + "@example-test.com");
            user.setProfile(UserProfile.Factory.newInstance());
            user.getProfile().setFirstName(EasyMock.getCurrentArguments()[0].toString());
            user.getProfile().setLastName(EasyMock.getCurrentArguments()[0].toString());
            return user;
        }
    };
    EasyMock.expect(
            userManagement.findUserByExternalUserId(EasyMock.anyObject(String.class),
                    EasyMock.anyObject(String.class))).andAnswer(answer).anyTimes();
    EasyMock.replay(userManagement);
}
 
Example 18
Project: intellij-ce-playground   File: DeviceTest.java   Source Code and License 6 votes vote down vote up
/** Helper method that sets the mock device to return the given response on a shell command */
@SuppressWarnings("unchecked")
static void injectShellResponse(IDevice mockDevice, final String response) throws Exception {
    IAnswer<Object> shellAnswer = new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            // insert small delay to simulate latency
            Thread.sleep(50);
            IShellOutputReceiver receiver =
                (IShellOutputReceiver)EasyMock.getCurrentArguments()[1];
            byte[] inputData = response.getBytes();
            receiver.addOutput(inputData, 0, inputData.length);
            return null;
        }
    };
    mockDevice.executeShellCommand(EasyMock.<String>anyObject(),
                EasyMock.<IShellOutputReceiver>anyObject(),
                EasyMock.anyLong(), EasyMock.<TimeUnit>anyObject());
    EasyMock.expectLastCall().andAnswer(shellAnswer);
}
 
Example 19
Project: training   File: BatchUploadProcessorTest.java   Source Code and License 6 votes vote down vote up
private void expectFindConsumerByEmail() {
	final Capture<String> consumerEmailCapture = new Capture<>();
	expect(consumerService.getConsumerByEmail(capture(consumerEmailCapture))).andAnswer(new IAnswer<Consumer>() {
		@Override
		public Consumer answer() throws Throwable {
			String email = consumerEmailCapture.getValue();
			Consumer consumer = new Consumer();
			consumer.setEmailAddress(email);
			Address oldAddress = new Address();
			oldAddress.setStreet("Old Street");
			oldAddress.setNumber("old nr");
			oldAddress.setPostalCode("1234");
			oldAddress.setCity("Old City");
			consumer.setAddress(oldAddress);
			return consumer;
		}
	}).anyTimes();
}
 
Example 20
Project: proarc   File: TiffImporterTest.java   Source Code and License 6 votes vote down vote up
private DaoFactory createMockDaoFactory() {
    DaoFactory daos = EasyMock.createMock(DaoFactory.class);
    EasyMock.expect(daos.createTransaction()).andAnswer(new IAnswer<Transaction>() {

        @Override
        public Transaction answer() throws Throwable {
            return createMockTransaction();
        }
    }).anyTimes();
    EasyMock.expect(daos.createBatchItem()).andAnswer(new IAnswer<BatchItemDao>() {

        @Override
        public BatchItemDao answer() throws Throwable {
            return createMockBatchItemDao();
        }
    }).anyTimes();
    EasyMock.replay(daos);
    toVerify.add(daos);
    return daos;
}
 
Example 21
Project: search   File: MockInitialContextFactory.java   Source Code and License 6 votes vote down vote up
public MockInitialContextFactory() {
  mockControl = EasyMock.createStrictControl();
  context = mockControl.createMock(javax.naming.Context.class);

  try {
    EasyMock.expect(context.lookup((String) EasyMock.anyObject())).andAnswer(
        new IAnswer<Object>() {
          @Override
          public Object answer() throws Throwable {
            return objects.get(EasyMock.getCurrentArguments()[0]);
          }
        }).anyTimes();

  } catch (NamingException e) {
    throw new RuntimeException(e);
  }

  mockControl.replay();
}
 
Example 22
Project: pasteque-android   File: AbstractDataTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
@Before
public void setup() throws IOException {
    this.fakeContext = createMock(Context.class);
    java.io.File file = new java.io.File(TMP_FILENAME_EMPTY);
    file.getParentFile().mkdirs();
    file.createNewFile();
    file = new java.io.File(getFullTmpFilename());
    file.getParentFile().mkdirs();
    file.createNewFile();
    mockStatic(Pasteque.class);
    expect(Pasteque.getAppContext()).andStubReturn(this.fakeContext);
    expect(fakeContext.getDir(anyString(), anyInt())).andStubAnswer(new IAnswer<java.io.File>() {
        @Override
        public java.io.File answer() throws Throwable {
            return new java.io.File(Constant.BUILD_FOLDER);
        }
    });
}
 
Example 23
Project: superfly   File: InternalSSOServiceImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRegisterUserPasswordEncoding() throws Exception {
    MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder();
    encoder.setAlgorithm("md5");
    internalSSOService.setPasswordEncoder(encoder);
    internalSSOService.setSaltSource(new ConstantSaltSource("e2e4"));
    expect(userDao.getUserPasswordHistoryAndCurrentPassword("user")).andReturn(
            Collections.<PasswordSaltPair>emptyList());
    expect(userDao.registerUser(anyObject(UserRegisterRequest.class))).andAnswer(new IAnswer<RoutineResult>() {
        public RoutineResult answer() throws Throwable {
            UserRegisterRequest user = (UserRegisterRequest) getCurrentArguments()[0];
            assertEquals(DigestUtils.md5Hex("secret{e2e4}"), user.getPassword());
            assertNotNull(user.getHotpSalt());
            user.setUserid(1L);
            return RoutineResult.okResult();
        }
    });
    hotpService.sendTableIfSupported("subsystem", 1L);
    expectLastCall();
    replay(userDao, hotpService);
    internalSSOService.registerUser("user", "secret", "email", "subsystem", new RoleGrantSpecification[]{}, "user",
            "user", "question", "answer", null, "test organization");
    verify(userDao, hotpService);
}
 
Example 24
Project: superfly   File: UserServiceLoggingTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCloneUser() throws Exception {
    EasyMock.expect(userDao.cloneUser(anyObject(UICloneUserRequest.class))).andAnswer(new IAnswer<RoutineResult>() {
        public RoutineResult answer() throws Throwable {
            UICloneUserRequest user = (UICloneUserRequest) EasyMock.getCurrentArguments()[0];
            user.setId(1L);
            return okResult();
        }
    });
    loggerSink.info(anyObject(Logger.class), eq("CLONE_USER"), eq(true), eq("1->new-user"));
    EasyMock.replay(loggerSink, userDao);

    userService.cloneUser(1L, "new-user", "new-password", "new-email", "new key", null);

    EasyMock.verify(loggerSink);
}
 
Example 25
Project: superfly   File: UserServiceImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCloneUserPasswordEncryption() throws MessageSendException {
    EasyMock.expect(userDao.cloneUser(anyObject(UICloneUserRequest.class))).andAnswer(new IAnswer<RoutineResult>() {
        public RoutineResult answer() throws Throwable {
            UICloneUserRequest user = (UICloneUserRequest) EasyMock.getCurrentArguments()[0];
            assertEquals(DigestUtils.shaHex("secret{c3pio}"), user.getPassword());
            user.setId(1L);
            return RoutineResult.okResult();
        }
    });
    EasyMock.replay(userDao);

    userService.cloneUser(1L, "pete", "secret", "email", "new key", null);

    EasyMock.verify(userDao);
}
 
Example 26
Project: superfly   File: UserServiceImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCloneUser() throws MessageSendException {
    EasyMock.expect(userDao.cloneUser(anyObject(UICloneUserRequest.class))).andAnswer(new IAnswer<RoutineResult>() {
        public RoutineResult answer() throws Throwable {
            UICloneUserRequest user = (UICloneUserRequest) EasyMock.getCurrentArguments()[0];
            assertEquals("pete", user.getUsername());
            assertNotNull(user.getPassword());
            assertEquals("new-email", user.getEmail());
            assertNotNull(user.getSalt());
            assertNotNull(user.getHotpSalt());
            user.setId(1L);
            return RoutineResult.okResult();
        }
    });
    EasyMock.replay(userDao);

    userService.cloneUser(1L, "pete", "secret", "new-email", "new key", null);

    EasyMock.verify(userDao);
}
 
Example 27
Project: superfly   File: SuperflyUsernamePasswordAuthenticationProcessingFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAuthenticate() throws Exception {
    // expecting some request examination...
    initExpectationsForAuthentication();
    // expecting authentication attempt
    expect(authenticationManager.authenticate(anyObject(UsernamePasswordAuthRequestInfoAuthenticationToken.class)))
            .andAnswer(new IAnswer<Authentication>() {
                public Authentication answer() throws Throwable {
                    CompoundAuthentication compound = (CompoundAuthentication) EasyMock.getCurrentArguments()[0];
                    UsernamePasswordAuthRequestInfoAuthenticationToken token = (UsernamePasswordAuthRequestInfoAuthenticationToken) compound.getCurrentAuthenticationRequest();
                    assertEquals("192.168.0.4", token.getAuthRequestInfo().getIpAddress());
                    assertEquals("my-subsystem", token.getAuthRequestInfo().getSubsystemIdentifier());
                    return new UsernamePasswordCheckedToken(createSSOUserWithOneRole());
                }
            });
    // expecting a redirect to a success
    expectRedirectTo("/");
    replay(request, response, chain, authenticationManager);

    filter.doFilter(request, response, chain);
    assertTrue(SecurityContextHolder.getContext().getAuthentication() instanceof UsernamePasswordCheckedToken);

    verify(request, response, chain, authenticationManager);
}
 
Example 28
Project: superfly   File: SuperflySSOAuthenticationProcessingFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAuthenticate() throws Exception {
    // expecting some request examination...
    initExpectationsForAuthentication();
    // expecting authentication attempt
    expect(authenticationManager.authenticate(anyObject(SSOAuthenticationRequest.class)))
            .andAnswer(new IAnswer<Authentication>() {
                public Authentication answer() throws Throwable {
                    CompoundAuthentication compound = (CompoundAuthentication) EasyMock.getCurrentArguments()[0];
                    SSOAuthenticationRequest token = (SSOAuthenticationRequest) compound.getCurrentAuthenticationRequest();
                    assertEquals("abcdef", token.getSubsystemToken());
                    return new UsernamePasswordCheckedToken(createSSOUserWithOneRole());
                }
            });
    // expecting a redirect to a success
    expectRedirectTo("/");
    replay(request, response, chain, authenticationManager);

    filter.doFilter(request, response, chain);
    assertTrue(SecurityContextHolder.getContext().getAuthentication() instanceof UsernamePasswordCheckedToken);

    verify(request, response, chain, authenticationManager);
}
 
Example 29
Project: superfly   File: SuperflyHOTPAuthenticationProcessingFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testAuthenticate() throws Exception {
    // expecting some request examination...
    initExpectationsForAuthentication();
    // expecting authentication attempt
    expect(authenticationManager.authenticate(anyObject(CheckHOTPToken.class)))
            .andAnswer(new IAnswer<Authentication>() {
                public Authentication answer() throws Throwable {
                    CompoundAuthentication compound = (CompoundAuthentication) EasyMock.getCurrentArguments()[0];
                    CheckHOTPToken token = (CheckHOTPToken) compound.getCurrentAuthenticationRequest();
                    assertEquals("pete", token.getName());
                    assertEquals("123456", token.getCredentials().toString());
                    return new HOTPCheckedToken(createSSOUserWithOneRole());
                }
            });
    // expecting a redirect to success
    expectRedirectTo("/");
    replay(request, response, chain, authenticationManager);

    SecurityContextHolder.getContext().setAuthentication(createInputAuthentication());
    filter.doFilter(request, response, chain);
    assertTrue("Got " + SecurityContextHolder.getContext().getAuthentication().getClass(),
            SecurityContextHolder.getContext().getAuthentication() instanceof HOTPCheckedToken);

    verify(request, response, chain, authenticationManager);
}
 
Example 30
Project: gitlab-auth-plugin   File: MockDataCreators.java   Source Code and License 6 votes vote down vote up
/**
 * Mocks the constructor of {@link GitLabFolderAuthorization}.
 *
 * Mocks constructor calls to {@link GitLabFolderAuthorization} with an int parameter returning a mock folder
 * authorization object from {@link #mockFolderAuthorization(int)}.
 *
 * Note: the test class must run with {@link PowerMockRunner} and prepare the {@link GitLabFolderAuthorization}
 * class and the class invoking the constructor for testing with PowerMock.
 */
public static void expectNewFolderAuthorization() {
    try {
        // create a new mock folder authorization with the groupId parameter when the constructor is invoked
        expectNew(GitLabFolderAuthorization.class, anyInt())
                .andAnswer(new IAnswer<GitLabFolderAuthorization>() {
                    public GitLabFolderAuthorization answer() throws Throwable {
                        return mockFolderAuthorization((Integer)getCurrentArguments()[0]);
                    }
                }).anyTimes();
        PowerMock.replay(GitLabFolderAuthorization.class);
    } catch (Exception e) {
        // not expected to throw an exception, rethrow as runtime exception
        throw new RuntimeException(e);
    }
}
 
Example 31
Project: xgogdownloader   File: MainTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testHelp() throws Exception {
	reset(mockedFactory);
	createFactoryExpectations(null, null, mockedFOS, folderMock, fileMock);

	expect(mockedFactory.pGetApi()).andStubAnswer(new IAnswer<IApi>() {
		@Override
		public IApi answer() throws Throwable {
			Assert.fail("GogApi not needed for Version/Help command");
			return null;
		}
	});
	expect(mockedFactory.pCreateHttpClient()).andStubAnswer(
			new IAnswer<HttpClient>() {
				@Override
				public HttpClient answer() throws Throwable {
					Assert.fail("HttpClient not needed for Version/Help command");
					return null;
				}
			});
	replay(mockedFactory);
	Main.main(new String[] { "-help" });
	Main.main(new String[] { "-version" });
	Assert.assertEquals("", errContent.toString("UTF-8"));
}
 
Example 32
Project: reviki   File: TestWikiUrlsImpl.java   Source Code and License 6 votes vote down vote up
public void testNoFixedBaseUrl() {
  expect(_applicationUrls.url((String) EasyMock.anyObject())).andAnswer(new IAnswer<String>() {
    public String answer() {
      String relative = (String) EasyMock.getCurrentArguments()[0];
      return "http://www.example.com/reviki" + relative;
    }
  }).anyTimes();
  expect(_configuration.getWikiName()).andReturn("foo");
  expect(_configuration.getFixedBaseUrl((String) EasyMock.anyObject())).andReturn(null).anyTimes();
  WikiUrlsImpl urls = createURLs("foo");
  assertEquals("http://www.example.com/reviki/pages/foo/", urls.pagesRoot());
  assertEquals("http://www.example.com/reviki/pages/foo/Spaced%20Out", urls.page(null, "Spaced Out"));
  assertEquals("http://www.example.com/reviki/pages/foo/Spaced+Out", urls.page(null, "Spaced+Out"));
  assertEquals("http://www.example.com/reviki/pages/foo/RecentChanges?ctype=atom", urls.feed());
  assertEquals("http://www.example.com/reviki/pages/foo/FindPage", urls.search());
}
 
Example 33
Project: reviki   File: TestSVNPageStore.java   Source Code and License 6 votes vote down vote up
public void testDeleteAttachment() throws Exception {
  final String pageName = "ThePage";
  final PageReference pageRef = new PageReferenceImpl(pageName);
  final String attachmentName = "attachment.txt";
  _operations.execute((SVNEditAction) anyObject());
  expectLastCall().andAnswer(new IAnswer<Object>() {
    public Object answer() throws Throwable {
      SVNEditAction action = (SVNEditAction) getCurrentArguments()[0];
      action.driveCommitEditor(_commitEditor, _operations);
      return 2L;
    }
  });
  _operations.delete((ISVNEditor) anyObject(), eq("ThePage-attachments/attachment.txt"), eq(-1L));
  replay();
  assertEquals(2, _store.deleteAttachment(pageRef, attachmentName, -1, "A delete"));
  verify();
}
 
Example 34
Project: reviki   File: TestSVNPageStore.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void testGetPage() throws PageStoreException {
  final String content = "Content";
  PageReferenceImpl ref = new PageReferenceImpl("Page");
  expect(_operations.checkPath(ref.getPath(), -1L)).andReturn(SVNNodeKind.FILE);
  _operations.getFile(eq(ref.getPath()), eq(-1L), (Map<String, String>) anyObject(), (OutputStream) anyObject());
  expectLastCall().andAnswer(new IAnswer<Object>() {
    public Object answer() throws Throwable {
      OutputStream out = (OutputStream) getCurrentArguments()[3];
      out.write(content.getBytes());
      return null;
    }
  });
  expect(_operations.getLock(ref.getPath())).andReturn(null);
  replay();
  VersionedPageInfo returnValue = _store.get(ref, -1);
  assertEquals(ref.getName(), returnValue.getName());
  assertEquals(content, returnValue.getContent());
  assertEquals(MapUtils.EMPTY_MAP, returnValue.getAttributes());
  verify();
}
 
Example 35
Project: collabware   File: AbstractCometdProtocolEndpointTest.java   Source Code and License 6 votes vote down vote up
private BayeuxServer createBayeuxService() {
	BayeuxServer bayeux = createMock(BayeuxServer.class);
	BayeuxContext context = createMock(BayeuxContext.class);
	expect(context.getHttpSessionAttribute(HttpSessionAttributes.COLLABWARE_AUTHENTICATED_USER)).andStubReturn(createMockUser());
	expect(bayeux.getContext()).andStubReturn(context);
	final Capture<String> sessionId = new Capture<String>();
	expect(bayeux.getSession(capture(sessionId))).andStubAnswer(new IAnswer< ServerSession >() {

		@Override
		public  ServerSession answer() throws Throwable {
			return sessions.get(sessionId.getValue());
		}});
	
	replay(context, bayeux);
	return bayeux;
}
 
Example 36
Project: collabware   File: AbstractCometdProtocolEndpointTest.java   Source Code and License 6 votes vote down vote up
protected ServerSession mockRemoteSession(final ExpectedMessage ...expectedMessages) {
	ServerSession remote = createMock(ServerSession.class);
	String id = UUID.randomUUID().toString();
	expect(remote.getId()).andStubReturn(id);
	for (final ExpectedMessage messageReceiver: expectedMessages) {
		final Capture<JSONObject> payload = new Capture<JSONObject>();
		final Capture<String> channel = new Capture<String>();
		remote.deliver(anyObject(ServerSession.class), capture(channel), capture(payload), anyObject(String.class));
		expectLastCall().andAnswer(new IAnswer<Object>() {
			public Object answer() throws Throwable {
				messageReceiver.expect(channel.getValue(), payload.getValue());
				return null;
			}
		}).once();
	}
	
	remote.addListener(anyObject(RemoveListener.class));
	expectLastCall().once();
	
	replay(remote);
	sessions.put(id, remote);
	return remote;
}
 
Example 37
Project: collabware   File: ClientProxyTest.java   Source Code and License 6 votes vote down vote up
private ModifyableCollaboration createCollaborationExpectingOperationsWithContexts(Context ... expectedContexts) throws ConflictingOperationsException {
	ModifyableCollaboration collaboration = createMock(ModifyableCollaboration.class);
	for (final Context expectedContext: expectedContexts) {
		final Capture<ContextualizedComplexOperation> op = new Capture<ContextualizedComplexOperation>();
		collaboration.apply(capture(op), anyObject(User.class));
		expectLastCall().andAnswer(new IAnswer<Object>() {
			@Override
			public Object answer() throws Throwable {
				assertEquals(expectedContext, op.getValue().getContext());
				return null;
			}
		});
	}
	
	replay(collaboration);
	return collaboration;
}
 
Example 38
Project: todo-apps   File: MongoStoreTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testPersist() {
	DBCollection coll = createMockCollection();
	ToDo td = new ToDo();
	td.setTitle("This is a test");
	td.setId("aaaaaaaaaaaaaaaaaaaaaaa1");
	expect(coll.insert(isA(DBObject.class))).andAnswer(new IAnswer<WriteResult>() {
		@Override
		public WriteResult answer() throws Throwable {
			DBObject obj = (DBObject)getCurrentArguments()[0];
			obj.put("_id", new ObjectId("aaaaaaaaaaaaaaaaaaaaaaa1"));
			return null;
		}
	});
	replay(coll);
	MongoStore store = new MongoStore(coll);
	assertEquals(td, store.persist(td));
	verify(coll);
}
 
Example 39
Project: NYBC   File: MockInitialContextFactory.java   Source Code and License 6 votes vote down vote up
public MockInitialContextFactory() {
  mockControl = EasyMock.createStrictControl();
  context = mockControl.createMock(javax.naming.Context.class);

  try {
    EasyMock.expect(context.lookup((String) EasyMock.anyObject())).andAnswer(
        new IAnswer<Object>() {
          @Override
          public Object answer() throws Throwable {
            return objects.get(EasyMock.getCurrentArguments()[0]);
          }
        }).anyTimes();

  } catch (NamingException e) {
    throw new RuntimeException(e);
  }

  mockControl.replay();
}
 
Example 40
Project: opennmszh   File: DroolsTicketerServiceLayerTest.java   Source Code and License 6 votes vote down vote up
/**
 * @param state
 */
private void expectNewTicket() {
    try {
        m_ticketerPlugin.saveOrUpdate(EasyMock.isA(Ticket.class));
    } catch (PluginException e) {
        e.printStackTrace();
    }
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        public Object answer() throws Throwable {
            Ticket ticket = (Ticket) EasyMock.getCurrentArguments()[0];
            assertNull(ticket.getId());
            ticket.setId("7");
            
            //
            // Verify the properties as generated by the Drools engine
            //
            assertEquals("Not Test Logmsg", ticket.getSummary());
            assertEquals("Not Test Description", ticket.getDetails());
            assertEquals("Jesse", ticket.getUser());
            return null;
        }
    });
}