focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public static <T> PTransform<PCollection<T>, PCollection<T>> intersectDistinct( PCollection<T> rightCollection) { checkNotNull(rightCollection, "rightCollection argument is null"); return new SetImpl<>(rightCollection, intersectDistinct()); }
@Test @Category(NeedsRunner.class) public void testIntersection() { PAssert.that(first.apply("strings", Sets.intersectDistinct(second))) .containsInAnyOrder("a", "b", "c", "d"); PCollection<Row> results = firstRows.apply("rows", Sets.intersectDistinct(secondRows)); PAssert.that(results).contai...
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CoordinatorRecord record = (CoordinatorRecord) o; if (!Objects.equals(key, record.key)) return false; return Objects.equals(value, record.value...
@Test public void testEquals() { ApiMessageAndVersion key = new ApiMessageAndVersion(mock(ApiMessage.class), (short) 0); ApiMessageAndVersion value = new ApiMessageAndVersion(mock(ApiMessage.class), (short) 0); CoordinatorRecord record1 = new CoordinatorRecord(key, value); Coordinato...
@VisibleForTesting Object evaluate(final GenericRow row) { return term.getValue(new TermEvaluationContext(row)); }
@Test public void shouldEvaluateComparisons_int() { // Given: final Expression expression1 = new ComparisonExpression( ComparisonExpression.Type.GREATER_THAN, COL7, new IntegerLiteral(10) ); final Expression expression2 = new ComparisonExpression( ComparisonExpression.T...
public static MetricName name(Class<?> klass, String... names) { return name(klass.getName(), names); }
@Test public void concatenatesClassesWithoutCanonicalNamesWithStrings() throws Exception { final Gauge<String> g = () -> null; assertThat(name(g.getClass(), "one", "two")) .isEqualTo(MetricName.build(g.getClass().getName() + ".one.two")); }
protected boolean writeRowTo( Object[] row ) throws KettleException { if ( meta.isServletOutput( ) ) { return writeRowToServlet( row ); } else { return writeRowToFile( row ); } }
@Test public void testWriteRowToFile_NoinitServletStreamWriter() throws Exception { // SETUP textFileOutput = new TextFileOutputTestHandler( stepMockHelper.stepMeta, stepMockHelper.stepDataInterface, 0, stepMockHelper.transMeta, stepMockHelper.trans ); TextFileOutputMeta mockTFOMeta...
@NotNull public DataSize getReservedSystemMemory() { return reservedSystemMemory; }
@Test public void testDefaults() { // This can't use assertRecordedDefaults because the default value is dependent on the current max heap size, which varies based on the current size of the survivor space. for (int i = 0; i < 1_000; i++) { DataSize expected = new DataSize(Runtime.ge...
@Override protected int command() { if (!validateConfigFilePresent()) { return 1; } final MigrationConfig config; try { config = MigrationConfig.load(getConfigFile()); } catch (KsqlException | MigrationException e) { LOGGER.error(e.getMessage()); return 1; } retur...
@Test public void shouldValidateSingleMigration() throws Exception { // Given: final List<String> versions = ImmutableList.of("1"); final List<String> checksums = givenExistingMigrationFiles(versions); givenAppliedMigrations(versions, checksums); // When: final int result = command.command(co...
@Override public PositionReader openPositionRead(String path, long fileLength) { return new OSSPositionReader(mClient, mBucketName, stripPrefixIfPresent(path), fileLength); }
@Test public void testOpenPositionRead() { PositionReader result = mOSSUnderFileSystem.openPositionRead(KEY, 1L); Assert.assertTrue(result instanceof OSSPositionReader); }
@Override public Optional<FunctionAuthData> cacheAuthData(Function.FunctionDetails funcDetails, AuthenticationDataSource authenticationDataSource) { String id = null; String tenant = funcDetails.getTenant(); String namespace = funcDetails.g...
@Test public void testCacheAuthData() throws ApiException { CoreV1Api coreV1Api = mock(CoreV1Api.class); doReturn(new V1Secret()).when(coreV1Api).createNamespacedSecret(anyString(), any(), anyString(), anyString(), anyString(), anyString()); KubernetesSecretsTokenAuthProvider kubernetesSecre...
public boolean isAdmin() { return this.memberRole.isAdministrator(); }
@Test void 어드민인_경우에_true를_반환한다() { // given Member admin = 어드민_유저_생성(); // when boolean result = admin.isAdmin(); // then assertThat(result).isTrue(); }
public Pair<ElectMasterResponseHeader, BrokerMemberGroup> electMaster(String controllerAddr, String clusterName, String brokerName, Long brokerId) throws MQBrokerException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, RemotingCommandException { ...
@Test public void assertElectMaster() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); BrokerMemberGroup responseBody = new BrokerMemberGroup(); setResponseBody(responseBody); GetMetaDataResponseHeader getMetaDataResponseHeader = new GetMetaDataRe...
public static Map<String, String> translateParameterMap(Map<String, String[]> parameterMap) throws Exception { Map<String, String> map = new HashMap<>(16); for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { map.put(entry.getKey(), entry.getValue()[0]); } retu...
@Test void testTranslateParameterMap() throws Exception { Map<String, String[]> map = Collections.singletonMap("K", new String[] {"V1", "V2"}); Map<String, String> resultMap = HttpUtils.translateParameterMap(map); assertEquals(Collections.singletonMap("K", "V1"), resultMap); }
Optional<CheckpointTriggerRequest> chooseRequestToExecute( CheckpointTriggerRequest newRequest, boolean isTriggering, long lastCompletionMs) { if (queuedRequests.size() >= maxQueuedRequests && !queuedRequests.last().isPeriodic) { // there are only non-periodic (ie user-submitted) request...
@Test void testQueueSizeLimit() { final int maxQueuedRequests = 10; final boolean isTriggering = true; CheckpointRequestDecider decider = decider(maxQueuedRequests); List<CheckpointTriggerRequest> requests = rangeClosed(0, maxQueuedRequests) .m...
public static List<String> splitPlainTextParagraphs( List<String> lines, int maxTokensPerParagraph) { return internalSplitTextParagraphs( lines, maxTokensPerParagraph, (text) -> internalSplitLines( text, maxTokensPerParagraph, false, s_plaintextSplitOp...
@Test public void canSplitTextParagraphsOnHyphens() { List<String> input = Arrays.asList( "This is a test of the emergency broadcast system-This is only a test", "We repeat-this is only a test-A unit test", "A small note-And another-And once again-Seriously, this is the e...
public static Read<GenericRecord> readAvroGenericRecords(org.apache.avro.Schema avroSchema) { AvroCoder<GenericRecord> coder = AvroCoder.of(avroSchema); Schema schema = AvroUtils.getSchema(GenericRecord.class, avroSchema); return Read.newBuilder(parsePayloadUsingCoder(coder)) .setCoder( ...
@Test public void testAvroGenericRecords() { AvroCoder<GenericRecord> coder = AvroCoder.of(SCHEMA); List<GenericRecord> inputs = ImmutableList.of( new AvroGeneratedUser("Bob", 256, null), new AvroGeneratedUser("Alice", 128, null), new AvroGeneratedUser("Ted", null, ...
@Override public String execute(CommandContext commandContext, String[] args) { logger.info("received publishMetadata command."); StringBuilder stringBuilder = new StringBuilder(); List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels(); for (ApplicationMod...
@Test void testExecute() { PublishMetadata publishMetadata = new PublishMetadata(frameworkModel); String result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[0]); String expectResult = "publish metadata succeeded. App:APP_0\n" + "publish metadata succeeded. App:AP...
@GetMapping("/plugin/selector/delete") public Mono<String> deleteSelector(@RequestParam("pluginName") final String pluginName, @RequestParam("id") final String id) { SelectorData selectorData = SelectorData.builder().pluginName(pluginName).id(id).build(); subsc...
@Test public void testDeleteSelector() throws Exception { final String selectorPluginName = "testSaveSelector"; final String testSelectorId = "id"; final SelectorData selectorData = new SelectorData(); selectorData.setId(testSelectorId); selectorData.setPluginName(selectorPlu...
@PutMapping("/{id}") @RequiresPermissions("system:pluginHandler:edit") public ShenyuAdminResult updatePluginHandle(@PathVariable("id") @Valid @Existed(provider = PluginHandleMapper.class, message = "rule not ...
@Test public void testUpdatePluginHandle() throws Exception { PluginHandleDTO pluginHandleDTO = new PluginHandleDTO(); pluginHandleDTO.setId("1"); pluginHandleDTO.setPluginId("1213"); pluginHandleDTO.setDataType(1); pluginHandleDTO.setField("f"); pluginHandleDTO.setTy...
public static void destroyAll() { for (Map.Entry<RegistryConfig, Registry> entry : ALL_REGISTRIES.entrySet()) { RegistryConfig config = entry.getKey(); Registry registry = entry.getValue(); try { registry.destroy(); ALL_REGISTRIES.remove(config...
@Test public void destroyAll() { }
@Override public CoordinatorRecord deserialize( ByteBuffer keyBuffer, ByteBuffer valueBuffer ) throws RuntimeException { final short recordType = readVersion(keyBuffer, "key"); final ApiMessage keyMessage = apiMessageKeyFor(recordType); readMessage(keyMessage, keyBuffer, ...
@Test public void testDeserializeWithInvalidKeyBytes() { GroupCoordinatorRecordSerde serde = new GroupCoordinatorRecordSerde(); ByteBuffer keyBuffer = ByteBuffer.allocate(2); keyBuffer.putShort((short) 3); keyBuffer.rewind(); ByteBuffer valueBuffer = ByteBuffer.allocate(2);...
public static boolean isDownvoteCounter(Counter counter) { String sceneValue = counter.getId().getTag(SCENE); if (StringUtils.isBlank(sceneValue)) { return false; } return DOWNVOTE_SCENE.equals(sceneValue); }
@Test void isDownvoteCounter() { MeterRegistry meterRegistry = new SimpleMeterRegistry(); Counter downvoteCounter = MeterUtils.downvoteCounter(meterRegistry, "posts.content.halo.run/fake-post"); assertThat(MeterUtils.isDownvoteCounter(downvoteCounter)).isTrue(); assertTha...
@Override public void accept(Point newPoint) { //ensure this method is never called by multiple threads at the same time. parallelismDetector.run( () -> doAccept(newPoint) ); }
@Test public void testTrackClosure_multipleTracks() { Duration TIME_LIMIT = Duration.ofSeconds(5); TestConsumer consumer = new TestConsumer(); TrackMaker maker = new TrackMaker(TIME_LIMIT, consumer); assertTrue( consumer.numCallsToAccept == 0, "The consumer...
@Override public synchronized UdfFactory ensureFunctionFactory(final UdfFactory factory) { validateFunctionName(factory.getName()); final String functionName = factory.getName().toUpperCase(); if (udafs.containsKey(functionName)) { throw new KsqlException("UdfFactory already registered as aggregate...
@Test public void shouldThrowOnEnsureUdfFactoryOnDifferentX() { // Given: functionRegistry.ensureFunctionFactory(udfFactory); when(udfFactory.matches(udfFactory1)).thenReturn(false); // When: final Exception e = assertThrows( KsqlException.class, () -> functionRegistry.ensureFunc...
public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((!Character.isWhitespace(str.charAt(i)))) { return false; } } ...
@Test public void testIsBlank() { Assert.assertFalse(StringUtil.isBlank("!!!!")); Assert.assertTrue(StringUtil.isBlank(null)); Assert.assertTrue(StringUtil.isBlank("\n\n")); Assert.assertTrue(StringUtil.isBlank("")); }
@PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteFlowRule(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity oldEntity = repository.findById(id); if (oldEntity =...
@Test public void testDeleteFlowRule() throws Exception { String path = "/gateway/flow/delete.json"; // Add one entity into memory repository for delete GatewayFlowRuleEntity addEntity = new GatewayFlowRuleEntity(); addEntity.setId(1L); addEntity.setApp(TEST_APP); ad...
@Override public SentWebAppMessage deserializeResponse(String answer) throws TelegramApiRequestException { return deserializeResponse(answer, SentWebAppMessage.class); }
@Test public void testAnswerWebAppQueryDeserializeErrorResponse() { String responseText = "{\"ok\":false,\"error_code\": 404,\"description\": \"Error message\"}"; AnswerWebAppQuery answerWebAppQuery = AnswerWebAppQuery .builder() .webAppQueryId("123456789") ...
@Override public void destroy() { mCurrentRunningLocalProxy.dispose(); mContext.unregisterReceiver(mMediaInsertionAvailableReceiver); }
@Test public void testReceiverLifeCycle() { Assert.assertEquals( 1, mShadowApplication.getRegisteredReceivers().stream() .filter( wrapper -> wrapper.broadcastReceiver instanceof RemoteInsertionImpl.MediaInsertionAvailableRecei...
public abstract boolean hasError();
@Test public void testPretty() throws UnsupportedEncodingException, IOException { String schemaText = "{ " + " \"type\": \"record\"," + " \"name\": \"LongList\"," + " \"fields\" : [" + " {\"name\": \"value\", \"type\": \"long\"}, " + " {\"name\": \"next\", \"type\": ...
public DoubleArrayAsIterable usingTolerance(double tolerance) { return new DoubleArrayAsIterable(tolerance(tolerance), iterableSubject()); }
@Test public void usingTolerance_containsExactly_primitiveDoubleArray_failure() { expectFailureWhenTestingThat(array(1.1, TOLERABLE_2POINT2, 3.3)) .usingTolerance(DEFAULT_TOLERANCE) .containsExactly(array(2.2, 1.1)); assertFailureKeys( "value of", "unexpected (1)", "---", "expected", "...
public static <K> KStreamHolder<K> build( final KStreamHolder<K> stream, final StreamSelect<K> step, final RuntimeBuildContext buildContext ) { final QueryContext queryContext = step.getProperties().getQueryContext(); final LogicalSchema sourceSchema = stream.getSchema(); final Optional...
@Test public void shouldReturnCorrectSchema() { // When: final KStreamHolder<Struct> result = step.build(planBuilder, planInfo); // Then: assertThat( result.getSchema(), is(LogicalSchema.builder() .keyColumn(SystemColumns.ROWKEY_NAME, SqlTypes.STRING) .valueCol...
protected Properties getDefaultProps() { final Properties props = new Properties(); props.setProperty( CONFLUENT_SUPPORT_METRICS_ENABLE_CONFIG, CONFLUENT_SUPPORT_METRICS_ENABLE_DEFAULT ); props.setProperty(CONFLUENT_SUPPORT_CUSTOMER_ID_CONFIG, CONFLUENT_SUPPORT_CUSTOMER_ID_DEFAULT); ...
@Test public void testGetDefaultProps() { // Given Properties overrideProps = new Properties(); // When BaseSupportConfig supportConfig = new TestSupportConfig(overrideProps); // Then assertTrue(supportConfig.getMetricsEnabled()); assertEquals("anonymous", supportConfig.getCustomerId()); ...
public MigrationResult run(Set<String> completedAlertConditions, Set<String> completedAlarmCallbacks) { final MigrationResult.Builder result = MigrationResult.builder(); streamsCollection.find().forEach(stream -> { final String streamId = stream.getObjectId("_id").toHexString(); ...
@Test @MongoDBFixtures("legacy-alert-conditions.json") public void run() { final int migratedConditions = 10; final int migratedCallbacks = 4; assertThat(migrator.run(Collections.emptySet(), Collections.emptySet())).satisfies(result -> { assertThat(result.completedAlertCondi...
public static String[] decodeBasicAuth(String credential) { String[] values = decodeBase64(credential).split(BASIC_AUTH_SEPARATOR, BASIC_AUTH_LENGTH); validateBasicAuth(values); return values; }
@Test @DisplayName("BasicAuth 인증 정보 디코딩 성공: 여러 개의 구분자 포함일 경우 첫 구분자 이후 문자열을 비밀번호로 인식") void decodeValidAuthWithMultipleSeparators() { String name = "codezap"; String password = "pass:word:123"; String credential = HttpHeaders.encodeBasicAuth(name, password, StandardCharsets.UTF_8); ...
@Override public Row poll() { return poll(Duration.ZERO); }
@Test public void shouldNotPollIfFailed() throws Exception { // Given handleQueryResultError(); // When final Exception e = assertThrows(IllegalStateException.class, () -> queryResult.poll()); // Then assertThat(e.getMessage(), containsString("Cannot poll on StreamedQueryResult that has fail...
@VisibleForTesting void validateLevelUnique(List<MemberLevelDO> list, Long id, Integer level) { for (MemberLevelDO levelDO : list) { if (ObjUtil.notEqual(levelDO.getLevel(), level)) { continue; } if (id == null || !id.equals(levelDO.getId())) { ...
@Test public void testUpdateLevel_levelUnique() { // 准备参数 Long id = randomLongId(); Integer level = randomInteger(); String name = randomString(); // mock 数据 memberlevelMapper.insert(randomLevelDO(o -> { o.setLevel(level); o.setName(name); ...
@Override public String getNext() { return String.valueOf(queryIdCounter.getAndIncrement()); }
@Test public void shouldGenerateMonotonicallyIncrementingIds() { assertThat(generator.getNext(), is("0")); assertThat(generator.getNext(), is("1")); assertThat(generator.getNext(), is("2")); }
public synchronized int sendFetches() { final Map<Node, FetchSessionHandler.FetchRequestData> fetchRequests = prepareFetchRequests(); sendFetchesInternal( fetchRequests, (fetchTarget, data, clientResponse) -> { synchronized (Fetcher.this) { ...
@Test public void testLeaderEpochInConsumerRecord() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); int partitionLeaderEpoch = 1; ByteBuffer buffer = ByteBuffer.allocate(1024); MemoryRecordsBuilder builder = MemoryRecords.builder(buffe...
public static AvroGenericCoder of(Schema schema) { return AvroGenericCoder.of(schema); }
@Test public void testDeterministicSimple() { assertDeterministic(AvroCoder.of(SimpleDeterministicClass.class)); }
@Deprecated public DomainNameMapping<V> add(String hostname, V output) { map.put(normalizeHostname(checkNotNull(hostname, "hostname")), checkNotNull(output, "output")); return this; }
@Test public void testNullValuesAreForbidden() { assertThrows(NullPointerException.class, new Executable() { @Override public void execute() { new DomainNameMappingBuilder<String>("NotFound").add("Some key", null); } }); }
public static ShardingRouteEngine newInstance(final ShardingRule shardingRule, final ShardingSphereDatabase database, final QueryContext queryContext, final ShardingConditions shardingConditions, final ConfigurationProperties props, final ConnectionContext connectionCon...
@Test void assertNewInstanceForComplex() { SQLStatement sqlStatement = mock(SQLStatement.class); when(sqlStatementContext.getSqlStatement()).thenReturn(sqlStatement); tableNames.add("1"); tableNames.add("2"); when(shardingRule.getShardingLogicTableNames(tableNames)).thenRetur...
public void setOuterJoinType(OuterJoinType outerJoinType) { this.outerJoinType = outerJoinType; }
@Test void testFullOuterJoinWithoutMatchingPartners() throws Exception { final List<String> leftInput = Arrays.asList("foo", "bar", "foobar"); final List<String> rightInput = Arrays.asList("oof", "rab", "raboof"); baseOperator.setOuterJoinType(OuterJoinOperatorBase.OuterJoinType.FULL); ...
@Override public PollResult poll(long currentTimeMs) { return pollInternal( prepareFetchRequests(), this::handleFetchSuccess, this::handleFetchFailure ); }
@Test public void testInvalidDefaultRecordBatch() { buildFetcher(); ByteBuffer buffer = ByteBuffer.allocate(1024); ByteBufferOutputStream out = new ByteBufferOutputStream(buffer); MemoryRecordsBuilder builder = new MemoryRecordsBuilder(out, DefaultRecordBatch.CURREN...
@Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { if (key == null) { return null; } return super.compute(key, remappingFunction); }
@Test public void testCompute() { Assert.assertEquals(VALUE, map.get(KEY)); Assert.assertEquals(null, map.compute(null, (key, value) -> "")); Assert.assertEquals(VALUE, map.get(KEY)); }
@Override public SingleRule build(final SingleRuleConfiguration ruleConfig, final String databaseName, final DatabaseType protocolType, final ResourceMetaData resourceMetaData, final Collection<ShardingSphereRule> builtRules, final ComputeNodeInstanceContext computeNodeInstanceContext) {...
@SuppressWarnings({"rawtypes", "unchecked"}) @Test void assertBuild() { DatabaseRuleBuilder builder = OrderedSPILoader.getServices(DatabaseRuleBuilder.class).iterator().next(); DatabaseRule actual = builder.build(mock(SingleRuleConfiguration.class), "", new MySQLDatabaseType(), m...
@Subscribe public void onChatMessage(ChatMessage event) { final String message = event.getMessage(); if (event.getType() != ChatMessageType.SPAM && event.getType() != ChatMessageType.GAMEMESSAGE) { return; } if (message.contains(DODGY_NECKLACE_PROTECTION_MESSAGE) || message.contains(SHADOW_VEIL_PROTECTI...
@Test public void testShadowVeil() { when(timersAndBuffsConfig.showArceuus()).thenReturn(true); when(client.getRealSkillLevel(Skill.MAGIC)).thenReturn(57); ChatMessage chatMessage = new ChatMessage(null, ChatMessageType.GAMEMESSAGE, "", "<col=6800bf>Your thieving abilities have been enhanced.</col>", "", 0); ...
public static Expression convert(Predicate[] predicates) { Expression expression = Expressions.alwaysTrue(); for (Predicate predicate : predicates) { Expression converted = convert(predicate); Preconditions.checkArgument( converted != null, "Cannot convert Spark predicate to Iceberg expres...
@Test public void testNestedInInsideNot() { NamedReference namedReference1 = FieldReference.apply("col1"); LiteralValue v1 = new LiteralValue(1, DataTypes.IntegerType); LiteralValue v2 = new LiteralValue(2, DataTypes.IntegerType); org.apache.spark.sql.connector.expressions.Expression[] attrAndValue1 =...
@Override public void start(final QueryId queryId) { }
@Test public void shouldStartQuery() { //When: validationSharedKafkaStreamsRuntime.start(queryId); //Then: assertThat("Query was not added", validationSharedKafkaStreamsRuntime.getQueries().contains(queryId)); }
public static long btcToSatoshi(BigDecimal coins) throws ArithmeticException { return coins.movePointRight(SMALLEST_UNIT_EXPONENT).longValueExact(); }
@Test(expected = ArithmeticException.class) public void testBtcToSatoshi_tooBig() { btcToSatoshi(new BigDecimal("92233720368.54775808")); // .00000001 more than maximum value }
@Override void handle(Connection connection, DatabaseCharsetChecker.State state) throws SQLException { // PostgreSQL does not have concept of case-sensitive collation. Only charset ("encoding" in postgresql terminology) // must be verified. expectUtf8AsDefault(connection); if (state == DatabaseCharse...
@Test public void fresh_install_verifies_that_default_charset_is_utf8() throws SQLException { answerDefaultCharset("utf8"); underTest.handle(connection, DatabaseCharsetChecker.State.FRESH_INSTALL); // no errors, charset has been verified verify(metadata).getDefaultCharset(same(connection)); verif...
@Override public void write(ProjectDump.Metadata metadata) { checkNotPublished(); if (metadataWritten.get()) { throw new IllegalStateException("Metadata has already been written"); } File file = new File(rootDir, METADATA.filename()); try (FileOutputStream output = FILES2.openOutputStream(fi...
@Test public void writeMetadata_writes_to_file() { underTest.write(newMetadata()); assertThat(dumpReader.metadata().getProjectKey()).isEqualTo("foo"); }
public void trackGTClickDelayed(String messageId, String title, String content) { try { Message message = Message.obtain(); message.what = GT_PUSH_MSG; message.obj = messageId; mGeTuiPushInfoMap.put(messageId, new NotificationInfo(title, content, System.currentTim...
@Test public void trackGTClickDelayed() { SAHelper.initSensors(mApplication); PushProcess.getInstance().trackGTClickDelayed("sdajh-asdjfhjas", "mock_title", "mock_content"); }
@Override public void validateDeleteGroup() throws ApiException { if (state() != ShareGroupState.EMPTY) { throw Errors.NON_EMPTY_GROUP.exception(); } }
@Test public void testValidateDeleteGroup() { ShareGroup shareGroup = createShareGroup("foo"); assertEquals(ShareGroupState.EMPTY, shareGroup.state()); assertDoesNotThrow(shareGroup::validateDeleteGroup); ShareGroupMember member1 = new ShareGroupMember.Builder("member1") ...
public String getServiceAccount() { return flinkConfig.get(KubernetesConfigOptions.JOB_MANAGER_SERVICE_ACCOUNT); }
@Test void testGetServiceAccountShouldReturnDefaultIfNotExplicitlySet() { assertThat(kubernetesJobManagerParameters.getServiceAccount()).isEqualTo("default"); }
@VisibleForTesting public List<Partition> getNewPartitionsFromPartitions(Database db, OlapTable olapTable, List<Long> sourcePartitionIds, Map<Long, String> origPartitions, OlapTable copiedTbl, ...
@Test public void testGetNewPartitionsFromPartitions() throws DdlException { Database db = connectContext.getGlobalStateMgr().getDb("test"); Table table = db.getTable("t1"); Assert.assertTrue(table instanceof OlapTable); OlapTable olapTable = (OlapTable) table; Partition sour...
public void publishArtifacts(List<ArtifactPlan> artifactPlans, EnvironmentVariableContext environmentVariableContext) { final File pluggableArtifactFolder = publishPluggableArtifacts(artifactPlans, environmentVariableContext); try { final List<ArtifactPlan> mergedPlans = artifactPlanFilter.g...
@Test public void shouldAddPluggableArtifactMetadataFileArtifactPlanAtTop() throws Exception { TestFileUtil.createTestFile(workingFolder, "installer.zip"); TestFileUtil.createTestFile(workingFolder, "testreports.xml"); final ArtifactStore artifactStore = new ArtifactStore("s3", "cd.go.s3", ...
public static Long fromHeaders(final String header, final Map<String, String> response) { final Map<String, String> headers = new HashMap<>(response.entrySet() .stream() .map(entry -> Maps.immutableEntry(StringUtils.lowerCase(entry.getKey()), entry.getValue())) .c...
@Test public void testFindMillisecondsTimestamp() throws Exception { final Map<String, String> headers = new HashMap<>(); headers.put("Mtime", "1530305150672"); // milliseconds assertEquals(1530305150672L, S3TimestampFeature.fromHeaders( S3TimestampFeature.METADATA_MODIFICATI...
@Override public GroupAssignment assign( GroupSpec groupSpec, SubscribedTopicDescriber subscribedTopicDescriber ) throws PartitionAssignorException { if (groupSpec.memberIds().isEmpty()) { return new GroupAssignment(Collections.emptyMap()); } else if (groupSpec.subscr...
@Test public void testFirstAssignmentThreeMembersThreeTopicsDifferentSubscriptions() { Map<Uuid, TopicMetadata> topicMetadata = new HashMap<>(); topicMetadata.put(topic1Uuid, new TopicMetadata( topic1Uuid, topic1Name, 3, Collections.emptyMap() ...
private static GuardedByExpression bind(JCTree.JCExpression exp, BinderContext context) { GuardedByExpression expr = BINDER.visit(exp, context); checkGuardedBy(expr != null, String.valueOf(exp)); checkGuardedBy(expr.kind() != Kind.TYPE_LITERAL, "Raw type literal: %s", exp); return expr; }
@Test public void staticOnStatic() { assertThat( bind( "Test", "Test.lock", forSourceLines( "threadsafety/Test.java", "package threadsafety;", "class Test {", " static final...
@Override public GenericAvroRecord read(byte[] bytes, int offset, int length) { try { if (offset == 0 && this.offset > 0) { offset = this.offset; } Decoder decoder = DecoderFactory.get().binaryDecoder(bytes, offset, length - offset, null); org....
@Test public void testGenericAvroReaderByWriterSchema() { byte[] fooBytes = fooSchema.encode(foo); GenericAvroReader genericAvroSchemaByWriterSchema = new GenericAvroReader(fooSchema.getAvroSchema()); GenericRecord genericRecordByWriterSchema = genericAvroSchemaByWriterSchema.read(fooBytes...
public long addAndGet(long delta) { return getAndAddVal( delta) + delta; }
@Test public void testAddAndGet() { PaddedAtomicLong counter = new PaddedAtomicLong(); long value = counter.addAndGet(1); assertEquals(1, value); assertEquals(1, counter.get()); }
public FileStoreInfo getFileStore(String fsKey) throws DdlException { try { return client.getFileStore(fsKey, serviceId); } catch (StarClientException e) { if (e.getCode() == StatusCode.NOT_EXIST) { return null; } throw new DdlException("Fa...
@Test public void testGetFileStore() throws StarClientException, DdlException { S3FileStoreInfo s3FsInfo = S3FileStoreInfo.newBuilder() .setRegion("region").setEndpoint("endpoint").build(); FileStoreInfo fsInfo = FileStoreInfo.newBuilder().setFsKey("test-fskey") .setF...
public AggregateAnalysisResult analyze( final ImmutableAnalysis analysis, final List<SelectExpression> finalProjection ) { if (!analysis.getGroupBy().isPresent()) { throw new IllegalArgumentException("Not an aggregate query"); } final AggAnalyzer aggAnalyzer = new AggAnalyzer(analysis, ...
@Test public void shouldNotThrowOnOtherExpressionTypesInProjection() { // Given: final Expression someExpression = mock(Expression.class); givenSelectExpression(someExpression); // When: analyzer.analyze(analysis, selects); // Then: did not throw. }
public synchronized void addService(URL url) { // fixme, pass in application mode context during initialization of MetadataInfo. if (this.loader == null) { this.loader = url.getOrDefaultApplicationModel().getExtensionLoader(MetadataParamsFilter.class); } List<MetadataParamsFi...
@Test void testJsonFormat() { MetadataInfo metadataInfo = new MetadataInfo("demo"); // export normal url again metadataInfo.addService(url); System.out.println(JsonUtils.toJson(metadataInfo)); MetadataInfo metadataInfo2 = new MetadataInfo("demo"); // export normal u...
@Override public void accept(ModemVisitor modemVisitor) { if (modemVisitor instanceof ZoomVisitor) { ((ZoomVisitor) modemVisitor).visit(this); } else { LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem"); } }
@Test void testAcceptForDos() { var zoom = new Zoom(); var mockVisitor = mock(ConfigureForDosVisitor.class); zoom.accept(mockVisitor); verify((ZoomVisitor) mockVisitor).visit(eq(zoom)); }
@Override public void encode(final ChannelHandlerContext context, final DatabasePacket message, final ByteBuf out) { boolean isIdentifierPacket = message instanceof PostgreSQLIdentifierPacket; if (isIdentifierPacket) { prepareMessageHeader(out, ((PostgreSQLIdentifierPacket) message).getI...
@Test void assertEncodePostgreSQLIdentifierPacket() { PostgreSQLIdentifierPacket packet = mock(PostgreSQLIdentifierPacket.class); when(packet.getIdentifier()).thenReturn(PostgreSQLMessagePacketType.AUTHENTICATION_REQUEST); when(byteBuf.readableBytes()).thenReturn(9); new PostgreSQLPa...
public Object toIdObject(String baseId) throws AmqpProtocolException { if (baseId == null) { return null; } try { if (hasAmqpUuidPrefix(baseId)) { String uuidString = strip(baseId, AMQP_UUID_PREFIX_LENGTH); return UUID.fromString(uuidStrin...
@Test public void testToIdObjectWithNull() throws Exception { assertNull("null object should have been returned", messageIdHelper.toIdObject(null)); }
@Override public boolean evaluate(Map<String, Object> values) { boolean toReturn = false; if (values.containsKey(name)) { logger.debug("found matching parameter, evaluating... "); toReturn = evaluation(values.get(name)); } return toReturn; }
@Test void evaluateStringNotIn() { ARRAY_TYPE arrayType = ARRAY_TYPE.STRING; List<Object> values = getObjects(arrayType, 4); KiePMMLSimpleSetPredicate kiePMMLSimpleSetPredicate = getKiePMMLSimpleSetPredicate(values, arrayType, ...
@Override public boolean remove(Object o) { return false; }
@Test public void remove() { SelectedSelectionKeySet set = new SelectedSelectionKeySet(); assertTrue(set.add(mockKey)); assertFalse(set.remove(mockKey)); assertFalse(set.remove(mockKey2)); }
@Override protected void unprotectedExecuteJob() throws LoadException { LoadTask task = new BrokerLoadPendingTask(this, fileGroupAggInfo.getAggKeyToFileGroups(), brokerDesc); idToTasks.put(task.getSignature(), task); submitTask(GlobalStateMgr.getCurrentState().getPendingLoadTaskScheduler(), ...
@Test public void testExecuteJob(@Mocked LeaderTaskExecutor leaderTaskExecutor) throws LoadException { new Expectations() { { leaderTaskExecutor.submit((LeaderTask) any); minTimes = 0; result = true; } }; GlobalStateMgr...
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (!(msg instanceof HttpMessage || msg instanceof HttpContent)) { ctx.write(msg, promise); return; } boolean release = true; SimpleChannelPromiseAggregator promiseA...
@Test public void testChunkedRequestWithBodyAndTrailingHeaders() throws Exception { final String text = "foooooo"; final String text2 = "goooo"; final List<String> receivedBuffers = Collections.synchronizedList(new ArrayList<String>()); doAnswer(new Answer<Void>() { @Over...
@Override public TCreatePartitionResult createPartition(TCreatePartitionRequest request) throws TException { LOG.info("Receive create partition: {}", request); TCreatePartitionResult result; try { if (partitionRequestNum.incrementAndGet() >= Config.thrift_server_max_worker_thre...
@Test public void testAutomaticPartitionPerLoadLimitExceed() throws TException { TransactionState state = new TransactionState(); new MockUp<GlobalTransactionMgr>() { @Mock public TransactionState getTransactionState(long dbId, long transactionId) { return sta...
@Initializer public static void relocateOldLogs() { relocateOldLogs(Jenkins.get().getRootDir()); }
@Test public void testRelocate() throws Exception { File d = File.createTempFile("jenkins", "test"); FilePath dir = new FilePath(d); try { dir.delete(); dir.mkdirs(); dir.child("slave-abc.log").touch(0); dir.child("slave-def.log.5").touch(0); ...
public static Object convertValue(String className, Object cleanValue, ClassLoader classLoader) { // "null" string is converted to null cleanValue = "null".equals(cleanValue) ? null : cleanValue; if (!isPrimitive(className) && cleanValue == null) { return null; } Cl...
@Test public void convertValueFailNotStringOrTypeTest() { assertThatThrownBy(() -> convertValue(RuleScenarioRunnerHelperTest.class.getCanonicalName(), 1, classLoader)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("Object 1 is not a String or an instan...
public Map<String, String> startSessionFromApp(@Valid AuthenticateRequest params) throws IOException, ParseException, JOSEException, InvalidSignatureException, DienstencatalogusException { var response = dcClient.retrieveMetadataFromDc(params.getClientId()); validateSignature(response, params); ...
@Test void startSessionFromAppTest() throws DienstencatalogusException, InvalidSignatureException, IOException, ParseException, JOSEException { //given AuthenticateRequest request = new AuthenticateRequest(); request.setClientId("PPP"); request.setRequest(client.generateRequest()); ...
@Override public EntityExcerpt createExcerpt(Output output) { return EntityExcerpt.builder() .id(ModelId.of(output.getId())) .type(ModelTypes.OUTPUT_V1) .title(output.getTitle()) .build(); }
@Test public void createExcerpt() { final ImmutableMap<String, Object> configuration = ImmutableMap.of(); final OutputImpl output = OutputImpl.create( "01234567890", "Output Title", "org.graylog2.output.SomeOutputClass", "admin", ...
@Override public ChannelBuffer copy() { return copy(readerIndex, readableBytes()); }
@Test void copyBoundaryCheck1() { Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.copy(-1, 0)); }
public static String filter(String htmlContent) { return new HTMLFilter().filter(htmlContent); }
@Test public void filterTest() { final String html = "<alert></alert>"; final String filter = HtmlUtil.filter(html); assertEquals("", filter); }
public ParseResult parse(File file) throws IOException, SchemaParseException { return parse(file, null); }
@Test void testParseTextWithFallbackJsonParser() { Schema schema = new SchemaParser().parse(SCHEMA_JSON).mainSchema(); assertEquals(SCHEMA_REAL, schema); }
@Override public void initialize(ServiceConfiguration config) throws IOException, IllegalArgumentException { String prefix = (String) config.getProperty(CONF_TOKEN_SETTING_PREFIX); if (null == prefix) { prefix = ""; } this.confTokenSecretKeySettingName = prefix + CONF_TOK...
@Test public void testTokenSettingPrefix() throws Exception { AuthenticationProviderToken provider = new AuthenticationProviderToken(); KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256); String publicKeyStr = AuthTokenUtils.encodeKeyBase64(keyPair.getPublic()); Properties ...
public static List<StreamedRow> toRows( final Buffer buff, final Function<StreamedRow, StreamedRow> addHostInfo ) { final List<StreamedRow> rows = new ArrayList<>(); int begin = 0; for (int i = 0; i <= buff.length(); i++) { if ((i == buff.length() && (i - begin > 1)) || (i < ...
@Test public void toRowsProto() { // When: final List<StreamedRow> rows = KsqlTargetUtil.toRows(Buffer.buffer("[{\"header\":{\"queryId\":\"queryId\"," + "\"schema\":\"`A` INTEGER KEY, `B` DOUBLE, `C` ARRAY<STRING>\"," + "\"protoSchema\":" + "\"syntax = \\\"proto3\\\";\\n" ...
static int compareAddresses(byte[] current, byte[] candidate) { if (candidate == null || candidate.length < EUI48_MAC_ADDRESS_LENGTH) { return 1; } // Must not be filled with only 0 and 1. boolean onlyZeroAndOne = true; for (byte b: candidate) { if (b != ...
@Test public void testCompareAddresses() { // should not prefer empty address when candidate is not globally unique assertEquals( 0, MacAddressUtil.compareAddresses( EMPTY_BYTES, new byte[]{(byte) 0x52, (byte) 0x54, (byt...
public void createStaticTopic(final String addr, final String defaultTopic, final TopicConfig topicConfig, final TopicQueueMappingDetail topicQueueMappingDetail, boolean force, final long timeoutMillis) throws RemotingException, InterruptedException, MQBrokerException { CreateTopicRequestHeader ...
@Test public void testCreateStaticTopic() throws RemotingException, InterruptedException, MQBrokerException { mockInvokeSync(); mqClientAPI.createStaticTopic(defaultBrokerAddr, defaultTopic, new TopicConfig(), new TopicQueueMappingDetail(), false, defaultTimeout); }
@Override public String toString() { return toString(false, null, BitcoinNetwork.MAINNET); }
@Test public void testNonCanonicalSigs() throws Exception { // Tests the noncanonical sigs from Bitcoin Core unit tests InputStream in = getClass().getResourceAsStream("sig_noncanonical.json"); // Poor man's JSON parser (because pulling in a lib for this is overkill) while (in.avail...
void tryStartApp() throws Exception { final boolean shutdown = runExecutable(preconditionChecker); if (shutdown) { return; } runExecutable(executable.get()); }
@Test public void shouldStopAppOnJoin() throws Exception { // Given: executable.shutdown(); expectLastCall(); replay(executable); // When: main.tryStartApp(); // Then: verify(executable); }
public static void notEmpty(Collection<?> collection, String message) { if (CollectionUtil.isEmpty(collection)) { throw new IllegalArgumentException(message); } }
@Test(expected = IllegalArgumentException.class) public void assertNotEmptyByMapAndMessageIsNull() { Assert.notEmpty(Collections.emptyMap()); }
@Override public UnderFileSystem create(String path, UnderFileSystemConfiguration conf) { Preconditions.checkNotNull(path, "Unable to create UnderFileSystem instance:" + " URI path should not be null"); if (checkCOSCredentials(conf)) { try { return COSUnderFileSystem.createInstance(new ...
@Test public void createInstanceWithPath() { UnderFileSystem ufs = mFactory.create(mCosPath, mConf); Assert.assertNotNull(ufs); Assert.assertTrue(ufs instanceof COSUnderFileSystem); }
void checkPerm(PlainAccessResource needCheckedAccess, PlainAccessResource ownedAccess) { permissionChecker.check(needCheckedAccess, ownedAccess); }
@Test public void checkPerm() { PlainAccessResource plainAccessResource = new PlainAccessResource(); plainAccessResource.addResourceAndPerm("topicA", Permission.PUB); plainPermissionManager.checkPerm(plainAccessResource, pubPlainAccessResource); plainAccessResource.addResourceAndPer...
@PostMapping("/selector") public ShenyuAdminResult saveSelector(@RequestBody @Valid @NotNull final DataPermissionDTO dataPermissionDTO) { return ShenyuAdminResult.success(ShenyuResultMessage.SAVE_SUCCESS, dataPermissionService.createSelector(dataPermissionDTO)); }
@Test public void saveSelector() throws Exception { DataPermissionDTO dataPermissionDTO = new DataPermissionDTO(); dataPermissionDTO.setDataId("testDataId"); dataPermissionDTO.setUserId("testUserId"); given(this.dataPermissionService.createSelector(dataPermissionDTO)).willReturn(1); ...
@Override public GlobalStatusRequestProto convert2Proto(GlobalStatusRequest globalStatusRequest) { final short typeCode = globalStatusRequest.getTypeCode(); final AbstractMessageProto abstractMessage = AbstractMessageProto.newBuilder().setMessageType( MessageTypeProto.forNumber(typeCode...
@Test public void convert2Proto() { GlobalStatusRequest globalStatusRequest = new GlobalStatusRequest(); globalStatusRequest.setExtraData("extraData"); globalStatusRequest.setXid("xid"); GlobalStatusRequestConvertor convertor = new GlobalStatusRequestConvertor(); GlobalStatu...
public static void removeColumnMetadataInfo(PropertiesConfiguration properties, String column) { properties.subset(COLUMN_PROPS_KEY_PREFIX + column).clear(); }
@Test public void testRemoveColumnMetadataInfo() throws Exception { PropertiesConfiguration configuration = CommonsConfigurationUtils.fromFile(CONFIG_FILE); configuration.setProperty(COLUMN_PROPERTY_KEY_PREFIX + "a", "foo"); configuration.setProperty(COLUMN_PROPERTY_KEY_PREFIX + "b", "bar"); con...
public static Range<Integer> integerRange(String range) { return ofString(range, Integer::parseInt, Integer.class); }
@Test public void emptyInfinityEquality() { assertEquals(integerRange("empty"), integerRange("empty")); assertEquals(integerRange("(infinity,infinity)"), integerRange("(infinity,infinity)")); assertEquals(integerRange("(,)"), integerRange("(infinity,infinity)")); assertEquals(integer...
static ParseResult parse(String expression, NameValidator variableValidator) { ParseResult result = new ParseResult(); try { Parser parser = new Parser(new Scanner("ignore", new StringReader(expression))); Java.Atom atom = parser.parseConditionalExpression(); if (pars...
@Test public void protectUsFromStuff() { NameValidator allNamesInvalid = s -> false; for (String toParse : Arrays.asList("", "new Object()", "java.lang.Object", "Test.class", "new Object(){}.toString().length", "{ 5}", "{ 5, 7 }", "Object.class", "System.out.println(\"\")", ...
public static boolean canChangeState(Function.FunctionMetaData functionMetaData, int instanceId, Function.FunctionState newState) { if (instanceId >= functionMetaData.getFunctionDetails().getParallelism()) { return false; } if (functionMetaDat...
@Test public void testCanChangeState() { long version = 5; Function.FunctionMetaData metaData = Function.FunctionMetaData.newBuilder().setFunctionDetails( Function.FunctionDetails.newBuilder().setName("func-1").setParallelism(2)).setVersion(version).build(); Assert.assertTr...
public static FunctionConfig validateUpdate(FunctionConfig existingConfig, FunctionConfig newConfig) { FunctionConfig mergedConfig = existingConfig.toBuilder().build(); if (!existingConfig.getTenant().equals(newConfig.getTenant())) { throw new IllegalArgumentException("Tenants differ"); ...
@Test public void testMergeDifferentResources() { FunctionConfig functionConfig = createFunctionConfig(); Resources resources = new Resources(); resources.setCpu(0.3); resources.setRam(1232L); resources.setDisk(123456L); FunctionConfig newFunctionConfig = createUpdate...
public int getFailedVerifyCount() { final AtomicInteger result = new AtomicInteger(); distroRecords.forEach((s, distroRecord) -> result.addAndGet(distroRecord.getFailedVerifyCount())); return result.get(); }
@Test void testGetFailedVerifyCount() { DistroRecordsHolder.getInstance().getRecord("testGetFailedVerifyCount"); Optional<DistroRecord> actual = DistroRecordsHolder.getInstance().getRecordIfExist("testGetFailedVerifyCount"); assertTrue(actual.isPresent()); assertEquals(0, DistroRecor...
public static void deleteDirectory(Path path) { try { if (Files.exists(path)) { try (Stream<Path> walk = Files.walk(path)) { walk.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); ...
@Test public void deleteDirectory() throws IOException { final Path tempDirectory = Files.createTempDirectory("temp"); final Path tempFile = Files.createTempFile(tempDirectory, "temp", "temp"); FileUtils.deleteDirectory(tempDirectory); assertThat(Files.exists(tempDirectory)).isFalse(...
public ValueAndTimestamp<V> get(final K key) { if (timestampedStore != null) { return timestampedStore.get(key); } if (versionedStore != null) { final VersionedRecord<V> versionedRecord = versionedStore.get(key); return versionedRecord == null ...
@Test public void shouldGetFromTimestampedStore() { givenWrapperWithTimestampedStore(); when(timestampedStore.get(KEY)).thenReturn(VALUE_AND_TIMESTAMP); assertThat(wrapper.get(KEY), equalTo(VALUE_AND_TIMESTAMP)); }
@Override public Page getNextPage() { if (closed) { return null; } if (serverResponseIterator == null) { serverResponseIterator = queryPinot(split); } ByteBuffer byteBuffer = null; try { // Pinot gRPC server response iterator r...
@Test public void testAllDataTypes() { PinotSessionProperties pinotSessionProperties = new PinotSessionProperties(pinotConfig); ConnectorSession session = new TestingConnectorSession(pinotSessionProperties.getSessionProperties()); List<DataTable> dataTables = IntStream.range(0, 3).mapToO...
@Override public Column convert(BasicTypeDefine typeDefine) { PhysicalColumn.PhysicalColumnBuilder builder = PhysicalColumn.builder() .name(typeDefine.getName()) .sourceType(typeDefine.getColumnType()) .nullable(typeDefi...
@Test public void testConvertSmallint() { BasicTypeDefine<Object> typeDefine = BasicTypeDefine.builder() .name("test") .columnType("smallint") .dataType("smallint") .build(); Column column...
public static @Nullable MetricsContainer setCurrentContainer( @Nullable MetricsContainer container) { MetricsContainerHolder holder = CONTAINER_FOR_THREAD.get(); @Nullable MetricsContainer previous = holder.container; holder.container = container; return previous; }
@Test public void testUsesAppropriateMetricsContainer() { Counter counter = Metrics.counter("ns", "name"); MetricsContainer c1 = Mockito.mock(MetricsContainer.class); MetricsContainer c2 = Mockito.mock(MetricsContainer.class); Counter counter1 = Mockito.mock(Counter.class); Counter counter2 = Moc...