@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()); }
@Test public void shouldGetCurrencyPairTradeHistory() throws IOException { // given final UserTrade[] expectedCpUserTrades = expectedCpUserTrades(); BitMarketHistoryTradesResponse historyTradesCPResponse = parse("trade/example-history-trades-cp-data", BitMarketHistoryTradesResponse.class); BitMarketHistoryOperationsResponse marketHistoryOperationsEurResponse = parse( "trade/example-history-operations-eur-data", BitMarketHistoryOperationsResponse.class); BitMarketHistoryOperationsResponse marketHistoryOperationsBtcResponse = parse( "trade/example-history-operations-btc-data", BitMarketHistoryOperationsResponse.class); BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class); PowerMockito.when( bitMarketAuthenticated.trades( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq("BTCEUR"), Mockito.eq(1000), Mockito.eq(0L))) .thenReturn(historyTradesCPResponse); PowerMockito.when( bitMarketAuthenticated.history( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.EUR.toString()), Mockito.anyInt(), Mockito.anyLong())) .thenReturn(marketHistoryOperationsEurResponse); PowerMockito.when( bitMarketAuthenticated.history( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.BTC.toString()), Mockito.anyInt(), Mockito.anyLong())) .thenReturn(marketHistoryOperationsBtcResponse); Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated); // when UserTrades tradesCP = tradeService.getTradeHistory( new DefaultTradeHistoryParamCurrencyPair(CurrencyPair.BTC_EUR)); List<UserTrade> userTrades = tradesCP.getUserTrades(); // then assertThat(userTrades).hasSize(2); for (int i = 0; i < userTrades.size(); i++) { BitMarketAssert.assertEquals(userTrades.get(i), expectedCpUserTrades[i]); } }
@Test public void scheduleRestartForVmsOnHost() { Mockito.when(hostVO.getType()).thenReturn(Host.Type.Routing); Mockito.when(hostVO.getHypervisorType()).thenReturn(HypervisorType.KVM); Mockito.when(_instanceDao.listByHostId(42l)) .thenReturn(Arrays.asList(Mockito.mock(VMInstanceVO.class))); Mockito.when(_podDao.findById(Mockito.anyLong())).thenReturn(Mockito.mock(HostPodVO.class)); Mockito.when(_dcDao.findById(Mockito.anyLong())).thenReturn(Mockito.mock(DataCenterVO.class)); highAvailabilityManager.scheduleRestartForVmsOnHost(hostVO, true); }
@Test public void shouldGetTradeHistory() throws IOException { // given BitMarketHistoryTradesResponse historyTradesBMResponse = parse("trade/example-history-trades-bm-data", BitMarketHistoryTradesResponse.class); BitMarketHistoryOperationsResponse marketHistoryOperationsEurResponse = parse( "trade/example-history-operations-eur-data", BitMarketHistoryOperationsResponse.class); BitMarketHistoryOperationsResponse marketHistoryOperationsBtcResponse = parse( "trade/example-history-operations-btc-data", BitMarketHistoryOperationsResponse.class); BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class); PowerMockito.when( bitMarketAuthenticated.trades( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq("BTCEUR"), Mockito.eq(3500), Mockito.eq(500L))) .thenReturn(historyTradesBMResponse); PowerMockito.when( bitMarketAuthenticated.history( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.EUR.toString()), Mockito.anyInt(), Mockito.anyLong())) .thenReturn(marketHistoryOperationsEurResponse); PowerMockito.when( bitMarketAuthenticated.history( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.BTC.toString()), Mockito.anyInt(), Mockito.anyLong())) .thenReturn(marketHistoryOperationsBtcResponse); Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated); // when UserTrades tradesBM = tradeService.getTradeHistory(new BitMarketHistoryParams(CurrencyPair.BTC_EUR, 500L, 3500)); List<UserTrade> userTrades = tradesBM.getUserTrades(); // then assertThat(userTrades).hasSize(1); BitMarketAssert.assertEquals(userTrades.get(0), EXPECTED_BM_USER_TRADES); }
@Test(expected = ExchangeException.class) public void shouldFailOnUnsuccessfulTradeHistory() throws IOException { // given BitMarketHistoryTradesResponse response = new BitMarketHistoryTradesResponse( false, null, new BitMarketAPILimit(3, 100, 12345000L), 502, "Invalid message hash"); BitMarketHistoryOperationsResponse marketHistoryOperationsPlnResponse = parse("trade/example-history-operations-data", BitMarketHistoryOperationsResponse.class); BitMarketHistoryOperationsResponse marketHistoryOperationsBtcResponse = parse( "trade/example-history-operations-btc-data", BitMarketHistoryOperationsResponse.class); BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class); PowerMockito.when( bitMarketAuthenticated.trades( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq("BTCPLN"), Mockito.eq(1000), Mockito.eq(0L))) .thenReturn(response); PowerMockito.when( bitMarketAuthenticated.history( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.PLN.toString()), Mockito.anyInt(), Mockito.anyLong())) .thenReturn(marketHistoryOperationsPlnResponse); PowerMockito.when( bitMarketAuthenticated.history( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.BTC.toString()), Mockito.anyInt(), Mockito.anyLong())) .thenReturn(marketHistoryOperationsBtcResponse); Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated); // when tradeService.getTradeHistory(new DefaultTradeHistoryParamPaging(150)); // then fail( "BitMarketTradeService should throw ExchangeException when open orders request was unsuccessful"); }
@Test public void accessBlockTest() throws Exception { Map<String, String> params = new HashMap<>(); params.put("blockId", "1"); TestCaseFactory.newWorkerTestCase( getEndpoint(BlockWorkerClientRestServiceHandler.ACCESS_BLOCK), params, "POST", null, mResource) .run(); Mockito.verify(mBlockWorker).accessBlock(Mockito.anyLong(), Mockito.anyLong()); }
@Test public void testWarnings() throws Exception { ConnectionImpl conn = Mockito.mock(ConnectionImpl.class); DQP dqp = Mockito.mock(DQP.class); ResultsFuture<ResultsMessage> results = new ResultsFuture<ResultsMessage>(); Mockito.stub(dqp.executeRequest(Mockito.anyLong(), (RequestMessage) Mockito.anyObject())) .toReturn(results); ResultsMessage rm = new ResultsMessage(); rm.setResults(new List<?>[] {Arrays.asList(1)}); rm.setWarnings(Arrays.asList(new Throwable())); rm.setColumnNames(new String[] {"expr1"}); rm.setDataTypes(new String[] {"string"}); results.getResultsReceiver().receiveResults(rm); Mockito.stub(conn.getDQP()).toReturn(dqp); StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY) { @Override protected java.util.TimeZone getServerTimeZone() throws java.sql.SQLException { return null; } }; statement.execute("select 'a'"); assertNotNull(statement.getResultSet()); SQLWarning warning = statement.getWarnings(); assertNotNull(warning); assertNull(warning.getNextWarning()); }
@Before public final void init() { workPlanService = new WorkPlansServiceImpl(); dataDefinitionService = mock(DataDefinitionService.class); TranslationService translationService = mock(TranslationService.class); workPlan = mock(Entity.class); workPlanDD = mock(DataDefinition.class); when(dataDefinitionService.get( WorkPlansConstants.PLUGIN_IDENTIFIER, WorkPlansConstants.MODEL_WORK_PLAN)) .thenReturn(workPlanDD); when(translationService.translate( Mockito.anyString(), Mockito.any(Locale.class), Mockito.anyString())) .thenReturn(TRANSLATED_STRING); when(workPlanDD.getName()).thenReturn(WorkPlansConstants.MODEL_WORK_PLAN); when(workPlanDD.getPluginIdentifier()).thenReturn(WorkPlansConstants.PLUGIN_IDENTIFIER); when(workPlanDD.get(Mockito.anyLong())).thenReturn(workPlan); when(workPlan.getDataDefinition()).thenReturn(workPlanDD); when(workPlan.getId()).thenReturn(1L); ReflectionTestUtils.setField(workPlanService, "dataDefinitionService", dataDefinitionService); ReflectionTestUtils.setField(workPlanService, "translationService", translationService); }
@Test public void requestSpaceTest() throws Exception { Map<String, String> params = new HashMap<>(); params.put("blockId", "1"); params.put("sessionId", "1"); params.put("requestBytes", "1"); TestCaseFactory.newWorkerTestCase( getEndpoint(BlockWorkerClientRestServiceHandler.REQUEST_SPACE), params, "POST", null, mResource) .run(); Mockito.verify(mBlockWorker) .requestSpace(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); }
@Test public void canDecreaseValue() { when(originalRepository.read(key)).thenReturn(integerItem); sut = new CoRepositoryClient(coRepository, originalRepository, keyUpdateTime, 1); sut.decrease(key); verify(coRepository).decrease(key); verify(keyUpdateTime, times(2)).notifyUpdated(Mockito.eq(key), Mockito.anyLong()); }
@Before public void setup() throws Exception { MockitoAnnotations.initMocks(this); mainClientExec = new MainClientExec( requestExecutor, connManager, reuseStrategy, keepAliveStrategy, proxyHttpProcessor, targetAuthStrategy, proxyAuthStrategy, userTokenHandler); target = new HttpHost("foo", 80); proxy = new HttpHost("bar", 8888); Mockito.when(connManager.requestConnection(Mockito.<HttpRoute>any(), Mockito.any())) .thenReturn(connRequest); Mockito.when(connRequest.get(Mockito.anyLong(), Mockito.<TimeUnit>any())) .thenReturn(managedConn); final Map<String, Header> challenges = new HashMap<String, Header>(); challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=test")); final AuthOption authOption = new AuthOption(new BasicScheme(), new UsernamePasswordCredentials("user:pass")); Mockito.when( targetAuthStrategy.getChallenges( Mockito.eq(target), Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any())) .thenReturn(challenges); Mockito.when( targetAuthStrategy.getChallenges( Mockito.eq(target), Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any())) .thenReturn(challenges); Mockito.when( targetAuthStrategy.select( Mockito.same(challenges), Mockito.eq(target), Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any())) .thenReturn(new LinkedList<AuthOption>(Arrays.asList(authOption))); Mockito.when( proxyAuthStrategy.getChallenges( Mockito.eq(proxy), Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any())) .thenReturn(challenges); Mockito.when( proxyAuthStrategy.getChallenges( Mockito.eq(proxy), Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any())) .thenReturn(challenges); Mockito.when( proxyAuthStrategy.select( Mockito.same(challenges), Mockito.eq(proxy), Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any())) .thenReturn(new LinkedList<AuthOption>(Arrays.asList(authOption))); }
@Override protected void setup(TestContainer container) { container.enableInterfaceMocking(true); dsMock = mock(DataService.class); when(dsMock.getCurrentUser()).thenReturn(givenUser()); localizerMock = mock(LocalizerServiceLocal.class); when(localizerMock.getLocalizedTextFromDatabase( Mockito.anyString(), Mockito.anyLong(), Mockito.any(LocalizedObjectTypes.class))) .thenReturn(LOCALIZED_RESOURCE); logCollector.localizer = localizerMock; }
@Test public void investigateHostStatusFailure() { Mockito.when(_hostDao.findById(Mockito.anyLong())).thenReturn(hostVO); // Set the list of investigators, CheckOnAgentInvestigator suffices for now // Also no need to mock isAgentAlive() as actual implementation returns null Investigator investigator = Mockito.mock(CheckOnAgentInvestigator.class); List<Investigator> investigators = new ArrayList<Investigator>(); investigators.add(investigator); highAvailabilityManager.setInvestigators(investigators); assertNull(highAvailabilityManager.investigate(1l)); }
@Test public void investigateHostStatusSuccess() { Mockito.when(_hostDao.findById(Mockito.anyLong())).thenReturn(hostVO); // Set the list of investigators, CheckOnAgentInvestigator suffices for now Investigator investigator = Mockito.mock(CheckOnAgentInvestigator.class); List<Investigator> investigators = new ArrayList<Investigator>(); investigators.add(investigator); highAvailabilityManager.setInvestigators(investigators); // Mock isAgentAlive to return host status as Down Mockito.when(investigator.isAgentAlive(hostVO)).thenReturn(Status.Down); assertTrue(highAvailabilityManager.investigate(1l) == Status.Down); }
@BeforeClass(groups = "fast") public void beforeMethod() throws Exception { super.beforeClass(); account = Mockito.mock(Account.class); Mockito.when( accountInternalApi.getAccountByRecordId( Mockito.anyLong(), Mockito.<InternalTenantContext>any())) .thenReturn(account); dateHelper = new EntitlementDateHelper(accountInternalApi, clock); clock.resetDeltaFromReality(); ; }
@Test public void writeBlockTest() throws Exception { Map<String, String> params = new HashMap<>(); params.put("blockId", "1"); params.put("sessionId", "1"); params.put("offset", "0"); params.put("length", "-1"); Random random = new Random(); byte[] bytes = CommonUtils.randomBytes(random.nextInt(64)); BlockWriter blockWriter = PowerMockito.mock(BlockWriter.class); Mockito.doReturn(blockWriter) .when(mBlockWorker) .getTempBlockWriterRemote(Mockito.anyLong(), Mockito.anyLong()); TestCase testCase = TestCaseFactory.newWorkerTestCase( getEndpoint(BlockWorkerClientRestServiceHandler.WRITE_BLOCK), params, "POST", null, mResource); HttpURLConnection connection = (HttpURLConnection) testCase.createURL().openConnection(); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestMethod(testCase.getMethod()); connection.setDoOutput(true); connection.connect(); connection.getOutputStream().write(bytes); Assert.assertEquals( testCase.getEndpoint(), Response.Status.OK.getStatusCode(), connection.getResponseCode()); Assert.assertEquals("", testCase.getResponse(connection)); Mockito.verify(mBlockWorker).getTempBlockWriterRemote(Mockito.anyLong(), Mockito.anyLong()); Mockito.verify(blockWriter).append(ByteBuffer.wrap(bytes)); }
@Test public void testGetDog() { Dog dog = new Dog( "Martin", "doga", new LocalDate(1998, 05, 22), new Customer("Martin", "Sakac", "Purkynova 4", "111")); dog.setId(1L); Mockito.stub(dogDaoImplMock.getDog(Mockito.anyLong())).toReturn(dog); DogDto dogActual = dogService.getDogById(1L); Mockito.verify(dogDaoImplMock).getDog(1L); assertDog(dog, dogActual); }
@Test public void testBatchExecution() throws Exception { ConnectionImpl conn = Mockito.mock(ConnectionImpl.class); DQP dqp = Mockito.mock(DQP.class); ResultsFuture<ResultsMessage> results = new ResultsFuture<ResultsMessage>(); Mockito.stub(dqp.executeRequest(Mockito.anyLong(), (RequestMessage) Mockito.anyObject())) .toReturn(results); ResultsMessage rm = new ResultsMessage(); rm.setResults(new List<?>[] {Arrays.asList(1), Arrays.asList(2)}); rm.setUpdateResult(true); results.getResultsReceiver().receiveResults(rm); Mockito.stub(conn.getDQP()).toReturn(dqp); StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); statement.clearBatch(); // previously caused npe statement.addBatch("delete from table"); // $NON-NLS-1$ statement.addBatch("delete from table1"); // $NON-NLS-1$ assertTrue(Arrays.equals(new int[] {1, 2}, statement.executeBatch())); }
@Test public void readBlockTest() throws Exception { Map<String, String> params = new HashMap<>(); params.put("blockId", "1"); params.put("sessionId", "1"); params.put("lockId", "1"); params.put("offset", "0"); params.put("length", "-1"); Random random = new Random(); byte[] bytes = CommonUtils.randomBytes(random.nextInt(64)); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); BlockReader blockReader = PowerMockito.mock(BlockReader.class); Mockito.doReturn(byteBuffer).when(blockReader).read(Mockito.anyLong(), Mockito.anyLong()); Mockito.doReturn((long) bytes.length).when(blockReader).getLength(); Mockito.doReturn(blockReader) .when(mBlockWorker) .readBlockRemote(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); TestCase testCase = TestCaseFactory.newWorkerTestCase( getEndpoint(BlockWorkerClientRestServiceHandler.READ_BLOCK), params, "GET", byteBuffer, mResource); HttpURLConnection connection = (HttpURLConnection) testCase.createURL().openConnection(); connection.setRequestMethod(testCase.getMethod()); connection.connect(); Assert.assertEquals( testCase.getEndpoint(), connection.getResponseCode(), Response.Status.OK.getStatusCode()); Assert.assertEquals(new String(byteBuffer.array()), testCase.getResponse(connection)); Mockito.verify(mBlockWorker) .readBlockRemote(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); }
@Test public void testUpdateRestaurantFail() { Restaurant restaurant = createExoticRestaurant(); when(restaurantRepository.exists(Mockito.anyLong())).thenReturn(false); try { MvcResult updateRestaurantResponse = mockMvc .perform( post("/restaurant/delete") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(restaurant))) .andExpect(status().isOk()) .andReturn(); String responseContent = updateRestaurantResponse.getResponse().getContentAsString(); assertTrue(responseContent.contains(Status.FAILED.getStatusValue())); } catch (Exception e) { fail(); } }
@Test public void testDeleteRestaurantFail() { when(restaurantRepository.exists(Mockito.anyLong())).thenReturn(false); Vote vote = new Vote(); vote.setRestaurantId(Long.MAX_VALUE); try { MvcResult deleteRestaurantResponse = mockMvc .perform( post("/restaurant/delete") .contentType(MediaType.APPLICATION_JSON) .content(mapper.writeValueAsString(vote))) .andExpect(status().isOk()) .andReturn(); String responseContent = deleteRestaurantResponse.getResponse().getContentAsString(); assertTrue(responseContent.contains(Status.FAILED.getStatusValue())); } catch (Exception e) { fail(); } }
@Test public void testAsynchTimeout() throws Exception { ConnectionImpl conn = Mockito.mock(ConnectionImpl.class); final StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); statement.setQueryTimeoutMS(1); DQP dqp = Mockito.mock(DQP.class); Mockito.stub(statement.getDQP()).toReturn(dqp); final AtomicInteger counter = new AtomicInteger(); Mockito.stub(dqp.cancelRequest(0)) .toAnswer( new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { synchronized (statement) { counter.incrementAndGet(); statement.notifyAll(); } return true; } }); ResultsFuture<ResultsMessage> future = new ResultsFuture<ResultsMessage>(); Mockito.stub(dqp.executeRequest(Mockito.anyLong(), (RequestMessage) Mockito.anyObject())) .toReturn(future); statement.submitExecute("select 'hello world'", null); synchronized (statement) { while (counter.get() != 1) { statement.wait(); } } statement.setQueryTimeoutMS(1); statement.submitExecute("select 'hello world'", null); synchronized (statement) { while (counter.get() != 2) { statement.wait(); } } }
@Before public void init() throws Exception { mutableReview = mock(MutableReview.class); comment = mock(Comment.class); when(mutableReview.createComment()).thenReturn(comment); review = mock(Review.class); workflowContext = mock(WorkflowContext.class); settings = new Settings(); when(workflowContext.getProjectSettings()).thenReturn(settings); assigneeLogin = "******"; jiraIssueCreator = mock(JiraIssueCreator.class); reviewDao = mock(ReviewDao.class); userFinder = mock(UserFinder.class); remoteIssue = new Issue( null, null, "FOO-15", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); parameters = new HashMap<String, String>(); parameters.put(JiraConstants.JIRA_ISSUE_REPORTER_PROPERTY, workflowContext.getUserLogin()); parameters.put(JiraConstants.JIRA_ISSUE_ASSIGNEE_PROPERTY, assigneeLogin); ReviewDto reviewDto = new ReviewDto(); reviewDto.setAssigneeId(40L); when(reviewDao.findById(Mockito.anyLong())).thenReturn(reviewDto); User assignee = new User(); assignee.setLogin(assigneeLogin); when(userFinder.findById(Mockito.anyInt())).thenReturn(assignee); when(jiraIssueCreator.createIssue(review, settings, parameters)).thenReturn(remoteIssue); action = new LinkFunction(jiraIssueCreator, reviewDao, userFinder); }
@Test public void requestBlockLocationTest() throws Exception { Map<String, String> params = new HashMap<>(); params.put("blockId", "1"); params.put("sessionId", "1"); params.put("initialBytes", "1"); String blockLocation = CommonUtils.randomString(10); Mockito.doReturn(blockLocation) .when(mBlockWorker) .createBlock(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyString(), Mockito.anyLong()); TestCaseFactory.newWorkerTestCase( getEndpoint(BlockWorkerClientRestServiceHandler.REQUEST_BLOCK_LOCATION), params, "POST", blockLocation, mResource) .run(); Mockito.verify(mBlockWorker) .createBlock(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyString(), Mockito.anyLong()); }
/** * Test that MetaReader will ride over server throwing "Server not running" IOEs. * * @see https://issues.apache.org/jira/browse/HBASE-3446 * @throws IOException * @throws InterruptedException */ @Test public void testRideOverServerNotRunning() throws IOException, InterruptedException { // Need a zk watcher. ZooKeeperWatcher zkw = new ZooKeeperWatcher( UTIL.getConfiguration(), this.getClass().getSimpleName(), ABORTABLE, true); // This is a servername we use in a few places below. ServerName sn = new ServerName("example.com", 1234, System.currentTimeMillis()); HConnection connection = null; CatalogTracker ct = null; try { // Mock an HRegionInterface. Our mock implementation will fail a few // times when we go to open a scanner. final HRegionInterface implementation = Mockito.mock(HRegionInterface.class); // When openScanner called throw IOE 'Server not running' a few times // before we return a scanner id. Whats WEIRD is that these // exceptions do not show in the log because they are caught and only // printed if we FAIL. We eventually succeed after retry so these don't // show. We will know if they happened or not because we will ask // mockito at the end of this test to verify that openscanner was indeed // called the wanted number of times. final long scannerid = 123L; Mockito.when(implementation.openScanner((byte[]) Mockito.any(), (Scan) Mockito.any())) .thenThrow(new IOException("Server not running (1 of 3)")) .thenThrow(new IOException("Server not running (2 of 3)")) .thenThrow(new IOException("Server not running (3 of 3)")) .thenReturn(scannerid); // Make it so a verifiable answer comes back when next is called. Return // the verifiable answer and then a null so we stop scanning. Our // verifiable answer is something that looks like a row in META with // a server and startcode that is that of the above defined servername. List<KeyValue> kvs = new ArrayList<KeyValue>(); final byte[] rowToVerify = Bytes.toBytes("rowToVerify"); kvs.add( new KeyValue( rowToVerify, HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER, Writables.getBytes(HRegionInfo.FIRST_META_REGIONINFO))); kvs.add( new KeyValue( rowToVerify, HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER, Bytes.toBytes(sn.getHostAndPort()))); kvs.add( new KeyValue( rowToVerify, HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER, Bytes.toBytes(sn.getStartcode()))); final Result[] result = new Result[] {new Result(kvs)}; Mockito.when(implementation.next(Mockito.anyLong(), Mockito.anyInt())) .thenReturn(result) .thenReturn(null); // Associate a spied-upon HConnection with UTIL.getConfiguration. Need // to shove this in here first so it gets picked up all over; e.g. by // HTable. connection = HConnectionTestingUtility.getSpiedConnection(UTIL.getConfiguration()); // Fix the location lookup so it 'works' though no network. First // make an 'any location' object. final HRegionLocation anyLocation = new HRegionLocation(HRegionInfo.FIRST_META_REGIONINFO, sn.getHostname(), sn.getPort()); // Return the any location object when locateRegion is called in HTable // constructor and when its called by ServerCallable (it uses getRegionLocation). // The ugly format below comes of 'Important gotcha on spying real objects!' from // http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html Mockito.doReturn(anyLocation) .when(connection) .locateRegion((byte[]) Mockito.any(), (byte[]) Mockito.any()); Mockito.doReturn(anyLocation) .when(connection) .getRegionLocation((byte[]) Mockito.any(), (byte[]) Mockito.any(), Mockito.anyBoolean()); // Now shove our HRI implementation into the spied-upon connection. Mockito.doReturn(implementation) .when(connection) .getHRegionConnection(Mockito.anyString(), Mockito.anyInt()); // Now start up the catalogtracker with our doctored Connection. ct = new CatalogTracker(zkw, null, connection, ABORTABLE, 0); ct.start(); // Scan meta for user tables and verify we got back expected answer. NavigableMap<HRegionInfo, Result> hris = MetaReader.getServerUserRegions(ct, sn); assertTrue(hris.size() == 1); assertTrue(hris.firstEntry().getKey().equals(HRegionInfo.FIRST_META_REGIONINFO)); assertTrue(Bytes.equals(rowToVerify, hris.firstEntry().getValue().getRow())); // Finally verify that openscanner was called four times -- three times // with exception and then on 4th attempt we succeed. Mockito.verify(implementation, Mockito.times(4)) .openScanner((byte[]) Mockito.any(), (Scan) Mockito.any()); } finally { if (ct != null) ct.stop(); HConnectionManager.deleteConnection(UTIL.getConfiguration(), true); zkw.close(); } }
/** * Make sure the system will re-attach to running jobs. * * @throws GenieException on issue */ @Test @SuppressWarnings("unchecked") public void canAttachToRunningJobs() throws GenieException { final ContextRefreshedEvent event = Mockito.mock(ContextRefreshedEvent.class); Mockito.when(this.jobSearchService.getAllActiveJobsOnHost(HOSTNAME)) .thenReturn(Sets.newHashSet()); this.coordinator.onStartup(event); Mockito.verify(this.scheduler, Mockito.never()) .scheduleWithFixedDelay(Mockito.any(JobMonitor.class), Mockito.anyLong()); // Simulate a job being started final String job1Id = UUID.randomUUID().toString(); final String job2Id = UUID.randomUUID().toString(); final String job3Id = UUID.randomUUID().toString(); final String job4Id = UUID.randomUUID().toString(); final String job5Id = UUID.randomUUID().toString(); final JobExecution.Builder builder = new JobExecution.Builder(UUID.randomUUID().toString()) .withProcessId(2818) .withCheckDelay(DELAY) .withMemory(1024) .withTimeout(this.tomorrow); builder.withId(job1Id); final JobExecution job1 = builder.build(); builder.withId(job2Id); final JobExecution job2 = builder.build(); builder.withId(job3Id); final JobExecution job3 = builder.build(); final JobStartedEvent event1 = new JobStartedEvent(job1, this); final ScheduledFuture future = Mockito.mock(ScheduledFuture.class); Mockito.when( this.scheduler.scheduleWithFixedDelay(Mockito.any(JobMonitor.class), Mockito.eq(DELAY))) .thenReturn(future); coordinator.init(job1Id); coordinator.schedule(job1Id, null, null, null, null, 1024); this.coordinator.onJobStarted(event1); Mockito.verify(this.scheduler, Mockito.times(1)) .scheduleWithFixedDelay(Mockito.any(JobMonitor.class), Mockito.eq(DELAY)); final Job j1 = Mockito.mock(Job.class); Mockito.when(j1.getId()).thenReturn(Optional.of(job1Id)); Mockito.when(j1.getStatus()).thenReturn(JobStatus.RUNNING); final Job j2 = Mockito.mock(Job.class); Mockito.when(j2.getId()).thenReturn(Optional.of(job2Id)); Mockito.when(j2.getStatus()).thenReturn(JobStatus.RUNNING); final Job j3 = Mockito.mock(Job.class); Mockito.when(j3.getId()).thenReturn(Optional.of(job3Id)); Mockito.when(j3.getStatus()).thenReturn(JobStatus.RUNNING); final Job j4 = Mockito.mock(Job.class); Mockito.when(j4.getId()).thenReturn(Optional.of(job4Id)); Mockito.when(j4.getStatus()).thenReturn(JobStatus.RUNNING); final Job j5 = Mockito.mock(Job.class); Mockito.when(j5.getId()).thenReturn(Optional.of(job5Id)); Mockito.when(j5.getStatus()).thenReturn(JobStatus.INIT); final Set<Job> jobs = Sets.newHashSet(j1, j2, j3, j4, j5); Mockito.when(this.jobSearchService.getAllActiveJobsOnHost(HOSTNAME)).thenReturn(jobs); Mockito.when(this.jobSearchService.getJobExecution(job1Id)).thenReturn(job1); Mockito.when(this.jobSearchService.getJobExecution(job2Id)).thenReturn(job2); Mockito.when(this.jobSearchService.getJobExecution(job3Id)).thenReturn(job3); Mockito.when(this.jobSearchService.getJobExecution(job4Id)) .thenThrow(new GenieNotFoundException("blah")); this.coordinator.onStartup(event); Mockito.verify(this.eventMulticaster, Mockito.times(2)) .multicastEvent(Mockito.any(JobFinishedEvent.class)); Mockito.verify(this.scheduler, Mockito.times(3)) .scheduleWithFixedDelay(Mockito.any(JobMonitor.class), Mockito.eq(DELAY)); Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(3)); Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(3 * 1024)); }
@Test public void testAuthenticate() throws Exception { SAML2LoginAPIAuthenticatorCmd cmd = Mockito.spy(new SAML2LoginAPIAuthenticatorCmd()); Field apiServerField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("_apiServer"); apiServerField.setAccessible(true); apiServerField.set(cmd, apiServer); Field managerField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("_samlAuthManager"); managerField.setAccessible(true); managerField.set(cmd, samlAuthManager); Field accountServiceField = BaseCmd.class.getDeclaredField("_accountService"); accountServiceField.setAccessible(true); accountServiceField.set(cmd, accountService); Field domainMgrField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("_domainMgr"); domainMgrField.setAccessible(true); domainMgrField.set(cmd, domainMgr); Field userAccountDaoField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("_userAccountDao"); userAccountDaoField.setAccessible(true); userAccountDaoField.set(cmd, userAccountDao); String spId = "someSPID"; String url = "someUrl"; KeyPair kp = SAMLUtils.generateRandomKeyPair(); X509Certificate cert = SAMLUtils.generateRandomX509Certificate(kp); SAMLProviderMetadata providerMetadata = new SAMLProviderMetadata(); providerMetadata.setEntityId("random"); providerMetadata.setSigningCertificate(cert); providerMetadata.setEncryptionCertificate(cert); providerMetadata.setKeyPair(kp); providerMetadata.setSsoUrl("http://test.local"); providerMetadata.setSloUrl("http://test.local"); Mockito.when(session.getAttribute(Mockito.anyString())).thenReturn(null); Mockito.when(domain.getId()).thenReturn(1L); Mockito.when(domainMgr.getDomain(Mockito.anyString())).thenReturn(domain); UserAccountVO user = new UserAccountVO(); user.setId(1000L); Mockito.when(userAccountDao.getUserAccount(Mockito.anyString(), Mockito.anyLong())) .thenReturn(user); Mockito.when(apiServer.verifyUser(Mockito.anyLong())).thenReturn(false); Mockito.when(samlAuthManager.getSPMetadata()).thenReturn(providerMetadata); Mockito.when(samlAuthManager.getIdPMetadata(Mockito.anyString())).thenReturn(providerMetadata); Map<String, Object[]> params = new HashMap<String, Object[]>(); // SSO redirection test cmd.authenticate( "command", params, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp); Mockito.verify(resp, Mockito.times(1)).sendRedirect(Mockito.anyString()); // SSO SAMLResponse verification test, this should throw ServerApiException for auth failure params.put(SAMLPluginConstants.SAML_RESPONSE, new String[] {"Some String"}); Mockito.stub(cmd.processSAMLResponse(Mockito.anyString())).toReturn(buildMockResponse()); try { cmd.authenticate( "command", params, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp); } catch (ServerApiException ignored) { } Mockito.verify(userAccountDao, Mockito.times(0)) .getUserAccount(Mockito.anyString(), Mockito.anyLong()); Mockito.verify(apiServer, Mockito.times(0)).verifyUser(Mockito.anyLong()); }
/** Retry addBlock() while another thread is in chooseTarget(). See HDFS-4452. */ @Test public void testRetryAddBlockWhileInChooseTarget() throws Exception { final String src = "/testRetryAddBlockWhileInChooseTarget"; FSNamesystem ns = cluster.getNamesystem(); BlockManager spyBM = spy(ns.getBlockManager()); final NamenodeProtocols nn = cluster.getNameNodeRpc(); // substitute mocked BlockManager into FSNamesystem Class<? extends FSNamesystem> nsClass = ns.getClass(); Field bmField = nsClass.getDeclaredField("blockManager"); bmField.setAccessible(true); bmField.set(ns, spyBM); doAnswer( new Answer<DatanodeStorageInfo[]>() { @Override public DatanodeStorageInfo[] answer(InvocationOnMock invocation) throws Throwable { LOG.info("chooseTarget for " + src); DatanodeStorageInfo[] ret = (DatanodeStorageInfo[]) invocation.callRealMethod(); count++; if (count == 1) { // run second addBlock() LOG.info("Starting second addBlock for " + src); nn.addBlock(src, "clientName", null, null, INodeId.GRANDFATHER_INODE_ID, null); LocatedBlocks lbs = nn.getBlockLocations(src, 0, Long.MAX_VALUE); assertEquals("Must be one block", 1, lbs.getLocatedBlocks().size()); lb2 = lbs.get(0); assertEquals("Wrong replication", REPLICATION, lb2.getLocations().length); } return ret; } }) .when(spyBM) .chooseTarget4NewBlock( Mockito.anyString(), Mockito.anyInt(), Mockito.<DatanodeDescriptor>any(), Mockito.<HashSet<Node>>any(), Mockito.anyLong(), Mockito.<List<String>>any(), Mockito.anyByte()); // create file nn.create( src, FsPermission.getFileDefault(), "clientName", new EnumSetWritable<CreateFlag>(EnumSet.of(CreateFlag.CREATE)), true, (short) 3, 1024, null); // start first addBlock() LOG.info("Starting first addBlock for " + src); nn.addBlock(src, "clientName", null, null, INodeId.GRANDFATHER_INODE_ID, null); // check locations LocatedBlocks lbs = nn.getBlockLocations(src, 0, Long.MAX_VALUE); assertEquals("Must be one block", 1, lbs.getLocatedBlocks().size()); lb1 = lbs.get(0); assertEquals("Wrong replication", REPLICATION, lb1.getLocations().length); assertEquals("Blocks are not equal", lb1.getBlock(), lb2.getBlock()); }