focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@JsonCreator public static TypeSignature parseTypeSignature(String signature) { return parseTypeSignature(signature, new HashSet<>()); }
@Test public void parseRowSignature() { // row signature with named fields assertRowSignature( "row(a bigint,b varchar)", rowSignature(namedParameter("a", false, signature("bigint")), namedParameter("b", false, varchar()))); assertRowSignature( ...
public int format(String... args) throws UsageException { CommandLineOptions parameters = processArgs(args); if (parameters.version()) { errWriter.println(versionString()); return 0; } if (parameters.help()) { throw new UsageException(); } JavaFormatterOptions options = ...
@Test public void optimizeImportsDoesNotLeaveEmptyLines() throws Exception { String[] input = { "package abc;", "", "import java.util.LinkedList;", "import java.util.List;", "import java.util.ArrayList;", "", "import static java.nio.charset.StandardCharsets.UTF_8;", ...
public String stringify(boolean value) { throw new UnsupportedOperationException( "stringify(boolean) was called on a non-boolean stringifier: " + toString()); }
@Test public void testTimestampMicrosStringifier() { for (PrimitiveStringifier stringifier : asList(TIMESTAMP_MICROS_STRINGIFIER, TIMESTAMP_MICROS_UTC_STRINGIFIER)) { String timezoneAmendment = (stringifier == TIMESTAMP_MICROS_STRINGIFIER ? "" : "+0000"); assertEquals(withZoneString("1970-01-...
public static ConfigurableResource parseResourceConfigValue(String value) throws AllocationConfigurationException { return parseResourceConfigValue(value, Long.MAX_VALUE); }
@Test public void testParseNewStyleResourceWithPercentagesVcoresNegativeWithMoreSpaces() throws Exception { expectNegativePercentageNewStyle(); parseResourceConfigValue("vcores = -75%, memory-mb = 40%"); }
public static String parseToString(Map<String, String> attributes) { if (attributes == null || attributes.size() == 0) { return ""; } List<String> kvs = new ArrayList<>(); for (Map.Entry<String, String> entry : attributes.entrySet()) { String value = entry.getVa...
@Test public void parseToString_ValidAttributes_ReturnsExpectedString() { Map<String, String> attributes = new HashMap<>(); attributes.put("key1", "value1"); attributes.put("key2", "value2"); attributes.put("key3", ""); String result = AttributeParser.parseToString(attribute...
@Override public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) { ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new); String tableNameSuffix = String.valueOf(doSharding(parseDa...
@Test void assertRangeDoShardingWithGreaterTenTables() { Properties props = PropertiesBuilder.build( new Property("datetime-lower", "2020-01-01 00:00:00"), new Property("datetime-upper", "2020-01-01 00:00:30"), new Property("sharding-seconds", "1")); AutoIntervalShardingAlgorithm sha...
public static List<Base64String> wrapList(final List<String> base64Strings) { return base64Strings.stream().map(Base64String::wrap).collect(Collectors.toList()); }
@Test public void testWrapList() { assertEquals(BASE64_WRAPPED_LIST, Base64String.wrapList(BASE64_LIST)); assertEquals(BASE64_4_WRAPPED_LIST, Base64String.wrapList(BASE64_4_LIST)); assertEquals(BASE64_4_WRAPPED_LIST, Base64String.wrapList(BASE64_4, BASE64_4)); }
protected List<String> filterPartitionPaths(List<String> partitionPaths) { List<String> filteredPartitions = ClusteringPlanPartitionFilter.filter(partitionPaths, getWriteConfig()); LOG.debug("Filtered to the following partitions: " + filteredPartitions); return filteredPartitions; }
@Test public void testFilterPartitionPaths() { PartitionAwareClusteringPlanStrategy strategyTestRegexPattern = new DummyPartitionAwareClusteringPlanStrategy(table, context, hoodieWriteConfig); ArrayList<String> fakeTimeBasedPartitionsPath = new ArrayList<>(); fakeTimeBasedPartitionsPath.add("20210718"); ...
@Override public Collection<Service> getAllSubscribeService() { return subscribers.keySet(); }
@Test void getAllSubscribeService() { Collection<Service> allSubscribeService = abstractClient.getAllSubscribeService(); assertNotNull(allSubscribeService); }
@Override public void commitJob(JobContext originalContext) throws IOException { JobContext jobContext = TezUtil.enrichContextWithVertexId(originalContext); JobConf jobConf = jobContext.getJobConf(); long startTime = System.currentTimeMillis(); LOG.info("Committing job {} has started", jobContext.get...
@Test public void testSuccessfulUnpartitionedWrite() throws IOException { HiveIcebergOutputCommitter committer = new HiveIcebergOutputCommitter(); Table table = table(temp.toFile().getPath(), false); JobConf conf = jobConf(table, 1); List<Record> expected = writeRecords(table.name(), 1, 0, true, fals...
public static ContainerStatus createPreemptedContainerStatus( ContainerId containerId, String diagnostics) { return createAbnormalContainerStatus(containerId, ContainerExitStatus.PREEMPTED, diagnostics); }
@Test public void testCreatePreemptedContainerStatus() { ContainerStatus cd = SchedulerUtils.createPreemptedContainerStatus( ContainerId.newContainerId(ApplicationAttemptId.newInstance( ApplicationId.newInstance(System.currentTimeMillis(), 1), 1), 1), "x"); Assert.assertEquals(...
@Override public boolean add(double score, V object) { return get(addAsync(score, object)); }
@Test public void testIteratorSequence() { RScoredSortedSet<Integer> set = redisson.getScoredSortedSet("simple"); for (int i = 0; i < 1000; i++) { set.add(i, Integer.valueOf(i)); } Set<Integer> setCopy = new HashSet<>(); for (int i = 0; i < 1000; i++) { ...
@Override public DescribeUserScramCredentialsResult describeUserScramCredentials(List<String> users, DescribeUserScramCredentialsOptions options) { final KafkaFutureImpl<DescribeUserScramCredentialsResponseData> dataFuture = new KafkaFutureImpl<>(); final long now = time.milliseconds(); Call...
@Test public void testDescribeUserScramCredentials() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { env.kafkaClient().setNodeApiVersions(NodeApiVersions.create()); final String user0Name = "user0"; final ScramMechanism user0ScramMechanism0 = Scra...
@Override public void putAll(Map<? extends K, ? extends V> m) { checkNotNull(m, "The passed in map cannot be null."); m.forEach((k, v) -> items.put(serializer.encode(k), serializer.encode(v))); }
@Test public void testPutAll() throws Exception { //Tests adding of an outside map Map<Integer, Integer> testMap = Maps.newHashMap(); fillMap(10); map.putAll(testMap); for (int i = 0; i < 10; i++) { assertTrue("The map should contain the current 'i' value.", map.c...
@Override public void onOpened() { digestNotification(); }
@Test public void onOpened_appVisible_dontSetInitialNotification() throws Exception { setUpForegroundApp(); Activity currentActivity = mock(Activity.class); when(mReactContext.getCurrentActivity()).thenReturn(currentActivity); final PushNotification uut = createUUT(); uut.on...
@Override public void fire(final Connection connection, final Object[] oldRow, final Object[] newRow) throws SQLException { try (PreparedStatement statement = connection.prepareStatement( "INSERT IGNORE INTO PLUGIN_HANDLE (`ID`,`PLUGIN_ID`,`FIELD`,`LABEL`,`DATA_TYPE`,`TYPE`,`SORT`,`EXT_OBJ`)...
@Test public void testPluginHandleH2Trigger() throws SQLException { final PluginHandleH2Trigger pluginHandleH2Trigger = new PluginHandleH2Trigger(); final Connection connection = mock(Connection.class); when(connection.prepareStatement(anyString())).thenReturn(mock(PreparedStatement.class));...
synchronized boolean processDeregister(FunctionMetaData deregisterRequestFs) throws IllegalArgumentException { String functionName = deregisterRequestFs.getFunctionDetails().getName(); String tenant = deregisterRequestFs.getFunctionDetails().getTenant(); String namespace = deregisterRequestFs.ge...
@Test public void processDeregister() throws PulsarClientException { SchedulerManager schedulerManager = mock(SchedulerManager.class); WorkerConfig workerConfig = new WorkerConfig(); workerConfig.setWorkerId("worker-1"); FunctionMetaDataManager functionMetaDataManager = spy( ...
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) { ProjectMeasuresQuery query = new ProjectMeasuresQuery(); Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids); criteria.forEach(criterion -> processCriterion(criterion, query));...
@Test public void fail_to_create_query_having_q_with_no_value() { assertThatThrownBy(() -> { newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("query").setOperator(EQ).build()), emptySet()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Query is invalid...
@Udf public <T extends Comparable<? super T>> T arrayMin(@UdfParameter( description = "Array of values from which to find the minimum") final List<T> input) { if (input == null) { return null; } T candidate = null; for (T thisVal : input) { if (thisVal != null) { if (candida...
@Test public void shouldFindStringMin() { final List<String> input = Arrays.asList("foo", "food", "bar"); assertThat(udf.arrayMin(input), is("bar")); }
@Override // Exposes internal mutable reference by design - Spotbugs is right to warn that this is dangerous public synchronized byte[] toByteArray() { // Note: count == buf.length is not a correct criteria to "return buf;", because the internal // buf may be reused after reset(). if (!isFallback && cou...
@Test public void testWriteSingleArray() throws IOException { writeToBoth(TEST_DATA); assertStreamContentsEquals(stream, exposedStream); assertNotSame(TEST_DATA, exposedStream.toByteArray()); }
@SuppressWarnings("unchecked") @Override public boolean setFlushListener(final CacheFlushListener<K, V> listener, final boolean sendOldValues) { final KeyValueStore<Bytes, byte[]> wrapped = wrapped(); if (wrapped instanceof CachedStateStore) { retu...
@Test public void shouldNotSetFlushListenerOnWrappedNoneCachingStore() { setUpWithoutContext(); assertFalse(metered.setFlushListener(null, false)); }
@Override public Collection<SQLToken> generateSQLTokens(final InsertStatementContext insertStatementContext) { InsertStatement insertStatement = insertStatementContext.getSqlStatement(); Preconditions.checkState(insertStatement.getOnDuplicateKeyColumns().isPresent()); Collection<ColumnAssign...
@Test void assertGenerateSQLTokens() { InsertStatementContext insertStatementContext = mock(InsertStatementContext.class, RETURNS_DEEP_STUBS); when(insertStatementContext.getTablesContext().getSchemaName()).thenReturn(Optional.of("db_test")); MySQLInsertStatement insertStatement = mock(MySQL...
@Nullable static String channelName(@Nullable Destination destination) { if (destination == null) return null; boolean isQueue = isQueue(destination); try { if (isQueue) { return ((Queue) destination).getQueueName(); } else { return ((Topic) destination).getTopicName(); } ...
@Test void channelName_queueAndTopic_topicOnNoQueueName() throws JMSException { QueueAndTopic destination = mock(QueueAndTopic.class); when(destination.getTopicName()).thenReturn("topic-foo"); assertThat(MessageParser.channelName(destination)) .isEqualTo("topic-foo"); }
public void resolveDcMetadata(SamlRequest samlRequest) throws DienstencatalogusException { final DcMetadataResponse metadataFromDc = dienstencatalogusClient.retrieveMetadataFromDc(samlRequest); if (samlRequest instanceof AuthenticationRequest) { dcMetadataResponseMapper.dcMetadataToAuthent...
@Test public void resolveDcMetadataNoLegacyWebserviceIdTest() throws DienstencatalogusException { DcMetadataResponse dcMetadataResponse = dcClientStubGetMetadata(stubsCaMetadataFile, null); when(dienstencatalogusClientMock.retrieveMetadataFromDc(any(SamlRequest.class))).thenReturn(dcMetadataResponse...
public void clearRange(Instant minTimestamp, Instant limitTimestamp) { checkState( !isClosed, "OrderedList user state is no longer usable because it is closed for %s", requestTemplate.getStateKey()); // Remove items (in a collection) in the specific range from pendingAdds. // The ol...
@Test public void testClearRange() throws Exception { FakeBeamFnStateClient fakeClient = new FakeBeamFnStateClient( timestampedValueCoder, ImmutableMap.of( createOrderedListStateKey("A", 1), asList(A1, B1), createOrderedListStateKey("...
@Override public boolean getBooleanValueOfVariable( String variableName, boolean defaultValue ) { if ( !Utils.isEmpty( variableName ) ) { String value = environmentSubstitute( variableName ); if ( !Utils.isEmpty( value ) ) { return ValueMetaString.convertStringToBoolean( value ); } }...
@Test public void testGetBooleanValueOfVariable() { assertFalse( meta.getBooleanValueOfVariable( null, false ) ); assertTrue( meta.getBooleanValueOfVariable( "", true ) ); assertTrue( meta.getBooleanValueOfVariable( "true", true ) ); assertFalse( meta.getBooleanValueOfVariable( "${myVar}", false ) ); ...
public static byte[] plus(byte[] in, int add) { if (in.length == 0) return in; final byte[] out = in.clone(); add(out, add); return out; }
@Test public void plusShouldCarry() { assertArrayEquals(new byte[] { 0, 0, 0}, ByteArrayUtils.plus(new byte[] { -1, -1, -1}, 1)); }
@Override public boolean databaseExists(String databaseName) throws CatalogException { if (catalog instanceof SupportsNamespaces) { boolean exists = ((SupportsNamespaces) catalog).namespaceExists(Namespace.of(databaseName)); log.info("Database {} existence status:...
@Test @Order(3) void databaseExists() { Assertions.assertTrue(icebergCatalog.databaseExists(databaseName)); Assertions.assertFalse(icebergCatalog.databaseExists("sssss")); }
@ScalarOperator(NOT_EQUAL) @SqlType(StandardTypes.BOOLEAN) public static boolean notEqual(@SqlType("unknown") boolean left, @SqlType("unknown") boolean right) { throw new AssertionError("value of unknown type should all be NULL"); }
@Test public void testNotEqual() { assertFunction("NULL <> NULL", BOOLEAN, null); }
public double getRelevance() { return relevance; }
@Test void testNaN2negativeInfinity() { LeanHit nan = new LeanHit(gidA, 0, 0, Double.NaN); assertFalse(Double.isNaN(nan.getRelevance())); assertTrue(Double.isInfinite(nan.getRelevance())); assertEquals(Double.NEGATIVE_INFINITY, nan.getRelevance(), DELTA); }
static void cleanStackTrace(Throwable throwable) { new StackTraceCleaner(throwable).clean(Sets.<Throwable>newIdentityHashSet()); }
@Test public void collapseStreaks() { Throwable throwable = createThrowableWithStackTrace( "com.example.MyTest", "junit.Foo", "org.junit.Bar", "com.google.testing.junit.Car", "com.google.testing.testsize.Dar", "com.google.testing.util...
@Override public int isNullable(final int column) { Preconditions.checkArgument(1 == column); return columnNoNulls; }
@Test void assertIsNullable() throws SQLException { assertThat(actualMetaData.isNullable(1), is(ResultSetMetaData.columnNoNulls)); }
@Override public Integer getLocalValue() { return this.min; }
@Test void testGet() { IntMinimum min = new IntMinimum(); assertThat(min.getLocalValue().intValue()).isEqualTo(Integer.MAX_VALUE); }
public void writeTrailingBytes(byte[] value) { if ((value == null) || (value.length == 0)) { throw new IllegalArgumentException("Value cannot be null or have 0 elements"); } encodedArrays.add(value); }
@Test public void testWriteTrailingBytes() { byte[] escapeChars = new byte[] { OrderedCode.ESCAPE1, OrderedCode.NULL_CHARACTER, OrderedCode.SEPARATOR, OrderedCode.ESCAPE2, OrderedCode.INFINITY, OrderedCode.FF_CHARACTER }; byte[] anoth...
public static List<ReporterSetup> fromConfiguration( final Configuration configuration, @Nullable final PluginManager pluginManager) { String includedReportersString = configuration.get(MetricOptions.REPORTERS_LIST, ""); Set<String> namedReporters = findEnabledTraceReporters...
@Test void testReporterArgumentForwarding() { final Configuration config = new Configuration(); configureReporter1(config); final List<ReporterSetup> reporterSetups = ReporterSetup.fromConfiguration(config, null); assertThat(reporterSetups).hasSize(1); final ReporterSetup...
@Override public void startInfrastructure(boolean shouldPoll) { removeBundleDirectory(); goPluginOSGiFramework.start(); addPluginChangeListener(new PluginChangeListener() { @Override public void pluginLoaded(GoPluginDescriptor pluginDescriptor) { } ...
@Test void shouldAddPluginChangeListener() { DefaultPluginManager pluginManager = new DefaultPluginManager(monitor, registry, mock(GoPluginOSGiFramework.class), jarChangeListener, pluginRequestProcessorRegistry, systemEnvironment, pluginLoader); pluginManager.startInfrastructure(true); InOr...
public final boolean isRewardHalvingPoint(final int previousHeight) { return ((previousHeight + 1) % REWARD_HALVING_INTERVAL) == 0; }
@Test public void isRewardHalvingPoint() { assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(209999)); assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(419999)); assertFalse(BITCOIN_PARAMS.isRewardHalvingPoint(629998)); assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(629999)); as...
@Override public Ability processAbility(Ability ab) { // Should never hit this throw new RuntimeException("Should not process any ability in a vanilla toggle"); }
@Test public void throwsOnProcessingAbility() { Assertions.assertThrows(RuntimeException.class, () -> toggle.processAbility(defaultAbs.claimCreator())); }
public DnsName getHost() { return host; }
@Test public void setFqdn() { DummyConnectionConfiguration.Builder builder = newUnitTestBuilder(); final String fqdn = "foo.example.org"; builder.setHost(fqdn); DummyConnectionConfiguration connectionConfiguration = builder.build(); assertEquals(fqdn, connectionConfiguratio...
@Override public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) { if (readerWay.hasTag("hazmat", "no")) hazEnc.setEnum(false, edgeId, edgeIntAccess, Hazmat.NO); }
@Test public void testNoNPE() { ReaderWay readerWay = new ReaderWay(1); EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1); int edgeId = 0; parser.handleWayTags(edgeId, edgeIntAccess, readerWay, relFlags); assertEquals(Hazmat.YES, hazEnc.getEnum(false, edgeId, edgeIntAcc...
@SuppressWarnings("rawtypes") @Override public Collection<String> doSharding(final Collection<String> availableTargetNames, final Collection<ShardingConditionValue> shardingConditionValues, final DataNodeInfo dataNodeInfo, final ConfigurationProperties props) { S...
@Test void assertDoShardingForListSharding() { Collection<String> actualListSharding = standardShardingStrategy.doSharding(targets, Collections.singletonList( new ListShardingConditionValue<>("column", "logicTable", Collections.singletonList(1))), dataNodeSegment, new ConfigurationProperties...
@GET @Timed @ApiOperation(value = "Get a list of all index sets") @ApiResponses(value = { @ApiResponse(code = 403, message = "Unauthorized"), }) public IndexSetResponse list(@ApiParam(name = "skip", value = "The number of elements to skip (offset).", required = true) ...
@Test public void list0() { when(indexSetService.findAll()).thenReturn(Collections.emptyList()); final IndexSetResponse list = indexSetsResource.list(0, 0, false); verify(indexSetService, times(1)).findAll(); verify(indexSetService, times(1)).getDefault(); verifyNoMoreInter...
@GET @Path("stats") @Timed @ApiOperation(value = "Get stats of all index sets") @ApiResponses(value = { @ApiResponse(code = 403, message = "Unauthorized"), }) public IndexSetStats globalStats() { checkPermission(RestPermissions.INDEXSETS_READ); return indices.getIndex...
@Test public void globalStatsDenied() { notPermitted(); expectedException.expect(ForbiddenException.class); expectedException.expectMessage("Not authorized"); try { indexSetsResource.globalStats(); } finally { verifyNoMoreInteractions(indexSetService...
@Override public void importData(JsonReader reader) throws IOException { logger.info("Reading configuration for 1.0"); // this *HAS* to start as an object reader.beginObject(); while (reader.hasNext()) { JsonToken tok = reader.peek(); switch (tok) { case NAME: String name = reader.nextName();...
@Test public void testImportGrants() throws IOException, ParseException { Date creationDate1 = formatter.parse("2014-09-10T22:49:44.090+00:00", Locale.ENGLISH); Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+00:00", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity....
@Override public String toString() { return columns.isEmpty() ? "" : "(" + String.join(", ", columns) + ")"; }
@Test void assertToStringWithEmptyColumn() { assertThat(new UseDefaultInsertColumnsToken(0, Collections.emptyList()).toString(), is("")); }
public static Expression resolve(final Expression expression, final SqlType sqlType) { if (sqlType instanceof SqlDecimal) { return resolveToDecimal(expression, (SqlDecimal)sqlType); } return expression; }
@Test public void shouldNotResolveNonDecimalTarget() { // When final Expression expression = ImplicitlyCastResolver.resolve(new IntegerLiteral(5), SqlTypes.STRING); // Then assertThat(expression, instanceOf(IntegerLiteral.class)); assertThat(((IntegerLiteral)expression).getValue(), is(5))...
@Override public Statistics getTableStatistics(OptimizerContext session, Table table, Map<ColumnRefOperator, Column> columns, List<PartitionKey> partitionKeys, ...
@Test public void testGetTableStatistics() { IcebergHiveCatalog icebergHiveCatalog = new IcebergHiveCatalog(CATALOG_NAME, new Configuration(), DEFAULT_CONFIG); IcebergMetadata metadata = new IcebergMetadata(CATALOG_NAME, HDFS_ENVIRONMENT, icebergHiveCatalog, Executors.newSingleThrea...
public Optional<UfsStatus[]> listFromUfs(String path, boolean isRecursive) throws IOException { ListOptions ufsListOptions = ListOptions.defaults().setRecursive(isRecursive); UnderFileSystem ufs = getUfsInstance(path); try { UfsStatus[] listResults = ufs.listStatus(path, ufsListOptions); i...
@Test public void listFromUfsGetWhenGetSuccess() throws IOException { UnderFileSystem system = mock(UnderFileSystem.class); UfsStatus fakeStatus = mock(UfsStatus.class); when(system.listStatus(anyString())).thenReturn(null); when(system.getStatus(anyString())).thenReturn(fakeStatus); doReturn(syst...
@Override public String convertToDatabaseColumn(MonetaryAmount amount) { return amount == null ? null : String.format("%s %s", amount.getCurrency().toString(), amount.getNumber().toString()); }
@Test void doesNotRoundValues() { assertThat(converter.convertToDatabaseColumn(Money.of(1.23456, "EUR"))).isEqualTo("EUR 1.23456"); }
public static void checkArgument(boolean isValid, String message) throws IllegalArgumentException { if (!isValid) { throw new IllegalArgumentException(message); } }
@Test public void testCheckArgumentWithThreeParams() { try { Preconditions.checkArgument(true, "Test message %s %s %s", 12, null, "column"); } catch (IllegalArgumentException e) { Assert.fail("Should not throw exception when isValid is true"); } try { Preconditions.checkArgument(fal...
protected final void setAccessExpireTime(K key, Expirable<?> expirable, long currentTimeMS) { try { Duration duration = expiry.getExpiryForAccess(); if (duration == null) { return; } else if (duration.isZero()) { expirable.setExpireTimeMS(0L); } else if (duration.isEternal())...
@Test public void setAccessExpireTime_exception() { when(expiry.getExpiryForAccess()).thenThrow(IllegalStateException.class); var expirable = new Expirable<Integer>(KEY_1, 0); jcache.setAccessExpireTime(KEY_1, expirable, 0); assertThat(expirable.getExpireTimeMS()).isEqualTo(0); }
DescriptorDigest getDigestFromFilename(Path layerFile) throws CacheCorruptedException { try { String hash = layerFile.getFileName().toString(); return DescriptorDigest.fromHash(hash); } catch (DigestException | IndexOutOfBoundsException ex) { throw new CacheCorruptedException( cache...
@Test public void testGetDiffId() throws DigestException, CacheCorruptedException { Assert.assertEquals( DescriptorDigest.fromHash( "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), TEST_CACHE_STORAGE_FILES.getDigestFromFilename( Paths.get( ...
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldNotIncludeBadValueInExceptionAsThatWouldBeASecurityIssue() { // Given: final KsqlJsonDeserializer<Long> deserializer = givenDeserializerForSchema(Schema.OPTIONAL_INT64_SCHEMA, Long.class); final byte[] bytes = "\"personal info: do not log me\"".getBytes(StandardCharsets.U...
public static <T> PCollections<T> pCollections() { return new PCollections<>(); }
@Test @Category(ValidatesRunner.class) public void testFlattenPCollectionsSingletonList() { PCollection<String> input = p.apply(Create.of(LINES)); PCollection<String> output = PCollectionList.of(input).apply(Flatten.pCollections()); assertThat(output, not(equalTo(input))); PAssert.that(output).con...
public static Class<?> getGenericClass(Class<?> cls) { return getGenericClass(cls, 0); }
@Test void testGetGenericClassWithIndex() { assertThat(ReflectUtils.getGenericClass(Foo1.class, 0), sameInstance(String.class)); assertThat(ReflectUtils.getGenericClass(Foo1.class, 1), sameInstance(Integer.class)); assertThat(ReflectUtils.getGenericClass(Foo2.class, 0), sameInstance(List.cla...
public WriteResult<T, K> save(T object) { return save(object, null); }
@Test void save() { final var collection = jacksonCollection("simple", Simple.class); final var foo = new Simple("000000000000000000000001", "foo"); final var saveFooResult = collection.save(foo); assertThat(saveFooResult.getSavedObject()).isEqualTo(foo); assertThat(collect...
int decreaseAndGet(final WorkerResourceSpec workerResourceSpec) { final Integer newValue = workerNums.compute( Preconditions.checkNotNull(workerResourceSpec), (ignored, num) -> { Preconditions.checkState( ...
@Test void testWorkerCounterDecreaseOnZero() { final WorkerResourceSpec spec = new WorkerResourceSpec.Builder().build(); final WorkerCounter counter = new WorkerCounter(); assertThatThrownBy(() -> counter.decreaseAndGet(spec)) .isInstanceOf(IllegalStateException.class); }
@Override protected void validateDataImpl(TenantId tenantId, DeviceProfile deviceProfile) { validateString("Device profile name", deviceProfile.getName()); if (deviceProfile.getType() == null) { throw new DataValidationException("Device profile type should be specified!"); } ...
@Test void testValidateNameInvocation() { DeviceProfile deviceProfile = new DeviceProfile(); deviceProfile.setName("default"); deviceProfile.setType(DeviceProfileType.DEFAULT); deviceProfile.setTransportType(DeviceTransportType.DEFAULT); DeviceProfileData data = new DevicePro...
@Override public URI uploadSegment(File segmentFile, LLCSegmentName segmentName) { return uploadSegment(segmentFile, segmentName, _timeoutInMs); }
@Test public void testNoSegmentStoreConfigured() { SegmentUploader segmentUploader = new PinotFSSegmentUploader("", TIMEOUT_IN_MS, _serverMetrics); URI segmentURI = segmentUploader.uploadSegment(_file, _llcSegmentName); Assert.assertNull(segmentURI); }
@Override public void deleteConfig(Long id) { // 校验配置存在 ConfigDO config = validateConfigExists(id); // 内置配置,不允许删除 if (ConfigTypeEnum.SYSTEM.getType().equals(config.getType())) { throw exception(CONFIG_CAN_NOT_DELETE_SYSTEM_TYPE); } // 删除 configMapp...
@Test public void testDeleteConfig_canNotDeleteSystemType() { // mock 数据 ConfigDO dbConfig = randomConfigDO(o -> { o.setType(ConfigTypeEnum.SYSTEM.getType()); // SYSTEM 不允许删除 }); configMapper.insert(dbConfig);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbConfig...
public static void start(IDetachedRunnable runnable, Object... args) { // Prepare child thread Thread shim = new ShimThread(runnable, args); shim.setDaemon(true); shim.start(); }
@Test public void testDetached() { final CountDownLatch stopped = new CountDownLatch(1); ZThread.start((args) -> { try (ZContext ctx = new ZContext()) { Socket push = ctx.createSocket(SocketType.PUSH); assertThat(push, notNullValue()); } ...
public static CharSequence escapeCsv(CharSequence value) { return escapeCsv(value, false); }
@Test public void escapeCsvWithMultipleLineFeedCharacter() { CharSequence value = "\n\n"; CharSequence expected = "\"\n\n\""; escapeCsv(value, expected); }
public String defaultRemoteUrl() { final String sanitizedUrl = sanitizeUrl(); try { URI uri = new URI(sanitizedUrl); if (uri.getUserInfo() != null) { uri = new URI(uri.getScheme(), removePassword(uri.getUserInfo()), uri.getHost(), uri.getPort(), uri.getPath(), uri...
@Test void shouldReturnAURLWhenPasswordIsNotSpecified() { assertThat(new HgUrlArgument("http://user@url##branch").defaultRemoteUrl(), is("http://user@url#branch")); }
public static void addHttp2ToHttpHeaders(int streamId, Http2Headers inputHeaders, FullHttpMessage destinationMessage, boolean addToTrailer) throws Http2Exception { addHttp2ToHttpHeaders(streamId, inputHeaders, addToTrailer ? destinationMessage.trailingHeaders() : destinationM...
@Test public void http2ToHttpHeaderTest() throws Exception { Http2Headers http2Headers = new DefaultHttp2Headers(); http2Headers.status("200"); http2Headers.path("/meow"); // HTTP/2 Header response should not contain 'path' in response. http2Headers.set("cat", "meow"); HttpH...
@Override public ExecutionResult toExecutionResult(String responseBody) { ExecutionResult executionResult = new ExecutionResult(); ArrayList<String> exceptions = new ArrayList<>(); try { Map result = (Map) GSON.fromJson(responseBody, Object.class); if (!(result.contai...
@Test public void shouldConstructExecutionResultFromFailureExecutionResponse() { GoPluginApiResponse response = mock(GoPluginApiResponse.class); when(response.responseBody()).thenReturn("{\"success\":false,\"message\":\"error1\"}"); ExecutionResult result = new JsonBasedTaskExtensionHandler...
@Override public Executor getExecutor(URL url) { String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME)); int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); int queues = url.getParameter(QUEUES_KEY, DEFAULT_Q...
@Test void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo://10.20.130.230:20880/context/path?" + THREAD_NAME_KEY + "=demo&" + CORE_THREADS_KEY + "=1&" + THREADS_KEY + "=2&" + QUEUES_KEY + "=0"); ThreadPool threadPool = n...
public static Map<TopicPartition, ListOffsetsResultInfo> fetchEndOffsets(final Collection<TopicPartition> partitions, final Admin adminClient) { if (partitions.isEmpty()) { return Collections.emptyMap(); } r...
@Test public void fetchEndOffsetsShouldRethrowRuntimeExceptionAsStreamsException() throws Exception { final Admin adminClient = mock(AdminClient.class); final ListOffsetsResult result = mock(ListOffsetsResult.class); @SuppressWarnings("unchecked") final KafkaFuture<Map<TopicPartition...
public static Event createProfile(String name, @Nullable String data, @Nullable String description) { return new Event(name, Category.PROFILE, data, description); }
@Test public void createProfile_fail_fast_null_check_on_null_name() { assertThatThrownBy(() -> Event.createProfile(null, SOME_DATA, SOME_DESCRIPTION)) .isInstanceOf(NullPointerException.class); }
@Override protected String getObjectDescription() { return "Artifact store"; }
@Test public void shouldReturnObjectDescription() { assertThat(new ArtifactStore().getObjectDescription(), is("Artifact store")); }
public SqlType getExpressionSqlType(final Expression expression) { return getExpressionSqlType(expression, Collections.emptyMap()); }
@Test public void shouldFailForCheckingComplexTypeEquality() { // Given: final Expression expression = new ComparisonExpression(Type.EQUAL, MAPCOL, ADDRESS); // When: final KsqlStatementException e = assertThrows( KsqlStatementException.class, () -> expressionTypeManager.getExpression...
public List<ServiceInstance> findAllInstancesInNotRunningState() { return jdbcRepository.getDslContextWrapper().transactionResult( configuration -> findAllInstancesInNotRunningState(configuration, false) ); }
@Test protected void shouldFindAllInstancesInNotRunningState() { // Given AbstractJdbcServiceInstanceRepositoryTest.Fixtures.all().forEach(repository::save); // When List<ServiceInstance> results = repository.findAllInstancesInNotRunningState(); // Then assertEquals...
@Override public Address getThisNodesAddress() { // no need to implement this for client part throw new UnsupportedOperationException(); }
@Test(expected = UnsupportedOperationException.class) public void testGetThisNodesAddress() { context.getThisNodesAddress(); }
@Override public CompressionOutputStream createOutputStream( OutputStream out ) throws IOException { return new NoneCompressionOutputStream( out, this ); }
@Test public void testCreateOutputStream() throws IOException { NoneCompressionProvider provider = (NoneCompressionProvider) factory.getCompressionProviderByName( PROVIDER_NAME ); ByteArrayOutputStream out = new ByteArrayOutputStream(); NoneCompressionOutputStream outStream = new NoneCompressionOutputStre...
@Override public T deserialize(final String topic, final byte[] bytes) { try { if (bytes == null) { return null; } // don't use the JsonSchemaConverter to read this data because // we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS, // which is not currently avail...
@Test public void shouldThrowIfCanNotCoerceToBigInt() { // Given: final KsqlJsonDeserializer<Long> deserializer = givenDeserializerForSchema(Schema.OPTIONAL_INT64_SCHEMA, Long.class); final byte[] bytes = serializeJson(BooleanNode.valueOf(true)); // When: final Exception e = assertThrow...
@Override public byte[] evaluateResponse(byte[] response) throws SaslException, SaslAuthenticationException { if (response.length == 1 && response[0] == OAuthBearerSaslClient.BYTE_CONTROL_A && errorMessage != null) { log.debug("Received %x01 response from client after it received our error"); ...
@Test public void authorizationIdEqualsAuthenticationId() throws Exception { byte[] nextChallenge = saslServer .evaluateResponse(clientInitialResponse(USER)); assertEquals(0, nextChallenge.length, "Next challenge is not empty"); }
public ConsumerGroup consumerGroup( String groupId, long committedOffset ) throws GroupIdNotFoundException { Group group = group(groupId, committedOffset); if (group.type() == CONSUMER) { return (ConsumerGroup) group; } else { // We don't support upgr...
@Test public void testJoiningConsumerGroupWithExistingStaticMemberAndNewSubscription() throws Exception { String groupId = "group-id"; Uuid fooTopicId = Uuid.randomUuid(); String fooTopicName = "foo"; Uuid barTopicId = Uuid.randomUuid(); String barTopicName = "bar"; U...
public static String getSimpleClassName(String qualifiedName) { if (null == qualifiedName) { return null; } int i = qualifiedName.lastIndexOf('.'); return i < 0 ? qualifiedName : qualifiedName.substring(i + 1); }
@Test void testGetSimpleClassName() { Assertions.assertNull(ClassUtils.getSimpleClassName(null)); Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getName())); Assertions.assertEquals("Map", ClassUtils.getSimpleClassName(Map.class.getSimpleName())); }
public long getLong(String key, long _default) { Object object = map.get(key); return object instanceof Number ? ((Number) object).longValue() : _default; }
@Test public void numericPropertyCanBeRetrievedAsLong() { PMap subject = new PMap("foo=1234|bar=5678"); assertEquals(1234L, subject.getLong("foo", 0)); }
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) { return decoder.decodeFunctionResult(rawInput, outputParameters); }
@Test @SuppressWarnings("unchecked") public void testDecodeStaticArrayValue() { List<TypeReference<Type>> outputParameters = new ArrayList<>(1); outputParameters.add( (TypeReference) new TypeReference.StaticArrayTypeReference<StaticArray<Uint256>>(2) {}); ...
public int mul(int... nums) { LOGGER.info("Arithmetic mul {}", VERSION); return source.accumulateMul(nums); }
@Test void testMul() { assertEquals(0, arithmetic.mul(-1, 0, 1)); }
public static void load(Configuration conf, InputStream is) throws IOException { conf.addResource(is); }
@Test public void constructors() throws Exception { Configuration conf = new Configuration(false); assertEquals(conf.size(), 0); byte[] bytes = "<configuration><property><name>a</name><value>A</value></property></configuration>".getBytes(); InputStream is = new ByteArrayInputStream(bytes); conf =...
@Override public void apply(IntentOperationContext<FlowObjectiveIntent> intentOperationContext) { Objects.requireNonNull(intentOperationContext); Optional<IntentData> toUninstall = intentOperationContext.toUninstall(); Optional<IntentData> toInstall = intentOperationContext.toInstall(); ...
@Test public void testGroupAlreadyRemoved() { // group already removed intentInstallCoordinator = new TestIntentInstallCoordinator(); installer.intentInstallCoordinator = intentInstallCoordinator; errors = ImmutableList.of(GROUPMISSING); installer.flowObjectiveService = new T...
public static String extractAccountNameFromHostName(final String hostName) { if (hostName == null || hostName.isEmpty()) { return null; } if (!containsAbfsUrl(hostName)) { return null; } String[] splitByDot = hostName.split("\\."); if (splitByDot.length == 0) { return null; ...
@Test public void testExtractRawAccountName() throws Exception { Assert.assertEquals("abfs", UriUtils.extractAccountNameFromHostName("abfs.dfs.core.windows.net")); Assert.assertEquals("abfs", UriUtils.extractAccountNameFromHostName("abfs.dfs.preprod.core.windows.net")); Assert.assertEquals(null, UriUtils....
@Override public <V1, R> KTable<K, R> leftJoin(final KTable<K, V1> other, final ValueJoiner<? super V, ? super V1, ? extends R> joiner) { return leftJoin(other, joiner, NamedInternal.empty()); }
@Test public void shouldNotAllowNullOtherTableOnLeftJoin() { assertThrows(NullPointerException.class, () -> table.leftJoin(null, MockValueJoiner.TOSTRING_JOINER)); }
public static ContainerPort createContainerPort(String name, int port) { return new ContainerPortBuilder() .withName(name) .withProtocol("TCP") .withContainerPort(port) .build(); }
@Test public void testCreateContainerPort() { ContainerPort port = ContainerUtils.createContainerPort("my-port", 1874); assertThat(port.getName(), is("my-port")); assertThat(port.getContainerPort(), is(1874)); assertThat(port.getProtocol(), is("TCP")); }
@Subscribe public void inputUpdated(InputUpdated inputUpdatedEvent) { final String inputId = inputUpdatedEvent.id(); LOG.debug("Input updated: {}", inputId); final Input input; try { input = inputService.find(inputId); } catch (NotFoundException e) { L...
@Test public void inputUpdatedDoesNotStartLocalInputOnOtherNode() throws Exception { final String inputId = "input-id"; final Input input = mock(Input.class); @SuppressWarnings("unchecked") final IOState<MessageInput> inputState = mock(IOState.class); when(inputState.getState...
@Override public void onAddClassLoader(ModuleModel scopeModel, ClassLoader classLoader) { refreshClassLoader(classLoader); }
@Test void testSerializable2() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ModuleModel moduleModel = applicationModel.newModule(); SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(...
@Override public void initialize(ServerAbilities abilities) { abilities.getRemoteAbility().setSupportRemoteConnection(true); }
@Test void testInitialize() { RemoteAbilityInitializer initializer = new RemoteAbilityInitializer(); ServerAbilities serverAbilities = new ServerAbilities(); assertFalse(serverAbilities.getRemoteAbility().isSupportRemoteConnection()); initializer.initialize(serverAbilities); ...
public Matrix aat() { Matrix C = new Matrix(m, m); C.mm(NO_TRANSPOSE, this, TRANSPOSE, this); C.uplo(LOWER); return C; }
@Test public void testAAT() { System.out.println("AAT"); Matrix c = matrix.aat(); assertEquals(c.nrow(), 3); assertEquals(c.ncol(), 3); for (int i = 0; i < C.length; i++) { for (int j = 0; j < C[i].length; j++) { assertEquals(C[i][j], c.get(i, j), ...
@SuppressWarnings("unchecked") @Override public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) throws YarnException, IOException { NodeStatus remoteNodeStatus = request.getNodeStatus(); /** * Here is the node heartbeat sequence... * 1. Check if it's a valid (i.e. not excl...
@Test public void testGracefulDecommissionNoApp() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); writeToHostsFile(""); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("h...
public static <T> Supplier<T> recover(Supplier<T> supplier, Predicate<T> resultPredicate, UnaryOperator<T> resultHandler) { return () -> { T result = supplier.get(); if(resultPredicate.test(result)){ return resultHandler.apply(result); } re...
@Test(expected = RuntimeException.class) public void shouldRethrowException() { Supplier<String> supplier = () -> { throw new RuntimeException("BAM!"); }; Supplier<String> supplierWithRecovery = SupplierUtils.recover(supplier, (ex) -> { throw new RuntimeException(); ...
public static String getHostAddress() throws SocketException, UnknownHostException { boolean isIPv6Preferred = Boolean.parseBoolean(System.getProperty("java.net.preferIPv6Addresses")); DatagramSocket ds = new DatagramSocket(); try { ds.connect(isIPv6Preferred ? Inet6Address.getByName(DUMMY_OUT_I...
@Test(description = "Test getHostAddress with no preferIPv6Addresses in IPv4 only environment") public void testGetHostAddressIPv4Env() { InetAddress mockInetAddress = mock(InetAddress.class); when(mockInetAddress.isAnyLocalAddress()).thenReturn(false); when(mockInetAddress.getHostAddress()).thenReturn(LO...
public static String md5(String data) { return md5(data.getBytes()); }
@Test public void testMd5() throws Exception { String biezhiMD5 = "b3b71cd2fbee70ae501d024fe12a8fba"; Assert.assertEquals( biezhiMD5, EncryptKit.md5("biezhi") ); Assert.assertEquals( biezhiMD5, EncryptKit.md5("biezhi".ge...
public T findAndRemove(Bson filter) { return delegate.findOneAndDelete(filter); }
@Test void findAndRemove() { final var collection = jacksonCollection("simple", Simple.class); final var foo = new Simple("000000000000000000000001", "foo"); final var bar = new Simple("000000000000000000000002", "bar"); collection.insert(List.of(foo, bar)); assertThat(col...
public int charAt(int position) { if (position > this.length) return -1; // too long if (position < 0) return -1; // duh. ByteBuffer bb = (ByteBuffer)ByteBuffer.wrap(bytes).position(position); return bytesToCodePoint(bb.slice()); }
@Test public void testCharAt() { String line = "adsawseeeeegqewgasddga"; Text text = new Text(line); for (int i = 0; i < line.length(); i++) { assertTrue("testCharAt error1 !!!", text.charAt(i) == line.charAt(i)); } assertEquals("testCharAt error2 !!!", -1, text.charAt(-1)); asse...
public static String removeLeadingSlashes(String path) { return SLASH_PREFIX_PATTERN.matcher(path).replaceFirst(""); }
@Test public void removeLeadingSlashes_whenMultipleLeadingSlashes_removesLeadingSlashes() { assertThat(removeLeadingSlashes("/////a/b/c/")).isEqualTo("a/b/c/"); }
public boolean enabled() { return get(ENABLED, defaultValue); }
@Test public void basicTest() { ConfigApplyDelegate delegate = configApply -> { }; ObjectMapper mapper = new ObjectMapper(); TestConfig enabled = new TestConfig(true); TestConfig disabled = new TestConfig(false); enabled.init("enabled", "KEY", JsonNodeFactory.instance.objec...
@Override @TpsControl(pointName = "ConfigRemove") @Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG) @ExtractorManager.Extractor(rpcExtractor = ConfigRequestParamExtractor.class) public ConfigRemoveResponse handle(ConfigRemoveRequest configRemoveRequest, RequestMeta meta) throw...
@Test void testHandle() { ConfigRemoveRequest configRemoveRequest = new ConfigRemoveRequest(); configRemoveRequest.setRequestId("requestId"); configRemoveRequest.setGroup("group"); configRemoveRequest.setDataId("dataId"); configRemoveRequest.setTenant("tenant"); Reque...
public static String buildAppAuthPath(final String appKey) { return String.join(PATH_SEPARATOR, APP_AUTH_PARENT, appKey); }
@Test public void testBuildAppAuthPath() { String appKey = RandomStringUtils.randomAlphanumeric(10); String appAuthPath = DefaultPathConstants.buildAppAuthPath(appKey); assertThat(appAuthPath, notNullValue()); assertThat(String.join(SEPARATOR, APP_AUTH_PARENT, appKey), equalTo(appAut...
@VisibleForTesting Object evaluate(final GenericRow row) { return term.getValue(new TermEvaluationContext(row)); }
@Test public void shouldEvaluateComparisons_decimal() { // Given: final Expression expression1 = new ComparisonExpression( ComparisonExpression.Type.GREATER_THAN, COL8, new DecimalLiteral(new BigDecimal("1.2")) ); final Expression expression2 = new ComparisonExpression( ...