@Test public void testContinueOnSomeDbDirectoriesMissing() throws Exception { File targetDir1 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); File targetDir2 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); try { assertTrue(targetDir1.mkdirs()); assertTrue(targetDir2.mkdirs()); if (!targetDir1.setWritable(false, false)) { System.err.println( "Cannot execute 'testContinueOnSomeDbDirectoriesMissing' because cannot mark directory non-writable"); return; } RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(TEMP_URI); rocksDbBackend.setDbStoragePaths(targetDir1.getAbsolutePath(), targetDir2.getAbsolutePath()); try { rocksDbBackend.initializeForJob(getMockEnvironment(), "foobar", IntSerializer.INSTANCE); } catch (Exception e) { e.printStackTrace(); fail("Backend initialization failed even though some paths were available"); } } finally { //noinspection ResultOfMethodCallIgnored targetDir1.setWritable(true, false); FileUtils.deleteDirectory(targetDir1); FileUtils.deleteDirectory(targetDir2); } }
private void _add(Object pojo) { if (tempPath == null) tempPath = "data" + File.separator + key; if (tempFile == null) { tempFile = "" + UUID.randomUUID(); } // 创建一个lock文件 File lockFile = FileUtil.openFile(tempPath, tempFile + ".lock"); // 将文件加锁 FileLock fileLock = FileUtil.tryLockFile(lockFile); if (fileLock == null) { tempFile = "" + UUID.randomUUID(); lockFile = FileUtil.openFile(tempPath, tempFile + ".lock"); fileLock = FileUtil.tryLockFile(lockFile); } // 将temp文件打开 File file = FileUtil.openFile(tempPath, tempFile + ".data"); FileUtil.writeObjectToFile(pojo, file, true); // 存储完毕,将文件解锁 FileUtil.unlockFile(fileLock); objListSize++; }
/** Make sure we can get a valid SAMLContextProvider. */ @Test public void canGetContextProvider() { final SAMLProperties properties = Mockito.mock(SAMLProperties.class); Mockito.when(properties.getLoadBalancer()).thenReturn(null); SAMLContextProvider provider = this.config.contextProvider(properties); Assert.assertNotNull(provider); Assert.assertFalse(provider instanceof SAMLContextProviderLB); final SAMLProperties.LoadBalancer loadBalancer = new SAMLProperties.LoadBalancer(); final String scheme = UUID.randomUUID().toString(); loadBalancer.setScheme(scheme); final String serverName = UUID.randomUUID().toString(); loadBalancer.setServerName(serverName); final int port = 443; loadBalancer.setServerPort(port); final String contextPath = UUID.randomUUID().toString(); loadBalancer.setContextPath(contextPath); Mockito.when(properties.getLoadBalancer()).thenReturn(loadBalancer); provider = this.config.contextProvider(properties); Assert.assertNotNull(provider); Assert.assertTrue(provider instanceof SAMLContextProviderLB); }
@Test public void shouldFindCarsByExample() throws Exception { String uniqueColor = "unique-color-" + UUID.randomUUID().toString(); Car exampleCar = CarBuilder.aCar() .withManufacturer(UUID.randomUUID().toString()) .withColor(uniqueColor) .build(); saveNewCopiesOfCarToRepository(exampleCar, 10); Car secondExampleCar = CarBuilder.aCar() .withManufacturer(UUID.randomUUID().toString()) .withColor(uniqueColor) .build(); saveNewCopiesOfCarToRepository(secondExampleCar, 5); Car searchByManufacturerExampleCar = new Car(null, 0, exampleCar.getManufacturer(), null); List<Car> foundCars = carRepository.findByExample(searchByManufacturerExampleCar); assertThat(foundCars).isNotNull().hasSize(10); Car searchByColorExampleCar = new Car(null, 0, null, uniqueColor); List<Car> foundCarsByColor = carRepository.findByExample(searchByColorExampleCar); assertThat(foundCarsByColor).isNotNull().hasSize(15); Car searchByManufacturerAndColorExampleCar = new Car(null, 0, exampleCar.getManufacturer(), uniqueColor); List<Car> foundCarsByManufacturerAndColor = carRepository.findByExample(searchByManufacturerAndColorExampleCar); assertThat(foundCarsByManufacturerAndColor).isNotNull().hasSize(10); }
@Test public void shouldCountCarsWithFindCommand() throws Exception { String uniqueColorForTest = "color-shouldCountCarsWithFindCommand"; Car exampleCar = CarBuilder.aCar() .withManufacturer(UUID.randomUUID().toString()) .withColor(uniqueColorForTest) .build(); saveNewCopiesOfCarToRepository(exampleCar, 10); Car secondExampleCar = CarBuilder.aCar() .withManufacturer(UUID.randomUUID().toString()) .withColor(uniqueColorForTest) .build(); saveNewCopiesOfCarToRepository(secondExampleCar, 5); // Car searchByManufacturerExampleCar = new Car(null, 0, exampleCar.getManufacturer(), null); FindCommand<Car> findCommand = FindCommand.create(Car.class); findCommand.withSearchFilter("manufacturer", exampleCar.getManufacturer()); long foundCars = carRepository.findTotalItemCount(findCommand); assertThat(foundCars).isEqualTo(10); FindCommand<Car> findCommand2 = FindCommand.create(Car.class); findCommand2.withSearchFilter("color", uniqueColorForTest); long foundCarsByColor = carRepository.findTotalItemCount(findCommand2); assertThat(foundCarsByColor).isEqualTo(15); FindCommand<Car> findCommand3 = FindCommand.create(Car.class); findCommand3.withSearchFilter("manufacturer", exampleCar.getManufacturer()); findCommand3.withSearchFilter("color", uniqueColorForTest); long foundCarsByManufacturerAndColor = carRepository.findTotalItemCount(findCommand3); assertThat(foundCarsByManufacturerAndColor).isEqualTo(10); }
@Test public void answer() throws ObjectNotFoundException { UUID selfHelpGuideResponseId = UUID.randomUUID(); UUID selfHelpGuideQuestionId = UUID.randomUUID(); Boolean answerResponse = true; SelfHelpGuideResponse selfHelpGuideResponse = new SelfHelpGuideResponse(); SelfHelpGuideQuestion selfHelpGuideQuestion = new SelfHelpGuideQuestion(); expect(service.get(selfHelpGuideResponseId)).andReturn(selfHelpGuideResponse); expect(selfHelpGuideQuestionService.get(selfHelpGuideQuestionId)) .andReturn(selfHelpGuideQuestion); expect( service.answerSelfHelpGuideQuestion( selfHelpGuideResponse, selfHelpGuideQuestion, answerResponse)) .andReturn(false); replay(service); replay(selfHelpGuideQuestionService); try { Boolean response = controller.answer(selfHelpGuideResponseId, selfHelpGuideQuestionId, answerResponse); verify(service); verify(selfHelpGuideQuestionService); assertFalse(response); } catch (Exception e) { fail("controller error"); } }
private Account createTestAccount(final int billCycleDay, final String phone) { final String thisKey = "test" + UUID.randomUUID().toString(); final String lastName = UUID.randomUUID().toString(); final String thisEmail = "*****@*****.**" + " " + UUID.randomUUID(); final String firstName = "Bob"; final String name = firstName + " " + lastName; final String locale = "EN-US"; final DateTimeZone timeZone = DateTimeZone.forID("America/Los_Angeles"); final int firstNameLength = firstName.length(); return new DefaultAccount( UUID.randomUUID(), thisKey, thisEmail, name, firstNameLength, Currency.USD, new DefaultBillCycleDay(billCycleDay, billCycleDay), UUID.randomUUID(), timeZone, locale, null, null, null, null, null, null, null, // add null address fields phone, false, false); }
@Test public void testMoveFromLocalMultiAndDir() throws Exception { String name1 = UUID.randomUUID() + "-1.txt"; String name2 = UUID.randomUUID() + "-2.txt"; String dst = "local/"; File f1 = new File(name1); File f2 = new File(name2); f1.deleteOnExit(); f2.deleteOnExit(); FileCopyUtils.copy(name1, new FileWriter(f1)); FileCopyUtils.copy(name2, new FileWriter(f2)); try { shell.moveFromLocal(name1, dst); shell.moveFromLocal(name2, dst); assertTrue(shell.test(dst + name1)); assertTrue(shell.test(dst + name2)); assertEquals(name1, shell.cat(dst + name1).toString()); assertEquals(name2, shell.cat(dst + name2).toString()); assertFalse(f1.exists()); assertFalse(f2.exists()); } finally { f1.delete(); f2.delete(); } }
@Test public void insert_rowkey_prefix_date() throws IOException { System.out.println(errorTable); errorTable.setAutoFlushTo(false); List<Put> puts = new ArrayList<Put>(); long t1 = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8); Put put = new Put(Bytes.toBytes("20150705" + "_" + uuid)); put.add( fBytes, Bytes.toBytes("stacktrace"), Bytes.toBytes("java.io.IOException:file not found" + UUID.randomUUID().toString())); // puts.add(put); errorTable.put(put); if (i % 10000 == 0) { errorTable.flushCommits(); } } errorTable.flushCommits(); long t2 = System.currentTimeMillis(); System.out.println("count=" + puts.size() + ",t2-t1=" + (t2 - t1)); // errorTable.close(); }
@Test public void testCopyToLocalMulti() throws Exception { String fName1 = UUID.randomUUID() + ".txt"; String name1 = "local/" + fName1; String fName2 = UUID.randomUUID() + ".txt"; String name2 = "local/" + fName2; File dir = new File("local"); dir.mkdir(); Resource res1 = TestUtils.writeToFS(cfg, name1); Resource res2 = TestUtils.writeToFS(cfg, name2); shell.copyToLocal(name1, "local"); shell.copyToLocal(false, true, name2, "local"); File fl1 = new File(name1); File fl2 = new File(name2); try { assertTrue(fl1.exists()); assertTrue(fl2.exists()); assertArrayEquals( FileCopyUtils.copyToByteArray(res1.getInputStream()), FileCopyUtils.copyToByteArray(fl1)); assertArrayEquals( FileCopyUtils.copyToByteArray(res2.getInputStream()), FileCopyUtils.copyToByteArray(fl2)); } finally { FileSystemUtils.deleteRecursively(dir); } }
@Test public void testGetMergeWithNewLine() throws Exception { String fName1 = UUID.randomUUID() + ".txt"; String name1 = "local/merge/" + fName1; TestUtils.writeToFS(cfg, name1); String fName2 = UUID.randomUUID() + ".txt"; String name2 = "local/merge/" + fName2; TestUtils.writeToFS(cfg, name2); File dir = new File("local"); dir.mkdir(); String localName = "local/merge.txt"; File fl1 = new File(localName); try { shell.getmerge("local/merge/", localName, true); assertTrue(fl1.exists()); String content = FileCopyUtils.copyToString(new FileReader(fl1)); assertTrue(content.contains(name1 + "\n")); assertTrue(content.contains(name2)); assertEquals(content.length(), name1.length() + name2.length() + 2); } finally { FileSystemUtils.deleteRecursively(dir); } }
static { String job1 = UUID.randomUUID().toString(); String job2 = UUID.randomUUID().toString(); String job3 = UUID.randomUUID().toString(); JOB_KEYS = new String[] {job1, job1, job2, job3, job3, job3}; }
@Test public void testVanishingTaskZNode() throws Exception { LOG.info("testVanishingTaskZNode"); conf.setInt("hbase.splitlog.manager.unassigned.timeout", 0); slm = new SplitLogManager(zkw, conf, stopper, "dummy-master", null); slm.finishInitialization(); FileSystem fs = TEST_UTIL.getTestFileSystem(); final Path logDir = new Path(fs.getWorkingDirectory(), UUID.randomUUID().toString()); fs.mkdirs(logDir); Path logFile = new Path(logDir, UUID.randomUUID().toString()); fs.createNewFile(logFile); new Thread() { public void run() { try { // this call will block because there are no SplitLogWorkers slm.splitLogDistributed(logDir); } catch (Exception e) { LOG.warn("splitLogDistributed failed", e); fail(); } } }.start(); waitForCounter(tot_mgr_node_create_result, 0, 1, 10000); String znode = ZKSplitLog.getEncodedNodeName(zkw, logFile.toString()); // remove the task znode ZKUtil.deleteNode(zkw, znode); waitForCounter(tot_mgr_get_data_nonode, 0, 1, 30000); waitForCounter(tot_mgr_log_split_batch_success, 0, 1, 1000); assertTrue(fs.exists(logFile)); fs.delete(logDir, true); }
private void checkFeed(String leader, List<String> followers) { JsonNode userFeed; // create user createUser(leader); String preFollowContent = leader + ": pre-something to look for " + UUID.randomUUID().toString(); addActivity(leader, leader + " " + leader + "son", preFollowContent); String lastUser = followers.get(followers.size() - 1); int i = 0; for (String user : followers) { createUser(user); follow(user, leader); } userFeed = getUserFeed(lastUser); assertTrue(userFeed.size() == 1); // retrieve feed userFeed = getUserFeed(lastUser); assertTrue(userFeed.size() == 1); String postFollowContent = leader + ": something to look for " + UUID.randomUUID().toString(); addActivity(leader, leader + " " + leader + "son", postFollowContent); // check feed userFeed = getUserFeed(lastUser); assertNotNull(userFeed); assertTrue(userFeed.size() > 1); String serialized = userFeed.toString(); assertTrue(serialized.indexOf(postFollowContent) > 0); assertTrue(serialized.indexOf(preFollowContent) > 0); }
@Test public void testCreateZoneWithNonUniqueSubdomain() { IdentityZone idZone1 = new IdentityZone(); String id1 = UUID.randomUUID().toString(); idZone1.setId(id1); idZone1.setSubdomain(id1 + "non-unique"); idZone1.setName("testCreateZone() " + id1); ResponseEntity<Void> response1 = client.exchange( serverRunning.getUrl("/identity-zones"), HttpMethod.POST, new HttpEntity<>(idZone1), new ParameterizedTypeReference<Void>() {}, id1); assertEquals(HttpStatus.CREATED, response1.getStatusCode()); IdentityZone idZone2 = new IdentityZone(); String id2 = UUID.randomUUID().toString(); idZone2.setId(id2); idZone2.setSubdomain(id1 + "non-unique"); idZone2.setName("testCreateZone() " + id2); ResponseEntity<Map<String, String>> response2 = client.exchange( serverRunning.getUrl("/identity-zones"), HttpMethod.POST, new HttpEntity<>(idZone2), new ParameterizedTypeReference<Map<String, String>>() {}, id2); assertEquals(HttpStatus.CONFLICT, response2.getStatusCode()); Assert.assertTrue( response2.getBody().get("error_description").toLowerCase().contains("subdomain")); }
@BeforeClass public static void initializeData() throws Exception { Config.loadProperties(); String datasource = Config.getDatasource(); ConnectionPool pool = ConnectionPoolFactory.getConnectionPool(datasource); handler = new SQLHandler(pool); DAOFactory factory = new DAOFactory(datasource); Connection connection = pool.getConnection(); workspaceDAO = factory.getWorkspaceDao(connection); userDao = factory.getUserDao(connection); user1 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "[email protected]", 100, 0); userDao.add(user1); Workspace workspace1 = new Workspace(null, 1, user1, false, false); workspaceDAO.add(workspace1); user2 = new User(UUID.randomUUID(), "tester1", "tester1", "AUTH_12312312", "[email protected]", 100, 0); userDao.add(user2); Workspace workspace2 = new Workspace(null, 1, user2, false, false); workspaceDAO.add(workspace2); }
@Test public void initiate() throws Exception { Person bob = new Person(UUID.randomUUID()); String sessionId = (new Date()).toString(); securityService.setCurrent(bob); UUID selfHelpGuideId = UUID.randomUUID(); SelfHelpGuide selfHelpGuide = new SelfHelpGuide(); SelfHelpGuideResponse selfHelpGuideResponse = new SelfHelpGuideResponse(); expect(selfHelpGuideService.get(selfHelpGuideId)).andReturn(selfHelpGuide); expect(service.initiateSelfHelpGuideResponse(selfHelpGuide, bob, sessionId)) .andReturn(selfHelpGuideResponse); replay(service); replay(selfHelpGuideService); String response = controller.initiate(selfHelpGuideId); verify(service); verify(selfHelpGuideService); assertEquals(selfHelpGuideResponse.toString(), response); }
@Test public void testSerialization() throws IOException, ClassNotFoundException { Condition cond = new Condition(); Set<UUID> ids = new HashSet<>(); ids.add(UUID.randomUUID()); ids.add(UUID.randomUUID()); cond.inPortIds = ids; cond.portGroup = UUID.randomUUID(); cond.tpSrc = new Range<>(40000, 41000); cond.tpSrcInv = false; cond.tpDst = new Range<>(42000, 43000); cond.tpDstInv = true; cond.etherType = 0x86DD; ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream out = new BufferedOutputStream(bos); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(new OutputStreamWriter(out)); jsonGenerator.writeObject(cond); out.close(); byte[] data = bos.toByteArray(); ByteArrayInputStream bis = new ByteArrayInputStream(data); InputStream in = new BufferedInputStream(bis); JsonParser jsonParser = jsonFactory.createJsonParser(new InputStreamReader(in)); Condition c = jsonParser.readValueAs(Condition.class); in.close(); Assert.assertTrue(cond.equals(c)); }
@Test(groups = "slow") public void testShouldBeAbleToHandleOtherBCDClass() throws Exception { final Account account = createTestAccount(); accountDao.create(account, internalCallContext); final MutableAccountData otherAccount = account.toMutableAccountData(); otherAccount.setAddress1(UUID.randomUUID().toString()); otherAccount.setEmail(UUID.randomUUID().toString()); // Same BCD, but not .equals method otherAccount.setBillCycleDay( new BillCycleDay() { @Override public int getDayOfMonthUTC() { return account.getBillCycleDay().getDayOfMonthUTC(); } @Override public int getDayOfMonthLocal() { return account.getBillCycleDay().getDayOfMonthLocal(); } }); final DefaultAccount newAccount = new DefaultAccount(account.getId(), otherAccount); accountDao.update(newAccount, internalCallContext); final Account newFetchedAccount = accountDao.getById(account.getId(), internalCallContext); Assert.assertEquals(newFetchedAccount.getAddress1(), newAccount.getAddress1()); Assert.assertEquals(newFetchedAccount.getEmail(), newAccount.getEmail()); // Same BCD Assert.assertEquals(newFetchedAccount.getBillCycleDay(), account.getBillCycleDay()); }
/** * Tests that a job is properly canceled in the case of a leader change. However, this time only * the JMs are notified about the leader change and the TMs still believe the old leader to have * leadership. */ @Test public void testStateCleanupAfterNewLeaderElection() throws Exception { UUID leaderSessionID = UUID.randomUUID(); UUID newLeaderSessionID = UUID.randomUUID(); cluster.grantLeadership(0, leaderSessionID); cluster.notifyRetrievalListeners(0, leaderSessionID); cluster.waitForTaskManagersToBeRegistered(); // submit blocking job so that we can test job clean up cluster.submitJobDetached(job); ActorGateway jm = cluster.getLeaderGateway(timeout); Future<Object> wait = jm.ask(new WaitForAllVerticesToBeRunningOrFinished(job.getJobID()), timeout); Await.ready(wait, timeout); Future<Object> jobRemoval = jm.ask(new NotifyWhenJobRemoved(job.getJobID()), timeout); // only notify the JMs about the new leader JM(1) cluster.grantLeadership(1, newLeaderSessionID); // job should be removed anyway Await.ready(jobRemoval, timeout); }
public static String generateUUIDs(int howMany) { StringBuilder builder = new StringBuilder(); // Append normal UUIDs: for (int count = 0; count < howMany; count++) { builder.append(UUID.randomUUID().toString()).append("\n"); } builder.append("\n"); // Append uppercase UUIDs: for (int count = 0; count < howMany; count++) { builder.append(UUID.randomUUID().toString().toUpperCase()).append("\n"); } builder.append("\n"); // Append uppercase w/ dashes removed: for (int count = 0; count < howMany; count++) { builder.append(UUID.randomUUID().toString().toUpperCase().replace("-", "")).append("\n"); } return builder.toString(); }
/** * Tests that a job is properly canceled in the event of a leader change. However, this time only * the TMs are notified about the changing leader. This should be enough to cancel the currently * running job, though. */ @Test public void testStateCleanupAfterListenerNotification() throws Exception { UUID leaderSessionID = UUID.randomUUID(); UUID newLeaderSessionID = UUID.randomUUID(); cluster.grantLeadership(0, leaderSessionID); cluster.notifyRetrievalListeners(0, leaderSessionID); cluster.waitForTaskManagersToBeRegistered(); // submit blocking job cluster.submitJobDetached(job); ActorGateway jm = cluster.getLeaderGateway(timeout); Future<Object> wait = jm.ask(new WaitForAllVerticesToBeRunningOrFinished(job.getJobID()), timeout); Await.ready(wait, timeout); Future<Object> jobRemoval = jm.ask(new NotifyWhenJobRemoved(job.getJobID()), timeout); // notify listeners (TMs) about the leader change cluster.notifyRetrievalListeners(1, newLeaderSessionID); Await.ready(jobRemoval, timeout); }
@Test public void shouldFindCarsWithFindCommandAndNamedQuery() throws Exception { // String uniqueColorForTest = "black-and-pink-with-ruby-named-query"; Car exampleCar = CarBuilder.aCar().withManufacturer(UUID.randomUUID().toString()).withYear(2000).build(); saveNewCopiesOfCarToRepository(exampleCar, 10); Car secondExampleCar = CarBuilder.aCar().withManufacturer(UUID.randomUUID().toString()).withYear(2005).build(); saveNewCopiesOfCarToRepository(secondExampleCar, 5); // Car searchByManufacturerExampleCar = new Car(null, 0, exampleCar.getManufacturer(), null); FindCommand<Car> findCommand = FindCommand.create(Car.class); findCommand.withSearchFilter("year", "2000").withNamedQuery("Car.findGreaterThanYear"); List<Car> foundCars = carRepository.findItemsWith(findCommand); assertThat(foundCars).isNotNull().hasSize(10); FindCommand<Car> findCommand2 = FindCommand.create(Car.class) .withSearchFilter("year", "2005") .withNamedQuery("Car.findGreaterThanYear"); List<Car> foundCarsByColor = carRepository.findItemsWith(findCommand2); assertThat(foundCarsByColor).isNotNull().hasSize(5); /*FindCommand<Car> findCommand3 = FindCommand.create(Car.class) .withNamedQuery("Car.findGreaterThanYear"); findCommand3.withSearchFilter("manufacturer", exampleCar.getManufacturer()); findCommand3.withSearchFilter("color", uniqueColorForTest); List<Car> foundCarsByManufacturerAndColor = carRepository.findItemsWith(findCommand3); assertThat(foundCarsByManufacturerAndColor).isNotNull().hasSize(10);*/ }
@Test(groups = "slow") public void testSetDefaultPaymentMethod() throws Exception { final PaymentPluginApi api = getTestApi(paymentPluginApiOSGIServiceRegistration, BUNDLE_TEST_RESOURCE_PREFIX); api.setDefaultPaymentMethod( UUID.randomUUID(), UUID.randomUUID(), ImmutableList.<PluginProperty>of(), callContext); }
/** This test tests that complete packet is build correctly */ public static void PacketBuilderTest() throws IOException, JdpException { /* Complete packet test */ { JdpJmxPacket p1 = new JdpJmxPacket(UUID.randomUUID(), "fake://unit-test"); p1.setMainClass("FakeUnitTest"); p1.setInstanceName("Fake"); byte[] b = p1.getPacketData(); JdpJmxPacket p2 = new JdpJmxPacket(b); JdpDoSomething.printJdpPacket(p1); JdpDoSomething.compaireJdpPacketEx(p1, p2); } /*Missed field packet test*/ { JdpJmxPacket p1 = new JdpJmxPacket(UUID.randomUUID(), "fake://unit-test"); p1.setMainClass("FakeUnitTest"); p1.setInstanceName(null); byte[] b = p1.getPacketData(); JdpJmxPacket p2 = new JdpJmxPacket(b); JdpDoSomething.printJdpPacket(p1); JdpDoSomething.compaireJdpPacketEx(p1, p2); } System.out.println("OK: Test passed"); }
@Test(groups = "slow") public void testGetPaymentInfo() throws Exception { final PaymentPluginApi api = getTestApi(paymentPluginApiOSGIServiceRegistration, BUNDLE_TEST_RESOURCE_PREFIX); final DateTime beforeCall = new DateTime().toDateTime(DateTimeZone.UTC).minusSeconds(1); final PaymentTransactionInfoPlugin res = api.getPaymentInfo( UUID.randomUUID(), UUID.randomUUID(), ImmutableList.<PluginProperty>of(), callContext) .get(0); final DateTime afterCall = new DateTime().toDateTime(DateTimeZone.UTC).plusSeconds(1); Assert.assertTrue(res.getAmount().compareTo(BigDecimal.ZERO) == 0); Assert.assertTrue(res.getCreatedDate().compareTo(beforeCall) >= 0); Assert.assertTrue(res.getCreatedDate().compareTo(afterCall) <= 0); Assert.assertTrue(res.getEffectiveDate().compareTo(beforeCall) >= 0); Assert.assertTrue(res.getEffectiveDate().compareTo(afterCall) <= 0); assertEquals(res.getGatewayError(), "gateway_error"); assertEquals(res.getGatewayErrorCode(), "gateway_error_code"); assertEquals(res.getStatus(), PaymentPluginStatus.PROCESSED); }
private SAMLProperties setupForKeyManager() { final ResourceLoader resourceLoader = Mockito.mock(ResourceLoader.class); this.config.setResourceLoader(resourceLoader); final Resource storeFile = Mockito.mock(Resource.class); final SAMLProperties properties = Mockito.mock(SAMLProperties.class); this.config.setSamlProperties(properties); final String keyStorePassword = UUID.randomUUID().toString(); final String keyStoreName = UUID.randomUUID().toString() + ".jks"; final String defaultKeyName = UUID.randomUUID().toString(); final String defaultKeyPassword = UUID.randomUUID().toString(); final SAMLProperties.Keystore keyStore = Mockito.mock(SAMLProperties.Keystore.class); final SAMLProperties.Keystore.DefaultKey defaultKey = Mockito.mock(SAMLProperties.Keystore.DefaultKey.class); Mockito.when(properties.getKeystore()).thenReturn(keyStore); Mockito.when(keyStore.getName()).thenReturn(keyStoreName); Mockito.when(keyStore.getPassword()).thenReturn(keyStorePassword); Mockito.when(keyStore.getDefaultKey()).thenReturn(defaultKey); Mockito.when(defaultKey.getName()).thenReturn(defaultKeyName); Mockito.when(defaultKey.getPassword()).thenReturn(defaultKeyPassword); Mockito.when(resourceLoader.getResource(Mockito.eq("classpath:" + keyStoreName))) .thenReturn(storeFile); return properties; }
@Test public void testUpdateState() throws Throwable { assertThat(vm.getState(), is(not(VmState.ERROR))); vmDcpBackend.updateState(vm, VmState.ERROR); assertThat(vm.getState(), is(VmState.ERROR)); vm = vmDcpBackend.findById(vmId); assertThat(vm.getState(), is(VmState.ERROR)); String agent = UUID.randomUUID().toString(); String agentIp = UUID.randomUUID().toString(); String datastoreId = UUID.randomUUID().toString(); String datastoreName = UUID.randomUUID().toString(); vmDcpBackend.updateState(vm, VmState.STARTED, agent, agentIp, datastoreId, datastoreName); assertThat(vm.getState(), is(VmState.STARTED)); assertThat(vm.getAgent(), is(agent)); assertThat(vm.getHost(), is(agentIp)); assertThat(vm.getDatastore(), is(datastoreId)); assertThat(vm.getDatastoreName(), is(datastoreName)); vm = vmDcpBackend.findById(vmId); assertThat(vm.getState(), is(VmState.STARTED)); assertThat(vm.getAgent(), is(agent)); assertThat(vm.getHost(), is(agentIp)); assertThat(vm.getDatastore(), is(datastoreId)); assertThat(vm.getDatastoreName(), is(datastoreName)); }
@Test public void testCreateRefFromUri() throws BadRequestException { final ParentListRef comptes_expected = ParentListRefImpl.create( // Mediatheque.ref(UUID.fromString("448028fd-fce5-45a5-8ef4-2b591800a7e2")) // , Compte.mCompte // , "comptes") // ; final ParentListRef<Mediatheque.Ref, Compte> comptes_result = Mediatheque.mMediatheque.comptes.parse( "mediatheque/448028fd-fce5-45a5-8ef4-2b591800a7e2/comptes"); assertEquals(comptes_expected, comptes_result); // ListRef result1 = Mediatheque.mMediatheque.comptes_ref(); final UUID idMediatheque = UUID.randomUUID(); final Mediatheque.Ref mediatheque_expected = Mediatheque.ref(idMediatheque); final Mediatheque.Ref mediatheque_result = Mediatheque.mMediatheque.createRefFromUri("mediatheque/" + idMediatheque); assertEquals(mediatheque_expected, mediatheque_result); final UUID idIndividu = UUID.randomUUID(); final Individu.Ref individu_expected = Individu.ref(idIndividu); final Individu.Ref individu_result = Individu.mIndividu.createRefFromUri("individu/" + idIndividu); assertEquals(individu_expected, individu_result); final Compte.Ref compte_expected = Compte.ref(mediatheque_expected, individu_expected); final Compte.Ref compte_result = Compte.mCompte.createRefFromUri( "mediatheque/" + idMediatheque + "/comptes/individu/" + idIndividu); assertEquals(compte_expected, compte_result); }
private static void MakeDummyFile(String testPath) throws IOException { String filePath = String.valueOf(Paths.get(testPath, String.valueOf(UUID.randomUUID()))); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath))); writer.write(String.valueOf(UUID.randomUUID())); writer.close(); }