org.mockito.internal.util.reflection.Whitebox Java Examples
The following examples show how to use
org.mockito.internal.util.reflection.Whitebox.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractBluetoothObjectGovernorTest.java From bluetooth-manager with Apache License 2.0 | 6 votes |
@Test public void testUpdateNotReadyToReady() throws Exception { // conditions Whitebox.setInternalState(governor, "bluetoothObject", null); governor.addGovernorListener(governorListener); governor.update(); InOrder inOrder = inOrder(governor, governorListener, bluetoothManager); inOrder.verify(bluetoothManager).getBluetoothObject(URL); inOrder.verify(governor).init(bluetoothObject); inOrder.verify(governorListener).ready(true); inOrder.verify(governorListener, never()).lastUpdatedChanged(any()); governor.updateLastInteracted(); governor.update(); inOrder.verify(governorListener).lastUpdatedChanged(any()); inOrder.verifyNoMoreInteractions(); }
Example #2
Source File: GraphQLCategoryProviderTest.java From aem-core-cif-components with Apache License 2.0 | 6 votes |
@Test public void testCategoryNotOrNoChildren() throws IOException { Page page = mock(Page.class); Resource pageContent = mock(Resource.class); when(page.getContentResource()).thenReturn(pageContent); GraphQLCategoryProvider categoryProvider = new GraphQLCategoryProvider(page .getContentResource(), null); MagentoGraphqlClient graphqlClient = mock(MagentoGraphqlClient.class); Whitebox.setInternalState(categoryProvider, "magentoGraphqlClient", graphqlClient); // test category not found GraphqlResponse<Query, Error> response = mock(GraphqlResponse.class); when(graphqlClient.execute(anyString())).thenReturn(response); Query rootQuery = mock(Query.class); when(response.getData()).thenReturn(rootQuery); Assert.assertNull(rootQuery.getCategory()); Assert.assertTrue(categoryProvider.getChildCategories(-10, 10).isEmpty()); // test category children not found CategoryTree category = mock(CategoryTree.class); when(rootQuery.getCategory()).thenReturn(category); when(category.getChildren()).thenReturn(null); Assert.assertNull(category.getChildren()); Assert.assertTrue(categoryProvider.getChildCategories(13, 10).isEmpty()); }
Example #3
Source File: SpanTest.java From wingtips with Apache License 2.0 | 6 votes |
@Test public void builder_withTags_does_nothing_if_passed_null() { // given Span.Builder builder = Span.newBuilder("foo", SpanPurpose.UNKNOWN); Map<String, String> tagsMapSpy = spy(new LinkedHashMap<>()); Whitebox.setInternalState(builder, "tags", tagsMapSpy); // when Span.Builder resultingBuilder = builder.withTags(null); // then assertThat(resultingBuilder).isSameAs(builder); verifyZeroInteractions(tagsMapSpy); // and when Span resultingSpan = resultingBuilder.build(); // then assertThat(resultingSpan.getTags()).isEmpty(); }
Example #4
Source File: RelatedProductsImplTest.java From aem-core-cif-components with Apache License 2.0 | 6 votes |
@Test public void testQueryExtensions() throws Exception { setUp(RelationType.RELATED_PRODUCTS, "graphql/magento-graphql-relatedproducts-result.json", false); AbstractProductsRetriever retriever = relatedProducts.getProductsRetriever(); retriever.extendProductQueryWith(p -> p.description(d -> d.html())); retriever.extendVariantQueryWith(v -> v.sku()); MagentoGraphqlClient client = (MagentoGraphqlClient) Whitebox.getInternalState(retriever, "client"); MagentoGraphqlClient clientSpy = Mockito.spy(client); Whitebox.setInternalState(retriever, "client", clientSpy); assertProducts(); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(clientSpy, times(1)).execute(captor.capture()); String expectedQuery = "{products(filter:{sku:{eq:\"24-MG01\"}}){items{__typename,related_products{__typename,sku,name,thumbnail{label,url},url_key,price_range{minimum_price{regular_price{value,currency},final_price{value,currency},discount{amount_off,percent_off}}},... on ConfigurableProduct{price_range{maximum_price{regular_price{value,currency},final_price{value,currency},discount{amount_off,percent_off}}}},... on ConfigurableProduct{variants{product{sku}}},description{html}}}}}"; Assert.assertEquals(expectedQuery, captor.getValue()); }
Example #5
Source File: DcosAuthImplTest.java From marathon-plugin with Apache License 2.0 | 6 votes |
/** * Test that all other algorithms besides RS256 are rejected. * * @throws Exception */ @Test public void testHSSecretKey() throws Exception { final Secret secret = PowerMockito.mock(Secret.class); final String[] algs = new String[]{"HS512", "HS256", "RS512"}; for (final String alg : algs) { final String secretText = String.format(DCOS_AUTH_JSON, testUser, "a secret key", alg); Whitebox.setInternalState(secret, "value", secretText); when(credentials.getSecret()).thenReturn(secret); when(secret.getPlainText()).thenReturn(secretText); final DcosAuthImpl dcosAuth = new DcosAuthImpl(credentials, options, ContentType.APPLICATION_JSON, builder, context); try { dcosAuth.createDcosLoginPayload(); assertFalse("Invalid algorithm was accepted", true); } catch (AuthenticationException e) { assertTrue("Does not list valid algorithm in message", e.getMessage().contains("RS256")); } } }
Example #6
Source File: TestRaftStorage.java From incubator-ratis with Apache License 2.0 | 6 votes |
@Test public void testMetaFile() throws Exception { RaftStorage storage = new RaftStorage(storageDir, StartupOption.FORMAT); File m = storage.getStorageDir().getMetaFile(); Assert.assertTrue(m.exists()); MetaFile metaFile = new MetaFile(m); Assert.assertEquals(MetaFile.DEFAULT_TERM, metaFile.getTerm()); Assert.assertEquals(MetaFile.EMPTY_VOTEFOR, metaFile.getVotedFor()); metaFile.set(123, "peer1"); metaFile.readFile(); Assert.assertEquals(123, metaFile.getTerm()); Assert.assertEquals("peer1", metaFile.getVotedFor()); MetaFile metaFile2 = new MetaFile(m); Assert.assertFalse((Boolean) Whitebox.getInternalState(metaFile2, "loaded")); Assert.assertEquals(123, metaFile.getTerm()); Assert.assertEquals("peer1", metaFile.getVotedFor()); storage.close(); }
Example #7
Source File: SpanTest.java From wingtips with Apache License 2.0 | 6 votes |
@Test public void builder_withTimestampedAnnotations_does_nothing_if_passed_null() { // given Span.Builder builder = Span.newBuilder("foo", SpanPurpose.UNKNOWN); List<TimestampedAnnotation> annotationsListSpy = spy(new ArrayList<>()); Whitebox.setInternalState(builder, "annotations", annotationsListSpy); // when Span.Builder resultingBuilder = builder.withTimestampedAnnotations(null); // then assertThat(resultingBuilder).isSameAs(builder); verifyZeroInteractions(annotationsListSpy); // and when Span resultingSpan = resultingBuilder.build(); // then assertThat(resultingSpan.getTimestampedAnnotations()).isEmpty(); }
Example #8
Source File: SearchFilterServiceImplTest.java From aem-core-cif-components with Apache License 2.0 | 6 votes |
@Before public void setup() throws IOException { searchFilterServiceUnderTest = context.registerInjectActivateService(new SearchFilterServiceImpl()); graphqlClient = new GraphqlClientImpl(); Whitebox.setInternalState(graphqlClient, "gson", QueryDeserializer.getGson()); Whitebox.setInternalState(graphqlClient, "client", httpClient); Whitebox.setInternalState(graphqlClient, "httpMethod", HttpMethod.POST); Utils.setupHttpResponse("graphql/magento-graphql-introspection-result.json", httpClient, HttpStatus.SC_OK, "{__type"); Utils.setupHttpResponse("graphql/magento-graphql-attributes-result.json", httpClient, HttpStatus.SC_OK, "{customAttributeMetadata"); page = Mockito.spy(context.currentPage(PAGE)); pageResource = Mockito.spy(page.adaptTo(Resource.class)); when(page.adaptTo(Resource.class)).thenReturn(pageResource); }
Example #9
Source File: TestDeleteRace.java From big-c with Apache License 2.0 | 6 votes |
@Override public void run() { try { Thread.sleep(1000); LOG.info("Deleting" + path); final FSDirectory fsdir = cluster.getNamesystem().dir; INode fileINode = fsdir.getINode4Write(path.toString()); INodeMap inodeMap = (INodeMap) Whitebox.getInternalState(fsdir, "inodeMap"); fs.delete(path, false); // after deletion, add the inode back to the inodeMap inodeMap.put(fileINode); LOG.info("Deleted" + path); } catch (Exception e) { LOG.info(e); } }
Example #10
Source File: SpringWebfluxUnhandledExceptionHandlerTest.java From backstopper with Apache License 2.0 | 6 votes |
@Test public void constructor_sets_fields_as_expected() { // when SpringWebfluxUnhandledExceptionHandler handler = new SpringWebfluxUnhandledExceptionHandler( testProjectApiErrors, generalUtils, springUtilsMock, viewResolversProviderMock, serverCodecConfigurerMock ); // then assertThat(Whitebox.getInternalState(handler, "projectApiErrors")).isSameAs(testProjectApiErrors); assertThat(Whitebox.getInternalState(handler, "utils")).isSameAs(generalUtils); assertThat(handler.springUtils).isEqualTo(springUtilsMock); assertThat(handler.messageReaders).isEqualTo(messageReaders); assertThat(handler.messageWriters).isEqualTo(messageWriters); assertThat(handler.viewResolvers).isEqualTo(viewResolvers); assertThat(handler.singletonGenericServiceError) .isEqualTo(Collections.singleton(testProjectApiErrors.getGenericServiceError())); assertThat(handler.genericServiceErrorHttpStatusCode) .isEqualTo(testProjectApiErrors.getGenericServiceError().getHttpStatusCode()); }
Example #11
Source File: CircuitBreakerImplTest.java From fastbreak with Apache License 2.0 | 6 votes |
@Test public void isExceptionACircuitBreakerFailure_returns_whatever_breakingEventStrategy_returns() { // given Throwable someThrowable = new Throwable(); BreakingExceptionStrategy falseDecider = ex -> false; Whitebox.setInternalState(cbSpy, "breakingExceptionStrategy", falseDecider); // expect assertThat(cbSpy.isExceptionACircuitBreakerFailure(someThrowable)).isFalse(); // and given BreakingExceptionStrategy trueDecider = ex -> true; Whitebox.setInternalState(cbSpy, "breakingExceptionStrategy", trueDecider); // expect assertThat(cbSpy.isExceptionACircuitBreakerFailure(someThrowable)).isTrue(); }
Example #12
Source File: Jersey2ApiExceptionHandlerTest.java From backstopper with Apache License 2.0 | 6 votes |
@Before public void beforeMethod() { HttpServletRequest mockRequest = mock(HttpServletRequest.class); when(mockRequest.getRequestURI()).thenReturn("/fake/path"); when(mockRequest.getMethod()).thenReturn("GET"); when(mockRequest.getQueryString()).thenReturn("queryString"); listenerList = new Jersey2ApiExceptionHandlerListenerList( Jersey2BackstopperConfigHelper.defaultApiExceptionHandlerListeners(testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL)); unhandledSpy = spy(new JaxRsUnhandledExceptionHandler(testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL)); handlerSpy = spy(new Jersey2ApiExceptionHandler( testProjectApiErrors, listenerList, ApiExceptionHandlerUtils.DEFAULT_IMPL, unhandledSpy)); Whitebox.setInternalState(handlerSpy, "request", mockRequest); Whitebox.setInternalState(handlerSpy, "response", mock(HttpServletResponse.class)); }
Example #13
Source File: JaxRsApiExceptionHandlerTest.java From backstopper with Apache License 2.0 | 6 votes |
@Before public void beforeMethod() { HttpServletRequest mockRequest = mock(HttpServletRequest.class); when(mockRequest.getRequestURI()).thenReturn("/fake/path"); when(mockRequest.getMethod()).thenReturn("GET"); when(mockRequest.getQueryString()).thenReturn("queryString"); listenerList = new JaxRsApiExceptionHandlerListenerList(testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL); unhandledSpy = spy(new JaxRsUnhandledExceptionHandler(testProjectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL)); handlerSpy = spy(new JaxRsApiExceptionHandler( testProjectApiErrors, listenerList, ApiExceptionHandlerUtils.DEFAULT_IMPL, unhandledSpy)); Whitebox.setInternalState(handlerSpy, "request", mockRequest); Whitebox.setInternalState(handlerSpy, "response", mock(HttpServletResponse.class)); }
Example #14
Source File: SpanTest.java From wingtips with Apache License 2.0 | 5 votes |
@Test public void toKeyValueString_should_use_cached_key_value_string() { // given Span validSpan = Span.generateRootSpanForNewTrace(spanName, spanPurpose).build(); String uuidString = UUID.randomUUID().toString(); Whitebox.setInternalState(validSpan, "cachedKeyValueRepresentation", uuidString); // when String toKeyValueStringResult = validSpan.toKeyValueString(); // then assertThat(toKeyValueStringResult).isEqualTo(uuidString); }
Example #15
Source File: TestDFSUpgradeWithHA.java From hadoop with Apache License 2.0 | 5 votes |
private long getCommittedTxnIdValue(MiniQJMHACluster qjCluster) throws IOException { Journal journal1 = qjCluster.getJournalCluster().getJournalNode(0) .getOrCreateJournal(MiniQJMHACluster.NAMESERVICE); BestEffortLongFile committedTxnId = (BestEffortLongFile) Whitebox .getInternalState(journal1, "committedTxnId"); return committedTxnId != null ? committedTxnId.get() : HdfsConstants.INVALID_TXID; }
Example #16
Source File: DcosAuthImplTest.java From marathon-plugin with Apache License 2.0 | 5 votes |
/** * Test that signs JWT with a private key and verifies the contents * using the matching public key. * * @throws Exception */ @Test public void testTokenCanBeVerifiedWithPublicKey() throws Exception { final Secret secret = PowerMockito.mock(Secret.class); // final payload final String secretText = String.format(DCOS_AUTH_JSON, testUser, RSAPrivateKeyForJSON, "RS256"); // convert pub key string to actual publickey final KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); final PemReader pemReader = new PemReader(new StringReader(RSAPublicKey)); final byte[] content = pemReader.readPemObject().getContent(); final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(content); final PublicKey publicKey = keyFactory.generatePublic(keySpec); Whitebox.setInternalState(secret, "value", secretText); when(credentials.getSecret()).thenReturn(secret); when(secret.getPlainText()).thenReturn(secretText); final DcosAuthImpl dcosAuth = new DcosAuthImpl(credentials, options, ContentType.APPLICATION_JSON, builder, context); final DcosLoginPayload payload = dcosAuth.createDcosLoginPayload(); assertNotNull("Payload is null", payload); assertEquals("Uid does not match", testUser, payload.getUid()); assertNotNull("Token was not created", payload.getToken()); // this proves we can validate the JWT with public key final JWTVerifier verifier = new JWTVerifier(publicKey); final Map<String, Object> claims = verifier.verify(payload.getToken()); assertFalse("Should be populated", claims.isEmpty()); assertEquals("Users do not match", testUser, claims.get("uid")); }
Example #17
Source File: LoggerFactoryTest.java From slf4j-json-logger with Apache License 2.0 | 5 votes |
@Test public void testGetLoggerByClass() throws Exception { Logger result = LoggerFactory.getLogger(LoggerFactoryTest.class); org.slf4j.Logger slf4jLogger = (org.slf4j.Logger) Whitebox.getInternalState(result, "slf4jLogger"); assertNotNull(slf4jLogger); assertEquals(LoggerFactoryTest.class.getName(), slf4jLogger.getName()); }
Example #18
Source File: LoggerFactoryTest.java From slf4j-json-logger with Apache License 2.0 | 5 votes |
@Test public void testGetLoggerByName() throws Exception { Logger result = LoggerFactory.getLogger("LoggerFactoryTest"); org.slf4j.Logger slf4jLogger = (org.slf4j.Logger) Whitebox.getInternalState(result, "slf4jLogger"); assertNotNull(slf4jLogger); assertEquals("LoggerFactoryTest", slf4jLogger.getName()); }
Example #19
Source File: TestFSNamesystem.java From big-c with Apache License 2.0 | 5 votes |
@Test public void testReplQueuesActiveAfterStartupSafemode() throws IOException, InterruptedException{ Configuration conf = new Configuration(); FSEditLog fsEditLog = Mockito.mock(FSEditLog.class); FSImage fsImage = Mockito.mock(FSImage.class); Mockito.when(fsImage.getEditLog()).thenReturn(fsEditLog); FSNamesystem fsNamesystem = new FSNamesystem(conf, fsImage); FSNamesystem fsn = Mockito.spy(fsNamesystem); //Make shouldPopulaeReplQueues return true HAContext haContext = Mockito.mock(HAContext.class); HAState haState = Mockito.mock(HAState.class); Mockito.when(haContext.getState()).thenReturn(haState); Mockito.when(haState.shouldPopulateReplQueues()).thenReturn(true); Whitebox.setInternalState(fsn, "haContext", haContext); //Make NameNode.getNameNodeMetrics() not return null NameNode.initMetrics(conf, NamenodeRole.NAMENODE); fsn.enterSafeMode(false); assertTrue("FSNamesystem didn't enter safemode", fsn.isInSafeMode()); assertTrue("Replication queues were being populated during very first " + "safemode", !fsn.isPopulatingReplQueues()); fsn.leaveSafeMode(); assertTrue("FSNamesystem didn't leave safemode", !fsn.isInSafeMode()); assertTrue("Replication queues weren't being populated even after leaving " + "safemode", fsn.isPopulatingReplQueues()); fsn.enterSafeMode(false); assertTrue("FSNamesystem didn't enter safemode", fsn.isInSafeMode()); assertTrue("Replication queues weren't being populated after entering " + "safemode 2nd time", fsn.isPopulatingReplQueues()); }
Example #20
Source File: LotBasedEffectivityConfigSpecTest.java From eplmp with Eclipse Public License 1.0 | 5 votes |
@Before public void setUp() { LBECS = mock(LotBasedEffectivityConfigSpec.class,CALLS_REAL_METHODS); initMocks(this); when(configurationItem.getId()).thenReturn("ITEM-001"); when(tmp_CI.getId()).thenReturn("ITEM-002"); Whitebox.setInternalState(LBECS, "lotId", "5"); when(configuration.getConfigurationItem()).thenReturn(configurationItem); }
Example #21
Source File: DeviceGovernorImplTest.java From bluetooth-manager with Apache License 2.0 | 5 votes |
@Test public void testReset() { Whitebox.setInternalState(governor, "online", false); when(device.isConnected()).thenReturn(false); governor.reset(device); verify(device, times(1)).disableRSSINotifications(); verify(device, times(1)).disableServicesResolvedNotifications(); verify(device, times(1)).disableConnectedNotifications(); verify(device, times(1)).disableBlockedNotifications(); verify(device, times(1)).disableServiceDataNotifications(); verify(device, times(1)).disableManufacturerDataNotifications(); verify(device, times(1)).isConnected(); verify(device, times(0)).disconnect(); verify(bluetoothSmartDeviceListener, times(0)).disconnected(); verify(genericDeviceListener, times(0)).offline(); verify(bluetoothManager, times(0)).resetDescendants(URL); Whitebox.setInternalState(governor, "online", true); when(device.isConnected()).thenReturn(true); governor.reset(device); verify(device, times(2)).disableRSSINotifications(); verify(device, times(2)).disableServicesResolvedNotifications(); verify(device, times(2)).disableConnectedNotifications(); verify(device, times(2)).disableBlockedNotifications(); verify(device, times(2)).disableServiceDataNotifications(); verify(device, times(2)).disableManufacturerDataNotifications(); verify(device, times(2)).isConnected(); verify(device, times(1)).disconnect(); verify(bluetoothSmartDeviceListener, times(1)).disconnected(); verify(genericDeviceListener, never()).offline(); verifyNoMoreInteractions(device, genericDeviceListener, bluetoothSmartDeviceListener); }
Example #22
Source File: AsyncWingtipsHelperTest.java From wingtips with Apache License 2.0 | 5 votes |
private void verifyFunctionWithTracing(Function result, Function expectedCoreInstance, Deque<Span> expectedSpanStack, Map<String, String> expectedMdcInfo) { assertThat(result).isInstanceOf(FunctionWithTracing.class); assertThat(Whitebox.getInternalState(result, "origFunction")).isSameAs(expectedCoreInstance); assertThat(Whitebox.getInternalState(result, "spanStackForExecution")).isEqualTo(expectedSpanStack); assertThat(Whitebox.getInternalState(result, "mdcContextMapForExecution")).isEqualTo(expectedMdcInfo); }
Example #23
Source File: WingtipsApacheHttpClientInterceptorTest.java From wingtips with Apache License 2.0 | 5 votes |
public HttpClientBuilderInterceptors(HttpClientBuilder builder) { this.firstRequestInterceptors = (List<HttpRequestInterceptor>) Whitebox.getInternalState(builder, "requestFirst"); this.lastRequestInterceptors = (List<HttpRequestInterceptor>) Whitebox.getInternalState(builder, "requestLast"); this.firstResponseInterceptors = (List<HttpResponseInterceptor>) Whitebox.getInternalState(builder, "responseFirst"); this.lastResponseInterceptors = (List<HttpResponseInterceptor>) Whitebox.getInternalState(builder, "responseLast"); }
Example #24
Source File: SpanTest.java From wingtips with Apache License 2.0 | 5 votes |
@Test public void equals_returns_false_and_hashCode_different_if_spanStartTimeEpochMicros_is_different() { // given Span fullSpan1 = createFilledOutSpan(true); Span fullSpan2 = createFilledOutSpan(true); Whitebox.setInternalState(fullSpan2, "spanStartTimeEpochMicros", fullSpan1.getSpanStartTimeEpochMicros() + 1); // expect assertThat(fullSpan1.equals(fullSpan2)).isFalse(); assertThat(fullSpan1.hashCode()).isNotEqualTo(fullSpan2.hashCode()); }
Example #25
Source File: ClickHouseStatementImplTest.java From clickhouse-jdbc with Apache License 2.0 | 5 votes |
private static Object readField(Object object, String fieldName, long timeoutSecs) { long start = System.currentTimeMillis(); Object value; do { value = Whitebox.getInternalState(object, fieldName); } while (value == null && TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - start) < timeoutSecs); return value; }
Example #26
Source File: TestGraphiteMetrics.java From hadoop with Apache License 2.0 | 5 votes |
@Test public void testPutMetrics() { GraphiteSink sink = new GraphiteSink(); List<MetricsTag> tags = new ArrayList<MetricsTag>(); tags.add(new MetricsTag(MsInfo.Context, "all")); tags.add(new MetricsTag(MsInfo.Hostname, "host")); Set<AbstractMetric> metrics = new HashSet<AbstractMetric>(); metrics.add(makeMetric("foo1", 1.25)); metrics.add(makeMetric("foo2", 2.25)); MetricsRecord record = new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics); ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); final GraphiteSink.Graphite mockGraphite = makeGraphite(); Whitebox.setInternalState(sink, "graphite", mockGraphite); sink.putMetrics(record); try { verify(mockGraphite).write(argument.capture()); } catch (IOException e) { e.printStackTrace(); } String result = argument.getValue(); assertEquals(true, result.equals("null.all.Context.Context=all.Hostname=host.foo1 1.25 10\n" + "null.all.Context.Context=all.Hostname=host.foo2 2.25 10\n") || result.equals("null.all.Context.Context=all.Hostname=host.foo2 2.25 10\n" + "null.all.Context.Context=all.Hostname=host.foo1 1.25 10\n")); }
Example #27
Source File: TestWebHDFS.java From big-c with Apache License 2.0 | 5 votes |
/** * Make sure a RetriableException is thrown when rpcServer is null in * NamenodeWebHdfsMethods. */ @Test public void testRaceWhileNNStartup() throws Exception { MiniDFSCluster cluster = null; final Configuration conf = WebHdfsTestUtil.createConf(); try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build(); cluster.waitActive(); final NameNode namenode = cluster.getNameNode(); final NamenodeProtocols rpcServer = namenode.getRpcServer(); Whitebox.setInternalState(namenode, "rpcServer", null); final Path foo = new Path("/foo"); final FileSystem webHdfs = WebHdfsTestUtil.getWebHdfsFileSystem(conf, WebHdfsFileSystem.SCHEME); try { webHdfs.mkdirs(foo); fail("Expected RetriableException"); } catch (RetriableException e) { GenericTestUtils.assertExceptionContains("Namenode is in startup mode", e); } Whitebox.setInternalState(namenode, "rpcServer", rpcServer); } finally { if (cluster != null) { cluster.shutdown(); } } }
Example #28
Source File: CompositeHandlerTest.java From aws-athena-query-federation with Apache License 2.0 | 5 votes |
@Test public void doGetSplits() throws Exception { GetSplitsRequest req = mock(GetSplitsRequest.class); when(req.getRequestType()).thenReturn(MetadataRequestType.GET_SPLITS); SpillLocationVerifier mockVerifier = mock(SpillLocationVerifier.class); doNothing().when(mockVerifier).checkBucketAuthZ(any(String.class)); Whitebox.setInternalState(mockMetadataHandler, "verifier", mockVerifier); compositeHandler.handleRequest(allocator, req, new ByteArrayOutputStream(), objectMapper); verify(mockMetadataHandler, times(1)).doGetSplits(any(BlockAllocatorImpl.class), any(GetSplitsRequest.class)); }
Example #29
Source File: TracerTest.java From wingtips with Apache License 2.0 | 5 votes |
@Test public void make_code_coverage_happy3() { Logger tracerClassLogger = (Logger) Whitebox.getInternalState(Tracer.getInstance(), "classLogger"); Level origLevel = tracerClassLogger.getLevel(); try { // Enable debug logging. tracerClassLogger.setLevel(Level.DEBUG); // Exercise a span lifecycle to trigger the code branches that only do something if debug logging is on. Tracer.getInstance().startRequestWithRootSpan("foo"); Tracer.getInstance().completeRequestSpan(); } finally { tracerClassLogger.setLevel(origLevel); } }
Example #30
Source File: WingtipsSpringUtilTest.java From wingtips with Apache License 2.0 | 5 votes |
private void verifyInterceptorFieldValues( Object wingtipsInterceptor, boolean expectedSubspanOptionValue, HttpTagAndSpanNamingStrategy<HttpRequest, ClientHttpResponse> expectedTagStrategy, HttpTagAndSpanNamingAdapter<HttpRequest, ClientHttpResponse> expectedTagAdapter ) { assertThat(Whitebox.getInternalState(wingtipsInterceptor, "surroundCallsWithSubspan")) .isEqualTo(expectedSubspanOptionValue); assertThat(Whitebox.getInternalState(wingtipsInterceptor, "tagAndNamingStrategy")) .isSameAs(expectedTagStrategy); assertThat(Whitebox.getInternalState(wingtipsInterceptor, "tagAndNamingAdapter")) .isSameAs(expectedTagAdapter); }