focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
@SuppressWarnings("MethodMayBeStatic") // Non-static to allow DI/mocking public QueryContext.Stacker buildNodeContext(final String context) { return new QueryContext.Stacker() .push(context); }
@Test public void shouldBuildNodeContext() { // When: final Stacker result = runtimeBuildContext.buildNodeContext("some-id"); // Then: assertThat(result, is(new Stacker().push("some-id"))); }
static String capitalizeFirst(String string) { if (string.isEmpty()) { return string; } return string.substring(0, 1).toUpperCase(Locale.ENGLISH) + string.substring(1); }
@Test public void testCapitalizeFirst() { assertEquals("", MessageGenerator.capitalizeFirst("")); assertEquals("AbC", MessageGenerator.capitalizeFirst("abC")); }
@Override public COSBase getCOSObject() { COSArray cos = new COSArray(); cos.add(COSArray.of(array)); cos.add(COSInteger.get(phase)); return cos; }
@Test void testGetCOSObject() { COSArray ar = new COSArray(); ar.add(COSInteger.ONE); ar.add(COSInteger.TWO); PDLineDashPattern dash = new PDLineDashPattern(ar, 3); COSArray dashBase = (COSArray) dash.getCOSObject(); COSArray dashArray = (COSArray) dashBase.getObj...
public @Nullable Struct getPartition(String partitionToken) { Statement statement; if (this.isPostgres()) { statement = Statement.newBuilder( "SELECT * FROM \"" + metadataTableName + "\" WHERE \"" + COLUMN_PARTIT...
@Test public void testInTransactionContextGetPartitionWithPartitions() { ResultSet resultSet = mock(ResultSet.class); when(transaction.executeQuery(any(), anyObject())).thenReturn(resultSet); when(resultSet.next()).thenReturn(true); when(resultSet.getCurrentRowAsStruct()).thenReturn(Struct.newBuilder(...
static Map<String, Object> classFilterGenerator(ClassFilter classFilter) { if (classFilter == null || classFilter.isEmpty()) { return Collections.emptyMap(); } Map<String, Object> classFilterMap = new LinkedHashMap<>(); List<String> packagesAsList = new ArrayList<>(); ...
@Test public void testClassFilterConfig() { ClassFilter filter = createClassFilter(); Map<String, Object> filterAsMap = DynamicConfigYamlGenerator.classFilterGenerator(filter); assertClassFilterAsMap(filterAsMap); }
public static BuildInfo getBuildInfo() { if (Overrides.isEnabled()) { // never use cache when override is enabled -> we need to re-parse everything Overrides overrides = Overrides.fromProperties(); return getBuildInfoInternalVersion(overrides); } return BUILD...
@Test public void testOverrideBuildNumber() { System.setProperty("hazelcast.build", "2"); BuildInfo buildInfo = BuildInfoProvider.getBuildInfo(); String version = buildInfo.getVersion(); String build = buildInfo.getBuild(); int buildNumber = buildInfo.getBuildNumber(); ...
public Set<EntityDescriptor> resolveEntities(Collection<EntityDescriptor> unresolvedEntities) { final MutableGraph<EntityDescriptor> dependencyGraph = GraphBuilder.directed() .allowsSelfLoops(false) .nodeOrder(ElementOrder.insertion()) .build(); unresolved...
@Test public void resolveEntitiesWithEmptyInput() { final Set<EntityDescriptor> resolvedEntities = contentPackService.resolveEntities(Collections.emptySet()); assertThat(resolvedEntities).isEmpty(); }
@Override public List<AwsEndpoint> getClusterEndpoints() { List<AwsEndpoint> result = new ArrayList<>(); Applications applications = applicationsSource.getApplications( transportConfig.getApplicationsResolverDataStalenessThresholdSeconds(), TimeUnit.SECONDS); if (applicatio...
@Test public void testVipDoesNotExist() { vipAddress = "doNotExist"; when(transportConfig.getReadClusterVip()).thenReturn(vipAddress); resolver = new ApplicationsResolver( // recreate the resolver as desired config behaviour has changed clientConfig, transpo...
@HighFrequencyInvocation public EncryptTable getEncryptTable(final String tableName) { return findEncryptTable(tableName).orElseThrow(() -> new EncryptTableNotFoundException(tableName)); }
@Test void assertGetNotExistedEncryptTable() { assertThrows(EncryptTableNotFoundException.class, () -> new EncryptRule("foo_db", createEncryptRuleConfiguration()).getEncryptTable("not_existed_tbl")); }
@Override public <T> ResponseFuture<T> sendRequest(Request<T> request, RequestContext requestContext) { FutureCallback<Response<T>> callback = new FutureCallback<>(); sendRequest(request, requestContext, callback); return new ResponseFutureImpl<>(callback); }
@SuppressWarnings("deprecation") @Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestAndGetResponseOptions") public void testRestLiResponseFuture(SendRequestOption sendRequestOption, GetResponseOption getResponseOption, ...
public static Response build(int errorCode, String msg) { ErrorResponse response = new ErrorResponse(); response.setErrorInfo(errorCode, msg); return response; }
@Test void testBuildWithErrorCode() { int errorCode = 500; String msg = "err msg"; Response response = ErrorResponse.build(errorCode, msg); assertEquals(errorCode, response.getErrorCode()); assertEquals(errorCode, response.getResultCode()); assertEqu...
public Optional<Details> runForeachBatch( Workflow workflow, Long internalId, long workflowVersionId, RunProperties runProperties, String foreachStepId, ForeachArtifact artifact, List<RunRequest> requests, List<Long> instanceIds, int batchSize) { if (ObjectHelpe...
@Test public void testCreateRestartForeachInstancesUpstreamModeFromBeginningWithoutStepParamOverride() { doNothing().when(workflowHelper).updateWorkflowInstance(any(), any()); when(instanceDao.getLatestWorkflowInstanceRun(anyString(), anyLong())) .thenReturn(new WorkflowInstance()); ForeachArtifa...
public boolean isValid(String value) { if (value == null) { return false; } URI uri; // ensure value is a valid URI try { uri = new URI(value); } catch (URISyntaxException e) { return false; } // OK, perfom additional validatio...
@Test public void testValidator342() { UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://example.rocks/")); assertTrue(urlValidator.isValid("http://example.rocks")); }
public static String decimalFormat(String pattern, double value) { Assert.isTrue(isValid(value), "value is NaN or Infinite!"); return new DecimalFormat(pattern).format(value); }
@Test public void decimalFormatNaNTest2() { assertThrows(IllegalArgumentException.class, ()->{ final Double a = 0D; final Double b = 0D; Console.log(NumberUtil.decimalFormat("#%", a / b)); }); }
public static <T> T checkNotNull(T reference, String errorMessageTemplate, Object... errorMessageArgs) { if (reference == null) { // If either of these parameters is null, the right thing happens anyway throw new NullPointerException(...
@Test void checkNotNullInputNullNotNullNullOutputNullPointerException() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> { // Arrange final Object reference = null; final String errorMessageTemplate = ""; final Object[] errorMessageArgs = null; Util.checkNotNu...
@Operation(summary = "OICD-session") @PostMapping(value = "/{id}", consumes = "application/json") @ResponseBody public StatusResponse oicdLoginSession(@PathVariable("id") String oidcSessionId, @Valid @RequestBody LoginRequest request) throws ChangeSetPersister.NotFoundException { Optional<OpenIdSess...
@Test void oicdLoginSessionNotFound() { assertThrows(ChangeSetPersister.NotFoundException.class, () -> controller.oicdLoginSession(SESSION_ID, loginRequest())); verify(service, times(0)).userLogin(session, 1l, "20", "success"); }
public Pet photoUrls(List<String> photoUrls) { this.photoUrls = photoUrls; return this; }
@Test public void photoUrlsTest() { // TODO: test photoUrls }
@Udf public <T> String toJsonString(@UdfParameter final T input) { return toJson(input); }
@Test public void shouldSerializeLong() { // When: final String result = udf.toJsonString(123L); // Then: assertEquals("123", result); }
@Deprecated public static <ElemT, ViewT> PCollectionView<ViewT> getView( AppliedPTransform< PCollection<ElemT>, PCollection<ElemT>, PTransform<PCollection<ElemT>, PCollection<ElemT>>> application) throws IOException { RunnerApi.PTransform transformP...
@Test public void testExtractionDirectFromTransform() throws Exception { SdkComponents components = SdkComponents.create(); components.registerEnvironment(Environments.createDockerEnvironment("java")); components.registerPCollection(testPCollection); AppliedPTransform<?, ?, ?> appliedPTransform = ...
@Override public int deleteAll() { final Set<GrokPattern> grokPatterns = loadAll(); final Set<String> patternNames = grokPatterns.stream() .map(GrokPattern::name) .collect(Collectors.toSet()); final int deletedPatterns = dbCollection.remove(DBQuery.empty()).g...
@Test @MongoDBFixtures("MongoDbGrokPatternServiceTest.json") public void deleteAll() { assertThat(collection.countDocuments()).isEqualTo(3); final int deletedRecords = service.deleteAll(); assertThat(deletedRecords).isEqualTo(3); assertThat(collection.countDocuments()).isEqualTo...
@ScalarOperator(DIVIDE) @SqlType(StandardTypes.INTEGER) public static long divide(@SqlType(StandardTypes.INTEGER) long left, @SqlType(StandardTypes.INTEGER) long right) { try { return left / right; } catch (ArithmeticException e) { throw new PrestoException(DI...
@Test public void testDivide() { assertFunction("INTEGER'37' / INTEGER'37'", INTEGER, 1); assertFunction("INTEGER'37' / INTEGER'17'", INTEGER, 37 / 17); assertFunction("INTEGER'17' / INTEGER'37'", INTEGER, 17 / 37); assertFunction("INTEGER'17' / INTEGER'17'", INTEGER, 1); ...
@Override public List<IndexSpec> getIndexSpecs() { return List.copyOf(this.indexSpecs.values()); }
@Test void getIndexSpecs() { var specs = new DefaultIndexSpecs(); specs.add(primaryKeyIndexSpec(FakeExtension.class)); assertThat(specs.getIndexSpecs()).hasSize(1); }
protected void insertModelAfter(EpoxyModel<?> modelToInsert, EpoxyModel<?> modelToInsertAfter) { int modelIndex = getModelPosition(modelToInsertAfter); if (modelIndex == -1) { throw new IllegalStateException("Model is not added: " + modelToInsertAfter); } int targetIndex = modelIndex + 1; pau...
@Test() public void testInsertModelAfter() { TestModel firstModel = new TestModel(); testAdapter.addModels(firstModel); testAdapter.insertModelAfter(new TestModel(), firstModel); verify(observer).onItemRangeInserted(1, 1); assertEquals(2, testAdapter.models.size()); assertEquals(firstModel, t...
public static boolean isServletRequestAuthenticatorInstanceOf(Class<? extends ServletRequestAuthenticator> clazz) { final AuthCheckFilter instance = getInstance(); if (instance == null) { // We've not yet been instantiated return false; } return servletRequestAuth...
@Test public void willReturnFalseIfTheWrongServletRequestAuthenticatorIsConfigured() { AuthCheckFilter.SERVLET_REQUEST_AUTHENTICATOR.setValue(NormalUserServletAuthenticatorClass.class); new AuthCheckFilter(adminManager, loginLimitManager); assertThat(AuthCheckFilter.isServletRequestAuthent...
@Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringC...
@Test public final void getCacheShouldReturnDifferentInstancesForDifferentNames() { // When final SpringCache firstObtainedSpringCache = objectUnderTest.getCache(TEST_CACHE_NAME); final SpringCache secondObtainedSpringCache = objectUnderTest.getCache(OTHER_TEST_CACHE_NAME); // Then ass...
public static String calculateSha256Hex(@Nonnull byte[] data) throws NoSuchAlgorithmException { return calculateSha256Hex(data, data.length); }
@Test public void testCalculateSha256Hex() throws Exception { byte[] data = {(byte) 0}; String result = Sha256Util.calculateSha256Hex(data); assertEquals("6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d", result); }
@LiteralParameters("x") @ScalarOperator(LESS_THAN) @SqlType(StandardTypes.BOOLEAN) public static boolean lessThan(@SqlType("varchar(x)") Slice left, @SqlType("varchar(x)") Slice right) { return left.compareTo(right) < 0; }
@Test public void testLessThan() { assertFunction("'foo' < 'foo'", BOOLEAN, false); assertFunction("'foo' < 'bar'", BOOLEAN, false); assertFunction("'bar' < 'foo'", BOOLEAN, true); assertFunction("'bar' < 'bar'", BOOLEAN, false); }
public String getEcosystem(DefCveItem cve) { final List<Reference> references = Optional.ofNullable(cve) .map(DefCveItem::getCve) .map(CveItem::getReferences) .orElse(null); if (Objects.nonNull(references)) { for (Reference r : references) { ...
@Test public void testGetEcosystemMustHandleNullCveItem() { // Given UrlEcosystemMapper mapper = new UrlEcosystemMapper(); // When String output = mapper.getEcosystem(null); // Then assertNull(output); }
@Override public void closeDiscountActivity(Long id) { // 校验存在 DiscountActivityDO activity = validateDiscountActivityExists(id); if (activity.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) { // 已关闭的活动,不能关闭噢 throw exception(DISCOUNT_ACTIVITY_CLOSE_FAIL_STATUS_CLOSED); ...
@Test public void testCloseDiscountActivity() { // mock 数据 DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus())); discountActivityMapper.insert(dbDiscountActivity);// @Sql: 先插入出一条存在的数据 ...
public static SlotManagerConfiguration fromConfiguration( Configuration configuration, WorkerResourceSpec defaultWorkerResourceSpec) throws ConfigurationException { final Time rpcTimeout = Time.fromDuration(configuration.get(RpcOptions.ASK_TIMEOUT_DURATION)); fi...
@Test void testComputeMinMaxCpuIsInvalid() { final Configuration configuration = new Configuration(); final double minTotalCpu = 10.0; final double maxTotalCpu = 11.0; final int numSlots = 3; final double cpuCores = 3; configuration.set(ResourceManagerOptions.MIN_TOTA...
public static <T> Stream<T> fromArray(Inspector array, Function<Inspector, T> mapper) { return IntStream.range(0, array.entries()) .mapToObj(array::entry) .map(mapper); }
@Test public void test_some_elements() { var inspector = new Slime().setArray(); inspector.addString("foo"); inspector.addString("bar"); var items = SlimeStream.fromArray(inspector, Inspector::asString).toList(); assertEquals(List.of("foo", "bar"), items); }
@Override public byte[] encode(ILoggingEvent event) { StringBuilder sb = new StringBuilder(); sb.append(OPEN_OBJ); var level = event.getLevel(); if (level != null) { appenderMember(sb, "level", level.levelStr); sb.append(VALUE_SEPARATOR); } appenderMember(sb, "message", StringEsca...
@Test void should_encode_when_no_stacktrace() { var logEvent = mock(ILoggingEvent.class); when(logEvent.getLevel()).thenReturn(Level.DEBUG); when(logEvent.getFormattedMessage()).thenReturn("message"); var bytes = underTest.encode(logEvent); assertThat(new String(bytes, StandardCharsets.UTF_8)).i...
@Override public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback) { //This code path cannot accept content types or accept types that contain //multipart/related. This is because these types of requests will usually have very large payloads and therefor...
@Test public void testRestRequestAttachmentsPresent() throws Exception { //This test verifies that a RestRequest sent to the RestLiServer throws an exception if the content type is multipart/related RestRequest contentTypeMultiPartRelated = new RestRequestBuilder(new URI("/statuses/abcd")) .setHeade...
public static LocalDateTime parse(CharSequence text) { return parse(text, (DateTimeFormatter) null); }
@Test public void parseBlankTest(){ final LocalDateTime parse = LocalDateTimeUtil.parse(""); assertNull(parse); }
RuleChange findChangesAndUpdateRule(RulesDefinition.Rule ruleDef, RuleDto ruleDto) { RuleChange ruleChange = new RuleChange(ruleDto); boolean ruleMerged = mergeRule(ruleDef, ruleDto, ruleChange); boolean debtDefinitionsMerged = mergeDebtDefinitions(ruleDef, ruleDto); boolean tagsMerged = mergeTags(ruleD...
@Test public void findChangesAndUpdateRule_whenImpactsChanged_thenDontIncludeUnchangedImpacts() { RulesDefinition.Rule ruleDef = getDefaultRuleDef(); when(ruleDef.cleanCodeAttribute()).thenReturn(CleanCodeAttribute.CLEAR); Map<SoftwareQuality, Severity> newImpacts = Map.of(SoftwareQuality.MAINTAINABILITY,...
@Override public void moveTo(long position) { if (position < 0 || length() < position) { throw new IllegalArgumentException("Position out of the bounds of the file!"); } fp = position; }
@Test public void moveTo() throws IOException { int readPosition = (int) len - 10; byte[] buff = new byte[1]; cs.moveTo(readPosition); cs.open(); int n = cs.read(buff); assertEquals(text[readPosition], buff[0]); assertEquals(buff.length, n); }
public long timeOfLastReset() { List<Status> statusList = sm.getCopyOfStatusList(); if (statusList == null) return -1; int len = statusList.size(); for (int i = len - 1; i >= 0; i--) { Status s = statusList.get(i); if (CoreConstants.RESET_MSG_PREFIX.equals(s.getMessage())) { r...
@Test public void emptyStatusListShouldResultInNotFound() { assertEquals(-1, statusUtil.timeOfLastReset()); }
public static <T> T retryOnException(Supplier<T> supplier, int maxRetries) { return retryOnException(supplier, maxRetries, 20L); }
@Test void retryOnExceptionForSupplier() { assertThatCode(() -> Exceptions.retryOnException(() -> "my string from supplier", 5)).doesNotThrowAnyException(); assertThatCode(() -> Exceptions.retryOnException(new SupplierThrowingRuntimeException(), 5)).isInstanceOf(StorageException.class); }
public <T> T fromXmlPartial(String partial, Class<T> o) throws Exception { return fromXmlPartial(toInputStream(partial, UTF_8), o); }
@Test void shouldLoadAllowOnlySuccessOnManualApprovalType() throws Exception { Approval approval = xmlLoader.fromXmlPartial("<approval type=\"manual\" allowOnlyOnSuccess=\"true\" />", Approval.class); assertThat(approval.getType()).isEqualTo("manual"); assertThat(approval.isAllowOnlyOnSucce...
public void addHeaders(Map<String, String> headersToAdd) { headers.putAll(headersToAdd); }
@Test public void testAddHeaders() { String headerName1 = "customized_header1"; String headerValue1 = "customized_value1"; String headerName2 = "customized_header2"; String headerValue2 = "customized_value2"; HashMap<String, String> headersToAdd = new HashMap<>(); h...
@Override public void recordPartitionInfo(int partitionIndex, ResultPartitionBytes partitionBytes) { // Once all partitions are finished, we can convert the subpartition bytes to aggregated // value to reduce the space usage, because the distribution of source splits does not // affect the d...
@Test void testGetBytesWithPartialPartitionInfos() { AllToAllBlockingResultInfo resultInfo = new AllToAllBlockingResultInfo(new IntermediateDataSetID(), 2, 2, false); resultInfo.recordPartitionInfo(0, new ResultPartitionBytes(new long[] {32L, 64L})); assertThatThrownBy(resul...
@ConstantFunction(name = "add", argTypes = {SMALLINT, SMALLINT}, returnType = SMALLINT, isMonotonic = true) public static ConstantOperator addSmallInt(ConstantOperator first, ConstantOperator second) { return ConstantOperator.createSmallInt((short) Math.addExact(first.getSmallint(), second.getSmallint())); ...
@Test public void addSmallInt() { assertEquals(20, ScalarOperatorFunctions.addSmallInt(O_SI_10, O_SI_10).getSmallint()); }
@VisibleForTesting AdminUserDO validateUserExists(Long id) { if (id == null) { return null; } AdminUserDO user = userMapper.selectById(id); if (user == null) { throw exception(USER_NOT_EXISTS); } return user; }
@Test public void testValidateUserExists_notExists() { assertServiceException(() -> userService.validateUserExists(randomLongId()), USER_NOT_EXISTS); }
protected PackageModel getPackageModel(PackageDescr packageDescr, PackageRegistry pkgRegistry, String pkgName) { return packageModels.getPackageModel(packageDescr, pkgRegistry, pkgName); }
@Test public void getPackageModelWithPkgUUID() { String pkgUUID = generateUUID(); PackageDescr packageDescr = getPackageDescr(pkgUUID); PackageModel retrieved = modelBuilder.getPackageModel(packageDescr, packageRegistry, internalKnowledgePackage.getName()); assertThat(retrieved).isN...
public boolean shouldKeepReport() { return configuration.getBoolean(KEEP_REPORT_PROP_KEY).orElse(false) || configuration.getBoolean(VERBOSE_KEY).orElse(false); }
@Test public void should_define_keep_report() { settings.setProperty("sonar.scanner.keepReport", "true"); assertThat(underTest.shouldKeepReport()).isTrue(); }
@Override public List<SysMenuVO> menuList(SysMenuListDTO dto) { QueryWrapper wrapper = QueryWrapper.create() .eq(SysMenu::getDelFlag, "F") /* .orderBy(SYS_MENU.DEEP.asc())*/ .orderBy(SysMenuTableDef.SYS_MENU.SORT.asc()); if (!dto.isShowButton()) { ...
@Test void menuList() { SysMenuListDTO dto = new SysMenuListDTO(); List<SysMenuVO> sysMenuVOS = sysMenuService.menuList(dto); System.out.println("sysMenuVOS ==" + JsonUtils.toJsonString(sysMenuVOS)); }
@Deprecated public static boolean isNullOrEmpty(String str) { return str == null || str.isEmpty(); }
@Test public void isNullOrEmpty() { String string = "null"; Assert.assertFalse(StringUtil.isEmpty(string)); }
@Override public Object read(final MySQLPacketPayload payload, final boolean unsigned) throws SQLException { int length = payload.readInt1(); switch (length) { case 0: throw new SQLFeatureNotSupportedException("Can not support date format if year, month, day is absent.");...
@Test void assertReadWithZeroByte() { assertThrows(SQLFeatureNotSupportedException.class, () -> new MySQLDateBinaryProtocolValue().read(payload, false)); }
public static List<?> convertToList(Schema schema, Object value) { return convertToArray(ARRAY_SELECTOR_SCHEMA, value); }
@Test public void shouldFailToConvertToListFromStringWithExtraDelimiters() { assertThrows(DataException.class, () -> Values.convertToList(Schema.STRING_SCHEMA, "[1, 2, 3,,,]")); }
@Override public void add(T item) { final int sizeAtTimeOfAdd; synchronized (items) { items.add(item); sizeAtTimeOfAdd = items.size(); } /* WARNING: It is possible that the item that was just added to the list has been processed by an ...
@Test public void timeTrigger() { TestAccumulator accumulator = new TestAccumulator(); accumulator.add(new TestItem("a")); timer.advanceTimeMillis(30, SHORT_REAL_TIME_DELAY); assertTrue("should not have fired yet", accumulator.batch.isEmpty()); accumulator.add(new TestItem("b...
public Entry<Object, Object> project(JetSqlRow row) { keyTarget.init(); valueTarget.init(); for (int i = 0; i < row.getFieldCount(); i++) { Object value = getToConverter(types[i]).convert(row.get(i)); injectors[i].set(value); } Object key = keyTarget.conc...
@Test public void test_projectValueNullNotAllowed() { KvProjector projector = new KvProjector( new QueryPath[]{QueryPath.KEY_PATH, QueryPath.VALUE_PATH}, new QueryDataType[]{QueryDataType.INT, QueryDataType.INT}, new MultiplyingTarget(), new Nu...
public static BigDecimal cast(final Integer value, final int precision, final int scale) { if (value == null) { return null; } return cast(value.longValue(), precision, scale); }
@Test public void shouldNotCastStringTooNegative() { // When: final Exception e = assertThrows( ArithmeticException.class, () -> cast("-10", 2, 1) ); // Then: assertThat(e.getMessage(), containsString("Numeric field overflow")); }
@Override public boolean match(Message msg, StreamRule rule) { Double msgVal = getDouble(msg.getField(rule.getField())); if (msgVal == null) { return false; } Double ruleVal = getDouble(rule.getValue()); if (ruleVal == null) { return false; } ...
@Test public void testSuccessfullInvertedMatch() { StreamRule rule = getSampleRule(); rule.setValue("10"); rule.setInverted(true); Message msg = getSampleMessage(); msg.addField("something", "4"); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matc...
public static void toJson(PartitionSpec spec, JsonGenerator generator) throws IOException { toJson(spec.toUnbound(), generator); }
@TestTemplate public void testToJsonForV1Table() { String expected = "{\n" + " \"spec-id\" : 0,\n" + " \"fields\" : [ {\n" + " \"name\" : \"data_bucket\",\n" + " \"transform\" : \"bucket[16]\",\n" + " \"source-id\" : 2,\n" ...
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DefaultDisjointPath) { final DefaultDisjointPath other = (DefaultDisjointPath) obj; return (Objects.equals(this.path1, other.path1) && Objects.equals(this.pa...
@Test public void testEquals() { new EqualsTester() .addEqualityGroup(disjointPath1, sameAsDisjointPath1, disjointPath2) .addEqualityGroup(disjointPath3) .addEqualityGroup(disjointPath4) .testEquals(); }
@Override public boolean checkExists(String path) { try { if (client.checkExists().forPath(path) != null) { return true; } } catch (Exception ignored) { } return false; }
@Test void testCheckExists() { String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; curatorClient.create(path, false, true); assertThat(curatorClient.checkExists(path), is(true)); assertThat(curatorClient.checkExists(path + "/noneexits"), is(false)); }
@Override public void processElement2(StreamRecord<IN2> element) throws Exception { collector.setTimestamp(element); rwContext.setElement(element); userFunction.processBroadcastElement(element.getValue(), rwContext, collector); rwContext.setElement(null); }
@Test void testNoKeyedStateOnBroadcastSide() throws Exception { try (TwoInputStreamOperatorTestHarness<String, Integer, String> testHarness = getInitializedTestHarness( BasicTypeInfo.STRING_TYPE_INFO, new IdentityKeySelector<>(), ...
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory( final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration, final Configuration jobConfiguration, final Configuration clusterConfiguration, final boolean is...
@Test void testFixedDelayStrategySpecifiedInJobConfig() { final Configuration jobConf = new Configuration(); jobConf.set(RestartStrategyOptions.RESTART_STRATEGY, FIXED_DELAY.getMainValue()); final Configuration clusterConf = new Configuration(); clusterConf.set(RestartStrategyOptions...
public void parse(DataByteArrayInputStream input, int readSize) throws Exception { if (currentParser == null) { currentParser = initializeHeaderParser(); } // Parser stack will run until current incoming data has all been consumed. currentParser.parse(input, readSize); }
@Test public void testConnectWithCredentialsBackToBack() throws Exception { CONNECT connect = new CONNECT(); connect.cleanSession(false); connect.clientId(new UTF8Buffer("test")); connect.userName(new UTF8Buffer("user")); connect.password(new UTF8Buffer("pass")); Da...
public static Subject.Factory<Re2jStringSubject, String> re2jString() { return Re2jStringSubject.FACTORY; }
@Test public void containsMatch_string_succeeds() { assertAbout(re2jString()).that("this is a hello world").containsMatch(PATTERN_STR); }
@Override protected void validateDataImpl(TenantId tenantId, Tenant tenant) { validateString("Tenant title", tenant.getTitle()); if (!StringUtils.isEmpty(tenant.getEmail())) { validateEmail(tenant.getEmail()); } }
@Test void testValidateNameInvocation() { Tenant tenant = new Tenant(); tenant.setTitle("Monster corporation ©"); tenant.setEmail("support@thingsboard.io"); validator.validateDataImpl(tenantId, tenant); verify(validator).validateString("Tenant title", tenant.getTitle()); ...
@Override public boolean contains(Object objectToCheck) { return contains(objectToCheck, objectToCheck.hashCode()); }
@Test public void testContains() { final OAHashSet<Integer> set = new OAHashSet<>(8); populateSet(set, 10); for (int i = 0; i < 10; i++) { final boolean contained = set.contains(i); assertTrue("Element " + i + " should be contained", contained); } }
public static ByteArrayClassLoader compile( ClassLoader parentClassLoader, CompileUnit... compileUnits) { final Map<String, byte[]> classes = toBytecode(parentClassLoader, compileUnits); // Set up a class loader that finds and defined the generated classes. return new ByteArrayClassLoader(classes, par...
@Test public void benchmark() { CompileUnit unit = new CompileUnit( "demo.pkg1", "A", ("" + "package demo.pkg1;\n" + "public class A {\n" + " public static String hello() { return \"HELLO\"; }\n" + "}")); ...
@Override public Double getValue() { return getRatio().getValue(); }
@Test public void handlesNaNDenominators() { final RatioGauge nan = new RatioGauge() { @Override protected Ratio getRatio() { return Ratio.of(10, Double.NaN); } }; assertThat(nan.getValue()) .isNaN(); }
public static byte[] intToByteArray(int value, int len) { if (len == 2 || len == 4) { if (len == 2 && (value < Short.MIN_VALUE || value > Short.MAX_VALUE)) { throw new IllegalArgumentException("Value outside range for signed short int."); } else { byte[] b...
@Test public void testIntToByteArray() throws Exception { byte[] ba; int len = 2; ba = TCPClientDecorator.intToByteArray(0, len); assertEquals(len, ba.length); assertEquals(0, ba[0]); assertEquals(0, ba[1]); ba = TCPClientDecorator.intToByteArray(15, len); ...
public static TopicMessageType getMessageType(SendMessageRequestHeader requestHeader) { Map<String, String> properties = MessageDecoder.string2messageProperties(requestHeader.getProperties()); String traFlag = properties.get(MessageConst.PROPERTY_TRANSACTION_PREPARED); TopicMessageType topicMess...
@Test public void testGetMessageTypeWithTransactionFlagButOtherPropertiesPresent() { SendMessageRequestHeader requestHeader = new SendMessageRequestHeader(); Map<String, String> map = new HashMap<>(); map.put(MessageConst.PROPERTY_TRANSACTION_PREPARED, "true"); map.put(MessageConst.P...
@Override public TreeEntry<K, V> get(Object key) { return nodes.get(key); }
@Test public void putAllNodeTest() { final ForestMap<String, Map<String, String>> map = new LinkedForestMap<>(false); final Map<String, String> aMap = MapBuilder.<String, String> create() .put("pid", null) .put("id", "a") .build(); final Map<String, String> bMap = MapBuilder.<String, String> create() ...
public static <T> RestResponse<T> toRestResponse( final ResponseWithBody resp, final String path, final Function<ResponseWithBody, T> mapper ) { final int statusCode = resp.getResponse().statusCode(); return statusCode == OK.code() ? RestResponse.successful(statusCode, mapper.apply(r...
@Test public void shouldCreateRestResponseFromSuccessfulResponse() { // Given: when(httpClientResponse.statusCode()).thenReturn(OK.code()); // When: final RestResponse<KsqlEntityList> restResponse = KsqlClientUtil.toRestResponse(response, PATH, mapper); // Then: assertThat("is succes...
public Collection<DevConsole> loadDevConsoles() { return loadDevConsoles(false); }
@Test public void testLoaderForce() { DefaultDevConsolesLoader loader = new DefaultDevConsolesLoader(context); Collection<DevConsole> col = loader.loadDevConsoles(true); Assertions.assertTrue(col.size() > 3); }
@Override public boolean exists( ValueMetaInterface meta ) { return ( meta != null ) && searchValueMeta( meta.getName() ) != null; }
@Test public void testExists() { assertTrue( rowMeta.exists( string ) ); assertTrue( rowMeta.exists( date ) ); assertTrue( rowMeta.exists( integer ) ); }
synchronized public Value addFirst(Transaction tx, Key key, Value value) throws IOException { assertLoaded(); getHead(tx).addFirst(tx, key, value); size.incrementAndGet(); flushCache(); return null; }
@Test(timeout=60000) public void testAddFirst() throws Exception { createPageFileAndIndex(100); ListIndex<String, Long> listIndex = ((ListIndex<String, Long>) this.index); this.index.load(tx); tx.commit(); tx = pf.tx(); // put is add last doInsert(10); ...
@Override public void open(InitializationContext context) throws IOException { try { PartitionTempFileManager fileManager = new PartitionTempFileManager( fsFactory, stagingPath, context.getTas...
@Test void testClosingWithoutInput() throws Exception { try (OneInputStreamOperatorTestHarness<Row, Object> testHarness = createTestHarness(createSinkFormat(false, false, false, new LinkedHashMap<>()))) { testHarness.setup(); testHarness.open(); } }
public List<Stream> match(Message message) { final Set<Stream> result = Sets.newHashSet(); final Set<String> blackList = Sets.newHashSet(); for (final Rule rule : rulesList) { if (blackList.contains(rule.getStreamId())) { continue; } final St...
@Test public void testOrMatching() { final String dummyField = "dummyField"; final String dummyValue = "dummyValue"; final Stream stream = mock(Stream.class); when(stream.getMatchingType()).thenReturn(Stream.MatchingType.OR); final StreamRule streamRule1 = getStreamRuleMock(...
public LockResource lockExclusive(StateLockOptions lockOptions) throws TimeoutException, InterruptedException, IOException { return lockExclusive(lockOptions, null); }
@Test public void testGraceMode_Timeout() throws Throwable { configureInterruptCycle(false); // The state-lock instance. StateLockManager stateLockManager = new StateLockManager(); // Start a thread that owns the state-lock in shared mode. StateLockingThread sharedHolderThread = new StateLockingTh...
@Description("Is the IP address in the subnet of IP prefix") @ScalarFunction("is_subnet_of") @SqlType(StandardTypes.BOOLEAN) public static boolean isSubnetOf(@SqlType(StandardTypes.IPPREFIX) Slice ipPrefix, @SqlType(StandardTypes.IPADDRESS) Slice ipAddress) { toInetAddress(ipAddress); re...
@Test public void testIsSubnetOf() { assertFunction("IS_SUBNET_OF(IPPREFIX '1.2.3.128/26', IPADDRESS '1.2.3.129')", BOOLEAN, true); assertFunction("IS_SUBNET_OF(IPPREFIX '1.2.3.128/26', IPADDRESS '1.2.5.1')", BOOLEAN, false); assertFunction("IS_SUBNET_OF(IPPREFIX '1.2.3.128/32', IPADDRES...
@Override public CloseableIterator<ScannerReport.CpdTextBlock> readCpdTextBlocks(int componentRef) { ensureInitialized(); return delegate.readCpdTextBlocks(componentRef); }
@Test public void readComponentDuplicationBlocks_is_not_cached() { writer.writeCpdTextBlocks(COMPONENT_REF, of(DUPLICATION_BLOCK)); assertThat(underTest.readCpdTextBlocks(COMPONENT_REF)).isNotSameAs(underTest.readCpdTextBlocks(COMPONENT_REF)); }
public void set(int idx, SelType obj) { val[idx].assignOps(SelOp.ASSIGN, obj); }
@Test public void testSet() { assertEquals("STRING_ARRAY: [foo, bar]", one.type() + ": " + one); one.set(1, SelString.of("baz")); assertEquals("STRING_ARRAY: [foo, baz]", one.type() + ": " + one); }
@Override public RouteContext route(final ShardingRule shardingRule) { RouteContext result = new RouteContext(); String dataSourceName = getDataSourceName(shardingRule.getDataSourceNames()); RouteMapper dataSourceMapper = new RouteMapper(dataSourceName, dataSourceName); if (logicTabl...
@Test void assertRoutingForBroadcastTableWithCursorStatement() { RouteContext actual = new ShardingUnicastRoutingEngine( mock(CursorStatementContext.class), Collections.singleton("t_config"), new ConnectionContext(Collections::emptySet)).route(shardingRule); assertThat(actual.getRout...
public static byte[] tryDecompress(InputStream raw) throws IOException { try (GZIPInputStream gis = new GZIPInputStream(raw); ByteArrayOutputStream out = new ByteArrayOutputStream()) { copy(gis, out); return out.toByteArray(); } }
@Test void testTryDecompressForNotGzip() throws Exception { byte[] testCase = "123".getBytes(Charsets.toCharset("UTF-8")); assertEquals(testCase, IoUtils.tryDecompress(testCase)); }
public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors( ReconnaissanceReport reconnaissanceReport) { return tsunamiPlugins.entrySet().stream() .filter(entry -> isVulnDetector(entry.getKey())) .map(entry -> matchAllVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanc...
@Test public void getVulnDetectors_whenOsServiceFilterHasMatchingClass_returnsMatches() { NetworkService wordPressService = NetworkService.newBuilder() .setNetworkEndpoint(NetworkEndpointUtils.forIpAndPort("1.1.1.1", 80)) .setTransportProtocol(TransportProtocol.TCP) .se...
@Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConsulConfig that = (ConsulConfig) o; return waitTime == that.waitTime && watchDela...
@Test public void testEquals() { assertEquals(consulConfig, consulConfig); assertEquals(consulConfig, that); assertNotEquals(consulConfig, null); assertNotEquals(consulConfig, new Object()); }
@Override public Service queryService(String serviceName, String groupName) throws NacosException { return null; }
@Test void testQueryService() throws NacosException { Service service = delegate.queryService("a", "b"); assertNull(service); }
public SubClusterId getHomeSubcluster( ApplicationSubmissionContext appSubmissionContext, List<SubClusterId> blackListSubClusters) throws YarnException { // the maps are concurrent, but we need to protect from reset() // reinitialization mid-execution by creating a new reference local to this /...
@Test public void testGetHomeSubcluster() throws YarnException { ApplicationSubmissionContext applicationSubmissionContext = mock(ApplicationSubmissionContext.class); when(applicationSubmissionContext.getQueue()).thenReturn(queue1); // the facade only contains the fallback behavior Assert.as...
@Override public String generateSqlType(Dialect dialect) { switch (dialect.getId()) { case MsSql.ID: return format("NVARCHAR (%d)", columnSize); case Oracle.ID: return format("VARCHAR2 (%d%s)", columnSize, ignoreOracleUnit ? "" : " CHAR"); default: return format("VARCHAR ...
@Test public void generateSqlType_does_not_set_unit_on_oracle_if_legacy_mode() { VarcharColumnDef def = new VarcharColumnDef.Builder() .setColumnName("issues") .setLimit(10) .setIsNullable(true) .setIgnoreOracleUnit(true) .build(); assertThat(def.generateSqlType(new Oracle())).i...
@Override @SuppressWarnings("unchecked") public AccessToken load(String token) { DBObject query = new BasicDBObject(); query.put(AccessTokenImpl.TOKEN, cipher.encrypt(token)); final List<DBObject> objects = query(AccessTokenImpl.class, query); if (objects.isEmpty()) { ...
@Test public void testLoadNoToken() throws Exception { final AccessToken accessToken = accessTokenService.load("foobar"); assertNull("No token should have been returned", accessToken); }
public static KTableHolder<GenericKey> build( final KGroupedStreamHolder groupedStream, final StreamAggregate aggregate, final RuntimeBuildContext buildContext, final MaterializedFactory materializedFactory) { return build( groupedStream, aggregate, buildContext, ...
@Test @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT") public void shouldBuildSessionWindowedAggregateCorrectly() { // Given: givenSessionWindowedAggregate(); // When: final KTableHolder<Windowed<GenericKey>> result = windowedAggregate.build(planBuilder, planInfo); // Then: as...
@Override public Mono<LookupUsernameLinkResponse> lookupUsernameLink(final LookupUsernameLinkRequest request) { final UUID linkHandle; try { linkHandle = UUIDUtil.fromByteString(request.getUsernameLinkHandle()); } catch (final IllegalArgumentException e) { throw Status.INVALID_ARGUMENT ...
@Test void lookupUsernameLink() { final UUID linkHandle = UUID.randomUUID(); final byte[] usernameCiphertext = TestRandomUtil.nextBytes(32); final Account account = mock(Account.class); when(account.getEncryptedUsername()).thenReturn(Optional.of(usernameCiphertext)); when(accountsManager.getByU...
private static String getProperty(String name, Configuration configuration) { return Optional.of(configuration.getStringArray(relaxPropertyName(name))) .filter(values -> values.length > 0) .map(Arrays::stream) .map(stream -> stream.collect(Collectors.joining(","))) .orElse(null);...
@Test public void assertHandlesDuplicateRelaxedKeys() throws IOException { Map<String, Object> baseProperties = new HashMap<>(); Map<String, String> mockedEnvironmentVariables = new HashMap<>(); String configFile = File.createTempFile("pinot-configuration-test-4", ".properties").getAbsolutePath(); ...
public WorkDuration subtract(@Nullable WorkDuration with) { if (with != null) { return WorkDuration.createFromMinutes(this.toMinutes() - with.toMinutes(), this.hoursInDay); } else { return this; } }
@Test public void subtract() { // 1d 1h - 5h = 4h WorkDuration result = WorkDuration.create(1, 1, 0, HOURS_IN_DAY).subtract(WorkDuration.createFromValueAndUnit(5, WorkDuration.UNIT.HOURS, HOURS_IN_DAY)); assertThat(result.days()).isZero(); assertThat(result.hours()).isEqualTo(4); assertThat(result...
public int getColumnSize() { return columnSize; }
@Test public void build_string_column_def() { VarcharColumnDef def = new VarcharColumnDef.Builder() .setColumnName("issues") .setLimit(10) .setIsNullable(true) .setDefaultValue("foo") .build(); assertThat(def.getName()).isEqualTo("issues"); assertThat(def.getColumnSize()).is...
@Override public PartialConfig load(File configRepoCheckoutDirectory, PartialConfigLoadContext context) { File[] allFiles = getFiles(configRepoCheckoutDirectory, context); // if context had changed files list then we could parse only new content PartialConfig[] allFragments = parseFiles(al...
@Test public void shouldFailToLoadDirectoryWithDuplicatedPipeline() throws Exception { GoConfigMother mother = new GoConfigMother(); PipelineConfig pipe1 = mother.cruiseConfigWithOnePipelineGroup().getAllPipelineConfigs().get(0); helper.addFileWithPipeline("pipe1.gocd.xml", pipe1); ...
@Override public void merge(ColumnStatisticsObj aggregateColStats, ColumnStatisticsObj newColStats) { LOG.debug("Merging statistics: [aggregateColStats:{}, newColStats: {}]", aggregateColStats, newColStats); DoubleColumnStatsDataInspector aggregateData = doubleInspectorFromStats(aggregateColStats); Doubl...
@Test public void testMergeNullWithNonNullValues() { ColumnStatisticsObj aggrObj = createColumnStatisticsObj(new ColStatsBuilder<>(double.class) .low(null) .high(null) .numNulls(0) .numDVs(0) .build()); ColumnStatisticsObj newObj = createColumnStatisticsObj(new ColStats...
public Progress getSortPhase() { return sortPhase; }
@Test public void testShufflePermissions() throws Exception { JobConf conf = new JobConf(); conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077"); conf.set(MRConfig.LOCAL_DIR, testRootDir.getAbsolutePath()); MapOutputFile mof = new MROutputFiles(); mof.setConf(conf); TaskAttemptID ...
public JibContainer runBuild() throws BuildStepsExecutionException, IOException, CacheDirectoryCreationException { try { logger.accept(LogEvent.lifecycle("")); logger.accept(LogEvent.lifecycle(startupMessage)); JibContainer jibContainer = jibContainerBuilder.containerize(containerizer); ...
@Test public void testBuildImage_registryCredentialsNotSentException() throws InterruptedException, IOException, CacheDirectoryCreationException, RegistryException, ExecutionException { Mockito.doThrow(mockRegistryCredentialsNotSentException) .when(mockJibContainerBuilder) .contain...
public static BigDecimal satoshiToBtc(long satoshis) { return new BigDecimal(satoshis).movePointLeft(SMALLEST_UNIT_EXPONENT); }
@Test public void testSatoshiToBtc() { assertThat(new BigDecimal("-92233720368.54775808"), Matchers.comparesEqualTo(satoshiToBtc(Long.MIN_VALUE))); assertThat(new BigDecimal("-0.00000001"), Matchers.comparesEqualTo(satoshiToBtc(NEGATIVE_SATOSHI.value))); assertThat(BigDecimal.ZERO, Matchers...
@ConstantFunction.List(list = { @ConstantFunction(name = "year", argTypes = {DATETIME}, returnType = SMALLINT, isMonotonic = true), @ConstantFunction(name = "year", argTypes = {DATE}, returnType = SMALLINT, isMonotonic = true) }) public static ConstantOperator year(ConstantOperator arg) ...
@Test public void year() { ConstantOperator date = ConstantOperator.createDatetime(LocalDateTime.of(2000, 10, 21, 12, 0)); ConstantOperator result = ScalarOperatorFunctions.year(date); assertEquals(Type.SMALLINT, result.getType()); assertEquals(2000, result.getSmallint()); }
public void setData( String data ) { this.data = data; }
@Test public void setData() { DragAndDropContainer dnd = new DragAndDropContainer( DragAndDropContainer.TYPE_BASE_STEP_TYPE, "Step Name" ); dnd.setData( "Another Step" ); assertEquals( "Another Step", dnd.getData() ); }
public void processVerstrekkingAanAfnemer(VerstrekkingAanAfnemer verstrekkingAanAfnemer){ if (logger.isDebugEnabled()) logger.debug("Processing verstrekkingAanAfnemer: {}", marshallElement(verstrekkingAanAfnemer)); Afnemersbericht afnemersbericht = afnemersberichtRepository.findByOnzeRefere...
@Test public void testProcessWa11(){ String testAnummer = "SSSSSSSSSS"; String testNieuwAnummer = "SSSSSSSSSS"; String datumGeldigheid = "SSSSSSSS"; Wa11 testWa11 = TestDglMessagesUtil.createTestWa11(testAnummer, testNieuwAnummer, datumGeldigheid); VerstrekkingInhoudType inho...
public int andCardinality(BitmapCollection bitmaps) { ImmutableRoaringBitmap left = reduceInternal(); ImmutableRoaringBitmap right = bitmaps.reduceInternal(); if (!_inverted) { if (!bitmaps._inverted) { return ImmutableRoaringBitmap.andCardinality(left, right); } return ImmutableRo...
@Test(dataProvider = "andCardinalityTestCases") public void testAndCardinality(int numDocs, ImmutableRoaringBitmap left, boolean leftInverted, ImmutableRoaringBitmap right, boolean rightInverted, int expected) { assertEquals(new BitmapCollection(numDocs, leftInverted, left).andCardinality( new Bitma...
@Override public List<DistroData> getVerifyData() { List<DistroData> result = null; for (String each : clientManager.allClientId()) { Client client = clientManager.getClient(each); if (null == client || !client.isEphemeral()) { continue; } ...
@Test void testGetVerifyData() { client.setRevision(10L); when(clientManager.allClientId()).thenReturn(Collections.singletonList(CLIENT_ID)); List<DistroData> list = distroClientDataProcessor.getVerifyData(); assertEquals(1, list.size()); assertEquals(DataOperation.VERIFY, li...