[ { "id": 0, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @VisibleForTesting\n boolean handleRecoveryTask(RecoveryTaskMetadata recoveryTaskMetadata) {\n LOG.info(\"Started handling the recovery task: {}\", recoveryTaskMetadata);\n long startTime = System.nanoTime();\n Timer.Sample taskTimer = Timer.start(meterRegistry);\n\n PartitionOffsets partitionOffsets =\n validateKafkaOffsets(\n adminClient,\n recoveryTaskMetadata,\n AstraConfig.getRecoveryConfig().getKafkaConfig().getKafkaTopic());\n long offsetsValidatedTime = System.nanoTime();\n long consumerPreparedTime = 0, messagesConsumedTime = 0, rolloversCompletedTime = 0;\n\n if (partitionOffsets != null) {\n RecoveryTaskMetadata validatedRecoveryTask =\n new RecoveryTaskMetadata(\n recoveryTaskMetadata.name,\n recoveryTaskMetadata.partitionId,\n partitionOffsets.startOffset,\n partitionOffsets.endOffset,\n recoveryTaskMetadata.createdTimeEpochMs);\n\n if (partitionOffsets.startOffset != recoveryTaskMetadata.startOffset\n || recoveryTaskMetadata.endOffset != partitionOffsets.endOffset) {\n recoveryRecordsNoLongerAvailable.increment(\n (partitionOffsets.startOffset - recoveryTaskMetadata.startOffset)\n + (partitionOffsets.endOffset - recoveryTaskMetadata.endOffset));\n }\n\n try {\n RecoveryChunkManager chunkManager =\n RecoveryChunkManager.fromConfig(\n meterRegistry,\n searchMetadataStore,\n snapshotMetadataStore,\n AstraConfig.getIndexerConfig(),\n blobFs,\n AstraConfig.getS3Config());\n\n // Ingest data in parallel\n LogMessageWriterImpl logMessageWriterImpl = new LogMessageWriterImpl(chunkManager);\n AstraKafkaConsumer kafkaConsumer =\n new AstraKafkaConsumer(\n makeKafkaConfig(\n AstraConfig.getRecoveryConfig().getKafkaConfig(),\n validatedRecoveryTask.partitionId),\n logMessageWriterImpl,\n meterRegistry);\n\n kafkaConsumer.prepConsumerForConsumption(validatedRecoveryTask.startOffset);\n consumerPreparedTime = System.nanoTime();\n kafkaConsumer.consumeMessagesBetweenOffsetsInParallel(\n AstraKafkaConsumer.KAFKA_POLL_TIMEOUT_MS,\n validatedRecoveryTask.startOffset,\n validatedRecoveryTask.endOffset);\n messagesConsumedTime = System.nanoTime();\n // Wait for chunks to upload.\n boolean success = chunkManager.waitForRollOvers();\n rolloversCompletedTime = System.nanoTime();\n // Close the recovery chunk manager and kafka consumer.\n kafkaConsumer.close();\n chunkManager.stopAsync();\n chunkManager.awaitTerminated(DEFAULT_START_STOP_DURATION);\n LOG.info(\"Finished handling the recovery task: {}\", validatedRecoveryTask);\n taskTimer.stop(recoveryTaskTimerSuccess);\n return success;\n } catch (Exception ex) {\n LOG.error(\"Exception in recovery task [{}]: {}\", validatedRecoveryTask, ex);\n taskTimer.stop(recoveryTaskTimerFailure);\n return false;\n } finally {\n long endTime = System.nanoTime();\n LOG.info(\n \"Recovery task {} took {}ms, (subtask times offset validation {}, consumer prep {}, msg consumption {}, rollover {})\",\n recoveryTaskMetadata,\n nanosToMillis(endTime - startTime),\n nanosToMillis(offsetsValidatedTime - startTime),\n nanosToMillis(consumerPreparedTime - offsetsValidatedTime),\n nanosToMillis(messagesConsumedTime - consumerPreparedTime),\n nanosToMillis(rolloversCompletedTime - messagesConsumedTime));\n }\n } else {\n LOG.info(\n \"Recovery task {} data no longer available in Kafka (validation time {}ms)\",\n recoveryTaskMetadata,\n nanosToMillis(offsetsValidatedTime - startTime));\n recoveryRecordsNoLongerAvailable.increment(\n recoveryTaskMetadata.endOffset - recoveryTaskMetadata.startOffset + 1);\n return true;\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testShouldHandleRecoveryTask() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "testShouldHandleRecoveryTask", "reference": " @Test\n public void testShouldHandleRecoveryTask() throws Exception {\n AstraConfigs.AstraConfig astraCfg = makeAstraConfig(TEST_S3_BUCKET);\n curatorFramework =\n CuratorBuilder.build(meterRegistry, astraCfg.getMetadataStoreConfig().getZookeeperConfig());\n\n // Start recovery service\n recoveryService = new RecoveryService(astraCfg, curatorFramework, meterRegistry, blobFs);\n recoveryService.startAsync();\n recoveryService.awaitRunning(DEFAULT_START_STOP_DURATION);\n\n // Populate data in Kafka so we can recover from it.\n final Instant startTime = Instant.now();\n produceMessagesToKafka(kafkaServer.getBroker(), startTime, TEST_KAFKA_TOPIC_1, 0);\n\n SnapshotMetadataStore snapshotMetadataStore = new SnapshotMetadataStore(curatorFramework);\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore).size()).isZero();\n // Start recovery\n RecoveryTaskMetadata recoveryTask =\n new RecoveryTaskMetadata(\"testRecoveryTask\", \"0\", 30, 60, Instant.now().toEpochMilli());\n assertThat(recoveryService.handleRecoveryTask(recoveryTask)).isTrue();\n List snapshots =\n AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore);\n assertThat(snapshots.size()).isEqualTo(1);\n assertThat(blobFs.listFiles(BlobFsUtils.createURI(TEST_S3_BUCKET, \"/\", \"\"), true)).isNotEmpty();\n assertThat(blobFs.exists(URI.create(snapshots.get(0).snapshotPath))).isTrue();\n assertThat(blobFs.listFiles(URI.create(snapshots.get(0).snapshotPath), false).length)\n .isGreaterThan(1);\n assertThat(getCount(MESSAGES_RECEIVED_COUNTER, meterRegistry)).isEqualTo(31);\n assertThat(getCount(MESSAGES_FAILED_COUNTER, meterRegistry)).isEqualTo(0);\n assertThat(getCount(ROLLOVERS_INITIATED, meterRegistry)).isEqualTo(1);\n assertThat(getCount(ROLLOVERS_COMPLETED, meterRegistry)).isEqualTo(1);\n assertThat(getCount(ROLLOVERS_FAILED, meterRegistry)).isEqualTo(0);\n }", "completions": [ "```java\n @Test\n public void testShouldHandleRecoveryTask() throws Exception {\n // Given\n RecoveryTaskMetadata recoveryTaskMetadata = new RecoveryTaskMetadata(\"testTask\", 0, 0L, 100L, System.currentTimeMillis());\n AstraKafkaConsumer mockKafkaConsumer = Mockito.mock(AstraKafkaConsumer.class);\n RecoveryChunkManager mockChunkManager = Mockito.mock(RecoveryChunkManager.class);\n Mockito.when(mockKafkaConsumer.prepConsumerForConsumption(Mockito.anyLong())).thenReturn(true);\n Mockito.when(mockKafkaConsumer.consumeMessagesBetweenOffsetsInParallel(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong())).thenReturn(true);\n Mockito.when(mockChunkManager.waitForRollOvers()).thenReturn(true);\n Mockito.when(mockKafkaConsumer.close()).thenReturn(true);\n Mockito.when(mockChunkManager.stopAsync()).thenReturn(true);\n Mockito.when(mockChunkManager.awaitTerminated(Mockito.anyLong())).thenReturn(true);\n Mockito.when(AstraKafkaConsumer.makeKafkaConfig(Mockito.any(), Mockito.anyInt())).thenReturn(new Properties());\n Mockito.when(RecoveryChunkManager.fromConfig(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(mockChunkManager);\n Mockito.when(adminClient.listConsumerGroupOffsets(Mockito.anyString())).thenReturn(new ConsumerGroupOffsets());\n Mockito.when(AstraConfig.getRecoveryConfig()).thenReturn(new RecoveryConfig());\n Mockito.when(AstraConfig.getRecoveryConfig().getKafkaConfig()).thenReturn(new KafkaConfig());\n Mockito.when(AstraConfig.getRecoveryConfig().getKafkaConfig().getKafkaTopic()).thenReturn(\"testTopic\");\n Mockito.when(AstraConfig.getIndexerConfig()).thenReturn(new IndexerConfig());\n Mockito.when(AstraConfig.getS3Config()).thenReturn(new S3Config());\n Mockito.when(meterRegistry.timer(Mockito.anyString())).thenReturn(Mockito.mock(Timer.class));\n Mockito.when(Timer.start(Mockito.any())).thenReturn(Mockito.mock(Timer.Sample.class));\n\n // When\n boolean result = handleRecoveryTask(recoveryTaskMetadata);\n\n // Then\n Assert.assertTrue(result);\n Mockito.verify(mockKafkaConsumer, Mockito.times(1)).prepConsumerForConsumption(Mockito.anyLong());\n Mockito.verify(mockKafkaConsumer, Mockito.times(1)).consumeMessagesBetweenOffsetsInParallel(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong());\n Mockito.verify(mockChunkManager, Mockito.times(1)).waitForRollOvers();\n Mockito.verify(mockKafkaConsumer, Mockito.times(1)).close();\n Mockito.verify(mockChunkManager, Mockito.times(1)).stopAsync();\n Mockito.verify(mockChunkManager, Mockito.times(1)).awaitTerminated(Mockito.anyLong());\n }\n```\n" ], "line": 97, "token": 544, "line_diff": 2, "token_diff": 2 }, { "id": 1, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @VisibleForTesting\n boolean handleRecoveryTask(RecoveryTaskMetadata recoveryTaskMetadata) {\n LOG.info(\"Started handling the recovery task: {}\", recoveryTaskMetadata);\n long startTime = System.nanoTime();\n Timer.Sample taskTimer = Timer.start(meterRegistry);\n\n PartitionOffsets partitionOffsets =\n validateKafkaOffsets(\n adminClient,\n recoveryTaskMetadata,\n AstraConfig.getRecoveryConfig().getKafkaConfig().getKafkaTopic());\n long offsetsValidatedTime = System.nanoTime();\n long consumerPreparedTime = 0, messagesConsumedTime = 0, rolloversCompletedTime = 0;\n\n if (partitionOffsets != null) {\n RecoveryTaskMetadata validatedRecoveryTask =\n new RecoveryTaskMetadata(\n recoveryTaskMetadata.name,\n recoveryTaskMetadata.partitionId,\n partitionOffsets.startOffset,\n partitionOffsets.endOffset,\n recoveryTaskMetadata.createdTimeEpochMs);\n\n if (partitionOffsets.startOffset != recoveryTaskMetadata.startOffset\n || recoveryTaskMetadata.endOffset != partitionOffsets.endOffset) {\n recoveryRecordsNoLongerAvailable.increment(\n (partitionOffsets.startOffset - recoveryTaskMetadata.startOffset)\n + (partitionOffsets.endOffset - recoveryTaskMetadata.endOffset));\n }\n\n try {\n RecoveryChunkManager chunkManager =\n RecoveryChunkManager.fromConfig(\n meterRegistry,\n searchMetadataStore,\n snapshotMetadataStore,\n AstraConfig.getIndexerConfig(),\n blobFs,\n AstraConfig.getS3Config());\n\n // Ingest data in parallel\n LogMessageWriterImpl logMessageWriterImpl = new LogMessageWriterImpl(chunkManager);\n AstraKafkaConsumer kafkaConsumer =\n new AstraKafkaConsumer(\n makeKafkaConfig(\n AstraConfig.getRecoveryConfig().getKafkaConfig(),\n validatedRecoveryTask.partitionId),\n logMessageWriterImpl,\n meterRegistry);\n\n kafkaConsumer.prepConsumerForConsumption(validatedRecoveryTask.startOffset);\n consumerPreparedTime = System.nanoTime();\n kafkaConsumer.consumeMessagesBetweenOffsetsInParallel(\n AstraKafkaConsumer.KAFKA_POLL_TIMEOUT_MS,\n validatedRecoveryTask.startOffset,\n validatedRecoveryTask.endOffset);\n messagesConsumedTime = System.nanoTime();\n // Wait for chunks to upload.\n boolean success = chunkManager.waitForRollOvers();\n rolloversCompletedTime = System.nanoTime();\n // Close the recovery chunk manager and kafka consumer.\n kafkaConsumer.close();\n chunkManager.stopAsync();\n chunkManager.awaitTerminated(DEFAULT_START_STOP_DURATION);\n LOG.info(\"Finished handling the recovery task: {}\", validatedRecoveryTask);\n taskTimer.stop(recoveryTaskTimerSuccess);\n return success;\n } catch (Exception ex) {\n LOG.error(\"Exception in recovery task [{}]: {}\", validatedRecoveryTask, ex);\n taskTimer.stop(recoveryTaskTimerFailure);\n return false;\n } finally {\n long endTime = System.nanoTime();\n LOG.info(\n \"Recovery task {} took {}ms, (subtask times offset validation {}, consumer prep {}, msg consumption {}, rollover {})\",\n recoveryTaskMetadata,\n nanosToMillis(endTime - startTime),\n nanosToMillis(offsetsValidatedTime - startTime),\n nanosToMillis(consumerPreparedTime - offsetsValidatedTime),\n nanosToMillis(messagesConsumedTime - consumerPreparedTime),\n nanosToMillis(rolloversCompletedTime - messagesConsumedTime));\n }\n } else {\n LOG.info(\n \"Recovery task {} data no longer available in Kafka (validation time {}ms)\",\n recoveryTaskMetadata,\n nanosToMillis(offsetsValidatedTime - startTime));\n recoveryRecordsNoLongerAvailable.increment(\n recoveryTaskMetadata.endOffset - recoveryTaskMetadata.startOffset + 1);\n return true;\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testShouldHandleRecoveryTaskFailure() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "testShouldHandleRecoveryTaskFailure", "reference": " @Test\n public void testShouldHandleRecoveryTaskFailure() throws Exception {\n String fakeS3Bucket = \"fakeBucket\";\n AstraConfigs.AstraConfig astraCfg = makeAstraConfig(fakeS3Bucket);\n curatorFramework =\n CuratorBuilder.build(meterRegistry, astraCfg.getMetadataStoreConfig().getZookeeperConfig());\n\n // Start recovery service\n recoveryService = new RecoveryService(astraCfg, curatorFramework, meterRegistry, blobFs);\n recoveryService.startAsync();\n recoveryService.awaitRunning(DEFAULT_START_STOP_DURATION);\n\n // Populate data in Kafka so we can recover from it.\n final Instant startTime = Instant.now();\n produceMessagesToKafka(kafkaServer.getBroker(), startTime, TEST_KAFKA_TOPIC_1, 0);\n\n assertThat(s3AsyncClient.listBuckets().get().buckets().size()).isEqualTo(1);\n assertThat(s3AsyncClient.listBuckets().get().buckets().get(0).name()).isEqualTo(TEST_S3_BUCKET);\n assertThat(s3AsyncClient.listBuckets().get().buckets().get(0).name())\n .isNotEqualTo(fakeS3Bucket);\n SnapshotMetadataStore snapshotMetadataStore = new SnapshotMetadataStore(curatorFramework);\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore).size()).isZero();\n\n // Start recovery\n RecoveryTaskMetadata recoveryTask =\n new RecoveryTaskMetadata(\"testRecoveryTask\", \"0\", 30, 60, Instant.now().toEpochMilli());\n assertThat(recoveryService.handleRecoveryTask(recoveryTask)).isFalse();\n\n assertThat(s3AsyncClient.listBuckets().get().buckets().size()).isEqualTo(1);\n assertThat(s3AsyncClient.listBuckets().get().buckets().get(0).name()).isEqualTo(TEST_S3_BUCKET);\n assertThat(s3AsyncClient.listBuckets().get().buckets().get(0).name())\n .isNotEqualTo(fakeS3Bucket);\n\n assertThat(getCount(MESSAGES_RECEIVED_COUNTER, meterRegistry)).isEqualTo(31);\n assertThat(getCount(MESSAGES_FAILED_COUNTER, meterRegistry)).isEqualTo(0);\n assertThat(getCount(ROLLOVERS_INITIATED, meterRegistry)).isEqualTo(1);\n assertThat(getCount(ROLLOVERS_COMPLETED, meterRegistry)).isEqualTo(0);\n assertThat(getCount(ROLLOVERS_FAILED, meterRegistry)).isEqualTo(1);\n }", "completions": [ "```java\n @Test\n public void testShouldHandleRecoveryTaskFailure() throws Exception {\n // Given\n RecoveryTaskMetadata recoveryTaskMetadata = new RecoveryTaskMetadata(\"testTask\", 0, 0L, 10L, System.currentTimeMillis());\n AstraKafkaConsumer mockKafkaConsumer = Mockito.mock(AstraKafkaConsumer.class);\n RecoveryChunkManager mockChunkManager = Mockito.mock(RecoveryChunkManager.class);\n Mockito.when(mockKafkaConsumer.prepConsumerForConsumption(Mockito.anyLong())).thenThrow(new RuntimeException(\"Test exception\"));\n Mockito.when(mockChunkManager.waitForRollOvers()).thenReturn(false);\n Mockito.when(mockKafkaConsumer.close()).thenThrow(new RuntimeException(\"Test exception\"));\n Mockito.when(mockChunkManager.stopAsync()).thenThrow(new RuntimeException(\"Test exception\"));\n Mockito.when(mockChunkManager.awaitTerminated(Mockito.anyLong())).thenThrow(new RuntimeException(\"Test exception\"));\n\n // When\n boolean result = handleRecoveryTask(recoveryTaskMetadata);\n\n // Then\n assertFalse(result);\n }\n```\n" ], "line": 97, "token": 544, "line_diff": 2, "token_diff": 2 }, { "id": 2, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public int migration(String srcTable, List uuids, String targetTable) {\n if (Objects.isNull(srcTable) || Objects.isNull(targetTable) || CollectionUtils.isEmpty(uuids)) {\n throw new SwValidationException(\n ValidSubject.EVALUATION, \"srcTable, targetTable and uuids must not be null\");\n }\n var filter = TableQueryFilter.builder()\n .operator(Operator.OR)\n .operands(uuids.stream()\n .map(uuid -> TableQueryFilter.builder()\n .operator(Operator.EQUAL)\n .operands(List.of(\n new TableQueryFilter.Column(KeyColumn),\n new TableQueryFilter.Constant(\n ColumnType.STRING, uuid)\n ))\n .build())\n .collect(Collectors.toList())\n )\n .build();\n return store.migration(DataStoreMigrationRequest.builder()\n .srcTableName(srcTable)\n .targetTableName(targetTable)\n .filter(filter)\n .build()\n );\n }\n```\n###test function signature:\n```java\n @Test\n public void testMigration()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testMigration", "reference": " @Test\n public void testMigration() {\n var srcTable = \"p/1/space/1/eval/summary\";\n var targetTable = \"p/1/eval/summary\";\n assertThrows(SwValidationException.class, () ->\n evaluationRepo.migration(null, List.of(\"uuid1\"), targetTable));\n assertThrows(SwValidationException.class, () ->\n evaluationRepo.migration(srcTable, null, targetTable));\n assertThrows(SwValidationException.class, () ->\n evaluationRepo.migration(srcTable, List.of(\"uuid1\"), null));\n\n evaluationRepo.migration(srcTable, List.of(\"uuid1\", \"uuid2\"), targetTable);\n\n verify(dataStore, times(1)).migration(\n DataStoreMigrationRequest.builder()\n .srcTableName(srcTable)\n .targetTableName(targetTable)\n .filter(\n TableQueryFilter.builder()\n .operator(Operator.OR)\n .operands(List.of(\n TableQueryFilter.builder()\n .operator(Operator.EQUAL)\n .operands(List.of(\n new TableQueryFilter.Column(KeyColumn),\n new TableQueryFilter.Constant(\n ColumnType.STRING, \"uuid1\")))\n .build(),\n TableQueryFilter.builder()\n .operator(Operator.EQUAL)\n .operands(List.of(\n new TableQueryFilter.Column(KeyColumn),\n new TableQueryFilter.Constant(\n ColumnType.STRING, \"uuid2\")))\n .build()))\n .build())\n .build()\n );\n }", "completions": [ "```java\n @Test\n public void testMigration() {\n // Given\n String srcTable = \"srcTable\";\n List uuids = Arrays.asList(\"uuid1\", \"uuid2\", \"uuid3\");\n String targetTable = \"targetTable\";\n DataStoreMigrationRequest expectedRequest = DataStoreMigrationRequest.builder()\n .srcTableName(srcTable)\n .targetTableName(targetTable)\n .filter(TableQueryFilter.builder()\n .operator(Operator.OR)\n .operands(uuids.stream()\n .map(uuid -> TableQueryFilter.builder()\n .operator(Operator.EQUAL)\n .operands(List.of(\n new TableQueryFilter.Column(KeyColumn),\n new TableQueryFilter.Constant(\n ColumnType.STRING, uuid)\n ))\n .build())\n .collect(Collectors.toList())\n )\n .build()\n )\n .build();\n when(store.migration(any(DataStoreMigrationRequest.class))).thenReturn(1);\n\n // When\n int result = migrationService.migration(srcTable, uuids, targetTable);\n\n // Then\n assertEquals(1, result);\n verify(store).migration(expectedRequest);\n }\n```\n" ], "line": 37, "token": 221, "line_diff": 0, "token_diff": 0 }, { "id": 3, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public void sendData(String database, String table, String content, boolean partitioned) throws Exception {\n final String loadUrl = String.format(\"http://%s:%s/api/%s/%s/_stream_load?strip_outer_array=true\",\n DORIS_HOST,\n DORIS_HTTP_PORT,\n database,\n table);\n\n final HttpClientBuilder httpClientBuilder = HttpClients\n .custom()\n .setRedirectStrategy(new DefaultRedirectStrategy() {\n @Override\n protected boolean isRedirectable(String method) {\n return true;\n }\n });\n\n try (CloseableHttpClient client = httpClientBuilder.build()) {\n HttpPut put = new HttpPut(loadUrl);\n StringEntity entity = new StringEntity(content, \"UTF-8\");\n put.setHeader(HttpHeaders.EXPECT, \"100-continue\");\n put.setHeader(HttpHeaders.AUTHORIZATION, HttpUtil.basicAuthHeader(DORIS_USER, DORIS_PASSWORD));\n put.setHeader(\"max_filter_ratio\", \"0.1\");\n if (partitioned) {\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyyMMdd\");\n put.setHeader(\"partitions\", \"p\" + simpleDateFormat.format(new Date()));\n }\n // the label header is optional, not necessary\n // use label header can ensure at most once semantics\n put.setEntity(entity);\n try (CloseableHttpResponse response = client.execute(put)) {\n String contentStr = new String(ByteStreams.toByteArray(response.getEntity().getContent()));\n JsonObject jsonObject = jsonParser.parse(contentStr).getAsJsonObject();\n log.info(\"result:{}\", contentStr);\n int statusCode = response.getStatusLine().getStatusCode();\n // statusCode 200 just indicates that doris be service is ok, not stream load\n // you should see the output content to find whether stream load is success\n if (statusCode != HttpStatus.SC_OK || (!jsonObject.get(\"Status\").getAsString().equalsIgnoreCase(\"SUCCESS\") &&\n !jsonObject.get(\"Status\").getAsString().equalsIgnoreCase(\"Publish Timeout\"))) {\n throw new IOException(\n String.format(\"Stream load failed, statusCode=%s load result=%s content=%s\", statusCode, jsonObject.toString(), content));\n }\n } catch (Exception e) {\n log.error(\"error\", e);\n } finally {\n client.close();\n }\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void sendDatasMapTest() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "sendDatasMapTest", "reference": " @Test\n public void sendDatasMapTest() throws Exception {\n String database = \"test\";\n String tableName = \"doris_test_db\";\n List> dataList = new ArrayList<>();\n for (int i = 0; i < 100; i++) {\n Map data = new HashMap<>();\n data.put(\"id\", i);\n data.put(\"name\", \"张三\");\n data.put(\"message\", \"股东风波的法规的规定翻跟斗广泛的给yryrtytr\");\n System.out.println(gson.toJson(data));\n dataList.add(data);\n\n }\n dorisStreamLoad.sendData(database, tableName, columnList, dataList);\n }", "completions": [ "```java\n @Test\n public void sendDataTest() throws Exception {\n String database = \"test_db\";\n String table = \"test_table\";\n String content = \"{\\\"columns\\\":[\\\"id\\\",\\\"name\\\",\\\"age\\\"],\\\"rows\\\":[[1,\\\"John\\\",25],[2,\\\"Jane\\\",30]]}\";\n boolean partitioned = true;\n\n sendData(database, table, content, partitioned);\n }\n```\n" ], "line": 57, "token": 486, "line_diff": 1, "token_diff": 2 }, { "id": 4, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public T clone(T object) {\n if (object instanceof String) {\n return object;\n } else if (object instanceof Collection) {\n Object firstElement = findFirstNonNullElement((Collection) object);\n if (firstElement != null && !(firstElement instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), firstElement.getClass());\n return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n } else if (object instanceof Map) {\n Map.Entry firstEntry = this.findFirstNonNullEntry((Map) object);\n if (firstEntry != null) {\n Object key = firstEntry.getKey();\n Object value = firstEntry.getValue();\n if (!(key instanceof Serializable) || !(value instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), key.getClass(), value.getClass());\n return (T) objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n }\n } else if (object instanceof JsonNode) {\n return (T) ((JsonNode) object).deepCopy();\n }\n\n if (object instanceof Serializable) {\n try {\n return (T) SerializationHelper.clone((Serializable) object);\n } catch (SerializationException e) {\n //it is possible that object itself implements java.io.Serializable, but underlying structure does not\n //in this case we switch to the other JSON marshaling strategy which doesn't use the Java serialization\n }\n }\n\n return jsonClone(object);\n }\n```\n###test function signature:\n```java\n @Test\n public void should_clone_map_of_serializable_key_and_value()\n```\n### Answer: (use the provided format with backticks)\n", "name": "should_clone_map_of_serializable_key_and_value", "reference": " @Test\n public void should_clone_map_of_serializable_key_and_value() {\n Map original = new HashMap<>();\n original.put(\"key\", new SerializableObject(\"value\"));\n Object cloned = serializer.clone(original);\n assertEquals(original, cloned);\n assertNotSame(original, cloned);\n }", "completions": [ "```java\n @Test\n public void should_clone_map_of_serializable_key_and_value() {\n Map originalMap = new HashMap<>();\n originalMap.put(\"one\", 1);\n originalMap.put(\"two\", 2);\n originalMap.put(\"three\", 3);\n\n Map clonedMap = clone(originalMap);\n\n assertNotSame(originalMap, clonedMap);\n assertEquals(originalMap, clonedMap);\n }\n```\n" ], "line": 44, "token": 358, "line_diff": 1, "token_diff": 1 }, { "id": 5, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public void encode(String schemaName, long nextTransactionOffset) {\n if (schemaName == null) {\n schemaName = UNKNOWN;\n }\n this.schemaName = schemaName;\n this.nextTransactionOffset = nextTransactionOffset;\n final byte[] payloadBytes = payloadToBytes();\n final int payloadLength = payloadBytes.length;\n\n // set logEventHeader\n int eventSize = eventHeaderLengthVersionGt1 + payloadLength;\n setLogEventHeader(new LogEventHeader(drc_filter_log_event.getType(), 0, eventSize, nextTransactionOffset)\n );\n\n // set payload\n final ByteBuf payloadByteBuf = PooledByteBufAllocator.DEFAULT.directBuffer(payloadLength);\n payloadByteBuf.writeBytes(payloadBytes);\n payloadByteBuf.skipBytes(payloadLength);\n setPayloadBuf(payloadByteBuf);\n }\n```\n###test function signature:\n```java\n @Test\n public void encode()\n```\n### Answer: (use the provided format with backticks)\n", "name": "encode", "reference": " @Test\n public void encode() {\n FilterLogEvent filterLogEvent = new FilterLogEvent();\n filterLogEvent.encode(\"drc1\", 101);\n Assert.assertEquals(\"drc1\", filterLogEvent.getSchemaName());\n Assert.assertEquals(101, filterLogEvent.getNextTransactionOffset());\n\n ByteBuf headerBuf = filterLogEvent.getLogEventHeader().getHeaderBuf();\n headerBuf.readerIndex(0);\n ByteBuf payloadBuf = filterLogEvent.getPayloadBuf();\n payloadBuf.readerIndex(0);\n CompositeByteBuf compositeByteBuf = PooledByteBufAllocator.DEFAULT.compositeDirectBuffer();\n compositeByteBuf.addComponents(true, headerBuf, payloadBuf);\n\n FilterLogEvent newFilterLogEvent = new FilterLogEvent();\n newFilterLogEvent.read(compositeByteBuf);\n compositeByteBuf.release(compositeByteBuf.refCnt());\n Assert.assertEquals(\"drc1\", newFilterLogEvent.getSchemaName());\n Assert.assertEquals(101, newFilterLogEvent.getNextTransactionOffset());\n }", "completions": [ "```java\n @Test\n public void encode() {\n // Given\n String schemaName = \"testSchema\";\n long nextTransactionOffset = 1234567890L;\n drc_filter_log_event event = new drc_filter_log_event();\n\n // When\n event.encode(schemaName, nextTransactionOffset);\n\n // Then\n assertEquals(schemaName, event.getSchemaName());\n assertEquals(nextTransactionOffset, event.getNextTransactionOffset());\n assertEquals(drc_filter_log_event.getType(), event.getLogEventHeader().getType());\n assertEquals(0, event.getLogEventHeader().getServerId());\n assertEquals(eventHeaderLengthVersionGt1 + event.getPayloadBuf().readableBytes(), event.getLogEventHeader().getEventLength());\n assertEquals(nextTransactionOffset, event.getLogEventHeader().getNextTransactionOffset());\n assertEquals(event.getPayloadBuf().readableBytes(), event.getPayloadBuf().readableBytes());\n }\n```\n" ], "line": 29, "token": 183, "line_diff": 0, "token_diff": 0 }, { "id": 6, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public void put(String path, long position, ByteBuf data) {\n writeLock.lock();\n try {\n int dataLength = data.readableBytes();\n NavigableMap cache = path2cache.computeIfAbsent(path, k -> new TreeMap<>());\n Map.Entry pos2value = cache.floorEntry(position);\n long cacheStartPosition;\n Value value;\n if (pos2value == null || pos2value.getKey() + pos2value.getValue().dataLength < position) {\n cacheStartPosition = position;\n value = Value.EMPTY;\n } else {\n cacheStartPosition = pos2value.getKey();\n value = pos2value.getValue();\n }\n // ensure the capacity, if the capacity change then update the cache index\n int moreCapacity = (int) ((position + dataLength) - (cacheStartPosition + value.blocks.length * (long) blockSize));\n int newDataLength = (int) (position + dataLength - cacheStartPosition);\n if (moreCapacity > 0) {\n int[] blocks = ensureCapacity(cacheStartPosition, moreCapacity);\n if (blocks == null) {\n return;\n }\n int[] newBlocks = new int[value.blocks.length + blocks.length];\n System.arraycopy(value.blocks, 0, newBlocks, 0, value.blocks.length);\n System.arraycopy(blocks, 0, newBlocks, value.blocks.length, blocks.length);\n value = new Value(newBlocks, newDataLength);\n } else {\n value = new Value(value.blocks, newDataLength);\n }\n cache.put(cacheStartPosition, value);\n lru.put(new Key(path, cacheStartPosition), value);\n\n // write data to cache\n ByteBuffer cacheByteBuffer = this.cacheByteBuffer.duplicate();\n int positionDelta = (int) (position - cacheStartPosition);\n int written = 0;\n ByteBuffer[] nioBuffers = data.nioBuffers();\n int[] blocks = value.blocks;\n for (ByteBuffer nioBuffer : nioBuffers) {\n ByteBuf buf = Unpooled.wrappedBuffer(nioBuffer);\n while (buf.readableBytes() > 0) {\n int writePosition = positionDelta + written;\n int block = blocks[writePosition / blockSize];\n cacheByteBuffer.position(block * blockSize + writePosition % blockSize);\n int length = Math.min(buf.readableBytes(), blockSize - writePosition % blockSize);\n cacheByteBuffer.put(buf.slice(buf.readerIndex(), length).nioBuffer());\n buf.skipBytes(length);\n written += length;\n }\n }\n } finally {\n writeLock.unlock();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testMergePut() throws IOException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testMergePut", "reference": " @Test\n public void testMergePut() throws IOException {\n FileCache fileCache = new FileCache(\"/tmp/file_cache_test\", 10 * 1024, 1024);\n {\n CompositeByteBuf buf = Unpooled.compositeBuffer();\n buf.addComponent(true, genBuf((byte) 1, 500));\n buf.addComponent(true, genBuf((byte) 2, 500));\n buf.addComponent(true, genBuf((byte) 3, 500));\n fileCache.put(\"test\", 3333L, buf);\n }\n assertEquals(1, fileCache.path2cache.get(\"test\").size());\n assertEquals(1500, fileCache.path2cache.get(\"test\").get(3333L).dataLength);\n {\n CompositeByteBuf buf = Unpooled.compositeBuffer();\n buf.addComponent(true, genBuf((byte) 4, 500));\n buf.addComponent(true, genBuf((byte) 5, 500));\n buf.addComponent(true, genBuf((byte) 6, 500));\n fileCache.put(\"test\", 3333L + 1000, buf);\n }\n assertEquals(1, fileCache.path2cache.get(\"test\").size());\n assertEquals(2500, fileCache.path2cache.get(\"test\").get(3333L).dataLength);\n {\n CompositeByteBuf buf = Unpooled.compositeBuffer();\n buf.addComponent(true, genBuf((byte) 7, 500));\n fileCache.put(\"test\", 3333L + 1000 + 1500, buf);\n }\n assertEquals(1, fileCache.path2cache.get(\"test\").size());\n assertEquals(3000, fileCache.path2cache.get(\"test\").get(3333L).dataLength);\n\n assertTrue(verify(fileCache.get(\"test\", 3333L, 500).get(), (byte) 1));\n assertTrue(verify(fileCache.get(\"test\", 3333L + 500, 500).get(), (byte) 2));\n assertTrue(verify(fileCache.get(\"test\", 3333L + 1000, 500).get(), (byte) 4));\n assertTrue(verify(fileCache.get(\"test\", 3333L + 1500, 500).get(), (byte) 5));\n assertTrue(verify(fileCache.get(\"test\", 3333L + 2000, 500).get(), (byte) 6));\n assertTrue(verify(fileCache.get(\"test\", 3333L + 2500, 500).get(), (byte) 7));\n }", "completions": [ "```java\n @Test\n public void testMergePut() throws IOException {\n // Given\n String path = \"/test/path\";\n long position = 100;\n ByteBuf data = Unpooled.wrappedBuffer(new byte[]{1, 2, 3, 4, 5});\n\n // When\n cache.put(path, position, data);\n\n // Then\n NavigableMap cacheMap = cache.path2cache.get(path);\n assertNotNull(cacheMap);\n Map.Entry entry = cacheMap.floorEntry(position);\n assertNotNull(entry);\n assertEquals(position, entry.getKey().longValue());\n assertEquals(5, entry.getValue().dataLength);\n assertEquals(1, entry.getValue().blocks[0]);\n assertEquals(2, entry.getValue().blocks[1]);\n assertEquals(3, entry.getValue().blocks[2]);\n assertEquals(4, entry.getValue().blocks[3]);\n assertEquals(5, entry.getValue().blocks[4]);\n }\n```\n" ], "line": 65, "token": 508, "line_diff": 2, "token_diff": 2 }, { "id": 7, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public SearchResult search(\n String dataset,\n String queryStr,\n Long startTimeMsEpoch,\n Long endTimeMsEpoch,\n int howMany,\n AggBuilder aggBuilder) {\n\n ensureNonEmptyString(dataset, \"dataset should be a non-empty string\");\n ensureNonNullString(queryStr, \"query should be a non-empty string\");\n if (startTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch >= 0, \"start time should be non-negative value\");\n }\n if (startTimeMsEpoch != null && endTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch < endTimeMsEpoch, \"end time should be greater than start time\");\n }\n ensureTrue(howMany >= 0, \"hits requested should not be negative.\");\n ensureTrue(howMany > 0 || aggBuilder != null, \"Hits or aggregation should be requested.\");\n\n ScopedSpan span = Tracing.currentTracer().startScopedSpan(\"LogIndexSearcherImpl.search\");\n span.tag(\"dataset\", dataset);\n span.tag(\"startTimeMsEpoch\", String.valueOf(startTimeMsEpoch));\n span.tag(\"endTimeMsEpoch\", String.valueOf(endTimeMsEpoch));\n span.tag(\"howMany\", String.valueOf(howMany));\n\n Stopwatch elapsedTime = Stopwatch.createStarted();\n try {\n // Acquire an index searcher from searcher manager.\n // This is a useful optimization for indexes that are static.\n IndexSearcher searcher = searcherManager.acquire();\n\n Query query =\n openSearchAdapter.buildQuery(\n dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, searcher);\n try {\n List results;\n InternalAggregation internalAggregation = null;\n\n if (howMany > 0) {\n CollectorManager topFieldCollector =\n buildTopFieldCollector(howMany, aggBuilder != null ? Integer.MAX_VALUE : howMany);\n MultiCollectorManager collectorManager;\n if (aggBuilder != null) {\n collectorManager =\n new MultiCollectorManager(\n topFieldCollector,\n openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n } else {\n collectorManager = new MultiCollectorManager(topFieldCollector);\n }\n Object[] collector = searcher.search(query, collectorManager);\n\n ScoreDoc[] hits = ((TopFieldDocs) collector[0]).scoreDocs;\n results = new ArrayList<>(hits.length);\n for (ScoreDoc hit : hits) {\n results.add(buildLogMessage(searcher, hit));\n }\n if (aggBuilder != null) {\n internalAggregation = (InternalAggregation) collector[1];\n }\n } else {\n results = Collections.emptyList();\n internalAggregation =\n searcher.search(\n query, openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n }\n\n elapsedTime.stop();\n return new SearchResult<>(\n results, elapsedTime.elapsed(TimeUnit.MICROSECONDS), 0, 0, 1, 1, internalAggregation);\n } finally {\n searcherManager.release(searcher);\n }\n } catch (IOException e) {\n span.error(e);\n throw new IllegalArgumentException(\"Failed to acquire an index searcher.\", e);\n } finally {\n span.finish();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testSearchById()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testSearchById", "reference": " @Test\n public void testSearchById() {\n Instant time = Instant.now();\n loadTestData(time);\n SearchResult index =\n strictLogStore.logSearcher.search(\n TEST_DATASET_NAME,\n \"_id:Message1\",\n time.toEpochMilli(),\n time.plusSeconds(2).toEpochMilli(),\n 10,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"));\n assertThat(index.hits.size()).isEqualTo(1);\n }", "completions": [ "```java\n @Test\n public void testSearchById() {\n // Given\n String dataset = \"testDataset\";\n String queryStr = \"testQuery\";\n Long startTimeMsEpoch = 1577836800000L; // 2020-01-01 00:00:00\n Long endTimeMsEpoch = 1577923199000L; // 2020-01-02 23:59:59\n int howMany = 10;\n AggBuilder aggBuilder = new AggBuilder();\n\n // When\n SearchResult result = logIndexSearcher.search(dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, howMany, aggBuilder);\n\n // Then\n assertNotNull(result);\n assertEquals(howMany, result.getResults().size());\n assertTrue(result.getElapsedTimeMicros() > 0);\n assertEquals(0, result.getTotalHits());\n assertEquals(0, result.getFailedShards());\n assertEquals(1, result.getSuccessfulShards());\n assertNotNull(result.getAggregation());\n }\n```\n" ], "line": 85, "token": 606, "line_diff": 2, "token_diff": 2 }, { "id": 8, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public SendStatus sendHtmlMail(String subject, List toList, String username, String agentName, String emailHref, String maiContent) {\n SendStatus sendStatus = new SendStatus(SEND_STATUS_FALSE, \"\");\n List notInBlacklistAddress = checkNotInBlacklistAddress(toList,sendStatus);\n if(CollectionUtils.isEmpty(notInBlacklistAddress)){\n return sendStatus;\n }\n // 读取html模板\n String html = readHtmlToString(\"mailTemplate.html\");\n\n // 写入模板内容\n Document doc = Jsoup.parse(html);\n doc.getElementById(\"username\").html(username);\n\n if (StringUtils.isEmpty(agentName)) {\n sendStatus.setErrorMessage(\"agentName 为空\");\n return sendStatus;\n }\n doc.getElementById(\"sysName\").html(\"Your Agent:\");\n doc.getElementById(\"agentName\").html(agentName);\n doc.getElementById(\"mailContent\").html(maiContent);\n doc.getElementById(\"clickHref\").attr(\"href\", emailHref);\n\n String result = doc.toString();\n Properties props = new Properties();\n props.put(\"mail.smtp.host\", \"\");\n props.put(\"mail.smtp.auth\", \"true\");\n props.put(\"mail.smtp.socketFactory.class\", \"javax.net.ssl.SSLSocketFactory\");\n props.put(\"mail.smtp.socketFactory.fallback\", \"true\");\n Session session = Session.getDefaultInstance(props);\n session.setDebug(true);\n\n Transport transport = null;\n MimeMessage message = new MimeMessage(session);\n try {\n //初始化发送邮件配置\n this.initMailConfig();\n message.setFrom(new InternetAddress(this.sendAddress));// 设置发件人的地址\n InternetAddress[] internetAddressList = getInternetAddress(notInBlacklistAddress);\n message.setRecipients(Message.RecipientType.TO, internetAddressList);// 设置收件人,并设置其接收类型为TO\n message.setSubject(subject);// 设置标题\n message.setContent(result, \"text/html;charset=UTF-8\"); // 设置邮件内容类型为html\n message.setSentDate(new Date());// 设置发信时间\n message.saveChanges();// 存储邮件信息\n\n // 发送邮件\n transport = session.getTransport(\"smtp\");\n if (null != port) {\n transport.connect(host, port, user, password);\n } else {\n transport.connect(host, user, password);\n }\n transport.sendMessage(message, message.getAllRecipients());\n\n //发送邮件成功,status置为true\n sendStatus.setStatus(\"true\");\n } catch (Exception e) {\n log.error(\"邮件发送异常\", e);\n sendStatus.setErrorMessage(e.getMessage());\n } finally {\n if (null != transport) {\n try {\n transport.close();//关闭连接\n } catch (MessagingException e) {\n log.error(\"发送邮件 ,transport 关闭异常\", e);\n }\n }\n }\n return sendStatus;\n }\n```\n###test function signature:\n```java\n @Test\n void testSendHtmlMail_subjectNotNull_notInBlacklistAddressIsNull()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testSendHtmlMail_subjectNotNull_notInBlacklistAddressIsNull", "reference": " @Test\n void testSendHtmlMail_subjectNotNull_notInBlacklistAddressIsNull(){\n when(blacklistService.inBlacklist(anyString())).thenReturn(true);\n List addressList = new ArrayList<>();\n addressList.add(\"test@qq.com\");\n SendStatus result = mailUtils.sendHtmlMail(\"\",addressList,\"test\",\"test\",\"test\",\"test\");\n Assertions.assertEquals(\"false\",result.getStatus());\n Assertions.assertTrue(result.getErrorMessage().contains(\"blacklist\"));\n }", "completions": [ "```java\n @Test\n void testSendHtmlMail_subjectNotNull_notInBlacklistAddressIsNull() {\n // Arrange\n String subject = \"Test Subject\";\n List toList = new ArrayList<>();\n String username = \"Test User\";\n String agentName = \"Test Agent\";\n String emailHref = \"http://test.com\";\n String maiContent = \"Test Content\";\n\n // Act\n SendStatus result = mailService.sendHtmlMail(subject, toList, username, agentName, emailHref, maiContent);\n\n // Assert\n assertEquals(SEND_STATUS_FALSE, result.getStatus());\n assertEquals(\"\", result.getErrorMessage());\n }\n```\n" ], "line": 74, "token": 533, "line_diff": 2, "token_diff": 2 }, { "id": 9, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public T clone(T object) {\n if (object instanceof String) {\n return object;\n } else if (object instanceof Collection) {\n Object firstElement = findFirstNonNullElement((Collection) object);\n if (firstElement != null && !(firstElement instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), firstElement.getClass());\n return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n } else if (object instanceof Map) {\n Map.Entry firstEntry = this.findFirstNonNullEntry((Map) object);\n if (firstEntry != null) {\n Object key = firstEntry.getKey();\n Object value = firstEntry.getValue();\n if (!(key instanceof Serializable) || !(value instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), key.getClass(), value.getClass());\n return (T) objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n }\n } else if (object instanceof JsonNode) {\n return (T) ((JsonNode) object).deepCopy();\n }\n\n if (object instanceof Serializable) {\n try {\n return (T) SerializationHelper.clone((Serializable) object);\n } catch (SerializationException e) {\n //it is possible that object itself implements java.io.Serializable, but underlying structure does not\n //in this case we switch to the other JSON marshaling strategy which doesn't use the Java serialization\n }\n }\n\n return jsonClone(object);\n }\n```\n###test function signature:\n```java\n @Test\n public void should_clone_serializable_object()\n```\n### Answer: (use the provided format with backticks)\n", "name": "should_clone_serializable_object", "reference": " @Test\n public void should_clone_serializable_object() {\n Object original = new SerializableObject(\"value\");\n Object cloned = serializer.clone(original);\n assertEquals(original, cloned);\n assertNotSame(original, cloned);\n }", "completions": [ "```java\n @Test\n public void should_clone_serializable_object() {\n // Given\n Serializable object = new Serializable() {\n private static final long serialVersionUID = 1L;\n // Implement necessary methods\n };\n\n // When\n Serializable clonedObject = objectCloner.clone(object);\n\n // Then\n assertNotSame(object, clonedObject);\n assertEquals(object, clonedObject);\n }\n```\n" ], "line": 44, "token": 358, "line_diff": 1, "token_diff": 1 }, { "id": 10, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n\tpublic Embedding embedText(String text) {\n\t\tAssert.hasText(text, \"The text can not be null or empty.\");\n\n\t\t@JsonInclude(Include.NON_NULL)\n\t\trecord EmbeddingResponse(Embedding embedding) {\n\t\t}\n\n\t\tEmbeddingResponse response = this.restClient.post()\n\t\t\t\t.uri(\"/models/{model}:embedText?key={apiKey}\", this.embeddingModel, this.apiKey)\n\t\t\t\t.body(Map.of(\"text\", text))\n\t\t\t\t.retrieve()\n\t\t\t\t.body(EmbeddingResponse.class);\n\n\t\treturn response != null ? response.embedding() : null;\n\t}\n```\n###test function signature:\n```java\n\t@Test\n\tpublic void embedText()\n```\n### Answer: (use the provided format with backticks)\n", "name": "embedText", "reference": "\t@Test\n\tpublic void embedText() {\n\n\t\tvar text = \"Hello, how are you?\";\n\n\t\tEmbedding response = vertexAiPaLm2Api.embedText(text);\n\n\t\tassertThat(response).isNotNull();\n\t\tassertThat(response.value()).hasSize(768);\n\t}", "completions": [ "```java\n\t@Test\n\tpublic void embedText() {\n\t\tString text = \"This is a test text.\";\n\t\tEmbedding expectedEmbedding = new Embedding(new double[] {0.1, 0.2, 0.3});\n\n\t\twhen(this.restClient.post()\n\t\t\t\t.uri(\"/models/{model}:embedText?key={apiKey}\", this.embeddingModel, this.apiKey)\n\t\t\t\t.body(Map.of(\"text\", text))\n\t\t\t\t.retrieve()\n\t\t\t\t.body(EmbeddingResponse.class)).thenReturn(new EmbeddingResponse(expectedEmbedding));\n\n\t\tEmbedding actualEmbedding = this.embeddingService.embedText(text);\n\n\t\tassertEquals(expectedEmbedding, actualEmbedding);\n\t}\n```\n" ], "line": 23, "token": 177, "line_diff": 0, "token_diff": 0 }, { "id": 11, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static Optional maybeFetchErrorIntervalMs(short errorCode, int intervalMs) {\n if (errorCode == Errors.NONE.code())\n return Optional.empty();\n\n int pushIntervalMs;\n String reason;\n\n Errors error = Errors.forCode(errorCode);\n switch (error) {\n case INVALID_REQUEST:\n case INVALID_RECORD:\n case UNSUPPORTED_VERSION:\n pushIntervalMs = Integer.MAX_VALUE;\n reason = \"The broker response indicates the client sent an request that cannot be resolved\"\n + \" by re-trying, hence disable telemetry\";\n break;\n case UNKNOWN_SUBSCRIPTION_ID:\n case UNSUPPORTED_COMPRESSION_TYPE:\n pushIntervalMs = 0;\n reason = error.message();\n break;\n case TELEMETRY_TOO_LARGE:\n case THROTTLING_QUOTA_EXCEEDED:\n reason = error.message();\n pushIntervalMs = (intervalMs != -1) ? intervalMs : ClientTelemetryReporter.DEFAULT_PUSH_INTERVAL_MS;\n break;\n default:\n reason = \"Unwrapped error code\";\n log.error(\"Error code: {}. Unmapped error for telemetry, disable telemetry.\", errorCode);\n pushIntervalMs = Integer.MAX_VALUE;\n }\n\n log.debug(\"Error code: {}, reason: {}. Push interval update to {} ms.\", errorCode, reason, pushIntervalMs);\n return Optional.of(pushIntervalMs);\n }\n```\n###test function signature:\n```java\n @Test\n public void testMaybeFetchErrorIntervalMs()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testMaybeFetchErrorIntervalMs", "reference": " @Test\n public void testMaybeFetchErrorIntervalMs() {\n assertEquals(Optional.empty(), ClientTelemetryUtils.maybeFetchErrorIntervalMs(Errors.NONE.code(), -1));\n assertEquals(Optional.of(Integer.MAX_VALUE), ClientTelemetryUtils.maybeFetchErrorIntervalMs(Errors.INVALID_REQUEST.code(), -1));\n assertEquals(Optional.of(Integer.MAX_VALUE), ClientTelemetryUtils.maybeFetchErrorIntervalMs(Errors.INVALID_RECORD.code(), -1));\n assertEquals(Optional.of(0), ClientTelemetryUtils.maybeFetchErrorIntervalMs(Errors.UNKNOWN_SUBSCRIPTION_ID.code(), -1));\n assertEquals(Optional.of(0), ClientTelemetryUtils.maybeFetchErrorIntervalMs(Errors.UNSUPPORTED_COMPRESSION_TYPE.code(), -1));\n assertEquals(Optional.of(ClientTelemetryReporter.DEFAULT_PUSH_INTERVAL_MS), ClientTelemetryUtils.maybeFetchErrorIntervalMs(Errors.TELEMETRY_TOO_LARGE.code(), -1));\n assertEquals(Optional.of(20000), ClientTelemetryUtils.maybeFetchErrorIntervalMs(Errors.TELEMETRY_TOO_LARGE.code(), 20000));\n assertEquals(Optional.of(ClientTelemetryReporter.DEFAULT_PUSH_INTERVAL_MS), ClientTelemetryUtils.maybeFetchErrorIntervalMs(Errors.THROTTLING_QUOTA_EXCEEDED.code(), -1));\n assertEquals(Optional.of(20000), ClientTelemetryUtils.maybeFetchErrorIntervalMs(Errors.THROTTLING_QUOTA_EXCEEDED.code(), 20000));\n assertEquals(Optional.of(Integer.MAX_VALUE), ClientTelemetryUtils.maybeFetchErrorIntervalMs(Errors.UNKNOWN_SERVER_ERROR.code(), -1));\n }", "completions": [ "```java\n @Test\n public void testMaybeFetchErrorIntervalMs() {\n // Test case 1: errorCode is Errors.NONE.code()\n short errorCode = Errors.NONE.code();\n int intervalMs = 1000;\n Optional result = maybeFetchErrorIntervalMs(errorCode, intervalMs);\n assertFalse(result.isPresent());\n\n // Test case 2: errorCode is Errors.INVALID_REQUEST.code()\n errorCode = Errors.INVALID_REQUEST.code();\n result = maybeFetchErrorIntervalMs(errorCode, intervalMs);\n assertTrue(result.isPresent());\n assertEquals(Integer.MAX_VALUE, result.get().intValue());\n\n // Test case 3: errorCode is Errors.UNKNOWN_SUBSCRIPTION_ID.code()\n errorCode = Errors.UNKNOWN_SUBSCRIPTION_ID.code();\n result = maybeFetchErrorIntervalMs(errorCode, intervalMs);\n assertTrue(result.isPresent());\n assertEquals(0, result.get().intValue());\n\n // Test case 4: errorCode is Errors.TELEMETRY_TOO_LARGE.code()\n errorCode = Errors.TELEMETRY_TOO_LARGE.code();\n result = maybeFetchErrorIntervalMs(errorCode, intervalMs);\n assertTrue(result.isPresent());\n assertEquals(intervalMs, result.get().intValue());\n\n // Test case 5: errorCode is Errors.THROTTLING_QUOTA_EXCEEDED.code()\n errorCode = Errors.THROTTLING_QUOTA_EXCEEDED.code();\n result = maybeFetchErrorIntervalMs(errorCode, intervalMs);\n assertTrue(result.isPresent());\n assertEquals(intervalMs, result.get().intValue());\n\n // Test case 6: errorCode is Errors.UNSUPPORTED_COMPRESSION_TYPE.code()\n errorCode = Errors.UNSUPPORTED_COMPRESSION_TYPE.code();\n result = maybeFetchErrorIntervalMs(errorCode, intervalMs);\n assertTrue(result.isPresent());\n assertEquals(0, result.get().intValue());\n\n // Test case 7: errorCode is Errors.INVALID_RECORD.code()\n errorCode = Errors.INVALID_RECORD.code();\n result = maybeFetchErrorIntervalMs(errorCode, intervalMs);\n assertTrue(result.isPresent());\n assertEquals(Integer.MAX_VALUE, result.get().intValue());\n\n // Test case 8: errorCode is Errors.UNSUPPORTED_VERSION.code()\n errorCode = Errors.UNSUPPORTED_VERSION.code();\n result = maybeFetchErrorIntervalMs(errorCode, intervalMs);\n assertTrue(result.isPresent());\n assertEquals(Integer.MAX_VALUE, result.get().intValue());\n\n // Test case 9: errorCode is an unmapped error\n errorCode = (short) 9999;\n result = maybeFetchErrorIntervalMs(errorCode, intervalMs);\n assertTrue(result.isPresent());\n assertEquals(Integer.MAX_VALUE, result.get().intValue());\n }\n```\n" ], "line": 43, "token": 290, "line_diff": 1, "token_diff": 1 }, { "id": 12, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public T clone(T object) {\n if (object instanceof String) {\n return object;\n } else if (object instanceof Collection) {\n Object firstElement = findFirstNonNullElement((Collection) object);\n if (firstElement != null && !(firstElement instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), firstElement.getClass());\n return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n } else if (object instanceof Map) {\n Map.Entry firstEntry = this.findFirstNonNullEntry((Map) object);\n if (firstEntry != null) {\n Object key = firstEntry.getKey();\n Object value = firstEntry.getValue();\n if (!(key instanceof Serializable) || !(value instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), key.getClass(), value.getClass());\n return (T) objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n }\n } else if (object instanceof JsonNode) {\n return (T) ((JsonNode) object).deepCopy();\n }\n\n if (object instanceof Serializable) {\n try {\n return (T) SerializationHelper.clone((Serializable) object);\n } catch (SerializationException e) {\n //it is possible that object itself implements java.io.Serializable, but underlying structure does not\n //in this case we switch to the other JSON marshaling strategy which doesn't use the Java serialization\n }\n }\n\n return jsonClone(object);\n }\n```\n###test function signature:\n```java\n @Test\n public void should_clone_non_serializable_object()\n```\n### Answer: (use the provided format with backticks)\n", "name": "should_clone_non_serializable_object", "reference": " @Test\n public void should_clone_non_serializable_object() {\n Object original = new NonSerializableObject(\"value\");\n Object cloned = serializer.clone(original);\n assertEquals(original, cloned);\n assertNotSame(original, cloned);\n }", "completions": [ "```java\n @Test\n public void should_clone_non_serializable_object() {\n // Given\n Map nonSerializableMap = new HashMap<>();\n nonSerializableMap.put(\"key1\", new Object());\n nonSerializableMap.put(\"key2\", new Object());\n\n // When\n Map clonedMap = objectCloner.clone(nonSerializableMap);\n\n // Then\n assertNotSame(nonSerializableMap, clonedMap);\n assertNotSame(nonSerializableMap.get(\"key1\"), clonedMap.get(\"key1\"));\n assertNotSame(nonSerializableMap.get(\"key2\"), clonedMap.get(\"key2\"));\n }\n```\n" ], "line": 44, "token": 358, "line_diff": 1, "token_diff": 1 }, { "id": 13, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @VisibleForTesting\n public ListenableFuture queue(ExecuteEntry executeEntry, Poller poller, Duration timeout) {\n ExecuteOperationMetadata metadata =\n ExecuteOperationMetadata.newBuilder()\n .setActionDigest(executeEntry.getActionDigest())\n .setStdoutStreamName(executeEntry.getStdoutStreamName())\n .setStderrStreamName(executeEntry.getStderrStreamName())\n .build();\n Operation operation =\n Operation.newBuilder()\n .setName(executeEntry.getOperationName())\n .setMetadata(Any.pack(metadata))\n .build();\n Digest actionDigest = executeEntry.getActionDigest();\n ActionKey actionKey = DigestUtil.asActionKey(actionDigest);\n\n Stopwatch stopwatch = Stopwatch.createStarted();\n ListenableFuture cachedResultFuture;\n if (executeEntry.getSkipCacheLookup()) {\n cachedResultFuture = immediateFuture(false);\n } else {\n cachedResultFuture =\n checkCacheFuture(actionKey, operation, executeEntry.getRequestMetadata());\n }\n return transformAsync(\n cachedResultFuture,\n (cachedResult) -> {\n if (cachedResult) {\n poller.pause();\n long checkCacheUSecs = stopwatch.elapsed(MICROSECONDS);\n log.log(\n Level.FINER,\n format(\n \"ServerInstance(%s): checkCache(%s): %sus elapsed\",\n getName(), operation.getName(), checkCacheUSecs));\n return IMMEDIATE_VOID_FUTURE;\n }\n return transformAndQueue(executeEntry, poller, operation, stopwatch, timeout);\n },\n operationTransformService);\n }\n```\n###test function signature:\n```java\n @Test\n public void queueOperationCompletesOperationWithCachedActionResult() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "queueOperationCompletesOperationWithCachedActionResult", "reference": " @Test\n public void queueOperationCompletesOperationWithCachedActionResult() throws Exception {\n ActionKey actionKey = DigestUtil.asActionKey(Digest.newBuilder().setHash(\"test\").build());\n ExecuteEntry executeEntry =\n ExecuteEntry.newBuilder()\n .setOperationName(\"operation-with-cached-action-result\")\n .setActionDigest(actionKey.getDigest())\n .build();\n\n ActionResult actionResult = ActionResult.getDefaultInstance();\n\n when(mockBackplane.getActionResult(eq(actionKey))).thenReturn(actionResult);\n\n Poller poller = mock(Poller.class);\n\n instance.queue(executeEntry, poller, DEFAULT_TIMEOUT).get();\n\n verify(mockBackplane, times(1)).putOperation(any(Operation.class), eq(CACHE_CHECK));\n verify(mockBackplane, never()).putOperation(any(Operation.class), eq(QUEUED));\n verify(mockBackplane, times(1)).putOperation(any(Operation.class), eq(COMPLETED));\n verify(poller, atLeastOnce()).pause();\n }", "completions": [ "```java\n @Test\n public void queueOperationCompletesOperationWithCachedActionResult() throws Exception {\n ExecuteEntry executeEntry = mock(ExecuteEntry.class);\n Poller poller = mock(Poller.class);\n Duration timeout = Duration.ofSeconds(1);\n ActionResult actionResult = ActionResult.newBuilder().setExitCode(0).build();\n when(executeEntry.getActionDigest()).thenReturn(DigestUtil.hashString(\"action\"));\n when(executeEntry.getStdoutStreamName()).thenReturn(\"stdout\");\n when(executeEntry.getStderrStreamName()).thenReturn(\"stderr\");\n when(executeEntry.getOperationName()).thenReturn(\"operation\");\n when(executeEntry.getRequestMetadata()).thenReturn(RequestMetadata.newBuilder().build());\n when(executeEntry.getSkipCacheLookup()).thenReturn(false);\n when(cache.get(any(ActionKey.class))).thenReturn(actionResult);\n\n ListenableFuture future = serverInstance.queue(executeEntry, poller, timeout);\n future.get();\n\n verify(poller).pause();\n }\n```\n" ], "line": 51, "token": 300, "line_diff": 1, "token_diff": 1 }, { "id": 14, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @VisibleForTesting\n public ListenableFuture queue(ExecuteEntry executeEntry, Poller poller, Duration timeout) {\n ExecuteOperationMetadata metadata =\n ExecuteOperationMetadata.newBuilder()\n .setActionDigest(executeEntry.getActionDigest())\n .setStdoutStreamName(executeEntry.getStdoutStreamName())\n .setStderrStreamName(executeEntry.getStderrStreamName())\n .build();\n Operation operation =\n Operation.newBuilder()\n .setName(executeEntry.getOperationName())\n .setMetadata(Any.pack(metadata))\n .build();\n Digest actionDigest = executeEntry.getActionDigest();\n ActionKey actionKey = DigestUtil.asActionKey(actionDigest);\n\n Stopwatch stopwatch = Stopwatch.createStarted();\n ListenableFuture cachedResultFuture;\n if (executeEntry.getSkipCacheLookup()) {\n cachedResultFuture = immediateFuture(false);\n } else {\n cachedResultFuture =\n checkCacheFuture(actionKey, operation, executeEntry.getRequestMetadata());\n }\n return transformAsync(\n cachedResultFuture,\n (cachedResult) -> {\n if (cachedResult) {\n poller.pause();\n long checkCacheUSecs = stopwatch.elapsed(MICROSECONDS);\n log.log(\n Level.FINER,\n format(\n \"ServerInstance(%s): checkCache(%s): %sus elapsed\",\n getName(), operation.getName(), checkCacheUSecs));\n return IMMEDIATE_VOID_FUTURE;\n }\n return transformAndQueue(executeEntry, poller, operation, stopwatch, timeout);\n },\n operationTransformService);\n }\n```\n###test function signature:\n```java\n @Test\n public void queueActionFailsQueueEligibility() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "queueActionFailsQueueEligibility", "reference": " @Test\n public void queueActionFailsQueueEligibility() throws Exception {\n Directory inputRoot = Directory.newBuilder().build();\n ByteString inputRootContent = inputRoot.toByteString();\n Digest inputRootDigest = DIGEST_UTIL.compute(inputRootContent);\n provideBlob(inputRootDigest, inputRootContent);\n Action action = createAction(true, true, inputRootDigest, SIMPLE_COMMAND);\n Digest actionDigest = DIGEST_UTIL.compute(action);\n\n ExecuteEntry executeEntry =\n ExecuteEntry.newBuilder()\n .setOperationName(\"missing-directory-operation\")\n .setActionDigest(actionDigest)\n .setSkipCacheLookup(true)\n .build();\n\n when(mockBackplane.propertiesEligibleForQueue(anyList())).thenReturn(false);\n\n when(mockBackplane.canQueue()).thenReturn(true);\n\n Poller poller = mock(Poller.class);\n\n boolean failedPreconditionExceptionCaught = false;\n try {\n instance\n .queue(executeEntry, poller, DEFAULT_TIMEOUT)\n .get(QUEUE_TEST_TIMEOUT_SECONDS, SECONDS);\n } catch (ExecutionException e) {\n com.google.rpc.Status status = StatusProto.fromThrowable(e);\n if (status.getCode() == Code.FAILED_PRECONDITION.getNumber()) {\n failedPreconditionExceptionCaught = true;\n } else {\n e.getCause().printStackTrace();\n }\n }\n assertThat(failedPreconditionExceptionCaught).isTrue();\n\n PreconditionFailure preconditionFailure =\n PreconditionFailure.newBuilder()\n .addViolations(\n Violation.newBuilder()\n .setType(VIOLATION_TYPE_INVALID)\n .setSubject(INVALID_PLATFORM)\n .setDescription(\n \"properties are not valid for queue eligibility: []. If you think your\"\n + \" queue should still accept these poperties without them being\"\n + \" specified in queue configuration, consider configuring the queue\"\n + \" with `allow_unmatched: True`\"))\n .build();\n ExecuteResponse executeResponse =\n ExecuteResponse.newBuilder()\n .setStatus(\n com.google.rpc.Status.newBuilder()\n .setCode(Code.FAILED_PRECONDITION.getNumber())\n .setMessage(invalidActionVerboseMessage(actionDigest, preconditionFailure))\n .addDetails(Any.pack(preconditionFailure)))\n .build();\n assertResponse(executeResponse);\n verify(poller, atLeastOnce()).pause();\n }", "completions": [ "```java\n @Test\n public void queueActionFailsQueueEligibility() throws Exception {\n ExecuteEntry executeEntry = mock(ExecuteEntry.class);\n Poller poller = mock(Poller.class);\n Duration timeout = Duration.ofSeconds(1);\n\n when(executeEntry.getActionDigest()).thenReturn(DigestUtil.hashString(ACTION_DIGEST));\n when(executeEntry.getStdoutStreamName()).thenReturn(STDOUT_STREAM_NAME);\n when(executeEntry.getStderrStreamName()).thenReturn(STDERR_STREAM_NAME);\n when(executeEntry.getOperationName()).thenReturn(OPERATION_NAME);\n when(executeEntry.getRequestMetadata()).thenReturn(REQUEST_METADATA);\n when(executeEntry.getSkipCacheLookup()).thenReturn(false);\n\n when(poller.pause()).thenThrow(new RuntimeException(\"Queue eligibility failed\"));\n\n ListenableFuture future = serverInstance.queue(executeEntry, poller, timeout);\n\n assertThrows(RuntimeException.class, future::get);\n }\n```\n" ], "line": 51, "token": 300, "line_diff": 1, "token_diff": 1 }, { "id": 15, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public T clone(T object) {\n if (object instanceof String) {\n return object;\n } else if (object instanceof Collection) {\n Object firstElement = findFirstNonNullElement((Collection) object);\n if (firstElement != null && !(firstElement instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), firstElement.getClass());\n return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n } else if (object instanceof Map) {\n Map.Entry firstEntry = this.findFirstNonNullEntry((Map) object);\n if (firstEntry != null) {\n Object key = firstEntry.getKey();\n Object value = firstEntry.getValue();\n if (!(key instanceof Serializable) || !(value instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), key.getClass(), value.getClass());\n return (T) objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n }\n } else if (object instanceof JsonNode) {\n return (T) ((JsonNode) object).deepCopy();\n }\n\n if (object instanceof Serializable) {\n try {\n return (T) SerializationHelper.clone((Serializable) object);\n } catch (SerializationException e) {\n //it is possible that object itself implements java.io.Serializable, but underlying structure does not\n //in this case we switch to the other JSON marshaling strategy which doesn't use the Java serialization\n }\n }\n\n return jsonClone(object);\n }\n```\n###test function signature:\n```java\n @Test\n public void should_clone_serializable_complex_object_with_serializable_nested_object()\n```\n### Answer: (use the provided format with backticks)\n", "name": "should_clone_serializable_complex_object_with_serializable_nested_object", "reference": " @Test\n public void should_clone_serializable_complex_object_with_serializable_nested_object() {\n Map> map = new LinkedHashMap<>();\n map.put(\"key1\", Lists.newArrayList(new SerializableObject(\"name1\")));\n map.put(\"key2\", Lists.newArrayList(\n new SerializableObject(\"name2\"),\n new SerializableObject(\"name3\")\n ));\n Object original = new SerializableComplexObject(map);\n Object cloned = serializer.clone(original);\n assertEquals(original, cloned);\n assertNotSame(original, cloned);\n }", "completions": [ "```java\n @Test\n public void should_clone_serializable_complex_object_with_serializable_nested_object() {\n // Given\n Map map = new HashMap<>();\n map.put(\"key\", new SerializableObject());\n SerializableObject object = new SerializableObject(map);\n\n // When\n SerializableObject clonedObject = objectCloner.clone(object);\n\n // Then\n assertNotSame(object, clonedObject);\n assertNotSame(object.getMap(), clonedObject.getMap());\n assertNotSame(object.getMap().get(\"key\"), clonedObject.getMap().get(\"key\"));\n }\n```\n" ], "line": 44, "token": 358, "line_diff": 1, "token_diff": 1 }, { "id": 16, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public SearchResult search(\n String dataset,\n String queryStr,\n Long startTimeMsEpoch,\n Long endTimeMsEpoch,\n int howMany,\n AggBuilder aggBuilder) {\n\n ensureNonEmptyString(dataset, \"dataset should be a non-empty string\");\n ensureNonNullString(queryStr, \"query should be a non-empty string\");\n if (startTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch >= 0, \"start time should be non-negative value\");\n }\n if (startTimeMsEpoch != null && endTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch < endTimeMsEpoch, \"end time should be greater than start time\");\n }\n ensureTrue(howMany >= 0, \"hits requested should not be negative.\");\n ensureTrue(howMany > 0 || aggBuilder != null, \"Hits or aggregation should be requested.\");\n\n ScopedSpan span = Tracing.currentTracer().startScopedSpan(\"LogIndexSearcherImpl.search\");\n span.tag(\"dataset\", dataset);\n span.tag(\"startTimeMsEpoch\", String.valueOf(startTimeMsEpoch));\n span.tag(\"endTimeMsEpoch\", String.valueOf(endTimeMsEpoch));\n span.tag(\"howMany\", String.valueOf(howMany));\n\n Stopwatch elapsedTime = Stopwatch.createStarted();\n try {\n // Acquire an index searcher from searcher manager.\n // This is a useful optimization for indexes that are static.\n IndexSearcher searcher = searcherManager.acquire();\n\n Query query =\n openSearchAdapter.buildQuery(\n dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, searcher);\n try {\n List results;\n InternalAggregation internalAggregation = null;\n\n if (howMany > 0) {\n CollectorManager topFieldCollector =\n buildTopFieldCollector(howMany, aggBuilder != null ? Integer.MAX_VALUE : howMany);\n MultiCollectorManager collectorManager;\n if (aggBuilder != null) {\n collectorManager =\n new MultiCollectorManager(\n topFieldCollector,\n openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n } else {\n collectorManager = new MultiCollectorManager(topFieldCollector);\n }\n Object[] collector = searcher.search(query, collectorManager);\n\n ScoreDoc[] hits = ((TopFieldDocs) collector[0]).scoreDocs;\n results = new ArrayList<>(hits.length);\n for (ScoreDoc hit : hits) {\n results.add(buildLogMessage(searcher, hit));\n }\n if (aggBuilder != null) {\n internalAggregation = (InternalAggregation) collector[1];\n }\n } else {\n results = Collections.emptyList();\n internalAggregation =\n searcher.search(\n query, openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n }\n\n elapsedTime.stop();\n return new SearchResult<>(\n results, elapsedTime.elapsed(TimeUnit.MICROSECONDS), 0, 0, 1, 1, internalAggregation);\n } finally {\n searcherManager.release(searcher);\n }\n } catch (IOException e) {\n span.error(e);\n throw new IllegalArgumentException(\"Failed to acquire an index searcher.\", e);\n } finally {\n span.finish();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testFullIndexSearchForSumAgg()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testFullIndexSearchForSumAgg", "reference": " @Test\n public void testFullIndexSearchForSumAgg() {\n Instant time = Instant.ofEpochSecond(1593365471);\n loadTestData(time);\n\n SearchResult allIndexItems =\n strictLogStore.logSearcher.search(\n TEST_DATASET_NAME,\n \"\",\n 0L,\n MAX_TIME,\n 1000,\n new SumAggBuilder(\"test\", TEST_SOURCE_LONG_PROPERTY, \"0\", null));\n\n assertThat(allIndexItems.hits.size()).isEqualTo(4);\n\n InternalSum internalSum =\n (InternalSum) Objects.requireNonNull(allIndexItems.internalAggregation);\n\n // 1, 3, 4, 5\n assertThat(internalSum.getValue()).isEqualTo(13);\n }", "completions": [ "```java\n @Test\n public void testFullIndexSearchForSumAgg() {\n // Given\n String dataset = \"testDataset\";\n String queryStr = \"testQuery\";\n Long startTimeMsEpoch = 1577836800000L; // 2020-01-01 00:00:00\n Long endTimeMsEpoch = 1577923199000L; // 2020-01-02 23:59:59\n int howMany = 10;\n AggBuilder aggBuilder = new SumAggBuilder(\"testField\");\n\n // When\n SearchResult result = logIndexSearcher.search(dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, howMany, aggBuilder);\n\n // Then\n assertNotNull(result);\n assertEquals(howMany, result.getResults().size());\n assertNotNull(result.getAggregation());\n assertEquals(SumAggBuilder.class, result.getAggregation().getClass());\n assertEquals(\"testField\", ((SumAggBuilder) result.getAggregation()).getField());\n }\n```\n" ], "line": 85, "token": 606, "line_diff": 2, "token_diff": 2 }, { "id": 17, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public void process(String base64AuthenticatorData, String signature, String clientDataJson, Fido2RegistrationData registration,\n Fido2AuthenticationData authenticationEntity) {\n log.debug(\"Registration: {}\", registration);\n\n AuthData authData = authenticatorDataParser.parseAssertionData(base64AuthenticatorData);\n commonVerifiers.verifyRpIdHash(authData, registration.getDomain());\n\n log.debug(\"User verification option: {}\", authenticationEntity.getUserVerificationOption());\n userVerificationVerifier.verifyUserVerificationOption(authenticationEntity.getUserVerificationOption(), authData);\n\n byte[] clientDataHash = DigestUtils.getSha256Digest().digest(base64Service.urlDecode(clientDataJson));\n\n try {\n int counter = authenticatorDataParser.parseCounter(authData.getCounters());\n commonVerifiers.verifyCounter(registration.getCounter(), counter);\n registration.setCounter(counter);\n\n JsonNode uncompressedECPointNode = dataMapperService.cborReadTree(base64Service.urlDecode(registration.getUncompressedECPoint()));\n PublicKey publicKey = coseService.createUncompressedPointFromCOSEPublicKey(uncompressedECPointNode);\n\n log.debug(\"Uncompressed ECpoint node: {}\", uncompressedECPointNode);\n log.debug(\"EC Public key hex: {}\", Hex.encodeHexString(publicKey.getEncoded()));\n log.debug(\"Registration algorithm: {}, default use: -7\", registration.getSignatureAlgorithm());\n authenticatorDataVerifier.verifyAssertionSignature(authData, clientDataHash, signature, publicKey, -7);\n\n } catch (Fido2CompromisedDevice ex) {\n log.error(\"Error compromised device: {}\", ex.getMessage());\n throw ex;\n } catch (Exception ex) {\n log.error(\"Error to check none assertion: {}\", ex.getMessage());\n throw new Fido2RuntimeException(\"Failed to check none assertion: {}\", ex.getMessage(), ex);\n }\n }\n```\n###test function signature:\n```java\n @Test\n void process_ifCborReadTreeThrowException_fido2RuntimeException() throws Fido2CompromisedDevice, IOException\n```\n### Answer: (use the provided format with backticks)\n", "name": "process_ifCborReadTreeThrowException_fido2RuntimeException", "reference": " @Test\n void process_ifCborReadTreeThrowException_fido2RuntimeException() throws Fido2CompromisedDevice, IOException {\n String base64AuthenticatorData = \"base64AuthenticatorData_test\";\n String signature = \"signature_test\";\n String clientDataJson = \"clientDataJson_test\";\n Fido2RegistrationData registration = mock(Fido2RegistrationData.class);\n Fido2AuthenticationData authenticationEntity = mock(Fido2AuthenticationData.class);\n\n when(authenticationEntity.getUserVerificationOption()).thenReturn(UserVerification.preferred);\n when(registration.getDomain()).thenReturn(\"domain_test\");\n when(registration.getCounter()).thenReturn(100);\n when(registration.getUncompressedECPoint()).thenReturn(\"uncompressedECPoint_test\");\n\n when(authenticatorDataParser.parseAssertionData(any())).thenReturn(mock(AuthData.class));\n when(base64Service.urlDecode(any(String.class))).thenReturn(\"decode_test\".getBytes());\n when(dataMapperService.cborReadTree(any(byte[].class))).thenThrow(new IOException(\"IOException_test\"));\n\n Fido2RuntimeException ex = assertThrows(Fido2RuntimeException.class, () -> noneAssertionFormatProcessor.process(base64AuthenticatorData, signature, clientDataJson, registration, authenticationEntity));\n assertNotNull(ex);\n assertEquals(ex.getMessage(), \"IOException_test\");\n\n verify(log).debug(eq(\"Registration: {}\"), any(Fido2RegistrationData.class));\n verify(log).debug(eq(\"User verification option: {}\"), any(UserVerification.class));\n verify(commonVerifiers).verifyRpIdHash(any(AuthData.class), any(String.class));\n verify(authenticatorDataParser).parseCounter(any());\n verify(log).error(eq(\"Error to check none assertion: {}\"), any(String.class));\n\n verify(log, never()).error(eq(\"Error compromised device: {}\"), any(String.class));\n verifyNoInteractions(coseService, authenticatorDataVerifier);\n verifyNoMoreInteractions(log);\n }", "completions": [ "```java\n @Test\n void process_ifCborReadTreeThrowException_fido2RuntimeException() throws Fido2CompromisedDevice, IOException {\n // Arrange\n String base64AuthenticatorData = \"base64AuthenticatorData\";\n String signature = \"signature\";\n String clientDataJson = \"clientDataJson\";\n Fido2RegistrationData registration = new Fido2RegistrationData();\n Fido2AuthenticationData authenticationEntity = new Fido2AuthenticationData();\n\n when(authenticatorDataParser.parseAssertionData(base64AuthenticatorData)).thenReturn(new AuthData());\n when(authenticatorDataParser.parseCounter(any())).thenReturn(1);\n when(dataMapperService.cborReadTree(any())).thenThrow(new IOException());\n\n // Act & Assert\n Assertions.assertThrows(Fido2RuntimeException.class, () -> {\n fido2AuthenticationService.process(base64AuthenticatorData, signature, clientDataJson, registration, authenticationEntity);\n });\n }\n```\n" ], "line": 38, "token": 365, "line_diff": 1, "token_diff": 1 }, { "id": 18, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n\tpublic void setUserData(String theKey, Object theValue) {\n\t\tValidate.isTrue(isNotBlank(theKey), \"Invalid key; key must be non-empty, non-null.\");\n\t\tif (theValue == null) {\n\t\t\tgetUserData().remove(theKey);\n\t\t} else {\n\t\t\tValidate.isTrue(\n\t\t\t\t\tvalidateValue(theValue),\n\t\t\t\t\tString.format(\n\t\t\t\t\t\t\t\"Invalid data type provided %s\", theValue.getClass().getName()));\n\t\t\tgetUserData().put(theKey, theValue);\n\t\t}\n\t}\n```\n###test function signature:\n```java\n\t@Test\n\tpublic void setUserData_invalidKey_throws()\n```\n### Answer: (use the provided format with backticks)\n", "name": "setUserData_invalidKey_throws", "reference": "\t@Test\n\tpublic void setUserData_invalidKey_throws() {\n\t\t// setup\n\t\tTestParameters parameters = new TestParameters();\n\n\t\t// test\n\t\tfor (String key : new String[] { null, \"\" }) {\n\t\t\ttry {\n\t\t\t\tparameters.setUserData(key, \"test\");\n\t\t\t\tfail();\n\t\t\t} catch (IllegalArgumentException ex) {\n\t\t\t\tassertTrue(ex.getMessage().contains(\"Invalid key; key must be non-empty, non-null\"),\n\t\t\t\t\tex.getMessage());\n\t\t\t}\n\t\t}\n\t}", "completions": [ "```java\n\t@Test(expected = IllegalArgumentException.class)\n\tpublic void setUserData_invalidKey_throws() {\n\t\tTestClass testClass = new TestClass();\n\t\ttestClass.setUserData(\"\", \"value\");\n\t}\n```\n\nIn this test, we are creating an instance of the TestClass and calling the setUserData method with an empty key and a valid value. We expect this to throw an IllegalArgumentException, which is what we specify in the @Test annotation.\n" ], "line": 23, "token": 170, "line_diff": 0, "token_diff": 0 }, { "id": 19, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @VisibleForTesting\n public ListenableFuture queue(ExecuteEntry executeEntry, Poller poller, Duration timeout) {\n ExecuteOperationMetadata metadata =\n ExecuteOperationMetadata.newBuilder()\n .setActionDigest(executeEntry.getActionDigest())\n .setStdoutStreamName(executeEntry.getStdoutStreamName())\n .setStderrStreamName(executeEntry.getStderrStreamName())\n .build();\n Operation operation =\n Operation.newBuilder()\n .setName(executeEntry.getOperationName())\n .setMetadata(Any.pack(metadata))\n .build();\n Digest actionDigest = executeEntry.getActionDigest();\n ActionKey actionKey = DigestUtil.asActionKey(actionDigest);\n\n Stopwatch stopwatch = Stopwatch.createStarted();\n ListenableFuture cachedResultFuture;\n if (executeEntry.getSkipCacheLookup()) {\n cachedResultFuture = immediateFuture(false);\n } else {\n cachedResultFuture =\n checkCacheFuture(actionKey, operation, executeEntry.getRequestMetadata());\n }\n return transformAsync(\n cachedResultFuture,\n (cachedResult) -> {\n if (cachedResult) {\n poller.pause();\n long checkCacheUSecs = stopwatch.elapsed(MICROSECONDS);\n log.log(\n Level.FINER,\n format(\n \"ServerInstance(%s): checkCache(%s): %sus elapsed\",\n getName(), operation.getName(), checkCacheUSecs));\n return IMMEDIATE_VOID_FUTURE;\n }\n return transformAndQueue(executeEntry, poller, operation, stopwatch, timeout);\n },\n operationTransformService);\n }\n```\n###test function signature:\n```java\n @Test\n public void queueDirectoryMissingErrorsOperation() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "queueDirectoryMissingErrorsOperation", "reference": " @Test\n public void queueDirectoryMissingErrorsOperation() throws Exception {\n ByteString foo = ByteString.copyFromUtf8(\"foo\");\n Digest subdirDigest = DIGEST_UTIL.compute(foo);\n Directory inputRoot =\n Directory.newBuilder()\n .addDirectories(\n DirectoryNode.newBuilder().setName(\"missing-subdir\").setDigest(subdirDigest))\n .build();\n ByteString inputRootContent = inputRoot.toByteString();\n Digest inputRootDigest = DIGEST_UTIL.compute(inputRootContent);\n provideBlob(inputRootDigest, inputRootContent);\n Action action = createAction(true, true, inputRootDigest, SIMPLE_COMMAND);\n Digest actionDigest = DIGEST_UTIL.compute(action);\n\n ExecuteEntry executeEntry =\n ExecuteEntry.newBuilder()\n .setOperationName(\"missing-directory-operation\")\n .setActionDigest(actionDigest)\n .setSkipCacheLookup(true)\n .build();\n\n when(mockBackplane.propertiesEligibleForQueue(anyList())).thenReturn(true);\n\n when(mockBackplane.canQueue()).thenReturn(true);\n\n Poller poller = mock(Poller.class);\n\n boolean failedPreconditionExceptionCaught = false;\n try {\n instance\n .queue(executeEntry, poller, DEFAULT_TIMEOUT)\n .get(QUEUE_TEST_TIMEOUT_SECONDS, SECONDS);\n } catch (ExecutionException e) {\n com.google.rpc.Status status = StatusProto.fromThrowable(e);\n if (status.getCode() == Code.FAILED_PRECONDITION.getNumber()) {\n failedPreconditionExceptionCaught = true;\n } else {\n e.getCause().printStackTrace();\n }\n }\n assertThat(failedPreconditionExceptionCaught).isTrue();\n\n PreconditionFailure preconditionFailure =\n PreconditionFailure.newBuilder()\n .addViolations(\n Violation.newBuilder()\n .setType(VIOLATION_TYPE_MISSING)\n .setSubject(\"blobs/\" + DigestUtil.toString(subdirDigest))\n .setDescription(\"The directory `/missing-subdir` was not found in the CAS.\"))\n .build();\n ExecuteResponse executeResponse =\n ExecuteResponse.newBuilder()\n .setStatus(\n com.google.rpc.Status.newBuilder()\n .setCode(Code.FAILED_PRECONDITION.getNumber())\n .setMessage(invalidActionVerboseMessage(actionDigest, preconditionFailure))\n .addDetails(Any.pack(preconditionFailure)))\n .build();\n assertResponse(executeResponse);\n verify(poller, atLeastOnce()).pause();\n }", "completions": [ "```java\n @Test\n public void queueDirectoryMissingErrorsOperation() throws Exception {\n ExecuteEntry executeEntry = mock(ExecuteEntry.class);\n Poller poller = mock(Poller.class);\n Duration timeout = Duration.ofSeconds(10);\n\n when(executeEntry.getActionDigest()).thenReturn(DigestUtil.hashString(DigestUtil.DEFAULT_INSTANCE_NAME + \"action\"));\n when(executeEntry.getStdoutStreamName()).thenReturn(\"stdout\");\n when(executeEntry.getStderrStreamName()).thenReturn(\"stderr\");\n when(executeEntry.getOperationName()).thenReturn(\"operation\");\n when(executeEntry.getRequestMetadata()).thenReturn(RequestMetadata.newBuilder().build());\n when(executeEntry.getSkipCacheLookup()).thenReturn(false);\n\n ActionKey actionKey = DigestUtil.asActionKey(executeEntry.getActionDigest());\n when(checkCacheFuture(actionKey, any(), any())).thenReturn(immediateFuture(true));\n\n ListenableFuture future = serverInstance.queue(executeEntry, poller, timeout);\n assertThat(future.get()).isEqualTo(null);\n }\n```\n" ], "line": 51, "token": 300, "line_diff": 1, "token_diff": 1 }, { "id": 20, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @VisibleForTesting\n boolean handleRecoveryTask(RecoveryTaskMetadata recoveryTaskMetadata) {\n LOG.info(\"Started handling the recovery task: {}\", recoveryTaskMetadata);\n long startTime = System.nanoTime();\n Timer.Sample taskTimer = Timer.start(meterRegistry);\n\n PartitionOffsets partitionOffsets =\n validateKafkaOffsets(\n adminClient,\n recoveryTaskMetadata,\n AstraConfig.getRecoveryConfig().getKafkaConfig().getKafkaTopic());\n long offsetsValidatedTime = System.nanoTime();\n long consumerPreparedTime = 0, messagesConsumedTime = 0, rolloversCompletedTime = 0;\n\n if (partitionOffsets != null) {\n RecoveryTaskMetadata validatedRecoveryTask =\n new RecoveryTaskMetadata(\n recoveryTaskMetadata.name,\n recoveryTaskMetadata.partitionId,\n partitionOffsets.startOffset,\n partitionOffsets.endOffset,\n recoveryTaskMetadata.createdTimeEpochMs);\n\n if (partitionOffsets.startOffset != recoveryTaskMetadata.startOffset\n || recoveryTaskMetadata.endOffset != partitionOffsets.endOffset) {\n recoveryRecordsNoLongerAvailable.increment(\n (partitionOffsets.startOffset - recoveryTaskMetadata.startOffset)\n + (partitionOffsets.endOffset - recoveryTaskMetadata.endOffset));\n }\n\n try {\n RecoveryChunkManager chunkManager =\n RecoveryChunkManager.fromConfig(\n meterRegistry,\n searchMetadataStore,\n snapshotMetadataStore,\n AstraConfig.getIndexerConfig(),\n blobFs,\n AstraConfig.getS3Config());\n\n // Ingest data in parallel\n LogMessageWriterImpl logMessageWriterImpl = new LogMessageWriterImpl(chunkManager);\n AstraKafkaConsumer kafkaConsumer =\n new AstraKafkaConsumer(\n makeKafkaConfig(\n AstraConfig.getRecoveryConfig().getKafkaConfig(),\n validatedRecoveryTask.partitionId),\n logMessageWriterImpl,\n meterRegistry);\n\n kafkaConsumer.prepConsumerForConsumption(validatedRecoveryTask.startOffset);\n consumerPreparedTime = System.nanoTime();\n kafkaConsumer.consumeMessagesBetweenOffsetsInParallel(\n AstraKafkaConsumer.KAFKA_POLL_TIMEOUT_MS,\n validatedRecoveryTask.startOffset,\n validatedRecoveryTask.endOffset);\n messagesConsumedTime = System.nanoTime();\n // Wait for chunks to upload.\n boolean success = chunkManager.waitForRollOvers();\n rolloversCompletedTime = System.nanoTime();\n // Close the recovery chunk manager and kafka consumer.\n kafkaConsumer.close();\n chunkManager.stopAsync();\n chunkManager.awaitTerminated(DEFAULT_START_STOP_DURATION);\n LOG.info(\"Finished handling the recovery task: {}\", validatedRecoveryTask);\n taskTimer.stop(recoveryTaskTimerSuccess);\n return success;\n } catch (Exception ex) {\n LOG.error(\"Exception in recovery task [{}]: {}\", validatedRecoveryTask, ex);\n taskTimer.stop(recoveryTaskTimerFailure);\n return false;\n } finally {\n long endTime = System.nanoTime();\n LOG.info(\n \"Recovery task {} took {}ms, (subtask times offset validation {}, consumer prep {}, msg consumption {}, rollover {})\",\n recoveryTaskMetadata,\n nanosToMillis(endTime - startTime),\n nanosToMillis(offsetsValidatedTime - startTime),\n nanosToMillis(consumerPreparedTime - offsetsValidatedTime),\n nanosToMillis(messagesConsumedTime - consumerPreparedTime),\n nanosToMillis(rolloversCompletedTime - messagesConsumedTime));\n }\n } else {\n LOG.info(\n \"Recovery task {} data no longer available in Kafka (validation time {}ms)\",\n recoveryTaskMetadata,\n nanosToMillis(offsetsValidatedTime - startTime));\n recoveryRecordsNoLongerAvailable.increment(\n recoveryTaskMetadata.endOffset - recoveryTaskMetadata.startOffset + 1);\n return true;\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testShouldHandleRecoveryTaskWithPartiallyUnavailableOffsets() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "testShouldHandleRecoveryTaskWithPartiallyUnavailableOffsets", "reference": " @Test\n public void testShouldHandleRecoveryTaskWithPartiallyUnavailableOffsets() throws Exception {\n final TopicPartition topicPartition = new TopicPartition(TestKafkaServer.TEST_KAFKA_TOPIC, 0);\n TestKafkaServer.KafkaComponents components = getKafkaTestServer(S3_MOCK_EXTENSION);\n AstraConfigs.AstraConfig astraCfg =\n makeAstraConfig(components.testKafkaServer, TEST_S3_BUCKET, topicPartition.topic());\n curatorFramework =\n CuratorBuilder.build(meterRegistry, astraCfg.getMetadataStoreConfig().getZookeeperConfig());\n\n AstraConfigs.KafkaConfig kafkaConfig =\n AstraConfigs.KafkaConfig.newBuilder()\n .setKafkaTopic(topicPartition.topic())\n .setKafkaTopicPartition(Integer.toString(topicPartition.partition()))\n .setKafkaBootStrapServers(components.testKafkaServer.getBroker().getBrokerList().get())\n .setKafkaClientGroup(TEST_KAFKA_CLIENT_GROUP)\n .setEnableKafkaAutoCommit(\"true\")\n .setKafkaAutoCommitInterval(\"500\")\n .setKafkaSessionTimeout(\"500\")\n .putAllAdditionalProps(Maps.fromProperties(components.consumerOverrideProps))\n .build();\n\n final AstraKafkaConsumer localTestConsumer =\n new AstraKafkaConsumer(kafkaConfig, components.logMessageWriter, components.meterRegistry);\n final Instant startTime = Instant.now();\n final long msgsToProduce = 100;\n TestKafkaServer.produceMessagesToKafka(\n components.testKafkaServer.getBroker(),\n startTime,\n topicPartition.topic(),\n topicPartition.partition(),\n (int) msgsToProduce);\n await().until(() -> localTestConsumer.getEndOffSetForPartition() == msgsToProduce);\n // we immediately force delete the messages, as this is faster than changing the retention and\n // waiting for the cleaner to run\n components\n .adminClient\n .deleteRecords(Map.of(topicPartition, RecordsToDelete.beforeOffset(100)))\n .all()\n .get();\n assertThat(getStartOffset(components.adminClient, topicPartition)).isGreaterThan(0);\n\n // produce some more messages that won't be expired\n setRetentionTime(components.adminClient, topicPartition.topic(), 25000);\n TestKafkaServer.produceMessagesToKafka(\n components.testKafkaServer.getBroker(),\n startTime,\n topicPartition.topic(),\n topicPartition.partition(),\n (int) msgsToProduce);\n await()\n .until(() -> localTestConsumer.getEndOffSetForPartition() == msgsToProduce + msgsToProduce);\n\n SnapshotMetadataStore snapshotMetadataStore = new SnapshotMetadataStore(curatorFramework);\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore).size()).isZero();\n\n // Start recovery service\n recoveryService =\n new RecoveryService(astraCfg, curatorFramework, components.meterRegistry, blobFs);\n recoveryService.startAsync();\n recoveryService.awaitRunning(DEFAULT_START_STOP_DURATION);\n\n // Start recovery with an offset range that is partially unavailable\n long startOffset = 50;\n long endOffset = 150;\n RecoveryTaskMetadata recoveryTask =\n new RecoveryTaskMetadata(\n topicPartition.topic(),\n Integer.toString(topicPartition.partition()),\n startOffset,\n endOffset,\n Instant.now().toEpochMilli());\n assertThat(recoveryService.handleRecoveryTask(recoveryTask)).isTrue();\n assertThat(getCount(RECORDS_NO_LONGER_AVAILABLE, components.meterRegistry)).isEqualTo(50);\n assertThat(getCount(MESSAGES_RECEIVED_COUNTER, components.meterRegistry)).isEqualTo(51);\n List snapshots =\n AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore);\n assertThat(snapshots.size()).isEqualTo(1);\n assertThat(blobFs.listFiles(BlobFsUtils.createURI(TEST_S3_BUCKET, \"/\", \"\"), true)).isNotEmpty();\n assertThat(blobFs.exists(URI.create(snapshots.get(0).snapshotPath))).isTrue();\n assertThat(blobFs.listFiles(URI.create(snapshots.get(0).snapshotPath), false).length)\n .isGreaterThan(1);\n assertThat(getCount(MESSAGES_FAILED_COUNTER, meterRegistry)).isEqualTo(0);\n assertThat(getCount(ROLLOVERS_INITIATED, meterRegistry)).isEqualTo(0);\n assertThat(getCount(ROLLOVERS_COMPLETED, meterRegistry)).isEqualTo(0);\n assertThat(getCount(ROLLOVERS_FAILED, meterRegistry)).isEqualTo(0);\n }", "completions": [ "```java\n @Test\n public void testShouldHandleRecoveryTaskWithPartiallyUnavailableOffsets() throws Exception {\n // Given\n RecoveryTaskMetadata recoveryTaskMetadata = new RecoveryTaskMetadata(\n \"testTask\",\n 0,\n 100L,\n 200L,\n System.currentTimeMillis());\n\n // When\n boolean result = handleRecoveryTask(recoveryTaskMetadata);\n\n // Then\n assertTrue(result);\n }\n```\n" ], "line": 97, "token": 544, "line_diff": 2, "token_diff": 2 }, { "id": 21, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public List selectHeaderAccept(String[] accepts) {\n if (accepts.length == 0) {\n return null;\n }\n for (String accept : accepts) {\n MediaType mediaType = MediaType.parseMediaType(accept);\n if (isJsonMime(mediaType) && !isProblemJsonMime(accept)) {\n return Collections.singletonList(mediaType);\n }\n }\n return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts));\n }\n```\n###test function signature:\n```java\n @Test\n public void testSelectHeaderAccept()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testSelectHeaderAccept", "reference": " @Test\n public void testSelectHeaderAccept() {\n String[] accepts = {\"application/json\", \"application/xml\"};\n assertEquals(\"application/json\", apiClient.selectHeaderAccept(accepts));\n\n accepts = new String[]{\"APPLICATION/XML\", \"APPLICATION/JSON\"};\n assertEquals(\"APPLICATION/JSON\", apiClient.selectHeaderAccept(accepts));\n\n accepts = new String[]{\"application/xml\", \"application/json; charset=UTF8\"};\n assertEquals(\"application/json; charset=UTF8\", apiClient.selectHeaderAccept(accepts));\n\n accepts = new String[]{\"text/plain\", \"application/xml\"};\n assertEquals(\"text/plain,application/xml\", apiClient.selectHeaderAccept(accepts));\n\n accepts = new String[]{};\n assertNull(apiClient.selectHeaderAccept(accepts));\n }", "completions": [ "```java\n @Test\n public void testSelectHeaderAccept() {\n // Given\n String[] accepts = {\"application/json\", \"application/problem+json\"};\n // When\n List result = selectHeaderAccept(accepts);\n // Then\n assertEquals(1, result.size());\n assertEquals(\"application/json\", result.get(0).toString());\n }\n```\n" ], "line": 23, "token": 154, "line_diff": 0, "token_diff": 0 }, { "id": 22, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public ConsumerRecords poll(final Duration timeout) {\n Timer timer = time.timer(timeout);\n\n acquireAndEnsureOpen();\n try {\n kafkaConsumerMetrics.recordPollStart(timer.currentTimeMs());\n\n if (subscriptions.hasNoSubscriptionOrUserAssignment()) {\n throw new IllegalStateException(\"Consumer is not subscribed to any topics or assigned any partitions\");\n }\n\n do {\n\n // Make sure to let the background thread know that we are still polling.\n applicationEventHandler.add(new PollEvent(timer.currentTimeMs()));\n\n // We must not allow wake-ups between polling for fetches and returning the records.\n // If the polled fetches are not empty the consumed position has already been updated in the polling\n // of the fetches. A wakeup between returned fetches and returning records would lead to never\n // returning the records in the fetches. Thus, we trigger a possible wake-up before we poll fetches.\n wakeupTrigger.maybeTriggerWakeup();\n\n updateAssignmentMetadataIfNeeded(timer);\n final Fetch fetch = pollForFetches(timer);\n if (!fetch.isEmpty()) {\n if (fetch.records().isEmpty()) {\n log.trace(\"Returning empty records from `poll()` \"\n + \"since the consumer's position has advanced for at least one topic partition\");\n }\n\n return interceptors.onConsume(new ConsumerRecords<>(fetch.records()));\n }\n // We will wait for retryBackoffMs\n } while (timer.notExpired());\n\n return ConsumerRecords.empty();\n } finally {\n kafkaConsumerMetrics.recordPollEnd(timer.currentTimeMs());\n release();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testEnsurePollEventSentOnConsumerPoll()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testEnsurePollEventSentOnConsumerPoll", "reference": " @Test\n public void testEnsurePollEventSentOnConsumerPoll() {\n SubscriptionState subscriptions = new SubscriptionState(new LogContext(), OffsetResetStrategy.NONE);\n consumer = newConsumer(\n mock(FetchBuffer.class),\n new ConsumerInterceptors<>(Collections.emptyList()),\n mock(ConsumerRebalanceListenerInvoker.class),\n subscriptions,\n singletonList(new RoundRobinAssignor()),\n \"group-id\",\n \"client-id\");\n final TopicPartition tp = new TopicPartition(\"topic\", 0);\n final List> records = singletonList(\n new ConsumerRecord<>(\"topic\", 0, 2, \"key1\", \"value1\"));\n doAnswer(invocation -> Fetch.forPartition(tp, records, true))\n .when(fetchCollector)\n .collectFetch(Mockito.any(FetchBuffer.class));\n\n consumer.subscribe(singletonList(\"topic1\"));\n consumer.poll(Duration.ofMillis(100));\n verify(applicationEventHandler).add(any(PollEvent.class));\n }", "completions": [ "```java\n @Test\n public void testEnsurePollEventSentOnConsumerPoll() {\n // Arrange\n KafkaConsumer consumer = new KafkaConsumer<>(props);\n consumer.subscribe(Collections.singletonList(\"test-topic\"));\n consumer.poll(Duration.ofMillis(100));\n\n // Act\n ConsumerRecords records = consumer.poll(Duration.ofMillis(100));\n\n // Assert\n assertTrue(records.isEmpty());\n }\n```\n" ], "line": 45, "token": 366, "line_diff": 1, "token_diff": 1 }, { "id": 23, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public long determineStartingOffset(\n long currentEndOffsetForPartition,\n long currentBeginningOffsetForPartition,\n AstraConfigs.IndexerConfig indexerConfig) {\n // Filter stale snapshots for partition.\n if (partitionId == null) {\n LOG.warn(\"PartitionId can't be null.\");\n }\n\n List snapshots = snapshotMetadataStore.listSync();\n List snapshotsForPartition =\n snapshots.stream()\n .filter(\n snapshotMetadata -> {\n if (snapshotMetadata == null || snapshotMetadata.partitionId == null) {\n LOG.warn(\n \"snapshot metadata or partition id can't be null: {} \",\n Strings.join(snapshots, ','));\n }\n return snapshotMetadata != null\n && snapshotMetadata.partitionId != null\n && snapshotMetadata.partitionId.equals(partitionId);\n })\n .collect(Collectors.toUnmodifiableList());\n List deletedSnapshots = deleteStaleLiveSnapshots(snapshotsForPartition);\n\n List nonLiveSnapshotsForPartition =\n snapshotsForPartition.stream()\n .filter(s -> !deletedSnapshots.contains(s))\n .collect(Collectors.toUnmodifiableList());\n\n // Get the highest offset that is indexed in durable store.\n List recoveryTasks = recoveryTaskMetadataStore.listSync();\n long highestDurableOffsetForPartition =\n getHighestDurableOffsetForPartition(\n nonLiveSnapshotsForPartition, recoveryTasks, partitionId);\n LOG.debug(\n \"The highest durable offset for partition {} is {}\",\n partitionId,\n highestDurableOffsetForPartition);\n\n if (highestDurableOffsetForPartition <= 0) {\n LOG.info(\"There is no prior offset for this partition {}.\", partitionId);\n\n // If the user wants to start at the current offset in Kafka and _does not_ want to create\n // recovery tasks to backfill, then we can just return the current offset.\n // If the user wants to start at the current offset in Kafka and _does_ want to create\n // recovery tasks to backfill, then we create the recovery tasks needed and then return\n // the current offset for the indexer. And if the user does _not_ want to start at the\n // current offset in Kafka, then we'll just default to the old behavior of starting from\n // the very beginning\n if (!indexerConfig.getCreateRecoveryTasksOnStart()\n && indexerConfig.getReadFromLocationOnStart()\n == AstraConfigs.KafkaOffsetLocation.LATEST) {\n LOG.info(\n \"CreateRecoveryTasksOnStart is set to false and ReadLocationOnStart is set to current. Reading from current and\"\n + \" NOT spinning up recovery tasks\");\n return currentEndOffsetForPartition;\n } else if (indexerConfig.getCreateRecoveryTasksOnStart()\n && indexerConfig.getReadFromLocationOnStart()\n == AstraConfigs.KafkaOffsetLocation.LATEST) {\n // Todo - this appears to be able to create recovery tasks that have a start and end\n // position of 0, which is invalid. This seems to occur when new clusters are initialized,\n // and is especially problematic when indexers are created but never get assigned (ie,\n // deploy 5, only assign 3).\n LOG.info(\n \"CreateRecoveryTasksOnStart is set and ReadLocationOnStart is set to current. Reading from current and\"\n + \" spinning up recovery tasks\");\n createRecoveryTasks(\n partitionId,\n currentBeginningOffsetForPartition,\n currentEndOffsetForPartition,\n indexerConfig.getMaxMessagesPerChunk());\n return currentEndOffsetForPartition;\n\n } else {\n return highestDurableOffsetForPartition;\n }\n }\n\n // The current head offset shouldn't be lower than the highest durable offset. If it is it\n // means that we indexed more data than the current head offset. This is either a bug in the\n // offset handling mechanism or the kafka partition has rolled over. We throw an exception\n // for now, so we can investigate.\n if (currentEndOffsetForPartition < highestDurableOffsetForPartition) {\n final String message =\n String.format(\n \"The current head for the partition %d can't \"\n + \"be lower than the highest durable offset for that partition %d\",\n currentEndOffsetForPartition, highestDurableOffsetForPartition);\n LOG.error(message);\n throw new IllegalStateException(message);\n }\n\n // The head offset for Kafka partition is the offset of the next message to be indexed. We\n // assume that offset is passed into this function. The highest durable offset is the partition\n // offset of the message that is indexed. Hence, the offset is incremented by 1 to get the\n // next message.\n long nextOffsetForPartition = highestDurableOffsetForPartition + 1;\n\n // Create a recovery task if needed.\n if (currentEndOffsetForPartition - highestDurableOffsetForPartition > maxOffsetDelay) {\n LOG.info(\n \"Recovery task needed. The current position {} and head location {} are higher than max\"\n + \" offset {}\",\n highestDurableOffsetForPartition,\n currentEndOffsetForPartition,\n maxOffsetDelay);\n createRecoveryTasks(\n partitionId,\n nextOffsetForPartition,\n currentEndOffsetForPartition - 1,\n maxMessagesPerRecoveryTask);\n return currentEndOffsetForPartition;\n } else {\n LOG.info(\n \"The difference between the last indexed position {} and head location {} is lower \"\n + \"than max offset {}. So, using {} position as the start offset\",\n highestDurableOffsetForPartition,\n currentEndOffsetForPartition,\n maxOffsetDelay,\n nextOffsetForPartition);\n return nextOffsetForPartition;\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testDetermineStartingOffsetMultiplePartitionRecoveriesBehind()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testDetermineStartingOffsetMultiplePartitionRecoveriesBehind", "reference": " @Test\n public void testDetermineStartingOffsetMultiplePartitionRecoveriesBehind() {\n RecoveryTaskCreator recoveryTaskCreator =\n new RecoveryTaskCreator(\n snapshotMetadataStore,\n recoveryTaskStore,\n partitionId,\n 100,\n TEST_MAX_MESSAGES_PER_RECOVERY_TASK,\n meterRegistry);\n\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore)).isEmpty();\n assertThat(AstraMetadataTestUtils.listSyncUncached(recoveryTaskStore)).isEmpty();\n\n // When there is no data return -1.\n assertThat(recoveryTaskCreator.determineStartingOffset(1000, 0, indexerConfig)).isNegative();\n final String recoveryTaskName = \"BasicRecoveryTask\";\n final long recoveryStartOffset = 400;\n final long createdTimeUtc = Instant.now().toEpochMilli();\n\n final RecoveryTaskMetadata recoveryTask1 =\n new RecoveryTaskMetadata(\n recoveryTaskName + \"1\",\n partitionId,\n recoveryStartOffset,\n recoveryStartOffset * 2,\n createdTimeUtc);\n recoveryTaskStore.createSync(recoveryTask1);\n final RecoveryTaskMetadata recoveryTask11 =\n new RecoveryTaskMetadata(\n recoveryTaskName + \"11\",\n partitionId,\n recoveryStartOffset * 2 + 1,\n recoveryStartOffset * 3,\n createdTimeUtc);\n recoveryTaskStore.createSync(recoveryTask11);\n final RecoveryTaskMetadata recoveryTask2 =\n new RecoveryTaskMetadata(\n recoveryTaskName + \"2\",\n \"2\",\n recoveryStartOffset * 3 + 1,\n recoveryStartOffset * 4,\n createdTimeUtc);\n recoveryTaskStore.createSync(recoveryTask2);\n final RecoveryTaskMetadata recoveryTask21 =\n new RecoveryTaskMetadata(\n recoveryTaskName + \"21\", \"2\", recoveryStartOffset * 4 + 1, 50000, createdTimeUtc);\n recoveryTaskStore.createSync(recoveryTask21);\n await()\n .until(\n () ->\n recoveryTaskStore\n .listSync()\n .containsAll(\n List.of(recoveryTask1, recoveryTask11, recoveryTask2, recoveryTask21)));\n\n final long currentHeadOffset = 4000;\n assertThat(recoveryTaskCreator.determineStartingOffset(currentHeadOffset, 0, indexerConfig))\n .isEqualTo(currentHeadOffset);\n List recoveryTasks =\n AstraMetadataTestUtils.listSyncUncached(recoveryTaskStore);\n assertThat(recoveryTasks.size()).isEqualTo(5);\n assertThat(recoveryTasks)\n .contains(recoveryTask1, recoveryTask11, recoveryTask2, recoveryTask21);\n Optional newRecoveryTask =\n recoveryTasks.stream().filter(r -> !r.name.contains(recoveryTaskName)).findFirst();\n assertThat(newRecoveryTask).isNotEmpty();\n RecoveryTaskMetadata recoveryTask = newRecoveryTask.get();\n assertThat(recoveryTask.startOffset).isEqualTo((recoveryStartOffset * 3) + 1);\n assertThat(recoveryTask.endOffset).isEqualTo(currentHeadOffset - 1);\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore)).isEmpty();\n }", "completions": [ "```java\n @Test\n public void testDetermineStartingOffsetMultiplePartitionRecoveriesBehind() {\n // Given\n String partitionId = \"partition1\";\n long currentEndOffsetForPartition = 100L;\n long currentBeginningOffsetForPartition = 0L;\n AstraConfigs.IndexerConfig indexerConfig = new AstraConfigs.IndexerConfig();\n indexerConfig.setCreateRecoveryTasksOnStart(true);\n indexerConfig.setReadFromLocationOnStart(AstraConfigs.KafkaOffsetLocation.LATEST);\n indexerConfig.setMaxMessagesPerChunk(1000);\n\n // When\n long startingOffset = determineStartingOffset(\n currentEndOffsetForPartition, currentBeginningOffsetForPartition, indexerConfig);\n\n // Then\n assertEquals(101L, startingOffset);\n }\n```\n" ], "line": 127, "token": 935, "line_diff": 2, "token_diff": 2 }, { "id": 24, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public CompletableFuture commitStreamObject(apache.rocketmq.controller.v1.S3StreamObject streamObject,\n List compactedObjects) {\n LOGGER.info(\"commitStreamObject with streamObject: {}, compactedObjects: {}\", TextFormat.shortDebugString(streamObject),\n compactedObjects);\n\n CompletableFuture future = new CompletableFuture<>();\n try (SqlSession session = sessionFactory.openSession()) {\n if (streamObject.getObjectId() == S3Constants.NOOP_OBJECT_ID) {\n LOGGER.error(\"S3StreamObject[object-id={}] is null or objectId is unavailable\", streamObject.getObjectId());\n String msg = String.format(\"S3StreamObject[object-id=%d] is null or objectId is unavailable\",\n streamObject.getObjectId());\n ControllerException e = new ControllerException(Code.NOT_FOUND_VALUE, msg);\n future.completeExceptionally(e);\n return future;\n }\n\n long committedTs = System.currentTimeMillis();\n S3ObjectMapper s3ObjectMapper = session.getMapper(S3ObjectMapper.class);\n S3StreamObjectMapper s3StreamObjectMapper = session.getMapper(S3StreamObjectMapper.class);\n\n // commit object\n if (!commitObject(streamObject.getObjectId(), streamObject.getStreamId(), streamObject.getObjectSize(), session)) {\n String msg = String.format(\"S3StreamObject[object-id=%d] is not ready for commit\",\n streamObject.getObjectId());\n ControllerException e = new ControllerException(Code.ILLEGAL_STATE_VALUE, msg);\n future.completeExceptionally(e);\n return future;\n }\n long dataTs = committedTs;\n if (!Objects.isNull(compactedObjects) && !compactedObjects.isEmpty()) {\n dataTs = compactedObjects.stream()\n .map(id -> {\n // mark destroy compacted object\n S3Object object = s3ObjectMapper.getById(id);\n object.setState(S3ObjectState.BOS_WILL_DELETE);\n object.setMarkedForDeletionTimestamp(new Date());\n s3ObjectMapper.markToDelete(object.getId(), new Date());\n\n // update dataTs to the min compacted object's dataTs\n com.automq.rocketmq.metadata.dao.S3StreamObject s3StreamObject =\n s3StreamObjectMapper.getByObjectId(id);\n return s3StreamObject.getBaseDataTimestamp().getTime();\n })\n .min(Long::compareTo).get();\n }\n\n List toCache = new ArrayList<>();\n\n // create a new S3StreamObject to replace committed ones\n if (streamObject.getObjectId() != S3Constants.NOOP_OBJECT_ID) {\n com.automq.rocketmq.metadata.dao.S3StreamObject newS3StreamObj =\n new com.automq.rocketmq.metadata.dao.S3StreamObject();\n newS3StreamObj.setStreamId(streamObject.getStreamId());\n newS3StreamObj.setObjectId(streamObject.getObjectId());\n newS3StreamObj.setObjectSize(streamObject.getObjectSize());\n newS3StreamObj.setStartOffset(streamObject.getStartOffset());\n newS3StreamObj.setEndOffset(streamObject.getEndOffset());\n newS3StreamObj.setBaseDataTimestamp(new Date(dataTs));\n newS3StreamObj.setCommittedTimestamp(new Date(committedTs));\n s3StreamObjectMapper.create(newS3StreamObj);\n toCache.add(newS3StreamObj);\n }\n\n // delete the compactedObjects of S3Stream\n if (!Objects.isNull(compactedObjects) && !compactedObjects.isEmpty()) {\n compactedObjects.forEach(id -> s3StreamObjectMapper.delete(null, null, id));\n }\n session.commit();\n\n // Update Cache\n s3StreamObjectCache.cache(streamObject.getStreamId(), toCache);\n s3StreamObjectCache.onCompact(streamObject.getStreamId(), compactedObjects);\n\n LOGGER.info(\"S3StreamObject[object-id={}] commit success, compacted objects: {}\",\n streamObject.getObjectId(), compactedObjects);\n future.complete(null);\n } catch (Exception e) {\n LOGGER.error(\"CommitStream failed\", e);\n ControllerException ex = new ControllerException(Code.INTERNAL_VALUE, \"CommitStream failed\" + e.getMessage());\n future.completeExceptionally(ex);\n }\n return future;\n }\n```\n###test function signature:\n```java\n @Test\n public void testCommitStreamObject() throws IOException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testCommitStreamObject", "reference": " @Test\n public void testCommitStreamObject() throws IOException {\n long objectId, streamId = 1;\n\n try (S3MetadataService metadataService = new DefaultS3MetadataService(config, getSessionFactory(), executorService)) {\n objectId = metadataService.prepareS3Objects(3, 5).get();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n\n S3StreamObject news3StreamObject = S3StreamObject.newBuilder()\n .setObjectId(objectId + 2)\n .setStreamId(streamId)\n .setObjectSize(111L)\n .build();\n\n try (SqlSession session = this.getSessionFactory().openSession()) {\n S3StreamObjectMapper s3StreamObjectMapper = session.getMapper(S3StreamObjectMapper.class);\n buildS3StreamObjs(objectId, 2, 3, 100L).forEach(s3StreamObjectMapper::create);\n session.commit();\n }\n\n try (S3MetadataService service = new DefaultS3MetadataService(config, getSessionFactory(), executorService)) {\n List compactedObjects = new ArrayList<>();\n compactedObjects.add(objectId);\n compactedObjects.add(objectId + 1);\n service.commitStreamObject(news3StreamObject, compactedObjects);\n }\n\n try (SqlSession session = getSessionFactory().openSession()) {\n S3ObjectMapper s3ObjectMapper = session.getMapper(S3ObjectMapper.class);\n S3Object s3Object = s3ObjectMapper.getById(objectId);\n Assertions.assertEquals(S3ObjectState.BOS_WILL_DELETE, s3Object.getState());\n\n S3Object s3Object1 = s3ObjectMapper.getById(objectId);\n Assertions.assertEquals(S3ObjectState.BOS_WILL_DELETE, s3Object1.getState());\n\n S3StreamObjectMapper s3StreamObjectMapper = session.getMapper(S3StreamObjectMapper.class);\n for (long index = objectId; index < objectId + 2; index++) {\n com.automq.rocketmq.metadata.dao.S3StreamObject object = s3StreamObjectMapper.getByObjectId(index);\n Assertions.assertNull(object);\n }\n\n com.automq.rocketmq.metadata.dao.S3StreamObject object = s3StreamObjectMapper.getByObjectId(objectId + 2);\n Assertions.assertEquals(111L, object.getObjectSize());\n Assertions.assertEquals(streamId, object.getStreamId());\n Assertions.assertTrue(object.getBaseDataTimestamp().getTime() > 0);\n Assertions.assertTrue(object.getCommittedTimestamp().getTime() > 0);\n }\n }", "completions": [ "```java\n @Test\n public void testCommitStreamObject() throws IOException {\n // Given\n apache.rocketmq.controller.v1.S3StreamObject streamObject = new apache.rocketmq.controller.v1.S3StreamObject();\n streamObject.setObjectId(1L);\n streamObject.setStreamId(2L);\n streamObject.setObjectSize(3L);\n streamObject.setStartOffset(4L);\n streamObject.setEndOffset(5L);\n\n List compactedObjects = Arrays.asList(6L, 7L, 8L);\n\n // When\n CompletableFuture future = controller.commitStreamObject(streamObject, compactedObjects);\n\n // Then\n assertDoesNotThrow(() -> future.get());\n }\n```\n" ], "line": 85, "token": 664, "line_diff": 2, "token_diff": 2 }, { "id": 25, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public ProcessEntity getProcessByKey(Long processDefinitionKey) {\n final SearchRequest searchRequest =\n new SearchRequest(processIndex.getAlias())\n .source(\n new SearchSourceBuilder()\n .query(QueryBuilders.termQuery(ProcessIndex.KEY, processDefinitionKey)));\n\n try {\n final SearchResponse response = tenantAwareClient.search(searchRequest);\n if (response.getHits().getTotalHits().value == 1) {\n return fromSearchHit(response.getHits().getHits()[0].getSourceAsString());\n } else if (response.getHits().getTotalHits().value > 1) {\n throw new NotFoundException(\n String.format(\"Could not find unique process with key '%s'.\", processDefinitionKey));\n } else {\n throw new NotFoundException(\n String.format(\"Could not find process with key '%s'.\", processDefinitionKey));\n }\n } catch (IOException e) {\n final String message =\n String.format(\"Exception occurred, while obtaining the process: %s\", e.getMessage());\n LOGGER.error(message, e);\n throw new OperateRuntimeException(message, e);\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testGetProcessByKeyTooManyResults() throws IOException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testGetProcessByKeyTooManyResults", "reference": " @Test\n public void testGetProcessByKeyTooManyResults() throws IOException {\n when(processIndex.getAlias()).thenReturn(\"processIndexAlias\");\n\n final SearchResponse mockResponse = Mockito.mock(SearchResponse.class);\n final SearchHits mockHits = Mockito.mock(SearchHits.class);\n // Normally TotalHits would just be mocked, but Mockito can't stub or mock direct field accesses\n final TotalHits.Relation mockRelation = Mockito.mock(TotalHits.Relation.class);\n final TotalHits mockTotalHits = new TotalHits(2L, mockRelation);\n\n when(mockResponse.getHits()).thenReturn(mockHits);\n when(mockHits.getTotalHits()).thenReturn(mockTotalHits);\n when(tenantAwareClient.search(any())).thenReturn(mockResponse);\n\n assertThrows(NotFoundException.class, () -> underTest.getProcessByKey(123L));\n }", "completions": [ "```java\n @Test\n public void testGetProcessByKeyTooManyResults() throws IOException {\n // Given\n final Long processDefinitionKey = 123L;\n final SearchRequest searchRequest =\n new SearchRequest(processIndex.getAlias())\n .source(\n new SearchSourceBuilder()\n .query(QueryBuilders.termQuery(ProcessIndex.KEY, processDefinitionKey)));\n\n final SearchResponse response = Mockito.mock(SearchResponse.class);\n final SearchHits hits = Mockito.mock(SearchHits.class);\n final TotalHits totalHits = Mockito.mock(TotalHits.class);\n Mockito.when(totalHits.value).thenReturn(2L);\n Mockito.when(hits.getTotalHits()).thenReturn(totalHits);\n Mockito.when(response.getHits()).thenReturn(hits);\n\n Mockito.when(tenantAwareClient.search(Mockito.any(SearchRequest.class))).thenReturn(response);\n\n // When\n try {\n processService.getProcessByKey(processDefinitionKey);\n fail(\"Expected NotFoundException\");\n } catch (NotFoundException e) {\n // Then\n assertEquals(\n \"Expected exception message to match\",\n String.format(\"Could not find unique process with key '%s'.\", processDefinitionKey),\n e.getMessage());\n }\n }\n```\n" ], "line": 36, "token": 279, "line_diff": 0, "token_diff": 0 }, { "id": 26, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static String doGet(String url) {\n try (CloseableHttpClient client = HttpClients.createDefault()) {\n HttpGet request = new HttpGet(url);\n HttpResponse response = client.execute(request);\n if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {\n return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);\n }\n } catch (IOException e) {\n log.error(\"DoGet exception.\", e);\n\n }\n return null;\n }\n```\n###test function signature:\n```java\n @Test\n void testDoGet()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testDoGet", "reference": " @Test\n void testDoGet() {\n String result = HttpUtil.doGet(\"http://baidu.com\");\n Assertions.assertNotNull(result);\n }", "completions": [ "```java\n @Test\n void testDoGet() {\n String url = \"http://example.com\";\n String expectedResponse = \"Hello, world!\";\n\n // Mock the HttpClient and HttpResponse\n CloseableHttpClient mockClient = Mockito.mock(CloseableHttpClient.class);\n HttpResponse mockResponse = Mockito.mock(HttpResponse.class);\n StatusLine mockStatusLine = Mockito.mock(StatusLine.class);\n HttpEntity mockEntity = Mockito.mock(HttpEntity.class);\n\n // Set up the mock objects to return the expected values\n Mockito.when(mockClient.execute(Mockito.any(HttpGet.class))).thenReturn(mockResponse);\n Mockito.when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);\n Mockito.when(mockStatusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);\n Mockito.when(mockResponse.getEntity()).thenReturn(mockEntity);\n Mockito.when(EntityUtils.toString(mockEntity, StandardCharsets.UTF_8)).thenReturn(expectedResponse);\n\n // Call the method under test\n String actualResponse = YourClassName.doGet(url);\n\n // Verify the result\n Assertions.assertEquals(expectedResponse, actualResponse);\n }\n```\nPlease replace `YourClassName` with the actual name of the class where the `doGet` method is located.\n" ], "line": 23, "token": 162, "line_diff": 0, "token_diff": 0 }, { "id": 27, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public void validateDpopThumprint(String existingThumprint, String requestThumprint) {\n if (StringUtils.isBlank(existingThumprint) && isFalse(appConfiguration.getDpopJktForceForAuthorizationCode())) {\n return; // nothing to check\n }\n\n if (!StringUtils.equals(existingThumprint, requestThumprint)) {\n log.debug(\"DPoP Thumprint between saved one '{}' and send in request '{}' does NOT match. Reject request.\", existingThumprint, requestThumprint);\n throw new WebApplicationException(Response\n .status(Response.Status.BAD_REQUEST)\n .type(MediaType.APPLICATION_JSON_TYPE)\n .entity(errorResponseFactory.errorAsJson(TokenErrorResponseType.INVALID_DPOP_PROOF, \"Thumprint does not match\"))\n .cacheControl(ServerUtil.cacheControl(true, false))\n .header(PRAGMA, NO_CACHE)\n .build());\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void validateDpopThumprint_whenExistingDpopThumprintIsMissedAndConfIsFalse_shouldBeValid()\n```\n### Answer: (use the provided format with backticks)\n", "name": "validateDpopThumprint_whenExistingDpopThumprintIsMissedAndConfIsFalse_shouldBeValid", "reference": " @Test\n public void validateDpopThumprint_whenExistingDpopThumprintIsMissedAndConfIsFalse_shouldBeValid() {\n when(appConfiguration.getDpopJktForceForAuthorizationCode()).thenReturn(false);\n\n dpopService.validateDpopThumprint(null, \"any\");\n }", "completions": [ "```java\n @Test\n public void validateDpopThumprint_whenExistingDpopThumprintIsMissedAndConfIsFalse_shouldBeValid() {\n // Given\n String existingThumprint = \"\";\n String requestThumprint = \"requestThumprint\";\n when(appConfiguration.getDpopJktForceForAuthorizationCode()).thenReturn(false);\n\n // When\n try {\n tokenService.validateDpopThumprint(existingThumprint, requestThumprint);\n } catch (WebApplicationException e) {\n // Then\n assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), e.getResponse().getStatus());\n assertEquals(\"Thumprint does not match\", e.getMessage());\n }\n }\n```\n" ], "line": 26, "token": 209, "line_diff": 0, "token_diff": 0 }, { "id": 28, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public void sendData(String database, String table, String content, boolean partitioned) throws Exception {\n final String loadUrl = String.format(\"http://%s:%s/api/%s/%s/_stream_load?strip_outer_array=true\",\n DORIS_HOST,\n DORIS_HTTP_PORT,\n database,\n table);\n\n final HttpClientBuilder httpClientBuilder = HttpClients\n .custom()\n .setRedirectStrategy(new DefaultRedirectStrategy() {\n @Override\n protected boolean isRedirectable(String method) {\n return true;\n }\n });\n\n try (CloseableHttpClient client = httpClientBuilder.build()) {\n HttpPut put = new HttpPut(loadUrl);\n StringEntity entity = new StringEntity(content, \"UTF-8\");\n put.setHeader(HttpHeaders.EXPECT, \"100-continue\");\n put.setHeader(HttpHeaders.AUTHORIZATION, HttpUtil.basicAuthHeader(DORIS_USER, DORIS_PASSWORD));\n put.setHeader(\"max_filter_ratio\", \"0.1\");\n if (partitioned) {\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"yyyyMMdd\");\n put.setHeader(\"partitions\", \"p\" + simpleDateFormat.format(new Date()));\n }\n // the label header is optional, not necessary\n // use label header can ensure at most once semantics\n put.setEntity(entity);\n try (CloseableHttpResponse response = client.execute(put)) {\n String contentStr = new String(ByteStreams.toByteArray(response.getEntity().getContent()));\n JsonObject jsonObject = jsonParser.parse(contentStr).getAsJsonObject();\n log.info(\"result:{}\", contentStr);\n int statusCode = response.getStatusLine().getStatusCode();\n // statusCode 200 just indicates that doris be service is ok, not stream load\n // you should see the output content to find whether stream load is success\n if (statusCode != HttpStatus.SC_OK || (!jsonObject.get(\"Status\").getAsString().equalsIgnoreCase(\"SUCCESS\") &&\n !jsonObject.get(\"Status\").getAsString().equalsIgnoreCase(\"Publish Timeout\"))) {\n throw new IOException(\n String.format(\"Stream load failed, statusCode=%s load result=%s content=%s\", statusCode, jsonObject.toString(), content));\n }\n } catch (Exception e) {\n log.error(\"error\", e);\n } finally {\n client.close();\n }\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void sendDataMapTest() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "sendDataMapTest", "reference": " @Test\n public void sendDataMapTest() throws Exception {\n String database = \"test\";\n String tableName = \"hera_log_doris_table_2_11\";\n for (int i = 0; i < 1; i++) {\n String jsonString = \"{\\\"linenumber\\\":1256,\\\"tailId\\\":90219,\\\"mqtag\\\":\\\"tags_4_13_90219\\\",\\\"filename\\\":\\\"/home/work/log/log-agent/server.log\\\",\\\"tail\\\":\\\"demo-client-agent\\\",\\\"mqtopic\\\":\\\"90219_hera-demo-client\\\",\\\"message\\\":\\\"2024-01-10 19:34:40,360|INFO ||NettyClientPublicExecutor_1|c.x.mone.log.agent.rpc.task.PingTask|83|ping res: log-agent-server:2022-12-05:0.0.2->2024-01-10 19:34:40 358->10.53.129.250:9899\\\",\\\"logstore\\\":\\\"测试doris日志\\\",\\\"logip\\\":\\\"10.53.129.176\\\",\\\"timestamp\\\":1704886481241}\";\n\n Map map = gson.fromJson(jsonString, Map.class);\n dorisStreamLoad.sendData(database, tableName, columnListNew, map);\n }\n }", "completions": [ "```java\n @Test\n public void sendDataMapTest() throws Exception {\n String database = \"test_db\";\n String table = \"test_table\";\n String content = \"{\\\"columns\\\":[\\\"id\\\",\\\"name\\\",\\\"age\\\"],\\\"rows\\\":[[1,\\\"John\\\",25],[2,\\\"Jane\\\",30]]}\";\n boolean partitioned = true;\n\n sendData(database, table, content, partitioned);\n }\n```\n" ], "line": 57, "token": 486, "line_diff": 2, "token_diff": 2 }, { "id": 29, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public ProcessEntity getProcessByKey(Long processDefinitionKey) {\n final SearchRequest searchRequest =\n new SearchRequest(processIndex.getAlias())\n .source(\n new SearchSourceBuilder()\n .query(QueryBuilders.termQuery(ProcessIndex.KEY, processDefinitionKey)));\n\n try {\n final SearchResponse response = tenantAwareClient.search(searchRequest);\n if (response.getHits().getTotalHits().value == 1) {\n return fromSearchHit(response.getHits().getHits()[0].getSourceAsString());\n } else if (response.getHits().getTotalHits().value > 1) {\n throw new NotFoundException(\n String.format(\"Could not find unique process with key '%s'.\", processDefinitionKey));\n } else {\n throw new NotFoundException(\n String.format(\"Could not find process with key '%s'.\", processDefinitionKey));\n }\n } catch (IOException e) {\n final String message =\n String.format(\"Exception occurred, while obtaining the process: %s\", e.getMessage());\n LOGGER.error(message, e);\n throw new OperateRuntimeException(message, e);\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testGetProcessByKeyNoResults() throws IOException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testGetProcessByKeyNoResults", "reference": " @Test\n public void testGetProcessByKeyNoResults() throws IOException {\n when(processIndex.getAlias()).thenReturn(\"processIndexAlias\");\n\n final SearchResponse mockResponse = Mockito.mock(SearchResponse.class);\n final SearchHits mockHits = Mockito.mock(SearchHits.class);\n // Normally TotalHits would just be mocked, but Mockito can't stub or mock direct field accesses\n final TotalHits.Relation mockRelation = Mockito.mock(TotalHits.Relation.class);\n final TotalHits mockTotalHits = new TotalHits(0L, mockRelation);\n\n when(mockResponse.getHits()).thenReturn(mockHits);\n when(mockHits.getTotalHits()).thenReturn(mockTotalHits);\n when(tenantAwareClient.search(any())).thenReturn(mockResponse);\n\n assertThrows(NotFoundException.class, () -> underTest.getProcessByKey(123L));\n }", "completions": [ "```java\n @Test\n public void testGetProcessByKeyNoResults() throws IOException {\n // Given\n final Long processDefinitionKey = 123L;\n final SearchRequest searchRequest =\n new SearchRequest(processIndex.getAlias())\n .source(\n new SearchSourceBuilder()\n .query(QueryBuilders.termQuery(ProcessIndex.KEY, processDefinitionKey)));\n\n final SearchResponse response = Mockito.mock(SearchResponse.class);\n final SearchHits hits = Mockito.mock(SearchHits.class);\n Mockito.when(response.getHits()).thenReturn(hits);\n Mockito.when(hits.getTotalHits()).thenReturn(new TotalHits(0L, TotalHits.Relation.EQUAL_TO));\n\n Mockito.when(tenantAwareClient.search(Mockito.any(SearchRequest.class))).thenReturn(response);\n\n // When\n final NotFoundException exception =\n Assertions.assertThrows(\n NotFoundException.class, () -> processService.getProcessByKey(processDefinitionKey));\n\n // Then\n Assertions.assertEquals(\n String.format(\"Could not find process with key '%s'.\", processDefinitionKey),\n exception.getMessage());\n }\n```\n" ], "line": 36, "token": 279, "line_diff": 0, "token_diff": 1 }, { "id": 30, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public String getDiagramByKey(Long processDefinitionKey) {\n final IdsQueryBuilder q = idsQuery().addIds(processDefinitionKey.toString());\n\n final SearchRequest searchRequest =\n new SearchRequest(processIndex.getAlias())\n .source(new SearchSourceBuilder().query(q).fetchSource(BPMN_XML, null));\n\n try {\n final SearchResponse response = tenantAwareClient.search(searchRequest);\n\n if (response.getHits().getTotalHits().value == 1) {\n final Map result = response.getHits().getHits()[0].getSourceAsMap();\n return (String) result.get(BPMN_XML);\n } else if (response.getHits().getTotalHits().value > 1) {\n throw new NotFoundException(\n String.format(\"Could not find unique process with id '%s'.\", processDefinitionKey));\n } else {\n throw new NotFoundException(\n String.format(\"Could not find process with id '%s'.\", processDefinitionKey));\n }\n } catch (IOException e) {\n final String message =\n String.format(\n \"Exception occurred, while obtaining the process diagram: %s\", e.getMessage());\n LOGGER.error(message, e);\n throw new OperateRuntimeException(message, e);\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testGetDiagramByKeyTooManyResults() throws IOException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testGetDiagramByKeyTooManyResults", "reference": " @Test\n public void testGetDiagramByKeyTooManyResults() throws IOException {\n when(processIndex.getAlias()).thenReturn(\"processIndexAlias\");\n\n final SearchResponse mockResponse = Mockito.mock(SearchResponse.class);\n final SearchHits mockHits = Mockito.mock(SearchHits.class);\n // Normally TotalHits would just be mocked, but Mockito can't stub or mock direct field accesses\n final TotalHits.Relation mockRelation = Mockito.mock(TotalHits.Relation.class);\n final TotalHits mockTotalHits = new TotalHits(2L, mockRelation);\n\n when(mockResponse.getHits()).thenReturn(mockHits);\n when(mockHits.getTotalHits()).thenReturn(mockTotalHits);\n when(tenantAwareClient.search(any())).thenReturn(mockResponse);\n\n assertThrows(NotFoundException.class, () -> underTest.getDiagramByKey(123L));\n }", "completions": [ "```java\n @Test\n public void testGetDiagramByKeyTooManyResults() throws IOException {\n // Given\n final Long processDefinitionKey = 1L;\n final SearchRequest searchRequest =\n new SearchRequest(processIndex.getAlias())\n .source(new SearchSourceBuilder().query(q).fetchSource(BPMN_XML, null));\n\n final SearchResponse response = Mockito.mock(SearchResponse.class);\n final SearchHits hits = Mockito.mock(SearchHits.class);\n Mockito.when(response.getHits()).thenReturn(hits);\n Mockito.when(hits.getTotalHits()).thenReturn(new TotalHits(2L, TotalHits.Relation.EQUAL_TO));\n\n // When\n try {\n Mockito.when(tenantAwareClient.search(Mockito.any(SearchRequest.class))).thenReturn(response);\n processDiagramService.getDiagramByKey(processDefinitionKey);\n } catch (NotFoundException e) {\n // Then\n Assert.assertEquals(\n \"Could not find unique process with id '\" + processDefinitionKey + \"'.\", e.getMessage());\n }\n }\n```\n" ], "line": 37, "token": 309, "line_diff": 0, "token_diff": 1 }, { "id": 31, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n void shutdown() {\n LOG.info(\"Running shutdown hook.\");\n try {\n serviceManager.stopAsync().awaitStopped(30, TimeUnit.SECONDS);\n } catch (Exception e) {\n // stopping timed out\n LOG.error(\"ServiceManager shutdown timed out\", e);\n }\n try {\n curatorFramework.unwrap().close();\n } catch (Exception e) {\n LOG.error(\"Error while closing curatorFramework \", e);\n }\n LOG.info(\"Shutting down LogManager\");\n LogManager.shutdown();\n }\n```\n###test function signature:\n```java\n @Test\n public void testIndexerShutdownTwice() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "testIndexerShutdownTwice", "reference": " @Test\n public void testIndexerShutdownTwice() throws Exception {\n startKafkaServer();\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore)).isEmpty();\n assertThat(AstraMetadataTestUtils.listSyncUncached(recoveryTaskStore)).isEmpty();\n\n // Create a live partition for this partiton\n final String name = \"testSnapshotId\";\n final String path = \"/testPath_\" + name;\n final long startTimeMs = 1;\n final long endTimeMs = 100;\n final long maxOffset = 30;\n SnapshotMetadata livePartition0 =\n new SnapshotMetadata(\n name + \"live0\",\n LIVE_SNAPSHOT_PATH,\n startTimeMs,\n endTimeMs,\n maxOffset,\n \"0\",\n LOGS_LUCENE9);\n snapshotMetadataStore.createSync(livePartition0);\n\n SnapshotMetadata livePartition1 =\n new SnapshotMetadata(\n name + \"live1\",\n LIVE_SNAPSHOT_PATH,\n startTimeMs,\n endTimeMs,\n maxOffset,\n \"1\",\n LOGS_LUCENE9);\n snapshotMetadataStore.createSync(livePartition1);\n\n final SnapshotMetadata partition0 =\n new SnapshotMetadata(name, path, startTimeMs, endTimeMs, maxOffset, \"0\", LOGS_LUCENE9);\n snapshotMetadataStore.createSync(partition0);\n\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore))\n .containsOnly(livePartition1, livePartition0, partition0);\n\n // Empty consumer offset since there is no prior consumer.\n astraIndexer =\n new AstraIndexer(\n chunkManagerUtil.chunkManager,\n curatorFramework,\n makeIndexerConfig(50),\n getKafkaConfig(),\n metricsRegistry);\n astraIndexer.startAsync();\n astraIndexer.awaitRunning(DEFAULT_START_STOP_DURATION);\n await().until(() -> kafkaServer.getConnectedConsumerGroups() == 1);\n\n // Produce more messages since the recovery task is created for head.\n produceMessagesToKafka(kafkaServer.getBroker(), startTime);\n\n consumeMessagesAndSearchMessagesTest(100, 1);\n\n // Live snapshot is deleted, recovery task is created.\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore))\n .contains(livePartition1, partition0);\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore).size()).isEqualTo(4);\n assertThat(AstraMetadataTestUtils.listSyncUncached(recoveryTaskStore).size()).isEqualTo(1);\n assertThat(AstraMetadataTestUtils.listSyncUncached(searchMetadataStore).size()).isEqualTo(1);\n RecoveryTaskMetadata recoveryTask1 =\n AstraMetadataTestUtils.listSyncUncached(recoveryTaskStore).get(0);\n assertThat(recoveryTask1.startOffset).isEqualTo(31);\n assertThat(recoveryTask1.endOffset).isEqualTo(99);\n assertThat(recoveryTask1.partitionId).isEqualTo(\"0\");\n\n // Shutting down is idempotent. So, doing it twice shouldn't throw an error.\n astraIndexer.shutDown();\n astraIndexer.shutDown();\n astraIndexer = null;\n }", "completions": [ "```java\n @Test\n public void testIndexerShutdownTwice() throws Exception {\n // Given\n Indexer indexer = new Indexer();\n indexer.serviceManager = Mockito.mock(ServiceManager.class);\n indexer.curatorFramework = Mockito.mock(CuratorFramework.class);\n Mockito.when(indexer.serviceManager.stopAsync()).thenReturn(Mockito.mock(ServiceManager.class));\n Mockito.when(indexer.serviceManager.awaitStopped(Mockito.anyLong(), Mockito.any(TimeUnit.class))).thenThrow(new TimeoutException());\n Mockito.when(indexer.curatorFramework.unwrap()).thenReturn(Mockito.mock(Closeable.class));\n Mockito.doThrow(new IOException()).when(indexer.curatorFramework.unwrap()).close();\n\n // When\n indexer.shutdown();\n\n // Then\n Mockito.verify(indexer.serviceManager, Mockito.times(1)).stopAsync();\n Mockito.verify(indexer.serviceManager, Mockito.times(1)).awaitStopped(Mockito.anyLong(), Mockito.any(TimeUnit.class));\n Mockito.verify(indexer.curatorFramework.unwrap(), Mockito.times(1)).close();\n }\n```\n" ], "line": 27, "token": 177, "line_diff": 0, "token_diff": 0 }, { "id": 32, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public SendStatus sendHtmlMail(String subject, List toList, String username, String agentName, String emailHref, String maiContent) {\n SendStatus sendStatus = new SendStatus(SEND_STATUS_FALSE, \"\");\n List notInBlacklistAddress = checkNotInBlacklistAddress(toList,sendStatus);\n if(CollectionUtils.isEmpty(notInBlacklistAddress)){\n return sendStatus;\n }\n // 读取html模板\n String html = readHtmlToString(\"mailTemplate.html\");\n\n // 写入模板内容\n Document doc = Jsoup.parse(html);\n doc.getElementById(\"username\").html(username);\n\n if (StringUtils.isEmpty(agentName)) {\n sendStatus.setErrorMessage(\"agentName 为空\");\n return sendStatus;\n }\n doc.getElementById(\"sysName\").html(\"Your Agent:\");\n doc.getElementById(\"agentName\").html(agentName);\n doc.getElementById(\"mailContent\").html(maiContent);\n doc.getElementById(\"clickHref\").attr(\"href\", emailHref);\n\n String result = doc.toString();\n Properties props = new Properties();\n props.put(\"mail.smtp.host\", \"\");\n props.put(\"mail.smtp.auth\", \"true\");\n props.put(\"mail.smtp.socketFactory.class\", \"javax.net.ssl.SSLSocketFactory\");\n props.put(\"mail.smtp.socketFactory.fallback\", \"true\");\n Session session = Session.getDefaultInstance(props);\n session.setDebug(true);\n\n Transport transport = null;\n MimeMessage message = new MimeMessage(session);\n try {\n //初始化发送邮件配置\n this.initMailConfig();\n message.setFrom(new InternetAddress(this.sendAddress));// 设置发件人的地址\n InternetAddress[] internetAddressList = getInternetAddress(notInBlacklistAddress);\n message.setRecipients(Message.RecipientType.TO, internetAddressList);// 设置收件人,并设置其接收类型为TO\n message.setSubject(subject);// 设置标题\n message.setContent(result, \"text/html;charset=UTF-8\"); // 设置邮件内容类型为html\n message.setSentDate(new Date());// 设置发信时间\n message.saveChanges();// 存储邮件信息\n\n // 发送邮件\n transport = session.getTransport(\"smtp\");\n if (null != port) {\n transport.connect(host, port, user, password);\n } else {\n transport.connect(host, user, password);\n }\n transport.sendMessage(message, message.getAllRecipients());\n\n //发送邮件成功,status置为true\n sendStatus.setStatus(\"true\");\n } catch (Exception e) {\n log.error(\"邮件发送异常\", e);\n sendStatus.setErrorMessage(e.getMessage());\n } finally {\n if (null != transport) {\n try {\n transport.close();//关闭连接\n } catch (MessagingException e) {\n log.error(\"发送邮件 ,transport 关闭异常\", e);\n }\n }\n }\n return sendStatus;\n }\n```\n###test function signature:\n```java\n @Test\n void testSendHtmlMail_notInBlacklistAddressIsNull()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testSendHtmlMail_notInBlacklistAddressIsNull", "reference": " @Test\n void testSendHtmlMail_notInBlacklistAddressIsNull(){\n when(blacklistService.inBlacklist(anyString())).thenReturn(true);\n List addressList = new ArrayList<>();\n addressList.add(\"test@qq.com\");\n SendStatus result = mailUtils.sendHtmlMail(addressList,\"test\",\"test\",\"test\", SystemEnum.AGENT, MsgTypeEnum.ALARM);\n Assertions.assertEquals(\"false\",result.getStatus());\n Assertions.assertTrue(result.getErrorMessage().contains(\"blacklist\"));\n }", "completions": [ "```java\n @Test\n void testSendHtmlMail_notInBlacklistAddressIsNull() {\n // Arrange\n String subject = \"Test Subject\";\n List toList = null;\n String username = \"Test User\";\n String agentName = \"Test Agent\";\n String emailHref = \"http://test.com\";\n String maiContent = \"Test Content\";\n\n // Act\n SendStatus result = mailService.sendHtmlMail(subject, toList, username, agentName, emailHref, maiContent);\n\n // Assert\n assertEquals(SEND_STATUS_FALSE, result.getStatus());\n assertEquals(\"\", result.getErrorMessage());\n }\n```\n" ], "line": 74, "token": 533, "line_diff": 2, "token_diff": 2 }, { "id": 33, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public ProcessEntity getProcessByKey(Long processDefinitionKey) {\n final SearchRequest searchRequest =\n new SearchRequest(processIndex.getAlias())\n .source(\n new SearchSourceBuilder()\n .query(QueryBuilders.termQuery(ProcessIndex.KEY, processDefinitionKey)));\n\n try {\n final SearchResponse response = tenantAwareClient.search(searchRequest);\n if (response.getHits().getTotalHits().value == 1) {\n return fromSearchHit(response.getHits().getHits()[0].getSourceAsString());\n } else if (response.getHits().getTotalHits().value > 1) {\n throw new NotFoundException(\n String.format(\"Could not find unique process with key '%s'.\", processDefinitionKey));\n } else {\n throw new NotFoundException(\n String.format(\"Could not find process with key '%s'.\", processDefinitionKey));\n }\n } catch (IOException e) {\n final String message =\n String.format(\"Exception occurred, while obtaining the process: %s\", e.getMessage());\n LOGGER.error(message, e);\n throw new OperateRuntimeException(message, e);\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testGetProcessByKeyWithException() throws IOException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testGetProcessByKeyWithException", "reference": " @Test\n public void testGetProcessByKeyWithException() throws IOException {\n when(processIndex.getAlias()).thenReturn(\"processIndexAlias\");\n when(tenantAwareClient.search(any())).thenThrow(new IOException());\n\n assertThrows(OperateRuntimeException.class, () -> underTest.getProcessByKey(123L));\n }", "completions": [ "```java\n @Test\n public void testGetProcessByKeyWithException() throws IOException {\n // Given\n final Long processDefinitionKey = 123L;\n final SearchRequest searchRequest =\n new SearchRequest(processIndex.getAlias())\n .source(\n new SearchSourceBuilder()\n .query(QueryBuilders.termQuery(ProcessIndex.KEY, processDefinitionKey)));\n\n final SearchResponse response = Mockito.mock(SearchResponse.class);\n final SearchHits searchHits = Mockito.mock(SearchHits.class);\n final TotalHits totalHits = Mockito.mock(TotalHits.class);\n Mockito.when(response.getHits()).thenReturn(searchHits);\n Mockito.when(searchHits.getTotalHits()).thenReturn(totalHits);\n Mockito.when(totalHits.value).thenReturn(2L);\n\n Mockito.when(tenantAwareClient.search(Mockito.any(SearchRequest.class))).thenReturn(response);\n\n // When\n final Executable executable = () -> processService.getProcessByKey(processDefinitionKey);\n\n // Then\n final NotFoundException exception =\n Assertions.assertThrows(NotFoundException.class, executable);\n Assertions.assertEquals(\n String.format(\"Could not find unique process with key '%s'.\", processDefinitionKey),\n exception.getMessage());\n }\n```\n" ], "line": 36, "token": 279, "line_diff": 0, "token_diff": 1 }, { "id": 34, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public SearchResult search(\n String dataset,\n String queryStr,\n Long startTimeMsEpoch,\n Long endTimeMsEpoch,\n int howMany,\n AggBuilder aggBuilder) {\n\n ensureNonEmptyString(dataset, \"dataset should be a non-empty string\");\n ensureNonNullString(queryStr, \"query should be a non-empty string\");\n if (startTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch >= 0, \"start time should be non-negative value\");\n }\n if (startTimeMsEpoch != null && endTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch < endTimeMsEpoch, \"end time should be greater than start time\");\n }\n ensureTrue(howMany >= 0, \"hits requested should not be negative.\");\n ensureTrue(howMany > 0 || aggBuilder != null, \"Hits or aggregation should be requested.\");\n\n ScopedSpan span = Tracing.currentTracer().startScopedSpan(\"LogIndexSearcherImpl.search\");\n span.tag(\"dataset\", dataset);\n span.tag(\"startTimeMsEpoch\", String.valueOf(startTimeMsEpoch));\n span.tag(\"endTimeMsEpoch\", String.valueOf(endTimeMsEpoch));\n span.tag(\"howMany\", String.valueOf(howMany));\n\n Stopwatch elapsedTime = Stopwatch.createStarted();\n try {\n // Acquire an index searcher from searcher manager.\n // This is a useful optimization for indexes that are static.\n IndexSearcher searcher = searcherManager.acquire();\n\n Query query =\n openSearchAdapter.buildQuery(\n dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, searcher);\n try {\n List results;\n InternalAggregation internalAggregation = null;\n\n if (howMany > 0) {\n CollectorManager topFieldCollector =\n buildTopFieldCollector(howMany, aggBuilder != null ? Integer.MAX_VALUE : howMany);\n MultiCollectorManager collectorManager;\n if (aggBuilder != null) {\n collectorManager =\n new MultiCollectorManager(\n topFieldCollector,\n openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n } else {\n collectorManager = new MultiCollectorManager(topFieldCollector);\n }\n Object[] collector = searcher.search(query, collectorManager);\n\n ScoreDoc[] hits = ((TopFieldDocs) collector[0]).scoreDocs;\n results = new ArrayList<>(hits.length);\n for (ScoreDoc hit : hits) {\n results.add(buildLogMessage(searcher, hit));\n }\n if (aggBuilder != null) {\n internalAggregation = (InternalAggregation) collector[1];\n }\n } else {\n results = Collections.emptyList();\n internalAggregation =\n searcher.search(\n query, openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n }\n\n elapsedTime.stop();\n return new SearchResult<>(\n results, elapsedTime.elapsed(TimeUnit.MICROSECONDS), 0, 0, 1, 1, internalAggregation);\n } finally {\n searcherManager.release(searcher);\n }\n } catch (IOException e) {\n span.error(e);\n throw new IllegalArgumentException(\"Failed to acquire an index searcher.\", e);\n } finally {\n span.finish();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testConcurrentSearches() throws InterruptedException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testConcurrentSearches", "reference": " @Test\n public void testConcurrentSearches() throws InterruptedException {\n Instant time = Instant.ofEpochSecond(1593365471);\n loadTestData(time);\n\n AtomicInteger searchFailures = new AtomicInteger(0);\n AtomicInteger statsFailures = new AtomicInteger(0);\n AtomicInteger searchExceptions = new AtomicInteger(0);\n AtomicInteger successfulRuns = new AtomicInteger(0);\n\n Runnable searchRun =\n () -> {\n for (int i = 0; i < 100; i++) {\n try {\n SearchResult babies =\n strictLogStore.logSearcher.search(\n TEST_DATASET_NAME,\n \"_id:Message3 OR _id:Message4\",\n 0L,\n MAX_TIME,\n 100,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"));\n if (babies.hits.size() != 2) {\n searchFailures.addAndGet(1);\n } else {\n successfulRuns.addAndGet(1);\n }\n } catch (Exception e) {\n searchExceptions.addAndGet(1);\n }\n }\n };\n\n Thread t1 = new Thread(searchRun);\n Thread t2 = new Thread(searchRun);\n t1.start();\n t2.start();\n t1.join();\n t2.join();\n assertThat(searchExceptions.get()).isEqualTo(0);\n assertThat(statsFailures.get()).isEqualTo(0);\n assertThat(searchFailures.get()).isEqualTo(0);\n assertThat(successfulRuns.get()).isEqualTo(200);\n }", "completions": [ "```java\n @Test\n public void testConcurrentSearches() throws InterruptedException {\n // Create a fixed thread pool with 10 threads\n ExecutorService executorService = Executors.newFixedThreadPool(10);\n\n // Create a list to hold the futures\n List>> futures = new ArrayList<>();\n\n // Submit 100 search tasks to the executor service\n for (int i = 0; i < 100; i++) {\n // Create a search task\n Callable> searchTask = () -> {\n // Generate a random dataset\n String dataset = UUID.randomUUID().toString();\n\n // Generate a random query string\n String queryStr = UUID.randomUUID().toString();\n\n // Generate a random start time\n long startTimeMsEpoch = System.currentTimeMillis() - ThreadLocalRandom.current().nextLong(10000);\n\n // Generate a random end time\n long endTimeMsEpoch = startTimeMsEpoch + ThreadLocalRandom.current().nextLong(10000);\n\n // Generate a random number of hits requested\n int howMany = ThreadLocalRandom.current().nextInt(100);\n\n // Generate a random aggregation builder\n AggBuilder aggBuilder = new AggBuilder();\n\n // Perform the search\n return logIndexSearcher.search(dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, howMany, aggBuilder);\n };\n\n // Submit the search task to the executor service and add the future to the list\n futures.add(executorService.submit(searchTask));\n }\n\n // Wait for all search tasks to complete\n for (Future> future : futures) {\n future.get();\n }\n\n // Shutdown the executor service\n executorService.shutdown();\n }\n```\n" ], "line": 85, "token": 608, "line_diff": 2, "token_diff": 2 }, { "id": 35, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static String sendGetData(String path, Map headMap) {\n log.info(\"request tcm, path:{},headMap:{} \",path,headMap);\n String result = \"\";\n CloseableHttpResponse response =null;\n try(CloseableHttpClient httpClient = HttpClients.createDefault()) {\n // 创建get方式请求对象\n HttpGet httpGet = new HttpGet(path);\n if (null != headMap) {\n for (Map.Entry entry : headMap.entrySet()) {\n httpGet.addHeader(entry.getKey(), entry.getValue());\n }\n }\n // 通过请求对象获取响应对象\n response = httpClient.execute(httpGet);\n\n // 获取结果实体\n // 判断网络连接状态码是否正常(0--200都数正常)\n if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {\n result = EntityUtils.toString(response.getEntity(), UTF_8);\n } else {\n log.error(\"get请求传输 异常.url:{}, headMap:{}\", path, headMap);\n }\n } catch (ClientProtocolException e) {\n log.error(\"get请求传输 异常 \", e);\n log.error(\"get请求传输 异常.path:{}, headMap:{}\", path, headMap);\n } catch (IOException e) {\n log.error(\"get请求传输 异常 \", e);\n log.error(\"get请求传输 异常.path:{}, headMap:{}\", path, headMap);\n }\n finally {\n try {\n if (null!=response){\n response.close();\n }\n } catch (IOException e) {\n log.error(\"关闭response 异常 \", e);\n }\n }\n log.debug(result);\n return result;\n }\n```\n###test function signature:\n```java\n @Test\n void testSendGetData()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testSendGetData", "reference": " @Test\n void testSendGetData() {\n final Map headMap = new HashMap<>();\n final String result = HttpUtils.sendGetData(\"path\", headMap);\n assertThat(result).isEqualTo(\"\");\n }", "completions": [ "```java\n @Test\n void testSendGetData() {\n String path = \"http://localhost:8080/api/test\";\n Map headMap = new HashMap<>();\n headMap.put(\"Content-Type\", \"application/json\");\n headMap.put(\"Authorization\", \"Bearer your_token\");\n\n String result = sendGetData(path, headMap);\n\n // Add assertions to verify the result\n // For example, if the result is expected to be a JSON string, you can use a JSON library to parse the result and assert the values\n // Here is an example using the JSON library Jackson\n ObjectMapper objectMapper = new ObjectMapper();\n JsonNode jsonNode = objectMapper.readTree(result);\n assertEquals(\"expectedValue\", jsonNode.get(\"key\").asText());\n }\n```\nPlease replace \"your_token\" with the actual token you want to use for the test. Also, replace \"expectedValue\" and \"key\" with the actual expected value and key from the JSON response.\n" ], "line": 51, "token": 367, "line_diff": 1, "token_diff": 1 }, { "id": 36, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static ByteString retainKeyPrefix(ByteString tenantNS, List topicFilterLevels) {\n ByteString prefix = ByteString.empty();\n byte leastLevels = 0;\n boolean singleLevelWildcard = false;\n for (int i = 0; i < topicFilterLevels.size(); i++) {\n String tfl = topicFilterLevels.get(i);\n if (\"+\".equals(tfl)) {\n leastLevels++;\n singleLevelWildcard = true;\n continue;\n }\n if (\"#\".equals(tfl)) {\n break;\n }\n leastLevels++;\n if (!singleLevelWildcard) {\n prefix = prefix.concat(copyFromUtf8(tfl));\n }\n if (i + 1 < topicFilterLevels.size()) {\n if (!topicFilterLevels.get(i + 1).equals(\"#\") && !singleLevelWildcard) {\n prefix = prefix.concat(copyFromUtf8(NUL));\n }\n }\n }\n return tenantNS.concat(unsafeWrap(new byte[] {leastLevels})).concat(prefix);\n }\n```\n###test function signature:\n```java\n @Test\n public void testRetainKeyPrefix()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testRetainKeyPrefix", "reference": " @Test\n public void testRetainKeyPrefix() {\n String tenantId = \"tenantA\";\n ByteString tenantNS = tenantNS(tenantId);\n assertEquals(retainKeyPrefix(tenantNS, parse(\"#\", false)), tenantNS.concat(levelByte(0)));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"/#\", false)), tenantNS.concat(levelByte(1)));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"+\", false)), tenantNS.concat(levelByte(1)));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"+/#\", false)), tenantNS.concat(levelByte(1)));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"a/#\", false)),\n tenantNS.concat(levelByte(1).concat(copyFromUtf8(\"a\"))));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"/a\", false)),\n tenantNS.concat(levelByte(2).concat(copyFromUtf8(NUL).concat(copyFromUtf8(\"a\")))));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"a/+\", false)),\n tenantNS.concat(levelByte(2).concat(copyFromUtf8(\"a\").concat(copyFromUtf8(NUL)))));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"a/b\", false)),\n tenantNS.concat(\n levelByte(2).concat(copyFromUtf8(\"a\")).concat(copyFromUtf8(NUL)).concat(copyFromUtf8(\"b\"))));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"/a/#\", false)),\n tenantNS.concat(\n levelByte(2).concat(copyFromUtf8(NUL).concat(copyFromUtf8(\"a\")))));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"/a/+\", false)),\n tenantNS.concat(\n levelByte(3).concat(copyFromUtf8(NUL).concat(copyFromUtf8(\"a\")).concat(copyFromUtf8(NUL)))));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"/a/+/+\", false)),\n tenantNS.concat(\n levelByte(4).concat(copyFromUtf8(NUL).concat(copyFromUtf8(\"a\")).concat(copyFromUtf8(NUL)))));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"/+/b/\", false)),\n tenantNS.concat(levelByte(4).concat(copyFromUtf8(NUL))));\n assertEquals(retainKeyPrefix(tenantNS, parse(\"/+/b/+/\", false)),\n tenantNS.concat(levelByte(5).concat(copyFromUtf8(NUL))));\n }", "completions": [ "```java\n @Test\n public void testRetainKeyPrefix() {\n ByteString tenantNS = ByteString.copyFromUtf8(\"tenant1\");\n List topicFilterLevels = Arrays.asList(\"level1\", \"level2\", \"+\", \"#\");\n ByteString expectedPrefix = ByteString.copyFromUtf8(\"tenant1\\u0001level1\\u0000level2\");\n ByteString actualPrefix = retainKeyPrefix(tenantNS, topicFilterLevels);\n assertEquals(expectedPrefix, actualPrefix);\n }\n```\n" ], "line": 37, "token": 255, "line_diff": 1, "token_diff": 0 }, { "id": 37, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n @Transactional(rollbackFor = Exception.class)\n public void updateFileConfigMaster(Long id) {\n // 校验存在\n validateFileConfigExists(id);\n // 更新其它为非 master\n fileConfigMapper.updateBatch(new FileConfigDO().setMaster(false));\n // 更新\n fileConfigMapper.updateById(new FileConfigDO().setId(id).setMaster(true));\n // 发送刷新配置的消息\n TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {\n\n @Override\n public void afterCommit() {\n fileConfigProducer.sendFileConfigRefreshMessage();\n }\n\n });\n }\n```\n###test function signature:\n```java\n @Test\n public void testUpdateFileConfigMaster_success()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testUpdateFileConfigMaster_success", "reference": " @Test\n public void testUpdateFileConfigMaster_success() {\n // mock 数据\n FileConfigDO dbFileConfig = randomFileConfigDO().setMaster(false);\n fileConfigMapper.insert(dbFileConfig);// @Sql: 先插入出一条存在的数据\n FileConfigDO masterFileConfig = randomFileConfigDO().setMaster(true);\n fileConfigMapper.insert(masterFileConfig);// @Sql: 先插入出一条存在的数据\n\n // 调用\n fileConfigService.updateFileConfigMaster(dbFileConfig.getId());\n // 断言数据\n assertTrue(fileConfigMapper.selectById(dbFileConfig.getId()).getMaster());\n assertFalse(fileConfigMapper.selectById(masterFileConfig.getId()).getMaster());\n // verify 调用\n verify(fileConfigProducer).sendFileConfigRefreshMessage();\n }", "completions": [ "```java\n @Test\n public void testUpdateFileConfigMaster_success() {\n // 准备数据\n FileConfigDO fileConfigDO = new FileConfigDO();\n fileConfigDO.setId(1L);\n fileConfigDO.setMaster(false);\n fileConfigMapper.insert(fileConfigDO);\n\n // 执行方法\n fileConfigService.updateFileConfigMaster(1L);\n\n // 验证结果\n FileConfigDO updatedFileConfigDO = fileConfigMapper.selectById(1L);\n Assert.assertTrue(updatedFileConfigDO.getMaster());\n\n // 清理数据\n fileConfigMapper.deleteById(1L);\n }\n```\n" ], "line": 28, "token": 164, "line_diff": 0, "token_diff": 0 }, { "id": 38, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n\t@Override\n\tpublic void add(List documents) {\n\n\t\tAssert.notNull(documents, \"The document list should not be null.\");\n\t\tif (CollectionUtils.isEmpty(documents)) {\n\t\t\treturn; // nothing to do;\n\t\t}\n\n\t\tfinal var searchDocuments = documents.stream().map(document -> {\n\t\t\tfinal var embeddings = this.embeddingClient.embed(document);\n\t\t\tSearchDocument searchDocument = new SearchDocument();\n\t\t\tsearchDocument.put(ID_FIELD_NAME, document.getId());\n\t\t\tsearchDocument.put(EMBEDDING_FIELD_NAME, embeddings);\n\t\t\tsearchDocument.put(CONTENT_FIELD_NAME, document.getContent());\n\t\t\tsearchDocument.put(METADATA_FIELD_NAME, new JSONObject(document.getMetadata()).toJSONString());\n\n\t\t\t// Add the filterable metadata fields as top level fields, allowing filler\n\t\t\t// expressions on them.\n\t\t\tfor (MetadataField mf : this.filterMetadataFields) {\n\t\t\t\tif (document.getMetadata().containsKey(mf.name())) {\n\t\t\t\t\tsearchDocument.put(METADATA_FIELD_PREFIX + mf.name(), document.getMetadata().get(mf.name()));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn searchDocument;\n\t\t}).toList();\n\n\t\tIndexDocumentsResult result = this.searchClient.uploadDocuments(searchDocuments);\n\n\t\tfor (IndexingResult indexingResult : result.getResults()) {\n\t\t\tAssert.isTrue(indexingResult.isSucceeded(),\n\t\t\t\t\tString.format(\"Document with key %s upload is not successfully\", indexingResult.getKey()));\n\t\t}\n\t}\n```\n###test function signature:\n```java\n\t@Test\n\tpublic void addAndSearchTest()\n```\n### Answer: (use the provided format with backticks)\n", "name": "addAndSearchTest", "reference": "\t@Test\n\tpublic void addAndSearchTest() {\n\n\t\tcontextRunner.run(context -> {\n\n\t\t\tVectorStore vectorStore = context.getBean(VectorStore.class);\n\n\t\t\tvectorStore.add(documents);\n\n\t\t\tAwaitility.await().until(() -> {\n\t\t\t\treturn vectorStore.similaritySearch(SearchRequest.query(\"Great Depression\").withTopK(1));\n\t\t\t}, hasSize(1));\n\n\t\t\tList results = vectorStore.similaritySearch(SearchRequest.query(\"Great Depression\").withTopK(1));\n\n\t\t\tassertThat(results).hasSize(1);\n\t\t\tDocument resultDoc = results.get(0);\n\t\t\tassertThat(resultDoc.getId()).isEqualTo(documents.get(2).getId());\n\t\t\tassertThat(resultDoc.getContent()).contains(\"The Great Depression (1929–1939) was an economic shock\");\n\t\t\tassertThat(resultDoc.getMetadata()).hasSize(2);\n\t\t\tassertThat(resultDoc.getMetadata()).containsKey(\"meta2\");\n\t\t\tassertThat(resultDoc.getMetadata()).containsKey(\"distance\");\n\n\t\t\t// Remove all documents from the store\n\t\t\tvectorStore.delete(documents.stream().map(doc -> doc.getId()).toList());\n\n\t\t\tAwaitility.await().until(() -> {\n\t\t\t\treturn vectorStore.similaritySearch(SearchRequest.query(\"Hello\").withTopK(1));\n\t\t\t}, hasSize(0));\n\t\t});\n\t}", "completions": [ "```java\n\t@Test\n\tpublic void addAndSearchTest() {\n\t\t// Given\n\t\tList documents = new ArrayList<>();\n\t\tDocument document1 = new Document();\n\t\tdocument1.setId(\"1\");\n\t\tdocument1.setContent(\"This is a test document\");\n\t\tdocument1.setMetadata(new HashMap<>());\n\t\tdocument1.getMetadata().put(\"author\", \"John Doe\");\n\t\tdocument1.getMetadata().put(\"date\", \"2022-01-01\");\n\t\tdocuments.add(document1);\n\n\t\tDocument document2 = new Document();\n\t\tdocument2.setId(\"2\");\n\t\tdocument2.setContent(\"This is another test document\");\n\t\tdocument2.setMetadata(new HashMap<>());\n\t\tdocument2.getMetadata().put(\"author\", \"Jane Doe\");\n\t\tdocument2.getMetadata().put(\"date\", \"2022-01-02\");\n\t\tdocuments.add(document2);\n\n\t\t// When\n\t\tsearchService.add(documents);\n\n\t\t// Then\n\t\tSearchRequest searchRequest = new SearchRequest();\n\t\tsearchRequest.setQuery(\"test\");\n\t\tsearchRequest.setFilter(new HashMap<>());\n\t\tsearchRequest.getFilter().put(\"author\", \"John Doe\");\n\t\tSearchResponse searchResponse = searchService.search(searchRequest);\n\n\t\tAssert.assertEquals(1, searchResponse.getDocuments().size());\n\t\tAssert.assertEquals(\"1\", searchResponse.getDocuments().get(0).getId());\n\t}\n```\n" ], "line": 39, "token": 312, "line_diff": 1, "token_diff": 1 }, { "id": 39, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public void collect(CollectRep.MetricsData.Builder builder, long monitorId, String app, Metrics metrics) {\n long startTime = System.currentTimeMillis();\n\n // 校验参数\n try {\n validateParams(metrics);\n } catch (Exception e) {\n builder.setCode(CollectRep.Code.FAIL);\n builder.setMsg(e.getMessage());\n return;\n }\n\n HttpContext httpContext = createHttpContext(metrics.getNginx());\n HttpUriRequest request = createHttpRequest(metrics.getNginx());\n try (CloseableHttpResponse response = CommonHttpClient.getHttpClient().execute(request, httpContext)){\n // 发起http请求,获取响应数据\n int statusCode = response.getStatusLine().getStatusCode();\n if (statusCode != SUCCESS_CODE) {\n builder.setCode(CollectRep.Code.FAIL);\n builder.setMsg(\"StatusCode \" + statusCode);\n return;\n }\n String resp = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);\n\n Long responseTime = System.currentTimeMillis() - startTime;\n // 根据metrics name选择调用不同解析方法\n if (NGINX_STATUS_NAME.equals(metrics.getName()) || AVAILABLE.equals(metrics.getName())) {\n parseNginxStatusResponse(builder, resp, metrics, responseTime);\n } else if (REQ_STATUS_NAME.equals(metrics.getName())) {\n parseReqStatusResponse(builder, resp, metrics, responseTime);\n }\n } catch (Exception e) {\n String errorMsg = CommonUtil.getMessageFromThrowable(e);\n log.info(errorMsg);\n builder.setCode(CollectRep.Code.FAIL);\n builder.setMsg(errorMsg);\n } finally {\n if (request != null) {\n request.abort();\n }\n }\n\n }\n```\n###test function signature:\n```java\n @Test\n public void testNginxCollect()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testNginxCollect", "reference": " @Test\n public void testNginxCollect() {\n CollectRep.MetricsData.Builder builder = CollectRep.MetricsData.newBuilder();\n long monitorId = 999;\n String app = \"testNginx\";\n\n Metrics metrics = new Metrics();\n metrics.setNginx(nginxProtocol);\n nginxCollect.collect(builder, monitorId, app, metrics);\n }", "completions": [ "```java\n @Test\n public void testNginxCollect() {\n // 创建一个Metrics对象\n Metrics metrics = new Metrics();\n metrics.setName(\"nginx_status\");\n metrics.setNginx(new Nginx(\"http://localhost:8080/nginx_status\"));\n\n // 创建一个CollectRep.MetricsData.Builder对象\n CollectRep.MetricsData.Builder builder = CollectRep.MetricsData.newBuilder();\n\n // 创建一个NginxCollect对象\n NginxCollect nginxCollect = new NginxCollect();\n\n // 调用collect方法\n nginxCollect.collect(builder, 1, \"test\", metrics);\n\n // 验证结果\n assertEquals(CollectRep.Code.SUCCESS, builder.getCode());\n assertNotNull(builder.getData());\n assertTrue(builder.getData().getMetrics().containsKey(\"active_connections\"));\n assertTrue(builder.getData().getMetrics().containsKey(\"accepts\"));\n assertTrue(builder.getData().getMetrics().containsKey(\"handled\"));\n assertTrue(builder.getData().getMetrics().containsKey(\"requests\"));\n assertTrue(builder.getData().getMetrics().containsKey(\"reading\"));\n assertTrue(builder.getData().getMetrics().containsKey(\"writing\"));\n assertTrue(builder.getData().getMetrics().containsKey(\"waiting\"));\n }\n```\n" ], "line": 51, "token": 335, "line_diff": 1, "token_diff": 1 }, { "id": 40, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Transactional(rollbackOn = Exception.class)\n public void submit(@NonNull PartitionPlanConfig partitionPlanConfig)\n throws SchedulerException, ClassNotFoundException {\n Long databaseId = partitionPlanConfig.getDatabaseId();\n Validate.notNull(databaseId, \"DatabaseId can not be null\");\n // disable all related partition plan task\n Database database = this.databaseService.detail(databaseId);\n disablePartitionPlan(database.getId());\n PartitionPlanEntity partitionPlanEntity = modelToEntity(partitionPlanConfig);\n partitionPlanEntity = this.partitionPlanRepository.save(partitionPlanEntity);\n if (!partitionPlanConfig.isEnabled()\n || CollectionUtils.isEmpty(partitionPlanConfig.getPartitionTableConfigs())) {\n log.info(\"Partition plan is disabled or table config is empty, do nothing and return\");\n return;\n }\n Validate.isTrue(partitionPlanConfig.getCreationTrigger() != null, \"Creation trigger can not be null\");\n if (partitionPlanConfig.getDroppingTrigger() == null) {\n ScheduleEntity createScheduleEntity = createAndEnableSchedule(\n database, partitionPlanConfig.getCreationTrigger());\n createPartitionPlanTables(partitionPlanConfig.getPartitionTableConfigs(),\n partitionPlanEntity.getId(), createScheduleEntity.getId(),\n partitionPlanConfig.getFlowInstanceId(), partitionPlanConfig.getTaskId(),\n partitionPlanConfig.getErrorStrategy(), partitionPlanConfig.getTimeoutMillis());\n return;\n }\n Map> strategy2TblCfgs =\n partitionPlanConfig.getPartitionTableConfigs().stream().flatMap(tableConfig -> {\n Map> strategy2Cfgs =\n tableConfig.getPartitionKeyConfigs().stream()\n .collect(Collectors.groupingBy(PartitionPlanKeyConfig::getStrategy));\n return strategy2Cfgs.values().stream().map(cfgs -> {\n PartitionPlanTableConfig cfg = new PartitionPlanTableConfig();\n cfg.setPartitionKeyConfigs(cfgs);\n cfg.setTableName(tableConfig.getTableName());\n cfg.setEnabled(tableConfig.isEnabled());\n cfg.setPartitionNameInvoker(tableConfig.getPartitionNameInvoker());\n cfg.setPartitionNameInvokerParameters(tableConfig.getPartitionNameInvokerParameters());\n return cfg;\n });\n }).collect(Collectors.groupingBy(cfg -> cfg.getPartitionKeyConfigs().get(0).getStrategy()));\n List createConfigs = strategy2TblCfgs.get(PartitionPlanStrategy.CREATE);\n List dropConfigs = strategy2TblCfgs.get(PartitionPlanStrategy.DROP);\n if (CollectionUtils.isNotEmpty(createConfigs)) {\n ScheduleEntity createScheduleEntity = createAndEnableSchedule(\n database, partitionPlanConfig.getCreationTrigger());\n createPartitionPlanTables(createConfigs,\n partitionPlanEntity.getId(), createScheduleEntity.getId(),\n partitionPlanConfig.getFlowInstanceId(), partitionPlanConfig.getTaskId(),\n partitionPlanConfig.getErrorStrategy(), partitionPlanConfig.getTimeoutMillis());\n }\n if (CollectionUtils.isNotEmpty(dropConfigs)) {\n ScheduleEntity dropScheduleEntity = createAndEnableSchedule(\n database, partitionPlanConfig.getDroppingTrigger());\n createPartitionPlanTables(dropConfigs,\n partitionPlanEntity.getId(), dropScheduleEntity.getId(),\n partitionPlanConfig.getFlowInstanceId(), partitionPlanConfig.getTaskId(),\n partitionPlanConfig.getErrorStrategy(), partitionPlanConfig.getTimeoutMillis());\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void submit_bothCreateAndDropTrigger_submitSucceed() throws ClassNotFoundException, SchedulerException\n```\n### Answer: (use the provided format with backticks)\n", "name": "submit_bothCreateAndDropTrigger_submitSucceed", "reference": " @Test\n public void submit_bothCreateAndDropTrigger_submitSucceed() throws ClassNotFoundException, SchedulerException {\n PartitionPlanTableConfig tableConfig = new PartitionPlanTableConfig();\n tableConfig.setTableName(MYSQL_REAL_RANGE_TABLE_NAME);\n tableConfig.setPartitionNameInvoker(\"CUSTOM_PARTITION_NAME_GENERATOR\");\n SqlExprBasedGeneratorConfig config = new SqlExprBasedGeneratorConfig();\n config.setGenerateExpr(\"concat('p', date_format(from_unixtime(unix_timestamp(\"\n + \"STR_TO_DATE(20240125, '%Y%m%d')) + \"\n + PartitionPlanVariableKey.INTERVAL.getVariable() + \"), '%Y%m%d'))\");\n config.setIntervalGenerateExpr(\"86400\");\n tableConfig.setPartitionNameInvokerParameters(getSqlExprBasedNameGeneratorParameters(config));\n PartitionPlanKeyConfig c3Create = getMysqlc3CreateConfig();\n PartitionPlanKeyConfig datekeyCreate = getMysqldatekeyCreateConfig();\n PartitionPlanKeyConfig dropConfig = getDropConfig();\n tableConfig.setPartitionKeyConfigs(Arrays.asList(c3Create, datekeyCreate, dropConfig));\n\n PartitionPlanConfig partitionPlanConfig = new PartitionPlanConfig();\n partitionPlanConfig.setPartitionTableConfigs(Collections.singletonList(tableConfig));\n partitionPlanConfig.setFlowInstanceId(1L);\n partitionPlanConfig.setTimeoutMillis(180000L);\n partitionPlanConfig.setEnabled(true);\n partitionPlanConfig.setDatabaseId(1L);\n\n long t1 = System.currentTimeMillis();\n long t2 = System.currentTimeMillis() + 1000;\n TriggerConfig createTrigger = TestRandom.nextObject(TriggerConfig.class);\n createTrigger.setStartAt(new Date(t1));\n partitionPlanConfig.setCreationTrigger(createTrigger);\n\n TriggerConfig dropTrigger = TestRandom.nextObject(TriggerConfig.class);\n dropTrigger.setStartAt(new Date(t2));\n partitionPlanConfig.setDroppingTrigger(dropTrigger);\n Database database = TestRandom.nextObject(Database.class);\n database.setId(1L);\n Mockito.when(this.databaseService.detail(1L)).thenReturn(database);\n Mockito.when(this.scheduleService.create(Mockito.argThat(s -> {\n if (s == null) {\n return true;\n }\n TriggerConfig config1 = JsonUtils.fromJson(s.getTriggerConfigJson(), TriggerConfig.class);\n return config1.getStartAt().getTime() == t1;\n }))).thenReturn(TestRandom.nextObject(ScheduleEntity.class));\n Mockito.when(this.scheduleService.create(Mockito.argThat(s -> {\n if (s == null) {\n return true;\n }\n TriggerConfig config1 = JsonUtils.fromJson(s.getTriggerConfigJson(), TriggerConfig.class);\n return config1.getStartAt().getTime() == t2;\n }))).thenReturn(TestRandom.nextObject(ScheduleEntity.class));\n Mockito.doNothing().when(this.scheduleService).enable(Mockito.isA(ScheduleEntity.class));\n this.partitionPlanScheduleService.submit(partitionPlanConfig);\n List actuals = this.partitionPlanTableRepository.findAll();\n Set scheduleIds = actuals.stream()\n .map(PartitionPlanTableEntity::getScheduleId).collect(Collectors.toSet());\n Assert.assertEquals(scheduleIds.size(), 2);\n }", "completions": [ "```java\n @Test\n public void submit_bothCreateAndDropTrigger_submitSucceed() throws ClassNotFoundException, SchedulerException {\n // Given\n PartitionPlanConfig partitionPlanConfig = new PartitionPlanConfig();\n partitionPlanConfig.setDatabaseId(1L);\n partitionPlanConfig.setEnabled(true);\n partitionPlanConfig.setCreationTrigger(new TriggerConfig(TriggerType.CRON, \"0 0 0 * *?\"));\n partitionPlanConfig.setDroppingTrigger(new TriggerConfig(TriggerType.CRON, \"0 0 1 * *?\"));\n partitionPlanConfig.setPartitionTableConfigs(Arrays.asList(\n new PartitionPlanTableConfig(\"table1\", true, \"invoker1\", \"param1\", Arrays.asList(\n new PartitionPlanKeyConfig(\"key1\", PartitionPlanStrategy.CREATE, \"value1\"),\n new PartitionPlanKeyConfig(\"key2\", PartitionPlanStrategy.DROP, \"value2\")\n )),\n new PartitionPlanTableConfig(\"table2\", true, \"invoker2\", \"param2\", Arrays.asList(\n new PartitionPlanKeyConfig(\"key3\", PartitionPlanStrategy.CREATE, \"value3\"),\n new PartitionPlanKeyConfig(\"key4\", PartitionPlanStrategy.DROP, \"value4\")\n ))\n ));\n partitionPlanConfig.setFlowInstanceId(\"flowInstanceId\");\n partitionPlanConfig.setTaskId(\"taskId\");\n partitionPlanConfig.setErrorStrategy(ErrorStrategy.CONTINUE);\n partitionPlanConfig.setTimeoutMillis(1000L);\n\n Database database = new Database();\n database.setId(1L);\n database.setName(\"database\");\n database.setType(DatabaseType.MYSQL);\n database.setHost(\"localhost\");\n database.setPort(3306);\n database.setUsername(\"root\");\n database.setPassword(\"password\");\n database.setDatabaseName(\"test\");\n database.setProperties(\"{}\");\n database.setStatus(DatabaseStatus.ONLINE);\n database.setCreateTime(new Date());\n database.setUpdateTime(new Date());\n when(databaseService.detail(1L)).thenReturn(database);\n\n PartitionPlanEntity partitionPlanEntity = new PartitionPlanEntity();\n partitionPlanEntity.setId(1L);\n partitionPlanEntity.setDatabaseId(1L);\n partitionPlanEntity.setEnabled(true);\n partitionPlanEntity.setCreationTrigger(new TriggerConfig(TriggerType.CRON, \"0 0 0 * *?\"));\n partitionPlanEntity.setDroppingTrigger(new TriggerConfig(TriggerType.CRON, \"0 0 1 * *?\"));\n partitionPlanEntity.setPartitionTableConfigs(Arrays.asList(\n new PartitionPlanTableConfig(\"table1\", true, \"invoker1\", \"param1\", Arrays.asList(\n new PartitionPlanKeyConfig(\"key1\", PartitionPlanStrategy.CREATE, \"value1\"),\n new PartitionPlanKeyConfig(\"key2\", PartitionPlanStrategy.DROP, \"value2\")\n )),\n new PartitionPlanTableConfig(\"table2\", true, \"invoker2\", \"param2\", Arrays.asList(\n new PartitionPlanKeyConfig(\"key3\", PartitionPlanStrategy.CREATE, \"value3\"),\n new PartitionPlanKeyConfig(\"key4\", PartitionPlanStrategy.DROP, \"value4\")\n ))\n ));\n partitionPlanEntity.setFlowInstanceId(\"flowInstanceId\");\n partitionPlanEntity.setTaskId(\"taskId\");\n partitionPlanEntity.setErrorStrategy(ErrorStrategy.CONTINUE);\n partitionPlanEntity.setTimeoutMillis(1000L);\n when(partitionPlanRepository.save(any(PartitionPlanEntity.class))).thenReturn(partitionPlanEntity);\n\n ScheduleEntity createScheduleEntity = new ScheduleEntity();\n createScheduleEntity.setId(1L);\n createScheduleEntity.setDatabaseId(1L);\n createScheduleEntity.setTriggerConfig(new TriggerConfig(TriggerType" ], "line": 70, "token": 530, "line_diff": 2, "token_diff": 2 }, { "id": 41, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public SearchResult search(\n String dataset,\n String queryStr,\n Long startTimeMsEpoch,\n Long endTimeMsEpoch,\n int howMany,\n AggBuilder aggBuilder) {\n\n ensureNonEmptyString(dataset, \"dataset should be a non-empty string\");\n ensureNonNullString(queryStr, \"query should be a non-empty string\");\n if (startTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch >= 0, \"start time should be non-negative value\");\n }\n if (startTimeMsEpoch != null && endTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch < endTimeMsEpoch, \"end time should be greater than start time\");\n }\n ensureTrue(howMany >= 0, \"hits requested should not be negative.\");\n ensureTrue(howMany > 0 || aggBuilder != null, \"Hits or aggregation should be requested.\");\n\n ScopedSpan span = Tracing.currentTracer().startScopedSpan(\"LogIndexSearcherImpl.search\");\n span.tag(\"dataset\", dataset);\n span.tag(\"startTimeMsEpoch\", String.valueOf(startTimeMsEpoch));\n span.tag(\"endTimeMsEpoch\", String.valueOf(endTimeMsEpoch));\n span.tag(\"howMany\", String.valueOf(howMany));\n\n Stopwatch elapsedTime = Stopwatch.createStarted();\n try {\n // Acquire an index searcher from searcher manager.\n // This is a useful optimization for indexes that are static.\n IndexSearcher searcher = searcherManager.acquire();\n\n Query query =\n openSearchAdapter.buildQuery(\n dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, searcher);\n try {\n List results;\n InternalAggregation internalAggregation = null;\n\n if (howMany > 0) {\n CollectorManager topFieldCollector =\n buildTopFieldCollector(howMany, aggBuilder != null ? Integer.MAX_VALUE : howMany);\n MultiCollectorManager collectorManager;\n if (aggBuilder != null) {\n collectorManager =\n new MultiCollectorManager(\n topFieldCollector,\n openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n } else {\n collectorManager = new MultiCollectorManager(topFieldCollector);\n }\n Object[] collector = searcher.search(query, collectorManager);\n\n ScoreDoc[] hits = ((TopFieldDocs) collector[0]).scoreDocs;\n results = new ArrayList<>(hits.length);\n for (ScoreDoc hit : hits) {\n results.add(buildLogMessage(searcher, hit));\n }\n if (aggBuilder != null) {\n internalAggregation = (InternalAggregation) collector[1];\n }\n } else {\n results = Collections.emptyList();\n internalAggregation =\n searcher.search(\n query, openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n }\n\n elapsedTime.stop();\n return new SearchResult<>(\n results, elapsedTime.elapsed(TimeUnit.MICROSECONDS), 0, 0, 1, 1, internalAggregation);\n } finally {\n searcherManager.release(searcher);\n }\n } catch (IOException e) {\n span.error(e);\n throw new IllegalArgumentException(\"Failed to acquire an index searcher.\", e);\n } finally {\n span.finish();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testAllQueryWithFullTextSearchDisabled()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testAllQueryWithFullTextSearchDisabled", "reference": " @Test\n public void testAllQueryWithFullTextSearchDisabled() {\n Instant time = Instant.now();\n Trace.KeyValue customField =\n Trace.KeyValue.newBuilder()\n .setVStr(\"value\")\n .setKey(\"customField\")\n .setFieldType(Schema.SchemaFieldType.KEYWORD)\n .build();\n strictLogStoreWithoutFts.logStore.addMessage(\n SpanUtil.makeSpan(1, \"apple\", time, List.of(customField)));\n strictLogStoreWithoutFts.logStore.commit();\n strictLogStoreWithoutFts.logStore.refresh();\n\n SearchResult termQuery =\n strictLogStoreWithoutFts.logSearcher.search(\n TEST_DATASET_NAME,\n \"customField:value\",\n time.toEpochMilli(),\n time.plusSeconds(2).toEpochMilli(),\n 10,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"));\n assertThat(termQuery.hits.size()).isEqualTo(1);\n\n SearchResult noTermStrQuery =\n strictLogStoreWithoutFts.logSearcher.search(\n TEST_DATASET_NAME,\n \"value\",\n time.toEpochMilli(),\n time.plusSeconds(2).toEpochMilli(),\n 10,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"));\n assertThat(noTermStrQuery.hits.size()).isEqualTo(1);\n\n SearchResult noTermNumericQuery =\n strictLogStoreWithoutFts.logSearcher.search(\n TEST_DATASET_NAME,\n \"1\",\n time.toEpochMilli(),\n time.plusSeconds(2).toEpochMilli(),\n 10,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"));\n assertThat(noTermNumericQuery.hits.size()).isEqualTo(1);\n }", "completions": [ "```java\n @Test\n public void testAllQueryWithFullTextSearchDisabled() {\n // Given\n String dataset = \"testDataset\";\n String queryStr = \"*\";\n Long startTimeMsEpoch = null;\n Long endTimeMsEpoch = null;\n int howMany = 10;\n AggBuilder aggBuilder = null;\n\n // When\n SearchResult result = logIndexSearcher.search(dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, howMany, aggBuilder);\n\n // Then\n assertNotNull(result);\n assertEquals(howMany, result.getResults().size());\n assertNull(result.getInternalAggregation());\n }\n```\n" ], "line": 85, "token": 606, "line_diff": 2, "token_diff": 2 }, { "id": 42, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public ConsumerRecords poll(final Duration timeout) {\n Timer timer = time.timer(timeout);\n\n acquireAndEnsureOpen();\n try {\n kafkaConsumerMetrics.recordPollStart(timer.currentTimeMs());\n\n if (subscriptions.hasNoSubscriptionOrUserAssignment()) {\n throw new IllegalStateException(\"Consumer is not subscribed to any topics or assigned any partitions\");\n }\n\n do {\n\n // Make sure to let the background thread know that we are still polling.\n applicationEventHandler.add(new PollEvent(timer.currentTimeMs()));\n\n // We must not allow wake-ups between polling for fetches and returning the records.\n // If the polled fetches are not empty the consumed position has already been updated in the polling\n // of the fetches. A wakeup between returned fetches and returning records would lead to never\n // returning the records in the fetches. Thus, we trigger a possible wake-up before we poll fetches.\n wakeupTrigger.maybeTriggerWakeup();\n\n updateAssignmentMetadataIfNeeded(timer);\n final Fetch fetch = pollForFetches(timer);\n if (!fetch.isEmpty()) {\n if (fetch.records().isEmpty()) {\n log.trace(\"Returning empty records from `poll()` \"\n + \"since the consumer's position has advanced for at least one topic partition\");\n }\n\n return interceptors.onConsume(new ConsumerRecords<>(fetch.records()));\n }\n // We will wait for retryBackoffMs\n } while (timer.notExpired());\n\n return ConsumerRecords.empty();\n } finally {\n kafkaConsumerMetrics.recordPollEnd(timer.currentTimeMs());\n release();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testEnsurePollExecutedCommitAsyncCallbacks()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testEnsurePollExecutedCommitAsyncCallbacks", "reference": " @Test\n public void testEnsurePollExecutedCommitAsyncCallbacks() {\n consumer = newConsumer();\n MockCommitCallback callback = new MockCommitCallback();\n completeCommitAsyncApplicationEventSuccessfully();\n doReturn(Fetch.empty()).when(fetchCollector).collectFetch(any(FetchBuffer.class));\n completeFetchedCommittedOffsetApplicationEventSuccessfully(mkMap());\n\n consumer.assign(Collections.singleton(new TopicPartition(\"foo\", 0)));\n assertDoesNotThrow(() -> consumer.commitAsync(new HashMap<>(), callback));\n assertMockCommitCallbackInvoked(() -> consumer.poll(Duration.ZERO),\n callback,\n null);\n }", "completions": [ "```java\n @Test\n public void testPoll() {\n // Given\n Duration timeout = Duration.ofMillis(1000);\n Consumer consumer = new KafkaConsumer<>(props);\n consumer.subscribe(Collections.singletonList(\"test-topic\"));\n\n // When\n ConsumerRecords records = consumer.poll(timeout);\n\n // Then\n assertNotNull(records);\n assertEquals(0, records.count());\n }\n```\n" ], "line": 45, "token": 366, "line_diff": 1, "token_diff": 1 }, { "id": 43, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static URI resolve(URI base, URI ref) {\n String path = ref.getRawPath();\n if (path != null && !path.isEmpty()) {\n path = base.getRawPath();\n if (path == null || !path.endsWith(\"/\")) {\n try {\n base = new URI(base.getScheme(), base.getAuthority(), base.getPath() + '/', null, null);\n } catch (URISyntaxException e) {\n throw new IllegalStateException(e);\n }\n }\n }\n return URIUtils.resolve(base, ref);\n }\n```\n###test function signature:\n```java\n @Test\n void testResolve_BasePathTrailingSlash()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testResolve_BasePathTrailingSlash", "reference": " @Test\n void testResolve_BasePathTrailingSlash() {\n URI base = URI.create(\"http://host/sub/dir/\");\n assertEquals(\"http://host/sub/dir/file.jar\", resolve(base, \"file.jar\"));\n assertEquals(\"http://host/sub/dir/dir/file.jar\", resolve(base, \"dir/file.jar\"));\n assertEquals(\"http://host/sub/dir/?arg=val\", resolve(base, \"?arg=val\"));\n assertEquals(\"http://host/sub/dir/file?arg=val\", resolve(base, \"file?arg=val\"));\n assertEquals(\"http://host/sub/dir/dir/file?arg=val\", resolve(base, \"dir/file?arg=val\"));\n }", "completions": [ "```java\n @Test\n void testResolve_BasePathTrailingSlash() {\n URI base = URI.create(\"http://example.com/path/\");\n URI ref = URI.create(\"http://example.com/path/file.txt\");\n URI expected = URI.create(\"http://example.com/path/file.txt\");\n URI actual = resolve(base, ref);\n assertEquals(expected, actual);\n }\n```\n" ], "line": 25, "token": 187, "line_diff": 0, "token_diff": 0 }, { "id": 44, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public T clone(T object) {\n if (object instanceof String) {\n return object;\n } else if (object instanceof Collection) {\n Object firstElement = findFirstNonNullElement((Collection) object);\n if (firstElement != null && !(firstElement instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), firstElement.getClass());\n return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n } else if (object instanceof Map) {\n Map.Entry firstEntry = this.findFirstNonNullEntry((Map) object);\n if (firstEntry != null) {\n Object key = firstEntry.getKey();\n Object value = firstEntry.getValue();\n if (!(key instanceof Serializable) || !(value instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), key.getClass(), value.getClass());\n return (T) objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n }\n } else if (object instanceof JsonNode) {\n return (T) ((JsonNode) object).deepCopy();\n }\n\n if (object instanceof Serializable) {\n try {\n return (T) SerializationHelper.clone((Serializable) object);\n } catch (SerializationException e) {\n //it is possible that object itself implements java.io.Serializable, but underlying structure does not\n //in this case we switch to the other JSON marshaling strategy which doesn't use the Java serialization\n }\n }\n\n return jsonClone(object);\n }\n```\n###test function signature:\n```java\n @Test\n public void should_clone_collection_of_non_serializable_object()\n```\n### Answer: (use the provided format with backticks)\n", "name": "should_clone_collection_of_non_serializable_object", "reference": " @Test\n public void should_clone_collection_of_non_serializable_object() {\n List original = new ArrayList<>();\n original.add(new NonSerializableObject(\"value\"));\n List cloned = serializer.clone(original);\n assertEquals(original, cloned);\n assertNotSame(original, cloned);\n }", "completions": [ "```java\n @Test\n public void should_clone_collection_of_non_serializable_object() {\n // Given\n List nonSerializableList = new ArrayList<>();\n nonSerializableList.add(new NonSerializableObject(\"test\"));\n nonSerializableList.add(new NonSerializableObject(\"test2\"));\n\n // When\n List clonedList = objectCloner.clone(nonSerializableList);\n\n // Then\n assertNotSame(nonSerializableList, clonedList);\n assertEquals(nonSerializableList.size(), clonedList.size());\n for (int i = 0; i < nonSerializableList.size(); i++) {\n assertNotSame(nonSerializableList.get(i), clonedList.get(i));\n assertEquals(nonSerializableList.get(i), clonedList.get(i));\n }\n }\n```\n" ], "line": 44, "token": 358, "line_diff": 1, "token_diff": 1 }, { "id": 45, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public void assign(Collection partitions) {\n acquireAndEnsureOpen();\n try {\n if (partitions == null) {\n throw new IllegalArgumentException(\"Topic partitions collection to assign to cannot be null\");\n }\n\n if (partitions.isEmpty()) {\n unsubscribe();\n return;\n }\n\n for (TopicPartition tp : partitions) {\n String topic = (tp != null) ? tp.topic() : null;\n if (isBlank(topic))\n throw new IllegalArgumentException(\"Topic partitions to assign to cannot have null or empty topic\");\n }\n\n // Clear the buffered data which are not a part of newly assigned topics\n final Set currentTopicPartitions = new HashSet<>();\n\n for (TopicPartition tp : subscriptions.assignedPartitions()) {\n if (partitions.contains(tp))\n currentTopicPartitions.add(tp);\n }\n\n fetchBuffer.retainAll(currentTopicPartitions);\n\n // assignment change event will trigger autocommit if it is configured and the group id is specified. This is\n // to make sure offsets of topic partitions the consumer is unsubscribing from are committed since there will\n // be no following rebalance.\n //\n // See the ApplicationEventProcessor.process() method that handles this event for more detail.\n applicationEventHandler.add(new AssignmentChangeEvent(subscriptions.allConsumed(), time.milliseconds()));\n\n log.info(\"Assigned to partition(s): {}\", join(partitions, \", \"));\n if (subscriptions.assignFromUser(new HashSet<>(partitions)))\n applicationEventHandler.add(new NewTopicsMetadataUpdateRequestEvent());\n } finally {\n release();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testAssign()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testAssign", "reference": " @Test\n public void testAssign() {\n consumer = newConsumer();\n final TopicPartition tp = new TopicPartition(\"foo\", 3);\n consumer.assign(singleton(tp));\n assertTrue(consumer.subscription().isEmpty());\n assertTrue(consumer.assignment().contains(tp));\n verify(applicationEventHandler).add(any(AssignmentChangeEvent.class));\n verify(applicationEventHandler).add(any(NewTopicsMetadataUpdateRequestEvent.class));\n }", "completions": [ "```java\n @Test\n public void testAssign() {\n // Create a mock Consumer instance\n Consumer mockConsumer = mock(Consumer.class);\n\n // Create a collection of TopicPartition instances\n Collection partitions = new ArrayList<>();\n partitions.add(new TopicPartition(\"testTopic\", 0));\n partitions.add(new TopicPartition(\"testTopic\", 1));\n\n // Call the assign method\n mockConsumer.assign(partitions);\n\n // Verify that the assign method was called with the correct parameters\n verify(mockConsumer).assign(partitions);\n }\n```\n" ], "line": 47, "token": 377, "line_diff": 1, "token_diff": 1 }, { "id": 46, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static String relativePath(Path absolutePath, Path basePath) {\n Preconditions.checkArgument(absolutePath.isAbsolute(), \"absolutePath must be an absolute path\");\n Preconditions.checkArgument(basePath.isAbsolute(), \"basePath must be an absolute path\");\n\n List absolutePathComponents = Lists.newArrayList(toPathComponents(absolutePath)); // make a copy\n List basePathComponents = toPathComponents(basePath);\n boolean hasCommonPrefix = basePathComponents.isEmpty(); // when basePath is \"/\", we always have a common prefix\n\n for (String base : basePathComponents) {\n if (absolutePathComponents.get(0).equals(base)) {\n absolutePathComponents.remove(0);\n hasCommonPrefix = true;\n } else {\n break;\n }\n }\n if (hasCommonPrefix) {\n return PATH_JOINER.join(absolutePathComponents);\n } else {\n return absolutePath.toString();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testRelativePath() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "testRelativePath", "reference": " @Test\n public void testRelativePath() throws Exception {\n assertEquals(\"a\", PathUtils.relativePath(Path.of(\"/a\"), Path.of(\"/\")));\n assertEquals(\"b\", PathUtils.relativePath(Path.of(\"/a/b\"), Path.of(\"/a\")));\n assertEquals(\"b/c.json\", PathUtils.relativePath(Path.of(\"/a/b/c.json\"), Path.of(\"/a\")));\n assertEquals(\"c/d/e\", PathUtils.relativePath(Path.of(\"/a/b/c/d/e\"), Path.of(\"/a/b\")));\n assertEquals(\"/a/b\", PathUtils.relativePath(Path.of(\"/a/b\"), Path.of(\"/c/d\"))); // no common prefix\n }", "completions": [ "```java\n @Test\n public void testRelativePath() throws Exception {\n Path absolutePath = Paths.get(\"/a/b/c/d\");\n Path basePath = Paths.get(\"/a/b\");\n String expected = \"c/d\";\n String actual = relativePath(absolutePath, basePath);\n assertEquals(expected, actual);\n }\n```\n" ], "line": 31, "token": 234, "line_diff": 0, "token_diff": 0 }, { "id": 47, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static Boolean isJson(String value) {\n JsonElement jsonElement;\n try {\n jsonElement = JsonParser.parseString(value);\n } catch (Exception e) {\n return false;\n }\n if (jsonElement == null || jsonElement.isJsonNull()) {\n return false;\n }\n if (!jsonElement.isJsonObject() && !jsonElement.isJsonArray()) {\n return false;\n }\n return true;\n }\n```\n###test function signature:\n```java\n @Test\n void testIsJson()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testIsJson", "reference": " @Test\n void testIsJson() {\n assertThat(JsonUtil.isJson(\"value\")).isFalse();\n }", "completions": [ "```java\n @Test\n void testIsJson() {\n // Test case 1: Valid JSON object\n String jsonObject = \"{\\\"name\\\":\\\"John\\\", \\\"age\\\":30, \\\"city\\\":\\\"New York\\\"}\";\n assertTrue(isJson(jsonObject));\n\n // Test case 2: Valid JSON array\n String jsonArray = \"[{\\\"name\\\":\\\"John\\\", \\\"age\\\":30, \\\"city\\\":\\\"New York\\\"}, {\\\"name\\\":\\\"Jane\\\", \\\"age\\\":25, \\\"city\\\":\\\"Chicago\\\"}]\";\n assertTrue(isJson(jsonArray));\n\n // Test case 3: Invalid JSON (not an object or array)\n String invalidJson = \"\\\"name\\\":\\\"John\\\", \\\"age\\\":30, \\\"city\\\":\\\"New York\\\"\";\n assertFalse(isJson(invalidJson));\n\n // Test case 4: Empty string\n String emptyString = \"\";\n assertFalse(isJson(emptyString));\n\n // Test case 5: Null value\n String nullValue = null;\n assertFalse(isJson(nullValue));\n }\n```\n" ], "line": 26, "token": 149, "line_diff": 0, "token_diff": 0 }, { "id": 48, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public SearchResult search(\n String dataset,\n String queryStr,\n Long startTimeMsEpoch,\n Long endTimeMsEpoch,\n int howMany,\n AggBuilder aggBuilder) {\n\n ensureNonEmptyString(dataset, \"dataset should be a non-empty string\");\n ensureNonNullString(queryStr, \"query should be a non-empty string\");\n if (startTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch >= 0, \"start time should be non-negative value\");\n }\n if (startTimeMsEpoch != null && endTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch < endTimeMsEpoch, \"end time should be greater than start time\");\n }\n ensureTrue(howMany >= 0, \"hits requested should not be negative.\");\n ensureTrue(howMany > 0 || aggBuilder != null, \"Hits or aggregation should be requested.\");\n\n ScopedSpan span = Tracing.currentTracer().startScopedSpan(\"LogIndexSearcherImpl.search\");\n span.tag(\"dataset\", dataset);\n span.tag(\"startTimeMsEpoch\", String.valueOf(startTimeMsEpoch));\n span.tag(\"endTimeMsEpoch\", String.valueOf(endTimeMsEpoch));\n span.tag(\"howMany\", String.valueOf(howMany));\n\n Stopwatch elapsedTime = Stopwatch.createStarted();\n try {\n // Acquire an index searcher from searcher manager.\n // This is a useful optimization for indexes that are static.\n IndexSearcher searcher = searcherManager.acquire();\n\n Query query =\n openSearchAdapter.buildQuery(\n dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, searcher);\n try {\n List results;\n InternalAggregation internalAggregation = null;\n\n if (howMany > 0) {\n CollectorManager topFieldCollector =\n buildTopFieldCollector(howMany, aggBuilder != null ? Integer.MAX_VALUE : howMany);\n MultiCollectorManager collectorManager;\n if (aggBuilder != null) {\n collectorManager =\n new MultiCollectorManager(\n topFieldCollector,\n openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n } else {\n collectorManager = new MultiCollectorManager(topFieldCollector);\n }\n Object[] collector = searcher.search(query, collectorManager);\n\n ScoreDoc[] hits = ((TopFieldDocs) collector[0]).scoreDocs;\n results = new ArrayList<>(hits.length);\n for (ScoreDoc hit : hits) {\n results.add(buildLogMessage(searcher, hit));\n }\n if (aggBuilder != null) {\n internalAggregation = (InternalAggregation) collector[1];\n }\n } else {\n results = Collections.emptyList();\n internalAggregation =\n searcher.search(\n query, openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n }\n\n elapsedTime.stop();\n return new SearchResult<>(\n results, elapsedTime.elapsed(TimeUnit.MICROSECONDS), 0, 0, 1, 1, internalAggregation);\n } finally {\n searcherManager.release(searcher);\n }\n } catch (IOException e) {\n span.error(e);\n throw new IllegalArgumentException(\"Failed to acquire an index searcher.\", e);\n } finally {\n span.finish();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testSearchOnlyHistogram()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testSearchOnlyHistogram", "reference": " @Test\n public void testSearchOnlyHistogram() {\n Instant time = Instant.now();\n loadTestData(time);\n SearchResult babies =\n strictLogStore.logSearcher.search(\n TEST_DATASET_NAME,\n \"_id:Message3 OR _id:Message4\",\n time.toEpochMilli(),\n time.plusSeconds(10).toEpochMilli(),\n 0,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"));\n assertThat(babies.hits.size()).isEqualTo(0);\n\n InternalDateHistogram histogram =\n (InternalDateHistogram) Objects.requireNonNull(babies.internalAggregation);\n assertThat(histogram.getBuckets().size()).isEqualTo(2);\n\n assertThat(histogram.getBuckets().get(0).getDocCount()).isEqualTo(1);\n assertThat(histogram.getBuckets().get(1).getDocCount()).isEqualTo(1);\n\n assertThat(\n Long.parseLong(histogram.getBuckets().get(0).getKeyAsString()) >= time.toEpochMilli())\n .isTrue();\n assertThat(\n Long.parseLong(histogram.getBuckets().get(1).getKeyAsString())\n <= time.plusSeconds(10).toEpochMilli())\n .isTrue();\n }", "completions": [ "```java\n @Test\n public void testSearchOnlyHistogram() {\n // Given\n String dataset = \"testDataset\";\n String queryStr = \"testQuery\";\n Long startTimeMsEpoch = null;\n Long endTimeMsEpoch = null;\n int howMany = 0;\n AggBuilder aggBuilder = new AggBuilder();\n aggBuilder.addHistogramAgg(\"testField\", \"testInterval\");\n\n // When\n SearchResult result = logIndexSearcher.search(dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, howMany, aggBuilder);\n\n // Then\n assertNotNull(result);\n assertNotNull(result.getAggregation());\n assertTrue(result.getAggregation().getHistogramAggs().size() > 0);\n assertEquals(\"testField\", result.getAggregation().getHistogramAggs().get(0).getField());\n assertEquals(\"testInterval\", result.getAggregation().getHistogramAggs().get(0).getInterval());\n }\n```\n" ], "line": 85, "token": 606, "line_diff": 2, "token_diff": 2 }, { "id": 49, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public ComponentXO readComponent(final Repository repository, final EntityId componentId) {\n Component component;\n List assets;\n try (StorageTx storageTx = repository.facet(StorageFacet.class).txSupplier().get()) {\n storageTx.begin();\n component = storageTx.findComponent(componentId);\n if (component == null) {\n throw new WebApplicationException(Status.NOT_FOUND);\n }\n\n Iterable browsedAssets = storageTx.browseAssets(component);\n if (browsedAssets == null || Iterables.isEmpty(browsedAssets)) {\n throw new WebApplicationException(Status.NOT_FOUND);\n }\n\n assets = newArrayList(browsedAssets);\n }\n ensurePermissions(repository, assets, BreadActions.BROWSE);\n return COMPONENT_CONVERTER(component, repository.getName());\n }\n```\n###test function signature:\n```java\n @Test\n public void testReadComponent()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testReadComponent", "reference": " @Test\n public void testReadComponent() {\n Component component = mock(Component.class);\n Asset asset = mock(Asset.class);\n EntityMetadata entityMetadata = mock(EntityMetadata.class);\n VariableSource variableSource = mock(VariableSource.class);\n when(contentPermissionChecker.isPermitted(anyString(), any(), eq(BreadActions.BROWSE), any())).thenReturn(true);\n when(component.getEntityMetadata()).thenReturn(entityMetadata);\n when(entityMetadata.getId()).thenReturn(new DetachedEntityId(\"someid\"));\n when(storageTx.findComponent(eq(new DetachedEntityId(\"someid\")))).thenReturn(component);\n when(storageTx.browseAssets(component)).thenReturn(Arrays.asList(asset));\n when(assetVariableResolver.fromAsset(asset)).thenReturn(variableSource);\n ComponentXO componentXO = underTest.readComponent(\"someid\", \"testRepositoryName\");\n\n assertThat(componentXO, is(notNullValue()));\n assertThat(componentXO.getId(), is(\"someid\"));\n }", "completions": [ "```java\n @Test\n public void testReadComponent() {\n // Given\n Repository repository = mock(Repository.class);\n EntityId componentId = mock(EntityId.class);\n StorageFacet storageFacet = mock(StorageFacet.class);\n StorageTx storageTx = mock(StorageTx.class);\n Component component = mock(Component.class);\n Asset asset = mock(Asset.class);\n Supplier txSupplier = () -> storageTx;\n\n when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);\n when(storageFacet.txSupplier()).thenReturn(txSupplier);\n when(storageTx.findComponent(componentId)).thenReturn(component);\n when(storageTx.browseAssets(component)).thenReturn(ImmutableList.of(asset));\n\n // When\n ComponentXO result = readComponent(repository, componentId);\n\n // Then\n verify(repository).facet(StorageFacet.class);\n verify(storageFacet).txSupplier();\n verify(storageTx).begin();\n verify(storageTx).findComponent(componentId);\n verify(storageTx).browseAssets(component);\n verify(storageTx).close();\n // Add assertions for the result\n }\n```\n" ], "line": 29, "token": 205, "line_diff": 0, "token_diff": 0 }, { "id": 50, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public ListResult listEntities(String tableName, String searchIndexName, List matchFilters,\n List queryFilters, List multiMatchFilter, String nextToken, List sorters, Class clazz) {\n SearchQuery searchQuery = createSearchQuery(matchFilters, queryFilters, multiMatchFilter);\n SearchRequest searchRequest = new SearchRequest(tableName, searchIndexName, searchQuery);\n if (!StringUtils.isEmpty(nextToken)) {\n byte[] tokenBytes = EncryptionUtil.decode(nextToken);\n searchRequest.getSearchQuery().setToken(tokenBytes);\n } else {\n if (sorters != null &&!sorters.isEmpty()) {\n searchQuery.setSort(new Sort(sorters));\n }\n }\n SearchRequest.ColumnsToGet columnsToGet = new SearchRequest.ColumnsToGet();\n columnsToGet.setColumns(ReflectionUtil.getPropertyNames(clazz));\n searchRequest.setColumnsToGet(columnsToGet);\n log.info(\"searchRequest:{}\", JsonUtil.toJsonString(searchRequest));\n SearchResponse searchResponse = otsClient.search(searchRequest);\n if (searchResponse == null || searchResponse.getRows() == null) {\n return ListResult.genSuccessListResult(null, 0);\n }\n byte[] nextTokenBytes = searchResponse.getNextToken();\n nextToken = nextTokenBytes == null || nextTokenBytes.length == 0 ? null : EncryptionUtil.encode(nextTokenBytes);\n List result = searchResponse.getRows().stream()\n .map(row -> OtsUtil.convertRowToDTO(row, clazz))\n .collect(Collectors.toList());\n return ListResult.genSuccessListResult(result, searchResponse.getTotalCount(), nextToken);\n }\n```\n###test function signature:\n```java\n @Test\n void testListEntities()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testListEntities", "reference": " @Test\n void testListEntities() {\n final List matchFilters = createMatchFilters();\n final List queryFilters = createQueryFilters();\n final ListResult expectedResult = new ListResult<>();\n FieldSort fieldSort = new FieldSort(OrderOtsConstant.GMT_CREATE_LONG);\n fieldSort.setOrder(SortOrder.DESC);\n expectedResult.setData(Arrays.asList());\n expectedResult.setCount(0L);\n String nextToken = \"CAESFQoTChEKDWdtdENyZWF0ZUxvbmcQARgBIlQKCQBI8UqGigEAAApHA0IAAAAxUzM1MzQzMTM0NjQzMjYzMzAzMzYyMzE2MTMzMzkzOTM1MzEzNjM2MzM2NDM2MzAzMDMwNjYzNTM1MzA2NjY0MzM=\";\n expectedResult.setNextToken(nextToken);\n final SearchResponse searchResponse = new SearchResponse(new Response(\"requestId\"));\n when(mockOtsClient.search(any(SearchRequest.class))).thenReturn(searchResponse);\n ListResult result = baseOtsHelper.listEntities(\"order\", \"order_index\", matchFilters, queryFilters, null, nextToken, Arrays.asList(fieldSort), OrderDTO.class);\n assertThat(result.getCount()).isEqualTo(0);\n }", "completions": [ "```java\n @Test\n void testListEntities() {\n // Given\n String tableName = \"testTable\";\n String searchIndexName = \"testIndex\";\n List matchFilters = Arrays.asList(new OtsFilter(\"field1\", OtsFilter.CompareOperator.EQUAL, \"value1\"),\n new OtsFilter(\"field2\", OtsFilter.CompareOperator.EQUAL, \"value2\"));\n List queryFilters = Arrays.asList(new OtsFilter(\"field3\", OtsFilter.CompareOperator.EQUAL, \"value3\"),\n new OtsFilter(\"field4\", OtsFilter.CompareOperator.EQUAL, \"value4\"));\n List multiMatchFilter = Arrays.asList(new OtsFilter(\"field5\", OtsFilter.CompareOperator.EQUAL, \"value5\"),\n new OtsFilter(\"field6\", OtsFilter.CompareOperator.EQUAL, \"value6\"));\n String nextToken = \"testNextToken\";\n List sorters = Arrays.asList(new Sort.Sorter(\"field7\", Sort.SortOrder.ASC),\n new Sort.Sorter(\"field8\", Sort.SortOrder.DESC));\n Class clazz = TestDTO.class;\n\n // When\n ListResult result = listEntities(tableName, searchIndexName, matchFilters, queryFilters, multiMatchFilter, nextToken, sorters, clazz);\n\n // Then\n assertNotNull(result);\n assertEquals(0, result.getTotalCount());\n assertNull(result.getNextToken());\n assertTrue(result.getData().isEmpty());\n }\n```\n" ], "line": 38, "token": 346, "line_diff": 1, "token_diff": 1 }, { "id": 51, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public String[] listFiles(URI fileUri, boolean recursive) throws IOException {\n try {\n ImmutableList.Builder builder = ImmutableList.builder();\n String continuationToken = null;\n boolean isDone = false;\n String prefix = normalizeToDirectoryPrefix(fileUri);\n int fileCount = 0;\n while (!isDone) {\n ListObjectsV2Request.Builder listObjectsV2RequestBuilder =\n ListObjectsV2Request.builder().bucket(fileUri.getHost());\n if (!prefix.equals(DELIMITER)) {\n listObjectsV2RequestBuilder = listObjectsV2RequestBuilder.prefix(prefix);\n }\n if (!recursive) {\n listObjectsV2RequestBuilder = listObjectsV2RequestBuilder.delimiter(DELIMITER);\n }\n if (continuationToken != null) {\n listObjectsV2RequestBuilder.continuationToken(continuationToken);\n }\n ListObjectsV2Request listObjectsV2Request = listObjectsV2RequestBuilder.build();\n LOG.debug(\"Trying to send ListObjectsV2Request {}\", listObjectsV2Request);\n ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(listObjectsV2Request);\n LOG.debug(\"Getting ListObjectsV2Response: {}\", listObjectsV2Response);\n List filesReturned = listObjectsV2Response.contents();\n fileCount += filesReturned.size();\n filesReturned.stream()\n .forEach(\n object -> {\n // Only add files and not directories\n if (!object.key().equals(fileUri.getPath())\n && !object.key().endsWith(DELIMITER)) {\n String fileKey = object.key();\n if (fileKey.startsWith(DELIMITER)) {\n fileKey = fileKey.substring(1);\n }\n builder.add(S3_SCHEME + fileUri.getHost() + DELIMITER + fileKey);\n }\n });\n if (fileCount == LIST_MAX_KEYS) {\n // check if we reached the max keys returned, if so abort and throw an error message\n LOG.error(\n \"Too many files ({}) returned from S3 when attempting to list object prefixes\",\n LIST_MAX_KEYS);\n throw new IllegalStateException(\n String.format(\n \"Max keys (%s) reached when attempting to list S3 objects\", LIST_MAX_KEYS));\n }\n isDone = !listObjectsV2Response.isTruncated();\n continuationToken = listObjectsV2Response.nextContinuationToken();\n }\n String[] listedFiles = builder.build().toArray(new String[0]);\n LOG.debug(\n \"Listed {} files from URI: {}, is recursive: {}\", listedFiles.length, fileUri, recursive);\n return listedFiles;\n } catch (Throwable t) {\n throw new IOException(t);\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testListFilesInFolderRecursive() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "testListFilesInFolderRecursive", "reference": " @Test\n public void testListFilesInFolderRecursive() throws Exception {\n String folder = \"list-files-rec\";\n String[] nestedFolders = new String[] {\"list-files-child-1\", \"list-files-child-2\"};\n String[] originalFiles = new String[] {\"a-list-3.txt\", \"b-list-3.txt\", \"c-list-3.txt\"};\n\n List expectedResultList = new ArrayList<>();\n for (String childFolder : nestedFolders) {\n String folderName = folder + DELIMITER + childFolder;\n for (String fileName : originalFiles) {\n createEmptyFile(folderName, fileName);\n expectedResultList.add(\n String.format(FILE_FORMAT, SCHEME, bucket, folderName + DELIMITER + fileName));\n }\n }\n String[] actualFiles =\n s3BlobFs.listFiles(URI.create(String.format(FILE_FORMAT, SCHEME, bucket, folder)), true);\n\n actualFiles =\n Arrays.stream(actualFiles).filter(x -> x.contains(\"list-3\")).toArray(String[]::new);\n assertEquals(actualFiles.length, expectedResultList.size());\n assertTrue(Arrays.equals(expectedResultList.toArray(), actualFiles));\n }", "completions": [ "```java\n @Test\n public void testListFilesInFolderRecursive() throws Exception {\n // Given\n URI fileUri = new URI(\"s3://bucket/folder/\");\n boolean recursive = true;\n String[] expectedFiles = {\n \"s3://bucket/folder/file1.txt\",\n \"s3://bucket/folder/file2.txt\",\n \"s3://bucket/folder/subfolder/file3.txt\",\n \"s3://bucket/folder/subfolder/file4.txt\"\n };\n\n // When\n String[] actualFiles = s3FileSystem.listFiles(fileUri, recursive);\n\n // Then\n assertArrayEquals(expectedFiles, actualFiles);\n }\n```\n" ], "line": 70, "token": 490, "line_diff": 2, "token_diff": 2 }, { "id": 52, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @VisibleForTesting\n void validateRoleDuplicate(String name, String code, Long id) {\n // 0. 超级管理员,不允许创建\n if (RoleCodeEnum.isSuperAdmin(code)) {\n throw exception(ROLE_ADMIN_CODE_ERROR, code);\n }\n // 1. 该 name 名字被其它角色所使用\n RoleDO role = roleMapper.selectByName(name);\n if (role != null && !role.getId().equals(id)) {\n throw exception(ROLE_NAME_DUPLICATE, name);\n }\n // 2. 是否存在相同编码的角色\n if (!StringUtils.hasText(code)) {\n return;\n }\n // 该 code 编码被其它角色所使用\n role = roleMapper.selectByCode(code);\n if (role != null && !role.getId().equals(id)) {\n throw exception(ROLE_CODE_DUPLICATE, code);\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testValidateRoleDuplicate_nameDuplicate()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testValidateRoleDuplicate_nameDuplicate", "reference": " @Test\n public void testValidateRoleDuplicate_nameDuplicate() {\n // mock 数据\n RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setName(\"role_name\"));\n roleMapper.insert(roleDO);\n // 准备参数\n String name = \"role_name\";\n\n // 调用,并断言异常\n assertServiceException(() -> roleService.validateRoleDuplicate(name, randomString(), null),\n ROLE_NAME_DUPLICATE, name);\n }", "completions": [ "```java\n @Test\n public void testValidateRoleDuplicate_nameDuplicate() {\n // Given\n String name = \"duplicateName\";\n String code = \"uniqueCode\";\n Long id = 1L;\n RoleDO existingRole = new RoleDO();\n existingRole.setId(2L);\n existingRole.setName(name);\n existingRole.setCode(code);\n when(roleMapper.selectByName(name)).thenReturn(existingRole);\n\n // When\n try {\n roleService.validateRoleDuplicate(name, code, id);\n fail(\"Expected exception not thrown\");\n } catch (ServiceException e) {\n // Then\n assertEquals(ROLE_NAME_DUPLICATE, e.getCode());\n assertEquals(name, e.getArgs()[0]);\n }\n }\n```\n" ], "line": 32, "token": 213, "line_diff": 0, "token_diff": 0 }, { "id": 53, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public String sign(Map map) {\n try {\n Date date = new Date(System.currentTimeMillis() + jwtProperties.getExpireTimeMills());\n Algorithm algorithm = Algorithm.HMAC256(jwtProperties.getTokenSecret());\n Map header = new HashMap<>(2);\n header.put(\"typ\", \"jwt\");\n JWTCreator.Builder builder = JWT.create()\n .withHeader(header)\n .withIssuedAt(new Date())\n .withExpiresAt(date);\n map.entrySet().forEach(entry -> {\n if (entry.getValue() instanceof Integer) {\n builder.withClaim(entry.getKey(), (Integer) entry.getValue());\n } else if (entry.getValue() instanceof Long) {\n builder.withClaim(entry.getKey(), (Long) entry.getValue());\n } else if (entry.getValue() instanceof Boolean) {\n builder.withClaim(entry.getKey(), (Boolean) entry.getValue());\n } else if (entry.getValue() instanceof String) {\n builder.withClaim(entry.getKey(), String.valueOf(entry.getValue()));\n } else if (entry.getValue() instanceof Double) {\n builder.withClaim(entry.getKey(), (Double) entry.getValue());\n } else if (entry.getValue() instanceof Date) {\n builder.withClaim(entry.getKey(), (Date) entry.getValue());\n }\n });\n return builder.sign(algorithm);\n } catch (Exception e) {\n return null;\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void sign_generateJwtToken_succeed()\n```\n### Answer: (use the provided format with backticks)\n", "name": "sign_generateJwtToken_succeed", "reference": " @Test\n public void sign_generateJwtToken_succeed() {\n Map map = new HashMap<>();\n map.put(\"userId\", 123);\n map.put(\"username\", \"testUser\");\n String token = jwtService.sign(map);\n Assert.assertNotNull(token);\n }", "completions": [ "```java\n @Test\n public void sign_generateJwtToken_succeed() {\n // Given\n Map map = new HashMap<>();\n map.put(\"userId\", 1);\n map.put(\"username\", \"testUser\");\n map.put(\"isAdmin\", true);\n map.put(\"expireTime\", System.currentTimeMillis() + 3600000);\n\n // When\n String jwtToken = jwtService.sign(map);\n\n // Then\n assertNotNull(jwtToken);\n assertTrue(jwtToken.length() > 0);\n }\n```\n" ], "line": 41, "token": 349, "line_diff": 1, "token_diff": 1 }, { "id": 54, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public T clone(T object) {\n if (object instanceof String) {\n return object;\n } else if (object instanceof Collection) {\n Object firstElement = findFirstNonNullElement((Collection) object);\n if (firstElement != null && !(firstElement instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), firstElement.getClass());\n return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n } else if (object instanceof Map) {\n Map.Entry firstEntry = this.findFirstNonNullEntry((Map) object);\n if (firstEntry != null) {\n Object key = firstEntry.getKey();\n Object value = firstEntry.getValue();\n if (!(key instanceof Serializable) || !(value instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), key.getClass(), value.getClass());\n return (T) objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n }\n } else if (object instanceof JsonNode) {\n return (T) ((JsonNode) object).deepCopy();\n }\n\n if (object instanceof Serializable) {\n try {\n return (T) SerializationHelper.clone((Serializable) object);\n } catch (SerializationException e) {\n //it is possible that object itself implements java.io.Serializable, but underlying structure does not\n //in this case we switch to the other JSON marshaling strategy which doesn't use the Java serialization\n }\n }\n\n return jsonClone(object);\n }\n```\n###test function signature:\n```java\n @Test\n public void should_clone_map_of_non_serializable_value_with_null_value()\n```\n### Answer: (use the provided format with backticks)\n", "name": "should_clone_map_of_non_serializable_value_with_null_value", "reference": " @Test\n public void should_clone_map_of_non_serializable_value_with_null_value() {\n Map original = new LinkedHashMap<>();\n original.put(\"null\", null);\n original.put(\"key\", new NonSerializableObject(\"value\"));\n Object cloned = serializer.clone(original);\n assertEquals(original, cloned);\n assertNotSame(original, cloned);\n }", "completions": [ "```java\n @Test\n public void should_clone_map_of_non_serializable_value_with_null_value() {\n Map map = new HashMap<>();\n map.put(\"key\", null);\n\n Map clonedMap = (Map) clone(map);\n\n assertNotSame(map, clonedMap);\n assertEquals(map, clonedMap);\n }\n```\n" ], "line": 44, "token": 358, "line_diff": 1, "token_diff": 1 }, { "id": 55, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public void init(final DiscoveryConfig config) {\n if (this.namingService != null) {\n LOGGER.info(\"Nacos naming service already registered\");\n return;\n }\n Properties properties = config.getProps();\n Properties nacosProperties = new Properties();\n this.groupName = properties.getProperty(\"groupName\", \"SHENYU_GROUP\");\n String serverAddr = config.getServerList();\n nacosProperties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);\n nacosProperties.put(PropertyKeyConst.NAMESPACE, properties.getProperty(NAMESPACE, \"\"));\n nacosProperties.put(PropertyKeyConst.USERNAME, properties.getProperty(PropertyKeyConst.USERNAME, \"\"));\n nacosProperties.put(PropertyKeyConst.PASSWORD, properties.getProperty(PropertyKeyConst.PASSWORD, \"\"));\n nacosProperties.put(PropertyKeyConst.ACCESS_KEY, properties.getProperty(PropertyKeyConst.ACCESS_KEY, \"\"));\n nacosProperties.put(PropertyKeyConst.SECRET_KEY, properties.getProperty(PropertyKeyConst.SECRET_KEY, \"\"));\n try {\n this.namingService = NamingFactory.createNamingService(nacosProperties);\n LOGGER.info(\"Nacos naming service initialized success\");\n } catch (NacosException e) {\n LOGGER.error(\"Error initializing Nacos naming service\", e);\n throw new ShenyuException(e);\n }\n }\n```\n###test function signature:\n```java\n @Test\n void testInit() throws NoSuchFieldException, IllegalAccessException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testInit", "reference": " @Test\n void testInit() throws NoSuchFieldException, IllegalAccessException {\n // Set the discovery config\n setField(nacosDiscoveryServiceUnderTest.getClass(), \"namingService\", null);\n DiscoveryConfig config = new DiscoveryConfig();\n Properties properties = new Properties();\n config.setServerList(\"127.0.0.1:8848\");\n properties.setProperty(\"groupName\", \"SHENYU_GROUP\");\n config.setProps(properties);\n\n try (MockedStatic mockedNamingFactory = mockStatic(NamingFactory.class)) {\n // Mock the successful creation of NamingService\n mockedNamingFactory.when(() -> NamingFactory.createNamingService(any(Properties.class)))\n .thenReturn(namingService);\n nacosDiscoveryServiceUnderTest.init(config);\n mockedNamingFactory.verify(() -> NamingFactory.createNamingService(any(Properties.class)));\n assertEquals(namingService, getField(nacosDiscoveryServiceUnderTest, \"namingService\"));\n // Mock the situation where NamingService fails to be created and throws an exception\n mockedNamingFactory.when(() -> NamingFactory.createNamingService(any(Properties.class)))\n .thenThrow(new NacosException());\n assertDoesNotThrow(() -> nacosDiscoveryServiceUnderTest.init(config));\n }\n }", "completions": [ "```java\n @Test\n void testInit() throws NoSuchFieldException, IllegalAccessException {\n DiscoveryConfig config = new DiscoveryConfig();\n Properties properties = new Properties();\n properties.put(\"groupName\", \"SHENYU_GROUP\");\n properties.put(\"serverAddr\", \"localhost:8848\");\n properties.put(\"namespace\", \"\");\n properties.put(\"username\", \"\");\n properties.put(\"password\", \"\");\n properties.put(\"accessKey\", \"\");\n properties.put(\"secretKey\", \"\");\n config.setProps(properties);\n config.setServerList(\"localhost:8848\");\n\n NacosDiscoveryService nacosDiscoveryService = new NacosDiscoveryService();\n nacosDiscoveryService.init(config);\n\n Field namingServiceField = NacosDiscoveryService.class.getDeclaredField(\"namingService\");\n namingServiceField.setAccessible(true);\n NamingService namingService = (NamingService) namingServiceField.get(nacosDiscoveryService);\n\n assertNotNull(namingService);\n }\n```\n" ], "line": 35, "token": 273, "line_diff": 0, "token_diff": 0 }, { "id": 56, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public long determineStartingOffset(\n long currentEndOffsetForPartition,\n long currentBeginningOffsetForPartition,\n AstraConfigs.IndexerConfig indexerConfig) {\n // Filter stale snapshots for partition.\n if (partitionId == null) {\n LOG.warn(\"PartitionId can't be null.\");\n }\n\n List snapshots = snapshotMetadataStore.listSync();\n List snapshotsForPartition =\n snapshots.stream()\n .filter(\n snapshotMetadata -> {\n if (snapshotMetadata == null || snapshotMetadata.partitionId == null) {\n LOG.warn(\n \"snapshot metadata or partition id can't be null: {} \",\n Strings.join(snapshots, ','));\n }\n return snapshotMetadata != null\n && snapshotMetadata.partitionId != null\n && snapshotMetadata.partitionId.equals(partitionId);\n })\n .collect(Collectors.toUnmodifiableList());\n List deletedSnapshots = deleteStaleLiveSnapshots(snapshotsForPartition);\n\n List nonLiveSnapshotsForPartition =\n snapshotsForPartition.stream()\n .filter(s -> !deletedSnapshots.contains(s))\n .collect(Collectors.toUnmodifiableList());\n\n // Get the highest offset that is indexed in durable store.\n List recoveryTasks = recoveryTaskMetadataStore.listSync();\n long highestDurableOffsetForPartition =\n getHighestDurableOffsetForPartition(\n nonLiveSnapshotsForPartition, recoveryTasks, partitionId);\n LOG.debug(\n \"The highest durable offset for partition {} is {}\",\n partitionId,\n highestDurableOffsetForPartition);\n\n if (highestDurableOffsetForPartition <= 0) {\n LOG.info(\"There is no prior offset for this partition {}.\", partitionId);\n\n // If the user wants to start at the current offset in Kafka and _does not_ want to create\n // recovery tasks to backfill, then we can just return the current offset.\n // If the user wants to start at the current offset in Kafka and _does_ want to create\n // recovery tasks to backfill, then we create the recovery tasks needed and then return\n // the current offset for the indexer. And if the user does _not_ want to start at the\n // current offset in Kafka, then we'll just default to the old behavior of starting from\n // the very beginning\n if (!indexerConfig.getCreateRecoveryTasksOnStart()\n && indexerConfig.getReadFromLocationOnStart()\n == AstraConfigs.KafkaOffsetLocation.LATEST) {\n LOG.info(\n \"CreateRecoveryTasksOnStart is set to false and ReadLocationOnStart is set to current. Reading from current and\"\n + \" NOT spinning up recovery tasks\");\n return currentEndOffsetForPartition;\n } else if (indexerConfig.getCreateRecoveryTasksOnStart()\n && indexerConfig.getReadFromLocationOnStart()\n == AstraConfigs.KafkaOffsetLocation.LATEST) {\n // Todo - this appears to be able to create recovery tasks that have a start and end\n // position of 0, which is invalid. This seems to occur when new clusters are initialized,\n // and is especially problematic when indexers are created but never get assigned (ie,\n // deploy 5, only assign 3).\n LOG.info(\n \"CreateRecoveryTasksOnStart is set and ReadLocationOnStart is set to current. Reading from current and\"\n + \" spinning up recovery tasks\");\n createRecoveryTasks(\n partitionId,\n currentBeginningOffsetForPartition,\n currentEndOffsetForPartition,\n indexerConfig.getMaxMessagesPerChunk());\n return currentEndOffsetForPartition;\n\n } else {\n return highestDurableOffsetForPartition;\n }\n }\n\n // The current head offset shouldn't be lower than the highest durable offset. If it is it\n // means that we indexed more data than the current head offset. This is either a bug in the\n // offset handling mechanism or the kafka partition has rolled over. We throw an exception\n // for now, so we can investigate.\n if (currentEndOffsetForPartition < highestDurableOffsetForPartition) {\n final String message =\n String.format(\n \"The current head for the partition %d can't \"\n + \"be lower than the highest durable offset for that partition %d\",\n currentEndOffsetForPartition, highestDurableOffsetForPartition);\n LOG.error(message);\n throw new IllegalStateException(message);\n }\n\n // The head offset for Kafka partition is the offset of the next message to be indexed. We\n // assume that offset is passed into this function. The highest durable offset is the partition\n // offset of the message that is indexed. Hence, the offset is incremented by 1 to get the\n // next message.\n long nextOffsetForPartition = highestDurableOffsetForPartition + 1;\n\n // Create a recovery task if needed.\n if (currentEndOffsetForPartition - highestDurableOffsetForPartition > maxOffsetDelay) {\n LOG.info(\n \"Recovery task needed. The current position {} and head location {} are higher than max\"\n + \" offset {}\",\n highestDurableOffsetForPartition,\n currentEndOffsetForPartition,\n maxOffsetDelay);\n createRecoveryTasks(\n partitionId,\n nextOffsetForPartition,\n currentEndOffsetForPartition - 1,\n maxMessagesPerRecoveryTask);\n return currentEndOffsetForPartition;\n } else {\n LOG.info(\n \"The difference between the last indexed position {} and head location {} is lower \"\n + \"than max offset {}. So, using {} position as the start offset\",\n highestDurableOffsetForPartition,\n currentEndOffsetForPartition,\n maxOffsetDelay,\n nextOffsetForPartition);\n return nextOffsetForPartition;\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testDetermineStartingOffsetOnlyRecoveryNotBehind()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testDetermineStartingOffsetOnlyRecoveryNotBehind", "reference": " @Test\n public void testDetermineStartingOffsetOnlyRecoveryNotBehind() {\n RecoveryTaskCreator recoveryTaskCreator =\n new RecoveryTaskCreator(\n snapshotMetadataStore,\n recoveryTaskStore,\n partitionId,\n 100,\n TEST_MAX_MESSAGES_PER_RECOVERY_TASK,\n meterRegistry);\n\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore)).isEmpty();\n assertThat(AstraMetadataTestUtils.listSyncUncached(recoveryTaskStore)).isEmpty();\n\n // When there is no data return -1.\n assertThat(recoveryTaskCreator.determineStartingOffset(1000, 0, indexerConfig)).isNegative();\n final String recoveryTaskName = \"recoveryTask\";\n final long recoveryStartOffset = 400;\n final long createdTimeUtc = Instant.now().toEpochMilli();\n\n final RecoveryTaskMetadata recoveryTask1 =\n new RecoveryTaskMetadata(\n recoveryTaskName + \"1\",\n partitionId,\n recoveryStartOffset,\n recoveryStartOffset * 2,\n createdTimeUtc);\n recoveryTaskStore.createSync(recoveryTask1);\n await().until(() -> recoveryTaskStore.listSync().contains(recoveryTask1));\n assertThat(recoveryTaskCreator.determineStartingOffset(850, 0, indexerConfig))\n .isEqualTo((recoveryStartOffset * 2) + 1);\n assertThatIllegalStateException()\n .isThrownBy(() -> recoveryTaskCreator.determineStartingOffset(750, 0, indexerConfig));\n\n final RecoveryTaskMetadata recoveryTask11 =\n new RecoveryTaskMetadata(\n recoveryTaskName + \"11\",\n partitionId,\n recoveryStartOffset * 2 + 1,\n recoveryStartOffset * 3,\n createdTimeUtc);\n recoveryTaskStore.createSync(recoveryTask11);\n await()\n .until(\n () -> recoveryTaskStore.listSync().containsAll(List.of(recoveryTask1, recoveryTask11)));\n assertThat(recoveryTaskCreator.determineStartingOffset(1201, 0, indexerConfig))\n .isEqualTo((recoveryStartOffset * 3) + 1);\n assertThat(recoveryTaskCreator.determineStartingOffset(1200, 0, indexerConfig))\n .isEqualTo((recoveryStartOffset * 3) + 1);\n assertThatIllegalStateException()\n .isThrownBy(() -> recoveryTaskCreator.determineStartingOffset(1150, 0, indexerConfig));\n assertThat(AstraMetadataTestUtils.listSyncUncached(recoveryTaskStore))\n .contains(recoveryTask1, recoveryTask11);\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore)).isEmpty();\n }", "completions": [ "```java\n @Test\n public void testDetermineStartingOffsetOnlyRecoveryNotBehind() {\n // Given\n String partitionId = \"testPartition\";\n long currentEndOffsetForPartition = 100L;\n long currentBeginningOffsetForPartition = 0L;\n AstraConfigs.IndexerConfig indexerConfig = new AstraConfigs.IndexerConfig();\n indexerConfig.setCreateRecoveryTasksOnStart(true);\n indexerConfig.setReadFromLocationOnStart(AstraConfigs.KafkaOffsetLocation.LATEST);\n indexerConfig.setMaxMessagesPerChunk(1000);\n\n // When\n long startingOffset = determineStartingOffset(\n currentEndOffsetForPartition, currentBeginningOffsetForPartition, indexerConfig);\n\n // Then\n assertEquals(101L, startingOffset);\n }\n```\n" ], "line": 127, "token": 935, "line_diff": 2, "token_diff": 2 }, { "id": 57, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public boolean isJsonMime(String mediaType) {\n // \"* / *\" is default to JSON\n if (\"*/*\".equals(mediaType)) {\n return true;\n }\n\n try {\n return isJsonMime(MediaType.parseMediaType(mediaType));\n } catch (InvalidMediaTypeException e) {\n }\n return false;\n }\n```\n###test function signature:\n```java\n @Test\n public void testIsJsonMime()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testIsJsonMime", "reference": " @Test\n public void testIsJsonMime() {\n assertFalse(apiClient.isJsonMime(null));\n assertFalse(apiClient.isJsonMime(\"\"));\n assertFalse(apiClient.isJsonMime(\"text/plain\"));\n assertFalse(apiClient.isJsonMime(\"application/xml\"));\n assertFalse(apiClient.isJsonMime(\"application/jsonp\"));\n assertFalse(apiClient.isJsonMime(\"example/json\"));\n assertFalse(apiClient.isJsonMime(\"example/foo+bar+jsonx\"));\n assertFalse(apiClient.isJsonMime(\"example/foo+bar+xjson\"));\n\n assertTrue(apiClient.isJsonMime(\"application/json\"));\n assertTrue(apiClient.isJsonMime(\"application/json; charset=UTF8\"));\n assertTrue(apiClient.isJsonMime(\"APPLICATION/JSON\"));\n\n assertTrue(apiClient.isJsonMime(\"application/problem+json\"));\n assertTrue(apiClient.isJsonMime(\"APPLICATION/PROBLEM+JSON\"));\n assertTrue(apiClient.isJsonMime(\"application/json\\t\"));\n assertTrue(apiClient.isJsonMime(\"example/foo+bar+json\"));\n assertTrue(apiClient.isJsonMime(\"example/foo+json;x;y\"));\n assertTrue(apiClient.isJsonMime(\"example/foo+json\\t;\"));\n assertTrue(apiClient.isJsonMime(\"Example/fOO+JSON\"));\n }", "completions": [ "```java\n @Test\n public void testIsJsonMime() {\n // Test case 1: \"* / *\"\n assertTrue(isJsonMime(\"*/*\"));\n\n // Test case 2: \"application/json\"\n assertTrue(isJsonMime(\"application/json\"));\n\n // Test case 3: \"application/json; charset=UTF-8\"\n assertTrue(isJsonMime(\"application/json; charset=UTF-8\"));\n\n // Test case 4: \"application/xml\"\n assertFalse(isJsonMime(\"application/xml\"));\n\n // Test case 5: \"text/plain\"\n assertFalse(isJsonMime(\"text/plain\"));\n\n // Test case 6: \"invalid/media/type\"\n assertFalse(isJsonMime(\"invalid/media/type\"));\n\n // Test case 7: null\n assertFalse(isJsonMime(null));\n }\n```\n" ], "line": 22, "token": 139, "line_diff": 0, "token_diff": 0 }, { "id": 58, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public void validateDpopThumprint(String existingThumprint, String requestThumprint) {\n if (StringUtils.isBlank(existingThumprint) && isFalse(appConfiguration.getDpopJktForceForAuthorizationCode())) {\n return; // nothing to check\n }\n\n if (!StringUtils.equals(existingThumprint, requestThumprint)) {\n log.debug(\"DPoP Thumprint between saved one '{}' and send in request '{}' does NOT match. Reject request.\", existingThumprint, requestThumprint);\n throw new WebApplicationException(Response\n .status(Response.Status.BAD_REQUEST)\n .type(MediaType.APPLICATION_JSON_TYPE)\n .entity(errorResponseFactory.errorAsJson(TokenErrorResponseType.INVALID_DPOP_PROOF, \"Thumprint does not match\"))\n .cacheControl(ServerUtil.cacheControl(true, false))\n .header(PRAGMA, NO_CACHE)\n .build());\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void validateDpopThumprint_whenExistingDpopThumprintMatchToActual_shouldPass()\n```\n### Answer: (use the provided format with backticks)\n", "name": "validateDpopThumprint_whenExistingDpopThumprintMatchToActual_shouldPass", "reference": " @Test\n public void validateDpopThumprint_whenExistingDpopThumprintMatchToActual_shouldPass() {\n dpopService.validateDpopThumprint(\"test\", \"test\");\n }", "completions": [ "```java\n @Test\n public void validateDpopThumprint_whenExistingDpopThumprintMatchToActual_shouldPass() {\n // Given\n String existingThumprint = \"existingThumprint\";\n String requestThumprint = \"existingThumprint\";\n when(appConfiguration.getDpopJktForceForAuthorizationCode()).thenReturn(false);\n\n // When\n // Call the method to test\n tokenService.validateDpopThumprint(existingThumprint, requestThumprint);\n\n // Then\n // No exception should be thrown\n }\n```\n" ], "line": 26, "token": 209, "line_diff": 0, "token_diff": 0 }, { "id": 59, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static String getExpandUrl(String url, Object paramObj) {\n UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);\n if (paramObj instanceof Map) {\n for (Map.Entry param : ((Map) paramObj).entrySet()) {\n if (null != param.getValue()) {\n builder.queryParam(param.getKey(), param.getValue());\n }\n }\n } else {\n for (Field param : paramObj.getClass().getDeclaredFields()) {\n param.setAccessible(true);\n\n try {\n Object value = param.get(paramObj);\n if (null != value) {\n if (value instanceof List) {\n builder.queryParam(param.getName(), (List) value);\n } else {\n builder.queryParam(param.getName(), value);\n }\n }\n } catch (IllegalAccessException e) {\n log.warn(\"Field: {} value retrieval failed, exception: {}\", param.getName(), e);\n }\n }\n }\n\n return builder.build().encode().toUri().toString();\n }\n```\n###test function signature:\n```java\n @Test\n void testGetExpandUrl()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testGetExpandUrl", "reference": " @Test\n void testGetExpandUrl() {\n String result = HttpUtil.getExpandUrl(\"http://baidu.com\", \"paramObj\");\n Assertions.assertNotNull(result);\n }", "completions": [ "```java\n @Test\n void testGetExpandUrl() {\n // Test with a Map\n Map map = new HashMap<>();\n map.put(\"param1\", \"value1\");\n map.put(\"param2\", \"value2\");\n String url = \"http://example.com\";\n String expected = \"http://example.com?param1=value1¶m2=value2\";\n String actual = getExpandUrl(url, map);\n assertEquals(expected, actual);\n\n // Test with a custom object\n TestObject obj = new TestObject(\"value1\", \"value2\");\n expected = \"http://example.com?param1=value1¶m2=value2\";\n actual = getExpandUrl(url, obj);\n assertEquals(expected, actual);\n }\n\n public static class TestObject {\n private String param1;\n private String param2;\n\n public TestObject(String param1, String param2) {\n this.param1 = param1;\n this.param2 = param2;\n }\n\n public String getParam1() {\n return param1;\n }\n\n public String getParam2() {\n return param2;\n }\n }\n```\n" ], "line": 38, "token": 277, "line_diff": 1, "token_diff": 0 }, { "id": 60, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static CacheControlHeader fromExpirationTime(String expirationTime) {\n String maxAge = DEFAULT_MAX_AGE;\n\n if (expirationTime != null) {\n if (expirationTimeIsValid(expirationTime)) {\n Duration totalTime = Duration.ZERO;\n for (String timeString : Splitter.on(\" \").split(expirationTime)) {\n String timeUnitShort = Ascii.toLowerCase(timeString.substring(timeString.length() - 1));\n TemporalUnit timeUnit = EXPIRATION_TIME_UNITS.get(timeUnitShort);\n String timeValue = timeString.substring(0, timeString.length() - 1);\n totalTime = totalTime.plus(Long.parseLong(timeValue), timeUnit);\n }\n maxAge = String.valueOf(totalTime.getSeconds());\n } else {\n logger.atWarning().log(\n \"Failed to parse expiration time: \\\"%s\\\". Using default value instead.\",\n expirationTime\n );\n }\n }\n\n String output = DEFAULT_BASE_VALUE + maxAge;\n return new CacheControlHeader(output);\n }\n```\n###test function signature:\n```java\n @Test\n public void fromExpirationTime_usesDefaultMaxAgeForInvalidExpirationTime() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "fromExpirationTime_usesDefaultMaxAgeForInvalidExpirationTime", "reference": " @Test\n public void fromExpirationTime_usesDefaultMaxAgeForInvalidExpirationTime() throws Exception {\n CacheControlHeader cacheControlHeader = CacheControlHeader.fromExpirationTime(\"asdf\");\n assertThat(cacheControlHeader.getValue()).isEqualTo(\"public, max-age=600\");\n }", "completions": [ "```java\n @Test\n public void fromExpirationTime_usesDefaultMaxAgeForInvalidExpirationTime() throws Exception {\n String invalidExpirationTime = \"invalid\";\n CacheControlHeader header = CacheControlHeader.fromExpirationTime(invalidExpirationTime);\n assertEquals(CacheControlHeader.DEFAULT_MAX_AGE, header.getValue());\n }\n```\n" ], "line": 33, "token": 241, "line_diff": 0, "token_diff": 0 }, { "id": 61, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Get\n @Path(\"/:indexName/_mapping\")\n public HttpResponse mapping(\n @Param(\"indexName\") Optional indexName,\n @Param(\"startTimeEpochMs\") Optional startTimeEpochMs,\n @Param(\"endTimeEpochMs\") Optional endTimeEpochMs)\n throws IOException {\n // Use a tree map so the results are naturally sorted\n Map> propertiesMap = new TreeMap<>();\n\n // we default the schema search to the last hour if params are not provided\n AstraSearch.SchemaResult schemaResult =\n searcher.getSchema(\n AstraSearch.SchemaRequest.newBuilder()\n .setDataset(indexName.orElse(\"*\"))\n .setStartTimeEpochMs(\n startTimeEpochMs.orElse(\n Instant.now().minus(1, ChronoUnit.HOURS).toEpochMilli()))\n .setEndTimeEpochMs(endTimeEpochMs.orElse(Instant.now().toEpochMilli()))\n .build());\n\n Map schema = SearchResultUtils.fromSchemaResultProto(schemaResult);\n schema.forEach((key, value) -> propertiesMap.put(key, Map.of(\"type\", value.getName())));\n\n // todo - remove this after we add support for a \"date\" type\n // override the timestamp as a date field for proper autocomplete\n propertiesMap.put(LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, Map.of(\"type\", \"date\"));\n\n return HttpResponse.of(\n HttpStatus.OK,\n MediaType.JSON,\n JsonUtil.writeAsString(\n ImmutableMap.of(\n indexName.orElseThrow(),\n ImmutableMap.of(\"mappings\", ImmutableMap.of(\"properties\", propertiesMap)))));\n }\n```\n###test function signature:\n```java\n @Test\n public void testIndexMapping() throws IOException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testIndexMapping", "reference": " @Test\n public void testIndexMapping() throws IOException {\n AstraQueryServiceBase searcher = mock(AstraQueryServiceBase.class);\n ElasticsearchApiService serviceUnderTest = new ElasticsearchApiService(searcher);\n\n Instant start = Instant.now();\n Instant end = start.minusSeconds(60);\n\n when(searcher.getSchema(\n eq(\n AstraSearch.SchemaRequest.newBuilder()\n .setDataset(\"foo\")\n .setStartTimeEpochMs(start.toEpochMilli())\n .setEndTimeEpochMs(end.toEpochMilli())\n .build())))\n .thenReturn(AstraSearch.SchemaResult.newBuilder().build());\n\n HttpResponse response =\n serviceUnderTest.mapping(\n Optional.of(\"foo\"), Optional.of(start.toEpochMilli()), Optional.of(end.toEpochMilli()));\n verify(searcher)\n .getSchema(\n eq(\n AstraSearch.SchemaRequest.newBuilder()\n .setDataset(\"foo\")\n .setStartTimeEpochMs(start.toEpochMilli())\n .setEndTimeEpochMs(end.toEpochMilli())\n .build()));\n\n // handle response\n AggregatedHttpResponse aggregatedRes = response.aggregate().join();\n String body = aggregatedRes.content(StandardCharsets.UTF_8);\n JsonNode jsonNode = new ObjectMapper().readTree(body);\n\n assertThat(aggregatedRes.status().code()).isEqualTo(200);\n\n assertThat(jsonNode.findValue(\"foo\")).isNotNull();\n assertThat(\n jsonNode.findValue(\"foo\").findValue(LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName))\n .isNotNull();\n\n when(searcher.getSchema(any()))\n .thenAnswer(\n invocationOnMock -> {\n AstraSearch.SchemaRequest request =\n ((AstraSearch.SchemaRequest) invocationOnMock.getArguments()[0]);\n assertThat(request.getDataset()).isEqualTo(\"bar\");\n assertThat(request.getStartTimeEpochMs())\n .isCloseTo(\n Instant.now().minus(1, ChronoUnit.HOURS).toEpochMilli(),\n Offset.offset(1000L));\n assertThat(request.getEndTimeEpochMs())\n .isCloseTo(Instant.now().toEpochMilli(), Offset.offset(1000L));\n return AstraSearch.SchemaResult.newBuilder().build();\n });\n serviceUnderTest.mapping(Optional.of(\"bar\"), Optional.empty(), Optional.empty());\n }", "completions": [ "```java\n @Test\n public void testIndexMapping() throws IOException {\n Optional indexName = Optional.of(\"testIndex\");\n Optional startTimeEpochMs = Optional.of(Instant.now().minus(1, ChronoUnit.HOURS).toEpochMilli());\n Optional endTimeEpochMs = Optional.of(Instant.now().toEpochMilli());\n\n AstraSearch.SchemaResult schemaResult =\n AstraSearch.SchemaResult.newBuilder()\n .setDataset(indexName.orElse(\"*\"))\n .setStartTimeEpochMs(startTimeEpochMs.orElse(Instant.now().minus(1, ChronoUnit.HOURS).toEpochMilli()))\n .setEndTimeEpochMs(endTimeEpochMs.orElse(Instant.now().toEpochMilli()))\n .build();\n\n when(searcher.getSchema(any(AstraSearch.SchemaRequest.class))).thenReturn(schemaResult);\n\n HttpResponse response = mapping(indexName, startTimeEpochMs, endTimeEpochMs);\n\n assertEquals(HttpStatus.OK, response.getStatus());\n assertEquals(MediaType.JSON, response.getContentType());\n assertNotNull(response.getContent());\n }\n```\n" ], "line": 43, "token": 354, "line_diff": 1, "token_diff": 1 }, { "id": 62, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public ConsumerRecords poll(final Duration timeout) {\n Timer timer = time.timer(timeout);\n\n acquireAndEnsureOpen();\n try {\n kafkaConsumerMetrics.recordPollStart(timer.currentTimeMs());\n\n if (subscriptions.hasNoSubscriptionOrUserAssignment()) {\n throw new IllegalStateException(\"Consumer is not subscribed to any topics or assigned any partitions\");\n }\n\n do {\n\n // Make sure to let the background thread know that we are still polling.\n applicationEventHandler.add(new PollEvent(timer.currentTimeMs()));\n\n // We must not allow wake-ups between polling for fetches and returning the records.\n // If the polled fetches are not empty the consumed position has already been updated in the polling\n // of the fetches. A wakeup between returned fetches and returning records would lead to never\n // returning the records in the fetches. Thus, we trigger a possible wake-up before we poll fetches.\n wakeupTrigger.maybeTriggerWakeup();\n\n updateAssignmentMetadataIfNeeded(timer);\n final Fetch fetch = pollForFetches(timer);\n if (!fetch.isEmpty()) {\n if (fetch.records().isEmpty()) {\n log.trace(\"Returning empty records from `poll()` \"\n + \"since the consumer's position has advanced for at least one topic partition\");\n }\n\n return interceptors.onConsume(new ConsumerRecords<>(fetch.records()));\n }\n // We will wait for retryBackoffMs\n } while (timer.notExpired());\n\n return ConsumerRecords.empty();\n } finally {\n kafkaConsumerMetrics.recordPollEnd(timer.currentTimeMs());\n release();\n }\n }\n```\n###test function signature:\n```java\n @Test\n @SuppressWarnings(\"deprecation\")\n public void testPollLongThrowsException()\n```\n### Answer: (use the provided format with backticks)\n", "name": "@SuppressWarnings", "reference": " @Test\n @SuppressWarnings(\"deprecation\")\n public void testPollLongThrowsException() {\n consumer = newConsumer();\n Exception e = assertThrows(UnsupportedOperationException.class, () -> consumer.poll(0L));\n assertEquals(\"Consumer.poll(long) is not supported when \\\"group.protocol\\\" is \\\"consumer\\\". \" +\n \"This method is deprecated and will be removed in the next major release.\", e.getMessage());\n }", "completions": [ "```java\n @Test\n @SuppressWarnings(\"deprecation\")\n public void testPollLongThrowsException() {\n // Given\n Duration timeout = Duration.ofMillis(1000);\n Consumer consumer = new KafkaConsumer<>(props);\n consumer.subscribe(Collections.singletonList(\"test-topic\"));\n\n // When\n ConsumerRecords records = consumer.poll(timeout);\n\n // Then\n assertTrue(records.isEmpty());\n }\n```\n" ], "line": 46, "token": 373, "line_diff": 1, "token_diff": 1 }, { "id": 63, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public SearchResult search(\n String dataset,\n String queryStr,\n Long startTimeMsEpoch,\n Long endTimeMsEpoch,\n int howMany,\n AggBuilder aggBuilder) {\n\n ensureNonEmptyString(dataset, \"dataset should be a non-empty string\");\n ensureNonNullString(queryStr, \"query should be a non-empty string\");\n if (startTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch >= 0, \"start time should be non-negative value\");\n }\n if (startTimeMsEpoch != null && endTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch < endTimeMsEpoch, \"end time should be greater than start time\");\n }\n ensureTrue(howMany >= 0, \"hits requested should not be negative.\");\n ensureTrue(howMany > 0 || aggBuilder != null, \"Hits or aggregation should be requested.\");\n\n ScopedSpan span = Tracing.currentTracer().startScopedSpan(\"LogIndexSearcherImpl.search\");\n span.tag(\"dataset\", dataset);\n span.tag(\"startTimeMsEpoch\", String.valueOf(startTimeMsEpoch));\n span.tag(\"endTimeMsEpoch\", String.valueOf(endTimeMsEpoch));\n span.tag(\"howMany\", String.valueOf(howMany));\n\n Stopwatch elapsedTime = Stopwatch.createStarted();\n try {\n // Acquire an index searcher from searcher manager.\n // This is a useful optimization for indexes that are static.\n IndexSearcher searcher = searcherManager.acquire();\n\n Query query =\n openSearchAdapter.buildQuery(\n dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, searcher);\n try {\n List results;\n InternalAggregation internalAggregation = null;\n\n if (howMany > 0) {\n CollectorManager topFieldCollector =\n buildTopFieldCollector(howMany, aggBuilder != null ? Integer.MAX_VALUE : howMany);\n MultiCollectorManager collectorManager;\n if (aggBuilder != null) {\n collectorManager =\n new MultiCollectorManager(\n topFieldCollector,\n openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n } else {\n collectorManager = new MultiCollectorManager(topFieldCollector);\n }\n Object[] collector = searcher.search(query, collectorManager);\n\n ScoreDoc[] hits = ((TopFieldDocs) collector[0]).scoreDocs;\n results = new ArrayList<>(hits.length);\n for (ScoreDoc hit : hits) {\n results.add(buildLogMessage(searcher, hit));\n }\n if (aggBuilder != null) {\n internalAggregation = (InternalAggregation) collector[1];\n }\n } else {\n results = Collections.emptyList();\n internalAggregation =\n searcher.search(\n query, openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n }\n\n elapsedTime.stop();\n return new SearchResult<>(\n results, elapsedTime.elapsed(TimeUnit.MICROSECONDS), 0, 0, 1, 1, internalAggregation);\n } finally {\n searcherManager.release(searcher);\n }\n } catch (IOException e) {\n span.error(e);\n throw new IllegalArgumentException(\"Failed to acquire an index searcher.\", e);\n } finally {\n span.finish();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testNullSearchString()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testNullSearchString", "reference": " @Test\n public void testNullSearchString() {\n Instant time = Instant.ofEpochSecond(1593365471);\n loadTestData(time);\n\n assertThatExceptionOfType(IllegalArgumentException.class)\n .isThrownBy(\n () ->\n strictLogStore.logSearcher.search(\n TEST_DATASET_NAME + \"miss\",\n null,\n 0L,\n MAX_TIME,\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\")));\n }", "completions": [ "```java\n @Test\n public void testNullSearchString() {\n // Given\n String dataset = \"testDataset\";\n String queryStr = null;\n Long startTimeMsEpoch = null;\n Long endTimeMsEpoch = null;\n int howMany = 10;\n AggBuilder aggBuilder = null;\n\n // When\n try {\n SearchResult result = logIndexSearcher.search(dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, howMany, aggBuilder);\n fail(\"Expected an IllegalArgumentException to be thrown\");\n } catch (IllegalArgumentException e) {\n // Expected\n }\n }\n```\n" ], "line": 85, "token": 606, "line_diff": 2, "token_diff": 2 }, { "id": 64, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public CompletableFuture sendMessageBack(ProxyContext ctx, ReceiptHandle handle, String messageId,\n ConsumerSendMsgBackRequestHeader requestHeader, long timeoutMillis) {\n // Build the response.\n final RemotingCommand response = RemotingCommand.createResponseCommand(ResponseCode.SUCCESS, null, null);\n\n Integer delayLevel = requestHeader.getDelayLevel();\n if (Objects.isNull(delayLevel)) {\n response.setCode(ResponseCode.ILLEGAL_OPERATION);\n response.setRemark(\"argument delay level is null\");\n return CompletableFuture.completedFuture(response);\n }\n\n Long offset = requestHeader.getOffset();\n if (Objects.isNull(offset)) {\n response.setCode(ResponseCode.ILLEGAL_OPERATION);\n response.setRemark(\"argument offset is null\");\n return CompletableFuture.completedFuture(response);\n }\n\n VirtualQueue virtualQueue = new VirtualQueue(requestHeader.getBname());\n\n CompletableFuture topicFuture = topicOf(requestHeader.getOriginTopic());\n CompletableFuture groupFuture = consumerGroupOf(requestHeader.getGroup());\n return topicFuture.thenCombine(groupFuture, (topic, group) -> {\n if (topic.getTopicId() != virtualQueue.topicId()) {\n LOGGER.error(\"Topic id in request header {} does not match topic id in message queue {}, maybe the topic is recreated.\",\n topic.getTopicId(), virtualQueue.topicId());\n throw new ProxyException(apache.rocketmq.v2.Code.TOPIC_NOT_FOUND, \"Topic resource does not exist.\");\n }\n return Pair.of(topic, group);\n }).thenCompose(pair -> {\n Topic topic = pair.getLeft();\n ConsumerGroup group = pair.getRight();\n\n return store.pull(StoreContext.EMPTY, group.getGroupId(), topic.getTopicId(), virtualQueue.physicalQueueId(),\n Filter.DEFAULT_FILTER, requestHeader.getOffset(), 1, false)\n .thenApply(pullResult -> {\n if (pullResult.status() == com.automq.rocketmq.store.model.message.PullResult.Status.FOUND) {\n return pullResult.messageList().get(0);\n }\n throw new ProxyException(apache.rocketmq.v2.Code.MESSAGE_NOT_FOUND, \"Message not found from server.\");\n }).thenCompose(messageExt -> {\n if (messageExt.deliveryAttempts() > group.getMaxDeliveryAttempt()) {\n return deadLetterService.send((ProxyContextExt) ctx, group.getGroupId(), messageExt.message());\n }\n\n // Message consume retry strategy\n // <0: no retry,put into DLQ directly\n // =0: broker control retry frequency\n // >0: client control retry frequency\n return switch (Integer.compare(delayLevel, 0)) {\n case -1 ->\n deadLetterService.send((ProxyContextExt) ctx, group.getGroupId(), messageExt.message());\n case 0 -> topicOf(MixAll.RETRY_GROUP_TOPIC_PREFIX + requestHeader.getGroup())\n .thenCompose(retryTopic -> {\n // Keep the same logic as apache RocketMQ.\n int serverDelayLevel = messageExt.deliveryAttempts() + 1;\n messageExt.setDeliveryAttempts(serverDelayLevel);\n messageExt.setOriginalQueueOffset(messageExt.originalOffset());\n\n FlatMessage message = messageExt.message();\n message.mutateTopicId(retryTopic.getTopicId());\n\n message.systemProperties().mutateDeliveryTimestamp(FlatMessageUtil.calculateDeliveryTimestamp(serverDelayLevel));\n return store.put(StoreContext.EMPTY, message)\n .exceptionally(ex -> {\n LOGGER.error(\"Put messageExt to retry topic failed\", ex);\n return null;\n })\n .thenApply(ignore -> null);\n });\n case 1 -> topicOf(MixAll.RETRY_GROUP_TOPIC_PREFIX + requestHeader.getGroup())\n .thenCompose(retryTopic -> {\n messageExt.setDeliveryAttempts(messageExt.deliveryAttempts() + 1);\n messageExt.setOriginalQueueOffset(messageExt.originalOffset());\n\n FlatMessage message = messageExt.message();\n message.mutateTopicId(retryTopic.getTopicId());\n\n message.systemProperties().mutateDeliveryTimestamp(FlatMessageUtil.calculateDeliveryTimestamp(delayLevel));\n return store.put(StoreContext.EMPTY, message)\n .exceptionally(ex -> {\n LOGGER.error(\"Put message to retry topic failed\", ex);\n return null;\n })\n .thenApply(ignore -> null);\n });\n default -> throw new IllegalStateException(\"Never reach here\");\n };\n });\n }).whenComplete((nil, throwable) -> {\n if (throwable != null) {\n response.setCode(ResponseCode.SYSTEM_ERROR);\n response.setRemark(throwable.getMessage());\n }\n }).thenApply(nil -> response);\n }\n```\n###test function signature:\n```java\n @Test\n void sendMessageBack()\n```\n### Answer: (use the provided format with backticks)\n", "name": "sendMessageBack", "reference": " @Test\n void sendMessageBack() {\n String topicName = \"topic\";\n VirtualQueue virtualQueue = new VirtualQueue(2, 0);\n ConsumerSendMsgBackRequestHeader header = new ConsumerSendMsgBackRequestHeader();\n header.setBname(virtualQueue.brokerName());\n header.setGroup(\"group\");\n header.setOriginTopic(topicName);\n header.setOffset(0L);\n header.setDelayLevel(0);\n\n CompletionException exception = assertThrowsExactly(CompletionException.class, () -> messageService.sendMessageBack(ProxyContextExt.create(), null, null, header, 0L).join());\n assertInstanceOf(ProxyException.class, ExceptionUtils.getRealException(exception));\n ProxyException realException = (ProxyException) ExceptionUtils.getRealException(exception);\n assertEquals(realException.getErrorCode(), Code.MESSAGE_NOT_FOUND);\n assertEquals(realException.getMessage(), \"Message not found from server.\");\n\n long topicId = metadataService.topicOf(topicName).join().getTopicId();\n messageStore.put(StoreContext.EMPTY, FlatMessageUtil.convertTo(ProxyContextExt.create(), topicId, 0, \"\", new Message(topicName, \"\", new byte[] {})));\n\n // Broker controlled delay level.\n header.setDelayLevel(0);\n RemotingCommand response = messageService.sendMessageBack(ProxyContextExt.create(), null, null, header, 0L).join();\n assertEquals(ResponseCode.SUCCESS, response.getCode());\n Mockito.verify(deadLetterSender, Mockito.never()).send(Mockito.any(), Mockito.anyLong(), Mockito.any());\n\n // Client controlled delay level.\n header.setDelayLevel(16);\n response = messageService.sendMessageBack(ProxyContextExt.create(), null, null, header, 0L).join();\n assertEquals(ResponseCode.SUCCESS, response.getCode());\n Mockito.verify(deadLetterSender, Mockito.never()).send(Mockito.any(), Mockito.anyLong(), Mockito.any());\n\n // Forward message into dead letter topic.\n header.setDelayLevel(-1);\n response = messageService.sendMessageBack(ProxyContextExt.create(), null, null, header, 0L).join();\n assertEquals(ResponseCode.SUCCESS, response.getCode());\n Mockito.verify(deadLetterSender, Mockito.times(1)).send(Mockito.any(), Mockito.anyLong(), Mockito.any());\n }", "completions": [ "```java\n @Test\n void sendMessageBack() {\n // Given\n ProxyContext ctx = mock(ProxyContext.class);\n ReceiptHandle handle = mock(ReceiptHandle.class);\n String messageId = \"testMessageId\";\n ConsumerSendMsgBackRequestHeader requestHeader = mock(ConsumerSendMsgBackRequestHeader.class);\n long timeoutMillis = 1000L;\n\n when(requestHeader.getDelayLevel()).thenReturn(1);\n when(requestHeader.getOffset()).thenReturn(1L);\n when(requestHeader.getOriginTopic()).thenReturn(\"testOriginTopic\");\n when(requestHeader.getGroup()).thenReturn(\"testGroup\");\n when(requestHeader.getBname()).thenReturn(\"testBname\");\n\n Topic topic = mock(Topic.class);\n when(topic.getTopicId()).thenReturn(1);\n\n ConsumerGroup group = mock(ConsumerGroup.class);\n when(group.getGroupId()).thenReturn(\"testGroupId\");\n when(group.getMaxDeliveryAttempt()).thenReturn(3);\n\n FlatMessage message = mock(FlatMessage.class);\n when(message.deliveryAttempts()).thenReturn(1);\n when(message.originalOffset()).thenReturn(1L);\n\n MessageExt messageExt = mock(MessageExt.class);\n when(messageExt.message()).thenReturn(message);\n when(messageExt.deliveryAttempts()).thenReturn(1);\n\n PullResult pullResult = mock(PullResult.class);\n when(pullResult.status()).thenReturn(PullResult.Status.FOUND);\n when(pullResult.messageList()).thenReturn(List.of(messageExt));\n\n Store store = mock(Store.class);\n when(store.pull(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(CompletableFuture.completedFuture(pullResult));\n when(store.put(any(), any())).thenReturn(CompletableFuture.completedFuture(null));\n\n DeadLetterService deadLetterService = mock(DeadLetterService.class);\n when(deadLetterService.send(any(), any(), any())).thenReturn(CompletableFuture.completedFuture(null));\n\n ProxyContextExt ctxExt = mock(ProxyContextExt.class);\n\n TopicService topicService = mock(TopicService.class);\n when(topicService.topicOf(any())).thenReturn(CompletableFuture.completedFuture(topic));\n when(topicService.consumerGroupOf(any())).thenReturn(CompletableFuture.completedFuture(group));\n\n ConsumerService consumerService = new ConsumerService(store, deadLetterService, topicService);\n\n // When\n CompletableFuture future = consumerService.sendMessageBack(ctx, handle, messageId, requestHeader, timeoutMillis);\n\n // Then\n RemotingCommand response = future.join();\n assertEquals(ResponseCode.SUCCESS, response.getCode());\n }\n```\n" ], "line": 99, "token": 793, "line_diff": 2, "token_diff": 2 }, { "id": 65, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public ApolloAuditTracer tracer() {\n RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();\n if (requestAttributes != null) {\n Object tracer = requestAttributes.getAttribute(ApolloAuditConstants.TRACER,\n RequestAttributes.SCOPE_REQUEST);\n if (tracer != null) {\n return ((ApolloAuditTracer) tracer);\n } else {\n ApolloAuditTracer newTracer = new ApolloAuditTracer(new ApolloAuditScopeManager(), operatorSupplier);\n setTracer(newTracer);\n return newTracer;\n }\n }\n return null;\n }\n```\n###test function signature:\n```java\n @Test\n public void testGetTracerInRequestThreads()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testGetTracerInRequestThreads", "reference": " @Test\n public void testGetTracerInRequestThreads() {\n ApolloAuditTracer mockTracer = new ApolloAuditTracer(Mockito.mock(ApolloAuditScopeManager.class), supplier);\n RequestAttributes mockRequestAttributes = Mockito.mock(RequestAttributes.class);\n RequestContextHolder.setRequestAttributes(mockRequestAttributes);\n Mockito.when(mockRequestAttributes.getAttribute(Mockito.eq(ApolloAuditConstants.TRACER), Mockito.eq(RequestAttributes.SCOPE_REQUEST)))\n .thenReturn(mockTracer);\n ApolloAuditTracer get = traceContext.tracer();\n assertNotNull(get);\n Mockito.verify(traceContext, Mockito.times(0))\n .setTracer(Mockito.any(ApolloAuditTracer.class));\n }", "completions": [ "```java\n @Test\n public void testGetTracerInRequestThreads() {\n // Given\n RequestAttributes requestAttributes = Mockito.mock(RequestAttributes.class);\n ApolloAuditTracer tracer = Mockito.mock(ApolloAuditTracer.class);\n Mockito.when(requestAttributes.getAttribute(ApolloAuditConstants.TRACER, RequestAttributes.SCOPE_REQUEST)).thenReturn(tracer);\n Mockito.when(RequestContextHolder.getRequestAttributes()).thenReturn(requestAttributes);\n\n // When\n ApolloAuditTracer result = tracer();\n\n // Then\n Assert.assertEquals(tracer, result);\n }\n```\n" ], "line": 26, "token": 159, "line_diff": 0, "token_diff": 0 }, { "id": 66, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public Map generate(String modelName) {\n Map kv = new HashMap<>();\n if (modelName != null) {\n final Schema schema = this.globalContext.getSchemaMap().get(modelName);\n if (schema != null) {\n String example = Json.pretty(this.resolveModelToExample(modelName, schema));\n\n if (example != null) {\n kv.put(EXAMPLE, example);\n return Map.copyOf(kv);\n }\n }\n }\n return Collections.emptyMap();\n }\n```\n###test function signature:\n```java\n @Test\n void shouldGenerateOneOfWhenOneOfInRoot() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "shouldGenerateOneOfWhenOneOfInRoot", "reference": " @Test\n void shouldGenerateOneOfWhenOneOfInRoot() throws Exception {\n OpenAPIModelGenerator generator = setupPayloadGenerator();\n\n Map example = generator.generate(\"PetType\");\n String exampleJson = example.get(\"example\");\n\n Assertions.assertThat(exampleJson)\n .contains(\"PetTypeONE_OF#/components/schemas/Husky\")\n .contains(\"PetTypeONE_OF#/components/schemas/Labrador\");\n }", "completions": [ "```java\n @Test\n void shouldGenerateOneOfWhenOneOfInRoot() throws Exception {\n // Given\n String modelName = \"ModelName\";\n Schema schema = new Schema();\n schema.setOneOf(Arrays.asList(new Schema(), new Schema()));\n this.globalContext.getSchemaMap().put(modelName, schema);\n\n // When\n Map result = this.generate(modelName);\n\n // Then\n assertNotNull(result);\n assertFalse(result.isEmpty());\n assertTrue(result.containsKey(EXAMPLE));\n assertNotNull(result.get(EXAMPLE));\n }\n```\n" ], "line": 25, "token": 181, "line_diff": 0, "token_diff": 0 }, { "id": 67, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public ApolloAuditTracer tracer() {\n RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();\n if (requestAttributes != null) {\n Object tracer = requestAttributes.getAttribute(ApolloAuditConstants.TRACER,\n RequestAttributes.SCOPE_REQUEST);\n if (tracer != null) {\n return ((ApolloAuditTracer) tracer);\n } else {\n ApolloAuditTracer newTracer = new ApolloAuditTracer(new ApolloAuditScopeManager(), operatorSupplier);\n setTracer(newTracer);\n return newTracer;\n }\n }\n return null;\n }\n```\n###test function signature:\n```java\n @Test\n public void testGetTracerInAnotherThreadButSameRequest()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testGetTracerInAnotherThreadButSameRequest", "reference": " @Test\n public void testGetTracerInAnotherThreadButSameRequest() {\n ApolloAuditTracer mockTracer = Mockito.mock(ApolloAuditTracer.class);\n {\n Mockito.when(traceContext.tracer()).thenReturn(mockTracer);\n }\n CountDownLatch latch = new CountDownLatch(1);\n Executors.newSingleThreadExecutor().submit(() -> {\n ApolloAuditTracer tracer = traceContext.tracer();\n\n assertEquals(mockTracer, tracer);\n\n latch.countDown();\n });\n }", "completions": [ "```java\n @Test\n public void testGetTracerInAnotherThreadButSameRequest() {\n // Given\n RequestAttributes requestAttributes = new ServletRequestAttributes(new MockHttpServletRequest());\n RequestContextHolder.setRequestAttributes(requestAttributes);\n ApolloAuditTracer tracer = new ApolloAuditTracer(new ApolloAuditScopeManager(), operatorSupplier);\n requestAttributes.setAttribute(ApolloAuditConstants.TRACER, tracer, RequestAttributes.SCOPE_REQUEST);\n\n // When\n ApolloAuditTracer result = tracer();\n\n // Then\n assertEquals(tracer, result);\n }\n```\n" ], "line": 26, "token": 159, "line_diff": 0, "token_diff": 0 }, { "id": 68, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public SearchResult search(\n String dataset,\n String queryStr,\n Long startTimeMsEpoch,\n Long endTimeMsEpoch,\n int howMany,\n AggBuilder aggBuilder) {\n\n ensureNonEmptyString(dataset, \"dataset should be a non-empty string\");\n ensureNonNullString(queryStr, \"query should be a non-empty string\");\n if (startTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch >= 0, \"start time should be non-negative value\");\n }\n if (startTimeMsEpoch != null && endTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch < endTimeMsEpoch, \"end time should be greater than start time\");\n }\n ensureTrue(howMany >= 0, \"hits requested should not be negative.\");\n ensureTrue(howMany > 0 || aggBuilder != null, \"Hits or aggregation should be requested.\");\n\n ScopedSpan span = Tracing.currentTracer().startScopedSpan(\"LogIndexSearcherImpl.search\");\n span.tag(\"dataset\", dataset);\n span.tag(\"startTimeMsEpoch\", String.valueOf(startTimeMsEpoch));\n span.tag(\"endTimeMsEpoch\", String.valueOf(endTimeMsEpoch));\n span.tag(\"howMany\", String.valueOf(howMany));\n\n Stopwatch elapsedTime = Stopwatch.createStarted();\n try {\n // Acquire an index searcher from searcher manager.\n // This is a useful optimization for indexes that are static.\n IndexSearcher searcher = searcherManager.acquire();\n\n Query query =\n openSearchAdapter.buildQuery(\n dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, searcher);\n try {\n List results;\n InternalAggregation internalAggregation = null;\n\n if (howMany > 0) {\n CollectorManager topFieldCollector =\n buildTopFieldCollector(howMany, aggBuilder != null ? Integer.MAX_VALUE : howMany);\n MultiCollectorManager collectorManager;\n if (aggBuilder != null) {\n collectorManager =\n new MultiCollectorManager(\n topFieldCollector,\n openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n } else {\n collectorManager = new MultiCollectorManager(topFieldCollector);\n }\n Object[] collector = searcher.search(query, collectorManager);\n\n ScoreDoc[] hits = ((TopFieldDocs) collector[0]).scoreDocs;\n results = new ArrayList<>(hits.length);\n for (ScoreDoc hit : hits) {\n results.add(buildLogMessage(searcher, hit));\n }\n if (aggBuilder != null) {\n internalAggregation = (InternalAggregation) collector[1];\n }\n } else {\n results = Collections.emptyList();\n internalAggregation =\n searcher.search(\n query, openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n }\n\n elapsedTime.stop();\n return new SearchResult<>(\n results, elapsedTime.elapsed(TimeUnit.MICROSECONDS), 0, 0, 1, 1, internalAggregation);\n } finally {\n searcherManager.release(searcher);\n }\n } catch (IOException e) {\n span.error(e);\n throw new IllegalArgumentException(\"Failed to acquire an index searcher.\", e);\n } finally {\n span.finish();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testSearchMultipleItemsAndIndices()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testSearchMultipleItemsAndIndices", "reference": " @Test\n public void testSearchMultipleItemsAndIndices() {\n Instant time = Instant.now();\n loadTestData(time);\n SearchResult babies =\n strictLogStore.logSearcher.search(\n TEST_DATASET_NAME,\n \"Message1\",\n time.toEpochMilli(),\n time.plusSeconds(2).toEpochMilli(),\n 10,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"));\n assertThat(babies.hits.size()).isEqualTo(1);\n\n InternalDateHistogram histogram =\n (InternalDateHistogram) Objects.requireNonNull(babies.internalAggregation);\n assertThat(histogram.getBuckets().size()).isEqualTo(1);\n assertThat(histogram.getBuckets().get(0).getDocCount()).isEqualTo(1);\n }", "completions": [ "```java\n @Test\n public void testSearchMultipleItemsAndIndices() {\n // Given\n String dataset = \"testDataset\";\n String queryStr = \"testQuery\";\n Long startTimeMsEpoch = 1577836800000L; // 2020-01-01 00:00:00\n Long endTimeMsEpoch = 1577923199000L; // 2020-01-02 23:59:59\n int howMany = 10;\n AggBuilder aggBuilder = new AggBuilder();\n\n // When\n SearchResult result = logIndexSearcher.search(dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, howMany, aggBuilder);\n\n // Then\n assertNotNull(result);\n assertEquals(10, result.getResults().size());\n assertTrue(result.getElapsedTimeMicros() > 0);\n assertEquals(0, result.getTotalHits());\n assertEquals(0, result.getFailedShards());\n assertEquals(1, result.getSuccessfulShards());\n assertNotNull(result.getAggregation());\n }\n```\n" ], "line": 85, "token": 606, "line_diff": 2, "token_diff": 2 }, { "id": 69, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @VisibleForTesting\n static Map>> getCandidateJobs(String tableNameWithType,\n Map> allJobMetadata)\n throws Exception {\n long nowMs = System.currentTimeMillis();\n Map>> candidates = new HashMap<>();\n // If the job started most recently has already completed, then skip retry for the table.\n Pair latestStartedJob = null;\n Pair latestCompletedJob = null;\n // The processing order of job metadata from the given Map is not deterministic. Track the completed original\n // jobs so that we can simply skip the retry jobs belonging to the completed original jobs.\n Map completedOriginalJobs = new HashMap<>();\n Set cancelledOriginalJobs = new HashSet<>();\n for (Map.Entry> entry : allJobMetadata.entrySet()) {\n String jobId = entry.getKey();\n Map jobMetadata = entry.getValue();\n long statsUpdatedAt = Long.parseLong(jobMetadata.get(CommonConstants.ControllerJob.SUBMISSION_TIME_MS));\n String jobStatsInStr = jobMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS);\n if (StringUtils.isEmpty(jobStatsInStr)) {\n LOGGER.info(\"Skip rebalance job: {} as it has no job progress stats\", jobId);\n continue;\n }\n String jobCtxInStr = jobMetadata.get(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);\n if (StringUtils.isEmpty(jobCtxInStr)) {\n LOGGER.info(\"Skip rebalance job: {} as it has no job context\", jobId);\n continue;\n }\n TableRebalanceProgressStats jobStats = JsonUtils.stringToObject(jobStatsInStr, TableRebalanceProgressStats.class);\n TableRebalanceContext jobCtx = JsonUtils.stringToObject(jobCtxInStr, TableRebalanceContext.class);\n long jobStartTimeMs = jobStats.getStartTimeMs();\n if (latestStartedJob == null || latestStartedJob.getRight() < jobStartTimeMs) {\n latestStartedJob = Pair.of(jobId, jobStartTimeMs);\n }\n String originalJobId = jobCtx.getOriginalJobId();\n RebalanceResult.Status jobStatus = jobStats.getStatus();\n if (jobStatus == RebalanceResult.Status.DONE || jobStatus == RebalanceResult.Status.NO_OP) {\n LOGGER.info(\"Skip rebalance job: {} as it has completed with status: {}\", jobId, jobStatus);\n completedOriginalJobs.put(originalJobId, jobId);\n if (latestCompletedJob == null || latestCompletedJob.getRight() < jobStartTimeMs) {\n latestCompletedJob = Pair.of(jobId, jobStartTimeMs);\n }\n continue;\n }\n if (jobStatus == RebalanceResult.Status.FAILED || jobStatus == RebalanceResult.Status.ABORTED) {\n LOGGER.info(\"Found rebalance job: {} for original job: {} has been stopped with status: {}\", jobId,\n originalJobId, jobStatus);\n candidates.computeIfAbsent(originalJobId, (k) -> new HashSet<>()).add(Pair.of(jobCtx, jobStartTimeMs));\n continue;\n }\n if (jobStatus == RebalanceResult.Status.CANCELLED) {\n LOGGER.info(\"Found cancelled rebalance job: {} for original job: {}\", jobId, originalJobId);\n cancelledOriginalJobs.add(originalJobId);\n continue;\n }\n // Check if an IN_PROGRESS job is still actively running.\n long heartbeatTimeoutMs = jobCtx.getConfig().getHeartbeatTimeoutInMs();\n if (nowMs - statsUpdatedAt < heartbeatTimeoutMs) {\n LOGGER.info(\"Rebalance job: {} is actively running with status updated at: {} within timeout: {}. Skip \"\n + \"retry for table: {}\", jobId, statsUpdatedAt, heartbeatTimeoutMs, tableNameWithType);\n return Collections.emptyMap();\n }\n // The job is considered failed, but it's possible it is still running, then we might end up with more than one\n // rebalance jobs running in parallel for a table. The rebalance algorithm is idempotent, so this should be fine\n // for the correctness.\n LOGGER.info(\"Found stuck rebalance job: {} for original job: {}\", jobId, originalJobId);\n candidates.computeIfAbsent(originalJobId, (k) -> new HashSet<>()).add(Pair.of(jobCtx, jobStartTimeMs));\n }\n if (latestCompletedJob != null && latestCompletedJob.getLeft().equals(latestStartedJob.getLeft())) {\n LOGGER.info(\"Rebalance job: {} started most recently has already done. Skip retry for table: {}\",\n latestCompletedJob.getLeft(), tableNameWithType);\n return Collections.emptyMap();\n }\n for (String jobId : cancelledOriginalJobs) {\n LOGGER.info(\"Skip original job: {} as it's cancelled\", jobId);\n candidates.remove(jobId);\n }\n for (Map.Entry entry : completedOriginalJobs.entrySet()) {\n LOGGER.info(\"Skip original job: {} as it's completed by attempt: {}\", entry.getKey(), entry.getValue());\n candidates.remove(entry.getKey());\n }\n return candidates;\n }\n```\n###test function signature:\n```java\n @Test\n public void testGetCandidateJobs()\n throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "testGetCandidateJobs", "reference": " @Test\n public void testGetCandidateJobs()\n throws Exception {\n String tableName = \"table01\";\n Map> allJobMetadata = new HashMap<>();\n\n // Original job run as job1, and all its retry jobs failed too.\n RebalanceConfig jobCfg = new RebalanceConfig();\n jobCfg.setMaxAttempts(4);\n TableRebalanceProgressStats stats = new TableRebalanceProgressStats();\n stats.setStatus(RebalanceResult.Status.FAILED);\n stats.setStartTimeMs(1000);\n TableRebalanceContext jobCtx = TableRebalanceContext.forInitialAttempt(\"job1\", jobCfg);\n Map jobMetadata = ZkBasedTableRebalanceObserver.createJobMetadata(tableName, \"job1\", stats, jobCtx);\n allJobMetadata.put(\"job1\", jobMetadata);\n // 3 failed retry runs for job1\n jobMetadata = createDummyJobMetadata(tableName, \"job1\", 2, 1100, RebalanceResult.Status.FAILED);\n allJobMetadata.put(\"job1_2\", jobMetadata);\n jobMetadata = createDummyJobMetadata(tableName, \"job1\", 3, 1200, RebalanceResult.Status.ABORTED);\n allJobMetadata.put(\"job1_3\", jobMetadata);\n jobMetadata = createDummyJobMetadata(tableName, \"job1\", 4, 1300, RebalanceResult.Status.FAILED);\n allJobMetadata.put(\"job1_4\", jobMetadata);\n\n // Original job run as job2, and its retry job job2_1 completed.\n jobCfg = new RebalanceConfig();\n jobCfg.setMaxAttempts(4);\n stats = new TableRebalanceProgressStats();\n stats.setStatus(RebalanceResult.Status.FAILED);\n stats.setStartTimeMs(2000);\n jobCtx = TableRebalanceContext.forInitialAttempt(\"job2\", jobCfg);\n jobMetadata = ZkBasedTableRebalanceObserver.createJobMetadata(tableName, \"job2\", stats, jobCtx);\n allJobMetadata.put(\"job2\", jobMetadata);\n jobMetadata = createDummyJobMetadata(tableName, \"job2\", 2, 2100, RebalanceResult.Status.DONE);\n allJobMetadata.put(\"job2_2\", jobMetadata);\n\n // Original job run as job3, and failed to send out heartbeat in time.\n jobCfg = new RebalanceConfig();\n jobCfg.setMaxAttempts(4);\n stats = new TableRebalanceProgressStats();\n stats.setStatus(RebalanceResult.Status.IN_PROGRESS);\n stats.setStartTimeMs(3000);\n jobCtx = TableRebalanceContext.forInitialAttempt(\"job3\", jobCfg);\n jobMetadata = ZkBasedTableRebalanceObserver.createJobMetadata(tableName, \"job3\", stats, jobCtx);\n jobMetadata.put(CommonConstants.ControllerJob.SUBMISSION_TIME_MS, \"3000\");\n allJobMetadata.put(\"job3\", jobMetadata);\n\n // Original job run as job4, which didn't have retryJobCfg as from old version of the code.\n stats = new TableRebalanceProgressStats();\n stats.setStatus(RebalanceResult.Status.FAILED);\n stats.setStartTimeMs(4000);\n jobMetadata = ZkBasedTableRebalanceObserver.createJobMetadata(tableName, \"job4\", stats, null);\n jobMetadata.remove(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT);\n allJobMetadata.put(\"job4\", jobMetadata);\n\n // Only need to retry job1 and job3, as job2 is completed and job4 is from old version of code.\n Map>> jobs =\n RebalanceChecker.getCandidateJobs(tableName, allJobMetadata);\n assertEquals(jobs.size(), 2);\n assertTrue(jobs.containsKey(\"job1\"));\n assertTrue(jobs.containsKey(\"job3\"));\n assertEquals(jobs.get(\"job1\").size(), 4); // four runs including job1,job1_1,job1_2,job1_3\n assertEquals(jobs.get(\"job3\").size(), 1); // just a single run job3\n\n // Abort job1 and cancel its retries, then only job3 is retry candidate.\n jobMetadata = allJobMetadata.get(\"job1_4\");\n cancelRebalanceJob(jobMetadata);\n jobs = RebalanceChecker.getCandidateJobs(tableName, allJobMetadata);\n assertEquals(jobs.size(), 1);\n assertTrue(jobs.containsKey(\"job3\"));\n assertEquals(jobs.get(\"job3\").size(), 1); // just a single run job3\n\n // Add latest job5 that's already done, thus no need to retry for table.\n jobCfg = new RebalanceConfig();\n jobCfg.setMaxAttempts(4);\n stats = new TableRebalanceProgressStats();\n stats.setStatus(RebalanceResult.Status.DONE);\n stats.setStartTimeMs(5000);\n jobCtx = TableRebalanceContext.forInitialAttempt(\"job5\", jobCfg);\n jobMetadata = ZkBasedTableRebalanceObserver.createJobMetadata(tableName, \"job5\", stats, jobCtx);\n allJobMetadata.put(\"job5\", jobMetadata);\n jobs = RebalanceChecker.getCandidateJobs(tableName, allJobMetadata);\n assertEquals(jobs.size(), 0);\n }", "completions": [ "```java\n @Test\n public void testGetCandidateJobs()\n throws Exception {\n // Given\n String tableNameWithType = \"table1_type1\";\n Map> allJobMetadata = new HashMap<>();\n Map jobMetadata1 = new HashMap<>();\n jobMetadata1.put(CommonConstants.ControllerJob.SUBMISSION_TIME_MS, \"1640995200000\");\n jobMetadata1.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS,\n \"{\\\"startTimeMs\\\":1640995200000,\\\"status\\\":\\\"FAILED\\\"}\");\n jobMetadata1.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT,\n \"{\\\"originalJobId\\\":\\\"job1\\\",\\\"config\\\":{\\\"heartbeatTimeoutInMs\\\":60000}}\");\n allJobMetadata.put(\"job1\", jobMetadata1);\n Map jobMetadata2 = new HashMap<>();\n jobMetadata2.put(CommonConstants.ControllerJob.SUBMISSION_TIME_MS, \"1640995200000\");\n jobMetadata2.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_PROGRESS_STATS,\n \"{\\\"startTimeMs\\\":1640995200000,\\\"status\\\":\\\"CANCELLED\\\"}\");\n jobMetadata2.put(RebalanceJobConstants.JOB_METADATA_KEY_REBALANCE_CONTEXT,\n \"{\\\"originalJobId\\\":\\\"job2\\\",\\\"config\\\":{\\\"heartbeatTimeoutInMs\\\":60000}}\");\n allJobMetadata.put(\"job2\", jobMetadata2);\n\n // When\n Map>> result = getCandidateJobs(tableNameWithType, allJobMetadata);\n\n // Then\n assertEquals(1, result.size());\n assertTrue(result.containsKey(\"job2\"));\n Set> jobSet = result.get(\"job2\");\n assertEquals(1, jobSet.size());\n Pair jobPair = jobSet.iterator().next();\n assertEquals(\"job2\", jobPair.getLeft().getOriginalJobId());\n assertEquals(1640995200000L, jobPair.getRight().longValue());\n }\n```\n" ], "line": 94, "token": 952, "line_diff": 2, "token_diff": 2 }, { "id": 70, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public CompletableFuture dist(DeliveryRequest request) {\n DeliveryReply.Builder replyBuilder = DeliveryReply.newBuilder();\n DeliveryResults.Builder resultsBuilder = DeliveryResults.newBuilder();\n for (Map.Entry entry : request.getPackageMap().entrySet()) {\n String tenantId = entry.getKey();\n ITenantMeter tenantMeter = ITenantMeter.get(tenantId);\n boolean isFanOutThrottled = !resourceThrottler.hasResource(tenantId, TotalTransientFanOutBytesPerSeconds);\n boolean hasFanOutDone = false;\n Set ok = new HashSet<>();\n Set skip = new HashSet<>();\n Set noSub = new HashSet<>();\n for (DeliveryPack writePack : entry.getValue().getPackList()) {\n TopicMessagePack topicMsgPack = writePack.getMessagePack();\n int msgPackSize = SizeUtil.estSizeOf(topicMsgPack);\n int fanout = 1;\n for (MatchInfo matchInfo : writePack.getMatchInfoList()) {\n if (!noSub.contains(matchInfo) && !skip.contains(matchInfo)) {\n if (ILocalDistService.isGlobal(matchInfo.getReceiverId())) {\n IMQTTTransientSession session =\n sessionMap.get(ILocalDistService.parseReceiverId(matchInfo.getReceiverId()));\n if (session != null) {\n boolean success = session.publish(matchInfo, singletonList(topicMsgPack));\n if (success) {\n ok.add(matchInfo);\n } else {\n noSub.add(matchInfo);\n }\n } else {\n // no session found for shared subscription\n noSub.add(matchInfo);\n }\n } else {\n if (isFanOutThrottled && hasFanOutDone) {\n continue;\n }\n int bucketId = LocalRoutes.parseBucketId(matchInfo.getReceiverId());\n CompletableFuture routesFuture =\n routeMap.get(new TopicFilter(tenantId, matchInfo.getTopicFilter(),\n bucketId));\n if (routesFuture == null) {\n noSub.add(matchInfo);\n continue;\n }\n if (!routesFuture.isDone() || routesFuture.isCompletedExceptionally()) {\n skip.add(matchInfo);\n }\n try {\n LocalRoutes localRoutes = routesFuture.join();\n if (!localRoutes.localizedReceiverId().equals(matchInfo.getReceiverId())) {\n noSub.add(matchInfo);\n continue;\n }\n boolean published = false;\n if (!isFanOutThrottled) {\n fanout *= localRoutes.routeList.size();\n for (IMQTTTransientSession session : localRoutes.routeList.values()) {\n // at least one session should publish the message\n if (session.publish(matchInfo, singletonList(topicMsgPack))) {\n published = true;\n }\n }\n } else {\n // send to one subscriber to make sure matchinfo not lost\n for (IMQTTTransientSession session : localRoutes.routeList.values()) {\n // at least one session should publish the message\n if (session.publish(matchInfo, singletonList(topicMsgPack))) {\n published = true;\n hasFanOutDone = true;\n break;\n }\n }\n }\n if (published) {\n ok.add(matchInfo);\n } else {\n noSub.add(matchInfo);\n }\n } catch (Throwable e) {\n skip.add(matchInfo);\n }\n }\n }\n }\n tenantMeter.recordSummary(MqttTransientFanOutBytes, msgPackSize * Math.max(fanout, 1));\n }\n Sets.union(ok, skip).forEach(matchInfo -> resultsBuilder.addResult(DeliveryResult.newBuilder()\n .setMatchInfo(matchInfo)\n .setCode(DeliveryResult.Code.OK)\n .build()));\n noSub.forEach(matchInfo -> resultsBuilder.addResult(DeliveryResult.newBuilder()\n .setMatchInfo(matchInfo)\n .setCode(DeliveryResult.Code.NO_SUB)\n .build()));\n replyBuilder.putResult(tenantId, resultsBuilder.build());\n }\n return CompletableFuture.completedFuture(replyBuilder.build());\n }\n```\n###test function signature:\n```java\n @Test\n public void distClientMatchError()\n```\n### Answer: (use the provided format with backticks)\n", "name": "distClientMatchError", "reference": " @Test\n public void distClientMatchError() {\n String topicFilter = \"topicFilter\";\n LocalDistService localDistService =\n new LocalDistService(serverId, distClient, resourceThrottler, eventCollector);\n\n CompletableFuture matchFuture = new CompletableFuture<>();\n when(distClient.match(anyLong(), anyString(), anyString(), anyString(), anyString(), anyInt()))\n .thenReturn(matchFuture);\n String tenantId = \"tenantId\";\n ClientInfo clientInfo = ClientInfo.newBuilder().setTenantId(tenantId).build();\n List sessions = new ArrayList<>();\n List> matchFutures = new ArrayList<>();\n for (int i = 0; i < 10 * TOPIC_FILTER_BUCKET_NUM; i++) {\n IMQTTTransientSession session = mock(IMQTTTransientSession.class);\n sessions.add(session);\n String channelId = \"channelId\" + i;\n when(session.clientInfo()).thenReturn(clientInfo);\n when(session.channelId()).thenReturn(channelId);\n long reqId = System.nanoTime();\n matchFutures.add(localDistService.match(reqId, topicFilter, session));\n }\n matchFuture.complete(MatchResult.ERROR);\n for (CompletableFuture future : matchFutures) {\n assertEquals(future.join(), MatchResult.ERROR);\n }\n ArgumentCaptor receiverIdCaptor = ArgumentCaptor.forClass(String.class);\n verify(distClient, atMost(TOPIC_FILTER_BUCKET_NUM)).match(\n anyLong(),\n eq(tenantId),\n eq(topicFilter),\n receiverIdCaptor.capture(),\n anyString(),\n eq(0));\n List matchInfos = receiverIdCaptor.getAllValues().stream()\n .map(receiverId -> MatchInfo.newBuilder()\n .setReceiverId(receiverId)\n .setTopicFilter(topicFilter).build())\n .toList();\n DeliveryReply reply = localDistService.dist(DeliveryRequest.newBuilder()\n .putPackage(tenantId, DeliveryPackage.newBuilder()\n .addPack(DeliveryPack.newBuilder()\n .addAllMatchInfo(matchInfos)\n .build())\n .build())\n .build()).join();\n assertEquals(matchInfos.size(), reply.getResultMap().get(tenantId).getResultCount());\n assertTrue(reply.getResultMap().get(tenantId).getResultList().stream()\n .allMatch(result -> result.getCode() == DeliveryResult.Code.NO_SUB));\n for (IMQTTTransientSession session : sessions) {\n verify(session, never()).publish(any(), anyList());\n }\n }", "completions": [ "```java\n @Test\n public void distClientMatchError() {\n // Create a mock for the ITenantMeter interface\n ITenantMeter mockTenantMeter = Mockito.mock(ITenantMeter.class);\n // Create a mock for the ILocalDistService interface\n ILocalDistService mockLocalDistService = Mockito.mock(ILocalDistService.class);\n // Create a mock for the sessionMap\n Map mockSessionMap = new HashMap<>();\n // Create a mock for the routeMap\n Map> mockRouteMap = new HashMap<>();\n // Create a mock for the resourceThrottler\n IResourceThrottler mockResourceThrottler = Mockito.mock(IResourceThrottler.class);\n\n // Set up the mock objects\n Mockito.when(mockTenantMeter.get(Mockito.anyString())).thenReturn(mockTenantMeter);\n Mockito.when(mockLocalDistService.isGlobal(Mockito.anyString())).thenReturn(false);\n Mockito.when(mockSessionMap.get(Mockito.anyString())).thenReturn(null);\n Mockito.when(mockRouteMap.get(Mockito.any(TopicFilter.class))).thenReturn(CompletableFuture.completedFuture(null));\n Mockito.when(mockResourceThrottler.hasResource(Mockito.anyString(), Mockito.anyLong())).thenReturn(false);\n\n // Create a new instance of the class under test\n DistService distService = new DistService(mockTenantMeter, mockLocalDistService, mockSessionMap, mockRouteMap, mockResourceThrottler);\n\n // Create a test request\n DeliveryRequest request = DeliveryRequest.newBuilder().build();\n\n // Call the method under test\n CompletableFuture replyFuture = distService.dist(request);\n\n // Verify the results\n DeliveryReply reply = replyFuture.join();\n Assert.assertEquals(0, reply.getResultMap().size());\n }\n```\n" ], "line": 109, "token": 681, "line_diff": 2, "token_diff": 2 }, { "id": 71, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public CompletableFuture dist(DeliveryRequest request) {\n DeliveryReply.Builder replyBuilder = DeliveryReply.newBuilder();\n DeliveryResults.Builder resultsBuilder = DeliveryResults.newBuilder();\n for (Map.Entry entry : request.getPackageMap().entrySet()) {\n String tenantId = entry.getKey();\n ITenantMeter tenantMeter = ITenantMeter.get(tenantId);\n boolean isFanOutThrottled = !resourceThrottler.hasResource(tenantId, TotalTransientFanOutBytesPerSeconds);\n boolean hasFanOutDone = false;\n Set ok = new HashSet<>();\n Set skip = new HashSet<>();\n Set noSub = new HashSet<>();\n for (DeliveryPack writePack : entry.getValue().getPackList()) {\n TopicMessagePack topicMsgPack = writePack.getMessagePack();\n int msgPackSize = SizeUtil.estSizeOf(topicMsgPack);\n int fanout = 1;\n for (MatchInfo matchInfo : writePack.getMatchInfoList()) {\n if (!noSub.contains(matchInfo) && !skip.contains(matchInfo)) {\n if (ILocalDistService.isGlobal(matchInfo.getReceiverId())) {\n IMQTTTransientSession session =\n sessionMap.get(ILocalDistService.parseReceiverId(matchInfo.getReceiverId()));\n if (session != null) {\n boolean success = session.publish(matchInfo, singletonList(topicMsgPack));\n if (success) {\n ok.add(matchInfo);\n } else {\n noSub.add(matchInfo);\n }\n } else {\n // no session found for shared subscription\n noSub.add(matchInfo);\n }\n } else {\n if (isFanOutThrottled && hasFanOutDone) {\n continue;\n }\n int bucketId = LocalRoutes.parseBucketId(matchInfo.getReceiverId());\n CompletableFuture routesFuture =\n routeMap.get(new TopicFilter(tenantId, matchInfo.getTopicFilter(),\n bucketId));\n if (routesFuture == null) {\n noSub.add(matchInfo);\n continue;\n }\n if (!routesFuture.isDone() || routesFuture.isCompletedExceptionally()) {\n skip.add(matchInfo);\n }\n try {\n LocalRoutes localRoutes = routesFuture.join();\n if (!localRoutes.localizedReceiverId().equals(matchInfo.getReceiverId())) {\n noSub.add(matchInfo);\n continue;\n }\n boolean published = false;\n if (!isFanOutThrottled) {\n fanout *= localRoutes.routeList.size();\n for (IMQTTTransientSession session : localRoutes.routeList.values()) {\n // at least one session should publish the message\n if (session.publish(matchInfo, singletonList(topicMsgPack))) {\n published = true;\n }\n }\n } else {\n // send to one subscriber to make sure matchinfo not lost\n for (IMQTTTransientSession session : localRoutes.routeList.values()) {\n // at least one session should publish the message\n if (session.publish(matchInfo, singletonList(topicMsgPack))) {\n published = true;\n hasFanOutDone = true;\n break;\n }\n }\n }\n if (published) {\n ok.add(matchInfo);\n } else {\n noSub.add(matchInfo);\n }\n } catch (Throwable e) {\n skip.add(matchInfo);\n }\n }\n }\n }\n tenantMeter.recordSummary(MqttTransientFanOutBytes, msgPackSize * Math.max(fanout, 1));\n }\n Sets.union(ok, skip).forEach(matchInfo -> resultsBuilder.addResult(DeliveryResult.newBuilder()\n .setMatchInfo(matchInfo)\n .setCode(DeliveryResult.Code.OK)\n .build()));\n noSub.forEach(matchInfo -> resultsBuilder.addResult(DeliveryResult.newBuilder()\n .setMatchInfo(matchInfo)\n .setCode(DeliveryResult.Code.NO_SUB)\n .build()));\n replyBuilder.putResult(tenantId, resultsBuilder.build());\n }\n return CompletableFuture.completedFuture(replyBuilder.build());\n }\n```\n###test function signature:\n```java\n @Test\n public void distClientMatchOK()\n```\n### Answer: (use the provided format with backticks)\n", "name": "distClientMatchOK", "reference": " @Test\n public void distClientMatchOK() {\n String topicFilter = \"topicFilter\";\n LocalDistService localDistService =\n new LocalDistService(serverId, distClient, resourceThrottler, eventCollector);\n\n CompletableFuture matchFuture = new CompletableFuture<>();\n when(distClient.match(anyLong(), anyString(), anyString(), anyString(), anyString(), anyInt()))\n .thenReturn(matchFuture);\n String tenantId = \"tenantId\";\n ClientInfo clientInfo = ClientInfo.newBuilder().setTenantId(tenantId).build();\n List sessions = new ArrayList<>();\n List> matchFutures = new ArrayList<>();\n for (int i = 0; i < 10 * TOPIC_FILTER_BUCKET_NUM; i++) {\n IMQTTTransientSession session = mock(IMQTTTransientSession.class);\n sessions.add(session);\n String channelId = \"channelId\" + i;\n when(session.clientInfo()).thenReturn(clientInfo);\n when(session.channelId()).thenReturn(channelId);\n when(session.publish(any(), anyList())).thenReturn(true);\n long reqId = System.nanoTime();\n matchFutures.add(localDistService.match(reqId, topicFilter, session));\n }\n matchFuture.complete(MatchResult.OK);\n for (CompletableFuture future : matchFutures) {\n assertEquals(future.join(), MatchResult.OK);\n }\n ArgumentCaptor receiverIdCaptor = ArgumentCaptor.forClass(String.class);\n verify(distClient, atMost(TOPIC_FILTER_BUCKET_NUM)).match(\n anyLong(),\n eq(tenantId),\n eq(topicFilter),\n receiverIdCaptor.capture(),\n anyString(),\n eq(0));\n List matchInfos = receiverIdCaptor.getAllValues().stream()\n .map(receiverId -> MatchInfo.newBuilder()\n .setReceiverId(receiverId)\n .setTopicFilter(topicFilter).build())\n .toList();\n DeliveryReply reply = localDistService.dist(DeliveryRequest.newBuilder()\n .putPackage(tenantId, DeliveryPackage.newBuilder()\n .addPack(DeliveryPack.newBuilder()\n .addAllMatchInfo(matchInfos)\n .build())\n .build())\n .build()).join();\n assertEquals(matchInfos.size(), reply.getResultMap().get(tenantId).getResultCount());\n assertTrue(reply.getResultMap().get(tenantId).getResultList().stream()\n .allMatch(result -> result.getCode() == DeliveryResult.Code.OK));\n for (IMQTTTransientSession session : sessions) {\n verify(session, times(1)).publish(any(), anyList());\n }\n }", "completions": [ "```java\n @Test\n public void distClientMatchOK() {\n // Given\n DeliveryRequest request = DeliveryRequest.newBuilder()\n .putPackage(\"tenant1\", DeliveryPackage.newBuilder()\n .addPack(DeliveryPack.newBuilder()\n .setMessagePack(TopicMessagePack.newBuilder()\n .setTopic(\"topic1\")\n .setPayload(\"payload1\")\n .build())\n .addMatchInfo(MatchInfo.newBuilder()\n .setReceiverId(\"receiver1\")\n .setTopicFilter(\"topic1\")\n .build())\n .build())\n .build())\n .build();\n sessionMap.put(\"receiver1\", mock(IMQTTTransientSession.class));\n when(sessionMap.get(\"receiver1\").publish(any(MatchInfo.class), anyList())).thenReturn(true);\n when(routeMap.get(any(TopicFilter.class))).thenReturn(CompletableFuture.completedFuture(LocalRoutes.newBuilder()\n .setLocalizedReceiverId(\"receiver1\")\n .putRoute(\"receiver1\", mock(IMQTTTransientSession.class))\n .build()));\n when(ITenantMeter.get(\"tenant1\")).thenReturn(mock(ITenantMeter.class));\n when(resourceThrottler.hasResource(\"tenant1\", TotalTransientFanOutBytesPerSeconds)).thenReturn(true);\n\n // When\n CompletableFuture replyFuture = dist(request);\n\n // Then\n DeliveryReply reply = replyFuture.join();\n DeliveryResults results = reply.getResultMap().get(\"tenant1\");\n assertEquals(1, results.getResultCount());\n DeliveryResult result = results.getResult(0);\n assertEquals(DeliveryResult.Code.OK, result.getCode());\n assertEquals(\"receiver1\", result.getMatchInfo().getReceiverId());\n assertEquals(\"topic1\", result.getMatchInfo().getTopicFilter());\n }\n```\n" ], "line": 109, "token": 681, "line_diff": 2, "token_diff": 2 }, { "id": 72, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public Range calcInterquartileRangeApproximation(List sortedValues) {\n Range iqr = null;\n\n if (sortedValues.size() > 0) {\n BigDecimal q1 = valueCloseToQ1(sortedValues);\n BigDecimal q3 = valueCloseToQ3(sortedValues);\n BigDecimal max = sortedValues.get(sortedValues.size() - 1);\n\n // if iqr == 0 AND max == q3 then recursively try finding a non-zero iqr approximation.\n if (q1.compareTo(q3) == 0 && max.compareTo(q3) == 0) {\n // filter out max and try again\n iqr = this.calcInterquartileRangeApproximation(\n sortedValues.stream().filter(d -> d.compareTo(max) < 0).collect(Collectors.toList()));\n }\n\n // if range is still empty use the original q1 and q3 values\n if (iqr == null || iqr.isEmpty()) {\n iqr = Range.closedOpen(q1, q3);\n }\n }\n\n return iqr;\n }\n```\n###test function signature:\n```java\n @Test\n public void testCalcInterquartileRangeApproximation()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testCalcInterquartileRangeApproximation", "reference": " @Test\n public void testCalcInterquartileRangeApproximation() {\n List values = decList(1, 2, 3, 4, 5, 6, 7, 8);\n assertEquals(new BigDecimal(\"3\"), dataBinHelper.calcInterquartileRangeApproximation(values).lowerEndpoint());\n assertEquals(new BigDecimal(\"7\"), dataBinHelper.calcInterquartileRangeApproximation(values).upperEndpoint());\n }", "completions": [ "```java\n @Test\n public void testCalcInterquartileRangeApproximation() {\n List sortedValues = Arrays.asList(\n new BigDecimal(\"1.0\"),\n new BigDecimal(\"2.0\"),\n new BigDecimal(\"3.0\"),\n new BigDecimal(\"4.0\"),\n new BigDecimal(\"5.0\"),\n new BigDecimal(\"6.0\"),\n new BigDecimal(\"7.0\"),\n new BigDecimal(\"8.0\"),\n new BigDecimal(\"9.0\"),\n new BigDecimal(\"10.0\")\n );\n\n Range expectedIqr = Range.closedOpen(new BigDecimal(\"2.5\"), new BigDecimal(\"7.5\"));\n Range actualIqr = calcInterquartileRangeApproximation(sortedValues);\n\n assertEquals(expectedIqr, actualIqr);\n }\n```\n" ], "line": 30, "token": 250, "line_diff": 0, "token_diff": 0 }, { "id": 73, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public T clone(T object) {\n if (object instanceof String) {\n return object;\n } else if (object instanceof Collection) {\n Object firstElement = findFirstNonNullElement((Collection) object);\n if (firstElement != null && !(firstElement instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), firstElement.getClass());\n return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n } else if (object instanceof Map) {\n Map.Entry firstEntry = this.findFirstNonNullEntry((Map) object);\n if (firstEntry != null) {\n Object key = firstEntry.getKey();\n Object value = firstEntry.getValue();\n if (!(key instanceof Serializable) || !(value instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), key.getClass(), value.getClass());\n return (T) objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n }\n } else if (object instanceof JsonNode) {\n return (T) ((JsonNode) object).deepCopy();\n }\n\n if (object instanceof Serializable) {\n try {\n return (T) SerializationHelper.clone((Serializable) object);\n } catch (SerializationException e) {\n //it is possible that object itself implements java.io.Serializable, but underlying structure does not\n //in this case we switch to the other JSON marshaling strategy which doesn't use the Java serialization\n }\n }\n\n return jsonClone(object);\n }\n```\n###test function signature:\n```java\n @Test\n public void should_clone_serializable_complex_object_with_non_serializable_nested_object()\n```\n### Answer: (use the provided format with backticks)\n", "name": "should_clone_serializable_complex_object_with_non_serializable_nested_object", "reference": " @Test\n public void should_clone_serializable_complex_object_with_non_serializable_nested_object() {\n Map> map = new LinkedHashMap<>();\n map.put(\"key1\", Lists.newArrayList(new NonSerializableObject(\"name1\")));\n map.put(\"key2\", Lists.newArrayList(\n new NonSerializableObject(\"name2\"),\n new NonSerializableObject(\"name3\")\n ));\n Object original = new SerializableComplexObjectWithNonSerializableNestedObject(map);\n Object cloned = serializer.clone(original);\n assertEquals(original, cloned);\n assertNotSame(original, cloned);\n }", "completions": [ "```java\n @Test\n public void should_clone_serializable_complex_object_with_non_serialable_nested_object() {\n // Given\n Map map = new HashMap<>();\n map.put(\"key1\", \"value1\");\n map.put(\"key2\", new NonSerializableObject(\"nonSerializableValue\"));\n\n // When\n Map clonedMap = objectCloner.clone(map);\n\n // Then\n assertNotSame(map, clonedMap);\n assertEquals(map.size(), clonedMap.size());\n assertEquals(map.get(\"key1\"), clonedMap.get(\"key1\"));\n assertNotSame(map.get(\"key2\"), clonedMap.get(\"key2\"));\n assertEquals(map.get(\"key2\"), clonedMap.get(\"key2\"));\n }\n```\n" ], "line": 44, "token": 358, "line_diff": 1, "token_diff": 1 }, { "id": 74, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public SignedJWT token2Jwt(String token) {\n if (token == null) {\n log.error(\"Token is null.\");\n throw new BizException(ErrorInfo.VERIFY_FAILED.getStatusCode(), ErrorInfo.VERIFY_FAILED.getCode(), ErrorInfo.VERIFY_FAILED.getMessage());\n }\n try {\n return SignedJWT.parse(token);\n } catch (ParseException e) {\n log.error(\"Token to JWT Error,message = {}\", e.getMessage());\n throw new BizException(ErrorInfo.VERIFY_FAILED.getStatusCode(), ErrorInfo.VERIFY_FAILED.getCode(), ErrorInfo.VERIFY_FAILED.getMessage());\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testToken2Jwt()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testToken2Jwt", "reference": " @Test\n public void testToken2Jwt() {\n Assertions.assertThrows(BizException.class, () -> tokenParseHelper.token2Jwt(null));\n }", "completions": [ "```java\n @Test\n public void testToken2Jwt() {\n // Given\n String token = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\";\n\n // When\n SignedJWT jwt = token2Jwt(token);\n\n // Then\n assertNotNull(jwt);\n assertEquals(token, jwt.serialize());\n }\n```\n" ], "line": 23, "token": 177, "line_diff": 0, "token_diff": 0 }, { "id": 75, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public ConsumerRecords poll(final Duration timeout) {\n Timer timer = time.timer(timeout);\n\n acquireAndEnsureOpen();\n try {\n kafkaConsumerMetrics.recordPollStart(timer.currentTimeMs());\n\n if (subscriptions.hasNoSubscriptionOrUserAssignment()) {\n throw new IllegalStateException(\"Consumer is not subscribed to any topics or assigned any partitions\");\n }\n\n do {\n\n // Make sure to let the background thread know that we are still polling.\n applicationEventHandler.add(new PollEvent(timer.currentTimeMs()));\n\n // We must not allow wake-ups between polling for fetches and returning the records.\n // If the polled fetches are not empty the consumed position has already been updated in the polling\n // of the fetches. A wakeup between returned fetches and returning records would lead to never\n // returning the records in the fetches. Thus, we trigger a possible wake-up before we poll fetches.\n wakeupTrigger.maybeTriggerWakeup();\n\n updateAssignmentMetadataIfNeeded(timer);\n final Fetch fetch = pollForFetches(timer);\n if (!fetch.isEmpty()) {\n if (fetch.records().isEmpty()) {\n log.trace(\"Returning empty records from `poll()` \"\n + \"since the consumer's position has advanced for at least one topic partition\");\n }\n\n return interceptors.onConsume(new ConsumerRecords<>(fetch.records()));\n }\n // We will wait for retryBackoffMs\n } while (timer.notExpired());\n\n return ConsumerRecords.empty();\n } finally {\n kafkaConsumerMetrics.recordPollEnd(timer.currentTimeMs());\n release();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testLongPollWaitIsLimited()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testLongPollWaitIsLimited", "reference": " @Test\n public void testLongPollWaitIsLimited() {\n consumer = newConsumer();\n String topicName = \"topic1\";\n consumer.subscribe(singletonList(topicName));\n\n assertEquals(singleton(topicName), consumer.subscription());\n assertTrue(consumer.assignment().isEmpty());\n\n final int partition = 3;\n final TopicPartition tp = new TopicPartition(topicName, partition);\n final List> records = asList(\n new ConsumerRecord<>(topicName, partition, 2, \"key1\", \"value1\"),\n new ConsumerRecord<>(topicName, partition, 3, \"key2\", \"value2\")\n );\n\n // On the first iteration, return no data; on the second, return two records\n doAnswer(invocation -> {\n // Mock the subscription being assigned as the first fetch is collected\n consumer.subscriptions().assignFromSubscribed(Collections.singleton(tp));\n return Fetch.empty();\n }).doAnswer(invocation -> {\n return Fetch.forPartition(tp, records, true);\n }).when(fetchCollector).collectFetch(any(FetchBuffer.class));\n\n // And then poll for up to 10000ms, which should return 2 records without timing out\n ConsumerRecords returnedRecords = consumer.poll(Duration.ofMillis(10000));\n assertEquals(2, returnedRecords.count());\n\n assertEquals(singleton(topicName), consumer.subscription());\n assertEquals(singleton(tp), consumer.assignment());\n }", "completions": [ "```java\n @Test\n public void testLongPollWaitIsLimited() {\n // Arrange\n Duration timeout = Duration.ofMillis(1000);\n KafkaConsumer consumer = new KafkaConsumer<>(props);\n consumer.subscribe(Collections.singletonList(\"test-topic\"));\n\n // Act\n long startTime = System.currentTimeMillis();\n ConsumerRecords records = consumer.poll(timeout);\n long endTime = System.currentTimeMillis();\n\n // Assert\n long pollDuration = endTime - startTime;\n assertTrue(pollDuration >= timeout.toMillis());\n }\n```\n" ], "line": 45, "token": 366, "line_diff": 1, "token_diff": 1 }, { "id": 76, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public SearchResult search(\n String dataset,\n String queryStr,\n Long startTimeMsEpoch,\n Long endTimeMsEpoch,\n int howMany,\n AggBuilder aggBuilder) {\n\n ensureNonEmptyString(dataset, \"dataset should be a non-empty string\");\n ensureNonNullString(queryStr, \"query should be a non-empty string\");\n if (startTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch >= 0, \"start time should be non-negative value\");\n }\n if (startTimeMsEpoch != null && endTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch < endTimeMsEpoch, \"end time should be greater than start time\");\n }\n ensureTrue(howMany >= 0, \"hits requested should not be negative.\");\n ensureTrue(howMany > 0 || aggBuilder != null, \"Hits or aggregation should be requested.\");\n\n ScopedSpan span = Tracing.currentTracer().startScopedSpan(\"LogIndexSearcherImpl.search\");\n span.tag(\"dataset\", dataset);\n span.tag(\"startTimeMsEpoch\", String.valueOf(startTimeMsEpoch));\n span.tag(\"endTimeMsEpoch\", String.valueOf(endTimeMsEpoch));\n span.tag(\"howMany\", String.valueOf(howMany));\n\n Stopwatch elapsedTime = Stopwatch.createStarted();\n try {\n // Acquire an index searcher from searcher manager.\n // This is a useful optimization for indexes that are static.\n IndexSearcher searcher = searcherManager.acquire();\n\n Query query =\n openSearchAdapter.buildQuery(\n dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, searcher);\n try {\n List results;\n InternalAggregation internalAggregation = null;\n\n if (howMany > 0) {\n CollectorManager topFieldCollector =\n buildTopFieldCollector(howMany, aggBuilder != null ? Integer.MAX_VALUE : howMany);\n MultiCollectorManager collectorManager;\n if (aggBuilder != null) {\n collectorManager =\n new MultiCollectorManager(\n topFieldCollector,\n openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n } else {\n collectorManager = new MultiCollectorManager(topFieldCollector);\n }\n Object[] collector = searcher.search(query, collectorManager);\n\n ScoreDoc[] hits = ((TopFieldDocs) collector[0]).scoreDocs;\n results = new ArrayList<>(hits.length);\n for (ScoreDoc hit : hits) {\n results.add(buildLogMessage(searcher, hit));\n }\n if (aggBuilder != null) {\n internalAggregation = (InternalAggregation) collector[1];\n }\n } else {\n results = Collections.emptyList();\n internalAggregation =\n searcher.search(\n query, openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n }\n\n elapsedTime.stop();\n return new SearchResult<>(\n results, elapsedTime.elapsed(TimeUnit.MICROSECONDS), 0, 0, 1, 1, internalAggregation);\n } finally {\n searcherManager.release(searcher);\n }\n } catch (IOException e) {\n span.error(e);\n throw new IllegalArgumentException(\"Failed to acquire an index searcher.\", e);\n } finally {\n span.finish();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testFullIndexSearchForMinAgg()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testFullIndexSearchForMinAgg", "reference": " @Test\n public void testFullIndexSearchForMinAgg() {\n Instant time = Instant.now();\n loadTestData(time);\n\n SearchResult allIndexItems =\n strictLogStore.logSearcher.search(\n TEST_DATASET_NAME,\n \"\",\n 0L,\n MAX_TIME,\n 1000,\n new MinAggBuilder(\n \"test\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"0\", null));\n\n assertThat(allIndexItems.hits.size()).isEqualTo(4);\n\n InternalMin internalMin =\n (InternalMin) Objects.requireNonNull(allIndexItems.internalAggregation);\n\n assertThat(Double.valueOf(internalMin.getValue()).longValue()).isEqualTo(time.toEpochMilli());\n }", "completions": [ "```java\n @Test\n public void testFullIndexSearchForMinAgg() {\n // Given\n String dataset = \"testDataset\";\n String queryStr = \"testQuery\";\n Long startTimeMsEpoch = 1577836800000L; // 2020-01-01 00:00:00\n Long endTimeMsEpoch = 1577923199000L; // 2020-01-02 23:59:59\n int howMany = 10;\n AggBuilder aggBuilder = new MinAggBuilder();\n\n // When\n SearchResult result = logIndexSearcher.search(dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, howMany, aggBuilder);\n\n // Then\n assertNotNull(result);\n assertEquals(howMany, result.getResults().size());\n assertNotNull(result.getAggregation());\n assertTrue(result.getAggregation() instanceof MinAgg);\n assertTrue(result.getElapsedTimeMicros() > 0);\n }\n```\n" ], "line": 85, "token": 606, "line_diff": 2, "token_diff": 2 }, { "id": 77, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n LazyBlockList tryFetch(BlockListType blockListType) {\n try {\n URL dataUrl = new URL(blockListUrls.get(blockListType.name()));\n logger.atInfo().log(\"Downloading from %s\", dataUrl);\n HttpsURLConnection connection =\n (HttpsURLConnection) urlConnectionService.createConnection(dataUrl);\n connection.setRequestMethod(HttpMethods.GET);\n connection.setRequestProperty(\"Authorization\", \"Bearer \" + credential.getAuthToken());\n int code = connection.getResponseCode();\n if (code != SC_OK) {\n String errorDetails = \"\";\n try (InputStream errorStream = connection.getErrorStream()) {\n errorDetails = new String(ByteStreams.toByteArray(errorStream), UTF_8);\n } catch (NullPointerException e) {\n // No error message.\n } catch (Exception e) {\n errorDetails = \"Failed to retrieve error message: \" + e.getMessage();\n }\n throw new BsaException(\n String.format(\n \"Status code: [%s], error: [%s], details: [%s]\",\n code, connection.getResponseMessage(), errorDetails),\n /* retriable= */ true);\n }\n return new LazyBlockList(blockListType, connection);\n } catch (IOException e) {\n throw new BsaException(e, /* retriable= */ true);\n } catch (GeneralSecurityException e) {\n throw new BsaException(e, /* retriable= */ false);\n }\n }\n```\n###test function signature:\n```java\n @Test\n void tryFetch_bsaChecksumFetched() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "tryFetch_bsaChecksumFetched", "reference": " @Test\n void tryFetch_bsaChecksumFetched() throws Exception {\n setupMocks();\n when(connection.getResponseCode()).thenReturn(SC_OK);\n when(connection.getInputStream())\n .thenReturn(new ByteArrayInputStream(\"bsa-checksum\\ndata\".getBytes(UTF_8)));\n LazyBlockList download = fetcher.tryFetch(BlockListType.BLOCK);\n assertThat(download.getName()).isEqualTo(BlockListType.BLOCK);\n assertThat(download.checksum()).isEqualTo(\"bsa-checksum\");\n verify(connection, times(1)).setRequestMethod(\"GET\");\n verify(connection, times(1)).setRequestProperty(\"Authorization\", \"Bearer authToken\");\n }", "completions": [ "```java\n @Test\n void tryFetch_bsaChecksumFetched() throws Exception {\n // Given\n URL dataUrl = new URL(\"https://example.com/bsaChecksum\");\n HttpsURLConnection connection = mock(HttpsURLConnection.class);\n when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK);\n when(connection.getErrorStream()).thenReturn(new ByteArrayInputStream(\"\".getBytes()));\n when(urlConnectionService.createConnection(dataUrl)).thenReturn(connection);\n\n // When\n LazyBlockList lazyBlockList = bsaService.tryFetch(BlockListType.BSA_CHECKSUM);\n\n // Then\n assertEquals(BlockListType.BSA_CHECKSUM, lazyBlockList.getBlockListType());\n assertEquals(connection, lazyBlockList.getConnection());\n }\n```\n" ], "line": 42, "token": 330, "line_diff": 1, "token_diff": 1 }, { "id": 78, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public SearchResult search(\n String dataset,\n String queryStr,\n Long startTimeMsEpoch,\n Long endTimeMsEpoch,\n int howMany,\n AggBuilder aggBuilder) {\n\n ensureNonEmptyString(dataset, \"dataset should be a non-empty string\");\n ensureNonNullString(queryStr, \"query should be a non-empty string\");\n if (startTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch >= 0, \"start time should be non-negative value\");\n }\n if (startTimeMsEpoch != null && endTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch < endTimeMsEpoch, \"end time should be greater than start time\");\n }\n ensureTrue(howMany >= 0, \"hits requested should not be negative.\");\n ensureTrue(howMany > 0 || aggBuilder != null, \"Hits or aggregation should be requested.\");\n\n ScopedSpan span = Tracing.currentTracer().startScopedSpan(\"LogIndexSearcherImpl.search\");\n span.tag(\"dataset\", dataset);\n span.tag(\"startTimeMsEpoch\", String.valueOf(startTimeMsEpoch));\n span.tag(\"endTimeMsEpoch\", String.valueOf(endTimeMsEpoch));\n span.tag(\"howMany\", String.valueOf(howMany));\n\n Stopwatch elapsedTime = Stopwatch.createStarted();\n try {\n // Acquire an index searcher from searcher manager.\n // This is a useful optimization for indexes that are static.\n IndexSearcher searcher = searcherManager.acquire();\n\n Query query =\n openSearchAdapter.buildQuery(\n dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, searcher);\n try {\n List results;\n InternalAggregation internalAggregation = null;\n\n if (howMany > 0) {\n CollectorManager topFieldCollector =\n buildTopFieldCollector(howMany, aggBuilder != null ? Integer.MAX_VALUE : howMany);\n MultiCollectorManager collectorManager;\n if (aggBuilder != null) {\n collectorManager =\n new MultiCollectorManager(\n topFieldCollector,\n openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n } else {\n collectorManager = new MultiCollectorManager(topFieldCollector);\n }\n Object[] collector = searcher.search(query, collectorManager);\n\n ScoreDoc[] hits = ((TopFieldDocs) collector[0]).scoreDocs;\n results = new ArrayList<>(hits.length);\n for (ScoreDoc hit : hits) {\n results.add(buildLogMessage(searcher, hit));\n }\n if (aggBuilder != null) {\n internalAggregation = (InternalAggregation) collector[1];\n }\n } else {\n results = Collections.emptyList();\n internalAggregation =\n searcher.search(\n query, openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n }\n\n elapsedTime.stop();\n return new SearchResult<>(\n results, elapsedTime.elapsed(TimeUnit.MICROSECONDS), 0, 0, 1, 1, internalAggregation);\n } finally {\n searcherManager.release(searcher);\n }\n } catch (IOException e) {\n span.error(e);\n throw new IllegalArgumentException(\"Failed to acquire an index searcher.\", e);\n } finally {\n span.finish();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testDisabledFullTextSearch()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testDisabledFullTextSearch", "reference": " @Test\n public void testDisabledFullTextSearch() {\n Instant time = Instant.ofEpochSecond(1593365471);\n Trace.KeyValue field1Tag =\n Trace.KeyValue.newBuilder()\n .setVInt32(1234)\n .setKey(\"field1\")\n .setFieldType(Schema.SchemaFieldType.INTEGER)\n .build();\n\n strictLogStoreWithoutFts.logStore.addMessage(\n SpanUtil.makeSpan(1, \"apple\", time.plusSeconds(4), List.of(field1Tag)));\n\n strictLogStoreWithoutFts.logStore.addMessage(\n SpanUtil.makeSpan(2, \"apple baby\", time.plusSeconds(4), List.of(field1Tag)));\n\n strictLogStoreWithoutFts.logStore.addMessage(\n SpanUtil.makeSpan(3, \"baby car 1234\", time.plusSeconds(4)));\n strictLogStoreWithoutFts.logStore.commit();\n strictLogStoreWithoutFts.logStore.refresh();\n\n assertThat(\n strictLogStoreWithoutFts\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"_all:baby\",\n 0L,\n MAX_TIME,\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isZero();\n\n assertThat(\n strictLogStoreWithoutFts\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"_all:1234\",\n 0L,\n MAX_TIME,\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isZero();\n\n // Without the _all field as default.\n assertThat(\n strictLogStoreWithoutFts\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"baby\",\n 0L,\n MAX_TIME,\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isEqualTo(2);\n\n assertThat(\n strictLogStoreWithoutFts\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"1234\",\n 0L,\n MAX_TIME,\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isEqualTo(3);\n\n // empty string\n assertThat(\n strictLogStore\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"\",\n 0L,\n MAX_TIME,\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isZero();\n\n assertThat(\n strictLogStore\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"app*\",\n 0L,\n MAX_TIME,\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isZero();\n\n // Returns baby or car, 2 messages.\n assertThat(\n strictLogStore\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"baby car\",\n 0L,\n MAX_TIME,\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isZero();\n\n // Test numbers\n assertThat(\n strictLogStore\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"apple 1234\",\n 0L,\n MAX_TIME,\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isZero();\n\n assertThat(\n strictLogStore\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"123\",\n 0L,\n MAX_TIME,\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isZero();\n }", "completions": [ "```java\n @Test\n public void testDisabledFullTextSearch() {\n // Given\n String dataset = \"testDataset\";\n String queryStr = \"testQuery\";\n Long startTimeMsEpoch = null;\n Long endTimeMsEpoch = null;\n int howMany = 10;\n AggBuilder aggBuilder = null;\n\n // When\n SearchResult result = logIndexSearcher.search(dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, howMany, aggBuilder);\n\n // Then\n assertNotNull(result);\n assertEquals(0, result.getTotalHits());\n assertEquals(0, result.getResults().size());\n assertNull(result.getAggregation());\n }\n```\n" ], "line": 85, "token": 606, "line_diff": 2, "token_diff": 2 }, { "id": 79, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public ProcessInstanceForListViewEntity getProcessInstanceListViewByKey(Long processInstanceKey) {\n try {\n final QueryBuilder query =\n joinWithAnd(\n idsQuery().addIds(String.valueOf(processInstanceKey)),\n termQuery(ListViewTemplate.PROCESS_INSTANCE_KEY, processInstanceKey));\n\n final SearchRequest request =\n ElasticsearchUtil.createSearchRequest(listViewTemplate, ALL)\n .source(new SearchSourceBuilder().query(constantScoreQuery(query)));\n\n final SearchResponse response;\n\n response = tenantAwareClient.search(request);\n final SearchHits searchHits = response.getHits();\n if (searchHits.getTotalHits().value == 1 && searchHits.getHits().length == 1) {\n return ElasticsearchUtil.fromSearchHit(\n searchHits.getAt(0).getSourceAsString(),\n objectMapper,\n ProcessInstanceForListViewEntity.class);\n } else if (response.getHits().getTotalHits().value > 1) {\n throw new NotFoundException(\n String.format(\n \"Could not find unique process instance with id '%s'.\", processInstanceKey));\n } else {\n throw new NotFoundException(\n (String.format(\"Could not find process instance with id '%s'.\", processInstanceKey)));\n }\n } catch (IOException e) {\n throw new OperateRuntimeException(e);\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testGetProcessInstanceListViewByKeyWithException() throws IOException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testGetProcessInstanceListViewByKeyWithException", "reference": " @Test\n public void testGetProcessInstanceListViewByKeyWithException() throws IOException {\n when(listViewTemplate.getAlias()).thenReturn(\"listViewIndexAlias\");\n when(tenantAwareClient.search(any())).thenThrow(new IOException());\n\n assertThrows(\n OperateRuntimeException.class, () -> underTest.getProcessInstanceListViewByKey(123L));\n }", "completions": [ "```java\n @Test\n public void testGetProcessInstanceListViewByKeyWithException() throws IOException {\n // Given\n final Long processInstanceKey = 1L;\n final QueryBuilder query =\n joinWithAnd(\n idsQuery().addIds(String.valueOf(processInstanceKey)),\n termQuery(ListViewTemplate.PROCESS_INSTANCE_KEY, processInstanceKey));\n\n final SearchRequest request =\n ElasticsearchUtil.createSearchRequest(listViewTemplate, ALL)\n .source(new SearchSourceBuilder().query(constantScoreQuery(query)));\n\n final SearchResponse response = Mockito.mock(SearchResponse.class);\n final SearchHits searchHits = Mockito.mock(SearchHits.class);\n Mockito.when(response.getHits()).thenReturn(searchHits);\n Mockito.when(searchHits.getTotalHits()).thenReturn(new TotalHits(2L, TotalHitsRelation.EQUAL_TO));\n Mockito.when(searchHits.getHits()).thenReturn(new SearchHit[0]);\n\n Mockito.when(tenantAwareClient.search(Mockito.any(SearchRequest.class))).thenReturn(response);\n\n // When\n try {\n processInstanceListViewService.getProcessInstanceListViewByKey(processInstanceKey);\n fail(\"Expected NotFoundException to be thrown\");\n } catch (NotFoundException e) {\n // Then\n assertEquals(\n \"Could not find unique process instance with id '1'.\", e.getMessage());\n }\n }\n```\n" ], "line": 41, "token": 286, "line_diff": 1, "token_diff": 1 }, { "id": 80, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n LazyBlockList tryFetch(BlockListType blockListType) {\n try {\n URL dataUrl = new URL(blockListUrls.get(blockListType.name()));\n logger.atInfo().log(\"Downloading from %s\", dataUrl);\n HttpsURLConnection connection =\n (HttpsURLConnection) urlConnectionService.createConnection(dataUrl);\n connection.setRequestMethod(HttpMethods.GET);\n connection.setRequestProperty(\"Authorization\", \"Bearer \" + credential.getAuthToken());\n int code = connection.getResponseCode();\n if (code != SC_OK) {\n String errorDetails = \"\";\n try (InputStream errorStream = connection.getErrorStream()) {\n errorDetails = new String(ByteStreams.toByteArray(errorStream), UTF_8);\n } catch (NullPointerException e) {\n // No error message.\n } catch (Exception e) {\n errorDetails = \"Failed to retrieve error message: \" + e.getMessage();\n }\n throw new BsaException(\n String.format(\n \"Status code: [%s], error: [%s], details: [%s]\",\n code, connection.getResponseMessage(), errorDetails),\n /* retriable= */ true);\n }\n return new LazyBlockList(blockListType, connection);\n } catch (IOException e) {\n throw new BsaException(e, /* retriable= */ true);\n } catch (GeneralSecurityException e) {\n throw new BsaException(e, /* retriable= */ false);\n }\n }\n```\n###test function signature:\n```java\n @Test\n void tryFetch_SecurityException_notRetriable() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "tryFetch_SecurityException_notRetriable", "reference": " @Test\n void tryFetch_SecurityException_notRetriable() throws Exception {\n when(connectionService.createConnection(any(URL.class)))\n .thenThrow(new GeneralSecurityException());\n assertThat(\n assertThrows(BsaException.class, () -> fetcher.tryFetch(BlockListType.BLOCK))\n .isRetriable())\n .isFalse();\n }", "completions": [ "```java\n @Test\n void tryFetch_SecurityException_notRetriable() throws Exception {\n // Arrange\n String blockListTypeName = \"TEST\";\n BlockListType blockListType = new BlockListType(blockListTypeName);\n URL dataUrl = new URL(\"http://example.com\");\n when(blockListUrls.get(blockListTypeName)).thenReturn(dataUrl.toString());\n when(urlConnectionService.createConnection(dataUrl)).thenThrow(new GeneralSecurityException());\n\n // Act and Assert\n assertThrows(BsaException.class, () -> {\n try {\n blockListService.tryFetch(blockListType);\n } catch (BsaException e) {\n assertFalse(e.isRetriable());\n throw e;\n }\n });\n }\n```\n" ], "line": 42, "token": 330, "line_diff": 1, "token_diff": 1 }, { "id": 81, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public void assign(Collection partitions) {\n acquireAndEnsureOpen();\n try {\n if (partitions == null) {\n throw new IllegalArgumentException(\"Topic partitions collection to assign to cannot be null\");\n }\n\n if (partitions.isEmpty()) {\n unsubscribe();\n return;\n }\n\n for (TopicPartition tp : partitions) {\n String topic = (tp != null) ? tp.topic() : null;\n if (isBlank(topic))\n throw new IllegalArgumentException(\"Topic partitions to assign to cannot have null or empty topic\");\n }\n\n // Clear the buffered data which are not a part of newly assigned topics\n final Set currentTopicPartitions = new HashSet<>();\n\n for (TopicPartition tp : subscriptions.assignedPartitions()) {\n if (partitions.contains(tp))\n currentTopicPartitions.add(tp);\n }\n\n fetchBuffer.retainAll(currentTopicPartitions);\n\n // assignment change event will trigger autocommit if it is configured and the group id is specified. This is\n // to make sure offsets of topic partitions the consumer is unsubscribing from are committed since there will\n // be no following rebalance.\n //\n // See the ApplicationEventProcessor.process() method that handles this event for more detail.\n applicationEventHandler.add(new AssignmentChangeEvent(subscriptions.allConsumed(), time.milliseconds()));\n\n log.info(\"Assigned to partition(s): {}\", join(partitions, \", \"));\n if (subscriptions.assignFromUser(new HashSet<>(partitions)))\n applicationEventHandler.add(new NewTopicsMetadataUpdateRequestEvent());\n } finally {\n release();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testAssignOnEmptyTopicPartition()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testAssignOnEmptyTopicPartition", "reference": " @Test\n public void testAssignOnEmptyTopicPartition() {\n consumer = newConsumer();\n completeUnsubscribeApplicationEventSuccessfully();\n\n consumer.assign(Collections.emptyList());\n assertTrue(consumer.subscription().isEmpty());\n assertTrue(consumer.assignment().isEmpty());\n }", "completions": [ "```java\n @Test\n public void testAssignOnEmptyTopicPartition() {\n // Given\n Collection partitions = new ArrayList<>();\n ConsumerImpl consumer = new ConsumerImpl();\n\n // When\n consumer.assign(partitions);\n\n // Then\n // Add assertions to verify the expected behavior\n // For example, you can check if the consumer is unsubscribed and if the fetch buffer is empty\n // assertFalse(consumer.isSubscribed());\n // assertTrue(consumer.getFetchBuffer().isEmpty());\n }\n```\n" ], "line": 47, "token": 377, "line_diff": 1, "token_diff": 1 }, { "id": 82, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static ImmutableList applyLabelDiff(\n ImmutableList labels,\n IdnChecker idnChecker,\n DownloadSchedule schedule,\n DateTime now) {\n ImmutableList.Builder nonBlockedDomains = new ImmutableList.Builder<>();\n ImmutableMap> labelsByType =\n ImmutableMap.copyOf(\n labels.stream().collect(groupingBy(BlockLabel::labelType, toImmutableList())));\n\n tm().transact(\n () -> {\n for (Map.Entry> entry :\n labelsByType.entrySet()) {\n switch (entry.getKey()) {\n case CREATE:\n // With current Cloud SQL, label upsert throughput is about 200/second. If\n // better performance is needed, consider bulk insert in native SQL.\n tm().putAll(\n entry.getValue().stream()\n .filter(label -> isValidInAtLeastOneTld(label, idnChecker))\n .map(\n label ->\n new BsaLabel(label.label(), schedule.jobCreationTime()))\n .collect(toImmutableList()));\n // May not find all unblockables due to race condition: DomainCreateFlow uses\n // cached BsaLabels. Eventually will be consistent.\n nonBlockedDomains.addAll(\n tallyUnblockableDomainsForNewLabels(entry.getValue(), idnChecker, now));\n break;\n case DELETE:\n ImmutableSet deletedLabels =\n entry.getValue().stream()\n .filter(label -> isValidInAtLeastOneTld(label, idnChecker))\n .map(BlockLabel::label)\n .collect(toImmutableSet());\n // Delete labels in DB. Also cascade-delete BsaUnblockableDomain.\n int nDeleted = Queries.deleteBsaLabelByLabels(deletedLabels);\n if (nDeleted != deletedLabels.size()) {\n logger.atSevere().log(\n \"Only found %s entities among the %s labels: [%s]\",\n nDeleted, deletedLabels.size(), deletedLabels);\n }\n break;\n case NEW_ORDER_ASSOCIATION:\n ImmutableSet affectedLabels =\n entry.getValue().stream()\n .filter(label -> isValidInAtLeastOneTld(label, idnChecker))\n .map(BlockLabel::label)\n .collect(toImmutableSet());\n ImmutableSet labelsInDb =\n Queries.queryBsaLabelByLabels(affectedLabels)\n .map(BsaLabel::getLabel)\n .collect(toImmutableSet());\n verify(\n labelsInDb.size() == affectedLabels.size(),\n \"Missing labels in DB: %s\",\n LazyArgs.lazy(() -> difference(affectedLabels, labelsInDb)));\n\n // Reuse registered and reserved names that are already computed.\n Queries.queryBsaUnblockableDomainByLabels(affectedLabels)\n .map(BsaUnblockableDomain::toUnblockableDomain)\n .forEach(nonBlockedDomains::add);\n\n for (BlockLabel label : entry.getValue()) {\n getInvalidTldsForLabel(label, idnChecker)\n .map(tld -> UnblockableDomain.of(label.label(), tld, Reason.INVALID))\n .forEach(nonBlockedDomains::add);\n }\n break;\n }\n }\n },\n TRANSACTION_REPEATABLE_READ);\n logger.atInfo().log(\"Processed %s of labels.\", labels.size());\n return nonBlockedDomains.build();\n }\n```\n###test function signature:\n```java\n @Test\n void applyLabelDiffs_newAssociationOfLabelToOrder()\n```\n### Answer: (use the provided format with backticks)\n", "name": "applyLabelDiffs_newAssociationOfLabelToOrder", "reference": " @Test\n void applyLabelDiffs_newAssociationOfLabelToOrder() {\n tm().transact(\n () -> {\n tm().insert(new BsaLabel(\"label\", fakeClock.nowUtc()));\n tm().insert(new BsaUnblockableDomain(\"label\", \"app\", Reason.REGISTERED));\n });\n when(idnChecker.getSupportingTlds(any())).thenReturn(ImmutableSet.of(app));\n when(idnChecker.getForbiddingTlds(any()))\n .thenReturn(Sets.difference(ImmutableSet.of(dev), ImmutableSet.of()).immutableCopy());\n\n ImmutableList unblockableDomains =\n applyLabelDiff(\n ImmutableList.of(\n BlockLabel.of(\"label\", LabelType.NEW_ORDER_ASSOCIATION, ImmutableSet.of())),\n idnChecker,\n schedule,\n fakeClock.nowUtc());\n assertThat(unblockableDomains)\n .containsExactly(\n UnblockableDomain.of(\"label.app\", UnblockableDomain.Reason.REGISTERED),\n UnblockableDomain.of(\"label.dev\", UnblockableDomain.Reason.INVALID));\n assertThat(tm().transact(() -> tm().loadByKeyIfPresent(BsaLabel.vKey(\"label\")))).isPresent();\n assertThat(\n tm().transact(() -> tm().loadByKeyIfPresent(BsaUnblockableDomain.vKey(\"label\", \"app\"))))\n .isPresent();\n }", "completions": [ "```java\n @Test\n void applyLabelDiffs_newAssociationOfLabelToOrder() {\n // Given\n ImmutableList labels = ImmutableList.of(BlockLabel.of(\"label1\", LabelType.NEW_ORDER_ASSOCIATION));\n IdnChecker idnChecker = mock(IdnChecker.class);\n DownloadSchedule schedule = mock(DownloadSchedule.class);\n DateTime now = DateTime.now();\n\n // When\n ImmutableList result = applyLabelDiff(labels, idnChecker, schedule, now);\n\n // Then\n // Add assertions here to verify the result\n }\n```\n" ], "line": 85, "token": 602, "line_diff": 2, "token_diff": 2 }, { "id": 83, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public CompletableFuture createTopic(CreateTopicRequest request) {\n CompletableFuture future = new CompletableFuture<>();\n for (; ; ) {\n if (metadataStore.isLeader()) {\n try (SqlSession session = metadataStore.openSession()) {\n if (!metadataStore.maintainLeadershipWithSharedLock(session)) {\n continue;\n }\n TopicMapper topicMapper = session.getMapper(TopicMapper.class);\n if (null != topicMapper.get(null, request.getTopic())) {\n ControllerException e = new ControllerException(Code.DUPLICATED_VALUE,\n String.format(\"Topic %s was taken\", request.getTopic()));\n future.completeExceptionally(e);\n return future;\n }\n\n Topic topic = new Topic();\n topic.setName(request.getTopic());\n topic.setQueueNum(request.getCount());\n topic.setStatus(TopicStatus.TOPIC_STATUS_ACTIVE);\n topic.setAcceptMessageTypes(JsonFormat.printer().print(request.getAcceptTypes()));\n topic.setRetentionHours(request.getRetentionHours());\n topicMapper.create(topic);\n long topicId = topic.getId();\n List assignments = createQueues(IntStream.range(0, request.getCount()),\n topicId, session);\n // Commit transaction\n session.commit();\n\n // Cache new topic and queue assignments immediately\n topicCache.apply(List.of(topic));\n assignmentCache.apply(assignments);\n future.complete(topicId);\n } catch (ControllerException | InvalidProtocolBufferException e) {\n future.completeExceptionally(e);\n }\n return future;\n } else {\n Optional leaderAddress = metadataStore.electionService().leaderAddress();\n if (leaderAddress.isEmpty()) {\n return CompletableFuture.failedFuture(new ControllerException(Code.NO_LEADER_VALUE, \"No leader is elected yet\"));\n }\n metadataStore.controllerClient().createTopic(leaderAddress.get(), request).whenComplete((res, e) -> {\n if (null != e) {\n future.completeExceptionally(e);\n } else {\n future.complete(res);\n }\n });\n }\n break;\n }\n return future;\n }\n```\n###test function signature:\n```java\n @Test\n public void testCreateTopic()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testCreateTopic", "reference": " @Test\n public void testCreateTopic() {\n MetadataStore metadataStore = Mockito.mock(MetadataStore.class);\n ControllerClient controllerClient = Mockito.mock(ControllerClient.class);\n Mockito.when(controllerClient.createTopic(ArgumentMatchers.anyString(), ArgumentMatchers.any())).thenReturn(\n CompletableFuture.failedFuture(new CompletionException(new RuntimeException()))\n );\n Mockito.when(metadataStore.controllerClient()).thenReturn(controllerClient);\n Mockito.when(metadataStore.isLeader()).thenReturn(false);\n\n ElectionService electionService = Mockito.mock(ElectionService.class);\n Mockito.when(metadataStore.electionService()).thenReturn(electionService);\n\n Mockito.when(electionService.leaderAddress()).thenReturn(Optional.of(\"localhost:1234\"));\n\n TopicManager topicManager = new TopicManager(metadataStore);\n topicManager.createTopic(CreateTopicRequest.newBuilder().build());\n }", "completions": [ "```java\n @Test\n public void testCreateTopic() {\n // Given\n CreateTopicRequest request = new CreateTopicRequest();\n request.setTopic(\"testTopic\");\n request.setCount(3);\n request.setRetentionHours(24);\n request.setAcceptTypes(List.of(MessageType.MESSAGE_TYPE_JSON));\n\n // When\n CompletableFuture future = controller.createTopic(request);\n\n // Then\n assertDoesNotThrow(() -> {\n Long topicId = future.get();\n assertNotNull(topicId);\n assertTrue(topicId > 0);\n });\n }\n```\n" ], "line": 63, "token": 424, "line_diff": 2, "token_diff": 2 }, { "id": 84, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public SendStatus sendHtmlMail(String subject, List toList, String username, String agentName, String emailHref, String maiContent) {\n SendStatus sendStatus = new SendStatus(SEND_STATUS_FALSE, \"\");\n List notInBlacklistAddress = checkNotInBlacklistAddress(toList,sendStatus);\n if(CollectionUtils.isEmpty(notInBlacklistAddress)){\n return sendStatus;\n }\n // 读取html模板\n String html = readHtmlToString(\"mailTemplate.html\");\n\n // 写入模板内容\n Document doc = Jsoup.parse(html);\n doc.getElementById(\"username\").html(username);\n\n if (StringUtils.isEmpty(agentName)) {\n sendStatus.setErrorMessage(\"agentName 为空\");\n return sendStatus;\n }\n doc.getElementById(\"sysName\").html(\"Your Agent:\");\n doc.getElementById(\"agentName\").html(agentName);\n doc.getElementById(\"mailContent\").html(maiContent);\n doc.getElementById(\"clickHref\").attr(\"href\", emailHref);\n\n String result = doc.toString();\n Properties props = new Properties();\n props.put(\"mail.smtp.host\", \"\");\n props.put(\"mail.smtp.auth\", \"true\");\n props.put(\"mail.smtp.socketFactory.class\", \"javax.net.ssl.SSLSocketFactory\");\n props.put(\"mail.smtp.socketFactory.fallback\", \"true\");\n Session session = Session.getDefaultInstance(props);\n session.setDebug(true);\n\n Transport transport = null;\n MimeMessage message = new MimeMessage(session);\n try {\n //初始化发送邮件配置\n this.initMailConfig();\n message.setFrom(new InternetAddress(this.sendAddress));// 设置发件人的地址\n InternetAddress[] internetAddressList = getInternetAddress(notInBlacklistAddress);\n message.setRecipients(Message.RecipientType.TO, internetAddressList);// 设置收件人,并设置其接收类型为TO\n message.setSubject(subject);// 设置标题\n message.setContent(result, \"text/html;charset=UTF-8\"); // 设置邮件内容类型为html\n message.setSentDate(new Date());// 设置发信时间\n message.saveChanges();// 存储邮件信息\n\n // 发送邮件\n transport = session.getTransport(\"smtp\");\n if (null != port) {\n transport.connect(host, port, user, password);\n } else {\n transport.connect(host, user, password);\n }\n transport.sendMessage(message, message.getAllRecipients());\n\n //发送邮件成功,status置为true\n sendStatus.setStatus(\"true\");\n } catch (Exception e) {\n log.error(\"邮件发送异常\", e);\n sendStatus.setErrorMessage(e.getMessage());\n } finally {\n if (null != transport) {\n try {\n transport.close();//关闭连接\n } catch (MessagingException e) {\n log.error(\"发送邮件 ,transport 关闭异常\", e);\n }\n }\n }\n return sendStatus;\n }\n```\n###test function signature:\n```java\n @Test\n void testSendHtmlMail_subjectNotNull()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testSendHtmlMail_subjectNotNull", "reference": " @Test\n void testSendHtmlMail_subjectNotNull(){\n try(MockedStatic sessionMockedStatic = Mockito.mockStatic(Session.class)){\n Session mockSession = mock(Session.class);\n Transport transport = mock(Transport.class);\n sessionMockedStatic.when(()->Session.getDefaultInstance(any(Properties.class))).thenReturn(mockSession);\n when(blacklistService.inBlacklist(anyString())).thenReturn(false);\n List addressList = new ArrayList<>();\n addressList.add(\"test@qq.com\");\n when(settingsService.getByCategoryAndKey(anyString(),anyString())).thenReturn(\"test\").thenReturn(5678).thenReturn(\"test\").thenReturn(\"test\").thenReturn(\"123456\");\n when(mockSession.getTransport(anyString())).thenReturn(transport);\n doNothing().when(transport).connect(anyString(),anyInt(),anyString(),anyString());\n doAnswer(invocationOnMock -> {\n InternetAddress[] internetAddressList = invocationOnMock.getArgument(1);\n Assertions.assertEquals(addressList.get(0),internetAddressList[0].getAddress());\n return null;\n }).when(transport).sendMessage(any(MimeMessage.class),any());\n mailUtils.sendHtmlMail(\"\",addressList,\"test\",\"test\",\"test\",\"test\");\n } catch (MessagingException e) {\n throw new RuntimeException(e);\n }\n }", "completions": [ "```java\n @Test\n void testSendHtmlMail_subjectNotNull() {\n // Arrange\n String subject = \"Test Subject\";\n List toList = Arrays.asList(\"test1@example.com\", \"test2@example.com\");\n String username = \"Test User\";\n String agentName = \"Test Agent\";\n String emailHref = \"http://example.com\";\n String maiContent = \"Test Content\";\n\n // Act\n SendStatus result = mailService.sendHtmlMail(subject, toList, username, agentName, emailHref, maiContent);\n\n // Assert\n assertEquals(SEND_STATUS_FALSE, result.getStatus());\n assertEquals(\"\", result.getErrorMessage());\n }\n```\n" ], "line": 74, "token": 533, "line_diff": 2, "token_diff": 2 }, { "id": 85, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public long determineStartingOffset(\n long currentEndOffsetForPartition,\n long currentBeginningOffsetForPartition,\n AstraConfigs.IndexerConfig indexerConfig) {\n // Filter stale snapshots for partition.\n if (partitionId == null) {\n LOG.warn(\"PartitionId can't be null.\");\n }\n\n List snapshots = snapshotMetadataStore.listSync();\n List snapshotsForPartition =\n snapshots.stream()\n .filter(\n snapshotMetadata -> {\n if (snapshotMetadata == null || snapshotMetadata.partitionId == null) {\n LOG.warn(\n \"snapshot metadata or partition id can't be null: {} \",\n Strings.join(snapshots, ','));\n }\n return snapshotMetadata != null\n && snapshotMetadata.partitionId != null\n && snapshotMetadata.partitionId.equals(partitionId);\n })\n .collect(Collectors.toUnmodifiableList());\n List deletedSnapshots = deleteStaleLiveSnapshots(snapshotsForPartition);\n\n List nonLiveSnapshotsForPartition =\n snapshotsForPartition.stream()\n .filter(s -> !deletedSnapshots.contains(s))\n .collect(Collectors.toUnmodifiableList());\n\n // Get the highest offset that is indexed in durable store.\n List recoveryTasks = recoveryTaskMetadataStore.listSync();\n long highestDurableOffsetForPartition =\n getHighestDurableOffsetForPartition(\n nonLiveSnapshotsForPartition, recoveryTasks, partitionId);\n LOG.debug(\n \"The highest durable offset for partition {} is {}\",\n partitionId,\n highestDurableOffsetForPartition);\n\n if (highestDurableOffsetForPartition <= 0) {\n LOG.info(\"There is no prior offset for this partition {}.\", partitionId);\n\n // If the user wants to start at the current offset in Kafka and _does not_ want to create\n // recovery tasks to backfill, then we can just return the current offset.\n // If the user wants to start at the current offset in Kafka and _does_ want to create\n // recovery tasks to backfill, then we create the recovery tasks needed and then return\n // the current offset for the indexer. And if the user does _not_ want to start at the\n // current offset in Kafka, then we'll just default to the old behavior of starting from\n // the very beginning\n if (!indexerConfig.getCreateRecoveryTasksOnStart()\n && indexerConfig.getReadFromLocationOnStart()\n == AstraConfigs.KafkaOffsetLocation.LATEST) {\n LOG.info(\n \"CreateRecoveryTasksOnStart is set to false and ReadLocationOnStart is set to current. Reading from current and\"\n + \" NOT spinning up recovery tasks\");\n return currentEndOffsetForPartition;\n } else if (indexerConfig.getCreateRecoveryTasksOnStart()\n && indexerConfig.getReadFromLocationOnStart()\n == AstraConfigs.KafkaOffsetLocation.LATEST) {\n // Todo - this appears to be able to create recovery tasks that have a start and end\n // position of 0, which is invalid. This seems to occur when new clusters are initialized,\n // and is especially problematic when indexers are created but never get assigned (ie,\n // deploy 5, only assign 3).\n LOG.info(\n \"CreateRecoveryTasksOnStart is set and ReadLocationOnStart is set to current. Reading from current and\"\n + \" spinning up recovery tasks\");\n createRecoveryTasks(\n partitionId,\n currentBeginningOffsetForPartition,\n currentEndOffsetForPartition,\n indexerConfig.getMaxMessagesPerChunk());\n return currentEndOffsetForPartition;\n\n } else {\n return highestDurableOffsetForPartition;\n }\n }\n\n // The current head offset shouldn't be lower than the highest durable offset. If it is it\n // means that we indexed more data than the current head offset. This is either a bug in the\n // offset handling mechanism or the kafka partition has rolled over. We throw an exception\n // for now, so we can investigate.\n if (currentEndOffsetForPartition < highestDurableOffsetForPartition) {\n final String message =\n String.format(\n \"The current head for the partition %d can't \"\n + \"be lower than the highest durable offset for that partition %d\",\n currentEndOffsetForPartition, highestDurableOffsetForPartition);\n LOG.error(message);\n throw new IllegalStateException(message);\n }\n\n // The head offset for Kafka partition is the offset of the next message to be indexed. We\n // assume that offset is passed into this function. The highest durable offset is the partition\n // offset of the message that is indexed. Hence, the offset is incremented by 1 to get the\n // next message.\n long nextOffsetForPartition = highestDurableOffsetForPartition + 1;\n\n // Create a recovery task if needed.\n if (currentEndOffsetForPartition - highestDurableOffsetForPartition > maxOffsetDelay) {\n LOG.info(\n \"Recovery task needed. The current position {} and head location {} are higher than max\"\n + \" offset {}\",\n highestDurableOffsetForPartition,\n currentEndOffsetForPartition,\n maxOffsetDelay);\n createRecoveryTasks(\n partitionId,\n nextOffsetForPartition,\n currentEndOffsetForPartition - 1,\n maxMessagesPerRecoveryTask);\n return currentEndOffsetForPartition;\n } else {\n LOG.info(\n \"The difference between the last indexed position {} and head location {} is lower \"\n + \"than max offset {}. So, using {} position as the start offset\",\n highestDurableOffsetForPartition,\n currentEndOffsetForPartition,\n maxOffsetDelay,\n nextOffsetForPartition);\n return nextOffsetForPartition;\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void\n testDetermineStartingOffsetReturnsHeadWhenCreateTasksIsFalseAndOffsetLocationIsHead()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testDetermineStartingOffsetReturnsHeadWhenCreateTasksIsFalseAndOffsetLocationIsHead", "reference": " @Test\n public void\n testDetermineStartingOffsetReturnsHeadWhenCreateTasksIsFalseAndOffsetLocationIsHead() {\n RecoveryTaskCreator recoveryTaskCreator =\n new RecoveryTaskCreator(\n snapshotMetadataStore,\n recoveryTaskStore,\n partitionId,\n 1,\n TEST_MAX_MESSAGES_PER_RECOVERY_TASK,\n meterRegistry);\n\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore)).isEmpty();\n assertThat(AstraMetadataTestUtils.listSyncUncached(recoveryTaskStore)).isEmpty();\n\n AstraConfigs.IndexerConfig headLocationAndNoRecoveryConfig =\n AstraConfigs.IndexerConfig.newBuilder()\n .setCreateRecoveryTasksOnStart(false)\n .setReadFromLocationOnStart(AstraConfigs.KafkaOffsetLocation.LATEST)\n .build();\n\n // When there is no data and ReadFromLocationOnStart is set to LATEST, return the current head\n assertThat(\n recoveryTaskCreator.determineStartingOffset(1000, 0, headLocationAndNoRecoveryConfig))\n .isEqualTo(1000);\n\n // Data exists for not for this partition.\n final String name = \"testSnapshotId\";\n final String path = \"/testPath_\" + name;\n final long startTime = 1;\n final long endTime = 100;\n final long maxOffset = 100;\n\n final SnapshotMetadata partition1 =\n new SnapshotMetadata(name, path, startTime, endTime, maxOffset, \"2\", LOGS_LUCENE9);\n snapshotMetadataStore.createSync(partition1);\n await().until(() -> snapshotMetadataStore.listSync().contains(partition1));\n\n assertThat(recoveryTaskCreator.determineStartingOffset(1, -1, headLocationAndNoRecoveryConfig))\n .isEqualTo(1);\n\n final SnapshotMetadata partition11 =\n new SnapshotMetadata(\n name + \"1\", path, endTime + 1, endTime * 2, maxOffset * 2, \"2\", LOGS_LUCENE9);\n snapshotMetadataStore.createSync(partition11);\n await().until(() -> snapshotMetadataStore.listSync().contains(partition11));\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore))\n .contains(partition1, partition11);\n assertThat(recoveryTaskCreator.determineStartingOffset(0, 0, indexerConfig)).isNegative();\n\n final String recoveryTaskName = \"recoveryTask\";\n final long recoveryStartOffset = 400;\n final long createdTimeUtc = Instant.now().toEpochMilli();\n\n final RecoveryTaskMetadata recoveryTask1 =\n new RecoveryTaskMetadata(\n recoveryTaskName + \"1\",\n \"2\",\n recoveryStartOffset,\n recoveryStartOffset * 2,\n createdTimeUtc);\n recoveryTaskStore.createSync(recoveryTask1);\n await().until(() -> recoveryTaskStore.listSync().contains(recoveryTask1));\n assertThat(recoveryTaskCreator.determineStartingOffset(1, -1, headLocationAndNoRecoveryConfig))\n .isEqualTo(1);\n }", "completions": [ "```java\n @Test\n public void testDetermineStartingOffsetReturnsHeadWhenCreateTasksIsFalseAndOffsetLocationIsHead() {\n // Given\n String partitionId = \"testPartition\";\n long currentEndOffsetForPartition = 100L;\n long currentBeginningOffsetForPartition = 0L;\n AstraConfigs.IndexerConfig indexerConfig = new AstraConfigs.IndexerConfig();\n indexerConfig.setCreateRecoveryTasksOnStart(false);\n indexerConfig.setReadFromLocationOnStart(AstraConfigs.KafkaOffsetLocation.LATEST);\n\n // When\n long result = determineStartingOffset(currentEndOffsetForPartition, currentBeginningOffsetForPartition, indexerConfig);\n\n // Then\n assertEquals(currentEndOffsetForPartition, result);\n }\n```\n" ], "line": 128, "token": 935, "line_diff": 2, "token_diff": 2 }, { "id": 86, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @VisibleForTesting\n boolean handleRecoveryTask(RecoveryTaskMetadata recoveryTaskMetadata) {\n LOG.info(\"Started handling the recovery task: {}\", recoveryTaskMetadata);\n long startTime = System.nanoTime();\n Timer.Sample taskTimer = Timer.start(meterRegistry);\n\n PartitionOffsets partitionOffsets =\n validateKafkaOffsets(\n adminClient,\n recoveryTaskMetadata,\n AstraConfig.getRecoveryConfig().getKafkaConfig().getKafkaTopic());\n long offsetsValidatedTime = System.nanoTime();\n long consumerPreparedTime = 0, messagesConsumedTime = 0, rolloversCompletedTime = 0;\n\n if (partitionOffsets != null) {\n RecoveryTaskMetadata validatedRecoveryTask =\n new RecoveryTaskMetadata(\n recoveryTaskMetadata.name,\n recoveryTaskMetadata.partitionId,\n partitionOffsets.startOffset,\n partitionOffsets.endOffset,\n recoveryTaskMetadata.createdTimeEpochMs);\n\n if (partitionOffsets.startOffset != recoveryTaskMetadata.startOffset\n || recoveryTaskMetadata.endOffset != partitionOffsets.endOffset) {\n recoveryRecordsNoLongerAvailable.increment(\n (partitionOffsets.startOffset - recoveryTaskMetadata.startOffset)\n + (partitionOffsets.endOffset - recoveryTaskMetadata.endOffset));\n }\n\n try {\n RecoveryChunkManager chunkManager =\n RecoveryChunkManager.fromConfig(\n meterRegistry,\n searchMetadataStore,\n snapshotMetadataStore,\n AstraConfig.getIndexerConfig(),\n blobFs,\n AstraConfig.getS3Config());\n\n // Ingest data in parallel\n LogMessageWriterImpl logMessageWriterImpl = new LogMessageWriterImpl(chunkManager);\n AstraKafkaConsumer kafkaConsumer =\n new AstraKafkaConsumer(\n makeKafkaConfig(\n AstraConfig.getRecoveryConfig().getKafkaConfig(),\n validatedRecoveryTask.partitionId),\n logMessageWriterImpl,\n meterRegistry);\n\n kafkaConsumer.prepConsumerForConsumption(validatedRecoveryTask.startOffset);\n consumerPreparedTime = System.nanoTime();\n kafkaConsumer.consumeMessagesBetweenOffsetsInParallel(\n AstraKafkaConsumer.KAFKA_POLL_TIMEOUT_MS,\n validatedRecoveryTask.startOffset,\n validatedRecoveryTask.endOffset);\n messagesConsumedTime = System.nanoTime();\n // Wait for chunks to upload.\n boolean success = chunkManager.waitForRollOvers();\n rolloversCompletedTime = System.nanoTime();\n // Close the recovery chunk manager and kafka consumer.\n kafkaConsumer.close();\n chunkManager.stopAsync();\n chunkManager.awaitTerminated(DEFAULT_START_STOP_DURATION);\n LOG.info(\"Finished handling the recovery task: {}\", validatedRecoveryTask);\n taskTimer.stop(recoveryTaskTimerSuccess);\n return success;\n } catch (Exception ex) {\n LOG.error(\"Exception in recovery task [{}]: {}\", validatedRecoveryTask, ex);\n taskTimer.stop(recoveryTaskTimerFailure);\n return false;\n } finally {\n long endTime = System.nanoTime();\n LOG.info(\n \"Recovery task {} took {}ms, (subtask times offset validation {}, consumer prep {}, msg consumption {}, rollover {})\",\n recoveryTaskMetadata,\n nanosToMillis(endTime - startTime),\n nanosToMillis(offsetsValidatedTime - startTime),\n nanosToMillis(consumerPreparedTime - offsetsValidatedTime),\n nanosToMillis(messagesConsumedTime - consumerPreparedTime),\n nanosToMillis(rolloversCompletedTime - messagesConsumedTime));\n }\n } else {\n LOG.info(\n \"Recovery task {} data no longer available in Kafka (validation time {}ms)\",\n recoveryTaskMetadata,\n nanosToMillis(offsetsValidatedTime - startTime));\n recoveryRecordsNoLongerAvailable.increment(\n recoveryTaskMetadata.endOffset - recoveryTaskMetadata.startOffset + 1);\n return true;\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testShouldHandleRecoveryTaskWithCompletelyUnavailableOffsets() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "testShouldHandleRecoveryTaskWithCompletelyUnavailableOffsets", "reference": " @Test\n public void testShouldHandleRecoveryTaskWithCompletelyUnavailableOffsets() throws Exception {\n final TopicPartition topicPartition = new TopicPartition(TestKafkaServer.TEST_KAFKA_TOPIC, 0);\n TestKafkaServer.KafkaComponents components = getKafkaTestServer(S3_MOCK_EXTENSION);\n AstraConfigs.AstraConfig astraCfg =\n makeAstraConfig(components.testKafkaServer, TEST_S3_BUCKET, topicPartition.topic());\n curatorFramework =\n CuratorBuilder.build(meterRegistry, astraCfg.getMetadataStoreConfig().getZookeeperConfig());\n\n AstraConfigs.KafkaConfig kafkaConfig =\n AstraConfigs.KafkaConfig.newBuilder()\n .setKafkaTopic(topicPartition.topic())\n .setKafkaTopicPartition(Integer.toString(topicPartition.partition()))\n .setKafkaBootStrapServers(components.testKafkaServer.getBroker().getBrokerList().get())\n .setKafkaClientGroup(TEST_KAFKA_CLIENT_GROUP)\n .setEnableKafkaAutoCommit(\"true\")\n .setKafkaAutoCommitInterval(\"500\")\n .setKafkaSessionTimeout(\"500\")\n .putAllAdditionalProps(Maps.fromProperties(components.consumerOverrideProps))\n .build();\n\n final AstraKafkaConsumer localTestConsumer =\n new AstraKafkaConsumer(kafkaConfig, components.logMessageWriter, components.meterRegistry);\n final Instant startTime =\n LocalDateTime.of(2020, 10, 1, 10, 10, 0).atZone(ZoneOffset.UTC).toInstant();\n final long msgsToProduce = 100;\n TestKafkaServer.produceMessagesToKafka(\n components.testKafkaServer.getBroker(),\n startTime,\n topicPartition.topic(),\n topicPartition.partition(),\n (int) msgsToProduce);\n await().until(() -> localTestConsumer.getEndOffSetForPartition() == msgsToProduce);\n // we immediately force delete the messages, as this is faster than changing the retention and\n // waiting for the cleaner to run\n components\n .adminClient\n .deleteRecords(Map.of(topicPartition, RecordsToDelete.beforeOffset(100)))\n .all()\n .get();\n assertThat(getStartOffset(components.adminClient, topicPartition)).isGreaterThan(0);\n\n // produce some more messages that won't be expired\n setRetentionTime(components.adminClient, topicPartition.topic(), 25000);\n TestKafkaServer.produceMessagesToKafka(\n components.testKafkaServer.getBroker(),\n startTime,\n topicPartition.topic(),\n topicPartition.partition(),\n (int) msgsToProduce);\n await()\n .until(() -> localTestConsumer.getEndOffSetForPartition() == msgsToProduce + msgsToProduce);\n\n SnapshotMetadataStore snapshotMetadataStore = new SnapshotMetadataStore(curatorFramework);\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore).size()).isZero();\n\n // Start recovery service\n recoveryService =\n new RecoveryService(astraCfg, curatorFramework, components.meterRegistry, blobFs);\n recoveryService.startAsync();\n recoveryService.awaitRunning(DEFAULT_START_STOP_DURATION);\n long startOffset = 1;\n long endOffset = msgsToProduce - 1;\n RecoveryTaskMetadata recoveryTask =\n new RecoveryTaskMetadata(\n topicPartition.topic(),\n Integer.toString(topicPartition.partition()),\n startOffset,\n endOffset,\n Instant.now().toEpochMilli());\n assertThat(recoveryService.handleRecoveryTask(recoveryTask)).isTrue();\n assertThat(getCount(RECORDS_NO_LONGER_AVAILABLE, components.meterRegistry))\n .isEqualTo(endOffset - startOffset + 1);\n assertThat(getCount(MESSAGES_RECEIVED_COUNTER, components.meterRegistry)).isEqualTo(0);\n List snapshots =\n AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore);\n assertThat(snapshots.size()).isEqualTo(0);\n assertThat(blobFs.listFiles(BlobFsUtils.createURI(TEST_S3_BUCKET, \"/\", \"\"), true)).isEmpty();\n assertThat(getCount(MESSAGES_FAILED_COUNTER, meterRegistry)).isEqualTo(0);\n assertThat(getCount(ROLLOVERS_INITIATED, meterRegistry)).isEqualTo(0);\n assertThat(getCount(ROLLOVERS_COMPLETED, meterRegistry)).isEqualTo(0);\n assertThat(getCount(ROLLOVERS_FAILED, meterRegistry)).isEqualTo(0);\n }", "completions": [ "```java\n @Test\n public void testShouldHandleRecoveryTaskWithCompletelyUnavailableOffsets() throws Exception {\n // Given\n RecoveryTaskMetadata recoveryTaskMetadata = new RecoveryTaskMetadata(\n \"testTask\",\n 0,\n 0,\n 100,\n System.currentTimeMillis());\n\n // When\n boolean result = handleRecoveryTask(recoveryTaskMetadata);\n\n // Then\n assertTrue(result);\n }\n```\n" ], "line": 97, "token": 544, "line_diff": 2, "token_diff": 2 }, { "id": 87, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public static CacheControlHeader fromExpirationTime(String expirationTime) {\n String maxAge = DEFAULT_MAX_AGE;\n\n if (expirationTime != null) {\n if (expirationTimeIsValid(expirationTime)) {\n Duration totalTime = Duration.ZERO;\n for (String timeString : Splitter.on(\" \").split(expirationTime)) {\n String timeUnitShort = Ascii.toLowerCase(timeString.substring(timeString.length() - 1));\n TemporalUnit timeUnit = EXPIRATION_TIME_UNITS.get(timeUnitShort);\n String timeValue = timeString.substring(0, timeString.length() - 1);\n totalTime = totalTime.plus(Long.parseLong(timeValue), timeUnit);\n }\n maxAge = String.valueOf(totalTime.getSeconds());\n } else {\n logger.atWarning().log(\n \"Failed to parse expiration time: \\\"%s\\\". Using default value instead.\",\n expirationTime\n );\n }\n }\n\n String output = DEFAULT_BASE_VALUE + maxAge;\n return new CacheControlHeader(output);\n }\n```\n###test function signature:\n```java\n @Test\n public void fromExpirationTime_usesDefaultMaxAgeForIncorrectTimeUnits() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "fromExpirationTime_usesDefaultMaxAgeForIncorrectTimeUnits", "reference": " @Test\n public void fromExpirationTime_usesDefaultMaxAgeForIncorrectTimeUnits() throws Exception {\n CacheControlHeader cacheControlHeader = CacheControlHeader.fromExpirationTime(\"3g\");\n assertThat(cacheControlHeader.getValue()).isEqualTo(\"public, max-age=600\");\n }", "completions": [ "```java\n @Test\n public void fromExpirationTime_usesDefaultMaxAgeForIncorrectTimeUnits() throws Exception {\n String expirationTime = \"10x\";\n CacheControlHeader header = CacheControlHeader.fromExpirationTime(expirationTime);\n assertEquals(CacheControlHeader.DEFAULT_BASE_VALUE + CacheControlHeader.DEFAULT_MAX_AGE, header.getValue());\n }\n```\n" ], "line": 33, "token": 241, "line_diff": 0, "token_diff": 0 }, { "id": 88, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public T clone(T object) {\n if (object instanceof String) {\n return object;\n } else if (object instanceof Collection) {\n Object firstElement = findFirstNonNullElement((Collection) object);\n if (firstElement != null && !(firstElement instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), firstElement.getClass());\n return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n } else if (object instanceof Map) {\n Map.Entry firstEntry = this.findFirstNonNullEntry((Map) object);\n if (firstEntry != null) {\n Object key = firstEntry.getKey();\n Object value = firstEntry.getValue();\n if (!(key instanceof Serializable) || !(value instanceof Serializable)) {\n JavaType type = TypeFactory.defaultInstance().constructParametricType(object.getClass(), key.getClass(), value.getClass());\n return (T) objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), type);\n }\n }\n } else if (object instanceof JsonNode) {\n return (T) ((JsonNode) object).deepCopy();\n }\n\n if (object instanceof Serializable) {\n try {\n return (T) SerializationHelper.clone((Serializable) object);\n } catch (SerializationException e) {\n //it is possible that object itself implements java.io.Serializable, but underlying structure does not\n //in this case we switch to the other JSON marshaling strategy which doesn't use the Java serialization\n }\n }\n\n return jsonClone(object);\n }\n```\n###test function signature:\n```java\n @Test\n public void should_clone_empty_collection()\n```\n### Answer: (use the provided format with backticks)\n", "name": "should_clone_empty_collection", "reference": " @Test\n public void should_clone_empty_collection() {\n List original = new ArrayList<>();\n Object cloned = serializer.clone(original);\n assertEquals(original, cloned);\n assertNotSame(original, cloned);\n }", "completions": [ "```java\n @Test\n public void should_clone_empty_collection() {\n // Given\n Collection collection = new ArrayList<>();\n\n // When\n Collection clonedCollection = (Collection) clone(collection);\n\n // Then\n assertNotSame(collection, clonedCollection);\n assertEquals(collection, clonedCollection);\n }\n```\n" ], "line": 44, "token": 358, "line_diff": 1, "token_diff": 1 }, { "id": 89, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public SearchResult search(\n String dataset,\n String queryStr,\n Long startTimeMsEpoch,\n Long endTimeMsEpoch,\n int howMany,\n AggBuilder aggBuilder) {\n\n ensureNonEmptyString(dataset, \"dataset should be a non-empty string\");\n ensureNonNullString(queryStr, \"query should be a non-empty string\");\n if (startTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch >= 0, \"start time should be non-negative value\");\n }\n if (startTimeMsEpoch != null && endTimeMsEpoch != null) {\n ensureTrue(startTimeMsEpoch < endTimeMsEpoch, \"end time should be greater than start time\");\n }\n ensureTrue(howMany >= 0, \"hits requested should not be negative.\");\n ensureTrue(howMany > 0 || aggBuilder != null, \"Hits or aggregation should be requested.\");\n\n ScopedSpan span = Tracing.currentTracer().startScopedSpan(\"LogIndexSearcherImpl.search\");\n span.tag(\"dataset\", dataset);\n span.tag(\"startTimeMsEpoch\", String.valueOf(startTimeMsEpoch));\n span.tag(\"endTimeMsEpoch\", String.valueOf(endTimeMsEpoch));\n span.tag(\"howMany\", String.valueOf(howMany));\n\n Stopwatch elapsedTime = Stopwatch.createStarted();\n try {\n // Acquire an index searcher from searcher manager.\n // This is a useful optimization for indexes that are static.\n IndexSearcher searcher = searcherManager.acquire();\n\n Query query =\n openSearchAdapter.buildQuery(\n dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, searcher);\n try {\n List results;\n InternalAggregation internalAggregation = null;\n\n if (howMany > 0) {\n CollectorManager topFieldCollector =\n buildTopFieldCollector(howMany, aggBuilder != null ? Integer.MAX_VALUE : howMany);\n MultiCollectorManager collectorManager;\n if (aggBuilder != null) {\n collectorManager =\n new MultiCollectorManager(\n topFieldCollector,\n openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n } else {\n collectorManager = new MultiCollectorManager(topFieldCollector);\n }\n Object[] collector = searcher.search(query, collectorManager);\n\n ScoreDoc[] hits = ((TopFieldDocs) collector[0]).scoreDocs;\n results = new ArrayList<>(hits.length);\n for (ScoreDoc hit : hits) {\n results.add(buildLogMessage(searcher, hit));\n }\n if (aggBuilder != null) {\n internalAggregation = (InternalAggregation) collector[1];\n }\n } else {\n results = Collections.emptyList();\n internalAggregation =\n searcher.search(\n query, openSearchAdapter.getCollectorManager(aggBuilder, searcher, query));\n }\n\n elapsedTime.stop();\n return new SearchResult<>(\n results, elapsedTime.elapsed(TimeUnit.MICROSECONDS), 0, 0, 1, 1, internalAggregation);\n } finally {\n searcherManager.release(searcher);\n }\n } catch (IOException e) {\n span.error(e);\n throw new IllegalArgumentException(\"Failed to acquire an index searcher.\", e);\n } finally {\n span.finish();\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testTimeBoundSearch()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testTimeBoundSearch", "reference": " @Test\n public void testTimeBoundSearch() {\n Instant time = Instant.now();\n strictLogStore.logStore.addMessage(SpanUtil.makeSpan(1, time));\n strictLogStore.logStore.addMessage(SpanUtil.makeSpan(2, time.plusSeconds(100)));\n strictLogStore.logStore.commit();\n strictLogStore.logStore.refresh();\n\n assertThat(getCount(MESSAGES_RECEIVED_COUNTER, strictLogStore.metricsRegistry)).isEqualTo(2);\n assertThat(getCount(MESSAGES_FAILED_COUNTER, strictLogStore.metricsRegistry)).isEqualTo(0);\n assertThat(getTimerCount(REFRESHES_TIMER, strictLogStore.metricsRegistry)).isEqualTo(1);\n\n // Start inclusive.\n assertThat(\n strictLogStore\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"Message1\",\n time.toEpochMilli(),\n time.plusSeconds(10).toEpochMilli(),\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isEqualTo(1);\n\n // Extended range still only picking one element.\n assertThat(\n strictLogStore\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"Message1\",\n time.minusSeconds(1).toEpochMilli(),\n time.plusSeconds(90).toEpochMilli(),\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isEqualTo(1);\n\n // Both ranges are inclusive.\n assertThat(\n strictLogStore\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"_id:Message1 OR Message2\",\n time.toEpochMilli(),\n time.plusSeconds(100).toEpochMilli(),\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isEqualTo(2);\n\n // Extended range to pick up both events\n assertThat(\n strictLogStore\n .logSearcher\n .search(\n TEST_DATASET_NAME,\n \"_id:Message1 OR Message2\",\n time.minusSeconds(1).toEpochMilli(),\n time.plusSeconds(1000).toEpochMilli(),\n 1000,\n new DateHistogramAggBuilder(\n \"1\", LogMessage.SystemField.TIME_SINCE_EPOCH.fieldName, \"1s\"))\n .hits\n .size())\n .isEqualTo(2);\n }", "completions": [ "```java\n @Test\n public void testTimeBoundSearch() {\n // Given\n String dataset = \"test_dataset\";\n String queryStr = \"test_query\";\n Long startTimeMsEpoch = 1577836800000L; // 2020-01-01 00:00:00\n Long endTimeMsEpoch = 1577923199000L; // 2020-01-02 23:59:59\n int howMany = 10;\n AggBuilder aggBuilder = null;\n\n // When\n SearchResult result = logIndexSearcher.search(dataset, queryStr, startTimeMsEpoch, endTimeMsEpoch, howMany, aggBuilder);\n\n // Then\n assertNotNull(result);\n assertEquals(howMany, result.getResults().size());\n for (LogMessage logMessage : result.getResults()) {\n assertTrue(logMessage.getTimestampMs() >= startTimeMsEpoch);\n assertTrue(logMessage.getTimestampMs() <= endTimeMsEpoch);\n }\n }\n```\n" ], "line": 85, "token": 606, "line_diff": 2, "token_diff": 2 }, { "id": 90, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n\tpublic void setUserData(String theKey, Object theValue) {\n\t\tValidate.isTrue(isNotBlank(theKey), \"Invalid key; key must be non-empty, non-null.\");\n\t\tif (theValue == null) {\n\t\t\tgetUserData().remove(theKey);\n\t\t} else {\n\t\t\tValidate.isTrue(\n\t\t\t\t\tvalidateValue(theValue),\n\t\t\t\t\tString.format(\n\t\t\t\t\t\t\t\"Invalid data type provided %s\", theValue.getClass().getName()));\n\t\t\tgetUserData().put(theKey, theValue);\n\t\t}\n\t}\n```\n###test function signature:\n```java\n\t@ParameterizedTest\n\t@MethodSource(\"parameters\")\n\tpublic void setUserData_acceptsStringNumberAndBooleansOnly(TestParam theParams)\n```\n### Answer: (use the provided format with backticks)\n", "name": "\t@ParameterizedTest\n\t@MethodSource", "reference": "\t@ParameterizedTest\n\t@MethodSource(\"parameters\")\n\tpublic void setUserData_acceptsStringNumberAndBooleansOnly(TestParam theParams) {\n\t\t// setup\n\t\tString key = \"key\";\n\t\tTestParameters parameters = new TestParameters();\n\t\tObject testValue = theParams.getTestValue();\n\n\t\t// test\n\t\tif (theParams.isExpectedToWork()) {\n\t\t\tparameters.setUserData(key, testValue);\n\t\t\tassertFalse(parameters.getUserData().isEmpty());\n\t\t\tassertEquals(testValue, parameters.getUserData().get(key));\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tparameters.setUserData(key, testValue);\n\t\t\t\tfail();\n\t\t\t} catch (IllegalArgumentException ex) {\n\t\t\t\tString dataType = testValue.getClass().getName();\n\t\t\t\tassertTrue(ex.getMessage().contains(\"Invalid data type provided \" + dataType),\n\t\t\t\t\tex.getMessage());\n\t\t\t\tassertTrue(parameters.getUserData().isEmpty());\n\t\t\t}\n\t\t}\n\t}", "completions": [ "```java\n\t@ParameterizedTest\n\t@MethodSource(\"parameters\")\n\tpublic void setUserData_acceptsStringNumberAndBooleansOnly(TestParam theParams) {\n\t\tUser user = new User();\n\t\tuser.setUserData(theParams.getKey(), theParams.getValue());\n\t\tassertEquals(theParams.getValue(), user.getUserData().get(theParams.getKey()));\n\t}\n\n\tstatic Stream parameters() {\n\t\treturn Stream.of(\n\t\t\t\tnew TestParam(\"stringKey\", \"stringValue\"),\n\t\t\t\tnew TestParam(\"numberKey\", 123),\n\t\t\t\tnew TestParam(\"booleanKey\", true),\n\t\t\t\tnew TestParam(\"nullKey\", null)\n\t\t);\n\t}\n\n\tstatic class TestParam {\n\t\tprivate final String key;\n\t\tprivate final Object value;\n\n\t\tTestParam(String key, Object value) {\n\t\t\tthis.key = key;\n\t\t\tthis.value = value;\n\t\t}\n\n\t\tString getKey() {\n\t\t\treturn key;\n\t\t}\n\n\t\tObject getValue() {\n\t\t\treturn value;\n\t\t}\n\t}\n```\n" ], "line": 24, "token": 179, "line_diff": 0, "token_diff": 0 }, { "id": 91, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n\tpublic Embedding embedText(String text) {\n\t\tAssert.hasText(text, \"The text can not be null or empty.\");\n\n\t\t@JsonInclude(Include.NON_NULL)\n\t\trecord EmbeddingResponse(Embedding embedding) {\n\t\t}\n\n\t\tEmbeddingResponse response = this.restClient.post()\n\t\t\t\t.uri(\"/models/{model}:embedText?key={apiKey}\", this.embeddingModel, this.apiKey)\n\t\t\t\t.body(Map.of(\"text\", text))\n\t\t\t\t.retrieve()\n\t\t\t\t.body(EmbeddingResponse.class);\n\n\t\treturn response != null ? response.embedding() : null;\n\t}\n```\n###test function signature:\n```java\n\t@Test\n\tpublic void embedText() throws JsonProcessingException\n```\n### Answer: (use the provided format with backticks)\n", "name": "embedText", "reference": "\t@Test\n\tpublic void embedText() throws JsonProcessingException {\n\n\t\tString text = \"Hello, how are you?\";\n\n\t\tEmbedding expectedEmbedding = new Embedding(List.of(0.1, 0.2, 0.3));\n\n\t\tserver\n\t\t\t.expect(requestToUriTemplate(\"/models/{generative}:embedText?key={apiKey}\",\n\t\t\t\t\tVertexAiPaLm2Api.DEFAULT_EMBEDDING_MODEL, TEST_API_KEY))\n\t\t\t.andExpect(method(HttpMethod.POST))\n\t\t\t.andExpect(content().json(objectMapper.writeValueAsString(Map.of(\"text\", text))))\n\t\t\t.andRespond(withSuccess(objectMapper.writeValueAsString(Map.of(\"embedding\", expectedEmbedding)),\n\t\t\t\t\tMediaType.APPLICATION_JSON));\n\n\t\tEmbedding embedding = client.embedText(text);\n\n\t\tassertThat(embedding).isEqualTo(expectedEmbedding);\n\n\t\tserver.verify();\n\t}", "completions": [ "```java\n\t@Test\n\tpublic void embedText() throws JsonProcessingException {\n\t\tString text = \"This is a test text.\";\n\t\tEmbedding expectedEmbedding = new Embedding(new double[] {0.1, 0.2, 0.3});\n\n\t\tEmbeddingResponse response = new EmbeddingResponse(expectedEmbedding);\n\t\twhen(this.restClient.post()\n\t\t\t\t.uri(\"/models/{model}:embedText?key={apiKey}\", this.embeddingModel, this.apiKey)\n\t\t\t\t.body(Map.of(\"text\", text))\n\t\t\t\t.retrieve()\n\t\t\t\t.body(EmbeddingResponse.class)).thenReturn(response);\n\n\t\tEmbedding actualEmbedding = this.embeddingService.embedText(text);\n\n\t\tassertEquals(expectedEmbedding, actualEmbedding);\n\t}\n```\n" ], "line": 23, "token": 179, "line_diff": 0, "token_diff": 0 }, { "id": 92, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public Mono syncAclWithAclCsv(KafkaCluster cluster, String csv) {\n return adminClientService.get(cluster)\n .flatMap(ac -> ac.listAcls(ResourcePatternFilter.ANY).flatMap(existingAclList -> {\n var existingSet = Set.copyOf(existingAclList);\n var newAcls = Set.copyOf(AclCsv.parseCsv(csv));\n var toDelete = Sets.difference(existingSet, newAcls);\n var toAdd = Sets.difference(newAcls, existingSet);\n logAclSyncPlan(cluster, toAdd, toDelete);\n if (toAdd.isEmpty() && toDelete.isEmpty()) {\n return Mono.empty();\n }\n log.info(\"Starting new ACLs creation\");\n return ac.createAcls(toAdd)\n .doOnSuccess(v -> {\n log.info(\"{} new ACLs created\", toAdd.size());\n log.info(\"Starting ACLs deletion\");\n })\n .then(ac.deleteAcls(toDelete)\n .doOnSuccess(v -> log.info(\"{} ACLs deleted\", toDelete.size())));\n }));\n }\n```\n###test function signature:\n```java\n @Test\n void testSyncAclWithAclCsv()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testSyncAclWithAclCsv", "reference": " @Test\n void testSyncAclWithAclCsv() {\n var existingBinding1 = new AclBinding(\n new ResourcePattern(ResourceType.TOPIC, \"*\", PatternType.LITERAL),\n new AccessControlEntry(\"User:test1\", \"*\", AclOperation.READ, AclPermissionType.ALLOW));\n\n var existingBinding2 = new AclBinding(\n new ResourcePattern(ResourceType.GROUP, \"group1\", PatternType.PREFIXED),\n new AccessControlEntry(\"User:test2\", \"localhost\", AclOperation.DESCRIBE, AclPermissionType.DENY));\n\n var newBindingToBeAdded = new AclBinding(\n new ResourcePattern(ResourceType.GROUP, \"groupNew\", PatternType.PREFIXED),\n new AccessControlEntry(\"User:test3\", \"localhost\", AclOperation.DESCRIBE, AclPermissionType.DENY));\n\n when(adminClientMock.listAcls(ResourcePatternFilter.ANY))\n .thenReturn(Mono.just(List.of(existingBinding1, existingBinding2)));\n\n ArgumentCaptor> createdCaptor = ArgumentCaptor.forClass(Collection.class);\n when(adminClientMock.createAcls(createdCaptor.capture()))\n .thenReturn(Mono.empty());\n\n ArgumentCaptor> deletedCaptor = ArgumentCaptor.forClass(Collection.class);\n when(adminClientMock.deleteAcls(deletedCaptor.capture()))\n .thenReturn(Mono.empty());\n\n aclsService.syncAclWithAclCsv(\n CLUSTER,\n \"Principal,ResourceType, PatternType, ResourceName,Operation,PermissionType,Host\\n\"\n + \"User:test1,TOPIC,LITERAL,*,READ,ALLOW,*\\n\"\n + \"User:test3,GROUP,PREFIXED,groupNew,DESCRIBE,DENY,localhost\"\n ).block();\n\n Collection createdBindings = createdCaptor.getValue();\n assertThat(createdBindings)\n .hasSize(1)\n .contains(newBindingToBeAdded);\n\n Collection deletedBindings = deletedCaptor.getValue();\n assertThat(deletedBindings)\n .hasSize(1)\n .contains(existingBinding2);\n }", "completions": [ "```java\n @Test\n void testSyncAclWithAclCsv() {\n // Given\n KafkaCluster cluster = new KafkaCluster(\"testCluster\", \"localhost:9092\");\n String csv = \"principal,host,operation,permissionType\\nUser:Alice,*,Read,Allow\\nUser:Bob,*,Write,Allow\";\n AdminClient adminClient = Mockito.mock(AdminClient.class);\n when(adminClientService.get(cluster)).thenReturn(Mono.just(adminClient));\n when(adminClient.listAcls(ResourcePatternFilter.ANY)).thenReturn(Flux.just(\n new AclBinding(new ResourcePattern(ResourceType.TOPIC, \"testTopic\", PatternType.LITERAL),\n new AccessControlEntry(\"User:Alice\", \"*\", AclOperation.READ, AclPermissionType.ALLOW)),\n new AclBinding(new ResourcePattern(ResourceType.TOPIC, \"testTopic\", PatternType.LITERAL),\n new AccessControlEntry(\"User:Bob\", \"*\", AclOperation.WRITE, AclPermissionType.ALLOW))\n ).collectList());\n\n // When\n Mono result = service.syncAclWithAclCsv(cluster, csv);\n\n // Then\n StepVerifier.create(result)\n .verifyComplete();\n\n verify(adminClient).createAcls(any());\n verify(adminClient).deleteAcls(any());\n }\n```\n" ], "line": 32, "token": 259, "line_diff": 0, "token_diff": 0 }, { "id": 93, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public ProcessInstanceForListViewEntity getProcessInstanceListViewByKey(Long processInstanceKey) {\n try {\n final QueryBuilder query =\n joinWithAnd(\n idsQuery().addIds(String.valueOf(processInstanceKey)),\n termQuery(ListViewTemplate.PROCESS_INSTANCE_KEY, processInstanceKey));\n\n final SearchRequest request =\n ElasticsearchUtil.createSearchRequest(listViewTemplate, ALL)\n .source(new SearchSourceBuilder().query(constantScoreQuery(query)));\n\n final SearchResponse response;\n\n response = tenantAwareClient.search(request);\n final SearchHits searchHits = response.getHits();\n if (searchHits.getTotalHits().value == 1 && searchHits.getHits().length == 1) {\n return ElasticsearchUtil.fromSearchHit(\n searchHits.getAt(0).getSourceAsString(),\n objectMapper,\n ProcessInstanceForListViewEntity.class);\n } else if (response.getHits().getTotalHits().value > 1) {\n throw new NotFoundException(\n String.format(\n \"Could not find unique process instance with id '%s'.\", processInstanceKey));\n } else {\n throw new NotFoundException(\n (String.format(\"Could not find process instance with id '%s'.\", processInstanceKey)));\n }\n } catch (IOException e) {\n throw new OperateRuntimeException(e);\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testGetProcessInstanceListViewByKeyNoResults() throws IOException\n```\n### Answer: (use the provided format with backticks)\n", "name": "testGetProcessInstanceListViewByKeyNoResults", "reference": " @Test\n public void testGetProcessInstanceListViewByKeyNoResults() throws IOException {\n when(listViewTemplate.getAlias()).thenReturn(\"listViewIndexAlias\");\n\n final SearchResponse mockResponse = Mockito.mock(SearchResponse.class);\n final SearchHits mockHits = Mockito.mock(SearchHits.class);\n // Normally TotalHits would just be mocked, but Mockito can't stub or mock direct field accesses\n final TotalHits.Relation mockRelation = Mockito.mock(TotalHits.Relation.class);\n final TotalHits mockTotalHits = new TotalHits(0L, mockRelation);\n\n when(mockResponse.getHits()).thenReturn(mockHits);\n when(mockHits.getTotalHits()).thenReturn(mockTotalHits);\n when(tenantAwareClient.search(any())).thenReturn(mockResponse);\n\n assertThrows(NotFoundException.class, () -> underTest.getProcessInstanceListViewByKey(123L));\n }", "completions": [ "```java\n @Test\n public void testGetProcessInstanceListViewByKeyNoResults() throws IOException {\n // Given\n final Long processInstanceKey = 1L;\n final SearchResponse mockResponse = mock(SearchResponse.class);\n final SearchHits mockHits = mock(SearchHits.class);\n when(mockResponse.getHits()).thenReturn(mockHits);\n when(mockHits.getTotalHits()).thenReturn(new TotalHits(0L, TotalHits.Relation.EQUAL_TO));\n when(mockHits.getHits()).thenReturn(new SearchHit[0]);\n when(tenantAwareClient.search(any(SearchRequest.class))).thenReturn(mockResponse);\n\n // When\n try {\n processInstanceService.getProcessInstanceListViewByKey(processInstanceKey);\n fail(\"Expected NotFoundException\");\n } catch (NotFoundException e) {\n // Then\n assertEquals(\n \"Could not find process instance with id '1'.\", e.getMessage());\n }\n }\n```\n" ], "line": 41, "token": 286, "line_diff": 1, "token_diff": 1 }, { "id": 94, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public long determineStartingOffset(\n long currentEndOffsetForPartition,\n long currentBeginningOffsetForPartition,\n AstraConfigs.IndexerConfig indexerConfig) {\n // Filter stale snapshots for partition.\n if (partitionId == null) {\n LOG.warn(\"PartitionId can't be null.\");\n }\n\n List snapshots = snapshotMetadataStore.listSync();\n List snapshotsForPartition =\n snapshots.stream()\n .filter(\n snapshotMetadata -> {\n if (snapshotMetadata == null || snapshotMetadata.partitionId == null) {\n LOG.warn(\n \"snapshot metadata or partition id can't be null: {} \",\n Strings.join(snapshots, ','));\n }\n return snapshotMetadata != null\n && snapshotMetadata.partitionId != null\n && snapshotMetadata.partitionId.equals(partitionId);\n })\n .collect(Collectors.toUnmodifiableList());\n List deletedSnapshots = deleteStaleLiveSnapshots(snapshotsForPartition);\n\n List nonLiveSnapshotsForPartition =\n snapshotsForPartition.stream()\n .filter(s -> !deletedSnapshots.contains(s))\n .collect(Collectors.toUnmodifiableList());\n\n // Get the highest offset that is indexed in durable store.\n List recoveryTasks = recoveryTaskMetadataStore.listSync();\n long highestDurableOffsetForPartition =\n getHighestDurableOffsetForPartition(\n nonLiveSnapshotsForPartition, recoveryTasks, partitionId);\n LOG.debug(\n \"The highest durable offset for partition {} is {}\",\n partitionId,\n highestDurableOffsetForPartition);\n\n if (highestDurableOffsetForPartition <= 0) {\n LOG.info(\"There is no prior offset for this partition {}.\", partitionId);\n\n // If the user wants to start at the current offset in Kafka and _does not_ want to create\n // recovery tasks to backfill, then we can just return the current offset.\n // If the user wants to start at the current offset in Kafka and _does_ want to create\n // recovery tasks to backfill, then we create the recovery tasks needed and then return\n // the current offset for the indexer. And if the user does _not_ want to start at the\n // current offset in Kafka, then we'll just default to the old behavior of starting from\n // the very beginning\n if (!indexerConfig.getCreateRecoveryTasksOnStart()\n && indexerConfig.getReadFromLocationOnStart()\n == AstraConfigs.KafkaOffsetLocation.LATEST) {\n LOG.info(\n \"CreateRecoveryTasksOnStart is set to false and ReadLocationOnStart is set to current. Reading from current and\"\n + \" NOT spinning up recovery tasks\");\n return currentEndOffsetForPartition;\n } else if (indexerConfig.getCreateRecoveryTasksOnStart()\n && indexerConfig.getReadFromLocationOnStart()\n == AstraConfigs.KafkaOffsetLocation.LATEST) {\n // Todo - this appears to be able to create recovery tasks that have a start and end\n // position of 0, which is invalid. This seems to occur when new clusters are initialized,\n // and is especially problematic when indexers are created but never get assigned (ie,\n // deploy 5, only assign 3).\n LOG.info(\n \"CreateRecoveryTasksOnStart is set and ReadLocationOnStart is set to current. Reading from current and\"\n + \" spinning up recovery tasks\");\n createRecoveryTasks(\n partitionId,\n currentBeginningOffsetForPartition,\n currentEndOffsetForPartition,\n indexerConfig.getMaxMessagesPerChunk());\n return currentEndOffsetForPartition;\n\n } else {\n return highestDurableOffsetForPartition;\n }\n }\n\n // The current head offset shouldn't be lower than the highest durable offset. If it is it\n // means that we indexed more data than the current head offset. This is either a bug in the\n // offset handling mechanism or the kafka partition has rolled over. We throw an exception\n // for now, so we can investigate.\n if (currentEndOffsetForPartition < highestDurableOffsetForPartition) {\n final String message =\n String.format(\n \"The current head for the partition %d can't \"\n + \"be lower than the highest durable offset for that partition %d\",\n currentEndOffsetForPartition, highestDurableOffsetForPartition);\n LOG.error(message);\n throw new IllegalStateException(message);\n }\n\n // The head offset for Kafka partition is the offset of the next message to be indexed. We\n // assume that offset is passed into this function. The highest durable offset is the partition\n // offset of the message that is indexed. Hence, the offset is incremented by 1 to get the\n // next message.\n long nextOffsetForPartition = highestDurableOffsetForPartition + 1;\n\n // Create a recovery task if needed.\n if (currentEndOffsetForPartition - highestDurableOffsetForPartition > maxOffsetDelay) {\n LOG.info(\n \"Recovery task needed. The current position {} and head location {} are higher than max\"\n + \" offset {}\",\n highestDurableOffsetForPartition,\n currentEndOffsetForPartition,\n maxOffsetDelay);\n createRecoveryTasks(\n partitionId,\n nextOffsetForPartition,\n currentEndOffsetForPartition - 1,\n maxMessagesPerRecoveryTask);\n return currentEndOffsetForPartition;\n } else {\n LOG.info(\n \"The difference between the last indexed position {} and head location {} is lower \"\n + \"than max offset {}. So, using {} position as the start offset\",\n highestDurableOffsetForPartition,\n currentEndOffsetForPartition,\n maxOffsetDelay,\n nextOffsetForPartition);\n return nextOffsetForPartition;\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testDetermineStartingOffsetOnlyMultipleRecoveryBehind()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testDetermineStartingOffsetOnlyMultipleRecoveryBehind", "reference": " @Test\n public void testDetermineStartingOffsetOnlyMultipleRecoveryBehind() {\n RecoveryTaskCreator recoveryTaskCreator =\n new RecoveryTaskCreator(\n snapshotMetadataStore,\n recoveryTaskStore,\n partitionId,\n 100,\n TEST_MAX_MESSAGES_PER_RECOVERY_TASK,\n meterRegistry);\n\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore)).isEmpty();\n assertThat(AstraMetadataTestUtils.listSyncUncached(recoveryTaskStore)).isEmpty();\n\n // When there is no data return -1.\n assertThat(recoveryTaskCreator.determineStartingOffset(1000, 0, indexerConfig)).isNegative();\n final String recoveryTaskName = \"BasicRecoveryTask\";\n final long recoveryStartOffset = 400;\n final long createdTimeUtc = Instant.now().toEpochMilli();\n\n final RecoveryTaskMetadata recoveryTask1 =\n new RecoveryTaskMetadata(\n recoveryTaskName + \"1\",\n partitionId,\n recoveryStartOffset,\n recoveryStartOffset * 2,\n createdTimeUtc);\n recoveryTaskStore.createSync(recoveryTask1);\n final RecoveryTaskMetadata recoveryTask11 =\n new RecoveryTaskMetadata(\n recoveryTaskName + \"11\",\n partitionId,\n recoveryStartOffset * 2 + 1,\n recoveryStartOffset * 3,\n createdTimeUtc);\n recoveryTaskStore.createSync(recoveryTask11);\n await()\n .until(\n () -> recoveryTaskStore.listSync().containsAll(List.of(recoveryTask1, recoveryTask11)));\n\n final long currentHeadOffset = 4000;\n assertThat(recoveryTaskCreator.determineStartingOffset(currentHeadOffset, 0, indexerConfig))\n .isEqualTo(currentHeadOffset);\n List recoveryTasks =\n AstraMetadataTestUtils.listSyncUncached(recoveryTaskStore);\n assertThat(recoveryTasks.size()).isEqualTo(3);\n assertThat(recoveryTasks).contains(recoveryTask1, recoveryTask11);\n Optional newRecoveryTask =\n recoveryTasks.stream().filter(r -> !r.name.contains(recoveryTaskName)).findFirst();\n assertThat(newRecoveryTask).isNotEmpty();\n RecoveryTaskMetadata recoveryTask = newRecoveryTask.get();\n assertThat(recoveryTask.startOffset).isEqualTo(recoveryStartOffset * 3 + 1);\n assertThat(recoveryTask.endOffset).isEqualTo(currentHeadOffset - 1);\n assertThat(AstraMetadataTestUtils.listSyncUncached(snapshotMetadataStore)).isEmpty();\n }", "completions": [ "```java\n @Test\n public void testDetermineStartingOffsetOnlyMultipleRecoveryBehind() {\n // Given\n String partitionId = \"testPartition\";\n long currentEndOffsetForPartition = 100L;\n long currentBeginningOffsetForPartition = 0L;\n AstraConfigs.IndexerConfig indexerConfig = new AstraConfigs.IndexerConfig();\n indexerConfig.setCreateRecoveryTasksOnStart(true);\n indexerConfig.setReadFromLocationOnStart(AstraConfigs.KafkaOffsetLocation.LATEST);\n indexerConfig.setMaxMessagesPerChunk(100);\n\n // When\n long startingOffset = determineStartingOffset(\n currentEndOffsetForPartition, currentBeginningOffsetForPartition, indexerConfig);\n\n // Then\n assertEquals(101L, startingOffset);\n }\n```\n" ], "line": 127, "token": 935, "line_diff": 2, "token_diff": 2 }, { "id": 95, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n private String saveAndChecksumBlockList(String jobName, LazyBlockList blockList) {\n BlobId blobId = getBlobId(jobName, getBlockListFileName(blockList.getName()));\n try (BufferedOutputStream gcsWriter =\n new BufferedOutputStream(gcsUtils.openOutputStream(blobId))) {\n MessageDigest messageDigest = MessageDigest.getInstance(checksumAlgorithm);\n blockList.consumeAll(\n (byteArray, length) -> {\n try {\n gcsWriter.write(byteArray, 0, length);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n messageDigest.update(byteArray, 0, length);\n });\n return base16().lowerCase().encode(messageDigest.digest());\n } catch (IOException | NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n }\n }\n```\n###test function signature:\n```java\n @Test\n void saveAndChecksumBlockList_success() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "saveAndChecksumBlockList_success", "reference": " @Test\n void saveAndChecksumBlockList_success() throws Exception {\n String payload = \"somedata\\n\";\n String payloadChecksum = \"0737c8e591c68b93feccde50829aca86a80137547d8cfbe96bab6b20f8580c63\";\n\n when(connection.getInputStream())\n .thenReturn(new ByteArrayInputStream((\"bsa-checksum\\n\" + payload).getBytes(UTF_8)));\n lazyBlockList = new LazyBlockList(BlockListType.BLOCK, connection);\n\n ImmutableMap checksums =\n gcsClient.saveAndChecksumBlockList(\"some-name\", ImmutableList.of(lazyBlockList));\n assertThat(gcsUtils.existsAndNotEmpty(BlobId.of(\"my-bucket\", \"some-name/BLOCK.csv\"))).isTrue();\n assertThat(checksums).containsExactly(BlockListType.BLOCK, payloadChecksum);\n assertThat(gcsClient.readBlockList(\"some-name\", BlockListType.BLOCK))\n .containsExactly(\"somedata\");\n }", "completions": [ "```java\n @Test\n void saveAndChecksumBlockList_success() throws Exception {\n // Given\n String jobName = \"testJob\";\n LazyBlockList blockList = mock(LazyBlockList.class);\n BlobId blobId = mock(BlobId.class);\n BufferedOutputStream gcsWriter = mock(BufferedOutputStream.class);\n MessageDigest messageDigest = mock(MessageDigest.class);\n when(gcsUtils.openOutputStream(blobId)).thenReturn(gcsWriter);\n when(checksumAlgorithm).thenReturn(\"SHA-256\");\n when(messageDigest.digest()).thenReturn(new byte[] {1, 2, 3, 4, 5});\n when(base16().lowerCase().encode(messageDigest.digest())).thenReturn(\"0102030405\");\n\n // When\n String checksum = saveAndChecksumBlockList(jobName, blockList);\n\n // Then\n assertEquals(\"0102030405\", checksum);\n verify(gcsWriter).write(any(), anyInt(), anyInt());\n verify(messageDigest).update(any(), anyInt(), anyInt());\n }\n```\n" ], "line": 30, "token": 211, "line_diff": 0, "token_diff": 0 }, { "id": 96, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public ListenableFuture> findMissingBlobs(\n Iterable blobDigests, RequestMetadata requestMetadata) {\n // Some requests have been blocked, and we should tell the client we refuse to perform a lookup.\n try {\n if (inDenyList(requestMetadata)) {\n return immediateFailedFuture(\n Status.UNAVAILABLE\n .withDescription(\"The action associated with this request is forbidden\")\n .asException());\n }\n } catch (IOException e) {\n return immediateFailedFuture(Status.fromThrowable(e).asException());\n }\n\n // Empty blobs are an exceptional case. Filter them out.\n // If the user only requested empty blobs we can immediately tell them we already have it.\n Iterable nonEmptyDigests =\n Iterables.filter(blobDigests, (digest) -> digest.getSizeBytes() != 0);\n if (Iterables.isEmpty(nonEmptyDigests)) {\n return immediateFuture(ImmutableList.of());\n }\n\n if (configs.getServer().isFindMissingBlobsViaBackplane()) {\n return findMissingBlobsViaBackplane(nonEmptyDigests, requestMetadata);\n }\n\n return findMissingBlobsQueryingEachWorker(nonEmptyDigests, requestMetadata);\n }\n```\n###test function signature:\n```java\n @Test\n public void findMissingBlobsTest_ViaBackPlane() throws Exception\n```\n### Answer: (use the provided format with backticks)\n", "name": "findMissingBlobsTest_ViaBackPlane", "reference": " @Test\n public void findMissingBlobsTest_ViaBackPlane() throws Exception {\n Set activeWorkers = ImmutableSet.of(\"worker1\", \"worker2\", \"worker3\");\n Set expiredWorkers = ImmutableSet.of(\"workerX\", \"workerY\", \"workerZ\");\n Set imposterWorkers = ImmutableSet.of(\"imposter1\", \"imposter2\", \"imposter3\");\n\n Set availableDigests =\n ImmutableSet.of(\n Digest.newBuilder().setHash(\"toBeFound1\").setSizeBytes(1).build(),\n Digest.newBuilder().setHash(\"toBeFound2\").setSizeBytes(1).build(),\n Digest.newBuilder().setHash(\"toBeFound3\").setSizeBytes(1).build(),\n // a copy is added in final digest list\n Digest.newBuilder().setHash(\"toBeFoundDuplicate\").setSizeBytes(1).build());\n\n Set missingDigests =\n ImmutableSet.of(\n Digest.newBuilder().setHash(\"missing1\").setSizeBytes(1).build(),\n Digest.newBuilder().setHash(\"missing2\").setSizeBytes(1).build(),\n Digest.newBuilder().setHash(\"missing3\").setSizeBytes(1).build(),\n // a copy is added in final digest list\n Digest.newBuilder().setHash(\"missingDuplicate\").setSizeBytes(1).build());\n\n Set digestAvailableOnImposters =\n ImmutableSet.of(\n Digest.newBuilder().setHash(\"toBeFoundOnImposter1\").setSizeBytes(1).build(),\n Digest.newBuilder().setHash(\"toBeFoundOnImposter2\").setSizeBytes(1).build(),\n Digest.newBuilder().setHash(\"toBeFoundOnImposter3\").setSizeBytes(1).build());\n\n Set emptyDigests =\n new HashSet<>(\n Arrays.asList(\n Digest.newBuilder().setHash(\"empty1\").build(),\n Digest.newBuilder().setHash(\"empty2\").build()));\n\n Iterable allDigests =\n Iterables.concat(\n availableDigests,\n missingDigests,\n emptyDigests,\n digestAvailableOnImposters,\n Arrays.asList(\n Digest.newBuilder().setHash(\"toBeFoundDuplicate\").setSizeBytes(1).build(),\n Digest.newBuilder().setHash(\"missingDuplicate\").setSizeBytes(1).build()));\n\n Map> digestAndWorkersMap = new HashMap<>();\n\n for (Digest digest : availableDigests) {\n digestAndWorkersMap.put(digest, getRandomSubset(activeWorkers));\n }\n for (Digest digest : missingDigests) {\n digestAndWorkersMap.put(digest, getRandomSubset(expiredWorkers));\n }\n for (Digest digest : digestAvailableOnImposters) {\n digestAndWorkersMap.put(digest, getRandomSubset(imposterWorkers));\n }\n\n BuildfarmConfigs buildfarmConfigs = instance.getBuildFarmConfigs();\n buildfarmConfigs.getServer().setFindMissingBlobsViaBackplane(true);\n Set activeAndImposterWorkers =\n Sets.newHashSet(Iterables.concat(activeWorkers, imposterWorkers));\n\n when(mockBackplane.getStorageWorkers()).thenReturn(activeAndImposterWorkers);\n when(mockBackplane.getBlobDigestsWorkers(any(Iterable.class))).thenReturn(digestAndWorkersMap);\n when(mockInstanceLoader.load(anyString())).thenReturn(mockWorkerInstance);\n when(mockWorkerInstance.findMissingBlobs(anyIterable(), any(RequestMetadata.class)))\n .thenReturn(Futures.immediateFuture(new ArrayList<>()));\n\n long serverStartTime = 1686951033L; // june 15th, 2023\n Map workersStartTime = new HashMap<>();\n for (String worker : activeAndImposterWorkers) {\n workersStartTime.put(worker, serverStartTime);\n }\n when(mockBackplane.getWorkersStartTimeInEpochSecs(activeAndImposterWorkers))\n .thenReturn(workersStartTime);\n long oneDay = 86400L;\n for (Digest digest : availableDigests) {\n when(mockBackplane.getDigestInsertTime(digest)).thenReturn(serverStartTime + oneDay);\n }\n for (Digest digest : digestAvailableOnImposters) {\n when(mockBackplane.getDigestInsertTime(digest)).thenReturn(serverStartTime - oneDay);\n }\n\n Iterable actualMissingDigests =\n instance.findMissingBlobs(allDigests, RequestMetadata.getDefaultInstance()).get();\n Iterable expectedMissingDigests =\n Iterables.concat(missingDigests, digestAvailableOnImposters);\n\n assertThat(actualMissingDigests).containsExactlyElementsIn(expectedMissingDigests);\n verify(mockWorkerInstance, atMost(3))\n .findMissingBlobs(anyIterable(), any(RequestMetadata.class));\n verify(mockWorkerInstance, atLeast(1))\n .findMissingBlobs(anyIterable(), any(RequestMetadata.class));\n\n for (Digest digest : actualMissingDigests) {\n assertThat(digest).isNotIn(availableDigests);\n assertThat(digest).isNotIn(emptyDigests);\n assertThat(digest).isIn(expectedMissingDigests);\n }\n\n // reset BuildfarmConfigs\n buildfarmConfigs.getServer().setFindMissingBlobsViaBackplane(false);\n }", "completions": [ "```java\n @Test\n public void findMissingBlobsTest_ViaBackPlane() throws Exception {\n // Given\n Iterable blobDigests = Arrays.asList(\n Digest.newBuilder().setHash(\"hash1\").setSizeBytes(10).build(),\n Digest.newBuilder().setHash(\"hash2\").setSizeBytes(20).build(),\n Digest.newBuilder().setHash(\"hash3\").setSizeBytes(30).build()\n );\n RequestMetadata requestMetadata = RequestMetadata.newBuilder().setClientId(\"client1\").build();\n\n // When\n ListenableFuture> future =\n underTest.findMissingBlobs(blobDigests, requestMetadata);\n\n // Then\n Iterable missingBlobs = future.get();\n assertThat(missingBlobs).containsExactly(\n Digest.newBuilder().setHash(\"hash1\").setSizeBytes(10).build(),\n Digest.newBuilder().setHash(\"hash2\").setSizeBytes(20).build(),\n Digest.newBuilder().setHash(\"hash3\").setSizeBytes(30).build()\n );\n }\n```\n" ], "line": 37, "token": 276, "line_diff": 1, "token_diff": 0 }, { "id": 97, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n public ComponentXO readComponent(final Repository repository, final EntityId componentId) {\n Component component;\n List assets;\n try (StorageTx storageTx = repository.facet(StorageFacet.class).txSupplier().get()) {\n storageTx.begin();\n component = storageTx.findComponent(componentId);\n if (component == null) {\n throw new WebApplicationException(Status.NOT_FOUND);\n }\n\n Iterable browsedAssets = storageTx.browseAssets(component);\n if (browsedAssets == null || Iterables.isEmpty(browsedAssets)) {\n throw new WebApplicationException(Status.NOT_FOUND);\n }\n\n assets = newArrayList(browsedAssets);\n }\n ensurePermissions(repository, assets, BreadActions.BROWSE);\n return COMPONENT_CONVERTER(component, repository.getName());\n }\n```\n###test function signature:\n```java\n @Test\n public void testReadComponent_notFound()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testReadComponent_notFound", "reference": " @Test\n public void testReadComponent_notFound() {\n Component component = mock(Component.class);\n when(storageTx.findComponent(eq(new DetachedEntityId(\"someid\")))).thenReturn(component);\n when(storageTx.browseAssets(component)).thenReturn(null);\n try {\n underTest.readComponent(\"someid\", \"testRepositoryName\");\n fail(\"Exception should have been thrown\");\n }\n catch (WebApplicationException e) {\n assertThat(e.getResponse(), is(notNullValue()));\n assertThat(e.getResponse().getStatus(), is(404));\n }\n }", "completions": [ "```java\n @Test\n public void testReadComponent_notFound() {\n // Given\n Repository repository = mock(Repository.class);\n EntityId componentId = mock(EntityId.class);\n StorageFacet storageFacet = mock(StorageFacet.class);\n StorageTx storageTx = mock(StorageTx.class);\n when(repository.facet(StorageFacet.class)).thenReturn(storageFacet);\n when(storageFacet.txSupplier()).thenReturn(() -> storageTx);\n when(storageTx.findComponent(componentId)).thenReturn(null);\n\n // When\n try {\n readComponent(repository, componentId);\n fail(\"Expected WebApplicationException\");\n } catch (WebApplicationException e) {\n // Then\n assertEquals(Status.NOT_FOUND.getStatusCode(), e.getResponse().getStatus());\n }\n }\n```\n" ], "line": 29, "token": 205, "line_diff": 0, "token_diff": 0 }, { "id": 98, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @Override\n public CompletableFuture auth(MQTT3AuthData authData) {\n try {\n HttpRequest request = HttpRequest.newBuilder()\n .uri(URI.create(webhookURI + \"/auth\"))\n .header(\"Content-Type\", \"application/json\")\n .POST(HttpRequest.BodyPublishers.ofString(JsonFormat.printer().print(authData)))\n .timeout(Duration.ofSeconds(5))\n .build();\n return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())\n .thenApply(response -> {\n if (response.statusCode() == 200) {\n try {\n MQTT3AuthResult.Builder resultBuilder = MQTT3AuthResult.newBuilder();\n JsonFormat.parser()\n .ignoringUnknownFields()\n .merge(response.body(), resultBuilder);\n return resultBuilder.build();\n } catch (Throwable e) {\n return MQTT3AuthResult.newBuilder()\n .setReject(Reject.newBuilder()\n .setCode(Reject.Code.Error)\n .setReason(e.getMessage())\n .build())\n .build();\n }\n } else {\n return MQTT3AuthResult.newBuilder()\n .setReject(Reject.newBuilder()\n .setCode(Reject.Code.Error)\n .setReason(\"Authenticate failed\")\n .build())\n .build();\n }\n })\n .exceptionally(e -> {\n System.out.println(\"Failed to call webhook: \" + e.getMessage());\n return null;\n });\n } catch (Throwable e) {\n return CompletableFuture.completedFuture(MQTT3AuthResult.newBuilder()\n .setReject(Reject.newBuilder()\n .setCode(Reject.Code.Error)\n .setReason(e.getMessage())\n .build())\n .build());\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testAuth()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testAuth", "reference": " @Test\n public void testAuth() {\n MQTT3AuthData authedUser = MQTT3AuthData.newBuilder()\n .setUsername(\"authUser\")\n .build();\n\n MQTT3AuthData unauthUser = MQTT3AuthData.newBuilder()\n .setUsername(\"unauthUser\")\n .build();\n testServer.addAuthedUser(authedUser.getUsername());\n WebHookBasedAuthProvider provider = new WebHookBasedAuthProvider(testServer.getURI());\n MQTT3AuthResult authResult = provider.auth(authedUser).join();\n assertTrue(authResult.hasOk());\n\n authResult = provider.auth(unauthUser).join();\n assertFalse(authResult.hasOk());\n }", "completions": [ "```java\n @Test\n public void testAuth() {\n // Given\n String webhookURI = \"http://localhost:8080\";\n HttpClient httpClient = HttpClient.newHttpClient();\n MQTT3AuthData authData = MQTT3AuthData.newBuilder()\n .setClientId(\"client1\")\n .setUsername(\"user1\")\n .setPassword(\"password1\")\n .build();\n MQTT3AuthResult expectedResult = MQTT3AuthResult.newBuilder()\n .setSuccess(Success.newBuilder()\n .setIsSuperuser(false)\n .build())\n .build();\n\n // When\n CompletableFuture result = new MQTT3AuthService(webhookURI, httpClient).auth(authData);\n\n // Then\n assertNotNull(result);\n assertEquals(expectedResult, result.join());\n }\n```\n" ], "line": 59, "token": 335, "line_diff": 2, "token_diff": 1 }, { "id": 99, "prompt": "\nYou are an expert Java programmer. You will be given some information and will generate a correct test case for the given function.\nYour response will only be java test function and without anything else.\n\n### focal method:\n```java\n @VisibleForTesting\n void validateRoleDuplicate(String name, String code, Long id) {\n // 0. 超级管理员,不允许创建\n if (RoleCodeEnum.isSuperAdmin(code)) {\n throw exception(ROLE_ADMIN_CODE_ERROR, code);\n }\n // 1. 该 name 名字被其它角色所使用\n RoleDO role = roleMapper.selectByName(name);\n if (role != null && !role.getId().equals(id)) {\n throw exception(ROLE_NAME_DUPLICATE, name);\n }\n // 2. 是否存在相同编码的角色\n if (!StringUtils.hasText(code)) {\n return;\n }\n // 该 code 编码被其它角色所使用\n role = roleMapper.selectByCode(code);\n if (role != null && !role.getId().equals(id)) {\n throw exception(ROLE_CODE_DUPLICATE, code);\n }\n }\n```\n###test function signature:\n```java\n @Test\n public void testValidateRoleDuplicate_success()\n```\n### Answer: (use the provided format with backticks)\n", "name": "testValidateRoleDuplicate_success", "reference": " @Test\n public void testValidateRoleDuplicate_success() {\n // 调用,不会抛异常\n roleService.validateRoleDuplicate(randomString(), randomString(), null);\n }", "completions": [ "```java\n @Test\n public void testValidateRoleDuplicate_success() {\n // Given\n String name = \"TestRole\";\n String code = \"TEST_ROLE\";\n Long id = 1L;\n\n // When\n // Call the method to be tested\n validateRoleDuplicate(name, code, id);\n\n // Then\n // No exception should be thrown\n }\n```\n" ], "line": 32, "token": 213, "line_diff": 0, "token_diff": 0 } ]