focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static List<String> validateJson(JsonNode schemaNode, JsonNode jsonNode) {
try {
return JsonSchemaValidator.validateJson(schemaNode, jsonNode);
} catch (ProcessingException e) {
log.debug("Got a ProcessingException while trying to interpret schemaNode as a real schema");
Li... | @Test
void testValidateJson() {
String schemaText;
String queryText = "{\n" + " hero {\n" + " name\n" + " email\n" + " family\n" + " affiliate\n"
+ " movies {\n" + " title\n" + " }\n" + " }\n" + "}";
String responseText = "{\n" + " \"data\": {\n" + " \"hero\... |
@Override
public List<RedisClientInfo> getClientList(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<List<String>> f = executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST);
List<String> list = syncFuture(f);
return CONVERTER.convert(l... | @Test
public void testGetClientList() {
RedisClusterNode master = getFirstMaster();
List<RedisClientInfo> list = connection.getClientList(master);
assertThat(list.size()).isGreaterThan(10);
} |
@Override
public boolean skip(final ServerWebExchange exchange) {
return false;
} | @Test
public void skipTest() {
Assumptions.assumeFalse(casdoorPluginTest.skip(exchange));
} |
@Override
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @Test
public void smallDifferenceInLongRepresentation() {
expectFailureWhenTestingThat(array(-4.4501477170144023E-308))
.isEqualTo(array(-4.450147717014402E-308));
} |
@Override
public void request(final long n) {
Preconditions.checkArgument(n == 1, "number of requested items must be 1");
if (needsSchema) {
if (schema != null) {
subscriber.onSchema(schema);
}
needsSchema = false;
}
// check status since request() can be reentrant through s... | @Test(expected = IllegalArgumentException.class)
public void testExpectsNEqualsOne() {
final TestSubscriber<String> testSubscriber = new TestSubscriber<String>() {
@Override
public void onSubscribe(final Subscription subscription) {
subscription.request(2);
}
};
final TestPublish... |
public MessageListener messageListener(MessageListener messageListener, boolean addConsumerSpan) {
if (messageListener instanceof TracingMessageListener) return messageListener;
return new TracingMessageListener(messageListener, this, addConsumerSpan);
} | @Test void messageListener_wrapsInput() {
assertThat(jmsTracing.messageListener(mock(MessageListener.class), false))
.isInstanceOf(TracingMessageListener.class);
} |
static int toInteger(final JsonNode object) {
if (object instanceof NumericNode) {
return object.intValue();
}
if (object instanceof TextNode) {
try {
return Integer.parseInt(object.textValue());
} catch (final NumberFormatException e) {
throw failedStringCoercionException(... | @Test
public void shouldConvertLongToIntCorrectly() {
final Integer i = JsonSerdeUtils.toInteger(JsonNodeFactory.instance.numberNode(1L));
assertThat(i, equalTo(1));
} |
@ApiOperation(value = "Unassign Alarm (unassignAlarm)",
notes = "Unassign the Alarm. " +
"Once unassigned, the 'assign_ts' field will be set to current timestamp and special rule chain event 'ALARM_UNASSIGNED' will be generated. " +
"Referencing non-existing Alarm Id ... | @Test
public void testUnassignAlarm() throws Exception {
loginTenantAdmin();
Alarm alarm = createAlarm(TEST_ALARM_TYPE);
Mockito.reset(tbClusterService, auditLogService);
long beforeAssignmentTs = System.currentTimeMillis();
Thread.sleep(2);
doPost("/api/alarm/" + al... |
@Override
public int compareTo(Point point) {
if (this.x > point.x) {
return 1;
} else if (this.x < point.x) {
return -1;
} else if (this.y > point.y) {
return 1;
} else if (this.y < point.y) {
return -1;
}
return 0;
... | @Test
public void compareToTest() {
Point point1 = new Point(1, 2);
Point point2 = new Point(1, 2);
Point point3 = new Point(1, 1);
Point point4 = new Point(2, 2);
Assert.assertEquals(0, point1.compareTo(point2));
TestUtils.notCompareToTest(point1, point3);
... |
public void setMd5sum(String md5sum) {
this.md5sum = md5sum;
} | @Test
public void testSetMd5sum() {
String md5sum = "test";
Dependency instance = new Dependency();
instance.setMd5sum(md5sum);
assertEquals(md5sum, instance.getMd5sum());
} |
public Plan validateReservationUpdateRequest(
ReservationSystem reservationSystem, ReservationUpdateRequest request)
throws YarnException {
ReservationId reservationId = request.getReservationId();
Plan plan = validateReservation(reservationSystem, reservationId,
AuditConstants.UPDATE_RESERV... | @Test
public void testUpdateReservationNegativeRecurrenceExpression() {
ReservationUpdateRequest request =
createSimpleReservationUpdateRequest(1, 1, 1, 5, 3, "-1234");
plan = null;
try {
plan =
rrValidator.validateReservationUpdateRequest(rSystem, request);
Assert.fail();
... |
public EventWithContext addMessageContext(Message message) {
return toBuilder().messageContext(message).build();
} | @Test
public void addMessageContext() {
final Event event = new TestEvent();
final Message message = messageFactory.createMessage("", "", DateTime.now(DateTimeZone.UTC));
final EventWithContext withContext = EventWithContext.builder()
.event(event)
.build();
... |
public static ClassLoader getClassLoader(Class<?> clazz) {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back to system class loader...
}
if ... | @Test
public void testGetClassLoader() {
ClassLoader expectedClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader actualClassLoader = ClassUtil.getClassLoader(ClassUtilTest.class);
Assert.assertEquals(expectedClassLoader, actualClassLoader);
expectedClassLoader ... |
@Override
protected RemotingCommand processRequest0(ChannelHandlerContext ctx, RemotingCommand request,
ProxyContext context) throws Exception {
PullMessageRequestHeader requestHeader = (PullMessageRequestHeader) request.decodeCommandCustomHeader(PullMessageRequestHeader.class);
int sysFlag ... | @Test
public void testPullMessageWithoutSub() throws Exception {
when(messagingProcessorMock.getConsumerGroupInfo(any(), eq(group)))
.thenReturn(consumerGroupInfoMock);
SubscriptionData subscriptionData = new SubscriptionData();
subscriptionData.setSubString(subString);
s... |
public ByteKey interpolateKey(double fraction) {
checkArgument(
fraction >= 0.0 && fraction < 1.0, "Fraction %s must be in the range [0, 1)", fraction);
byte[] startBytes = startKey.getBytes();
byte[] endBytes = endKey.getBytes();
// If the endKey is unspecified, add a leading 1 byte to it and a... | @Test
public void testInterpolateKeyIsNotEmpty() {
String fmt = "Interpolating %s at fraction 0.0 should not return the empty key";
for (ByteKeyRange ignored : TEST_RANGES) {
ByteKeyRange range = ByteKeyRange.ALL_KEYS;
assertFalse(String.format(fmt, range), range.interpolateKey(0.0).isEmpty());
... |
public String toJson(boolean pretty) { return SlimeUtils.toJson(inspector, !pretty); } | @Test
void builds_expected_json() {
var expected =
"""
{
"string": "bar",
"integer": 42,
"floaty": 8.25,
"bool": true,
"array": [
1,
2,
... |
@Override
public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception {
if (args.isEmpty()) {
printHelp(out);
return 0;
}
OutputStream output = out;
if (args.size() > 1) {
output = Util.fileOrStdout(args.get(args.size() - 1), out);
arg... | @Test
void differentMetadataFail() throws Exception {
Map<String, String> metadata1 = new HashMap<>();
metadata1.put("myMetaKey", "myMetaValue");
Map<String, String> metadata2 = new HashMap<>();
metadata2.put("myOtherMetaKey", "myOtherMetaValue");
File input1 = generateData(name.getMethodName() +... |
public double calculateMinPercentageUsedBy(NormalizedResources used, double totalMemoryMb, double usedMemoryMb) {
if (LOG.isTraceEnabled()) {
LOG.trace("Calculating min percentage used by. Used Mem: {} Total Mem: {}"
+ " Used Normalized Resources: {} Total Normalized Resources:... | @Test
public void testCalculateMinWithCpuMemAndGenericResource() {
Map<String, Double> allResourcesMap = new HashMap<>();
allResourcesMap.put(Constants.COMMON_CPU_RESOURCE_NAME, 2.0);
allResourcesMap.put(gpuResourceName, 10.0);
NormalizedResources resources = new NormalizedResources(... |
@Override
public void close() {
try {
if (!closed) {
closed = true;
// Fail all buffered streams.
Http2ChannelClosedException e = new Http2ChannelClosedException();
while (!pendingStreams.isEmpty()) {
PendingStr... | @Test
public void headersAfterCloseShouldImmediatelyFail() {
encoder.writeSettingsAck(ctx, newPromise());
encoder.close();
ChannelFuture f = encoderWriteHeaders(3, newPromise());
assertNotNull(f.cause());
} |
public Map<String, Object> getProducerClientConfigProps() {
final Map<String, Object> map = new HashMap<>();
map.putAll(getConfigsFor(ProducerConfig.configNames()));
// producer client metrics aren't used in Confluent deployment
possiblyConfigureConfluentTelemetry(map);
return Collections.unmodifiab... | @Test
public void shouldFilterProducerConfigs() {
// Given:
final Map<String, Object> configs = new HashMap<>();
configs.put(ProducerConfig.ACKS_CONFIG, "all");
configs.put(ProducerConfig.CLIENT_ID_CONFIG, null);
configs.put("not.a.config", "123");
final KsqlConfig ksqlConfig = new KsqlConfig... |
@Override
protected void doExecute() {
if (vpls == null) {
vpls = get(Vpls.class);
}
if (interfaceService == null) {
interfaceService = get(InterfaceService.class);
}
VplsCommandEnum enumCommand = VplsCommandEnum.enumFromString(command);
if (e... | @Test
public void testIfaceAssociated() {
((TestVpls) vplsCommand.vpls).initSampleData();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
System.setOut(ps);
vplsCommand.command = VplsCommandEnum.ADD_IFACE.toString();
v... |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
final byte[] payload = rawMessage.getPayload();
final JsonNode event;
try {
event = objectMapper.readTree(payload);
if (event == null || event.isMissingNode()) {
throw new ... | @Test
public void decodeMessagesHandlesMetricbeatMessages() throws Exception {
final String[] testFiles = {
"metricbeat-docker-container.json",
"metricbeat-docker-cpu.json",
"metricbeat-docker-diskio.json",
"metricbeat-docker-info.json",
... |
public byte[] getHl7AcknowledgementBytes() {
return hl7AcknowledgementBytes;
} | @Test
public void testGetHl7AcknowledgementBytes() {
instance = new MllpException(EXCEPTION_MESSAGE, LOG_PHI_TRUE);
assertNull(instance.getHl7AcknowledgementBytes());
instance = new MllpException(EXCEPTION_MESSAGE, NULL_BYTE_ARRAY, LOG_PHI_TRUE);
assertNull(instance.getHl7Acknowledg... |
public Document process(Document input) throws IOException, TransformerException {
Document doc = Xml.copyDocument(input);
includeFile(application, doc.getDocumentElement());
return doc;
} | @Test(expected = NoSuchFileException.class)
public void testRequiredIncludeIsDefault() throws ParserConfigurationException, IOException, SAXException, TransformerException {
File app = new File("src/test/resources/multienvapp_failrequired");
DocumentBuilder docBuilder = Xml.getPreprocessDocumentBuil... |
@Override
public void afterComponent(Component component) {
componentsWithUnprocessedIssues.remove(component.getUuid());
Optional<MovedFilesRepository.OriginalFile> originalFile = movedFilesRepository.getOriginalFile(component);
if (originalFile.isPresent()) {
componentsWithUnprocessedIssues.remove(... | @Test
public void remove_processed_files() {
when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.empty());
underTest.afterComponent(component);
verify(movedFilesRepository).getOriginalFile(component);
verify(componentsWithUnprocessedIssues).remove(UUID);
verifyNoM... |
public ConvertedTime getConvertedTime(long duration) {
Set<Seconds> keys = RULES.keySet();
for (Seconds seconds : keys) {
if (duration <= seconds.getSeconds()) {
return RULES.get(seconds).getConvertedTime(duration);
}
}
return new TimeConverter.Ove... | @Test
public void testShouldReportOneMinuteFor30Seconds() {
assertEquals(TimeConverter.ABOUT_1_MINUTE_AGO, timeConverter.getConvertedTime(30));
} |
@Override
protected long doGetContentSize() throws Exception {
return 0;
} | @Test
public void testDoGetContentSizeReturns0() throws Exception {
// For coverage. This method is abstract and must be overridden, however, it's not supposed to be called,
// given getContent is overridden and delegated to the resolved file object.
assertEquals( 0, fileObject.doGetContentSize() );
} |
public Flowable<PendingTransactionNotification> newPendingTransactionsNotifications() {
return web3jService.subscribe(
new Request<>(
"eth_subscribe",
Arrays.asList("newPendingTransactions"),
web3jService,
... | @Test
public void testPendingTransactionsNotifications() {
geth.newPendingTransactionsNotifications();
verify(webSocketClient)
.send(
matches(
"\\{\"jsonrpc\":\"2.0\",\"method\":\"eth_subscribe\",\"params\":"
... |
@Override
public String execute(CommandContext commandContext, String[] args) {
Channel channel = commandContext.getRemote();
if (ArrayUtils.isEmpty(args)) {
return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService";
}
String message = args[0];
... | @Test
void testChangeCancel2() {
String result = change.execute(mockCommandContext, new String[] {"/"});
assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result);
} |
public List<String> toList(boolean trim) {
return toList((str) -> trim ? StrUtil.trim(str) : str);
} | @Test
public void splitLimitTest(){
String text = "55:02:18";
SplitIter splitIter = new SplitIter(text,
new CharFinder(':'),
3,
false
);
final List<String> strings = splitIter.toList(false);
assertEquals(3, strings.size());
} |
public List<InterpreterResultMessage> message() {
return msg;
} | @Test
void testSimpleMagicData() {
InterpreterResult result = null;
result = new InterpreterResult(InterpreterResult.Code.SUCCESS,
"%table col1\tcol2\naaa\t123\n");
assertEquals("col1\tcol2\naaa\t123\n", result.message().get(0).getData(),
"%table col1\tcol2\naaa\t123\n");
result = ne... |
public String indexName(Record<GenericObject> record) {
if (this.dateTimeFormatters.isEmpty()) {
return this.indexNameFormat;
}
Instant eventTime = Instant.ofEpochMilli(record.getEventTime()
.orElseThrow(() -> new IllegalStateException("No event time in record")));
... | @Test(dataProvider = "indexFormats")
public void testIndexFormats(String format, String result) {
Record record = Mockito.mock(Record.class);
when(record.getEventTime()).thenReturn(Optional.of(1645182000000L));
IndexNameFormatter formatter = new IndexNameFormatter(format);
assertEqua... |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testCreateTimeUpConversionV1ToV2() {
long timestamp = System.currentTimeMillis();
Compression compression = Compression.gzip().build();
MemoryRecords records = createRecords(RecordBatch.MAGIC_VALUE_V1, timestamp, compression);
LogValidator validator = new LogValida... |
protected int getDiffSize() {
return brokerConfigDiff.size();
} | @Test
public void testChangedKRaftControllerConfigForCombinedNode() {
NodeRef combinedNodeId = new NodeRef("broker-0", 0, "broker", true, true);
List<ConfigEntry> desiredControllerConfig = singletonList(new ConfigEntry("controller.quorum.election.timeout.ms", "5000"));
List<ConfigEntry> curr... |
public ListedHashTree getClonedTree() {
return newTree;
} | @Test
@SuppressWarnings("ReferenceEquality")
public void testCloning() throws Exception {
ListedHashTree original = new ListedHashTree();
GenericController controller = new GenericController();
controller.setName("controller");
Arguments args = new Arguments();
args.setNa... |
@Override
public Num getValue(int index) {
return values.get(index);
} | @Test
public void cashFlowValue() {
// First sample series
BarSeries sampleBarSeries = new MockBarSeries(numFunction, 3d, 2d, 5d, 1000d, 5000d, 0.0001d, 4d, 7d, 6d, 7d,
8d, 5d, 6d);
TradingRecord tradingRecord = new BaseTradingRecord(Trade.buyAt(0, sampleBarSeries),
... |
@Override
protected boolean copyObject(String src, String dst) {
LOG.debug("Copying {} to {}", src, dst);
GSObject obj = new GSObject(dst);
// Retry copy for a few times, in case some Jets3t or GCS internal errors happened during copy.
int retries = 3;
for (int i = 0; i < retries; i++) {
try... | @Test
public void testCopyObject() throws ServiceException {
// test successful copy object
when(mClient.copyObject(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(),
ArgumentMatchers.anyString(), ArgumentMatchers.any(StorageObject.class),
ArgumentMatchers.anyBoolean())).thenReturn(nu... |
static int getNext(final CronEntry entry, final int current, final Calendar working) throws MessageFormatException {
int result = 0;
if (entry.currentWhen == null) {
entry.currentWhen = calculateValues(entry);
}
List<Integer> list = entry.currentWhen;
int next = -1;... | @Test
public void testGetNext() throws MessageFormatException {
testGetNextSingle("0 0 1 * *", "2016-04-15T00:00:00", "2016-05-01T00:00:00");
testGetNextSingle("0 0 1,15 * *", "2016-04-15T00:00:00", "2016-05-01T00:00:00");
testGetNextSingle("0 0 1 * *", "2016-05-15T00:00:00", "2016-06-01T00:... |
StringBuilder codeForMapWithValueMessageType(Descriptors.FieldDescriptor desc,
String fieldNameInCode,
String valueDescClassName,
int indent,
int varNum) {
StringBuilder code = new StringBuilder();
varNum++;
String mapVarName = "map" + varNum;
StringBuilder code1 = new StringBuil... | @Test
public void testCodeForMapWithValueMessageType() {
MessageCodeGen messageCodeGen = new MessageCodeGen();
// Repeated decoder method is non empty
Descriptors.FieldDescriptor fd = ComplexTypes.TestMessage.getDescriptor().findFieldByName(COMPLEX_MAP);
String fieldNameInCode = Prot... |
public static void cleanDirectory(File directory) throws IOException {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is ... | @Test
public void testCleanDirectory() throws Exception {
for (int i = 0; i < 10; i++) {
IOTinyUtils.writeStringToFile(new File(testRootDir, "testCleanDirectory" + i), "testCleanDirectory", StandardCharsets.UTF_8.name());
}
File dir = new File(testRootDir);
assertTrue(di... |
static SearchProtocol.SearchRequest convertFromQuery(Query query, int hits, String serverId, double requestTimeout) {
var builder = SearchProtocol.SearchRequest.newBuilder().setHits(hits).setOffset(query.getOffset())
.setTimeout((int) (requestTimeout * 1000));
var documentDb = query.get... | @Test
void testQuerySerialization() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/tensortypes").compile();
Query query = new Query.Builder().setQueryProfile(registry.getComponent("profile1"))
.setR... |
public static Instruction writeMetadata(long metadata, long metadataMask) {
return new MetadataInstruction(metadata, metadataMask);
} | @Test
public void testWriteMetadataMethod() {
final Instruction instruction =
Instructions.writeMetadata(metadata1, metadataMask1);
final Instructions.MetadataInstruction metadataInstruction =
checkAndConvert(instruction,
Instruction.Ty... |
@Pointcut("@annotation(org.apache.shenyu.admin.aspect.annotation.DataPermission)")
public void dataPermissionCut() { } | @Test
public void dataPermissionCutTest() {
assertDoesNotThrow(() -> dataPermissionAspect.dataPermissionCut());
} |
public Map<String, Parameter> generateMergedStepParams(
WorkflowSummary workflowSummary,
Step stepDefinition,
StepRuntime stepRuntime,
StepRuntimeSummary runtimeSummary) {
Map<String, ParamDefinition> allParamDefs = new LinkedHashMap<>();
// Start with default step level params if prese... | @Test
public void testStepParamSanity() {
Map<String, Parameter> stepParams =
paramsManager.generateMergedStepParams(workflowSummary, step, stepRuntime, runtimeSummary);
Assert.assertTrue(stepParams.isEmpty());
when(defaultParamManager.getDefaultStepParams())
.thenReturn(
Colle... |
@Override
public List<String> listDbNames() {
return icebergCatalog.listAllDatabases();
} | @Test
public void testListDatabaseNames(@Mocked IcebergCatalog icebergCatalog) {
new Expectations() {
{
icebergCatalog.listAllDatabases();
result = Lists.newArrayList("db1", "db2");
minTimes = 0;
}
};
IcebergMetadata me... |
@Override
public MapperResult findAllConfigKey(MapperContext context) {
String sql = " SELECT data_id,group_id,app_name FROM ( "
+ " SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT " + context.getStartRow() + ","
+ context.getPageSize() + " )" + " g, conf... | @Test
void testFindAllConfigKey() {
MapperResult mapperResult = configInfoMapperByMySql.findAllConfigKey(context);
assertEquals(mapperResult.getSql(),
" SELECT data_id,group_id,app_name FROM ( " + " SELECT id FROM config_info WHERE tenant_id LIKE ? ORDER BY id LIMIT "
... |
public static <T> T getBean(Class<T> interfaceClass, Class typeClass) {
Object object = serviceMap.get(interfaceClass.getName() + "<" + typeClass.getName() + ">");
if(object == null) return null;
if(object instanceof Object[]) {
return (T)Array.get(object, 0);
} else {
... | @Test
public void testTwoGenericTypes() {
Pair p = SingletonServiceFactory.getBean(Pair.class);
Assert.assertEquals("key1", p.getKey());
Assert.assertEquals("value1", p.getValue());
} |
@Override
public Set<NodeDiskUsageStats> diskUsageStats() {
final List<NodeResponse> result = nodes();
return result.stream()
.map(node -> NodeDiskUsageStats.create(node.name(), node.role(), node.ip(), node.host(), node.diskUsed(), node.diskTotal(), node.diskUsedPercent()))
... | @Test
void testDiskUsageStats() {
doReturn(List.of(NODE_WITH_CORRECT_INFO, NODE_WITH_MISSING_DISK_STATISTICS)).when(catApi).nodes();
final Set<NodeDiskUsageStats> diskUsageStats = clusterAdapter.diskUsageStats();
assertThat(diskUsageStats)
.hasSize(1)
.noneSa... |
public static String convertToYamlString(final ShardingTableReferenceRuleConfiguration data) {
return String.format("%s:%s", data.getName(), data.getReference());
} | @Test
void assertConvertToYamlString() {
ShardingTableReferenceRuleConfiguration data = new ShardingTableReferenceRuleConfiguration("foo", "LOGIC_TABLE,SUB_LOGIC_TABLE");
String actual = YamlShardingTableReferenceRuleConfigurationConverter.convertToYamlString(data);
assertThat(actual, is("fo... |
@Override
public void filterConsumer(Exchange exchange, WebServiceMessage response) {
if (exchange != null) {
AttachmentMessage responseMessage = exchange.getMessage(AttachmentMessage.class);
processHeaderAndAttachments(responseMessage, response);
}
} | @Test
public void consumerWithHeader() throws Exception {
exchange.getOut().getHeaders().put("headerAttributeKey", "testAttributeValue");
exchange.getOut().getHeaders().put("headerAttributeElement", new QName("http://shouldBeInHeader", "myElement"));
filter.filterConsumer(exchange, message);... |
public static String generateRandomPassword() {
SecureRandom random = new SecureRandom();
List<Character> pwdChars = new ArrayList<>();
pwdChars.add(LOWER_CASE.charAt(random.nextInt(LOWER_CASE.length())));
pwdChars.add(UPPER_CASE.charAt(random.nextInt(UPPER_CASE.length(... | @Test
void generatePwd() {
String pwd = PasswordGeneratorUtil.generateRandomPassword();
assertEquals(8, pwd.length());
} |
public void dropTable(String dbName, String tableName) {
try (Timer ignored = Tracers.watchScope(EXTERNAL, "HMS.dropTable")) {
callRPC("dropTable", "Failed to drop table " + dbName + "." + tableName,
dbName, tableName, true, false);
}
} | @Test
public void testDropTable(@Mocked HiveMetaStoreClient metaStoreClient) throws TException {
new Expectations() {
{
metaStoreClient.dropTable("hive_db", "hive_table", anyBoolean, anyBoolean);
result = any;
}
};
HiveConf hiveConf = ... |
@Override
public void close() throws IOException {
httpAsyncRequestProducer.close();
} | @Test
public void close() throws IOException {
final HttpAsyncRequestProducer delegate = Mockito.mock(HttpAsyncRequestProducer.class);
final HttpAsyncRequestProducerDecorator decorator = new HttpAsyncRequestProducerDecorator(
delegate, null, null);
decorator.close();
... |
String loadAllKeys() {
return loadAllKeys;
} | @Test
public void testLoadAllKeysIsQuoted() {
Queries queries = new Queries(mapping, idColumn, columnMetadata);
String result = queries.loadAllKeys();
assertEquals("SELECT \"id\" FROM \"mymapping\"", result);
} |
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return typesMatch(type, genericType) && MoreMediaTypes.TEXT_CSV_TYPE.isCompatible(mediaType);
} | @Test
void isWritableForSimpleMessagesAutoValueType() {
boolean isWritable = sut.isWriteable(AutoValue_SimpleMessageChunk.class, SimpleMessageChunk.class, null, MoreMediaTypes.TEXT_CSV_TYPE);
assertThat(isWritable).isTrue();
} |
@Override
public Type getDefaultType() {
return PROJECTS;
} | @Test
public void default_type() {
assertThat(underTest.getDefaultType()).isEqualTo(PROJECTS);
} |
@Override
public KTable<K, V> toTable() {
return toTable(NamedInternal.empty(), Materialized.with(keySerde, valueSerde));
} | @Test
public void shouldNotAllowNullMaterializedOnToTable() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.toTable((Materialized<String, String, KeyValueStore<Bytes, byte[]>>) null));
assertThat(exception.getMessage(), equa... |
static String generateTopicName(String baseString) {
return generateResourceId(
baseString,
ILLEGAL_TOPIC_NAME_CHARS,
REPLACE_TOPIC_NAME_CHAR,
MAX_TOPIC_NAME_LENGTH,
TIME_FORMAT);
} | @Test
public void testGenerateTopicNameShouldReplaceIllegalChars() {
String testBaseString = "^apache_beam/io\\kafka\0";
String actual = KafkaResourceManagerUtils.generateTopicName(testBaseString);
assertThat(actual).matches("-apache_beam-io-kafka--\\d{8}-\\d{6}-\\d{6}");
} |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently avail... | @Test
public void shouldDeserializedJsonNumberAsDouble() {
// Given:
final KsqlJsonDeserializer<Double> deserializer =
givenDeserializerForSchema(Schema.OPTIONAL_FLOAT64_SCHEMA, Double.class);
final List<String> validCoercions = ImmutableList.of(
"42",
"42.000",
"\"42\"",... |
public static String serializeRecordToJsonExpandingValue(ObjectMapper mapper, Record<GenericObject> record,
boolean flatten)
throws JsonProcessingException {
JsonRecord jsonRecord = new JsonRecord();
GenericObject value = record.ge... | @Test(dataProvider = "schemaType")
public void testKeyValueSerializeRecordToJsonExpandingValue(SchemaType schemaType) throws Exception {
RecordSchemaBuilder keySchemaBuilder = org.apache.pulsar.client.api.schema.SchemaBuilder.record("key");
keySchemaBuilder.field("a").type(SchemaType.STRING).optiona... |
public String getServiceAccount() {
return flinkConfig.get(KubernetesConfigOptions.JOB_MANAGER_SERVICE_ACCOUNT);
} | @Test
void testGetServiceAccountFallback() {
flinkConfig.set(KubernetesConfigOptions.KUBERNETES_SERVICE_ACCOUNT, "flink-fallback");
assertThat(kubernetesJobManagerParameters.getServiceAccount()).isEqualTo("flink-fallback");
} |
public static SQLStatementParserEngine getSQLStatementParserEngine(final DatabaseType databaseType,
final CacheOption sqlStatementCacheOption, final CacheOption parseTreeCacheOption) {
SQLStatementParserEngine result = ENGINES.get(databaseTy... | @Test
void assertGetSQLStatementParserEngineNotSame() {
SQLStatementParserEngine before = SQLStatementParserEngineFactory.getSQLStatementParserEngine(databaseType, new CacheOption(2000, 65535L), new CacheOption(64, 1024L));
SQLStatementParserEngine after = SQLStatementParserEngineFactory.getSQLState... |
public static void checkContextPath(String contextPath) {
if (contextPath == null) {
return;
}
Matcher matcher = CONTEXT_PATH_MATCH.matcher(contextPath);
if (matcher.find()) {
throw new IllegalArgumentException("Illegal url path expression");
}
} | @Test
void testContextPathLegal() {
String contextPath1 = "/nacos";
ValidatorUtils.checkContextPath(contextPath1);
String contextPath2 = "nacos";
ValidatorUtils.checkContextPath(contextPath2);
String contextPath3 = "/";
ValidatorUtils.checkContextPath(contextPath3);
... |
public ShardingSphereDatabase getDatabase(final String databaseName) {
return databases.get(databaseName);
} | @Test
void assertGetDatabase() {
ShardingSphereRule globalRule = mock(ShardingSphereRule.class);
ShardingSphereDatabase database = mockDatabase(mock(ResourceMetaData.class, RETURNS_DEEP_STUBS), new MockedDataSource(), globalRule);
Map<String, ShardingSphereDatabase> databases = new HashMap<>... |
public void createOrUpdateItem(final String key, final Object value, final String comment) {
this.createOrUpdateItem(key, GsonUtils.getInstance().toJson(value), comment);
} | @Test
public void testCreateOrUpdateItem() {
doNothing().when(apolloClient)
.createOrUpdateItem(Mockito.any(), Mockito.<Object>any(), Mockito.any());
apolloClient.createOrUpdateItem("Key", (Object) "Value", "Comment");
verify(apolloClient).createOrUpdateItem(Mockito.any(), Mo... |
public static Read read() {
return new AutoValue_TFRecordIO_Read.Builder()
.setValidate(true)
.setCompression(Compression.AUTO)
.build();
} | @Test
public void testReadNamed() {
readPipeline.enableAbandonedNodeEnforcement(false);
assertThat(
readPipeline.apply(TFRecordIO.read().from("foo.*").withoutValidation()).getName(),
startsWith("TFRecordIO.Read/Read"));
assertThat(
readPipeline.apply("MyRead", TFRecordIO.read().fr... |
public static String byteArrayToHexString(byte[] bytes) {
return byteArrayToHexString(bytes, "0x", " ");
} | @Test
public void byteArrayToHexString() {
assertEquals("", FormatUtils.byteArrayToHexString(new byte[0]));
assertEquals("0x01", FormatUtils.byteArrayToHexString(new byte[]{1}));
assertEquals("0x01 0xac", FormatUtils.byteArrayToHexString(new byte[]{1, (byte) 0xac}));
assertEquals("01ac",
Forma... |
public static byte[] baToHexBytes(byte[] ba) {
byte[] hb = new byte[ba.length * 2];
for (int i = 0; i < ba.length; i++) {
byte upper = (byte) ((ba[i] & 0xf0) >> 4);
byte lower = (byte) (ba[i] & 0x0f);
hb[2 * i] = toHexChar(upper);
hb[2 * i + 1] = toHexChar... | @Test
public void testbaToByte() throws Exception {
assertEqualsArray(new byte[]{}, JOrphanUtils.baToHexBytes(new byte[]{}));
assertEqualsArray(new byte[]{'0', '0'}, JOrphanUtils.baToHexBytes(new byte[]{0}));
assertEqualsArray("0f107f8081ff".getBytes(StandardCharsets.UTF_8),
... |
@Override
public void register(long ref, String uuid, boolean file) {
requireNonNull(uuid, "uuid can not be null");
Long existingRef = refsByUuid.get(uuid);
if (existingRef != null) {
checkArgument(ref == existingRef, "Uuid '%s' already registered under ref '%s' in repository", uuid, existingRef);
... | @Test
public void register_throws_IAE_same_uuid_added_with_different_refs() {
underTest.register(SOME_REF, SOME_UUID, true);
assertThatThrownBy(() -> underTest.register(946512, SOME_UUID, true))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Uuid '" + SOME_UUID + "' already registered... |
public static String toJsonStr(JSON json, int indentFactor) {
if (null == json) {
return null;
}
return json.toJSONString(indentFactor);
} | @Test
public void toJsonStrFromSortedTest() {
final SortedMap<Object, Object> sortedMap = new TreeMap<Object, Object>() {
private static final long serialVersionUID = 1L;
{
put("attributes", "a");
put("b", "b");
put("c", "c");
}
};
assertEquals("{\"attributes\":\"a\",\"b\":\"b\",\"c\":\"c\... |
@Override
@Deprecated
public <K1, V1> KStream<K1, V1> flatTransform(final org.apache.kafka.streams.kstream.TransformerSupplier<? super K, ? super V, Iterable<KeyValue<K1, V1>>> transformerSupplier,
final String... stateStoreNames) {
Objects.requireNonNul... | @Test
@SuppressWarnings("deprecation")
public void shouldNotAllowNullNamedOnFlatTransformWithStoreName() {
final NullPointerException exception = assertThrows(
NullPointerException.class,
() -> testStream.flatTransform(flatTransformerSupplier, (Named) null, "storeName"));
... |
@Override
public String render(String text) {
if (StringUtils.isBlank(text)) {
return "";
}
if (regex.isEmpty() || link.isEmpty()) {
Comment comment = new Comment();
comment.escapeAndAdd(text);
return comment.render();
}
try {
... | @Test
public void shouldEscapeTheWholeCommentIfNoneIsMatched() {
trackingTool = new DefaultCommentRenderer("", "");
String toRender = "some <string>";
String result = trackingTool.render(toRender);
assertThat(result, is(StringEscapeUtils.escapeHtml4(toRender)));
} |
@Transactional
public AppNamespace createAppNamespaceInLocal(AppNamespace appNamespace) {
return createAppNamespaceInLocal(appNamespace, true);
} | @Test
@Sql(scripts = "/sql/appnamespaceservice/init-appnamespace.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testCreatePublicAppNamespaceNotExistedWithNoAppendnamespacePrefix() {
AppNamespac... |
@Override
protected String defaultWarehouseLocation(TableIdentifier table) {
return SLASH.join(defaultNamespaceLocation(table.namespace()), table.name());
} | @Test
public void testDefaultWarehouseLocation() throws Exception {
TableIdentifier testTable = TableIdentifier.of("tbl");
TableIdentifier testTable2 = TableIdentifier.of(Namespace.of("ns"), "tbl");
assertThat(warehouseLocation + "/" + testTable.name())
.isEqualTo(catalog.defaultWarehouseLocation(... |
@Override
public Type classify(final Throwable e) {
final Type type = SchemaRegistryUtil.isAuthErrorCode(e) ? Type.USER : Type.UNKNOWN;
if (type == Type.USER) {
LOG.info(
"Classified error as USER error based on missing SR subject access rights. "
+ "Query ID: {} Exception: {}",... | @Test
public void shouldClassifySRAuthorizationErrorCodeAsUserError() {
// Given:
final Exception e = new RestClientException("foo", 403, 40301);
// When:
final QueryError.Type type = new SchemaAuthorizationClassifier("").classify(e);
// Then:
assertThat(type, is(QueryError.Type.USER));
} |
@Override
@SuppressWarnings("unchecked")
public <U> U[] toArray(U[] a) {
if (a == null) {
throw new NullPointerException("Input array can not be null");
}
if (a.length < size) {
a = (U[]) java.lang.reflect.Array.newInstance(a.getClass()
.getComponentType(), size);
}
int cur... | @Test
public void testOther() {
LOG.info("Test other");
assertTrue(set.addAll(list));
// to array
Integer[] array = set.toArray(new Integer[0]);
assertEquals(NUM, array.length);
for (int i = 0; i < array.length; i++) {
assertTrue(list.contains(array[i]));
}
assertEquals(NUM, set.... |
@Override
public List<?> deserialize(final String topic, final byte[] bytes) {
if (bytes == null) {
return null;
}
try {
final String recordCsvString = new String(bytes, StandardCharsets.UTF_8);
final List<CSVRecord> csvRecords = CSVParser.parse(recordCsvString, csvFormat)
.ge... | @Test
public void shouldDeserializedTopLevelPrimitiveTypeIfSchemaHasOnlySingleField() {
// Given:
final PersistenceSchema schema = persistenceSchema(
column("id", SqlTypes.INTEGER)
);
final KsqlDelimitedDeserializer deserializer =
createDeserializer(schema);
final byte[] bytes = ... |
public static String getViewContent(View view) {
return getViewContent(view, false);
} | @Test
public void testGetViewContent() {
TextView textView1 = new TextView(mApplication);
textView1.setText("child1");
Assert.assertEquals("child1", SAViewUtils.getViewContent(textView1));
} |
@Override
public void putTaskConfigs(String connector, List<Map<String, String>> configs) {
Timer timer = time.timer(READ_WRITE_TOTAL_TIMEOUT_MS);
// Make sure we're at the end of the log. We should be the only writer, but we want to make sure we don't have
// any outstanding lagging data to... | @Test
public void testPutTaskConfigs() throws Exception {
configStorage.setupAndCreateKafkaBasedLog(TOPIC, config);
verifyConfigure();
configStorage.start();
verify(configLog).start();
doAnswer(expectReadToEnd(new LinkedHashMap<>()))
.doAnswer(expectReadToEnd... |
public Integer doCall() throws Exception {
File resolvedWorkingDir;
if (workingDir != null) {
resolvedWorkingDir = new File(workingDir);
} else {
String projectName;
if (name != null) {
projectName = KubernetesHelper.sanitize(name);
... | @Test
public void shouldDeleteKubernetesResources() throws Exception {
kubernetesClient.apps().deployments().resource(new DeploymentBuilder()
.withNewMetadata()
.withName("route")
.addToLabels(BaseTrait.INTEGRATION_LABEL, "route")
.endMetadata(... |
static MemberMap createNew(MemberImpl... members) {
return createNew(0, members);
} | @Test
public void createNew() {
MemberImpl[] members = newMembers(5);
MemberMap map = MemberMap.createNew(members);
assertEquals(members.length, map.getMembers().size());
assertEquals(members.length, map.getAddresses().size());
assertEquals(members.length, map.size());
... |
public boolean isGameRunning() {
return status == GameStatus.RUNNING;
} | @Test
void testIsGameRunning() {
assertFalse(gameLoop.isGameRunning());
} |
@Override
@Transactional(rollbackFor = Exception.class)
public Long createJob(JobSaveReqVO createReqVO) throws SchedulerException {
validateCronExpression(createReqVO.getCronExpression());
// 校验唯一性
if (jobMapper.selectByHandlerName(createReqVO.getHandlerName()) != null) {
thr... | @Test
public void testCreateJob_cronExpressionValid() {
// 准备参数。Cron 表达式为 String 类型,默认随机字符串。
JobSaveReqVO reqVO = randomPojo(JobSaveReqVO.class);
// 调用,并断言异常
assertServiceException(() -> jobService.createJob(reqVO), JOB_CRON_EXPRESSION_VALID);
} |
@Bean
public PluginDataHandler wafPluginDataHandler() {
return new WafPluginDataHandler();
} | @Test
public void testWafPluginDataHandler() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(WafPluginConfiguration.class))
.withBean(WafPluginConfigurationTest.class)
.withPropertyValues("debug=true")
.run(context -> {
... |
@Override
public void accept(ModemVisitor modemVisitor) {
if (modemVisitor instanceof HayesVisitor) {
((HayesVisitor) modemVisitor).visit(this);
} else {
LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem");
}
} | @Test
void testAcceptForDos() {
var hayes = new Hayes();
var mockVisitor = mock(ConfigureForDosVisitor.class);
hayes.accept(mockVisitor);
verify((HayesVisitor) mockVisitor).visit(eq(hayes));
} |
public void set(PropertyKey key, Object value) {
set(key, value, Source.RUNTIME);
} | @Test
public void getMalformedBooleanThrowsException() {
mThrown.expect(IllegalArgumentException.class);
mConfiguration.set(PropertyKey.WEB_THREAD_DUMP_TO_LOG, 2);
} |
@VisibleForTesting
WxMaService getWxMaService(Integer userType) {
// 第一步,查询 DB 的配置项,获得对应的 WxMaService 对象
SocialClientDO client = socialClientMapper.selectBySocialTypeAndUserType(
SocialTypeEnum.WECHAT_MINI_APP.getType(), userType);
if (client != null && Objects.equals(client.... | @Test
public void testGetWxMaService_clientNull() {
// 准备参数
Integer userType = randomPojo(UserTypeEnum.class).getValue();
// mock 方法
// 调用
WxMaService result = socialClientService.getWxMaService(userType);
// 断言
assertSame(wxMaService, result);
} |
public void initialize(ServiceConfiguration conf) throws Exception {
for (ProtocolHandler handler : handlers.values()) {
handler.initialize(conf);
}
} | @Test
public void testInitialize() throws Exception {
ServiceConfiguration conf = new ServiceConfiguration();
handlers.initialize(conf);
verify(handler1, times(1)).initialize(same(conf));
verify(handler2, times(1)).initialize(same(conf));
} |
@Override
public void init(InitContext context) {
String state = context.generateCsrfState();
OAuth20Service scribe = newScribeBuilder(context).build(scribeApi);
String url = scribe.getAuthorizationUrl(state);
context.redirectTo(url);
} | @Test
public void init() {
enableBitbucketAuthentication(true);
OAuth2IdentityProvider.InitContext context = mock(OAuth2IdentityProvider.InitContext.class);
when(context.generateCsrfState()).thenReturn("state");
when(context.getCallbackUrl()).thenReturn("http://localhost/callback");
underTest.ini... |
@Override
public void initialize(String inputName, Map<String, String> properties) {
this.catalogProperties = ImmutableMap.copyOf(properties);
this.name = inputName;
if (conf == null) {
LOG.warn("No Hadoop Configuration was set, using the default environment Configuration");
this.conf = new Co... | @Test
public void testInitialize() {
assertThatNoException()
.isThrownBy(
() -> {
HiveCatalog hiveCatalog = new HiveCatalog();
hiveCatalog.initialize("hive", Maps.newHashMap());
});
} |
public TableStats merge(TableStats other, @Nullable Set<String> partitionKeys) {
if (this.rowCount < 0 || other.rowCount < 0) {
return TableStats.UNKNOWN;
}
long rowCount =
this.rowCount >= 0 && other.rowCount >= 0
? this.rowCount + other.rowCo... | @Test
void testMerge() {
Map<String, ColumnStats> colStats1 = new HashMap<>();
colStats1.put("a", new ColumnStats(4L, 5L, 2D, 3, 15, 2));
TableStats stats1 = new TableStats(30, colStats1);
Map<String, ColumnStats> colStats2 = new HashMap<>();
colStats2.put("a", new ColumnSta... |
@Description("Inverse of normal cdf given a mean, std, and probability")
@ScalarFunction
@SqlType(StandardTypes.DOUBLE)
public static double inverseNormalCdf(@SqlType(StandardTypes.DOUBLE) double mean, @SqlType(StandardTypes.DOUBLE) double sd, @SqlType(StandardTypes.DOUBLE) double p)
{
checkCond... | @Test
public void testInverseNormalCdf()
{
assertFunction("inverse_normal_cdf(0, 1, 0.3)", DOUBLE, -0.52440051270804089);
assertFunction("inverse_normal_cdf(10, 9, 0.9)", DOUBLE, 21.533964089901406);
assertFunction("inverse_normal_cdf(0.5, 0.25, 0.65)", DOUBLE, 0.59633011660189195);
... |
public String getClientVersion() {
return clientVersion;
} | @Test
void testGetClientVersion() {
assertEquals("1.0.0", requestMeta.getClientVersion());
} |
@Override
public void doDelete(HttpServletRequest req, HttpServletResponse resp) {
resp.setContentType(CONTENT_TYPE);
try (PrintWriter out = resp.getWriter()) {
out.println(msgPartOne + " Delete " + msgPartTwo);
} catch (Exception e) {
LOGGER.error("Exception occurred DELETE request processing... | @Test
void testDoDelete() throws Exception {
HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
when(mo... |
@Nullable
@Override
public Message decode(@Nonnull RawMessage rawMessage) {
String s = new String(rawMessage.getPayload(), StandardCharsets.UTF_8);
LOG.trace("Received raw message: {}", s);
String timezoneID = configuration.getString(CK_TIMEZONE);
// previously existing PA input... | @Test
public void valuesTest() {
// Test System message results
PaloAltoCodec codec = new PaloAltoCodec(Configuration.EMPTY_CONFIGURATION, messageFactory);
Message message = codec.decode(new RawMessage(PANORAMA_SYSTEM_MESSAGE.getBytes(StandardCharsets.UTF_8)));
assertEquals("SYSTEM"... |
@SuppressWarnings("unchecked")
public final T get() {
if (maxCapacityPerThread == 0) {
return newObject((Handle<T>) NOOP_HANDLE);
}
LocalPool<T> localPool = threadLocal.get();
DefaultHandle<T> handle = localPool.claim();
T obj;
if (handle == null) {
... | @Test
public void verySmallRecycer() {
newRecycler(2, 0, 1).get();
} |
@Override
public boolean load() {
boolean cqLoadResult = loadConsumeQueues(getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()), CQType.SimpleCQ);
boolean bcqLoadResult = loadConsumeQueues(getStorePathBatchConsumeQueue(this.messageStoreConfig.getStorePathRootDir()), CQType.BatchCQ... | @Test
public void testLoadConsumeQueuesWithWrongAttribute() {
String normalTopic = UUID.randomUUID().toString();
ConcurrentMap<String, TopicConfig> topicConfigTable = createTopicConfigTable(normalTopic, CQType.SimpleCQ);
this.topicConfigTableMap.putAll(topicConfigTable);
for (int i ... |
public void setOuterJoinType(OuterJoinType outerJoinType) {
this.outerJoinType = outerJoinType;
} | @Test
void testLeftOuterJoin() throws Exception {
final List<String> leftInput =
Arrays.asList("foo", "foo", "foo", "bar", "bar", "foobar", "foobar");
final List<String> rightInput =
Arrays.asList("foo", "foo", "bar", "bar", "bar", "barfoo", "barfoo");
baseOpe... |
private void unionFailResponse(final ServletResponse response) throws IOException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setContentType("application/json;charset=utf-8");
httpResponse.setCharacterEncoding("utf-8");
wrapCorsResponse(httpResponse)... | @Test
public void testUnionFailResponse() {
PrintWriter printWriter = mock(PrintWriter.class);
try {
when(httpServletResponse.getWriter()).thenReturn(printWriter);
doNothing().when(printWriter).println();
Method testMethod = statelessAuthFilter.getClass().getDecla... |
@Override
public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
int type = columnDef.getColumnMeta() >> 8;
int length = columnDef.getColumnMeta() & 0xff;
// unpack type & length, see https://bugs.mysql.com/bug.php?id=37426.
if (0x30 != (ty... | @Test
void assertReadEnumValueWithMetaFailure() {
columnDef.setColumnMeta((MySQLBinaryColumnType.ENUM.getValue() << 8) + 3);
assertThrows(UnsupportedSQLOperationException.class, () -> new MySQLStringBinlogProtocolValue().read(columnDef, payload));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.