focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@Override public V load(K key) { awaitSuccessfulInit(); try (SqlResult queryResult = sqlService.execute(queries.load(), key)) { Iterator<SqlRow> it = queryResult.iterator(); V value = null; if (it.hasNext()) { SqlRow sqlRow = it.next(); ...
@Test public void givenTypeName_whenLoad_thenReturnGenericRecordWithCorrectTypeName() { ObjectSpec spec = objectProvider.createObject(mapName, false); objectProvider.insertItems(spec, 1); Properties properties = new Properties(); properties.setProperty(DATA_CONNECTION_REF_PROPERTY, ...
public static ConsumerCreationStrategyFactory create(PulsarConsumer pulsarConsumer) { validate(pulsarConsumer); return new ConsumerCreationStrategyFactory(pulsarConsumer); }
@Test public void givenPulsarConsumerAndRetryPolicyNonNullwhenICreateFactoryverifyIllegalArgumentExceptionIsNotThrown() { ConsumerCreationStrategyFactory factory = ConsumerCreationStrategyFactory.create(mock(PulsarConsumer.class)); assertNotNull(factory); }
@Override public Consumer<Packet> get() { return responseHandler; }
@Test public void get_whenMultipleResponseThreads() { supplier = newSupplier(2); assertInstanceOf(AsyncMultithreadedResponseHandler.class, supplier.get()); }
@Override public ObjectNode encode(Instruction instruction, CodecContext context) { checkNotNull(instruction, "Instruction cannot be null"); return new EncodeInstructionCodecHelper(instruction, context).encode(); }
@Test public void modIPv6SrcInstructionTest() { final Ip6Address ip = Ip6Address.valueOf("1111::2222"); final L3ModificationInstruction.ModIPInstruction instruction = (L3ModificationInstruction.ModIPInstruction) Instructions.modL3IPv6Src(ip); final Obj...
boolean openNextFile() { try { if ( meta.getFileInFields() ) { data.readrow = getRow(); // Grab another row ... if ( data.readrow == null ) { // finished processing! if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "LoadFileInput.Log.FinishedProcessing" )...
@Test public void testOpenNextFile_noFiles() { assertFalse( stepMetaInterface.isIgnoreEmptyFile() ); // ensure default value assertFalse( stepLoadFileInput.openNextFile() ); }
@SuppressWarnings("unused") // Part of required API. public void execute( final ConfiguredStatement<InsertValues> statement, final SessionProperties sessionProperties, final KsqlExecutionContext executionContext, final ServiceContext serviceContext ) { final InsertValues insertValues = s...
@Test public void shouldThrowOnClusterAuthorizationExceptionWrappedInKafkaException() { // Given: final ConfiguredStatement<InsertValues> statement = givenInsertValues( allAndPseudoColumnNames(SCHEMA), ImmutableList.of( new LongLiteral(1L), new StringLiteral("str"), ...
public static ServiceDiscovery<ZookeeperInstance> buildServiceDiscovery( CuratorFramework curatorFramework, String basePath) { return ServiceDiscoveryBuilder.builder(ZookeeperInstance.class) .client(curatorFramework) .basePath(basePath) .build(); }
@Test void testBuildServiceDiscovery() throws Exception { CuratorFramework curatorFramework = CuratorFrameworkUtils.buildCuratorFramework(registryUrl, null); ServiceDiscovery<ZookeeperInstance> discovery = CuratorFrameworkUtils.buildServiceDiscovery(curatorFramework, ROOT_PATH.getPar...
public synchronized String decrypt(String keyRingId, String keyId, String ciphertext) { CryptoKeyName keyName = CryptoKeyName.of(projectId, region, keyRingId, keyId); LOG.info("Decrypting given ciphertext using key {}.", keyName.toString()); try (KeyManagementServiceClient client = clientFactory.getKMSCli...
@Test public void testDecryptShouldEncodeEncryptedMessageWithUTF8() { String ciphertext = "ciphertext"; DecryptResponse decryptedResponse = DecryptResponse.newBuilder().setPlaintext(ByteString.copyFromUtf8(ciphertext)).build(); String base64EncodedCiphertext = new String( Base6...
public Set<String> assembleAllWatchKeys(String appId, String clusterName, String namespace, String dataCenter) { Multimap<String, String> watchedKeysMap = assembleAllWatchKeys(appId, clusterName, Sets.newHashSet(namespace), dataCenter); return Sets.newHashSet(wa...
@Test public void testAssembleWatchKeysForNoAppIdPlaceHolder() throws Exception { Multimap<String, String> watchKeysMap = watchKeysUtil.assembleAllWatchKeys(ConfigConsts.NO_APPID_PLACEHOLDER, someCluster, Sets.newHashSet(someNamespace, anotherNamespace), someDC); assertTrue(watchKeysMap.i...
public int doWork() { final long nowNs = nanoClock.nanoTime(); cachedNanoClock.update(nowNs); dutyCycleTracker.measureAndUpdate(nowNs); final int workCount = commandQueue.drain(CommandProxy.RUN_TASK, Configuration.COMMAND_DRAIN_LIMIT); final long shortSendsBefore = shortSen...
@Test void shouldSendSetupFrameOnChannelWhenTimeoutWithoutStatusMessage() { sender.doWork(); assertThat(receivedFrames.size(), is(1)); nanoClock.advance(Configuration.PUBLICATION_SETUP_TIMEOUT_NS - 1); sender.doWork(); assertThat(receivedFrames.size(), is(1)); na...
@Override @SuppressWarnings("unchecked") public int run() throws IOException { Preconditions.checkArgument(targets != null && targets.size() == 1, "Parquet file is required."); if (targets.size() > 1) { Preconditions.checkArgument(outputPath == null, "Cannot output multiple schemas to file %s", outpu...
@Test public void testSchemaCommandOverwriteExistentFile() throws IOException { File inputFile = parquetFile(); File outputFile = new File(getTempFolder(), getClass().getSimpleName() + ".avsc"); FileUtils.touch(outputFile); Assert.assertEquals(0, outputFile.length()); SchemaCommand command = new S...
@Override public Branch getBranch() { checkState(branch.isInitialized(), BRANCH_NOT_SET); return branch.getProperty(); }
@Test public void getBranch_throws_ISE_when_holder_is_not_initialized() { assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getBranch()) .isInstanceOf(IllegalStateException.class) .hasMessage("Branch has not been set"); }
@Override public long checksum() { byte[] bs = new byte[16]; Bits.putLong(bs, 0, this.index); Bits.putLong(bs, 8, this.term); return CrcUtil.crc64(bs); }
@Test public void testChecksum() { LogId logId = new LogId(); logId.setIndex(1); logId.setTerm(2); long c = logId.checksum(); assertTrue(c != 0); assertEquals(c, logId.checksum()); }
public static KafkaPrincipalBuilder createPrincipalBuilder(Map<String, ?> configs, KerberosShortNamer kerberosShortNamer, SslPrincipalMapper sslPrincipalMapper) { Class<?> principalBuild...
@Test public void testCreateConfigurableKafkaPrincipalBuilder() { Map<String, Object> configs = new HashMap<>(); configs.put(BrokerSecurityConfigs.PRINCIPAL_BUILDER_CLASS_CONFIG, ConfigurableKafkaPrincipalBuilder.class); KafkaPrincipalBuilder builder = ChannelBuilders.createPrincipalBuilder(...
public WorkProcessor<Page> merge(List<Type> keyTypes, List<Type> allTypes, List<WorkProcessor<Page>> pages, DriverYieldSignal driverYieldSignal) { return merge(keyTypes, null, allTypes, pages, driverYieldSignal); }
@Test public void testBinaryMergeIteratorOverPageWith() { Page emptyPage = new Page(0, BIGINT.createFixedSizeBlockBuilder(0).build()); Page page = rowPagesBuilder(BIGINT).row(42).build().get(0); WorkProcessor<Page> mergedPage = new MergeHashSort(newSimpleAggregatedMemoryContext()).merge...
public ConsumerGroupDescribeResponseData.DescribedGroup asDescribedGroup( long committedOffset, String defaultAssignor, TopicsImage topicsImage ) { ConsumerGroupDescribeResponseData.DescribedGroup describedGroup = new ConsumerGroupDescribeResponseData.DescribedGroup() .se...
@Test public void testAsDescribedGroup() { SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext()); ConsumerGroup group = new ConsumerGroup(snapshotRegistry, "group-id-1", mock(GroupCoordinatorMetricsShard.class)); snapshotRegistry.idempotentCreateSnapshot(0); asse...
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) { MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).get()); if (handshakeReceived) { MySQLPacket responsePacket = dec...
@Test void assertDecodeAuthSwitchRequestPacket() throws ReflectiveOperationException { MySQLNegotiatePackageDecoder negotiatePackageDecoder = new MySQLNegotiatePackageDecoder(); Plugins.getMemberAccessor().set(MySQLNegotiatePackageDecoder.class.getDeclaredField("handshakeReceived"), negotiatePackage...
public CompletableFuture<Void> requestDownloadTopologyBlobs(final LocalAssignment assignment, final int port, final BlobChangingCallback cb) throws IOException { final PortAndAssignment pna = new TimePortAndAssignment(new PortAndAssignmentImpl(port...
@Test public void testRequestDownloadTopologyBlobs() throws Exception { ConfigUtils mockedConfigUtils = mock(ConfigUtils.class); ConfigUtils previousConfigUtils = ConfigUtils.setInstance(mockedConfigUtils); AsyncLocalizer victim = null; try (TmpPath stormLocal = new TmpPath(); TmpP...
protected static String getReverseZoneNetworkAddress(String baseIp, int range, int index) throws UnknownHostException { if (index < 0) { throw new IllegalArgumentException( String.format("Invalid index provided, must be positive: %d", index)); } if (range < 0) { throw new Illegal...
@Test public void testThrowIllegalArgumentExceptionIfRangeIsNegative() throws Exception { exception.expect(IllegalArgumentException.class); ReverseZoneUtils.getReverseZoneNetworkAddress(NET, -1, INDEX); }
public static <T extends Serializable> SerializableCoder<T> of(TypeDescriptor<T> type) { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) type.getRawType(); return new SerializableCoder<>(clazz, type); }
@Test @Category(NeedsRunner.class) public void testDefaultCoder() throws Exception { p.enableAbandonedNodeEnforcement(true); // Use MyRecord as input and output types without explicitly specifying // a coder (this uses the default coders, which may not be // SerializableCoder). PCollection<Stri...
@Override public Enumeration<URL> getResources(String name) throws IOException { List<URL> resources = new ArrayList<>(); ClassLoadingStrategy loadingStrategy = getClassLoadingStrategy(name); log.trace("Received request to load resources '{}'", name); for (ClassLoadingStrategy.Source...
@Test void parentFirstGetResourcesExistsInParent() throws IOException, URISyntaxException { Enumeration<URL> resources = parentFirstPluginClassLoader.getResources("META-INF/file-only-in-parent"); assertNumberOfResourcesAndFirstLineOfFirstElement(1, "parent", resources); }
@Nullable static String normalizeIdField(String field, @Nullable String id, boolean isNullable) { if (id == null) { if (isNullable) return null; throw new NullPointerException(field + " == null"); } int length = id.length(); if (length == 0) { if (isNullable) return null; throw n...
@Test void normalizeIdField_padsTo128() { assertThat(normalizeIdField("traceId", "4d2000000000000162e", false)) .isEqualTo("00000000000004d2000000000000162e"); }
@Override public void getPipeline( GetJobPipelineRequest request, StreamObserver<GetJobPipelineResponse> responseObserver) { LOG.trace("{} {}", GetJobPipelineRequest.class.getSimpleName(), request); String invocationId = request.getJobId(); try { JobInvocation invocation = getInvocation(invoca...
@Test public void testGetPipelineFailure() { prepareJob(); JobApi.GetJobPipelineRequest request = JobApi.GetJobPipelineRequest.newBuilder().setJobId(TEST_JOB_ID).build(); RecordingObserver<JobApi.GetJobPipelineResponse> recorder = new RecordingObserver<>(); service.getPipeline(request, record...
@Override public int read() throws IOException { if (mPosition == mLength) { // at end of file return -1; } updateStreamIfNeeded(); int res = mUfsInStream.get().read(); if (res == -1) { return -1; } mPosition++; Metrics.BYTES_READ_FROM_UFS.inc(1); return res; }
@Test public void manyBytesRead() throws IOException, AlluxioException { AlluxioURI ufsPath = getUfsPath(); createFile(ufsPath, CHUNK_SIZE); try (FileInStream inStream = getStream(ufsPath)) { byte[] res = new byte[CHUNK_SIZE]; assertEquals(CHUNK_SIZE, inStream.read(res)); assertTrue(Buff...
@Override public void start(final Xid xid, final int flags) throws XAException { try { delegate.start(xid, flags); } catch (final XAException ex) { throw mapXAException(ex); } }
@Test void assertStart() throws XAException { singleXAResource.start(xid, 1); verify(xaResource).start(xid, 1); }
@Override public String upgradeFirmwareOndemand(String target) { DriverHandler handler = handler(); NetconfController controller = handler.get(NetconfController.class); MastershipService mastershipService = handler.get(MastershipService.class); DeviceId ncDeviceId = handler.data().de...
@Test public void testInvalidOndemandFirmwareUpgradeInput() throws Exception { String reply; String target; for (int i = ZERO; i < INVALID_ONDEMAND_FWDL_TCS.length; i++) { target = INVALID_ONDEMAND_FWDL_TCS[i]; reply = voltConfig.upgradeFirmwareOndemand(target); ...
@Override public long offset() { if (recordContext == null) { // This is only exposed via the deprecated ProcessorContext, // in which case, we're preserving the pre-existing behavior // of returning dummy values when the record context is undefined. // For of...
@Test public void shouldReturnOffsetFromRecordContext() { assertThat(context.offset(), equalTo(recordContext.offset())); }
public FEELFnResult<Boolean> invoke(@ParameterName("string") String string, @ParameterName("match") String match) { if ( string == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null")); } if ( match == null ) { return...
@Test void invokeNotContains() { FunctionTestUtil.assertResult(containsFunction.invoke("test", "ex"), false); FunctionTestUtil.assertResult(containsFunction.invoke("test", "u"), false); FunctionTestUtil.assertResult(containsFunction.invoke("test", "esty"), false); }
@Override public Flux<ReactiveRedisConnection.BooleanResponse<RenameCommand>> renameNX(Publisher<RenameCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getNewName(), "New name must not be null...
@Test public void testRenameNX() { connection.stringCommands().set(originalKey, value).block(); if (hasTtl) { connection.keyCommands().expire(originalKey, Duration.ofSeconds(1000)).block(); } Integer originalSlot = getSlotForKey(originalKey); newKey = getNewKeyFo...
@Override @PublicAPI(usage = ACCESS) public SliceRule as(String newDescription) { return copyWithTransformation(new As(newDescription)); }
@Test public void reports_number_of_violations_if_all_cycles_are_reported() { int expectedNumberOfCycles = getNumberOfCyclesInCompleteGraph(7); String failureReport = evaluateCompleteGraphCycleFreeWithCycleLimit(expectedNumberOfCycles); assertThat(failureReport).as("failure report").contai...
public JSONObject getProperties() { return properties; }
@Test public void getProperties() { SAExposureData exposureData = new SAExposureData("ExposeEvent"); exposureData.setProperties(new JSONObject()); Assert.assertNotNull(exposureData.getProperties()); }
@Override public Collection<RedisServer> slaves(NamedNode master) { List<Map<String, String>> slaves = connection.sync(StringCodec.INSTANCE, RedisCommands.SENTINEL_SLAVES, master.getName()); return toRedisServersList(slaves); }
@Test public void testSlaves() { Collection<RedisServer> masters = connection.masters(); Collection<RedisServer> slaves = connection.slaves(masters.iterator().next()); assertThat(slaves).hasSize(2); }
static ConfigServer[] toConfigServers(String configserversString) { return multiValueParameterStream(configserversString) .map(CloudConfigInstallVariables::toConfigServer) .toArray(ConfigServer[]::new); }
@Test public void port_can_be_configured() { CloudConfigOptions.ConfigServer[] parsed = toConfigServers("myhost:123"); int port = parsed[0].port.get(); assertEquals(123, port); }
static boolean needWrap(MethodDescriptor methodDescriptor, Class<?>[] parameterClasses, Class<?> returnClass) { String methodName = methodDescriptor.getMethodName(); // generic call must be wrapped if (CommonConstants.$INVOKE.equals(methodName) || CommonConstants.$INVOKE_ASYNC.equals(methodName)...
@Test void testMethodWithNoParametersAndReturnJava() throws Exception { Method method = DescriptorService.class.getMethod("noParameterAndReturnJavaClassMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); assertEquals("", descriptor.getParamDesc()); Asserti...
public static ReadChangeStream readChangeStream() { return ReadChangeStream.create(); }
@Test public void testReadChangeStreamPassWithoutValidation() { BigtableIO.ReadChangeStream readChangeStream = BigtableIO.readChangeStream() .withProjectId("project") .withInstanceId("instance") .withTableId("table") .withoutValidation(); // No error is ...
public static ConsumerCreationStrategyFactory create(PulsarConsumer pulsarConsumer) { validate(pulsarConsumer); return new ConsumerCreationStrategyFactory(pulsarConsumer); }
@Test public void givenPulsarConsumerIsNullwhenICreateFactoryverifyIllegalArgumentExceptionIsThrown() { assertThrows(IllegalArgumentException.class, () -> ConsumerCreationStrategyFactory.create(null)); }
@Override public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { try { final IRODSFileSystemAO fs = session.getClient(); final IRODSFileFactory factory = fs.getIRODSFileFactory();...
@Test(expected = NotfoundException.class) public void testReadNotFound() throws Exception { final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol()))); final Profile profile = new ProfilePlistReader(factory).read( this.getClass().ge...
protected RemotingCommand request(ChannelHandlerContext ctx, RemotingCommand request, ProxyContext context, long timeoutMillis) throws Exception { String brokerName; if (request.getCode() == RequestCode.SEND_MESSAGE_V2) { if (request.getExtFields().get(BROKER_NAME_FIELD_FOR_SEND_MESS...
@Test public void testRequest() throws Exception { String brokerName = "broker"; RemotingCommand response = RemotingCommand.createResponseCommand(ResponseCode.SUCCESS, "remark"); when(messagingProcessorMock.request(any(), eq(brokerName), any(), anyLong())).thenReturn(CompletableFuture.comple...
@Override public String[] split(String text) { boundary.setText(text); List<String> words = new ArrayList<>(); int start = boundary.first(); int end = boundary.next(); while (end != BreakIterator.DONE) { String word = text.substring(start, end).trim(); ...
@Test public void testSplitHyphen() { System.out.println("tokenize hyphen"); String text = "On a noncash basis for the quarter, the bank reported a " + "loss of $7.3 billion because of a $10.4 billion write-down " + "in the value of its credit card unit, attributed to...
@VisibleForTesting static boolean isBrokenPipe(IOException original) { Throwable exception = original; while (exception != null) { String message = exception.getMessage(); if (message != null && message.toLowerCase(Locale.US).contains("broken pipe")) { return true; } exception...
@Test public void testIsBrokenPipe_nestedBrokenPipe() { IOException exception = new IOException(new SSLException(new SocketException("Broken pipe"))); Assert.assertTrue(RegistryEndpointCaller.isBrokenPipe(exception)); }
void performCleanUp(@Nullable Runnable task) { evictionLock.lock(); try { maintenance(task); } finally { evictionLock.unlock(); } rescheduleCleanUpIfIncomplete(); }
@Test @CheckMaxLogLevel(ERROR) public void cleanupTask_exception() { var expected = new RuntimeException(); BoundedLocalCache<?, ?> cache = Mockito.mock(); doThrow(expected).when(cache).performCleanUp(any()); var task = new PerformCleanupTask(cache); assertThat(task.exec()).isFalse(); assert...
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.about_menu_option: Navigation.findNavController(requireView()) .navigate(MainFragmentDirections.actionMainFragmentToAboutAnySoftKeyboardFragment()); return true; case R.id....
@Test @Config(sdk = Build.VERSION_CODES.JELLY_BEAN_MR2) @Ignore("Robolectric does not support this API level") public void testRestoreMenuItemNotSupportedPreKitKat() throws Exception { final MainFragment fragment = startFragment(); final FragmentActivity activity = fragment.getActivity(); Menu menu =...
public static UserAgent parse(String userAgentString) { return UserAgentParser.parse(userAgentString); }
@Test public void parseQQTest() { final String uaString = "User-Agent: MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; final UserAgent ua = UserAgentUtil.parse(uaString); assertEquals("QQBrowser",...
protected boolean shouldAllowPreemptiveResponse(Channel channel) { // If the request timed-out while being read, then there won't have been any LastContent, but thats ok because // the connection will have to be discarded anyway. StatusCategory status = StatusCategoryUtils.getSta...
@Test void flagResponseBeforeRequestRead() { final ClientResponseWriter responseWriter = new ClientResponseWriter(new BasicRequestCompleteHandler()); final EmbeddedChannel channel = new EmbeddedChannel(); final SessionContext context = new SessionContext(); StatusCategoryUtils.setSt...
@Override public Column convert(BasicTypeDefine typeDefine) { Long typeDefineLength = typeDefine.getLength(); PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.get...
@Test public void testConvertDate() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder().name("test").columnType("date").dataType("date").build(); Column column = IrisTypeConverter.INSTANCE.convert(typeDefine); Assertions.assertEquals(typeDefine.getName(), column....
public IssueQuery create(SearchRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { final ZoneId timeZone = parseTimeZone(request.getTimeZone()).orElse(clock.getZone()); Collection<RuleDto> ruleDtos = ruleKeysToRuleId(dbSession, request.getRules()); Collection<String> rule...
@Test public void add_unknown_when_no_component_found() { SearchRequest request = new SearchRequest() .setComponentKeys(asList("does_not_exist")); IssueQuery query = underTest.create(request); assertThat(query.componentUuids()).containsOnly("<UNKNOWN>"); }
public List<String> nodesWithTimedOutRequests(long now) { List<String> nodeIds = new ArrayList<>(); for (Map.Entry<String, Deque<NetworkClient.InFlightRequest>> requestEntry : requests.entrySet()) { String nodeId = requestEntry.getKey(); Deque<NetworkClient.InFlightRequest> deque...
@Test public void testTimedOutNodes() { Time time = new MockTime(); addRequest("A", time.milliseconds(), 50); addRequest("B", time.milliseconds(), 200); addRequest("B", time.milliseconds(), 100); time.sleep(50); assertEquals(Collections.emptyList(), inFlightRequests...
public void setProperty(String name, String value) { if (value == null) { return; } Method setter = aggregationAssessor.findSetterMethod(name); if (setter == null) { addWarn("No setter for property [" + name + "] in " + objClass.getName() + "."); } else { ...
@Test public void charset() { setter.setProperty("charset", "UTF-8"); assertEquals(Charset.forName("UTF-8"), house.getCharset()); house.setCharset(null); setter.setProperty("charset", "UTF"); assertNull(house.getCharset()); StatusChecker checker = new StatusChecker(...
public void cancelTimer(IPollEvents sink, int id) { assert (Thread.currentThread() == worker); TimerInfo copy = new TimerInfo(sink, id); // Complexity of this operation is O(n). We assume it is rarely used. TimerInfo timerInfo = timers.find(copy); if (timerInfo != null) { ...
@Test public void testCancelTimer() { final PollerBaseTested poller = new PollerBaseTested(); poller.addTimer(1000, sink, 1); long timeout = poller.executeTimers(); assertThat(timeout, is(1000L)); assertThat(poller.isEmpty(), is(false)); poller.cancelTimer(sink...
public static InputStream limitedInputStream(final InputStream is, final int limit) throws IOException { return new InputStream() { private int mPosition = 0; private int mMark = 0; private final int mLimit = Math.min(limit, is.available()); @Override ...
@Test void testReadEmptyByteArray() { Assertions.assertThrows(NullPointerException.class, () -> { InputStream is = StreamUtilsTest.class.getResourceAsStream("/StreamUtilsTest.txt"); try { is = StreamUtils.limitedInputStream(is, 2); is.read(null, 0, 1);...
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle( final LifecycleScopeProvider<E> provider) throws OutsideScopeException { return resolveScopeFromLifecycle(provider, true); }
@Test public void resolveScopeFromLifecycle_error() { PublishSubject<Integer> lifecycle = PublishSubject.create(); TestObserver<?> o = testSource(resolveScopeFromLifecycle(lifecycle, 3)); lifecycle.onNext(0); o.assertNoErrors().assertNotComplete(); lifecycle.onNext(1); o.assertNoErrors().ass...
public static Range<Integer> integerRange(String range) { return ofString(range, Integer::parseInt, Integer.class); }
@Test public void testUnboundedRangeStringIsRejected() { PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE; assertEquals(Range.all(), instance.integerRange("(,)")); }
public boolean updateTenantCapacity(String tenant, Integer quota, Integer maxSize, Integer maxAggrCount, Integer maxAggrSize) { List<Object> argList = CollectionUtils.list(); List<String> columns = new ArrayList<>(); if (quota != null) { columns.add("quota"); ...
@Test void testUpdateTenantCapacity() { final MockedStatic<TimeUtils> timeUtilsMockedStatic = Mockito.mockStatic(TimeUtils.class); List<Object> argList = CollectionUtils.list(); Integer quota = 1; argList.add(quota); Integer maxSize = 2; arg...
@Override public boolean equals(Object o) { if (!(o instanceof Path)) { return false; } Path that = (Path)o; return this.uri.equals(that.uri); }
@Test (timeout = 30000) public void testEquals() { assertFalse(new Path("/").equals(new Path("/foo"))); }
public static ShenyuAdminResult success() { return success(""); }
@Test public void testSuccessWithMsg() { final ShenyuAdminResult result = ShenyuAdminResult.success("msg"); assertEquals(CommonErrorCode.SUCCESSFUL, result.getCode().intValue()); assertEquals("msg", result.getMessage()); assertNull(result.getData()); assertEquals(3582918, res...
public static Split split(String regex) { return split(Pattern.compile(regex), false); }
@Test @Category(NeedsRunner.class) public void testSplitsWithoutEmpty() { PCollection<String> output = p.apply(Create.of("The quick brown fox jumps over the lazy dog")) .apply(Regex.split("\\s", false)); PAssert.that(output) .containsInAnyOrder("The", "quick", "brown", "f...
@Override public List<TransferItem> list(final Session<?> session, final Path directory, final Local local, final ListProgressListener listener) throws BackgroundException { if(log.isDebugEnabled()) { log.debug(String.format("List children for %s", directory));...
@Test public void testList() throws Exception { final Path root = new Path("/t", EnumSet.of(Path.Type.directory)); Transfer t = new DownloadTransfer(new Host(new TestProtocol()), root, new NullLocal("l")); final NullSession session = new NullSession(new Host(new TestProtocol())) { ...
public static HollowSchema parseSchema(String schema) throws IOException { StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(schema)); configureTokenizer(tokenizer); return parseSchema(tokenizer); }
@Test public void parsesSetSchemaWithKey() throws IOException { String listSchema = "SetOfTypeA Set<TypeA> @HashKey(id.value);\n"; HollowSetSchema schema = (HollowSetSchema) HollowSchemaParser.parseSchema(listSchema); Assert.assertEquals("SetOfTypeA", schema.getName()); Assert.asse...
public int run(String[] args) throws Exception { if (args.length == 0) { System.err.println("Too few arguments!"); printUsage(); return 1; } Path path = new Path(args[0]); FileSystem fs = path.getFileSystem(getConf()); if (fs.exists(path)) { System.err.println("given path exi...
@Test public void testLoading() throws Exception { Configuration conf = new Configuration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2) .build(); FileSystem fs = cluster.getFileSystem(); ByteArrayOutputStream out = new ByteArrayOutputStream(); TypedBytes...
public static <@NonNull E> CompletableSource resolveScopeFromLifecycle( final LifecycleScopeProvider<E> provider) throws OutsideScopeException { return resolveScopeFromLifecycle(provider, true); }
@Test public void lifecycleCheckEnd_shouldFailIfEndedWithNoHandler() { TestLifecycleScopeProvider lifecycle = TestLifecycleScopeProvider.createInitial(STOPPED); try { testSource(resolveScopeFromLifecycle(lifecycle, true)); throw new AssertionError("Lifecycle resolution should have failed due to i...
@Override public void run(DiagnosticsLogWriter writer) { writer.startSection("BuildInfo"); writer.writeKeyValueEntry("Build", buildInfo.getBuild()); // we convert to string to prevent formatting the number writer.writeKeyValueEntry("BuildNumber", "" + buildInfo.getBuildNumber()); ...
@Test public void test() { plugin.run(logWriter); BuildInfo buildInfo = BuildInfoProvider.getBuildInfo(); assertContains("BuildNumber=" + buildInfo.getBuildNumber()); assertContains("Build=" + buildInfo.getBuild()); assertContains("Revision=" + buildInfo.getRevision()); ...
@Override public Long createMailAccount(MailAccountSaveReqVO createReqVO) { MailAccountDO account = BeanUtils.toBean(createReqVO, MailAccountDO.class); mailAccountMapper.insert(account); return account.getId(); }
@Test public void testCreateMailAccount_success() { // 准备参数 MailAccountSaveReqVO reqVO = randomPojo(MailAccountSaveReqVO.class, o -> o.setMail(randomEmail())) .setId(null); // 防止 id 被赋值 // 调用 Long mailAccountId = mailAccountService.createMailAccount(reqVO); /...
@Override public boolean remove(long key1, long key2) { return super.remove0(key1, key2); }
@Test public void testRemove() { final long key1 = randomKey(); final long key2 = randomKey(); insert(key1, key2); assertTrue(hsa.remove(key1, key2)); assertFalse(hsa.remove(key1, key2)); }
public static void runBeforeProcessing(PipelineOptions options) { // We load the logger in the method to minimize the amount of class loading that happens // during class initialization. Logger logger = LoggerFactory.getLogger(JvmInitializers.class); for (JvmInitializer initializer : ReflectHelpers.load...
@Test public void runBeforeProcessing_runsInitializersWithOptions() { PipelineOptions options = TestPipeline.testingPipelineOptions(); JvmInitializers.runBeforeProcessing(options); assertTrue(beforeProcessingRan); assertEquals(options, receivedOptions); expectedLogs.verifyInfo("Running JvmInitia...
@Override public WidgetsBundle findWidgetsBundleByTenantIdAndAlias(UUID tenantId, String alias) { return DaoUtil.getData(widgetsBundleRepository.findWidgetsBundleByTenantIdAndAlias(tenantId, alias)); }
@Test public void testFindWidgetsBundleByTenantIdAndAlias() { createSystemWidgetBundles(1, "WB_"); WidgetsBundle widgetsBundle = widgetsBundleDao.findWidgetsBundleByTenantIdAndAlias( TenantId.SYS_TENANT_ID.getId(), "WB_" + 0); widgetsBundles = List.of(widgetsBundle); ...
public List<NacosServiceInstance> getInstances(String serviceId) { try { return Optional.of(nacosServiceDiscovery.getInstances(serviceId)) .map(instances -> { ServiceCache.setInstances(serviceId, instances); return instances; ...
@Test public void testGetInstances() throws NacosException { mockNamingService(); Assert.assertNotNull(nacosClient.getInstances("test")); }
@Override public void doSubscribe(URL url, NotifyListener listener) { url = addRegistryClusterKey(url); serviceDiscovery.subscribe(url, listener); Set<String> mappingByUrl = ServiceNameMapping.getMappingByUrl(url); String key = ServiceNameMapping.buildMappingKey(url); if ...
@Test void testDoSubscribe() { ApplicationModel applicationModel = spy(ApplicationModel.defaultModel()); when(applicationModel.getDefaultExtension(ServiceNameMapping.class)).thenReturn(mapping); // Exceptional case, no interface-app mapping found when(mapping.getAndListen(any(), any(...
protected String getCurrentReleaseVersion() { HttpURLConnection conn = null; try { final String str = settings.getString(Settings.KEYS.ENGINE_VERSION_CHECK_URL, "https://jeremylong.github.io/DependencyCheck/current.txt"); final URL url = new URL(str); final URLConnect...
@Test public void testGetCurrentReleaseVersion() { EngineVersionCheck instance = new EngineVersionCheck(getSettings()); DependencyVersion minExpResult = new DependencyVersion("1.2.6"); String release = instance.getCurrentReleaseVersion(); DependencyVersion result = new DependencyVers...
@POST @ZeppelinApi public Response createNote(String message) throws IOException { String user = authenticationService.getPrincipal(); LOGGER.info("Creating new note by JSON {}", message); NewNoteRequest request = GSON.fromJson(message, NewNoteRequest.class); String defaultInterpreterGroup = request...
@Test void testGetReloadNote() throws IOException { LOG.info("Running testGetNote"); String note1Id = null; try { note1Id = notebook.createNote("note1", anonymous); notebook.processNote(note1Id, note1 -> { note1.addNewParagraph(AuthenticationInfo.ANONYMOUS); noteb...
@PutMapping(value = "/log") @Secured(action = ActionTypes.WRITE, resource = "nacos/admin", signType = SignType.CONSOLE) public RestResult<Void> updateLog(@RequestBody LogUpdateRequest logUpdateRequest) { Loggers.setLogLevel(logUpdateRequest.getLogName(), logUpdateRequest.getLogLevel()); return R...
@Test void testSetLogLevel() { LogUpdateRequest request = new LogUpdateRequest(); request.setLogName("core"); request.setLogLevel("debug"); RestResult<?> res = coreOpsV2Controller.updateLog(request); assertTrue(res.ok()); assertTrue(Loggers.CORE.isDebugEnable...
@SuppressWarnings("unchecked") public static <T> AgentServiceLoader<T> getServiceLoader(final Class<T> service) { return (AgentServiceLoader<T>) LOADERS.computeIfAbsent(service, AgentServiceLoader::new); }
@Test void assertGetServiceLoaderWithImplementSPI() { AgentServiceLoader<AgentServiceSPIFixture> actual = AgentServiceLoader.getServiceLoader(AgentServiceSPIFixture.class); assertThat(actual.getServices().size(), is(1)); AgentServiceSPIFixture actualInstance = actual.getServices().iterator()...
public Map<String, DataSourceConfiguration> loadDataSourceConfigurations(final String databaseName) { return dataSourceUnitService.load(databaseName).entrySet().stream().collect(Collectors.toMap(Entry::getKey, entry -> DataSourcePoolPropertiesCreator.createConfiguration(entry.getValue()), (oldVa...
@Test void assertLoadDataSourceConfigurations() { assertTrue(metaDataPersistService.loadDataSourceConfigurations("foo_db").isEmpty()); }
@Override public boolean isEnhanced() { return true; }
@Test void testIsEnhancedAlwaysTrueAsTiered() { assertTrue(service.isEnhanced()); }
@Nonnull @Override public Optional<Signature> parse( @Nullable String str, @Nonnull DetectionLocation detectionLocation) { if (str == null) { return Optional.empty(); } final String generalizedStr = str.toLowerCase().trim(); if (!generalizedStr.contains("...
@Test void SHA384withDSA() { DetectionLocation testDetectionLocation = new DetectionLocation("testfile", 1, 1, List.of("test"), () -> "SSL"); JcaSignatureMapper jcaSignatureMapper = new JcaSignatureMapper(); Optional<Signature> signatureOptional = jcaSignatur...
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldEvaluateBooleanSchemaForNotLikeExpression() { final Expression expression = new NotExpression(new LikePredicate(COL1, new StringLiteral("%foo"), Optional.empty())); final SqlType exprType0 = expressionTypeManager.getExpressionSqlType(expression); assertThat(exprType0, is(Sq...
@Override public String getGroupKeyString(int rowIndex, int groupKeyColumnIndex) { throw new AssertionError("No group key string for result table"); }
@Test(expectedExceptions = AssertionError.class) public void testGetGroupKeyString() { // Run the test _resultTableResultSetUnderTest.getGroupKeyString(0, 0); }
@Override public List<JreInfoRestResponse> getJresMetadata(@Nullable String os, @Nullable String arch) { Predicate<JreInfoRestResponse> osFilter = isBlank(os) ? jre -> true : (jre -> OS.from(jre.os()) == OS.from(os)); Predicate<JreInfoRestResponse> archFilter = isBlank(arch) ? jre -> true : (jre -> Arch.from(...
@Test void getJresMetadata_shouldReturnEmptyList_whenNoMetadata() { List<JreInfoRestResponse> result = jresHandler.getJresMetadata("windows", "x64"); assertThat(result).isEmpty(); }
public static DynamicVoter parse(String input) { input = input.trim(); int atIndex = input.indexOf("@"); if (atIndex < 0) { throw new IllegalArgumentException("No @ found in dynamic voter string."); } if (atIndex == 0) { throw new IllegalArgumentException(...
@Test public void testParseDynamicVoterWithUnbalancedBrackets() { assertEquals("Hostname began with left bracket, but no right bracket was found.", assertThrows(IllegalArgumentException.class, () -> DynamicVoter.parse("5@[2001:4860:4860::8888:8020:__0IZ-0DRNazJ49kCZ1EMQ")). ...
public void start() throws Exception { this.producerNameGenerator = new DistributedIdGenerator(pulsar.getCoordinationService(), PRODUCER_NAME_GENERATOR_PATH, pulsar.getConfiguration().getClusterName()); ServiceConfiguration serviceConfig = pulsar.getConfiguration(); List<BindAdd...
@Test public void shouldNotPreventCreatingTopicWhenNonexistingTopicIsCached() throws Exception { // run multiple iterations to increase the chance of reproducing a race condition in the topic cache for (int i = 0; i < 100; i++) { final String topicName = "persistent://prop/ns-abc/topic-c...
@Override public void createFloatingIp(KubevirtFloatingIp floatingIp) { checkNotNull(floatingIp, ERR_NULL_FLOATING_IP); checkArgument(!Strings.isNullOrEmpty(floatingIp.id()), ERR_NULL_FLOATING_IP_ID); kubevirtRouterStore.createFloatingIp(floatingIp); log.info(String.format(MSG_FLOA...
@Test(expected = IllegalArgumentException.class) public void testCreateDuplicateFloatingIp() { target.createFloatingIp(FLOATING_IP_ASSOCIATED); target.createFloatingIp(FLOATING_IP_DISASSOCIATED); }
static BsonTimestamp startAtTimestamp(Map<String, String> options) { String startAtValue = options.get(START_AT_OPTION); if (isNullOrEmpty(startAtValue)) { throw QueryException.error("startAt property is required for MongoDB stream. " + POSSIBLE_VALUES); } if ("now".equalsIgn...
@Test public void parses_dateTimeString_startAt() { // given long time = System.currentTimeMillis(); LocalDateTime timeDate = LocalDateTime.ofEpochSecond(time / 1000, 0, UTC); String dateAsString = timeDate.format(DateTimeFormatter.ISO_DATE_TIME) + "Z"; // when BsonT...
public boolean isAbsolute() { return mUri.isAbsolute(); }
@Test public void isAbsoluteTests() { assertTrue(new AlluxioURI("file:/a").isAbsolute()); assertTrue(new AlluxioURI("file://localhost/a").isAbsolute()); assertFalse(new AlluxioURI("//localhost/a").isAbsolute()); assertFalse(new AlluxioURI("//localhost/").isAbsolute()); assertFalse(new AlluxioURI("...
@Override @Nullable public IdentifiedDataSerializable create(int typeId) { if (typeId >= 0 && typeId < len) { Supplier<IdentifiedDataSerializable> factory = constructors[typeId]; return factory != null ? factory.get() : null; } return null; }
@Test public void testCreate() { Supplier<IdentifiedDataSerializable>[] constructorFunctions = new Supplier[1]; constructorFunctions[0] = () -> new SampleIdentifiedDataSerializable(); ArrayDataSerializableFactory factory = new ArrayDataSerializableFactory(constructorFunctions); as...
public void setSchema(Schema schema) { this.userDefinedSchema = schema; }
@Test void testGenericRecord() throws IOException { final Path outputPath = new Path(File.createTempFile("avro-output-file", "generic.avro").getAbsolutePath()); final AvroOutputFormat<GenericRecord> outputFormat = new AvroOutputFormat<>(outputPath, GenericRecord.class...
public boolean fileIsInAllowedPath(Path path) { if (allowedPaths.isEmpty()) { return true; } final Path realFilePath = resolveRealPath(path); if (realFilePath == null) { return false; } for (Path allowedPath : allowedPaths) { final Pat...
@Test public void noPathsFileLocationOkNoChecksRequired() throws IOException { pathChecker = new AllowedAuxiliaryPathChecker(new TreeSet<>(Collections.emptySet())); assertTrue(pathChecker.fileIsInAllowedPath(permittedTempDir.newFile(FILE).toPath())); }
@SuppressWarnings("unchecked") public <T> T convert(DocString docString, Type targetType) { if (DocString.class.equals(targetType)) { return (T) docString; } List<DocStringType> docStringTypes = docStringTypeRegistry.lookup(docString.getContentType(), targetType); if (d...
@Test void throws_if_converter_type_conflicts_with_type() { registry.defineDocStringType(jsonNodeForJson); registry.defineDocStringType(stringForText); DocString docString = DocString.create("hello world", "json"); CucumberDocStringException exception = assertThrows( Cucu...
@Override public <T> T clone(T object) { if (object instanceof String) { return object; } else if (object instanceof Collection) { Object firstElement = findFirstNonNullElement((Collection) object); if (firstElement != null && !(firstElement instanceof Serializabl...
@Test public void should_clone_collection_of_serializable_object() { List<SerializableObject> original = new ArrayList<>(); original.add(new SerializableObject("value")); List<SerializableObject> cloned = serializer.clone(original); assertEquals(original, cloned); assertNotSa...
public static String evaluate(final co.elastic.logstash.api.Event event, final String template) throws JsonProcessingException { if (event instanceof Event) { return evaluate((Event) event, template); } else { throw new IllegalStateException("Unknown event concrete class:...
@Test public void TestValueIsArray() throws IOException { ArrayList<String> l = new ArrayList<>(); l.add("Hello"); l.add("world"); Event event = getTestEvent(); event.setField("message", l); String path = "%{message}"; assertEquals("Hello,world", StringInter...
@Override public Name getLocation(final Path file) throws BackgroundException { final Path container = containerService.getContainer(file); if(container.isRoot()) { return unknown; } return new B2BucketTypeName(BucketType.valueOf(new B2AttributesFinderFeature(session, fil...
@Test public void testAllPrivate() throws Exception { final B2VersionIdProvider fileid = new B2VersionIdProvider(session); final Path bucket = new B2DirectoryFeature(session, fileid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), ...
@Override public String named() { return PluginEnum.REQUEST.getName(); }
@Test public void tesNamed() { assertEquals(this.requestPlugin.named(), PluginEnum.REQUEST.getName()); }
@Override public boolean support(AnnotatedElement annotatedEle) { return annotatedEle instanceof Field; }
@Test public void getAnnotationsTest() { AnnotationScanner scanner = new FieldAnnotationScanner(); Field field = ReflectUtil.getField(Example.class, "id"); assertNotNull(field); assertTrue(scanner.support(field)); List<Annotation> annotations = scanner.getAnnotations(field); assertEquals(1, annotations.siz...
@Override public File exportDumpOf(ProjectDescriptor descriptor) { String fileName = slugify(descriptor.getKey()) + DUMP_FILE_EXTENSION; return new File(exportDir, fileName); }
@Test public void exportDumpOf_is_located_in_governance_project_dump_out() { assertThat(underTest.exportDumpOf(projectDescriptor)).isEqualTo(new File(dataDir, "governance/project_dumps/export/project_key.zip")); }
Map<String, String> describeNetworkInterfaces(List<String> privateAddresses, AwsCredentials credentials) { if (privateAddresses.isEmpty()) { return Collections.emptyMap(); } try { Map<String, String> attributes = createAttributesDescribeNetworkInterfaces(privateAddresses)...
@Test public void describeNetworkInterfacesNoPublicIp() { // given List<String> privateAddresses = asList("10.0.1.207", "10.0.1.82"); String requestUrl = "/?Action=DescribeNetworkInterfaces" + "&Filter.1.Name=addresses.private-ip-address" + "&Filter.1.Value.1=10.0.1....
@Override public int compare(Optional<String> a, Optional<String> b) { if (!a.isPresent()) { if (!b.isPresent()) { return 0; } else { return -1; } } else if (!b.isPresent()) { return 1; } return a.get().c...
@Test public void testComparisons() { assertEquals(0, INSTANCE.compare(Optional.of("foo"), Optional.of("foo"))); assertEquals(-1, INSTANCE.compare(Optional.of("a"), Optional.of("b"))); assertEquals(1, INSTANCE.compare(Optional.of("b"), Optional.of("a"))); assertEquals(-1, INSTANCE.co...
@Config("function-implementation-type") public SqlFunctionLanguageConfig setFunctionImplementationType(String implementationType) { this.functionImplementationType = FunctionImplementationType.valueOf(implementationType.toUpperCase()); return this; }
@Test public void testCPPType() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("function-implementation-type", "CPP") .build(); SqlFunctionLanguageConfig expected = new SqlFunctionLanguageConfig() .setFunctionImp...
@Override @CheckForNull public EmailMessage format(Notification notification) { if (!BuiltInQPChangeNotification.TYPE.equals(notification.getType())) { return null; } BuiltInQPChangeNotificationBuilder profilesNotification = parse(notification); StringBuilder message = new StringBuilder("The ...
@Test public void notification_contains_from_and_to_date() { String profileName = newProfileName(); String languageKey = newLanguageKey(); String languageName = newLanguageName(); long startDate = 1_000_000_000_000L; long endDate = startDate + 1_100_000_000_000L; BuiltInQPChangeNotificationBui...
public static Slice encodeScaledValue(BigDecimal value, int scale) { checkArgument(scale >= 0); return encodeScaledValue(value.setScale(scale, UNNECESSARY)); }
@Test public void testEncodeScaledValue() { assertEquals(encodeScaledValue(new BigDecimal("2.00"), 2), sliceFromBytes(200, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); assertEquals(encodeScaledValue(new BigDecimal("2.13"), 2), sliceFromBytes(213, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); ...
@Override public AppResponse process(Flow flow, AppSessionRequest request) { Map<String, Object> result = new HashMap<>(digidClient.getAccountRequestGbaStatus(appSession.getRegistrationId())); if (result.get(lowerUnderscore(STATUS)).equals("OK")) { return new OkResponse(); } els...
@Test void processOKTest() { when(digidClientMock.getAccountRequestGbaStatus(1337L)).thenReturn(Map.of( lowerUnderscore(STATUS), "OK" )); AppResponse appResponse = pollBrp.process(flowMock, null); assertTrue(appResponse instanceof OkResponse); assertEquals("OK",...
@Override public String addResource(String key, String fileName) { String interned = intern(key); synchronized (interned) { SharedCacheResource resource = cachedResources.get(interned); if (resource == null) { resource = new SharedCacheResource(fileName); cachedResources.put(intern...
@Test void testAddResourceConcurrency() throws Exception { startEmptyStore(); final String key = "key1"; int count = 5; ExecutorService exec = HadoopExecutors.newFixedThreadPool(count); List<Future<String>> futures = new ArrayList<Future<String>>(count); final CountDownLatch start = new CountD...
public static void toast(Context context, @StringRes int message) { // this is a static method so it is easier to call, // as the context checking and casting is done for you if (context == null) return; if (!(context instanceof Application)) { context = context.getApplicationContext(); } ...
@Test public void testToastWithString() { AppConfig.toast(ApplicationProvider.getApplicationContext(), "Hello world"); shadowOf(getMainLooper()).idle(); await().atMost(5, TimeUnit.SECONDS).until(() -> ShadowToast.getLatestToast() != null); assertEquals("Hello world", ShadowToast.getTextOfLatestToast()...