src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
Label { public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw n... | @Test public void testLabelInstances() { Label label = Label.of("example"); assertTrue(label instanceof Label.ASCIILabel.LDHLabel.NonReservedLDHLabel); label = Label.of(""); assertTrue(label instanceof Label.RootLabel); label = Label.of("xn--bcher-kva"); assertTrue(label instanceof Label.ASCIILabel.LDHLabel.ReservedLDH... |
Label { public Label toUnicode() { return this; } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); static final Logger LOGGER; static final int IDNA_OPTIONS; } | @Test public void testToUnicode() { Label label = Label.of("xn--bcher-kva"); assertEquals("b\u00FCcher", label.toUnicode().getStringValue()); } |
Label { public Label toLDH() { return this; } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); static final Logger LOGGER; static final int IDNA_OPTIONS; } | @Test public void testToLDH() { Label label = Label.of("b\u00FCcher"); assertEquals("xn--bcher-kva", label.toLDH().getStringValue()); label = Label.of("Bu\u0308cher"); assertEquals("xn--bcher-kva", label.toLDH().getStringValue()); assertEquals("b\u00FCcher", label.getStringValue()); } |
TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if... | @Test public void testInvalidCountryCode() { assertThrows(new Closure() { @Override public void execute() throws Throwable { TelephoneNumber.of(1000, new BigInteger("1234567890")); } }, IllegalArgumentException.class, "Should throw IllegalArgumentException"); }
@Test public void testTooLongTelephoneNumber() { assertThr... |
CIDR { public static CIDR of(String cidr) { String[] parts = cidr.split("\\/"); if (parts.length == 1) { try { InetAddress address = InetAddress.getByName(parts[0]); int length = address instanceof Inet4Address ? 32 : 128; return new CIDR(address.getAddress(), length); } catch (UnknownHostException e) { throw new Illeg... | @Test public void testDoesItSmoke() { Assert.assertThrows(new Assert.Closure() { @Override public void execute() throws Throwable { CIDR.of("1.1.1.1/-1"); } }, IllegalArgumentException.class, "negative prefix size"); } |
SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e ins... | @Test public void translateExceptionIfPossible_should_translate_DuplicateItemNameException_into_DuplicateKeyException() { DuplicateItemNameException duplicateItemException = new DuplicateItemNameException("Duplicate Item"); DataAccessException dataAccessException = translator.translateExceptionIfPossible(duplicateItemE... |
AlphanumStringComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { int c = 0; Matcher m1 = prefixRexp.matcher(s1); Matcher m2 = prefixRexp.matcher(s2); if (m1.find() && m2.find()) { Integer i1 = Integer.valueOf(m1.group(1)); Integer i2 = Integer.valueOf(m2.group(1)); c = i1.co... | @Test public void should_correctly_compare_alphanumerical_strings() throws Exception { AlphanumStringComparator comparator = new AlphanumStringComparator(); assertTrue(comparator.compare("10@foo", "2@foo") > 0); assertTrue(comparator.compare("2@foo", "10@foo") < 0); assertTrue(comparator.compare("10@foo", "10@foo") == ... |
MapUtils { public static List<Map<String, List<String>>> splitToChunksOfSize(Map<String, List<String>> rawMap, int chunkSize) { List<Map<String, List<String>>> mapChunks = new LinkedList<Map<String, List<String>>>(); Set<Map.Entry<String, List<String>>> rawEntries = rawMap.entrySet(); Map<String, List<String>> currentC... | @Test public void splitToChunksOfSize_should_split_entries_exceeding_size() throws Exception { Map<String, List<String>> attributes = new LinkedHashMap<String, List<String>>(); for(int i = 0; i < SAMPLE_MAP_SIZE + 100; i++) { List<String> list = new ArrayList<String>(); list.add("Value: " + i); attributes.put("Key: " +... |
PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part... | @Test public void should_create_corect_query_for_simple_property() { final String methodName = "findByItemName"; final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class); final String query = PartTreeConverter.toIndexedQuery(tree); final String expected = " itemName = ? "; assertEquals(expected, query... |
SimpleDbRepositoryQuery implements RepositoryQuery { void assertNotHavingNestedQueryParameters(String query) { List<String> attributesFromQuery = QueryUtils.getQueryPartialFieldNames(query); final Class<?> domainClass = method.getDomainClazz(); for(String attribute : attributesFromQuery) { try { Field field = Reflectio... | @SuppressWarnings({ "rawtypes", "unchecked" }) @Test(expected = IllegalArgumentException.class) public void assertNotHavingNestedQueryParameters_should_fail_for_nested_attributes() { SimpleDbQueryMethod method = Mockito.mock(SimpleDbQueryMethod.class); Mockito.when(method.getDomainClazz()).thenReturn((Class) SampleEnti... |
SimpleDbQueryRunner { public Object executeSingleResultQuery() { List<?> returnListFromDb = executeQuery(); return getSingleResult(returnListFromDb); } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> dom... | @Test(expected = IllegalArgumentException.class) public void executeSingleResultQuery_should_fail_if_multiple_results_are_retrieved() { SimpleDbOperations simpleDbOperations = Mockito.mock(SimpleDbOperations.class); List<SampleEntity> sampleMultipleResults = new ArrayList<SampleEntity>(); sampleMultipleResults.add(new ... |
SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) :... | @Test public void getSingleResult_should_return_null_for_empty_list() { SimpleDbQueryRunner runner = new SimpleDbQueryRunner(null, SampleEntity.class, null); final Object result = runner.getSingleResult(new ArrayList<SampleEntity>()); assertNull(result); }
@Test public void getSingleResult_should_return_single_value_fr... |
SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter();... | @Test public void filterNamedAttributesAsList_should_return_list_of_named_attributes() throws Exception { List<SampleEntity> entities = new ArrayList<SampleEntity>(); SampleEntity entity = new SampleEntity(); entity.setSampleAttribute(SAMPLE_INT_VALUE); entities.add(entity); List<Object> filteredAttributes = SimpleDbRe... |
SimpleDbResultConverter { public static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName) { Set<Object> ret = new LinkedHashSet<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter()... | @Test public void filterNamedAttributesAsSet_should_return_Set_of_named_attributes() throws Exception { List<SampleEntity> entities = new ArrayList<SampleEntity>(); SampleEntity entity = new SampleEntity(); entity.setSampleAttribute(SAMPLE_INT_VALUE); entities.add(entity); Set<Object> filteredAttributes = SimpleDbResul... |
SimpleDbResultConverter { public static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames) { if(entityList.size() > 0) { List<List<Object>> rows = new ArrayList<List<Object>>(); for(Object entity : entityList) { List<Object> cols = new ArrayList<Object>(); for(String fiel... | @Test public void toListOfListOfObject_should_return_List_of_Lists_containing_requested_attributes() { List<SampleEntity> entities = new ArrayList<SampleEntity>(); SampleEntity entity = new SampleEntity(); entity.setSampleAttribute(SAMPLE_INT_VALUE); entity.setSampleList(new ArrayList<Integer>()); entities.add(entity);... |
MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNa... | @Test public void detectResultType_should_return_COLLECTION_OF_DOMAIN_ENTITIES() throws Exception { SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectAll", SampleEntity.class); MultipleResultExecution multipleResultExecution = new MultipleResultExecution(null); assertEquals(MultipleResultExecution.... |
PagedResultExecution extends AbstractSimpleDbQueryExecution { @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } Pag... | @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void doExecute_should_return_Page_type() throws Exception { final SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectAllIntoPage", SampleEntity.class); final PagedResultExecution execution = new PagedResultExecution(null); final SimpleDbQue... |
SimpleDBAttributeConverter { public static Object decodeToPrimitiveArray(List<String> fromSimpleDbAttValues, Class<?> retType) throws ParseException { Object primitiveCollection = Array.newInstance(retType, fromSimpleDbAttValues.size()); int idx = 0; for(Iterator<String> iterator = fromSimpleDbAttValues.iterator(); ite... | @Test public void toSimpleDBAttributeValues_should_return_an_string_representation_of_concatenated_array_elements() throws ParseException { final int[] expectedIntArray = { 1, 2, 3, 4 }; final List<String> simpleDBValues = Arrays.asList("1", "2", "3", "4"); Object returnedPrimitiveCol = SimpleDBAttributeConverter.decod... |
SimpleDbAttributeValueSplitter { public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entr... | @Test public void splitAttributeValuesWithExceedingLengths_should_detect_long_attributes() throws Exception { Map<String, String> rawAttributes = new LinkedHashMap<String, String>(); rawAttributes.put(SAMPLE_ATT_NAME, STRING_OF_MAX_SIMPLE_DB_LENGTH + "c"); Map<String, List<String>> splitAttributes = SimpleDbAttributeVa... |
QueryBuilder { @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation); QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation, boolean shouldCount); QueryBuilder(String c... | @Test public void should_create_correct_queries_if_no_other_clauses_are_specified() throws Exception { QueryBuilder builder = new QueryBuilder(SimpleDbSampleEntity.entityInformation()); String returnedQuery = builder.toString(); assertEquals("select * from `simpleDbSampleEntity`", returnedQuery); }
@Test public void sh... |
EntityWrapper { public Map<String, String> serialize() { return serialize(""); } EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item, boolean isNested); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation); Enti... | @Test public void test_getSerializedPrimitiveAttributes() throws ParseException { final SampleEntity entity = new SampleEntity(); entity.setIntField(11); entity.setLongField(123); entity.setShortField((short) -12); entity.setFloatField(-0.01f); entity.setDoubleField(1.2d); entity.setByteField((byte) 1); entity.setBoole... |
DomainItemBuilder { public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } List<T> populateDomainItems(SimpleDbEntityInformation<T, ?> entityInformation, SelectResult selectResult); T populateDomainItem(SimpleDbEntityInformation<T,... | @Test public void populateDomainItem_should_convert_item_name() { Item sampleItem = new Item(SAMPLE_ITEM_NAME, new ArrayList<Attribute>()); SimpleDbEntityInformation<SimpleDbSampleEntity, String> entityInformation = SimpleDbSampleEntity .entityInformation(); domainItemBuilder = new DomainItemBuilder<SimpleDbSampleEntit... |
Util { public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } private Util(); static String getDefaultMusicFolder(); static String getDefaultP... | @Test public void objectToStringMapNull() { MediaLibraryStatistics statistics = null; Map<String, String> stringStringMap = Util.objectToStringMap(statistics); assertNull(stringStringMap); }
@Test public void objectToStringMap() { Date date = new Date(1568350960725L); MediaLibraryStatistics statistics = new MediaLibrar... |
InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG... | @Test public void testRedirectLoop() { List<InternetRadioSource> radioSources = internetRadioService.getInternetRadioSources(radioMoveLoop); Assert.assertEquals(0, radioSources.size()); }
@Test public void testParseSimplePlaylist() { List<InternetRadioSource> radioSources = internetRadioService.getInternetRadioSources(... |
Util { public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void set... | @Test public void stringMapToObject() { Map<String, String> stringStringMap = new HashMap<>(); stringStringMap.put("albumCount", "5"); stringStringMap.put("songCount", "4"); stringStringMap.put("artistCount", "910823"); stringStringMap.put("totalDurationInSeconds", "30"); stringStringMap.put("totalLengthInBytes", "2930... |
Util { public static <T> T stringMapToValidObject(Class<T> clazz, Map<String, String> data) { T object = stringMapToObject(clazz, data); Set<ConstraintViolation<T>> validate = validator.validate(object); if (validate.isEmpty()) { return object; } else { throw new IllegalArgumentException("Created object was not valid")... | @Test(expected = IllegalArgumentException.class) public void stringMapToValidObjectWithNoData() { Map<String, String> stringStringMap = new HashMap<>(); MediaLibraryStatistics statistics = Util.stringMapToValidObject(MediaLibraryStatistics.class, stringStringMap); } |
JWTSecurityService { public String addJWTToken(String uri) { return addJWTToken(UriComponentsBuilder.fromUriString(uri)).build().toString(); } @Autowired JWTSecurityService(SettingsService settingsService); static String generateKey(); static Algorithm getAlgorithm(String jwtKey); String addJWTToken(String uri); UriCo... | @Test public void addJWTToken() { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(uriString); String actualUri = service.addJWTToken(builder).build().toUriString(); String jwtToken = UriComponentsBuilder.fromUriString(actualUri).build().getQueryParams().getFirst( JWTSecurityService.JWT_PARAM_NAME); De... |
CsarController { @ApiOperation( value = "List all CSARs stored on the server", notes = "Returns a Hypermedia Resource containing all CSARs" + " that have been uploaded to the server and did not get removed", response = CsarResources.class, produces = "application/hal+json" ) @RequestMapping( path = "", method = Request... | @Test public void listCsars() throws Exception { ResultActions resultActions = mvc.perform( get(LIST_CSARS_URL).accept(ACCEPTED_MIME_TYPE) ).andDo(print()).andExpect(status().is2xxSuccessful()); resultActions.andExpect(jsonPath("$.links[0].rel").value("self")); resultActions.andExpect(jsonPath("$.links[0].href").value(... |
ReadmeBuilder { @Override public String toString() { Parser markdownParser = Parser.builder().build(); Node markdownDocument = markdownParser.parse(this.markdownText); HtmlRenderer renderer = HtmlRenderer.builder().build(); return TEMPLATE.replace(README_TEMPLATE_TITLE_KEY, this.pageTitle) .replace(README_TEMPLATE_BODY... | @Test public void testBuilderWithMarkdownString() { logger.info("Initilaizing Readme Builder"); ReadmeBuilder builder = new ReadmeBuilder("# Hello World", "Hello"); logger.info("Rendering"); String result = builder.toString(); logger.info("Rendered: {}", result); assertTrue(result.contains("<h1>Hello World</h1>")); ass... |
KubernetesPlugin extends ToscanaPlugin<KubernetesLifecycle> { @Override public KubernetesLifecycle getInstance(TransformationContext context) throws Exception { return new KubernetesLifecycle(context, mapper); } @Autowired KubernetesPlugin(BaseImageMapper mapper); @Override KubernetesLifecycle getInstance(Transformati... | @Test(expected = ValidationFailureException.class) public void modelCheckTest() throws Exception { EffectiveModel singleComputeModel = new EffectiveModelFactory().create(TestCsars.VALID_SINGLE_COMPUTE_WINDOWS_TEMPLATE, logMock()); TransformationContext context = setUpMockTransformationContext(singleComputeModel); Kuber... |
SudoUtils { public static Optional<String> getSudoInstallCommand(String baseImage) { String imageName = baseImage.split(":")[0]; return Optional.ofNullable(IMAGE_MAP.get(imageName)); } static Optional<String> getSudoInstallCommand(String baseImage); } | @Test public void validate() { Optional<String> result = SudoUtils.getSudoInstallCommand(input); if (expected == null) { assertTrue(!result.isPresent()); return; } String r = result.get(); assertEquals(r, expected); } |
ResourceFileCreator { public HashMap<String, String> getResourceYaml() throws JsonProcessingException { HashMap<String, String> result = new HashMap<>(); for (IKubernetesResource<?> resource : resources) { result.put(resource.getName(), resource.toYaml()); } return result; } ResourceFileCreator(Collection<Pod> pods); H... | @Test public void testReplicationControllerCreation() { ResourceFileCreator resourceFileCreator = new ResourceFileCreator(Pod.getPods(TestNodeStacks.getLampNodeStacks(logMock()))); HashMap<String, String> result = null; try { result = resourceFileCreator.getResourceYaml(); } catch (JsonProcessingException e) { e.printS... |
MapperUtils { public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } static boolean anythingSet(OsCapability capab... | @Test public void testNoneSet() { assertFalse(anythingSet(new OsCapability(entity))); }
@Test public void testOneSet() { assertTrue(anythingSet(new OsCapability(entity).setType(Type.LINUX))); } |
CapabilityMapper { public String mapOsCapabilityToImageId(OsCapability osCapability) throws SdkClientException, ParseException, IllegalArgumentException { AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withRegion(awsRegion) .build(); DescribeImagesR... | @Test public void testMapOsCapabilityToImageId() throws ParseException { try { String imageId = capabilityMapper.mapOsCapabilityToImageId(osCapability); Assert.assertThat(imageId, CoreMatchers.containsString("ami-")); } catch (SdkClientException se) { logger.info("Probably no internet connection / credentials, omitting... |
CapabilityMapper { public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> ins... | @Test public void testMapComputeCapabilityToInstanceTypeEC2() { String instanceType = capabilityMapper.mapComputeCapabilityToInstanceType(containerCapability, EC2_DISTINCTION); Assert.assertEquals(instanceType, expectedEC2); }
@Test public void testMapComputeCapabilityToInstanceTypeRDS() { String instanceType = capabil... |
CapabilityMapper { public Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability) { final Integer minSize = 20; final Integer maxSize = 6144; Integer diskSize = computeCapability.getDiskSizeInMb().orElse(minSize * 1000); diskSize = diskSize / 1000; if (diskSize > maxSize) { logger.debug("... | @Test public void testMapComputeCapabilityToRDSAllocatedStorage() { int newDiskSize = capabilityMapper.mapComputeCapabilityToRDSAllocatedStorage(containerCapability); Assert.assertEquals(newDiskSize, expectedDiskSize); } |
CsarController { @ApiOperation( value = "Deletes a Existing CSAR", notes = "Deletes the Resulting CSAR and its transformations (if none of them is running). " + "If a transformation is running (in the state TRANSFORMING) the CSAR cannot be deleted" ) @ApiResponses({ @ApiResponse( code = 200, message = "The deletion of ... | @Test public void testDelete() throws Exception { final boolean[] executed = new boolean[]{false}; doAnswer(iom -> executed[0] = true).when(service).deleteCsar(any(Csar.class)); mvc.perform( delete(DELETE_VALID_CSAR_URL).accept(ACCEPTED_MIME_TYPE) ).andDo(print()) .andExpect(status().is(200)) .andExpect(content().bytes... |
CloudFormationFileCreator { public void writeScripts() throws IOException { writeFileUploadScript(); writeStackCreationScript(); writeDeployScript(); writeCleanUpScript(); } CloudFormationFileCreator(TransformationContext context, CloudFormationModule cfnModule); void copyFiles(); void writeScripts(); void copyUtilScri... | @Test public void testWriteScripts() throws Exception { cfnModule.addFileUpload(new FileUpload(FILENAME_TEST_FILE, FROM_CSAR)); fileCreator.writeScripts(); File deployScript = new File(targetDir, SCRIPTS_DIR_PATH + FILENAME_DEPLOY + BASH_FILE_ENDING); File fileUploadScript = new File(targetDir, SCRIPTS_DIR_PATH + FILEN... |
CloudFormationFileCreator { public void copyUtilScripts() throws IOException { List<String> utilScripts = IOUtils.readLines( getClass().getResourceAsStream(FILEPATH_SCRIPTS_UTIL + "scripts-list"), Charsets.UTF_8 ); logger.debug("Copying util scripts to the target artifact."); copyUtilFile(utilScripts, FILEPATH_SCRIPTS_... | @Test public void copyUtilScripts() throws Exception { fileCreator.copyUtilScripts(); File createBucketUtilScript = new File(targetDir, UTIL_DIR_PATH + FILENAME_CREATE_BUCKET + BASH_FILE_ENDING); File uploadFileUtilScript = new File(targetDir, UTIL_DIR_PATH + FILENAME_UPLOAD_FILE + BASH_FILE_ENDING); assertTrue(createB... |
CloudFormationFileCreator { public void copyFiles() { List<String> fileUploadList = getFilePaths(getFileUploadByType(cfnModule.getFileUploadList(), FROM_CSAR)); logger.debug("Checking if files need to be copied."); if (!fileUploadList.isEmpty()) { logger.debug("Files to be copied found. Attempting to copy files to the ... | @Test public void copyFiles() { cfnModule.addFileUpload(new FileUpload(FILENAME_TEST_FILE, FROM_CSAR)); fileCreator.copyFiles(); assertTrue(FILEPATH_TARGET_TEST_FILE.exists()); } |
BashScript { public void append(String string) throws IOException { logger.debug("Appending {} to {}.sh", string, name); access.access(scriptPath).appendln(string).close(); } BashScript(PluginFileAccess access, String name); void append(String string); void checkEnvironment(String command); String getScriptPath(); stat... | @Test public void appendTest() throws IOException { String string = UUID.randomUUID().toString(); bashScript.append(string); File expectedGeneratedScript = new File(targetScriptFolder, fileName + ".sh"); List<String> result = IOUtils.readLines(new FileInputStream(expectedGeneratedScript)); assertEquals(string, result.g... |
ZipUtility { public static boolean unzip(ZipInputStream zipIn, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { return false; } while (entry != null) { String filePath = destDirector... | @Test public void unzipFile() throws IOException { ZipInputStream is = new ZipInputStream(new FileInputStream(TestCsars.VALID_LAMP_INPUT)); boolean result = ZipUtility.unzip(is, tmpdir.toString()); assertTrue(result); }
@Test public void unzipNotAFile() throws IOException { ZipInputStream is = new ZipInputStream(new Fi... |
PluginFileAccess { public void copy(String relativePath) throws IOException { copy(relativePath, relativePath); } PluginFileAccess(File sourceDir, File targetDir, Log log); void copy(String relativePath); void copy(String relativeSourcePath, String relativeTargetPath); BufferedLineWriter access(String relativePath); Bu... | @Test public void copyFile() throws Exception { String filename = "testFile"; File file = new File(sourceDir, "testFile"); file.createNewFile(); File expectedFile = new File(targetDir, filename); assertFalse(expectedFile.exists()); access.copy(filename); assertTrue(expectedFile.exists()); }
@Test public void copyDirRec... |
TransformationController { @ApiOperation( value = "Retrieve the outputs and their values", tags = {"transformations"}, notes = "This operation returns the outputs of a deployment. Retrieval of the outputs is not possible " + "if the transformation (including deployment) is not done yet" ) @ApiResponses({ @ApiResponse( ... | @Test public void testGetOutputs() throws Exception { List<Transformation> transformations = preInitNonCreationTests(); Transformation t = transformations.get(0); when(t.getState()).thenReturn(TransformationState.DONE); String outputKey = "test_output"; List<OutputProperty> outputs = Lists.newArrayList(new PlatformInpu... |
PluginFileAccess { public BufferedLineWriter access(String relativePath) throws IOException { File target = new File(targetDir, relativePath); target.getParentFile().mkdirs(); try { return new BufferedLineWriter(new FileWriter(target, true)); } catch (FileNotFoundException e) { logger.error("Failed to create OutputStre... | @Test public void write() throws Exception { String secondString = "second_test_string"; access.access(targetFileName).appendln(fileContent).close(); access.access(targetFileName).append(secondString).close(); assertTrue(targetFile.isFile()); List<String> result = IOUtils.readLines(new FileInputStream(targetFile)); ass... |
PluginFileAccess { public String read(String relativePath) throws IOException { File source = new File(sourceDir, relativePath); try { return FileUtils.readFileToString(source); } catch (IOException e) { logger.error("Failed to read content from file '{}'", source); throw e; } } PluginFileAccess(File sourceDir, File ta... | @Test public void readSuccessful() throws IOException { String path = "file"; File file = new File(sourceDir, path); InputStream inputStream = IOUtils.toInputStream(fileContent, "UTF-8"); FileUtils.copyInputStreamToFile(inputStream, file); String result = access.read(path); assertNotNull(result); assertEquals(fileConte... |
PluginFileAccess { public String getAbsolutePath(String relativePath) throws FileNotFoundException { File targetFile = new File(targetDir, relativePath); if (targetFile.exists()) { return targetFile.getAbsolutePath(); } else { throw new FileNotFoundException(String.format("File '%s' not found", targetFile)); } } Plugin... | @Test public void getAbsolutePathSuccess() throws IOException { String filename = "some-source-file"; File sourceFile = new File(targetDir, filename); sourceFile.createNewFile(); String result = access.getAbsolutePath(filename); assertEquals(sourceFile.getAbsolutePath(), result); }
@Test(expected = FileNotFoundExceptio... |
PluginFileAccess { public void delete(String relativePath) { File file = new File(targetDir, relativePath); FileUtils.deleteQuietly(file); } PluginFileAccess(File sourceDir, File targetDir, Log log); void copy(String relativePath); void copy(String relativeSourcePath, String relativeTargetPath); BufferedLineWriter acce... | @Test public void delete() throws IOException { String filename = "some-file"; File file = new File(targetDir, filename); file.createNewFile(); assertTrue(file.exists()); access.delete(filename); assertFalse(file.exists()); } |
PluginFileAccess { public void createDirectories(String relativePath) { File targetFolder = new File(targetDir, relativePath); targetFolder.mkdirs(); } PluginFileAccess(File sourceDir, File targetDir, Log log); void copy(String relativePath); void copy(String relativeSourcePath, String relativeTargetPath); BufferedLine... | @Test public void createFolder() { String folder = "some-folder/some-subfolder/some-subsubfolder"; access.createDirectories(folder); File expectedFolder = new File(targetDir, folder); assertTrue(expectedFolder.exists()); } |
LogImpl implements Log { @Override public List<LogEntry> getLogEntries(int first, int last) { return getLogEntries(first, last, true); } LogImpl(File logFile); @Override void addLogEntry(LogEntry e); @Override List<LogEntry> getLogEntries(int first, int last); @Override List<LogEntry> getLogEntries(int firstIndex); @Ov... | @Test public void getAllLogEntries() throws Exception { logger.info("Trying to retrieve complete log"); List<LogEntry> logs = log.getLogEntries(0); logger.info("Checking length"); assertTrue(logs.size() == 100); logger.info("Checking data"); for (int i = 0; i < logs.size(); i++) { LogEntry e = logs.get(i); assertEquals... |
TransformationServiceImpl implements TransformationService { @Override public Transformation createTransformation(Csar csar, Platform targetPlatform) throws PlatformNotFoundException { return transformationDao.create(csar, targetPlatform); } @Autowired TransformationServiceImpl(
TransformationDao transformatio... | @Test(timeout = TEST_EXECUTION_TIMEOUT_MS) public void createTransformation() throws Exception { Transformation expected = new TransformationImpl(csar, PLATFORM1, log, modelMock()); Transformation transformation = service.createTransformation(csar, PLATFORM1); assertTrue(csar.getTransformation(PLATFORM1.id).isPresent()... |
TransformationServiceImpl implements TransformationService { @Override public boolean startTransformation(Transformation transformation) { if (transformation.getState() == TransformationState.READY) { Future<?> taskFuture = executor.submit( new ExecutionTask( transformation, artifactService, pluginService, csarDao.getC... | @Test(timeout = TEST_EXECUTION_TIMEOUT_MS) public void startTransformation() throws Exception { Transformation t = startTransformationInternal(TransformationState.DONE, PASSING_DUMMY.getPlatform()); assertNotNull(t); } |
TransformationController { @RequestMapping( path = "/{platform}/start", method = RequestMethod.POST, produces = "application/hal+json" ) @ApiOperation( value = "Start a Transformation", tags = {"transformations"}, notes = "Starts a transformation that has been created and is ready to get started. To start a transformat... | @Test public void testStartTransformationSuccess() throws Exception { preInitNonCreationTests(); when(transformationService.startTransformation(any(Transformation.class))).thenReturn(true); mvc.perform( post(START_TRANSFORMATION_VALID_URL) .contentType(MediaType.APPLICATION_JSON) .content(INPUTS_VALID) ).andDo(print())... |
TransformationServiceImpl implements TransformationService { @Override public boolean abortTransformation(Transformation transformation) { Future<?> task = tasks.get(transformation); if (task == null) { return false; } if (task.isDone()) { return false; } return task.cancel(true); } @Autowired TransformationServiceImp... | @Test(timeout = TEST_EXECUTION_TIMEOUT_MS) public void stopNotStarted() throws Exception { transformationCreationNoProps(); Transformation t = csar.getTransformations().get(PASSING_DUMMY.getPlatform().id); assertFalse(service.abortTransformation(t)); } |
TransformationServiceImpl implements TransformationService { @Override public boolean deleteTransformation(Transformation transformation) { if (transformation.getState() == TransformationState.TRANSFORMING) { return false; } transformationDao.delete(transformation); tasks.remove(transformation); return true; } @Autowir... | @Test(timeout = TEST_EXECUTION_TIMEOUT_MS) public void deleteTransformation() throws Exception { Transformation transformation = new TransformationImpl(csar, PLATFORM1, log, modelMock()); csar.getTransformations().put(PLATFORM1.id, transformation); service.deleteTransformation(transformation); assertFalse(csar.getTrans... |
TransformationFilesystemDao implements TransformationDao { @Override public File getRootDir(Transformation transformation) { return getRootDir(transformation.getCsar(), transformation.getPlatform()); } @Autowired TransformationFilesystemDao(PlatformService platformService, EffectiveModelFactory effectiveModelFactory);... | @Test public void getRootDir() { doReturn(new File(new File(tmpdir, csar.getIdentifier()), CsarFilesystemDao.TRANSFORMATION_DIR)).when(csarDao).getTransformationsDir(csar); doReturn(new File(tmpdir, csar.getIdentifier())).when(csarDao).getRootDir(csar); File expectedParent = new File(csarDao.getRootDir(csar), CsarFiles... |
TransformationFilesystemDao implements TransformationDao { @Override public Transformation create(Csar csar, Platform platform) throws PlatformNotFoundException { if (!platformService.isSupported(platform)) { throw new PlatformNotFoundException(); } Optional<Transformation> oldTransformation = csar.getTransformation(pl... | @Test public void createDeletesOldFilesAndCreatesBlankDir() { List<File> files = createRandomFiles(transformationRootDir); assertNotEquals(0, transformationRootDir.list().length); when(platformService.isSupported(PLATFORM1)).thenReturn(true); transformationDao.create(csar, PLATFORM1); for (File file : files) { assertFa... |
TransformationFilesystemDao implements TransformationDao { @Override public void delete(Transformation transformation) { transformation.getCsar().getTransformations().remove(transformation.getPlatform().id); File transformationDir = getRootDir(transformation); delete(transformationDir); } @Autowired TransformationFile... | @Test public void delete() { createRandomFiles(transformationRootDir); transformationDao.delete(transformation); assertFalse(transformationRootDir.exists()); } |
TransformationFilesystemDao implements TransformationDao { @Override public Optional<Transformation> find(Csar csar, Platform platform) { Set<Transformation> transformations = readFromDisk(csar); return Optional.ofNullable(transformations.stream() .filter(transformation -> transformation.getCsar().equals(csar) && trans... | @Test public void findFromSpecificCsar() { when(csarDao.getTransformationsDir(csar)).thenReturn(tmpdir); createRandomFiles(new File(tmpdir, PLATFORM1.id)); createRandomFiles(new File(tmpdir, PLATFORM2.id)); createRandomFiles(new File(tmpdir, PLATFORM_NOT_SUPPORTED.id)); when(platformService.findPlatformById(PLATFORM1.i... |
CsarImpl implements Csar { @Override public Optional<Transformation> getTransformation(String platformId) { Transformation t = transformations.get(platformId); return Optional.ofNullable(t); } CsarImpl(File rootDir, String identifier, Log log); @Override boolean validate(); @Override Map<String, Transformation> getTran... | @Test public void getTransformationsForSpecificPlatform() throws Exception { Optional<Transformation> result = csar.getTransformation(PLATFORM1.id); assertTrue(result.isPresent()); assertEquals(transformation1, result.get()); } |
CsarFilesystemDao implements CsarDao { @Override public Csar create(String identifier, InputStream inputStream) { csarMap.remove(identifier); File csarDir = setupDir(identifier); Csar csar = new CsarImpl(getRootDir(identifier), identifier, getLog(identifier)); File transformationDir = new File(csarDir, TRANSFORMATION_D... | @Test public void create() throws Exception { String identifier = "my-csar-checkStateNoPropsSet"; File csarFile = TestCsars.VALID_MINIMAL_DOCKER; InputStream csarStream = new FileInputStream(csarFile); csarDao.create(identifier, csarStream); File csarFolder = new File(generalCsarsDir, identifier); File contentFolder = ... |
CsarFilesystemDao implements CsarDao { @Override public void delete(String identifier) { File csarDir = new File(dataDir, identifier); try { FileUtils.deleteDirectory(csarDir); csarMap.remove(identifier); logger.info("Deleted csar directory '{}'", csarDir); } catch (IOException e) { logger.error("Failed to delete csar ... | @Test public void deleteCsarRemovesDataOnDisk() throws Exception { String identifier = createFakeCsarDirectories(1)[0]; csarDao.delete(identifier); File csarDir = new File(generalCsarsDir, identifier); assertFalse(csarDir.exists()); } |
CsarFilesystemDao implements CsarDao { @Override public Optional<Csar> find(String identifier) { Csar csar = csarMap.get(identifier); return Optional.ofNullable(csar); } @Autowired CsarFilesystemDao(Preferences preferences, @Lazy TransformationDao transformationDao); @PostConstruct void init(); @Override Csar create(S... | @Test public void find() { String identifier = createFakeCsarDirectories(1)[0]; csarDao = new CsarFilesystemDao(preferences, transformationDao); csarDao.init(); Optional<Csar> csar = csarDao.find(identifier); assertTrue(csar.isPresent()); assertEquals(identifier, csar.get().getIdentifier()); } |
CsarFilesystemDao implements CsarDao { @Override public List<Csar> findAll() { List<Csar> csarList = new ArrayList<>(); csarList.addAll(csarMap.values()); return csarList; } @Autowired CsarFilesystemDao(Preferences preferences, @Lazy TransformationDao transformationDao); @PostConstruct void init(); @Override Csar crea... | @Test public void findAll() { int numberOfCsars = 10; createFakeCsarDirectories(numberOfCsars); csarDao = new CsarFilesystemDao(preferences, transformationDao); csarDao.init(); List<Csar> csarList = csarDao.findAll(); assertEquals("Correct amount of csars returned", numberOfCsars, csarList.size()); } |
ServiceGraph extends SimpleDirectedGraph<Entity, Connection> { public Optional<Entity> getEntity(List<String> path) { Entity current = root; for (String segment : path) { Optional<Entity> child = current.getChild(segment); if (child.isPresent()) { current = child.get(); } else { return Optional.empty(); } } return Opti... | @Test public void requirementTest() { currentFile = REQUIREMENT; Optional<Entity> fulfiller = getGraph().getEntity(Lists.newArrayList("topology_template", "node_templates", "test-node", "requirements", "test-requirement1", "node")); assertTrue(fulfiller.isPresent()); Optional<Entity> fulfiller2 = getGraph().getEntity(L... |
ServiceGraph extends SimpleDirectedGraph<Entity, Connection> { public boolean inputsValid() { Map<String, InputProperty> inputs = getInputs(); return inputs.values().stream() .allMatch(InputProperty::isValid); } ServiceGraph(Log log); ServiceGraph(File template, Log log); void finalizeGraph(); boolean inputsValid(); M... | @Test public void allInputsSetTest() { currentFile = INPUT_NO_VALUE; ServiceGraph graph = getGraph(); assertFalse(graph.inputsValid()); currentFile = INPUT; graph = getGraph(); assertTrue(graph.inputsValid()); } |
TransformationController { @RequestMapping( path = "/{platform}/inputs", method = RequestMethod.GET, produces = "application/hal+json" ) @ApiOperation( value = "Retrieve the inputs of this transformation", tags = {"transformations"}, notes = "This Operation returns a list of inputs, specific to the csar and the platfor... | @Test public void getInputsTest() throws Exception { preInitNonCreationTests(); MvcResult result = mvc.perform( get(INPUTS_VALID_URL) ).andDo(print()) .andExpect(status().is(200)) .andExpect(content().contentType(DEFAULT_CHARSET_HAL_JSON)) .andExpect(jsonPath("$.inputs").isArray()) .andExpect(jsonPath("$.inputs").isNot... |
TransformationController { @RequestMapping( path = "/{platform}/delete", method = RequestMethod.DELETE, produces = "application/hal+json" ) @ApiOperation( value = "Delete a transformation", tags = {"transformations"}, notes = "Deletes a transformation and all the coresponding artifacts" ) @ApiResponses({ @ApiResponse( ... | @Test public void deleteTransformation() throws Exception { preInitNonCreationTests(); when(transformationService.deleteTransformation(any(Transformation.class))).thenReturn(true); mvc.perform( delete(DELETE_TRANSFORMATION_VALID_URL) ).andDo(print()) .andExpect(status().is(200)) .andReturn(); }
@Test public void delete... |
NamingUtil { public static String getUniqueName(final String suggestedName, final Set<String> existingNames) { String name = suggestedName != null ? suggestedName.trim() : ""; if (name.isEmpty()) name = "UNDEFINED"; if (existingNames != null && !existingNames.isEmpty()) { if (!isNameTaken(name, existingNames)) return n... | @Test public void testGetUniqueName() { Set<String> names = Sets.newSet( "My Name A", "My Name B", "My Name B(1)", "My Name B(3)", "My Name C(1)", "My Name D_1", "My Name E (1)" ); assertEquals("My Name", NamingUtil.getUniqueName("My Name", names)); assertEquals("My Name", NamingUtil.getUniqueName(" My Name \t", names)... |
LinearNumberInterpolator { public LinearNumberInterpolator(double lowerDomain, double upperDomain, double lowerRange, double upperRange) { this.lowerDomain = lowerDomain; this.lowerRange = lowerRange; this.upperDomain = upperDomain; this.upperRange = upperRange; } LinearNumberInterpolator(double lowerDomain, double upp... | @Test public void testLinearNumberInterpolator() { LinearNumberInterpolator interpolator = new LinearNumberInterpolator(0.5, 1.0, 0.0, 5.0); assertDouble(0.0, interpolator.getRangeValue(0.5)); assertDouble(1.0, interpolator.getRangeValue(0.6)); assertDouble(2.0, interpolator.getRangeValue(0.7)); assertDouble(3.0, inter... |
PathUtil { private PathUtil() {} private PathUtil(); static List<Path> dataSetsRoots(Collection<DataSetParameters> dataSets); static Path commonRoot(List<Path> paths); static Path commonRoot(Path p1, Path p2); } | @Test public void testPathUtil() { { Path c = PathUtil.commonRoot(plist("/a/b/c", "/a/b/d")); assertEquals(Paths.get("/a/b"), c); } { Path c = PathUtil.commonRoot(plist("/a/b/c/d/e", "/a/b/c/x/y", "/a/b/q/w")); assertEquals(Paths.get("/a/b"), c); } { Path c = PathUtil.commonRoot(plist("/x/y/z", "/a/b/d")); assertEquals... |
SimilarityKey { public SimilarityKey(String geneSet1, String geneSet2, String interaction, String name) { Objects.requireNonNull(geneSet1); Objects.requireNonNull(interaction); Objects.requireNonNull(geneSet2); this.geneSet1 = geneSet1; this.geneSet2 = geneSet2; this.interaction = interaction; this.name = name; } Simil... | @Test public void testSimilarityKey() { SimilarityKey k1 = new SimilarityKey("A", "B", "i", null); SimilarityKey k1p = new SimilarityKey("A", "B", "i", null); SimilarityKey k2 = new SimilarityKey("B", "A", "i", null); SimilarityKey k3 = new SimilarityKey("D", "C", "x", null); SimilarityKey k4 = new SimilarityKey("A", "... |
SimilarityKey { @Override public int hashCode() { return Objects.hash(geneSet1.hashCode() + geneSet2.hashCode(), interaction, name); } SimilarityKey(String geneSet1, String geneSet2, String interaction, String name); String getGeneSet1(); String getGeneSet2(); String getInteraction(); boolean isCompound(); String getNa... | @Test public void testSimilarityKeyHashCode() { SimilarityKey k1 = new SimilarityKey("A", "B", "i", null); SimilarityKey k1p = new SimilarityKey("A", "B", "i", null); SimilarityKey k2 = new SimilarityKey("B", "A", "i", null); SimilarityKey k3 = new SimilarityKey("D", "C", "x", null); SimilarityKey k4 = new SimilarityKe... |
SimilarityKey { @Override public String toString() { return isCompound() ? getCompoundName() : String.format("%s (%s_%s) %s", geneSet1, interaction, name, geneSet2); } SimilarityKey(String geneSet1, String geneSet2, String interaction, String name); String getGeneSet1(); String getGeneSet2(); String getInteraction(); b... | @Test public void testSimilarityKeyToString() { SimilarityKey k1 = new SimilarityKey("A", "B", "i", null); SimilarityKey k2 = new SimilarityKey("A", "B", "i", "1"); SimilarityKey k3 = new SimilarityKey("A", "B", "i", "2"); assertEquals("A (i) B", k1.toString()); assertEquals("A (i_1) B", k2.toString()); assertEquals("A... |
OpenPathwayCommonsTask extends AbstractTask { public String getPathwayCommonsURL() { EnrichmentMap map = emManager.getEnrichmentMap(network.getSUID()); if(map == null) return null; int port = Integer.parseInt(cy3props.getProperties().getProperty("rest.port")); String pcBaseUri = propertyManager.getValue(PropertyManager... | @Test public void testPathwayCommonsTask( CyNetworkManager networkManager, OpenBrowser openBrowser, PropertyManager propertyManager, OpenPathwayCommonsTask.Factory pathwayCommonsTaskFactory ) { CyNetwork network = networkManager.getNetwork(map.getNetworkID()); CyNode node = TestUtils.getNodes(network).get("TOP1_PLUS100... |
SpyEventHandlerSupport { void addSpyEventHandler( @Nonnull final SpyEventHandler handler ) { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> !_spyEventHandlers.contains( handler ), () -> "Arez-0102: Attempting to add handler " + handler + " that is already " + "in the list of spy handlers." ); } _spyEventH... | @Test public void addSpyEventHandler_alreadyExists() { final SpyEventHandlerSupport support = new SpyEventHandlerSupport(); final SpyEventHandler handler = new TestSpyEventHandler( Arez.context() ); support.addSpyEventHandler( handler ); assertInvariantFailure( () -> support.addSpyEventHandler( handler ), "Arez-0102: A... |
ArezContext { public <T> T action( @Nonnull final Function<T> executable ) throws Throwable { return action( executable, 0 ); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( @Nonnull final String type, @Nonnull final Object id ); @OmitSymbo... | @Test public void verifyActionFlags_badVerifyAction() { final Procedure executable = () -> { }; assertInvariantFailure( () -> Arez.context() .action( executable, ActionFlags.VERIFY_ACTION_REQUIRED | ActionFlags.NO_VERIFY_ACTION_REQUIRED ), "Arez-0127: Flags passed to action 'Action@1' include both VERIFY_ACTION_REQUIRE... |
ArezContext { public <T> T safeAction( @Nonnull final SafeFunction<T> executable ) { return safeAction( executable, 0 ); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( @Nonnull final String type, @Nonnull final Object id ); @OmitSymbol( un... | @Test public void safeAction_procedure_verifyActionRequired_false() { final SafeProcedure procedure = ValueUtil::randomString; Arez.context().safeAction( ValueUtil.randomString(), procedure, ActionFlags.NO_VERIFY_ACTION_REQUIRED ); }
@Test public void safeAction_procedure_verifyActionRequired_true_butInvariantsDisabled... |
ObserverInfoImpl implements ObserverInfo { @Nonnull @Override public ComputableValueInfo asComputableValue() { return _observer.getComputableValue().asInfo(); } ObserverInfoImpl( @Nonnull final Spy spy, @Nonnull final Observer observer ); @Nonnull @Override String getName(); @Override boolean isActive(); @Override bool... | @Test public void asComputableValue() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final ComputableValue<String> computableValue = context.computable( name, () -> "" ); final Observer observer = computableValue.getObserver(); final ObserverInfo info = observer.asInfo(); as... |
ArezContext { @OmitSymbol( unless = "arez.enable_observer_error_handlers" ) public void addObserverErrorHandler( @Nonnull final ObserverErrorHandler handler ) { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areObserverErrorHandlersEnabled, () -> "Arez-0182: ArezContext.addObserverErrorHandler() invoked when Ar... | @Test public void addObserverErrorHandler_whenDisabled() { ArezTestUtil.disableObserverErrorHandlers(); final ObserverErrorHandler handler = ( o, e, t ) -> { }; assertInvariantFailure( () -> Arez.context().addObserverErrorHandler( handler ), "Arez-0182: ArezContext.addObserverErrorHandler() invoked when Arez.areObserve... |
ArezContext { @OmitSymbol( unless = "arez.enable_observer_error_handlers" ) public void removeObserverErrorHandler( @Nonnull final ObserverErrorHandler handler ) { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areObserverErrorHandlersEnabled, () -> "Arez-0181: ArezContext.removeObserverErrorHandler() invoked w... | @Test public void removeObserverErrorHandler_whenDisabled() { ArezTestUtil.disableObserverErrorHandlers(); final ArezContext context = Arez.context(); final ObserverErrorHandler handler = ( o, e, t ) -> { }; assertInvariantFailure( () -> context.removeObserverErrorHandler( handler ), "Arez-0181: ArezContext.removeObser... |
ArezContext { void scheduleReaction( @Nonnull final Observer observer ) { if ( willPropagateSpyEvents() ) { getSpy().reportSpyEvent( new ObserveScheduleEvent( observer.asInfo() ) ); } if ( Arez.shouldEnforceTransactionType() && isTransactionActive() && Arez.shouldCheckInvariants() ) { invariant( () -> getTransaction().... | @Test public void scheduleReaction() { final ArezContext context = Arez.context(); final Observer observer = context.observer( new CountAndObserveProcedure() ); assertEquals( context.getTaskQueue().getOrderedTasks().count(), 0L ); context.scheduleReaction( observer ); assertEquals( context.getTaskQueue().getOrderedTask... |
ObserverInfoImpl implements ObserverInfo { @Nullable @Override public ComponentInfo getComponent() { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areNativeComponentsEnabled, () -> "Arez-0108: Spy.getComponent invoked when Arez.areNativeComponentsEnabled() returns false." ); } final Component component = _obse... | @Test public void getComponent_Observer_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final Spy spy = context.getSpy(); final Observer observer = context.observer( AbstractTest::observeADependency ); assertInvariantFailure( () -> spy.asObserverInfo( obs... |
ArezContext { @Nonnull public <T> ComputableValue<T> computable( @Nonnull final SafeFunction<T> function ) { return computable( function, 0 ); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( @Nonnull final String type, @Nonnull final Object... | @Test public void computableValue() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final SafeFunction<String> function = () -> { observeADependency(); return ""; }; final Procedure onActivate = ValueUtil::randomString; final Procedure onDeactivate = ValueUtil::randomString; ... |
ArezContext { @Nonnull public Observer observer( @Nonnull final Procedure observe ) { return observer( observe, 0 ); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( @Nonnull final String type, @Nonnull final Object id ); @OmitSymbol( unless... | @Test public void autorun_noObservers_manualReportStaleAllowed() { ignoreObserverErrors(); final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); context.observer( callCount::incrementAndGet, Observer.Flags.AREZ_OR_EXTERNAL_DEPENDENCIES ); assertEquals( callCount.get(), 1 ); as... |
ObserverInfoImpl implements ObserverInfo { @Override public int hashCode() { return _observer.hashCode(); } ObserverInfoImpl( @Nonnull final Spy spy, @Nonnull final Observer observer ); @Nonnull @Override String getName(); @Override boolean isActive(); @Override boolean isRunning(); @Override boolean isScheduled(); @Ov... | @SuppressWarnings( "EqualsWithItself" ) @Test public void equalsAndHashCode() { final ArezContext context = Arez.context(); final ObservableValue<Object> observableValue = context.observable(); final Observer observer1 = context.observer( ValueUtil.randomString(), observableValue::reportObserved ); final Observer obser... |
ArezContext { @Nonnull public Observer tracker( @Nonnull final Procedure onDepsChange ) { return tracker( onDepsChange, 0 ); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( @Nonnull final String type, @Nonnull final Object id ); @OmitSymbol... | @Test public void tracker() { final ArezContext context = Arez.context(); final TestSpyEventHandler handler = TestSpyEventHandler.subscribe( context ); final String name = ValueUtil.randomString(); final AtomicInteger callCount = new AtomicInteger(); final Observer observer = context.tracker( null, name, callCount::inc... |
ArezContext { @Nonnull public <T> ObservableValue<T> observable() { return observable( null ); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( @Nonnull final String type, @Nonnull final Object id ); @OmitSymbol( unless = "arez.enable_native... | @Test public void createObservable() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final ObservableValue<?> observableValue = context.observable( name ); assertEquals( observableValue.getName(), name ); assertNull( observableValue.getAccessor() ); assertNull( observableValu... |
ArezContext { @Nonnull public SchedulerLock pauseScheduler() { _schedulerLockCount++; return new SchedulerLock( Arez.areZonesEnabled() ? this : null ); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( @Nonnull final String type, @Nonnull fin... | @Test public void pauseScheduler() { final ArezContext context = Arez.context(); assertFalse( context.isSchedulerPaused() ); assertEquals( context.getSchedulerLockCount(), 0 ); final SchedulerLock lock1 = context.pauseScheduler(); assertEquals( context.getSchedulerLockCount(), 1 ); assertTrue( context.isSchedulerPaused... |
ArezContext { void releaseSchedulerLock() { _schedulerLockCount--; if ( Arez.shouldCheckInvariants() ) { invariant( () -> _schedulerLockCount >= 0, () -> "Arez-0016: releaseSchedulerLock() reduced schedulerLockCount below 0." ); } triggerScheduler(); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "ar... | @Test public void releaseSchedulerLock_whenNoLock() { assertInvariantFailure( () -> Arez.context().releaseSchedulerLock(), "Arez-0016: releaseSchedulerLock() reduced schedulerLockCount below 0." ); } |
ArezContext { @OmitSymbol( unless = "arez.enable_native_components" ) @Nonnull public Component component( @Nonnull final String type, @Nonnull final Object id ) { return component( type, id, Arez.areNamesEnabled() ? type + "@" + id : null ); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enabl... | @Test public void createComponent_spyEventHandlerPresent() { final ArezContext context = Arez.context(); final TestSpyEventHandler handler = TestSpyEventHandler.subscribe( context ); final Component component = context.component( ValueUtil.randomString(), ValueUtil.randomString(), ValueUtil.randomString() ); handler.as... |
ComputableValueInfoImpl implements ComputableValueInfo { @Override public boolean isComputing() { return _computableValue.isComputing(); } ComputableValueInfoImpl( @Nonnull final ComputableValue<?> computableValue ); @Nonnull @Override String getName(); @Override boolean isComputing(); @Nonnull @Override Priority getPr... | @Test public void isComputing() { final ArezContext context = Arez.context(); final Spy spy = context.getSpy(); final ComputableValue<String> computableValue = context.computable( () -> "" ); assertFalse( spy.asComputableValueInfo( computableValue ).isComputing() ); computableValue.setComputing( true ); assertTrue( spy... |
ArezContext { @OmitSymbol( unless = "arez.enable_native_components" ) public boolean isComponentPresent( @Nonnull final String type, @Nonnull final Object id ) { apiInvariant( Arez::areNativeComponentsEnabled, () -> "Arez-0135: ArezContext.isComponentPresent() invoked when Arez.areNativeComponentsEnabled() returns fals... | @Test public void isComponentPresent_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final String id = ValueUtil.randomString(); assertInvariantFailure( () -> context.isComponentPresent( type, id ), "Arez-0135... |
ArezContext { @OmitSymbol( unless = "arez.enable_native_components" ) void deregisterComponent( @Nonnull final Component component ) { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areNativeComponentsEnabled, () -> "Arez-0006: ArezContext.deregisterComponent() invoked when Arez.areNativeComponentsEnabled() ret... | @Test public void deregisterComponent_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final Component component = new Component( context, ValueUtil.randomString(), ValueUtil.randomString(), ValueUtil.randomString(), null, null ); assertInvariantFailure( (... |
ArezContext { @OmitSymbol( unless = "arez.enable_native_components" ) @Nullable Component findComponent( @Nonnull final String type, @Nonnull final Object id ) { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areNativeComponentsEnabled, () -> "Arez-0010: ArezContext.findComponent() invoked when Arez.areNativeCo... | @Test public void findComponent_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); final String id = ValueUtil.randomString(); assertInvariantFailure( () -> context.findComponent( type, id ), "Arez-0010: ArezCont... |
ArezContext { @OmitSymbol( unless = "arez.enable_native_components" ) @Nonnull Collection<Component> findAllComponentsByType( @Nonnull final String type ) { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areNativeComponentsEnabled, () -> "Arez-0011: ArezContext.findAllComponentsByType() invoked when Arez.areNat... | @Test public void findAllComponentsByType_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final String type = ValueUtil.randomString(); assertInvariantFailure( () -> context.findAllComponentsByType( type ), "Arez-0011: ArezContext.findAllComponentsByType(... |
ArezContext { @OmitSymbol( unless = "arez.enable_references" ) @Nonnull public Locator locator() { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( Arez::areReferencesEnabled, () -> "Arez-0192: ArezContext.locator() invoked but Arez.areReferencesEnabled() returned false." ); } assert null != _locator; return _loc... | @Test public void locator() { final ArezContext context = Arez.context(); final Locator locator = context.locator(); assertNotNull( locator ); assertNull( locator.findById( String.class, "21" ) ); final TypeBasedLocator worker = new TypeBasedLocator(); worker.registerLookup( String.class, String::valueOf ); final Dispo... |
ArezContext { @OmitSymbol( unless = "arez.enable_references" ) @Nonnull public Disposable registerLocator( @Nonnull final Locator locator ) { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( Arez::areReferencesEnabled, () -> "Arez-0191: ArezContext.registerLocator invoked but Arez.areReferencesEnabled() returned ... | @Test public void registerLocator_referencesDisabled() { ArezTestUtil.disableReferences(); assertInvariantFailure( () -> Arez.context().registerLocator( new TypeBasedLocator() ), "Arez-0191: ArezContext.registerLocator invoked but Arez.areReferencesEnabled() returned false." ); } |
ArezContext { @Nonnull public Task task( @Nonnull final SafeProcedure work ) { return task( null, work ); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( @Nonnull final String type, @Nonnull final Object id ); @OmitSymbol( unless = "arez.en... | @Test public void task() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final String name = ValueUtil.randomString(); final TestSpyEventHandler handler = TestSpyEventHandler.subscribe( context ); final Task task = context.task( name, callCount::incrementAndGet, 0 ); a... |
ComputableValueInfoImpl implements ComputableValueInfo { @Nonnull Transaction getTransactionComputing() { assert _computableValue.isComputing(); final Transaction transaction = getTrackerTransaction( _computableValue.getObserver() ); if ( Arez.shouldCheckInvariants() ) { invariant( () -> transaction != null, () -> "Are... | @Test public void getTransactionComputing() { final ArezContext context = Arez.context(); final ComputableValue<String> computableValue = context.computable( () -> "" ); final Observer observer = computableValue.getObserver(); final Observer observer2 = context.observer( new CountAndObserveProcedure() ); computableValu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.