@Test public void createAlternateRowsDocument() throws Exception { final PDDocument document = new PDDocument(); final PDPage page = new PDPage(PDRectangle.A4); page.setRotation(90); document.addPage(page); final PDPageContentStream contentStream = new PDPageContentStream(document, page); // TODO replace deprecated method call contentStream.concatenate2CTM(0, 1, -1, 0, page.getMediaBox().getWidth(), 0); final float startY = page.getMediaBox().getWidth() - 30; (new TableDrawer(contentStream, createAndGetTableWithAlternatingColors(), 30, startY)).draw(); contentStream.close(); document.save("target/alternateRows.pdf"); document.close(); }
@Test public void importJobsTest() throws Exception { List<AssetImportJob> importJobs = apiClient.getAssetImportApi().getAssetImportJobs(); assertNotNull(importJobs); for (AssetImportJob job : importJobs) { assertImportJobFields( job ); } // Retreive asset import job by job id if ( importJobs.size() > 0 ) { AssetImportJob importJob = apiClient.getAssetImportApi().getAssetImportJob( importJobs.get( 0 ).getJobId() ); assertNotNull( importJob ); assertImportJobFields( importJob ); } }
@Test(expected = BadRequestException.class) public void testFormFailsIfRequiredStringIsNotString() { Builder<Map<String, Object>> builder = new Builder<>(emptyList()); Form<Map<String, Object>> form = builder.title( __ -> "title" ).description( __ -> "description" ).constructor( HashMap::new ).addRequiredString( "long1", (map, string) -> map.put("l1", string) ).build(); form.get(_body); }
@Test public void testCancel_BuyLimit_1_Failed_for_PriceNotMatch() throws Exception { // cancel: sendOrders("100 cancel_buy_limit 003 2699.88"); // check ticks: assertTicks(); // check order books: assertOrderBook( // seq type price amount "001 sell 2703.33 4.4444", // "006 sell 2702.22 3.3333", // "002 sell 2702.22 2.2222", // "004 sell 2701.11 1.1111", // // ----------------------------------- "003 buy 2699.99 0.1111", // "005 buy 2688.88 2.2222", // "007 buy 2688.88 2.2222", // "009 buy 2666.66 4.4444" // ); }
@Test public void manageDeletionProcess_VSERVERS_STOPPING_NextStatusNotNormal() throws Exception { // given doReturn(Boolean.TRUE).when(vSystemProcessor.vsysComm) .getCombinedVServerState(paramHandler, VServerStatus.STOPPED); doReturn(Boolean.FALSE).when(vSystemProcessor).checkNextStatus( CONTROLLER_ID, INSTANCE_ID, FlowState.VSYSTEM_DELETING, paramHandler); // when FlowState newState = vSystemProcessor.manageDeletionProcess( CONTROLLER_ID, INSTANCE_ID, paramHandler, FlowState.VSERVERS_STOPPING); // then assertNull(newState); }
@Test public void testFetchGenesOnRegion() throws IOException, ExternalDbUnavailableException, InterruptedException { // arrange String fetchRes = readFile("ensembl_overlap_gene.json"); Mockito.when( httpDataManager.fetchData(Mockito.any(), Mockito.any(ParameterNameValue[].class)) ).thenReturn(fetchRes); // act List<EnsemblEntryVO> ensemblGeneList = ensemblDataManager.fetchVariationsOnRegion("human", "140424943", "140624564", "7"); // assert Assert.assertNotNull(ensemblGeneList); Assert.assertEquals(6, ensemblGeneList.size()); EnsemblEntryVO ensemblEntryVO = ensemblGeneList.get(0); Assert.assertNotNull(ensemblEntryVO); Assert.assertTrue(ensemblEntryVO.getStart().equals(START_ENTRY)); Assert.assertTrue(ensemblEntryVO.getEnd().equals(END_ENTRY)); }
@Test public void testConvertToIdsList() { // Test data final SearchResponse searchResponse = createMock(SearchResponse.class); final SearchHits searchHits = createMock(SearchHits.class); final SearchHit searchHit1 = createMock(SearchHit.class); final SearchHit searchHit2 = createMock(SearchHit.class); final SearchHit[] searchHitsArray = new SearchHit[]{searchHit1, searchHit2}; final String searchHit1Id = "search hit 1 id"; final String searchHit2Id = "search hit 1 id"; // Reset resetAll(); // Expectations expect(searchResponse.getHits()).andReturn(searchHits); expect(searchHits.getHits()).andReturn(searchHitsArray); expect(searchHit1.getId()).andReturn(searchHit1Id); expect(searchHit2.getId()).andReturn(searchHit2Id); // Replay replayAll(); // Run test scenario final List<String> response = searchResponseComponent.convertToIdsList(searchResponse); // Verify verifyAll(); assertEquals(Arrays.asList(searchHit1Id, searchHit2Id), response); }
/** * Tests the execution of a diamond query with types. */ @Test public void testDiamondQueryWithTypes() throws Exception { // Initialize the {@code TypeStore} with types used in the MATCH query. TypeAndPropertyKeyStore.getInstance().mapStringTypeToShortOrInsert("FOLLOWS"); TypeAndPropertyKeyStore.getInstance().mapStringTypeToShortOrInsert("LIKES"); //Create a one time MATCH query plan for a simple diamond pattern with types. StructuredQuery diamondStructuredQuery = new StructuredQueryParser().parse("MATCH (a)" + "-[:FOLLOWS]->(b),(a)-[:FOLLOWS]->(c),(b)-[:LIKES]->(d),(c)-[:LIKES]->(d)"); Integer[][] expectedMotifsAfterAdditions = {{0, 1, 1, 0}, {0, 1, 1, 4}, {3, 0, 0, 1}, {3, 0, 4, 1}, {3, 4, 0, 1}, {3, 4, 4, 1}, {3, 4, 4, 3}, {4, 1, 1, 0}, {4, 1, 1, 4}}; Integer[][] expectedMotifsAfterDeletion = {{3, 0, 0, 1}, {3, 0, 4, 1}, {3, 4, 0, 1}, {3, 4, 4, 1}, {3, 4, 4, 3}, {4, 1, 1, 0}, {4, 1, 1, 4}}; String[] headers = {"a", "b", "c", "d"}; assertComplexMatchQueryOutput(diamondStructuredQuery, constructSubgraphsQueryResult( expectedMotifsAfterAdditions, headers), constructSubgraphsQueryResult( expectedMotifsAfterDeletion, headers)); }
@Test public void testClose() { // create dynamic routing DynamicRoutingManager dynamicRoutingManager = new DynamicRoutingManager( "NAME", "GROUP", PropertyFactory.PREFIX, properties ); // close connection dynamicRoutingManager.close(); // verify all close methods have been called verify(publicationObserver, times(1)).close(); verify(subscriptionObserver, times(1)).close(); verify(dynamicPartitionObserver, times(1)).close(); verify(dynamicPartitionCommander, times(1)).close(); verify(domainParticipantAdministration, times(1)).delete_contained_entities(); verify(domainParticipantFactory, times(1)).delete_participant(domainParticipantAdministration); verify(domainParticipantDiscovery, times(1)).delete_contained_entities(); verify(domainParticipantFactory, times(1)).delete_participant(domainParticipantDiscovery); }
@Test(timeout=180000) public void testLosingFileAfterScannerInit() throws Exception { assertEquals(rowCount, fullScanAndCount(TEST_TABLE.getTableName())); final FileSystem fs = getFileSystem(); final Path tmpStoreFilePath = new Path(UTIL.getDataTestDir(), "corruptedHFile"); // try to query with the missing file int count = fullScanAndCount(TEST_TABLE.getTableName(), new ScanInjector() { private boolean hasFile = true; @Override public void beforeScan(Table table, Scan scan) throws Exception { // move the path away (now the region is corrupted) if (hasFile) { fs.copyToLocalFile(true, storeFiles.get(0), tmpStoreFilePath); LOG.info("Move file to local"); evictHFileCache(storeFiles.get(0)); hasFile = false; } } }); assertTrue("expected one file lost: rowCount=" + count + " lostRows=" + (NUM_ROWS - count), count >= (NUM_ROWS - ROW_PER_FILE)); }
/** * Tests the execution of "list member" command, when no cache is created * * @throws IOException * @throws ClassNotFoundException */ @Test public void testListMemberWithNoCache() throws IOException, ClassNotFoundException { final Host host = Host.getHost(0); final VM[] servers = {host.getVM(0), host.getVM(1)}; final int openPorts[] = AvailablePortHelper.getRandomAvailableTCPPorts(1); final File logFile = new File(getUniqueName() + "-locator" + openPorts[0] + ".log"); Locator locator = Locator.startLocator(openPorts[0], logFile); try { final Properties props = createProperties(host, openPorts[0]); CommandProcessor commandProcessor = new CommandProcessor(); Result result = commandProcessor.createCommandStatement(CliStrings.LIST_MEMBER, EMPTY_ENV).process(); getLogWriter().info("#SB" + getResultAsString(result)); assertEquals(true, result.getStatus().equals(Status.ERROR)); } finally { locator.stop(); // fix for bug 46562 } }
@Test public void xirr_issue_from_node_js_version() { double rate = new Xirr( new Transaction(-10000, "2000-05-24"), new Transaction(3027.25, "2000-06-05"), new Transaction(630.68, "2001-04-09"), new Transaction(2018.2, "2004-02-24"), new Transaction(1513.62, "2005-03-18"), new Transaction(1765.89, "2006-02-15"), new Transaction(4036.33, "2007-01-10"), new Transaction(4036.33, "2007-11-14"), new Transaction(1513.62, "2008-12-17"), new Transaction(1513.62, "2010-01-15"), new Transaction(2018.16, "2011-01-14"), new Transaction(1513.62, "2012-02-03"), new Transaction(1009.08, "2013-01-18"), new Transaction(1513.62, "2014-01-24"), new Transaction(1513.62, "2015-01-30"), new Transaction(1765.89, "2016-01-22"), new Transaction(1765.89, "2017-01-20"), new Transaction(22421.55, "2017-06-05") ).xirr(); assertEquals(0.2126861, rate, TOLERANCE); }
@Test public void testScoredSortedSetEntryRange() { RScoredSortedSetReactive<String> set = redisson.<String>getScoredSortedSet("simple"); sync(set.add(0, "a")); sync(set.add(1, "b")); sync(set.add(2, "c")); sync(set.add(3, "d")); sync(set.add(4, "e")); Collection<ScoredEntry<String>> r = sync(set.entryRange(1, true, 4, false, 1, 2)); ScoredEntry<String>[] a = r.toArray(new ScoredEntry[0]); Assert.assertEquals(2d, a[0].getScore(), 0); Assert.assertEquals(3d, a[1].getScore(), 0); Assert.assertEquals("c", a[0].getValue()); Assert.assertEquals("d", a[1].getValue()); }
@Test public void requestMaxStaleDirectiveWithNoValue() throws IOException { // Add a stale response to the cache. server.enqueue(new MockResponse() .setBody("A") .addHeader("Cache-Control: max-age=120") .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES))); server.enqueue(new MockResponse() .setBody("B")); assertEquals("A", readAscii(openConnection(server.url("/").url()))); // With max-stale, we'll return that stale response. URLConnection maxStaleConnection = openConnection(server.url("/").url()); maxStaleConnection.setRequestProperty("Cache-Control", "max-stale"); assertEquals("A", readAscii(maxStaleConnection)); assertEquals("110 HttpURLConnection \"Response is stale\"", maxStaleConnection.getHeaderField("Warning")); }
@Test public void testAddsBitmapsToBitmapPoolIfMemoryCacheIsFull() { Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); when(cache.getMaxSize()).thenReturn(0); PreFillType size = new PreFillType.Builder(bitmap.getWidth(), bitmap.getHeight()).setConfig(bitmap.getConfig()) .build(); Map<PreFillType, Integer> allocationOrder = new HashMap<>(); allocationOrder.put(size, 1); getHandler(allocationOrder).run(); verify(cache, never()).put(any(Key.class), anyResource()); // TODO(b/20335397): This code was relying on Bitmap equality which Robolectric removed // verify(pool).put(eq(bitmap)); // assertThat(addedBitmaps).containsExactly(bitmap); }
@Test public void testRemoveDefaultAclOnlyAccess() throws Exception { fs.create(path).close(); fs.setPermission(path, FsPermission.createImmutable((short)0640)); List<AclEntry> aclSpec = Lists.newArrayList( aclEntry(ACCESS, USER, ALL), aclEntry(ACCESS, USER, "foo", ALL), aclEntry(ACCESS, GROUP, READ_EXECUTE), aclEntry(ACCESS, OTHER, NONE)); fs.setAcl(path, aclSpec); fs.removeDefaultAcl(path); AclStatus s = fs.getAclStatus(path); AclEntry[] returned = s.getEntries().toArray(new AclEntry[0]); assertArrayEquals(new AclEntry[] { aclEntry(ACCESS, USER, "foo", ALL), aclEntry(ACCESS, GROUP, READ_EXECUTE) }, returned); assertPermission((short)010770); assertAclFeature(true); // restart of the cluster restartCluster(); s = fs.getAclStatus(path); AclEntry[] afterRestart = s.getEntries().toArray(new AclEntry[0]); assertArrayEquals(returned, afterRestart); }
@Test public void eth_compileSolidityWithoutSolidity() throws Exception { SystemProperties systemProperties = Mockito.mock(SystemProperties.class); String solc = System.getProperty("solc"); if(StringUtils.isEmpty(solc)) solc = "/usr/bin/solc"; Mockito.when(systemProperties.customSolcPath()).thenReturn(solc); Wallet wallet = WalletFactory.createWallet(); Ethereum eth = Web3Mocks.getMockEthereum(); WorldManager worldManager = Web3Mocks.getMockWorldManager(); EthModule ethModule = new EthModule(ConfigHelper.CONFIG, eth, new EthModuleSolidityDisabled(), new EthModuleWalletEnabled(ConfigHelper.CONFIG, eth, wallet, null)); Web3Impl web3 = new Web3RskImpl(eth, worldManager, ConfigHelper.CONFIG, null, null, new PersonalModuleWalletDisabled(), ethModule, Web3Mocks.getMockChannelManager(), Web3Mocks.getMockRepository(), null, null, null, null); String contract = "pragma solidity ^0.4.1; contract rsk { function multiply(uint a) returns(uint d) { return a * 7; } }"; Map<String, CompilationResultDTO> result = web3.eth_compileSolidity(contract); org.junit.Assert.assertNotNull(result); org.junit.Assert.assertEquals(0, result.size()); }
@Test public void choiceStateWithAndCondition() { final StateMachine stateMachine = stateMachine() .startAt("InitialState") .state("InitialState", choiceState() .defaultStateName("DefaultState") .choice(choice().transition(next("NextState")) .condition( and(eq("$.var", "value"), eq("$.other-var", 10) )))) .state("NextState", succeedState()) .state("DefaultState", succeedState()) .build(); assertStateMachine(stateMachine, "ChoiceStateWithAndCondition.json"); }
/** * User must have "MARKETPLACE_OWNER" role */ @Test(expected = EJBAccessException.class) public void saveEnterpriseLandingpageConfig_invalidRole() throws Throwable { // given wrong role String invalidRole = UserRoleType.ORGANIZATION_ADMIN.name(); container.login(mpOwnerUserKey, invalidRole); // when saving, then exception must be thrown try { landingpageServiceLocal .saveEnterpriseLandingpageConfig(MARKETPLACEID); } catch (EJBException e) { throw e.getCause(); } }
@Test public void shouldReturnValidationMessageForAgeMoreThan150() { //given LocalDate over150Years = LocalDate.now().minusYears(151); Individual claimant = SampleParty.builder() .withDateOfBirth(over150Years) .individual(); //when Set<String> errors = validate(claimant); //then assertThat(errors) .hasSize(1) .contains("dateOfBirth : Age must be between 18 and 150"); }
@Test public void testInterpretByArray() { Variable var = new Variable("s1.ip"); Context s1Ip = mock(Context.class); when(s1Ip.getValue(var)).thenReturn("192.168.10.1"); Equal equal = new Equal(); equal.setVariable(var); HashSet<Value> list = new HashSet<Value>(); list.add(new Number(new BigDecimal("4"))); list.add(new MyString("192.168.1.1")); equal.setValue(new Array(list)); assertFalse("The s1.ip (string) equals 192.168.1.1", equal.interpret(s1Ip)); list = new HashSet<Value>(); list.add(new Number(new BigDecimal("4"))); list.add(new MyString("192.168.1.1")); list.add(new MyString("192.168.10.1")); equal.setValue(new Array(list)); assertTrue("The s1.ip (string) equals 192.168.10.1", equal.interpret(s1Ip)); }
@Test public void testBuyLimit_SamePrice_Just_FullyFilled_All_Sells() throws Exception { // buy: sendOrders("100 buy_limit 2703.33 11.1110"); // check ticks: assertTicks( // "2701.11 1.1111", // "2702.22 2.2222", // "2702.22 3.3333", // "2703.33 4.4444"); // check order books: assertOrderBook( // seq type price amount // ----------------------------------- "003 buy 2699.99 0.1111", // "005 buy 2688.88 2.2222", // "007 buy 2688.88 2.2222", // "009 buy 2666.66 4.4444" // ); }
@Test public void step08_ClientCreateFiberTableTest() { StatusProto.ResponseStatus expect = StatusProto.ResponseStatus.newBuilder().setStatus(StatusProto.ResponseStatus.State.STATUS_OK).build(); ArrayList<String> columnName = new ArrayList<>(); columnName.add("smell"); columnName.add("color"); columnName.add("feel"); ArrayList<String> columnType = new ArrayList<>(); columnType.add("regular"); columnType.add("regular"); columnType.add("regular"); ArrayList<String> dataType = new ArrayList<>(); dataType.add("varchar(20)"); dataType.add("varchar(20)"); dataType.add("varchar(20)"); StatusProto.ResponseStatus status = client.createFiberTable("fruit", "grip", "alice", "StorageFormatName", 0, "FuncName", 1, columnName, dataType); assertEquals(expect, status); }
@Test(expected = FormatException.class) public void testFormatExceptionIfAckIsTooLarge() throws Exception { byte[] b = createAck(true); ByteArrayInputStream in = new ByteArrayInputStream(b); RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in); reader.readAck(); }
@Test public void testConstructor_withValidBuilder() { final ButtonBuilder builder = new ButtonBuilder(); builder.setText("Testing"); builder.setOnClickFunction(function); new Button(builder); }
@Test public void move_artifacts_to_target_directory() throws Exception { final Path storePath = temporaryFolder.newFolder("artifacts_store").toPath(); final LocalArtifactStore store = new LocalArtifactStore(storePath); final Future<URI> artifact = store.save(temporaryFolder.newFile("artifact").toPath()); assertEquals(storePath, Paths.get(artifact.get().getPath()).getParent().getParent()); }
@Test // decrypt cpp data public void test1(){ BigInteger privKey = new BigInteger("5e173f6ac3c669587538e7727cf19b782a4f2fda07c1eaa662c593e5e85e3051", 16); byte[] cipher = Hex.decode("049934a7b2d7f9af8fd9db941d9da281ac9381b5740e1f64f7092f3588d4f87f5ce55191a6653e5e80c1c5dd538169aa123e70dc6ffc5af1827e546c0e958e42dad355bcc1fcb9cdf2cf47ff524d2ad98cbf275e661bf4cf00960e74b5956b799771334f426df007350b46049adb21a6e78ab1408d5e6ccde6fb5e69f0f4c92bb9c725c02f99fa72b9cdc8dd53cff089e0e73317f61cc5abf6152513cb7d833f09d2851603919bf0fbe44d79a09245c6e8338eb502083dc84b846f2fee1cc310d2cc8b1b9334728f97220bb799376233e113"); byte[] payload = new byte[0]; try { payload = ECIESCoder.decrypt(privKey, cipher); } catch (Throwable e) {e.printStackTrace();} Assert.assertEquals("802b052f8b066640bba94a4fc39d63815c377fced6fcb84d27f791c9921ddf3e9bf0108e298f490812847109cbd778fae393e80323fd643209841a3b7f110397f37ec61d84cea03dcc5e8385db93248584e8af4b4d1c832d8c7453c0089687a700", Hex.toHexString(payload)); }
@Test public void testGetAdditionalKeys() { a.setProperty("xxx", "X-Value"); a.setProperty("yyy", "Y-Value"); a.setProperty("zzz", "Z-Value"); b.setProperty("aaa", "A-Value"); b.setProperty("bbb", "B-Value"); b.setProperty("xxx", "X-Value"); b.setProperty("yyy", "Y-Value"); b.setProperty("zzz", "Z-Value"); final PropertiesComparator comp = new PropertiesComparator(a, b); assertEquals(set("aaa", "bbb"), comp.getAdditionalKeys()); }
@Test public void haveFullyQualifiedName() { List<JavaClass> classes = filterClassesAppearingInFailureReport( classes().should().onlyBeAccessed().byClassesThat().haveFullyQualifiedName(Foo.class.getName())) .on(ClassAccessedByFoo.class, Foo.class, ClassAccessedByBar.class, Bar.class, ClassAccessedByBaz.class, Baz.class); assertThatClasses(classes).matchInAnyOrder( ClassAccessedByBar.class, Bar.class, ClassAccessedByBaz.class, Baz.class); }
@Test public void getNameTest() { LiBaseModelImpl.LiString name = new LiBaseModelImpl.LiString(); name.setValue(this.NAME); liRanking.setName(name); assertEquals(NAME, liRanking.getName()); assertTrue(liRanking.getNameAsLithiumString() instanceof LiBaseModelImpl.LiString); assertEquals(NAME, liRanking.getNameAsLithiumString().getValue()); }
@Test public void test () throws SQLException { String url = "jdbc:presto://presto00:8080/hive/rainbow"; Connection connection = DriverManager.getConnection(url, "test", null); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select count(*) from orc"); while (resultSet.next()) { System.out.println(resultSet.getInt(1)); } }
@Test public void testIsDateLessOrEqual() { Date date1 = new Date(); Date date2 = DateHelper.addDays(date1, 1); Date date3 = new Date(date1.getTime() + 1); Assert.assertTrue("Davor", DateHelper.isDateLessOrEqual(date1, date2)); Assert.assertFalse("Danach", DateHelper.isDateLessOrEqual(date2, date1)); Assert.assertTrue("Gleich", DateHelper.isDateLessOrEqual(date1, date1)); Assert.assertTrue("Gleich", DateHelper.isDateLessOrEqual(date1, date3)); }
@Test public void edgesConnecting_parallelEdges() { assertTrue(addEdge(N1, N2, E12)); assertTrue(addEdge(N1, N2, E12_A)); assertThat(network.edgesConnecting(N1, N2)).containsExactly(E12, E12_A); // Passed nodes should be in the correct edge direction, first is the // source node and the second is the target node assertThat(network.edgesConnecting(N2, N1)).isEmpty(); }
@Test public void testFindOne() throws Exception { when(productRepository.findOne(1L)).thenReturn(buildPersistentProduct()); mvc.perform(MockMvcRequestBuilders.get("/product/{productId}", 1L) .contentType(MediaType.APPLICATION_JSON) .content(PRODUCT_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content() .json("{}")); }
@Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.mobiledev.fontutils.test", appContext.getPackageName()); }
@Test public void oreillyHomeOffice() { Optional<Site> optionalSite = service.getLatLng("O'Reilly Media", "1005 Gravenstein Hwy N", "Sebastopol", "CA"); if (optionalSite.isPresent()) { Site site = optionalSite.get(); logger.info(site::toString); assertEquals(38.412, site.getLatitude(), 0.01); assertEquals(-122.841, site.getLongitude(), 0.01); } }
@Test public void initOK() throws Exception { Init init = new Init(config); File initPath = folder.newFolder("init"); init.run(initPath, rootPath, "freemarker"); File testFile = new File(initPath, "testfile.txt"); assertThat(testFile).exists(); }
@Test public void testMixedConstraints() { DeviceTestUtils.setCharging(context, false); DeviceTestUtils.setDeviceIdle(context, false); DeviceTestUtils.setNetworkInfo(context, false, false, false); PersistableBundle extras = new PersistableBundle(); extras.putLong(NoopAsyncJobService.EXTRA_DELAY, 2000); jobStore.add(JobStatus.createFromJobInfo( JobCreator.create(context, 0, DELAY_MS) .setRequiresCharging(true) .setRequiresDeviceIdle(true) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) .setMinimumLatency(LATENCY_MS) .build(), AlarmScheduler.TAG)); service.startCommand(0, 0); assertBoundServiceCount(0); DeviceTestUtils.setCharging(context, true); service.startCommand(0, 0); assertBoundServiceCount(0); DeviceTestUtils.setDeviceIdle(context, true); service.startCommand(0, 0); assertBoundServiceCount(0); DeviceTestUtils.setNetworkInfo(context, true, false, true); service.startCommand(0, 0); assertBoundServiceCount(0); DeviceTestUtils.advanceTime(LATENCY_MS); service.startCommand(0, 0); assertBoundServiceCount(1); }
/** * Test JSON serialisation and de-serialisation of Aggregations and Items. */ @Test public void testJsonSerialisationOfItem() throws IOException { LOG.info("testJsonSerialisationOfItem start"); // Create an Item String name = "myname"; String description = "My description"; String logicalId = "/providers/test/items/item"; String projectId = "project1"; String deviceName = "/dev/null"; ItemType it = new OsInstanceType(provider); it.setId(it.getLocalId()); TestTypeInstance item = new TestTypeInstance(logicalId, name, projectId, deviceName, it); TestTypeInstanceAttributes core = item.getCore(); core.setItemName(name); core.setItemDescription(description); item.setCore(core); item.setFibreCreated(new Date()); // Convert to JSON String itemJson = toJson(item); assertNotNull("Json of item was null", itemJson); LOG.info("testJsonSerialisationOfItem serialised Item json = " + itemJson); LOG.info("testJsonSerialisationOfItem serialised Item hashCode = " + item.hashCode()); // Get it back again Item recoveredItem = fromJson(itemJson, TestTypeInstance.class); LOG.info("testJsonSerialisationOfItem recovered Item = " + recoveredItem); LOG.info("testJsonSerialisationOfItem recovered Item hashCode = " + recoveredItem.hashCode()); LOG.info("testJsonSerialisationOfItem recovered Item json = " + toJson(recoveredItem)); assertNotNull("Recovered item was null", recoveredItem); assertEquals("Recovered item not same as original ", item, recoveredItem); assertNotNull("Recovered item did not have created date set", recoveredItem.getFibreCreated()); LOG.info("testJsonSerialisationOfItem end"); }
@Test public void getUser() throws IOException, InterruptedException { enqueueResponse("user-yigit.json"); User yigit = getValue(service.getUser("yigit")).body; RecordedRequest request = mockWebServer.takeRequest(); assertThat(request.getPath(), is("/users/yigit")); assertThat(yigit, notNullValue()); assertThat(yigit.avatarUrl, is("https://avatars3.githubusercontent.com/u/89202?v=3")); assertThat(yigit.company, is("Google")); assertThat(yigit.blog, is("birbit.com")); }