focal_method
stringlengths
13
60.9k
test_case
stringlengths
25
109k
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) { return new CreateStreamCommand( outputNode.getSinkName().get(), outputNode.getSchema(), outputNode.getTimestampColumn(), outputNode.getKsqlTopic().getKafkaTopicName(), Formats.from...
@Test public void shouldBuildSchemaWithExplicitKeyFieldForStream() { // Given: final CreateStream statement = new CreateStream( SOME_NAME, TableElements.of( tableElement("k", new Type(SqlTypes.STRING), KEY_CONSTRAINT), ELEMENT1, ELEMENT2 ), f...
@Override public void getConfig(FederationConfig.Builder builder) { for (Target target : resolvedTargets.values()) builder.target(target.getTargetConfig()); targetSelector.ifPresent(selector -> builder.targetSelector(selector.getGlobalComponentId().stringValue())); }
@Test void source_groups_are_not_inherited_when_inheritDefaultSources_is_false() throws Exception { FederationFixture f = new ProvidersWithSourceFixture(); FederationSearcher federationSearcherWithoutDefaultSources = newFederationSearcher(false, List.of()); f.initializeFederationSearcher(fe...
@Udf(description = "Converts a string representation of a date in the given format" + " into the TIMESTAMP value." + " Single quotes in the timestamp format can be escaped with ''," + " for example: 'yyyy-MM-dd''T''HH:mm:ssX'.") public Timestamp parseTimestamp( @UdfParameter( descrip...
@Test public void shouldSupportPSTTimeZone() { // When: final Object result = udf.parseTimestamp("2018-08-15 10:10:43", "yyyy-MM-dd HH:mm:ss", "America/Los_Angeles"); // Then: assertThat(result, is(new Timestamp(1534353043000L))); }
public Account update(Account account, Consumer<Account> updater) { return update(account, a -> { updater.accept(a); // assume that all updaters passed to the public method actually modify the account return true; }); }
@Test void testChangePhoneNumberViaUpdate() { final String originalNumber = "+14152222222"; final String targetNumber = "+14153333333"; final UUID uuid = UUID.randomUUID(); final Account account = AccountsHelper.generateTestAccount(originalNumber, uuid, UUID.randomUUID(), new ArrayList<>(), new byte[...
@Override public void remove(final MetaData metaData) { metaData.updateContextPath(); List<TarsInvokePrx> prxList = ApplicationConfigCache.getInstance() .get(metaData.getPath()).getTarsInvokePrxList(); List<TarsInvokePrx> removePrxList = prxList.stream() .filt...
@Test public void testUnSubscribe() { tarsMetaDataHandler.remove(metaData); }
@Override public void init() { if (inited.compareAndSet(false, true)) { this.scanPeriod = CommonUtils.parseInt(registryConfig.getParameter("registry.domain.scan.period"), scanPeriod); Runnable task = () -> { try { refreshDomain...
@Test public void testInit() { DomainRegistry domainRegistry = new DomainRegistry(new RegistryConfig()); assertNull(domainRegistry.scheduledExecutorService); domainRegistry.init(); assertTrue(domainRegistry.scheduledExecutorService.isStarted()); }
public OptExpression next() { // For logic scan to physical scan, we only need to match once if (isPatternWithoutChildren && groupExpressionIndex.get(0) > 0) { return null; } OptExpression expression; do { this.groupTraceKey = 0; // Match wit...
@Test public void testBinderDepth2Repeat4() { OptExpression expr1 = OptExpression.create(new MockOperator(OperatorType.LOGICAL_JOIN, 0), OptExpression.create(new MockOperator(OperatorType.LOGICAL_OLAP_SCAN, 1)), OptExpression.create(new MockOperator(OperatorType.LOGICAL_OLAP_...
@Override public Flux<ChatResponse> stream(Prompt prompt) { WatsonxAiRequest request = request(prompt); Flux<WatsonxAiResponse> response = this.watsonxAiApi.generateStreaming(request); return response.map(chunk -> { Generation generation = new Generation(chunk.results().get(0).generatedText()); if (chun...
@Test public void testStreamMethod() { WatsonxAiApi mockChatApi = mock(WatsonxAiApi.class); WatsonxAiChatModel chatModel = new WatsonxAiChatModel(mockChatApi); Prompt prompt = new Prompt(List.of(new SystemMessage("Your prompt here")), WatsonxAiChatOptions.builder().withModel("google/flan-ul2").build()); ...
@Override public boolean isDetected() { return system.envVariable("bamboo_buildNumber") != null; }
@Test public void isDetected() { assertThat(underTest.isDetected()).isFalse(); setEnvVariable("bamboo_buildNumber", "41"); assertThat(underTest.isDetected()).isTrue(); }
static CounterResult fromJson(String json) { return JsonUtil.parse(json, CounterResultParser::fromJson); }
@Test public void unsupportedUnit() { assertThatThrownBy(() -> CounterResultParser.fromJson("{\"unit\":\"unknown\",\"value\":23}")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Invalid unit: unknown"); }
@Subscribe public void inputCreated(InputCreated inputCreatedEvent) { final String inputId = inputCreatedEvent.id(); LOG.debug("Input created: {}", inputId); final Input input; try { input = inputService.find(inputId); } catch (NotFoundException e) { L...
@Test @SuppressWarnings("unchecked") public void inputCreatedDoesNotStopInputIfItIsNotRunning() throws Exception { final String inputId = "input-id"; final Input input = mock(Input.class); when(inputService.find(inputId)).thenReturn(input); when(inputRegistry.getInputState(inputI...
public static <T extends PipelineOptions> T as(Class<T> klass) { return new Builder().as(klass); }
@Test public void testGettersAnnotatedWithInconsistentDefault() throws Exception { // Initial construction is valid. GetterWithDefault options = PipelineOptionsFactory.as(GetterWithDefault.class); expectedException.expect(IllegalArgumentException.class); // Make sure the error message says what the ...
@Operation(summary = "list", description = "List stacks components") @GetMapping("/{stackName}/{stackVersion}/components") public ResponseEntity<List<ServiceComponentVO>> components( @PathVariable String stackName, @PathVariable String stackVersion) { return ResponseEntity.success(stackServi...
@Test void componentsReturnsAllComponentsForValidStack() { String stackName = "bigtop"; String stackVersion = "1.0.0"; List<ServiceComponentVO> components = Arrays.asList(new ServiceComponentVO(), new ServiceComponentVO()); when(stackService.components(stackName, stackVersion)).thenR...
public final Logger getLogger(final Class<?> clazz) { return getLogger(clazz.getName()); }
@Test public void loggerNameEndingInDotOrDollarShouldWork() { { String loggerName = "toto.x."; Logger logger = lc.getLogger(loggerName); assertEquals(loggerName, logger.getName()); } { String loggerName = "toto.x$"; Logger logger = lc.getLogger(loggerName); assertEqual...
public String getPath() { return mUri.getPath(); }
@Test public void getPathTests() { assertEquals(".", new AlluxioURI(".").getPath()); assertEquals("/", new AlluxioURI("/").getPath()); assertEquals("/", new AlluxioURI("alluxio:/").getPath()); assertEquals("/", new AlluxioURI("alluxio://localhost:80/").getPath()); assertEquals("/a.txt", new Alluxi...
public static Schema create(Type type) { switch (type) { case STRING: return new StringSchema(); case BYTES: return new BytesSchema(); case INT: return new IntSchema(); case LONG: return new LongSchema(); case FLOAT: return new FloatSchema(); case DOUBLE: ...
@Test void intAsFloatDefaultValue() { Schema.Field field = new Schema.Field("myField", Schema.create(Schema.Type.FLOAT), "doc", 1); assertTrue(field.hasDefaultValue()); assertEquals(1.0f, field.defaultVal()); assertEquals(1.0f, GenericData.get().getDefaultValue(field)); }
synchronized public void clear() { count = 0; bufferCount = 0; samples.clear(); }
@Test public void testClear() throws IOException { for (int i = 0; i < 1000; i++) { estimator.insert(i); } estimator.clear(); assertThat(estimator.getCount()).isZero(); assertThat(estimator.getSampleCount()).isZero(); assertThat(estimator.snapshot()).isNull(); }
public void addLicense(License license) { licenses.add(license); }
@Test public void testAddLicense() { License license = new License("name", "url"); Model instance = new Model(); instance.addLicense(license); assertNotNull(instance.getLicenses()); }
@Override public ClassLoader getDefaultClassLoader() { return DEFAULT_CLASS_LOADER; }
@Test public void loadClass_notFound() { runWithClassloader(provider -> { assertThrows(ClassNotFoundException.class, () -> provider.getDefaultClassLoader().loadClass("a.b.c")); }); }
public static URL socketToUrl(InetSocketAddress socketAddress) { String hostString = socketAddress.getHostString(); // If the hostString is an IPv6 address, it needs to be enclosed in square brackets // at the beginning and end. if (socketAddress.getAddress() != null && s...
@Test void testIpv4SocketToUrl() throws MalformedURLException { InetSocketAddress socketAddress = new InetSocketAddress("192.168.0.1", 8080); URL expectedResult = new URL("http://192.168.0.1:8080"); assertThat(socketToUrl(socketAddress)).isEqualTo(expectedResult); }
public static Collection<? extends Certificate> loadCertificates(Path certificatePath) throws CertificateException, IOException { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); File certFile = certificatePath.toFile(); if (certFile.isDirectory()) { final Byte...
@Test public void testLoadCertificates() throws Exception { final File certFile = resourceToFile(CERTIFICATES.get(keyAlgorithm)); final Collection<? extends Certificate> certificates = KeyUtil.loadCertificates(certFile.toPath()); assertThat(certificates) .isNotEmpty() ...
public void setMaxHeaderTableSize(ByteBuf out, long maxHeaderTableSize) throws Http2Exception { if (maxHeaderTableSize < MIN_HEADER_TABLE_SIZE || maxHeaderTableSize > MAX_HEADER_TABLE_SIZE) { throw connectionError(PROTOCOL_ERROR, "Header Table Size must be >= %d and <= %d but was %d", ...
@Test public void testSetMaxHeaderTableSizeOverflow() { assertThrows(Http2Exception.class, new Executable() { @Override public void execute() throws Throwable { hpackEncoder.setMaxHeaderTableSize(buf, MAX_HEADER_TABLE_SIZE + 1); } }); }
void addPartitionEpochs( Map<Uuid, Set<Integer>> assignment, int epoch ) { assignment.forEach((topicId, assignedPartitions) -> { currentPartitionEpoch.compute(topicId, (__, partitionsOrNull) -> { if (partitionsOrNull == null) { partitionsOrNull...
@Test public void testAddPartitionEpochs() { Uuid fooTopicId = Uuid.randomUuid(); ConsumerGroup consumerGroup = createConsumerGroup("foo"); consumerGroup.addPartitionEpochs( mkAssignment( mkTopicAssignment(fooTopicId, 1) ), 10 ); ...
@Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Paths paths = (Paths) o; return Objects.equals(this.extensions, paths.extensions) && ...
@Test public void testEquals() { Paths paths = new Paths(); Assert.assertTrue(paths.equals(paths)); Assert.assertTrue(paths.equals(new Paths())); Assert.assertFalse(paths.equals(null)); Assert.assertFalse(paths.equals(new String())); }
@Override public void getConfig(ComponentsConfig.Builder builder) { builder.setApplyOnRestart(getDeferChangesUntilRestart()); // Sufficient to set on one config builder.components.addAll(ComponentsConfigGenerator.generate(getAllComponents())); builder.components(new ComponentsConfig.Compone...
@Test void search_and_docproc_bundles_are_installed_for_application_clusters_with_search() { ApplicationContainerCluster cluster = newClusterWithSearch(createRoot(false), false, null); var bundleBuilder = new PlatformBundlesConfig.Builder(); cluster.getConfig(bundleBuilder); List<Pa...
public LinkedHashMap<String, String> getKeyPropertyList(ObjectName mbeanName) { LinkedHashMap<String, String> keyProperties = keyPropertiesPerBean.get(mbeanName); if (keyProperties == null) { keyProperties = new LinkedHashMap<>(); String properties = mbeanName.getKeyPropertyListS...
@Test public void testQuotedObjectNameWithComma() throws Throwable { JmxMBeanPropertyCache testCache = new JmxMBeanPropertyCache(); LinkedHashMap<String, String> parameterList = testCache.getKeyPropertyList( new ObjectName("com.organisation:name=\"value,more\"...
@Override public TableDataConsistencyCheckResult swapToObject(final YamlTableDataConsistencyCheckResult yamlConfig) { if (null == yamlConfig) { return null; } if (!Strings.isNullOrEmpty(yamlConfig.getIgnoredType())) { return new TableDataConsistencyCheckResult(TableDa...
@Test void assertSwapToObjectWithNullYamlTableDataConsistencyCheckResultIgnoredType() { YamlTableDataConsistencyCheckResult yamlConfig = new YamlTableDataConsistencyCheckResult(); yamlConfig.setIgnoredType(null); TableDataConsistencyCheckResult result = yamlTableDataConsistencyCheckResultSwa...
@Override public SentWebAppMessage deserializeResponse(String answer) throws TelegramApiRequestException { return deserializeResponse(answer, SentWebAppMessage.class); }
@Test public void testAnswerWebAppQueryDeserializeValidResponse() { String responseText = "{\"ok\":true,\"result\": { \"inline_message_id\": \"123456\" } }"; AnswerWebAppQuery answerWebAppQuery = AnswerWebAppQuery .builder() .webAppQueryId("123456789") ...
public int startWithRunStrategy( @NotNull WorkflowInstance instance, @NotNull RunStrategy runStrategy) { return withMetricLogError( () -> withRetryableTransaction( conn -> { final long nextInstanceId = getLatestInstanceId(conn, instan...
@Test public void testStartRunStrategyWithFirstOnly() { MaestroTestHelper.removeWorkflowInstance(dataSource, TEST_WORKFLOW_ID, 1); wfi.setWorkflowUuid("test-uuid"); wfi.setWorkflowInstanceId(0); int res = runStrategyDao.startWithRunStrategy(wfi, RunStrategy.create("FIRST_ONLY")); assertEquals(1, r...
@Override public ProcNodeInterface lookup(String beIdStr) throws AnalysisException { if (Strings.isNullOrEmpty(beIdStr)) { throw new AnalysisException("Backend id is null"); } long backendId = -1L; try { backendId = Long.parseLong(beIdStr); } catch (N...
@Test public void testLookupInvalid() { BackendsProcDir dir = new BackendsProcDir(systemInfoService); ExceptionChecker.expectThrows(AnalysisException.class, () -> dir.lookup(null)); ExceptionChecker.expectThrows(AnalysisException.class, () -> dir.lookup("")); }
static Class<?> obtainActualTypeInStreamObserver(Type typeInStreamObserver) { return (Class<?>) (typeInStreamObserver instanceof ParameterizedType ? ((ParameterizedType) typeInStreamObserver).getRawType() : typeInStreamObserver); }
@Test void testObtainActualType() throws NoSuchMethodException { Method method1 = DescriptorService.class.getMethod("serverStream1", Object.class, StreamObserver.class); Class<?> clazz1 = ReflectionPackableMethod.obtainActualTypeInStreamObserver( ((ParameterizedType) method1.getGene...
@Override public void apply(IntentOperationContext<FlowRuleIntent> context) { Optional<IntentData> toUninstall = context.toUninstall(); Optional<IntentData> toInstall = context.toInstall(); if (toInstall.isPresent() && toUninstall.isPresent()) { Intent intentToInstall = toInstal...
@Test public void testUninstallAndInstallUnchanged() { List<Intent> intentsToInstall = createFlowRuleIntents(); List<Intent> intentsToUninstall = createFlowRuleIntents(); IntentData toInstall = new IntentData(createP2PIntent(), IntentState.INSTA...
Map<String, File> scanExistingUsers() throws IOException { Map<String, File> users = new HashMap<>(); File[] userDirectories = listUserDirectories(); if (userDirectories != null) { for (File directory : userDirectories) { String userId = idStrategy.idFromFilename(dire...
@Test public void scanExistingUsersNone() throws IOException { File usersDirectory = createTestDirectory(getClass(), name); UserIdMigrator migrator = new UserIdMigrator(usersDirectory, IdStrategy.CASE_INSENSITIVE); Map<String, File> userMappings = migrator.scanExistingUsers(); assert...
public static String toString(InetAddress inetAddress) { if (inetAddress instanceof Inet6Address) { String address = InetAddresses.toAddrString(inetAddress); // toAddrString() returns any interface/scope as a %-suffix, // see https://github.com/google/guava/commit/3f61870ac6e...
@Test void testToStringWithInterface2() throws UnknownHostException { byte[] bytes = new byte[] { 0x10,(byte)0x80, 0,0, 0,0, 0,0, 0,8, 8,0, 0x20,0x0c, 0x41,0x7a }; Inet6Address address = Inet6Address.getByAddress(null, bytes, 1); // Verify Guava's InetAddresses.toAddrString() includes the in...
public List<String> getDatacentersFor( InetAddress address, String continent, String country, Optional<String> subdivision ) { final int NUM_DATACENTERS = 3; if(this.isEmpty()) { return Collections.emptyList(); } List<String> dcsBySubnet = getDatacentersBySubnet(address...
@Test void testGetFastestDatacentersDistinct() throws UnknownHostException { var v6address = Inet6Address.getByName("2001:db8:b0ac:aaaa:aaaa:aaaa:aaaa:0001"); var actual = basicTable.getDatacentersFor(v6address, "NA", "US", Optional.of("VA")); assertThat(actual).isEqualTo(List.of("datacenter-2", "datacent...
@Override public void invoke() throws Exception { // -------------------------------------------------------------------- // Initialize // -------------------------------------------------------------------- LOG.debug(getLogString("Start registering input and output")); // i...
@Test @SuppressWarnings("unchecked") void testCancelSortingDataSinkTask() { double memoryFraction = 1.0; super.initEnvironment(MEMORY_MANAGER_SIZE, NETWORK_BUFFER_SIZE); super.addInput(new InfiniteInputIterator(), 0); final DataSinkTask<Record> testTask = new DataSinkTask<>(thi...
public List<HandleAndLocalPath> uploadFilesToCheckpointFs( @Nonnull List<Path> files, CheckpointStreamFactory checkpointStreamFactory, CheckpointedStateScope stateScope, CloseableRegistry closeableRegistry, CloseableRegistry tmpResourcesRegistry) t...
@Test void testMultiThreadUploadCorrectly() throws Exception { File checkpointPrivateFolder = TempDirUtils.newFolder(temporaryFolder, "private"); org.apache.flink.core.fs.Path checkpointPrivateDirectory = org.apache.flink.core.fs.Path.fromLocalFile(checkpointPrivateFolder); ...
@Override public DataNode readNode(ResourceId path, Filter filter) { // FIXME transform filter? is it possible? return super.readNode(toAbsoluteId(path), filter); }
@Test public void testReadNode() { Filter filter = null; DataNode returned = view.readNode(relIntf, filter); assertTrue(ResourceIds.isPrefix(rid, realPath)); // FIXME test realFilter // TODO do we expect something to happen on returned? }
@Override public long recalculateRevision() { return revision.addAndGet(1); }
@Test void testRecalculateRevision() { assertEquals(0, connectionBasedClient.getRevision()); connectionBasedClient.recalculateRevision(); assertEquals(1, connectionBasedClient.getRevision()); }
boolean hasAsPathLoop(long localAsNumber) { for (PathSegment pathSegment : asPath.getPathSegments()) { for (Long asNumber : pathSegment.getSegmentAsNumbers()) { if (asNumber.equals(localAsNumber)) { return true; } } } re...
@Test public void testHasAsPathLoop() { BgpRouteEntry bgpRouteEntry = generateBgpRouteEntry(); // Test for loops: test each AS number in the interval [1, 6] for (int i = 1; i <= 6; i++) { assertThat(bgpRouteEntry.hasAsPathLoop(i), is(true)); } // Test for non-lo...
public static String implodeMultiline(List<String> lines) { if (lines==null) return null; return implode(lines.toArray(new String[0]), "\n"); }
@Test public void testImplodeMultiline() { assertEquals(StringUtilities.implodeMultiline(List.of("foo", "bar")), "foo\nbar"); assertEquals(StringUtilities.implodeMultiline(List.of("")), ""); assertNull(StringUtilities.implodeMultiline(null)); assertEquals(StringUtilities.implodeMulti...
protected List<List<Comparable>> getPartitionTransInfo(long txnId, long tableId) throws AnalysisException { List<List<Comparable>> partitionInfos = new ArrayList<List<Comparable>>(); readLock(); try { TransactionState transactionState = unprotectedGetTransactionState(txnId); ...
@Test public void testGetPartitionTransInfo() throws AnalysisException { DatabaseTransactionMgr masterDbTransMgr = masterTransMgr.getDatabaseTransactionMgr(GlobalStateMgrTestUtil.testDbId1); Long txnId = lableToTxnId.get(GlobalStateMgrTestUtil.testTxnLable1); List<List<Compar...
@Override protected Set<StepField> getUsedFields( RestMeta stepMeta ) { Set<StepField> usedFields = new HashSet<>(); // add url field if ( stepMeta.isUrlInField() && StringUtils.isNotEmpty( stepMeta.getUrlField() ) ) { usedFields.addAll( createStepFields( stepMeta.getUrlField(), getInputs() ) ); ...
@Test public void testGetUsedFields_urlInFieldNoFieldSet() throws Exception { Set<StepField> fields = new HashSet<>(); when( meta.isUrlInField() ).thenReturn( true ); when( meta.getUrlField() ).thenReturn( null ); Set<StepField> usedFields = analyzer.getUsedFields( meta ); verify( analyzer, neve...
@Override public boolean isActive() { return isActive; }
@Test(timeOut = 30000) public void testSendCommandBeforeCreatingProducer() throws Exception { resetChannel(); setChannelConnected(); // test SEND before producer is created sendMessage(); // Then expect channel to close Awaitility.await().atMost(10, TimeUnit.SECONDS...
public static boolean safeRangeEquals(final Range<Comparable<?>> sourceRange, final Range<Comparable<?>> targetRange) { Class<?> clazz = getRangeTargetNumericType(sourceRange, targetRange); if (null == clazz) { return sourceRange.equals(targetRange); } Range<Comparable<?>> ne...
@Test void assertSafeRangeEqualsForBigDecimal() { assertTrue(SafeNumberOperationUtils.safeRangeEquals(Range.greaterThan(BigDecimal.valueOf(1.1)), Range.greaterThan(1.1F))); }
@Override public void close() throws IOException { channel.close(); }
@Test public void testVersion() throws IOException { RecordIOWriter writer = new RecordIOWriter(file); FileChannel channel = FileChannel.open(file, StandardOpenOption.READ); ByteBuffer versionBuffer = ByteBuffer.allocate(1); channel.read(versionBuffer); versionBuffer.rewind()...
@VisibleForTesting boolean applyRaisingException() throws Exception { Boolean outcome = apply(); if (thrown != null) { throw thrown; } return outcome; }
@Test public void testReadFailureDoesNotSurfaceInAbort() throws Throwable { int threshold = 50; SDKStreamDrainer drainer = new SDKStreamDrainer("s3://example/", new FakeSDKInputStream(BYTES, threshold), true, BYTES, EMPTY_INPUT_STREAM_STATISTICS, "test"); drainer.applyRaisi...
public Map<String, String> parse(String body) { final ImmutableMap.Builder<String, String> newLookupBuilder = ImmutableMap.builder(); final String[] lines = body.split(lineSeparator); for (String line : lines) { if (line.startsWith(this.ignorechar)) { continue; ...
@Test public void parseKeyOnlyFile() throws Exception { final String input = "# Sample file for testing\n" + "foo\n" + "bar\n" + "baz"; final DSVParser dsvParser = new DSVParser("#", "\n", ":", "", true, false, 0, Optional.empty()); final Map<...
@Override public IMetaverseNode createResourceNode( IExternalResourceInfo resource ) throws MetaverseException { return createFileNode( resource.getName(), descriptor ); }
@Test public void testCreateResourceNode() throws Exception { IExternalResourceInfo res = mock( IExternalResourceInfo.class ); when( res.getName() ).thenReturn( "file:///Users/home/tmp/xyz.xml" ); IMetaverseNode resourceNode = analyzer.createResourceNode( res ); assertNotNull( resourceNode ); asse...
public static Table getTableMeta(DataSource ds, String tableName) { return getTableMeta(ds, null, null, tableName); }
@Test public void getTableIndexInfoTest() { final Table table = MetaUtil.getTableMeta(ds, "user_1"); assertEquals(table.getIndexInfoList().size(), 2); }
Mono<Locale> getLocaleFromSubscriber(Subscriber subscriber) { // TODO get locale from subscriber return Mono.just(Locale.getDefault()); }
@Test void getLocaleFromSubscriberTest() { var subscription = mock(Subscriber.class); notificationCenter.getLocaleFromSubscriber(subscription) .as(StepVerifier::create) .expectNext(Locale.getDefault()) .verifyComplete(); }
@Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { if (isDisabledByConfiguration(ctx)) { StatusViaSLF4JLoggerFactory.addInfo("Due to deployment instructions will NOT register an instance of " + LogbackServletContextListener.class +...
@Test public void noListenerShouldBeAddedWhenDisabled() throws ServletException { ServletContext mockedServletContext = mock(ServletContext.class); when(mockedServletContext.getInitParameter(CoreConstants.DISABLE_SERVLET_CONTAINER_INITIALIZER_KEY)) .thenReturn("true"); lsci.o...
public static <T> T visit(final Schema start, final SchemaVisitor<T> visitor) { // Set of Visited Schemas IdentityHashMap<Schema, Schema> visited = new IdentityHashMap<>(); // Stack that contains the Schams to process and afterVisitNonTerminal // functions. // Deque<Either<Schema, Supplier<SchemaVis...
@Test void visit2() { String s2 = "{\"type\": \"record\", \"name\": \"c1\", \"fields\": [" + "{\"name\": \"f1\", \"type\": \"int\"}" + "]}"; assertEquals("c1.\"int\"!", Schemas.visit(new Schema.Parser().parse(s2), new TestVisitor())); }
@Override public Character getChar(K name) { return null; }
@Test public void testGetCharDefault() { assertEquals('x', HEADERS.getChar("name1", 'x')); }
@Override public SchemaKStream<?> buildStream(final PlanBuildContext buildContext) { final Stacker contextStacker = buildContext.buildNodeContext(getId().toString()); return schemaKStreamFactory.create( buildContext, dataSource, contextStacker.push(SOURCE_OP_NAME) ); }
@Test public void shouldBuildTableByConvertingFromStream() { // Given: givenNodeWithMockSource(); // When: final SchemaKStream<?> returned = node.buildStream(buildContext); // Then: assertThat(returned, is(table)); }
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) { while (in.readableBytes() >= 1 + MySQLBinlogEventHeader.MYSQL_BINLOG_EVENT_HEADER_LENGTH) { in.markReaderIndex(); MySQLPacketPayload payload = new MySQLPacketPayload(in, ctx.c...
@Test void assertDecodeQueryEvent() { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeBytes(StringUtil.decodeHexDump("00f3e25665020100000087000000c2740f0a0400c9150000000000000400002d000000000000012000a045000000000603737464042d002d00e0000c0164735f3000116df40b00000" + "0000012ff00647...
public static String strip(CharSequence str, CharSequence prefixOrSuffix) { if (equals(str, prefixOrSuffix)) { // 对于去除相同字符的情况单独处理 return EMPTY; } return strip(str, prefixOrSuffix, prefixOrSuffix); }
@Test public void stripTest() { final String SOURCE_STRING = "aaa_STRIPPED_bbb"; // ---------------------------- test strip ---------------------------- // Normal test assertEquals("aa_STRIPPED_bbb", CharSequenceUtil.strip(SOURCE_STRING, "a")); assertEquals(SOURCE_STRING, CharSequenceUtil.strip(SOURCE_STR...
public ServiceInfo getServiceInfo(final String serviceName, final String groupName, final String clusters) { String groupedServiceName = NamingUtils.getGroupedName(serviceName, groupName); String key = ServiceInfo.getKey(groupedServiceName, clusters); return serviceInfoMap.get(key); }
@Test void testGetServiceInfo() { ServiceInfo info = new ServiceInfo("a@@b@@c"); Instance instance1 = createInstance("1.1.1.1", 1); List<Instance> hosts = new ArrayList<>(); hosts.add(instance1); info.setHosts(hosts); ServiceInfo expect = holder.processServic...
@Override public OpticalConnectivityId setupConnectivity(ConnectPoint ingress, ConnectPoint egress, Bandwidth bandwidth, Duration latency) { checkNotNull(ingress); checkNotNull(egress); log.info("setupConnectivity({}, {}, {}, {})", ingress, ...
@Test public void testInstalledEventRemote() { // set the master for ingress device of intent to remote node mastershipService.setMastership(DEVICE2.id(), MastershipRole.NONE); Bandwidth bandwidth = Bandwidth.bps(100); Duration latency = Duration.ofMillis(10); OpticalConnec...
static JavaType constructType(Type type) { try { return constructTypeInner(type); } catch (Exception e) { throw new InvalidDataTableTypeException(type, e); } }
@Test void lists_are_list_types() { JavaType javaType = TypeFactory.constructType(LIST_OF_LIST_OF_OBJECT); assertThat(javaType.getClass(), equalTo(TypeFactory.ListType.class)); assertThat(javaType.getOriginal(), is(LIST_OF_LIST_OF_OBJECT)); TypeFactory.ListType listType = (TypeFacto...
@Udf(description = "Returns the tangent of an INT value") public Double tan( @UdfParameter( value = "value", description = "The value in radians to get the tangent of." ) final Integer value ) { return tan(value == null ? null : value.doubleValue()); }
@Test public void shouldHandleNull() { assertThat(udf.tan((Integer) null), is(nullValue())); assertThat(udf.tan((Long) null), is(nullValue())); assertThat(udf.tan((Double) null), is(nullValue())); }
public static MqttTopicFilter toFilter(String topicFilter) { if (topicFilter == null || topicFilter.isEmpty()) { throw new IllegalArgumentException("Topic filter can't be empty!"); } return filters.computeIfAbsent(topicFilter, filter -> { if (filter.equals("#")) { ...
@Test public void metadataCanBeUpdated() throws ScriptException { MqttTopicFilter filter = MqttTopicFilterFactory.toFilter("Sensor/Temperature/House/+"); assertTrue(filter.filter(TEST_STR_1)); assertFalse(filter.filter(TEST_STR_2)); filter = MqttTopicFilterFactory.toFilter("Sensor/+...
@Override public @Nullable State waitUntilFinish() { return waitUntilFinish(Duration.millis(-1)); }
@Test public void testWaitToFinishFail() throws Exception { Dataflow.Projects.Locations.Jobs.Get statusRequest = mock(Dataflow.Projects.Locations.Jobs.Get.class); when(mockJobs.get(eq(PROJECT_ID), eq(REGION_ID), eq(JOB_ID))).thenReturn(statusRequest); when(statusRequest.execute()).thenThrow(IOExc...
Flux<DataEntityList> export(KafkaCluster cluster) { return kafkaConnectService.getConnects(cluster) .flatMap(connect -> kafkaConnectService.getConnectorNamesWithErrorsSuppress(cluster, connect.getName()) .flatMap(connectorName -> kafkaConnectService.getConnector(cluster, connect.getName(), conne...
@Test void exportsConnectorsAsDataTransformers() { ConnectDTO connect = new ConnectDTO(); connect.setName("testConnect"); connect.setAddress("http://kconnect:8083"); ConnectorDTO sinkConnector = new ConnectorDTO(); sinkConnector.setName("testSink"); sinkConnector.setType(ConnectorTypeDTO.SINK...
public void recordNanos(long durationNanos) { // nano clock is not guaranteed to be monotonic. So // lets record it as zero, so we can at least count. if (durationNanos < 0) { durationNanos = 0; } long d = NANOSECONDS.toMicros(durationNanos); int durationMicr...
@Test public void recordNanos() { recordNanos(0, 0); recordNanos(200, 0); recordNanos(TimeUnit.MICROSECONDS.toNanos(1), 0); recordNanos(TimeUnit.MICROSECONDS.toNanos(2), 1); recordNanos(TimeUnit.MICROSECONDS.toNanos(3), 1); recordNanos(TimeUnit.MICROSECONDS.toNanos...
public Object[][] getAllValuesInOrder() { return messages().stream() .map(this::valuesFrom) .toArray(Object[][]::new); }
@Test void getsValuesInOrder() { Object[] msg1Values = {"2015-01-01 01:00:00.000", "source-1"}; Object[] msg2Values = {"2015-01-02 01:00:00.000", "source-2"}; SimpleMessageChunk sut = simpleMessageChunk("timestamp,source", msg1Values, msg2Values ); ...
public static int MAXIM(@NonNull final byte[] data, final int offset, final int length) { return CRC(0x8005, 0x0000, data, offset, length, true, true, 0xFFFF); }
@Test public void MAXIM_123456789() { final byte[] data = "123456789".getBytes(); assertEquals(0x44C2, CRC16.MAXIM(data, 0, 9)); }
@Override public List<SmsReceiveRespDTO> parseSmsReceiveStatus(String text) { JSONArray statuses = JSONUtil.parseArray(text); // 字段参考 return convertList(statuses, status -> { JSONObject statusObj = (JSONObject) status; return new SmsReceiveRespDTO() ...
@Test public void testParseSmsReceiveStatus() { // 准备参数 String text = "[\n" + " {\n" + " \"user_receive_time\": \"2015-10-17 08:03:04\",\n" + " \"nationcode\": \"86\",\n" + " \"mobile\": \"13900000001\",\n" + ...
public synchronized String getDatabaseName() { return databaseName; }
@Test public void testGetDatabaseNameShouldReturnCorrectValue() { assertThat(testManager.getDatabaseName()).matches(TEST_ID + "-\\d{8}-\\d{6}-\\d{6}"); }
public static String subPath(String rootDir, File file) { try { return subPath(rootDir, file.getCanonicalPath()); } catch (IOException e) { throw new IORuntimeException(e); } }
@Test public void subPathTest2() { String subPath = FileUtil.subPath("d:/aaa/bbb/", "d:/aaa/bbb/ccc/"); assertEquals("ccc/", subPath); subPath = FileUtil.subPath("d:/aaa/bbb", "d:/aaa/bbb/ccc/"); assertEquals("ccc/", subPath); subPath = FileUtil.subPath("d:/aaa/bbb", "d:/aaa/bbb/ccc/test.txt"); assertEqu...
static String createPackageName(Class<?> cls) { return getPackageName(cls) + ".generated"; }
@Test public void testCreatePackageName() { assertEquals(AbiTypesGenerator.createPackageName(String.class), ("java.lang.generated")); }
@CanDistro @PutMapping(value = {"", "/instance"}) @Secured(action = ActionTypes.WRITE) public Result<String> update(UpdateHealthForm updateHealthForm) throws NacosException { updateHealthForm.validate(); healthOperatorV2.updateHealthStatusForPersistentInstance(updateHealthForm.getNamespaceId...
@Test void testUpdate() throws Exception { doNothing().when(healthOperatorV2).updateHealthStatusForPersistentInstance(TEST_NAMESPACE, NamingUtils.getGroupedName(updateHealthForm.getServiceName(), updateHealthForm.getGroupName()), TEST_CLUSTER_NAME, "123.123.123.123", 8888, tr...
public static Map<Integer, Map<RowExpression, VariableReferenceExpression>> collectCSEByLevel(List<? extends RowExpression> expressions) { if (expressions.isEmpty()) { return ImmutableMap.of(); } CommonSubExpressionCollector expressionCollector = new CommonSubExpressionCollector...
@Test void testCollectCSEByLevelCaseStatement() { List<RowExpression> expressions = ImmutableList.of(rowExpression("1 + CASE WHEN x = 1 THEN y + z WHEN x = 2 THEN z * 2 END"), rowExpression("2 + CASE WHEN x = 1 THEN y + z WHEN x = 2 THEN z * 2 END")); Map<Integer, Map<RowExpression, VariableRefe...
public Status currentStatus(FetchRequest request) { final DocumentStatus ds = fetchStatus(request); if (MUStatusType.ACTIEF == ds.getStatusMu() || ds.getDocType() == DocTypeType.NI) { switch (ds.getStatus()) { case GEACTIVEERD: return Status.ACTIVE; ...
@Test public void getIssuedStatusWithSuccesTest() throws Exception { final DocumentStatus dummyDocumentStatus = new DocumentStatus(); dummyDocumentStatus.setId(1L); dummyDocumentStatus.setDocType(DocTypeType.NL_RIJBEWIJS); dummyDocumentStatus.setPseudonym(pseudonym); dummyDoc...
@Bean @ConfigurationPropertiesBinding public StringToMatchTypeConverter stringToMatchTypeConverter() { return new StringToMatchTypeConverter(); }
@Test public void testStringToMatchTypeConverter() { contextRunner.withPropertyValues(PREFIX + ".repository=BUCKET4J_JCACHE") .run((context) -> assertThat(context).hasSingleBean(StringToMatchTypeConverter.class)); }
@Override public AppResponse process(Flow flow, AppSessionRequest request) { if (appSession.getRegistrationId() == null) { return new NokResponse(); } Map<String, String> result = digidClient.getExistingAccount(appSession.getRegistrationId(), appSession.getLanguage()); ...
@Test void processNOKMissingRegistrationTest(){ checkExistingAccount.getAppSession().setRegistrationId(null); AppResponse appResponse = checkExistingAccount.process(flowMock, null); assertTrue(appResponse instanceof NokResponse); assertEquals("NOK", ((NokResponse) appResponse).getS...
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { responseContext.getHeaders().add(X_FRAME_OPTIONS, (httpAllowEmbedding ? EmbeddingOptions.SAMEORIGIN : EmbeddingOptions.DENY).toString()); }
@Test void disallowsEmbeddingIfConfigurationSettingIsFalse() throws IOException { final EmbeddingControlFilter filter = new EmbeddingControlFilter(false); final ContainerResponseContext responseContext = new ContainerResponse(requestContext, Response.ok().build()); filter.filter(requestCont...
public static boolean isTotalCommentCounter(Counter counter) { String sceneValue = counter.getId().getTag(SCENE); if (StringUtils.isBlank(sceneValue)) { return false; } return TOTAL_COMMENT_SCENE.equals(sceneValue); }
@Test void isTotalCommentCounter() { MeterRegistry meterRegistry = new SimpleMeterRegistry(); Counter totalCommentCounter = MeterUtils.totalCommentCounter(meterRegistry, "posts.content.halo.run/fake-post"); assertThat(MeterUtils.isTotalCommentCounter(totalCommentCounter)).isTrue(...
@Override public Point calculatePositionForPreview( Keyboard.Key key, PreviewPopupTheme theme, int[] windowOffset) { Point point = new Point(key.x + windowOffset[0], windowOffset[1]); Rect padding = new Rect(); theme.getPreviewKeyBackground().getPadding(padding); point.offset((key.width / 2), ...
@Test public void testCalculatePositionForPreviewWithNoneExtendAnimation() throws Exception { mTheme.setPreviewAnimationType(PreviewPopupTheme.ANIMATION_STYLE_APPEAR); int[] offsets = new int[] {50, 60}; Point result = mUnderTest.calculatePositionForPreview(mTestKey, mTheme, offsets); Assert.assert...
public static List<SubscriptionItem> readFrom( final InputStream in, @Nullable final ImportExportEventListener eventListener) throws InvalidSourceException { if (in == null) { throw new InvalidSourceException("input is null"); } final List<SubscriptionItem> c...
@Test public void testInvalidSource() { final List<String> invalidList = Arrays.asList( "{}", "", null, "gibberish"); for (final String invalidContent : invalidList) { try { if (invalidContent != null) { ...
public static CloudConfiguration buildCloudConfigurationForStorage(Map<String, String> properties) { return buildCloudConfigurationForStorage(properties, false); }
@Test public void testAzureBlobCloudConfiguration() { Map<String, String> map = new HashMap<String, String>() { { put(CloudConfigurationConstants.AZURE_BLOB_SHARED_KEY, "XX"); put(CloudConfigurationConstants.AZURE_BLOB_CONTAINER, "XX"); put(CloudCo...
@Deprecated public DefaultMQPushConsumerImpl getDefaultMQPushConsumerImpl() { return defaultMQPushConsumerImpl; }
@Test public void testPullMessage_ExceptionOccursWhenComputePullFromWhere() throws MQClientException { final CountDownLatch countDownLatch = new CountDownLatch(1); final MessageExt[] messageExts = new MessageExt[1]; pushConsumer.getDefaultMQPushConsumerImpl().setConsumeMessageService( ...
public Model<T> reproduceFromProvenance() throws ClassNotFoundException { // Until now the object only holds the configuration for these objects, the following // functions will actually re-instantiate them. Trainer<T> newTrainer = recoverTrainer(); Dataset<T> newDataset = recoverDatas...
@Test public void testBaggingTrainerAllInvocationsChange() throws IOException, ClassNotFoundException { // This example has multiple trainers in the form of an ensemble, and all need to be set to the correct value CARTRegressionTrainer subsamplingTree = new CARTRegressionTrainer(Integer.MAX_VALUE, ...
public static CharSequence escapeCsv(CharSequence value) { return escapeCsv(value, false); }
@Test public void escapeCsvWithLineFeed() { CharSequence value = "some text\n more text"; CharSequence expected = "\"some text\n more text\""; escapeCsv(value, expected); }
public static BaseNCodec of(String alphabet) { return new BaseNCodec(alphabet); }
@Test void codec_generalizes_down_to_base_10() { var b10 = BaseNCodec.of("0123456789"); verifyRoundtrip(b10, unhex("00"), "0"); verifyRoundtrip(b10, unhex("000f"), "015"); verifyRoundtrip(b10, unhex("ffff"), "65535"); // A large prime number: 2^252 + 277423177773723535358519...
public void init() { try { ObjectName oName = new ObjectName(this.name + ":type=" + TaskManager.class.getSimpleName()); ManagementFactory.getPlatformMBeanServer().registerMBean(this, oName); } catch (Exception e) { LOGGER.error("registerMBean_fail", e); } ...
@Test void testInit() throws Exception { taskManager.init(); ObjectName oName = new ObjectName(TaskManagerTest.class.getName() + ":type=" + TaskManager.class.getSimpleName()); assertTrue(ManagementFactory.getPlatformMBeanServer().isRegistered(oName)); }
static String canonicalQueryString(Map<String, String> attributes) { List<String> components = getListOfEntries(attributes); Collections.sort(components); return canonicalQueryString(components); }
@Test public void canonicalQueryString() { // given Map<String, String> attributes = new HashMap<>(); attributes.put("second-attribute", "second-attribute+value"); attributes.put("attribute", "attribute+value"); attributes.put("name", "Name*"); // when String...
public CoordinatorResult<OffsetCommitResponseData, CoordinatorRecord> commitOffset( RequestContext context, OffsetCommitRequestData request ) throws ApiException { Group group = validateOffsetCommit(context, request); // In the old consumer group protocol, the offset commits maintai...
@Test public void testConsumerGroupOffsetCommitWithIllegalGenerationId() { OffsetMetadataManagerTestContext context = new OffsetMetadataManagerTestContext.Builder().build(); // Create an empty group. ConsumerGroup group = context.groupMetadataManager.getOrMaybeCreatePersistedConsumerGroup( ...
@Udf public String concat(@UdfParameter final String... jsonStrings) { if (jsonStrings == null) { return null; } final List<JsonNode> nodes = new ArrayList<>(jsonStrings.length); boolean allObjects = true; for (final String jsonString : jsonStrings) { if (jsonString == null) { ...
@Test public void shouldReturnNullIfArgumentIsNull() { assertNull(udf.concat(null)); }
public Rating getRatingForDensity(double value) { return ratingBounds.entrySet().stream() .filter(e -> e.getValue().match(value)) .map(Map.Entry::getKey) .findFirst() .orElseThrow(() -> new IllegalArgumentException(format("Invalid value '%s'", value))); }
@Test public void density_matching_exact_grid_values() { assertThat(ratingGrid.getRatingForDensity(0.1)).isEqualTo(A); assertThat(ratingGrid.getRatingForDensity(0.2)).isEqualTo(B); assertThat(ratingGrid.getRatingForDensity(0.5)).isEqualTo(C); assertThat(ratingGrid.getRatingForDensity(1)).isEqualTo(D);...
@Override public void getConfig(RuleBasedFilterConfig.Builder builder) { Set<String> hostNames = endpoints.stream() .flatMap(e -> e.names().stream()) .collect(Collectors.toCollection(() -> new LinkedHashSet<>())); if(hostNames.size() > 0) { Collection<Stri...
@Test void does_not_setup_blocking_rule_when_endpoints_empty() { var filter = new BlockFeedGlobalEndpointsFilter(Set.of(), true); var config = getConfig(filter); assertEquals(0, config.rule().size()); }
@Override public List<Node> sniff(List<Node> nodes) { if (attribute == null || value == null) { return nodes; } return nodes.stream() .filter(node -> nodeMatchesFilter(node, attribute, value)) .collect(Collectors.toList()); }
@Test void returnsNodesMatchingGivenFilter() throws Exception { final List<Node> nodes = mockNodes(); final NodesSniffer nodesSniffer = new FilteredElasticsearchNodesSniffer("rack", "42"); assertThat(nodesSniffer.sniff(nodes)).containsExactly(nodeOnRack42); }
public static <T> void concat(T[] sourceFirst, T[] sourceSecond, T[] dest) { System.arraycopy(sourceFirst, 0, dest, 0, sourceFirst.length); System.arraycopy(sourceSecond, 0, dest, sourceFirst.length, sourceSecond.length); }
@Test(expected = NullPointerException.class) public void concat_whenDestNull() { Integer[] first = new Integer[]{1, 2, 3}; Integer[] second = new Integer[]{4}; Integer[] concatenated = null; ArrayUtils.concat(first, second, concatenated); fail(); }
public ManagedChannel get(WindmillServiceAddress windmillServiceAddress) { return channelCache.getUnchecked(windmillServiceAddress); }
@Test public void testLoadingCacheReturnsLoadsChannelWhenNotPresent() { String channelName = "existingChannel"; ManagedChannel channel = newChannel(channelName); Function<WindmillServiceAddress, ManagedChannel> channelFactory = spy( new Function<WindmillServiceAddress, ManagedChannel>(...
public static ProxyBackendHandler newInstance(final SQLStatementContext sqlStatementContext, final String sql, final ConnectionSession connectionSession) { TCLStatement tclStatement = (TCLStatement) sqlStatementContext.getSqlStatement(); if (tclStatement instanceof BeginTransactionStatement || tclStatem...
@Test void assertBroadcastBackendHandlerReturnedWhenTCLStatementNotHit() { SQLStatementContext context = mock(SQLStatementContext.class); when(context.getSqlStatement()).thenReturn(mock(TCLStatement.class)); DatabaseConnectorFactory mockFactory = mock(DatabaseConnectorFactory.class); ...
@VisibleForTesting static Map<String, String> generatePostfix(Set<java.nio.file.Path> pathKeys) { Map<String, String> rawPathToMethodVer = new HashMap<>(); for (java.nio.file.Path path : pathKeys) { java.nio.file.Path firstLevel = path.subpath(0, 1); String version = isVersion(firstLevel.toString...
@Test public void testRawPathMapping() { // Following are the actual exhausted list of paths in Tables services at version Set<String> paths = new HashSet<>(); paths.add("/v0/databases"); paths.add("/v0.9/databases"); paths.add("/v1/databases"); paths.add("/databases"); paths.add("/databas...
public boolean isEnable() { return rpcClient.isRunning(); }
@Test void testIsEnable() { when(this.rpcClient.isRunning()).thenReturn(true); assertTrue(client.isEnable()); verify(this.rpcClient, times(1)).isRunning(); }
public static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register) { Map<String, Map<String, String>> newRegister = new HashMap<>(); for (Map.Entry<String, Map<String, String>> entry : register.entrySet()) { String serviceName = entry.getKey(); ...
@Test void testRevertRegister() { String key = "perf/dubbo.test.api.HelloService:1.0.0"; Map<String, Map<String, String>> register = new HashMap<String, Map<String, String>>(); Map<String, String> service = new HashMap<String, String>(); service.put("dubbo://127.0.0.1:20880/com.xxx.X...
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") @PostMapping(value = "/api/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public TbResourceInfo uploadImage(@RequestPart MultipartFile file, @RequestPart(required = false) String title, ...
@Test public void testUploadImageWithSameFilename() throws Exception { String filename = "my_jpeg_image.jpg"; TbResourceInfo imageInfo1 = uploadImage(HttpMethod.POST, "/api/image", filename, "image/jpeg", JPEG_IMAGE); assertThat(imageInfo1.getTitle()).isEqualTo(filename); assertThat(...
public boolean performCrashDetectingFlow() { final File newCrashFile = new File(mApp.getFilesDir(), NEW_CRASH_FILENAME); if (newCrashFile.isFile()) { String ackReportFilename = getAckReportFilename(); StringBuilder header = new StringBuilder(); StringBuilder report = new StringBuilder(); ...
@Test public void testCallsDetectedIfPreviouslyCrashed() throws Exception { Context app = ApplicationProvider.getApplicationContext(); var notificationDriver = Mockito.mock(NotificationDriver.class); var notificationBuilder = Mockito.mock(NotifyBuilder.class); Mockito.doReturn(notificationBuilder) ...