@SuppressWarnings("unchecked") @Test public void testAuthenticateTMForController_controllerSettingsMatch() throws Throwable { // given Map<String, String> proxySettings = getProxySettingsForMode("INTERNAL"); Map<String, Setting> controlleSettings = getControllerSettingsForOrg("tp123"); Mockito.doReturn(proxySettings).when(configService).getAllProxyConfigurationSettings(); Mockito.doReturn(controlleSettings) .when(configService) .getControllerConfigurationSettings(Matchers.anyString()); Mockito.doReturn(new PasswordAuthentication("user", "pass")) .when(configService) .getAuthenticationForBESTechnologyManager( Matchers.anyString(), Matchers.any(ServiceInstance.class), Matchers.anyMap()); Mockito.doReturn(null) .when(authService) .getAuthenticatedTMForController( Matchers.anyString(), Matchers.any(PasswordAuthentication.class)); // when authenticateTMForController(CTRL_ID, "user", "pass"); // then Mockito.verify(authService, Mockito.times(0)) .getAuthenticatedTMForController( Matchers.anyString(), Matchers.any(PasswordAuthentication.class)); }
@SuppressWarnings("unchecked") @Test public void testAuthenticateTMForInstance_SSO() throws Throwable { // given Map<String, String> settings = getProxySettingsForMode("SAML_SP"); createServiceInstance( ProvisioningStatus.COMPLETED, InstanceParameter.BSS_USER, InstanceParameter.BSS_USER_PWD); VOUserDetails manager = createVOUserDetails(10000, "user", "tp123"); manager.setUserRoles(Collections.singleton(UserRoleType.TECHNOLOGY_MANAGER)); Mockito.doReturn(manager) .when(besDAO) .getUserDetails( Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString()); Mockito.doReturn(new PasswordAuthentication("nobody", "")) .when(configService) .getWebServiceAuthentication(Matchers.any(ServiceInstance.class), Matchers.anyMap()); Mockito.doReturn(settings).when(configService).getAllProxyConfigurationSettings(); // when authenticateTMForInstance(CTRL_ID, "appInstanceId", manager.getUserId(), "pass"); // then Mockito.verify(besDAO, Mockito.times(0)) .getUser(Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class)); Mockito.verify(besDAO, Mockito.times(2)) .getUserDetails( Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString()); }
@SuppressWarnings("unchecked") @Test public void testAuthenticateAdministrator_SSO() throws Throwable { // given Map<String, String> settings = getProxySettingsForMode("SAML_SP"); VOUserDetails admin = createVOUserDetails(1000, "admin", "org"); admin.setUserRoles(Collections.singleton(UserRoleType.ORGANIZATION_ADMIN)); Mockito.doReturn(admin) .when(besDAO) .getUserDetails( Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString()); Mockito.doReturn(new PasswordAuthentication("nobody", "")) .when(configService) .getWebServiceAuthentication(Matchers.any(ServiceInstance.class), Matchers.anyMap()); Mockito.doReturn(settings).when(configService).getAllProxyConfigurationSettings(); // when authService.authenticateAdministrator( new PasswordAuthentication(admin.getUserId(), "admin123")); // then Mockito.verify(besDAO, Mockito.times(0)) .getUser(Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class)); }
@Test public void lockBlockTest() throws Exception { Map<String, String> params = new HashMap<>(); params.put("blockId", "1"); params.put("sessionId", "1"); LockBlockResult lockBlockResult = LockBlockResultTest.createRandom(); Mockito.doReturn(lockBlockResult.getLockId()) .when(mBlockWorker) .lockBlock(Mockito.anyLong(), Mockito.anyLong()); Mockito.doReturn(lockBlockResult.getBlockPath()) .when(mBlockWorker) .readBlock(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); TestCaseFactory.newWorkerTestCase( getEndpoint(BlockWorkerClientRestServiceHandler.LOCK_BLOCK), params, "POST", lockBlockResult, mResource) .run(); Mockito.verify(mBlockWorker).lockBlock(Mockito.anyLong(), Mockito.anyLong()); Mockito.verify(mBlockWorker).readBlock(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); }
public static ViewContext viewContext() { UserInterfaceSettings settings = Mockito.mock(UserInterfaceSettings.class); Mockito.doReturn("https://somehost.org").when(settings).getHostUri(); Mockito.doReturn("/piecework/ui").when(settings).getApplicationUrl(); Mockito.doReturn("/piecework/api").when(settings).getServiceUrl(); return new ViewContext(settings, "v0"); }
@Test public void testAuthenticateTMForController_SSO() throws Throwable { // given Map<String, String> proxySettings = getProxySettingsForMode("SAML_SP"); Map<String, Setting> controlleSettings = getControllerSettingsForOrg("tp123"); VOUserDetails manager = createVOUserDetails(10001, "user", "tp123"); manager.setUserRoles(Collections.singleton(UserRoleType.TECHNOLOGY_MANAGER)); Mockito.doReturn(proxySettings).when(configService).getAllProxyConfigurationSettings(); Mockito.doReturn(controlleSettings) .when(configService) .getControllerConfigurationSettings(Matchers.anyString()); Mockito.doReturn(manager) .when(besDAO) .getUserDetails( Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString()); // when authenticateTMForController(CTRL_ID, manager.getUserId(), "pass"); // then Mockito.verify(besDAO, Mockito.times(0)) .getUser(Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class)); Mockito.verify(besDAO, Mockito.times(1)) .getUserDetails( Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString()); }
private void mockContact() { Set<String> phoneNumbers = new HashSet<String>(); phoneNumbers.add(CONTACT_NUMBER); mContact = Mockito.mock(Contact.class); Mockito.doReturn(CONTACT_NAME).when(mContact).getDisplayName(); Mockito.doReturn(phoneNumbers).when(mContact).getPhoneNumbers(); }
/** * MulticolorLayout can throw if color name is not valid. * * @throws Exception If something goes wrong */ @Test(expected = IllegalArgumentException.class) public void throwsOnIllegalColorName() throws Exception { final MulticolorLayout layout = new MulticolorLayout(); layout.setConversionPattern("%color-oops{%p} %m"); final LoggingEvent event = Mockito.mock(LoggingEvent.class); Mockito.doReturn(Level.DEBUG).when(event).getLevel(); Mockito.doReturn("text").when(event).getRenderedMessage(); layout.format(event); }
public StubHttpProvider() { byte[] bytes = {1}; Mockito.doReturn(new HeaderAndBody(bytes, new HashMap<String, Object>())) .when(mock) .post((String) Mockito.any()); Mockito.doReturn(new HeaderAndBody(bytes, new HashMap<String, Object>())) .when(mock) .delete((String) Mockito.any()); }
/** * MulticolorLayout can transform event to text. * * @throws Exception If something goes wrong */ @Test public void transformsLoggingEventToText() throws Exception { final MulticolorLayout layout = new MulticolorLayout(); layout.setConversionPattern(MulticolorLayoutTest.CONV_PATTERN); final LoggingEvent event = Mockito.mock(LoggingEvent.class); Mockito.doReturn(Level.DEBUG).when(event).getLevel(); Mockito.doReturn("hello").when(event).getRenderedMessage(); MatcherAssert.assertThat( StringEscapeUtils.escapeJava(layout.format(event)), Matchers.equalTo("[\\u001B[2;37mDEBUG\\u001B[m] \\u001B[2;37mhello\\u001B[m")); }
/** * MulticolorLayout can render custom color. * * @throws Exception If something goes wrong */ @Test public void rendersCustomConstantColor() throws Exception { final MulticolorLayout layout = new MulticolorLayout(); layout.setConversionPattern("%color-red{%p} %m"); final LoggingEvent event = Mockito.mock(LoggingEvent.class); Mockito.doReturn(Level.DEBUG).when(event).getLevel(); Mockito.doReturn("foo").when(event).getRenderedMessage(); MatcherAssert.assertThat( StringEscapeUtils.escapeJava(layout.format(event)), Matchers.equalTo("\\u001B[31mDEBUG\\u001B[m foo")); }
/** * MulticolorLayout can transform event to text. * * @throws Exception If something goes wrong */ @Test public void overwriteDefaultColor() throws Exception { final MulticolorLayout layout = new MulticolorLayout(); layout.setConversionPattern(MulticolorLayoutTest.CONV_PATTERN); layout.setLevels("INFO:2;10"); final LoggingEvent event = Mockito.mock(LoggingEvent.class); Mockito.doReturn(Level.INFO).when(event).getLevel(); Mockito.doReturn("change").when(event).getRenderedMessage(); MatcherAssert.assertThat( StringEscapeUtils.escapeJava(layout.format(event)), Matchers.equalTo("[\\u001B[2;10mINFO\\u001B[m] \\u001B[2;10mchange\\u001B[m")); }
@Ignore // TODO in besDAO @Test(expected = AuthenticationException.class) public void testAuthenticateTMForInstance_wrongCreds() throws Throwable { createServiceInstance(ProvisioningStatus.COMPLETED, InstanceParameter.PUBLIC_IP); VOUserDetails user = createVOUserDetails(10000, "supplier", "tp123"); Mockito.doReturn(user).when(identityService).getCurrentUserDetails(); Mockito.doReturn(user).when(identityService).getUser(Matchers.any(VOUser.class)); authenticateTMForInstance( CTRL_ID, "appInstanceId", new PasswordAuthentication("supplier", "wrong")); }
// Suppress non relevant warning due to mockito internal stuff @SuppressWarnings("unchecked") private AppInsightsConfigurationBuilder createMockParser( boolean withChannel, boolean setChannel, boolean withPerformanceModules) { AppInsightsConfigurationBuilder mockParser = Mockito.mock(AppInsightsConfigurationBuilder.class); ApplicationInsightsXmlConfiguration appConf = new ApplicationInsightsXmlConfiguration(); appConf.setSdkLogger(new SDKLoggerXmlElement()); if (withChannel) { ChannelXmlElement channelXmlElement = new ChannelXmlElement(); channelXmlElement.setEndpointAddress(MOCK_ENDPOINT); String channelType = null; if (setChannel) { channelType = "com.microsoft.applicationinsights.internal.channel.stdout.StdOutChannel"; channelXmlElement.setType(channelType); } appConf.setChannel(channelXmlElement); } if (withPerformanceModules) { PerformanceCountersXmlElement performanceCountersXmlElement = new PerformanceCountersXmlElement(); appConf.setPerformance(performanceCountersXmlElement); } Mockito.doReturn(appConf).when(mockParser).build(any(InputStream.class)); return mockParser; }
@Test public final void testSequenceNumberValidator() { IKinesisProxy proxy = Mockito.mock(IKinesisProxy.class); SequenceNumberValidator validator = new SequenceNumberValidator(proxy, shardId, validateWithGetIterator); String goodSequence = "456"; String iterator = "happyiterator"; String badSequence = "789"; Mockito.doReturn(iterator) .when(proxy) .getIterator(shardId, ShardIteratorType.AFTER_SEQUENCE_NUMBER.toString(), goodSequence); Mockito.doThrow(new InvalidArgumentException("")) .when(proxy) .getIterator(shardId, ShardIteratorType.AFTER_SEQUENCE_NUMBER.toString(), badSequence); validator.validateSequenceNumber(goodSequence); Mockito.verify(proxy, Mockito.times(1)) .getIterator(shardId, ShardIteratorType.AFTER_SEQUENCE_NUMBER.toString(), goodSequence); try { validator.validateSequenceNumber(badSequence); fail("Bad sequence number did not cause the validator to throw an exception"); } catch (IllegalArgumentException e) { Mockito.verify(proxy, Mockito.times(1)) .getIterator(shardId, ShardIteratorType.AFTER_SEQUENCE_NUMBER.toString(), badSequence); } nonNumericValueValidationTest(validator, proxy, validateWithGetIterator); }
@Test public void testGetBSSWebServiceUrl_SAML_SP() throws Exception { // given String baseUrl = "http://127.0.0.1:8080/test"; Mockito.doReturn(baseUrl) .when(configService) .getProxyConfigurationSetting(PlatformConfigurationKey.BSS_STS_WEBSERVICE_URL); Mockito.doReturn("SAML_SP") .when(configService) .getProxyConfigurationSetting(PlatformConfigurationKey.BSS_AUTH_MODE); // when String webServiceUrl = platformService.getBSSWebServiceUrl(); // then assertEquals(baseUrl, webServiceUrl); }
@Test(expected = AuthenticationException.class) public void testAuthenticateTMForInstance_NullOrganizationId() throws Throwable { createServiceInstance(ProvisioningStatus.COMPLETED, InstanceParameter.PUBLIC_IP); VOUserDetails userToGet = createVOUserDetails(1000, "user", null); Mockito.doReturn(new VOUserDetails()) .when(besDAO) .getUserDetails( Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString()); Mockito.doReturn(userToGet) .when(besDAO) .getUser(Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class)); authenticateTMForInstance(CTRL_ID, "appInstanceId", defaultAuth); }
@SuppressWarnings("unchecked") @Test public void testAuthenticateTMForController_noControllerSettings() throws Throwable { // given VOUserDetails manager = createVOUserDetails(10000, "user", "tp123"); Mockito.doThrow(new ConfigurationException("test")) .when(configService) .getAuthenticationForBESTechnologyManager( Matchers.anyString(), Matchers.any(ServiceInstance.class), Matchers.anyMap()); Mockito.doReturn(null) .when(authService) .getAuthenticatedTMForController( Matchers.anyString(), Matchers.any(PasswordAuthentication.class)); ArgumentCaptor<PasswordAuthentication> ac = ArgumentCaptor.forClass(PasswordAuthentication.class); // when authenticateTMForController(CTRL_ID, manager.getUserId(), "pass"); // then Mockito.verify(authService).getAuthenticatedTMForController(Matchers.anyString(), ac.capture()); assertEquals(manager.getUserId(), ac.getValue().getUserName()); assertEquals("pass", ac.getValue().getPassword()); }
@Override public View onCreateCandidatesView() { View spiedRootView = Mockito.spy(super.onCreateCandidatesView()); mMockCandidateView = Mockito.mock(CandidateView.class); Mockito.doReturn(mMockCandidateView).when(spiedRootView).findViewById(R.id.candidates); return spiedRootView; }
/** MkAnswerMatchers can match MkAnswer body bytes. */ @Test public void canMatchBodyBytes() { final byte[] body = {0x01, 0x45, 0x21}; final MkAnswer query = Mockito.mock(MkAnswer.class); Mockito.doReturn(body).when(query).bodyBytes(); MatcherAssert.assertThat(query, MkAnswerMatchers.hasBodyBytes(Matchers.is(body))); }
@Before public void setUp() throws Exception { bitcoinCryptoVault = new BitcoinCryptoVault(userPublicKey); bitcoinCryptoVault.setPluginFileSystem(pluginFileSystem); bitcoinCryptoVault.setPluginDatabaseSystem(pluginDatabaseSystem); bitcoinCryptoVault.setPluginFileSystem(pluginFileSystem); bitcoinCryptoVault.setUserPublicKey(userPublicKey); bitcoinCryptoVault.setDatabase(mockDatabase); bitcoinCryptoVault.setPluginId(pluginId); bitcoinCryptoVault.setLogManager(mockLogManager); when(pluginFileSystem.createTextFile( pluginId, userPublicKey, userPublicKey.toString() + ".vault", FilePrivacy.PRIVATE, FileLifeSpan.PERMANENT)) .thenReturn(mockPluginTextFile); bitcoinCryptoVault.loadOrCreateVault(); when(pluginDatabaseSystem.openDatabase(pluginId, userPublicKey)).thenReturn(mockDatabase); when(mockDatabase.getTable(anyString())).thenReturn(mockTable); when(mockDatabase.newTransaction()).thenReturn(mockDatabaseTransaction); when(mockTable.getRecords()).thenReturn(mockRecords); Mockito.doReturn(mockRecord).when(mockRecords).get(0); }
/** MkAnswerMatchers should be able to match MkAnswer body. */ @Test public void canMatchBody() { final String body = "Hello \u20ac!"; final MkAnswer query = Mockito.mock(MkAnswer.class); Mockito.doReturn(body).when(query).body(); MatcherAssert.assertThat(query, MkAnswerMatchers.hasBody(Matchers.is(body))); }
/** Test Request Scheduler Service */ @Test public void testRequestSchedulerService() throws Exception { HttpServiceSchedulerClient client = Mockito.spy(new HttpServiceSchedulerClient(config, runtime, SCHEDULER_HTTP_ENDPOINT)); // Failed to create new http connection Mockito.doReturn(null).when(client).createHttpConnection(Mockito.any(Command.class)); Assert.assertFalse( client.requestSchedulerService(Mockito.any(Command.class), Mockito.any(byte[].class))); HttpURLConnection connection = Mockito.mock(HttpURLConnection.class); Mockito.doReturn(connection).when(client).createHttpConnection(Mockito.any(Command.class)); // Failed to send http post request PowerMockito.spy(NetworkUtils.class); PowerMockito.doReturn(false) .when( NetworkUtils.class, "sendHttpPostRequest", Mockito.eq(connection), Mockito.any(byte[].class)); Assert.assertFalse( client.requestSchedulerService(Mockito.any(Command.class), Mockito.any(byte[].class))); Mockito.verify(connection).disconnect(); // Received non-ok response PowerMockito.doReturn(true) .when( NetworkUtils.class, "sendHttpPostRequest", Mockito.eq(connection), Mockito.any(byte[].class)); Scheduler.SchedulerResponse notOKResponse = SchedulerUtils.constructSchedulerResponse(false); PowerMockito.doReturn(notOKResponse.toByteArray()) .when(NetworkUtils.class, "readHttpResponse", Mockito.eq(connection)); Assert.assertFalse( client.requestSchedulerService(Mockito.any(Command.class), Mockito.any(byte[].class))); Mockito.verify(connection, Mockito.times(2)).disconnect(); // Received ok response -- success case Scheduler.SchedulerResponse oKResponse = SchedulerUtils.constructSchedulerResponse(true); PowerMockito.doReturn(oKResponse.toByteArray()) .when(NetworkUtils.class, "readHttpResponse", Mockito.eq(connection)); Assert.assertTrue( client.requestSchedulerService(Mockito.any(Command.class), Mockito.any(byte[].class))); Mockito.verify(connection, Mockito.times(3)).disconnect(); }
private void mockSession() { final EventLoop eventLoop = Mockito.mock(EventLoop.class); final Channel channel = Mockito.mock(Channel.class); final ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class); Mockito.doReturn(null) .when(eventLoop) .schedule(any(Runnable.class), any(long.class), any(TimeUnit.class)); Mockito.doReturn(eventLoop).when(channel).eventLoop(); Mockito.doReturn(Boolean.TRUE).when(channel).isWritable(); Mockito.doReturn(null).when(channel).close(); Mockito.doReturn(pipeline).when(channel).pipeline(); Mockito.doCallRealMethod().when(channel).toString(); Mockito.doReturn(pipeline).when(pipeline).addLast(Mockito.any(ChannelHandler.class)); Mockito.doReturn(new DefaultChannelPromise(channel)) .when(channel) .writeAndFlush(any(Notification.class)); Mockito.doReturn(new InetSocketAddress("localhost", 12345)).when(channel).remoteAddress(); Mockito.doReturn(new InetSocketAddress("localhost", 12345)).when(channel).localAddress(); final List<BgpParameters> params = Lists.newArrayList( new BgpParametersBuilder() .setOptionalCapabilities( Lists.newArrayList( new OptionalCapabilitiesBuilder() .setCParameters( new CParametersBuilder() .addAugmentation( CParameters1.class, new CParameters1Builder() .setMultiprotocolCapability( new MultiprotocolCapabilityBuilder() .setAfi(Ipv4AddressFamily.class) .setSafi(UnicastSubsequentAddressFamily.class) .build()) .build()) .build()) .build())) .build()); this.session = new BGPSessionImpl( this.classic, channel, new OpenBuilder() .setBgpIdentifier(new Ipv4Address("1.1.1.1")) .setHoldTimer(50) .setMyAsNumber(72) .setBgpParameters(params) .build(), 30, null); }
@Test public void testKillJob() throws Exception { List<String> expectedCommand = asList( "aurora job killall %s %s %s %d", JOB_SPEC, VERBOSE_CONFIG, BATCH_CONFIG, Integer.MAX_VALUE); // Failed Mockito.doReturn(false).when(controller).runProcess(Matchers.anyListOf(String.class)); Assert.assertFalse(controller.killJob()); Mockito.verify(controller).runProcess(Mockito.eq(expectedCommand)); // Happy path Mockito.doReturn(true).when(controller).runProcess(Matchers.anyListOf(String.class)); Assert.assertTrue(controller.killJob()); Mockito.verify(controller, Mockito.times(2)).runProcess(expectedCommand); }
/** * Region.Prefixed can add prefix to table names. * * @throws Exception If some problem inside */ @Test public void appendsPrefixesToTableNames() throws Exception { final Table table = Mockito.mock(Table.class); final Region region = Mockito.mock(Region.class); Mockito.doReturn(table).when(region).table(Mockito.anyString()); new Region.Prefixed(region, "foo-").table("test"); Mockito.verify(region).table("foo-test"); }
/** * Milestone.Smart can fetch state property from Milestone. * * @throws Exception If some problem inside */ @Test public final void fetchesState() throws Exception { final Milestone milestone = Mockito.mock(Milestone.class); Mockito.doReturn(Json.createObjectBuilder().add("state", "state of the milestone").build()) .when(milestone) .json(); MatcherAssert.assertThat(new Milestone.Smart(milestone).state(), Matchers.notNullValue()); }
/** * Milestone.Smart can fetch due_on property from Milestone. * * @throws Exception If some problem inside */ @Test public final void fetchesDueOn() throws Exception { final Milestone milestone = Mockito.mock(Milestone.class); Mockito.doReturn(Json.createObjectBuilder().add("due_on", "2011-04-10T20:09:31Z").build()) .when(milestone) .json(); MatcherAssert.assertThat(new Milestone.Smart(milestone).dueOn(), Matchers.notNullValue()); }
@BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); Mockito.doReturn(builder) .when(context) .buildConstraintViolationWithTemplate(Mockito.anyString()); validator = new CidrValidator(); }
@SuppressWarnings("unchecked") @Test(expected = AuthenticationException.class) public void testAuthenticateTMForInstance_noRoles() throws Throwable { // given createServiceInstance(ProvisioningStatus.COMPLETED, InstanceParameter.PUBLIC_IP); VOUserDetails user = createVOUserDetails(10000, "supplier", "tp123"); Mockito.doReturn(user) .when(besDAO) .getUserDetails( Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString()); Mockito.doReturn(new PasswordAuthentication("nobody", "")) .when(configService) .getWebServiceAuthentication(Matchers.any(ServiceInstance.class), Matchers.anyMap()); // when authenticateTMForInstance( CTRL_ID, "appInstanceId", new PasswordAuthentication("supplier", "secret")); }