method2testcases
stringlengths
118
3.08k
### Question: 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("Disk size: '{}'", maxSize); return maxSize; } if (diskSize < minSize) { logger.debug("Disk size: '{}'", minSize); return minSize; } logger.debug("Disk size: '{}'", diskSize); return diskSize; } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); String mapOsCapabilityToImageId(OsCapability osCapability); String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction); Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability); void mapDiskSize(ComputeCapability computeCapability, CloudFormationModule cfnModule, String nodeName); static final String EC2_DISTINCTION; static final String RDS_DISTINCTION; }### Answer: @Test public void testMapComputeCapabilityToRDSAllocatedStorage() { int newDiskSize = capabilityMapper.mapComputeCapabilityToRDSAllocatedStorage(containerCapability); Assert.assertEquals(newDiskSize, expectedDiskSize); }
### Question: 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(); static final String SHEBANG; static final String SOURCE_UTIL_ALL; static final String SUBCOMMAND_EXIT; }### Answer: @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.get(result.size() - 1)); }
### Question: 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 = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { extractFile(zipIn, filePath); } else { logger.trace("Creating directory: {}", filePath); File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); return true; } static boolean unzip(ZipInputStream zipIn, String destDirectory); static void compressDirectory(File directory, OutputStream output); }### Answer: @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 FileInputStream(TestCsars.VALID_LAMP_INPUT_TEMPLATE)); boolean result = ZipUtility.unzip(is, tmpdir.toString()); assertFalse(result); }
### Question: 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); BufferedOutputStream accessAsOutputStream(String relativePath); String read(String relativePath); String getAbsolutePath(String relativePath); void delete(String relativePath); void createDirectories(String relativePath); }### Answer: @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 copyDirRecursively() throws IOException { String dirname = "dir"; File dir = new File(sourceDir, dirname); dir.mkdir(); for (int i = 0; i < 10; i++) { new File(dir, String.valueOf(i)).createNewFile(); } File expectedDir = new File(targetDir, dirname); assertFalse(expectedDir.exists()); access.copy(dirname); assertTrue(expectedDir.exists()); for (int i = 0; i < 10; i++) { assertTrue(new File(expectedDir, String.valueOf(i)).exists()); } } @Test(expected = FileNotFoundException.class) public void copyInvalidPathThrowsException() throws IOException { String file = "nonexistent_file"; access.copy(file); } @Test public void copySourceToGivenTargetSuccessful() throws IOException { String filename = "some-file"; File file = new File(sourceDir, filename); file.createNewFile(); String alternativeDirName = "some-dir/nested/even-deeper"; File alternateDirectory = new File(targetDir, alternativeDirName); File targetFile = new File(alternateDirectory, filename); String relativeTargetPath = String.format("%s/%s", alternativeDirName, filename); access.copy(filename, relativeTargetPath); assertTrue(targetFile.exists()); }
### Question: 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 OutputStream for file '{}'", target); throw e; } } PluginFileAccess(File sourceDir, File targetDir, Log log); void copy(String relativePath); void copy(String relativeSourcePath, String relativeTargetPath); BufferedLineWriter access(String relativePath); BufferedOutputStream accessAsOutputStream(String relativePath); String read(String relativePath); String getAbsolutePath(String relativePath); void delete(String relativePath); void createDirectories(String relativePath); }### Answer: @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)); assertEquals(fileContent, result.get(result.size() - 2)); assertEquals(secondString, result.get(result.size() - 1)); } @Test(expected = IOException.class) public void writePathIsDirectoryThrowsException() throws IOException { targetFile.mkdir(); access.access(targetFileName); } @Test public void writeSubDirectoriesGetAutomaticallyCreated() throws IOException { String path = "test/some/subdirs/filename"; access.access(path).append(fileContent).close(); File targetFile = new File(targetDir, path); assertTrue(targetFile.isFile()); assertEquals(fileContent, FileUtils.readFileToString(targetFile)); }
### Question: 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 targetDir, Log log); void copy(String relativePath); void copy(String relativeSourcePath, String relativeTargetPath); BufferedLineWriter access(String relativePath); BufferedOutputStream accessAsOutputStream(String relativePath); String read(String relativePath); String getAbsolutePath(String relativePath); void delete(String relativePath); void createDirectories(String relativePath); }### Answer: @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(fileContent, result); } @Test(expected = IOException.class) public void readFileNotExists() throws IOException { String path = "nonexistent-file"; access.read(path); }
### Question: 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)); } } PluginFileAccess(File sourceDir, File targetDir, Log log); void copy(String relativePath); void copy(String relativeSourcePath, String relativeTargetPath); BufferedLineWriter access(String relativePath); BufferedOutputStream accessAsOutputStream(String relativePath); String read(String relativePath); String getAbsolutePath(String relativePath); void delete(String relativePath); void createDirectories(String relativePath); }### Answer: @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 = FileNotFoundException.class) public void getAbsolutePathNoSuchFile() throws FileNotFoundException { String filename = "nonexistent-file"; access.getAbsolutePath(filename); fail("getAbsolutePath() should have raised FileNotFoundException."); }
### Question: 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 access(String relativePath); BufferedOutputStream accessAsOutputStream(String relativePath); String read(String relativePath); String getAbsolutePath(String relativePath); void delete(String relativePath); void createDirectories(String relativePath); }### Answer: @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()); }
### Question: 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); BufferedLineWriter access(String relativePath); BufferedOutputStream accessAsOutputStream(String relativePath); String read(String relativePath); String getAbsolutePath(String relativePath); void delete(String relativePath); void createDirectories(String relativePath); }### Answer: @Test public void createFolder() { String folder = "some-folder/some-subfolder/some-subsubfolder"; access.createDirectories(folder); File expectedFolder = new File(targetDir, folder); assertTrue(expectedFolder.exists()); }
### Question: TransformationServiceImpl implements TransformationService { @Override public Transformation createTransformation(Csar csar, Platform targetPlatform) throws PlatformNotFoundException { return transformationDao.create(csar, targetPlatform); } @Autowired TransformationServiceImpl( TransformationDao transformationDao, PluginService pluginService, @Lazy CsarDao csarDao, ArtifactService artifactService ); @Override Transformation createTransformation(Csar csar, Platform targetPlatform); @Override boolean startTransformation(Transformation transformation); @Override boolean abortTransformation(Transformation transformation); @Override boolean deleteTransformation(Transformation transformation); }### Answer: @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()); assertEquals(expected, transformation); } @Test(timeout = TEST_EXECUTION_TIMEOUT_MS) public void transformationCreationNoProps() throws Exception { Transformation t = service.createTransformation(csar, PASSING_DUMMY.getPlatform()); assertTrue(csar.getTransformation(PASSING_DUMMY.getPlatform().id).isPresent()); assertNotNull(t); assertEquals(TransformationState.READY, t.getState()); } @Test(expected = PlatformNotFoundException.class) public void transformationCreationPlatformNotFound() throws PlatformNotFoundException { service.createTransformation(csar, PLATFORM_NOT_SUPPORTED); } @Test(timeout = TEST_EXECUTION_TIMEOUT_MS) public void transformationCreationInputNeeded() throws Exception { Transformation t = service.createTransformation(csar, PLATFORM_PASSING_INPUT_REQUIRED_DUMMY); assertTrue(csar.getTransformation(PLATFORM_PASSING_INPUT_REQUIRED_DUMMY.id).isPresent()); assertNotNull(t); assertEquals(TransformationState.INPUT_REQUIRED, t.getState()); }
### Question: TransformationServiceImpl implements TransformationService { @Override public boolean startTransformation(Transformation transformation) { if (transformation.getState() == TransformationState.READY) { Future<?> taskFuture = executor.submit( new ExecutionTask( transformation, artifactService, pluginService, csarDao.getContentDir(transformation.getCsar()), transformationDao.getContentDir(transformation) ) ); tasks.put(transformation, taskFuture); return true; } return false; } @Autowired TransformationServiceImpl( TransformationDao transformationDao, PluginService pluginService, @Lazy CsarDao csarDao, ArtifactService artifactService ); @Override Transformation createTransformation(Csar csar, Platform targetPlatform); @Override boolean startTransformation(Transformation transformation); @Override boolean abortTransformation(Transformation transformation); @Override boolean deleteTransformation(Transformation transformation); }### Answer: @Test(timeout = TEST_EXECUTION_TIMEOUT_MS) public void startTransformation() throws Exception { Transformation t = startTransformationInternal(TransformationState.DONE, PASSING_DUMMY.getPlatform()); assertNotNull(t); }
### Question: 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 TransformationServiceImpl( TransformationDao transformationDao, PluginService pluginService, @Lazy CsarDao csarDao, ArtifactService artifactService ); @Override Transformation createTransformation(Csar csar, Platform targetPlatform); @Override boolean startTransformation(Transformation transformation); @Override boolean abortTransformation(Transformation transformation); @Override boolean deleteTransformation(Transformation transformation); }### Answer: @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)); }
### Question: TransformationServiceImpl implements TransformationService { @Override public boolean deleteTransformation(Transformation transformation) { if (transformation.getState() == TransformationState.TRANSFORMING) { return false; } transformationDao.delete(transformation); tasks.remove(transformation); return true; } @Autowired TransformationServiceImpl( TransformationDao transformationDao, PluginService pluginService, @Lazy CsarDao csarDao, ArtifactService artifactService ); @Override Transformation createTransformation(Csar csar, Platform targetPlatform); @Override boolean startTransformation(Transformation transformation); @Override boolean abortTransformation(Transformation transformation); @Override boolean deleteTransformation(Transformation transformation); }### Answer: @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.getTransformations().containsValue(transformation)); }
### Question: TransformationFilesystemDao implements TransformationDao { @Override public File getRootDir(Transformation transformation) { return getRootDir(transformation.getCsar(), transformation.getPlatform()); } @Autowired TransformationFilesystemDao(PlatformService platformService, EffectiveModelFactory effectiveModelFactory); @Override Transformation create(Csar csar, Platform platform); @Override void delete(Transformation transformation); @Override Optional<Transformation> find(Csar csar, Platform platform); @Override List<Transformation> find(Csar csar); @Override TargetArtifact createTargetArtifact(Transformation transformation); @Override File getRootDir(Transformation transformation); @Override File getContentDir(Transformation transformation); @Override void setCsarDao(CsarDao csarDao); final static String ARTIFACT_FAILED_REGEX; final static String ARTIFACT_SUCCESSFUL_REGEX; final static String CONTENT_DIR; }### Answer: @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), CsarFilesystemDao.TRANSFORMATION_DIR); File expected = new File(expectedParent, PLATFORM1.id); File actual = transformationDao.getRootDir(transformation); assertEquals(expected, actual); }
### Question: 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(platform.id); if (oldTransformation.isPresent()) { delete(oldTransformation.get()); } else { delete(getRootDir(csar, platform)); } Transformation transformation = createTransformation(csar, platform); csar.getTransformations().put(platform.id, transformation); getContentDir(transformation).mkdirs(); return transformation; } @Autowired TransformationFilesystemDao(PlatformService platformService, EffectiveModelFactory effectiveModelFactory); @Override Transformation create(Csar csar, Platform platform); @Override void delete(Transformation transformation); @Override Optional<Transformation> find(Csar csar, Platform platform); @Override List<Transformation> find(Csar csar); @Override TargetArtifact createTargetArtifact(Transformation transformation); @Override File getRootDir(Transformation transformation); @Override File getContentDir(Transformation transformation); @Override void setCsarDao(CsarDao csarDao); final static String ARTIFACT_FAILED_REGEX; final static String ARTIFACT_SUCCESSFUL_REGEX; final static String CONTENT_DIR; }### Answer: @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) { assertFalse(file.exists()); } assertTrue(transformationRootDir.exists()); File[] result = transformationRootDir.listFiles(); assertEquals(1, result.length); assertEquals(TransformationFilesystemDao.CONTENT_DIR, result[0].getName()); assertEquals(1, result[0].list().length); }
### Question: TransformationFilesystemDao implements TransformationDao { @Override public void delete(Transformation transformation) { transformation.getCsar().getTransformations().remove(transformation.getPlatform().id); File transformationDir = getRootDir(transformation); delete(transformationDir); } @Autowired TransformationFilesystemDao(PlatformService platformService, EffectiveModelFactory effectiveModelFactory); @Override Transformation create(Csar csar, Platform platform); @Override void delete(Transformation transformation); @Override Optional<Transformation> find(Csar csar, Platform platform); @Override List<Transformation> find(Csar csar); @Override TargetArtifact createTargetArtifact(Transformation transformation); @Override File getRootDir(Transformation transformation); @Override File getContentDir(Transformation transformation); @Override void setCsarDao(CsarDao csarDao); final static String ARTIFACT_FAILED_REGEX; final static String ARTIFACT_SUCCESSFUL_REGEX; final static String CONTENT_DIR; }### Answer: @Test public void delete() { createRandomFiles(transformationRootDir); transformationDao.delete(transformation); assertFalse(transformationRootDir.exists()); }
### Question: 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> getTransformations(); @Override Optional<Transformation> getTransformation(String platformId); @Override String getIdentifier(); @Override Log getLog(); @Override List<LifecyclePhase> getLifecyclePhases(); @Override LifecyclePhase getLifecyclePhase(Phase phase); @Override boolean equals(Object obj); @Override int hashCode(); @Override void setTransformations(List<Transformation> transformations); @Override File getContentDir(); @Override File getTemplate(); @Override String toString(); }### Answer: @Test public void getTransformationsForSpecificPlatform() throws Exception { Optional<Transformation> result = csar.getTransformation(PLATFORM1.id); assertTrue(result.isPresent()); assertEquals(transformation1, result.get()); }
### Question: 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_DIR); transformationDir.mkdir(); unzip(identifier, inputStream, csar, csarDir); csarMap.put(identifier, csar); return csar; } @Autowired CsarFilesystemDao(Preferences preferences, @Lazy TransformationDao transformationDao); @PostConstruct void init(); @Override Csar create(String identifier, InputStream inputStream); @Override void delete(String identifier); @Override Optional<Csar> find(String identifier); @Override List<Csar> findAll(); @Override File getRootDir(Csar csar); @Override File getContentDir(Csar csar); @Override File getTransformationsDir(Csar csar); final static String CSARS_DIR; final static String TRANSFORMATION_DIR; }### Answer: @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 = new File(csarFolder, CsarImpl.CONTENT_DIR); File transformationFolder = new File(csarFolder, CsarFilesystemDao.TRANSFORMATION_DIR); assertTrue(contentFolder.isDirectory()); assertTrue(transformationFolder.isDirectory()); assertTrue(contentFolder.list().length == 1); }
### Question: 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 directory with identifier '{}'", identifier, e); } } @Autowired CsarFilesystemDao(Preferences preferences, @Lazy TransformationDao transformationDao); @PostConstruct void init(); @Override Csar create(String identifier, InputStream inputStream); @Override void delete(String identifier); @Override Optional<Csar> find(String identifier); @Override List<Csar> findAll(); @Override File getRootDir(Csar csar); @Override File getContentDir(Csar csar); @Override File getTransformationsDir(Csar csar); final static String CSARS_DIR; final static String TRANSFORMATION_DIR; }### Answer: @Test public void deleteCsarRemovesDataOnDisk() throws Exception { String identifier = createFakeCsarDirectories(1)[0]; csarDao.delete(identifier); File csarDir = new File(generalCsarsDir, identifier); assertFalse(csarDir.exists()); }
### Question: 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(String identifier, InputStream inputStream); @Override void delete(String identifier); @Override Optional<Csar> find(String identifier); @Override List<Csar> findAll(); @Override File getRootDir(Csar csar); @Override File getContentDir(Csar csar); @Override File getTransformationsDir(Csar csar); final static String CSARS_DIR; final static String TRANSFORMATION_DIR; }### Answer: @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()); }
### Question: 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 create(String identifier, InputStream inputStream); @Override void delete(String identifier); @Override Optional<Csar> find(String identifier); @Override List<Csar> findAll(); @Override File getRootDir(Csar csar); @Override File getContentDir(Csar csar); @Override File getTransformationsDir(Csar csar); final static String CSARS_DIR; final static String TRANSFORMATION_DIR; }### Answer: @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()); }
### Question: 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(); Map<String, InputProperty> getInputs(); Map<String, OutputProperty> getOutputs(); void addEntity(Entity entity); Optional<Entity> getEntity(List<String> path); Optional<Entity> getEntity(EntityId id); Entity getEntityOrThrow(EntityId id); Iterator<Entity> iterator(EntityId id); void replaceEntity(Entity source, Entity target); void addConnection(Entity source, Entity target, String connectionName); Collection<Entity> getChildren(EntityId id); Logger getLogger(); Log getLog(); }### Answer: @Test public void allInputsSetTest() { currentFile = INPUT_NO_VALUE; ServiceGraph graph = getGraph(); assertFalse(graph.inputsValid()); currentFile = INPUT; graph = getGraph(); assertTrue(graph.inputsValid()); }
### Question: 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 upperDomain, double lowerRange, double upperRange); double getRangeValue(double domainValue); LinearNumberInterpolator withDomainCutoff(final double lowerValue, final double upperValue); }### Answer: @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, interpolator.getRangeValue(0.8)); assertDouble(4.0, interpolator.getRangeValue(0.9)); assertDouble(5.0, interpolator.getRangeValue(1.0)); assertDouble(-1.0, interpolator.getRangeValue(0.4)); assertDouble(6.0, interpolator.getRangeValue(1.1)); }
### Question: 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); }### Answer: @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(Paths.get("/"), c); } { Path c = PathUtil.commonRoot(plist("/", "/a/b/d")); assertEquals(Paths.get("/"), c); } { Path c = PathUtil.commonRoot(plist("/x/y/z", "a/b/d")); assertNull(c); } { Path c = PathUtil.commonRoot(plist("/x/y/z", null)); assertNull(c); } }
### Question: 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; } SimilarityKey(String geneSet1, String geneSet2, String interaction, String name); String getGeneSet1(); String getGeneSet2(); String getInteraction(); boolean isCompound(); String getName(); @Override int hashCode(); @Override boolean equals(Object o); String getCompoundName(); @Override String toString(); final String geneSet1; final String geneSet2; final String interaction; final String name; }### Answer: @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", "B", "x", null); assertEquals(k1, k1); assertEquals(k1, k1p); assertEquals(k1, k2); assertEquals(k2, k1); assertNotEquals(k1, k3); assertNotEquals(k1, k4); Set<SimilarityKey> keys = new HashSet<>(); Collections.addAll(keys, k1, k1p, k2, k3); assertEquals(2, keys.size()); }
### Question: 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 getName(); @Override int hashCode(); @Override boolean equals(Object o); String getCompoundName(); @Override String toString(); final String geneSet1; final String geneSet2; final String interaction; final String name; }### Answer: @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 SimilarityKey("A", "B", "x", null); assertEquals(k1.hashCode(), k1p.hashCode()); assertEquals(k1.hashCode(), k2.hashCode()); assertEquals(k2.hashCode(), k1.hashCode()); assertNotEquals(k1.hashCode(), k3.hashCode()); assertNotEquals(k1.hashCode(), k4.hashCode()); }
### Question: 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(); boolean isCompound(); String getName(); @Override int hashCode(); @Override boolean equals(Object o); String getCompoundName(); @Override String toString(); final String geneSet1; final String geneSet2; final String interaction; final String name; }### Answer: @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 (i_2) B", k3.toString()); }
### Question: 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.PATHWAY_COMMONS_URL); String nodeLabel = getNodeLabel(map); try { String returnPath; if(node == null) returnPath = "/enrichmentmap/expressions/heatmap"; else returnPath = String.format("/enrichmentmap/expressions/%s/%s", network.getSUID(), node.getSUID()); String returnUri = new URIBuilder() .setScheme("http") .setHost("localhost") .setPath(returnPath) .setPort(port) .build() .toString(); String pcUri = new URIBuilder(pcBaseUri) .addParameter("uri", returnUri) .addParameter("q", nodeLabel) .build() .toString(); return pcUri; } catch(URISyntaxException e) { e.printStackTrace(); return null; } } @AssistedInject OpenPathwayCommonsTask(@Assisted CyNetwork network, @Assisted CyNode node); @AssistedInject OpenPathwayCommonsTask(@Assisted CyNetwork network); String getPathwayCommonsURL(); @Override void run(TaskMonitor taskMonitor); static final String DEFAULT_BASE_URL; }### Answer: @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"); propertyManager.setValue(PropertyManager.PATHWAY_COMMONS_URL, "http: @SuppressWarnings("deprecation") String returnUri = URLEncoder.encode("http: String expectedUri = "http: OpenPathwayCommonsTask task = pathwayCommonsTaskFactory.create(network, node); String uri = task.getPathwayCommonsURL(); assertEquals(expectedUri, uri); }
### Question: 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." ); } _spyEventHandlers.add( Objects.requireNonNull( handler ) ); } }### Answer: @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: Attempting to add handler " + handler + " that is already " + "in the list of spy handlers." ); }
### Question: 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 boolean isRunning(); @Override boolean isScheduled(); @Override boolean isComputableValue(); @Override boolean isReadOnly(); @Nonnull @Override Priority getPriority(); @Nonnull @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nullable @Override ComponentInfo getComponent(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @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(); assertEquals( info.getName(), name ); assertTrue( info.isComputableValue() ); assertEquals( info.asComputableValue().getName(), computableValue.getName() ); assertFalse( info.isActive() ); }
### Question: 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 = _observer.getComponent(); return null == component ? null : component.asInfo(); } ObserverInfoImpl( @Nonnull final Spy spy, @Nonnull final Observer observer ); @Nonnull @Override String getName(); @Override boolean isActive(); @Override boolean isRunning(); @Override boolean isScheduled(); @Override boolean isComputableValue(); @Override boolean isReadOnly(); @Nonnull @Override Priority getPriority(); @Nonnull @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nullable @Override ComponentInfo getComponent(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @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( observer ).getComponent(), "Arez-0108: Spy.getComponent invoked when Arez.areNativeComponentsEnabled() returns false." ); }
### Question: 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(); @Override boolean isComputableValue(); @Override boolean isReadOnly(); @Nonnull @Override Priority getPriority(); @Nonnull @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nullable @Override ComponentInfo getComponent(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @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 observer2 = context.observer( ValueUtil.randomString(), observableValue::reportObserved ); final ObserverInfo info1a = observer1.asInfo(); final ObserverInfo info1b = new ObserverInfoImpl( context.getSpy(), observer1 ); final ObserverInfo info2 = observer2.asInfo(); assertNotEquals( info1a, "" ); assertEquals( info1a, info1a ); assertEquals( info1b, info1a ); assertNotEquals( info2, info1a ); assertEquals( info1a, info1b ); assertEquals( info1b, info1b ); assertNotEquals( info2, info1b ); assertNotEquals( info1a, info2 ); assertNotEquals( info1b, info2 ); assertEquals( info2, info2 ); assertEquals( info1a.hashCode(), observer1.hashCode() ); assertEquals( info1a.hashCode(), info1b.hashCode() ); assertEquals( info2.hashCode(), observer2.hashCode() ); }
### Question: 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 getPriority(); @Override boolean isActive(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @OmitSymbol( unless = "arez.enable_property_introspection" ) @Nullable @Override Object getValue(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @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.asComputableValueInfo( computableValue ).isComputing() ); }
### Question: ComputableValueInfoImpl implements ComputableValueInfo { @Nonnull Transaction getTransactionComputing() { assert _computableValue.isComputing(); final Transaction transaction = getTrackerTransaction( _computableValue.getObserver() ); if ( Arez.shouldCheckInvariants() ) { invariant( () -> transaction != null, () -> "Arez-0106: ComputableValue named '" + _computableValue.getName() + "' is marked as " + "computing but unable to locate transaction responsible for computing ComputableValue" ); } assert null != transaction; return transaction; } ComputableValueInfoImpl( @Nonnull final ComputableValue<?> computableValue ); @Nonnull @Override String getName(); @Override boolean isComputing(); @Nonnull @Override Priority getPriority(); @Override boolean isActive(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @OmitSymbol( unless = "arez.enable_property_introspection" ) @Nullable @Override Object getValue(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @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() ); computableValue.setComputing( true ); final ComputableValueInfoImpl info = (ComputableValueInfoImpl) computableValue.asInfo(); final Transaction transaction = new Transaction( context, null, observer.getName(), observer.isMutation(), observer, false ); Transaction.setTransaction( transaction ); assertEquals( info.getTransactionComputing(), transaction ); final Transaction transaction2 = new Transaction( context, transaction, ValueUtil.randomString(), observer2.isMutation(), observer2, false ); Transaction.setTransaction( transaction2 ); assertEquals( info.getTransactionComputing(), transaction ); }
### Question: RoundBasedTaskExecutor { void runTasks() { while ( true ) { if ( !runNextTask() ) { break; } } } RoundBasedTaskExecutor( @Nonnull final TaskQueue taskQueue, final int maxRounds ); }### Answer: @Test public void runTasks() { final ArezContext context = Arez.context(); final TaskQueue taskQueue = context.getTaskQueue(); final RoundBasedTaskExecutor executor = new RoundBasedTaskExecutor( taskQueue, 2 ); final AtomicInteger task1CallCount = new AtomicInteger(); final AtomicInteger task2CallCount = new AtomicInteger(); final AtomicInteger task3CallCount = new AtomicInteger(); context.task( "A", task1CallCount::incrementAndGet, Task.Flags.RUN_LATER ); context.task( "B", task2CallCount::incrementAndGet, Task.Flags.RUN_LATER ); context.task( "C", task3CallCount::incrementAndGet, Task.Flags.RUN_LATER ); assertEquals( executor.getMaxRounds(), 2 ); assertEquals( executor.getCurrentRound(), 0 ); assertEquals( executor.getRemainingTasksInCurrentRound(), 0 ); assertEquals( taskQueue.getQueueSize(), 3 ); assertEquals( task1CallCount.get(), 0 ); assertEquals( task2CallCount.get(), 0 ); assertEquals( task3CallCount.get(), 0 ); assertFalse( executor.areTasksExecuting() ); executor.runTasks(); assertFalse( executor.areTasksExecuting() ); assertEquals( task1CallCount.get(), 1 ); assertEquals( task2CallCount.get(), 1 ); assertEquals( task3CallCount.get(), 1 ); assertEquals( executor.getCurrentRound(), 0 ); assertEquals( executor.getRemainingTasksInCurrentRound(), 0 ); assertEquals( taskQueue.getQueueSize(), 0 ); assertFalse( executor.runNextTask() ); }
### Question: SpyImpl implements Spy { @Override public boolean isTransactionActive() { return getContext().isTransactionActive(); } SpyImpl( @Nullable final ArezContext context ); @Override void addSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void removeSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void reportSpyEvent( @Nonnull final Object event ); @Override boolean willPropagateSpyEvents(); @Override boolean isTransactionActive(); @Nonnull @Override TransactionInfo getTransaction(); @Nullable @Override ComponentInfo findComponent( @Nonnull final String type, @Nonnull final Object id ); @Nonnull @Override Collection<ComponentInfo> findAllComponentsByType( @Nonnull final String type ); @Nonnull @Override Collection<String> findAllComponentTypes(); @Nonnull @Override Collection<ObservableValueInfo> findAllTopLevelObservableValues(); @Nonnull @Override Collection<ObserverInfo> findAllTopLevelObservers(); @Nonnull @Override Collection<ComputableValueInfo> findAllTopLevelComputableValues(); @Nonnull @Override Collection<TaskInfo> findAllTopLevelTasks(); @Nonnull @Override ComponentInfo asComponentInfo( @Nonnull final Component component ); @Nonnull @Override ObserverInfo asObserverInfo( @Nonnull final Observer observer ); @Nonnull @Override ObservableValueInfo asObservableValueInfo( @Nonnull final ObservableValue<T> observableValue ); @Nonnull @Override ComputableValueInfo asComputableValueInfo( @Nonnull final ComputableValue<T> computableValue ); @Nonnull @Override TaskInfo asTaskInfo( @Nonnull final Task task ); }### Answer: @Test public void isTransactionActive() { final ArezContext context = Arez.context(); final Spy spy = context.getSpy(); assertFalse( spy.isTransactionActive() ); setupReadOnlyTransaction( context ); assertTrue( spy.isTransactionActive() ); }
### Question: SpyImpl implements Spy { @Nonnull @Override public TransactionInfo getTransaction() { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( this::isTransactionActive, () -> "Arez-0105: Spy.getTransaction() invoked but no transaction active." ); } return getContext().getTransaction().asInfo(); } SpyImpl( @Nullable final ArezContext context ); @Override void addSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void removeSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void reportSpyEvent( @Nonnull final Object event ); @Override boolean willPropagateSpyEvents(); @Override boolean isTransactionActive(); @Nonnull @Override TransactionInfo getTransaction(); @Nullable @Override ComponentInfo findComponent( @Nonnull final String type, @Nonnull final Object id ); @Nonnull @Override Collection<ComponentInfo> findAllComponentsByType( @Nonnull final String type ); @Nonnull @Override Collection<String> findAllComponentTypes(); @Nonnull @Override Collection<ObservableValueInfo> findAllTopLevelObservableValues(); @Nonnull @Override Collection<ObserverInfo> findAllTopLevelObservers(); @Nonnull @Override Collection<ComputableValueInfo> findAllTopLevelComputableValues(); @Nonnull @Override Collection<TaskInfo> findAllTopLevelTasks(); @Nonnull @Override ComponentInfo asComponentInfo( @Nonnull final Component component ); @Nonnull @Override ObserverInfo asObserverInfo( @Nonnull final Observer observer ); @Nonnull @Override ObservableValueInfo asObservableValueInfo( @Nonnull final ObservableValue<T> observableValue ); @Nonnull @Override ComputableValueInfo asComputableValueInfo( @Nonnull final ComputableValue<T> computableValue ); @Nonnull @Override TaskInfo asTaskInfo( @Nonnull final Task task ); }### Answer: @Test public void getTransaction() { final ArezContext context = Arez.context(); final Spy spy = context.getSpy(); final String name = ValueUtil.randomString(); context.safeAction( name, () -> { observeADependency(); assertEquals( spy.getTransaction().getName(), name ); } ); }
### Question: SpyImpl implements Spy { @Nonnull @Override public Collection<TaskInfo> findAllTopLevelTasks() { return TaskInfoImpl.asUnmodifiableInfos( getContext().getTopLevelTasks().values() ); } SpyImpl( @Nullable final ArezContext context ); @Override void addSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void removeSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void reportSpyEvent( @Nonnull final Object event ); @Override boolean willPropagateSpyEvents(); @Override boolean isTransactionActive(); @Nonnull @Override TransactionInfo getTransaction(); @Nullable @Override ComponentInfo findComponent( @Nonnull final String type, @Nonnull final Object id ); @Nonnull @Override Collection<ComponentInfo> findAllComponentsByType( @Nonnull final String type ); @Nonnull @Override Collection<String> findAllComponentTypes(); @Nonnull @Override Collection<ObservableValueInfo> findAllTopLevelObservableValues(); @Nonnull @Override Collection<ObserverInfo> findAllTopLevelObservers(); @Nonnull @Override Collection<ComputableValueInfo> findAllTopLevelComputableValues(); @Nonnull @Override Collection<TaskInfo> findAllTopLevelTasks(); @Nonnull @Override ComponentInfo asComponentInfo( @Nonnull final Component component ); @Nonnull @Override ObserverInfo asObserverInfo( @Nonnull final Observer observer ); @Nonnull @Override ObservableValueInfo asObservableValueInfo( @Nonnull final ObservableValue<T> observableValue ); @Nonnull @Override ComputableValueInfo asComputableValueInfo( @Nonnull final ComputableValue<T> computableValue ); @Nonnull @Override TaskInfo asTaskInfo( @Nonnull final Task task ); }### Answer: @Test public void findAllTopLevelTasks() { final ArezContext context = Arez.context(); final Task task = context.task( ValueUtil::randomString ); final Spy spy = context.getSpy(); final Collection<TaskInfo> values = spy.findAllTopLevelTasks(); assertEquals( values.size(), 1 ); assertEquals( values.iterator().next().getName(), task.getName() ); assertUnmodifiable( values ); }
### Question: ComputableValueInfoImpl implements ComputableValueInfo { @Nonnull @Override public String getName() { return _computableValue.getName(); } ComputableValueInfoImpl( @Nonnull final ComputableValue<?> computableValue ); @Nonnull @Override String getName(); @Override boolean isComputing(); @Nonnull @Override Priority getPriority(); @Override boolean isActive(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @OmitSymbol( unless = "arez.enable_property_introspection" ) @Nullable @Override Object getValue(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void getTransactionComputing_missingTracker() { final ArezContext context = Arez.context(); final ComputableValue<String> computableValue = context.computable( () -> "" ); computableValue.setComputing( true ); final ComputableValueInfoImpl info = (ComputableValueInfoImpl) computableValue.asInfo(); setupReadOnlyTransaction( context ); assertInvariantFailure( info::getTransactionComputing, "Arez-0106: ComputableValue named '" + computableValue.getName() + "' is marked as " + "computing but unable to locate transaction responsible for computing ComputableValue" ); }
### Question: SpyImpl implements Spy { @Nonnull @Override public Collection<ObservableValueInfo> findAllTopLevelObservableValues() { return ObservableValueInfoImpl.asUnmodifiableInfos( getContext().getTopLevelObservables().values() ); } SpyImpl( @Nullable final ArezContext context ); @Override void addSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void removeSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void reportSpyEvent( @Nonnull final Object event ); @Override boolean willPropagateSpyEvents(); @Override boolean isTransactionActive(); @Nonnull @Override TransactionInfo getTransaction(); @Nullable @Override ComponentInfo findComponent( @Nonnull final String type, @Nonnull final Object id ); @Nonnull @Override Collection<ComponentInfo> findAllComponentsByType( @Nonnull final String type ); @Nonnull @Override Collection<String> findAllComponentTypes(); @Nonnull @Override Collection<ObservableValueInfo> findAllTopLevelObservableValues(); @Nonnull @Override Collection<ObserverInfo> findAllTopLevelObservers(); @Nonnull @Override Collection<ComputableValueInfo> findAllTopLevelComputableValues(); @Nonnull @Override Collection<TaskInfo> findAllTopLevelTasks(); @Nonnull @Override ComponentInfo asComponentInfo( @Nonnull final Component component ); @Nonnull @Override ObserverInfo asObserverInfo( @Nonnull final Observer observer ); @Nonnull @Override ObservableValueInfo asObservableValueInfo( @Nonnull final ObservableValue<T> observableValue ); @Nonnull @Override ComputableValueInfo asComputableValueInfo( @Nonnull final ComputableValue<T> computableValue ); @Nonnull @Override TaskInfo asTaskInfo( @Nonnull final Task task ); }### Answer: @Test public void findAllTopLevelObservables() { final ArezContext context = Arez.context(); final ObservableValue<String> observableValue = context.observable(); final Spy spy = context.getSpy(); final Collection<ObservableValueInfo> values = spy.findAllTopLevelObservableValues(); assertEquals( values.size(), 1 ); assertEquals( values.iterator().next().getName(), observableValue.getName() ); assertUnmodifiable( values ); }
### Question: SpyImpl implements Spy { @Nonnull @Override public Collection<ObserverInfo> findAllTopLevelObservers() { return ObserverInfoImpl.asUnmodifiableInfos( getContext().getTopLevelObservers().values() ); } SpyImpl( @Nullable final ArezContext context ); @Override void addSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void removeSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void reportSpyEvent( @Nonnull final Object event ); @Override boolean willPropagateSpyEvents(); @Override boolean isTransactionActive(); @Nonnull @Override TransactionInfo getTransaction(); @Nullable @Override ComponentInfo findComponent( @Nonnull final String type, @Nonnull final Object id ); @Nonnull @Override Collection<ComponentInfo> findAllComponentsByType( @Nonnull final String type ); @Nonnull @Override Collection<String> findAllComponentTypes(); @Nonnull @Override Collection<ObservableValueInfo> findAllTopLevelObservableValues(); @Nonnull @Override Collection<ObserverInfo> findAllTopLevelObservers(); @Nonnull @Override Collection<ComputableValueInfo> findAllTopLevelComputableValues(); @Nonnull @Override Collection<TaskInfo> findAllTopLevelTasks(); @Nonnull @Override ComponentInfo asComponentInfo( @Nonnull final Component component ); @Nonnull @Override ObserverInfo asObserverInfo( @Nonnull final Observer observer ); @Nonnull @Override ObservableValueInfo asObservableValueInfo( @Nonnull final ObservableValue<T> observableValue ); @Nonnull @Override ComputableValueInfo asComputableValueInfo( @Nonnull final ComputableValue<T> computableValue ); @Nonnull @Override TaskInfo asTaskInfo( @Nonnull final Task task ); }### Answer: @Test public void findAllTopLevelObservers() { final ArezContext context = Arez.context(); final Observer observer = context.observer( AbstractTest::observeADependency ); final Spy spy = context.getSpy(); final Collection<ObserverInfo> values = spy.findAllTopLevelObservers(); assertEquals( values.size(), 1 ); assertEquals( values.iterator().next().getName(), observer.getName() ); assertUnmodifiable( values ); }
### Question: SpyImpl implements Spy { @Nonnull @Override public ComponentInfo asComponentInfo( @Nonnull final Component component ) { return component.asInfo(); } SpyImpl( @Nullable final ArezContext context ); @Override void addSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void removeSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void reportSpyEvent( @Nonnull final Object event ); @Override boolean willPropagateSpyEvents(); @Override boolean isTransactionActive(); @Nonnull @Override TransactionInfo getTransaction(); @Nullable @Override ComponentInfo findComponent( @Nonnull final String type, @Nonnull final Object id ); @Nonnull @Override Collection<ComponentInfo> findAllComponentsByType( @Nonnull final String type ); @Nonnull @Override Collection<String> findAllComponentTypes(); @Nonnull @Override Collection<ObservableValueInfo> findAllTopLevelObservableValues(); @Nonnull @Override Collection<ObserverInfo> findAllTopLevelObservers(); @Nonnull @Override Collection<ComputableValueInfo> findAllTopLevelComputableValues(); @Nonnull @Override Collection<TaskInfo> findAllTopLevelTasks(); @Nonnull @Override ComponentInfo asComponentInfo( @Nonnull final Component component ); @Nonnull @Override ObserverInfo asObserverInfo( @Nonnull final Observer observer ); @Nonnull @Override ObservableValueInfo asObservableValueInfo( @Nonnull final ObservableValue<T> observableValue ); @Nonnull @Override ComputableValueInfo asComputableValueInfo( @Nonnull final ComputableValue<T> computableValue ); @Nonnull @Override TaskInfo asTaskInfo( @Nonnull final Task task ); }### Answer: @Test public void asComponentInfo() { final ArezContext context = Arez.context(); final Component component = context.component( ValueUtil.randomString(), ValueUtil.randomString() ); final ComponentInfo info = context.getSpy().asComponentInfo( component ); assertEquals( info.getName(), component.getName() ); }
### Question: SpyImpl implements Spy { @Nonnull @Override public ObserverInfo asObserverInfo( @Nonnull final Observer observer ) { return observer.asInfo(); } SpyImpl( @Nullable final ArezContext context ); @Override void addSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void removeSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void reportSpyEvent( @Nonnull final Object event ); @Override boolean willPropagateSpyEvents(); @Override boolean isTransactionActive(); @Nonnull @Override TransactionInfo getTransaction(); @Nullable @Override ComponentInfo findComponent( @Nonnull final String type, @Nonnull final Object id ); @Nonnull @Override Collection<ComponentInfo> findAllComponentsByType( @Nonnull final String type ); @Nonnull @Override Collection<String> findAllComponentTypes(); @Nonnull @Override Collection<ObservableValueInfo> findAllTopLevelObservableValues(); @Nonnull @Override Collection<ObserverInfo> findAllTopLevelObservers(); @Nonnull @Override Collection<ComputableValueInfo> findAllTopLevelComputableValues(); @Nonnull @Override Collection<TaskInfo> findAllTopLevelTasks(); @Nonnull @Override ComponentInfo asComponentInfo( @Nonnull final Component component ); @Nonnull @Override ObserverInfo asObserverInfo( @Nonnull final Observer observer ); @Nonnull @Override ObservableValueInfo asObservableValueInfo( @Nonnull final ObservableValue<T> observableValue ); @Nonnull @Override ComputableValueInfo asComputableValueInfo( @Nonnull final ComputableValue<T> computableValue ); @Nonnull @Override TaskInfo asTaskInfo( @Nonnull final Task task ); }### Answer: @Test public void asObserverInfo() { final ArezContext context = Arez.context(); final Observer observer = context.observer( AbstractTest::observeADependency ); final ObserverInfo info = context.getSpy().asObserverInfo( observer ); assertEquals( info.getName(), observer.getName() ); }
### Question: SpyImpl implements Spy { @Nonnull @Override public TaskInfo asTaskInfo( @Nonnull final Task task ) { return task.asInfo(); } SpyImpl( @Nullable final ArezContext context ); @Override void addSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void removeSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void reportSpyEvent( @Nonnull final Object event ); @Override boolean willPropagateSpyEvents(); @Override boolean isTransactionActive(); @Nonnull @Override TransactionInfo getTransaction(); @Nullable @Override ComponentInfo findComponent( @Nonnull final String type, @Nonnull final Object id ); @Nonnull @Override Collection<ComponentInfo> findAllComponentsByType( @Nonnull final String type ); @Nonnull @Override Collection<String> findAllComponentTypes(); @Nonnull @Override Collection<ObservableValueInfo> findAllTopLevelObservableValues(); @Nonnull @Override Collection<ObserverInfo> findAllTopLevelObservers(); @Nonnull @Override Collection<ComputableValueInfo> findAllTopLevelComputableValues(); @Nonnull @Override Collection<TaskInfo> findAllTopLevelTasks(); @Nonnull @Override ComponentInfo asComponentInfo( @Nonnull final Component component ); @Nonnull @Override ObserverInfo asObserverInfo( @Nonnull final Observer observer ); @Nonnull @Override ObservableValueInfo asObservableValueInfo( @Nonnull final ObservableValue<T> observableValue ); @Nonnull @Override ComputableValueInfo asComputableValueInfo( @Nonnull final ComputableValue<T> computableValue ); @Nonnull @Override TaskInfo asTaskInfo( @Nonnull final Task task ); }### Answer: @Test public void asTaskInfo() { final ArezContext context = Arez.context(); final Task task = context.task( ValueUtil::randomString ); final TaskInfo info = context.getSpy().asTaskInfo( task ); assertEquals( info.getName(), task.getName() ); }
### Question: SpyImpl implements Spy { @Nonnull @Override public <T> ComputableValueInfo asComputableValueInfo( @Nonnull final ComputableValue<T> computableValue ) { return computableValue.asInfo(); } SpyImpl( @Nullable final ArezContext context ); @Override void addSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void removeSpyEventHandler( @Nonnull final SpyEventHandler handler ); @Override void reportSpyEvent( @Nonnull final Object event ); @Override boolean willPropagateSpyEvents(); @Override boolean isTransactionActive(); @Nonnull @Override TransactionInfo getTransaction(); @Nullable @Override ComponentInfo findComponent( @Nonnull final String type, @Nonnull final Object id ); @Nonnull @Override Collection<ComponentInfo> findAllComponentsByType( @Nonnull final String type ); @Nonnull @Override Collection<String> findAllComponentTypes(); @Nonnull @Override Collection<ObservableValueInfo> findAllTopLevelObservableValues(); @Nonnull @Override Collection<ObserverInfo> findAllTopLevelObservers(); @Nonnull @Override Collection<ComputableValueInfo> findAllTopLevelComputableValues(); @Nonnull @Override Collection<TaskInfo> findAllTopLevelTasks(); @Nonnull @Override ComponentInfo asComponentInfo( @Nonnull final Component component ); @Nonnull @Override ObserverInfo asObserverInfo( @Nonnull final Observer observer ); @Nonnull @Override ObservableValueInfo asObservableValueInfo( @Nonnull final ObservableValue<T> observableValue ); @Nonnull @Override ComputableValueInfo asComputableValueInfo( @Nonnull final ComputableValue<T> computableValue ); @Nonnull @Override TaskInfo asTaskInfo( @Nonnull final Task task ); }### Answer: @Test public void asComputableValueInfo() { final ArezContext context = Arez.context(); final ComputableValue<String> computableValue = context.computable( () -> "" ); final ComputableValueInfo info = context.getSpy().asComputableValueInfo( computableValue ); assertEquals( info.getName(), computableValue.getName() ); }
### Question: ObserverErrorHandlerSupport implements ObserverErrorHandler { void addObserverErrorHandler( @Nonnull final ObserverErrorHandler handler ) { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> !_handlers.contains( handler ), () -> "Arez-0096: Attempting to add handler " + handler + " that is already in " + "the list of error handlers." ); } _handlers.add( Objects.requireNonNull( handler ) ); } @Override void onObserverError( @Nonnull final Observer observer, @Nonnull final ObserverError error, @Nullable final Throwable throwable ); }### Answer: @Test public void addObserverErrorHandler_alreadyExists() { final ObserverErrorHandlerSupport support = new ObserverErrorHandlerSupport(); final ObserverErrorHandler handler = ( observerArg, errorArg, throwableArg ) -> { }; support.addObserverErrorHandler( handler ); assertInvariantFailure( () -> support.addObserverErrorHandler( handler ), "Arez-0096: Attempting to add handler " + handler + " that is already in " + "the list of error handlers." ); }
### Question: ComputableValueInfoImpl implements ComputableValueInfo { @Nonnull @Override public List<ObservableValueInfo> getDependencies() { if ( _computableValue.isComputing() ) { final Transaction transaction = getTransactionComputing(); final List<ObservableValue<?>> observableValues = transaction.getObservableValues(); if ( null == observableValues ) { return Collections.emptyList(); } else { final List<ObservableValue<?>> list = observableValues.stream().distinct().collect( Collectors.toList() ); return ObservableValueInfoImpl.asUnmodifiableInfos( list ); } } else { return ObservableValueInfoImpl.asUnmodifiableInfos( _computableValue.getObserver().getDependencies() ); } } ComputableValueInfoImpl( @Nonnull final ComputableValue<?> computableValue ); @Nonnull @Override String getName(); @Override boolean isComputing(); @Nonnull @Override Priority getPriority(); @Override boolean isActive(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @OmitSymbol( unless = "arez.enable_property_introspection" ) @Nullable @Override Object getValue(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void getDependencies() { final ArezContext context = Arez.context(); final ComputableValue<String> computableValue = context.computable( () -> "" ); final ComputableValueInfo info = computableValue.asInfo(); assertEquals( info.getDependencies().size(), 0 ); final ObservableValue<?> observableValue = context.observable(); observableValue.getObservers().add( computableValue.getObserver() ); computableValue.getObserver().getDependencies().add( observableValue ); final List<ObservableValueInfo> dependencies = info.getDependencies(); assertEquals( dependencies.size(), 1 ); assertEquals( dependencies.iterator().next().getName(), observableValue.getName() ); assertUnmodifiable( dependencies ); }
### Question: ObserverErrorHandlerSupport implements ObserverErrorHandler { void removeObserverErrorHandler( @Nonnull final ObserverErrorHandler handler ) { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> _handlers.contains( handler ), () -> "Arez-0097: Attempting to remove handler " + handler + " that is not in " + "the list of error handlers." ); } _handlers.remove( Objects.requireNonNull( handler ) ); } @Override void onObserverError( @Nonnull final Observer observer, @Nonnull final ObserverError error, @Nullable final Throwable throwable ); }### Answer: @Test public void removeObserverErrorHandler_noExists() { final ObserverErrorHandlerSupport support = new ObserverErrorHandlerSupport(); final ObserverErrorHandler handler = ( observerArg, errorArg, throwableArg ) -> { }; assertInvariantFailure( () -> support.removeObserverErrorHandler( handler ), "Arez-0097: Attempting to remove handler " + handler + " that is not in " + "the list of error handlers." ); }
### Question: Task extends Node { public void schedule() { if ( isIdle() ) { queueTask(); } getContext().triggerScheduler(); } Task( @Nullable final ArezContext context, @Nullable final String name, @Nonnull final SafeProcedure work, final int flags ); void schedule(); @Override void dispose(); @Override boolean isDisposed(); }### Answer: @Test public void schedule() { final AtomicInteger callCount = new AtomicInteger(); final Task task = Arez.context().task( callCount::incrementAndGet ); assertEquals( callCount.get(), 1 ); assertTrue( task.isIdle() ); task.schedule(); assertEquals( callCount.get(), 2 ); }
### Question: Task extends Node { void markAsQueued() { if ( Arez.shouldCheckInvariants() ) { invariant( this::isIdle, () -> "Arez-0128: Attempting to queue task named '" + getName() + "' when task is not idle." ); } _flags = Flags.setState( _flags, Flags.STATE_QUEUED ); } Task( @Nullable final ArezContext context, @Nullable final String name, @Nonnull final SafeProcedure work, final int flags ); void schedule(); @Override void dispose(); @Override boolean isDisposed(); }### Answer: @Test public void markAsQueued_alreadyScheduled() { final Task task = new Task( Arez.context(), "X", ValueUtil::randomString, 0 ); task.markAsQueued(); assertInvariantFailure( task::markAsQueued, "Arez-0128: Attempting to queue task named 'X' when task is not idle." ); }
### Question: Task extends Node { Task( @Nullable final ArezContext context, @Nullable final String name, @Nonnull final SafeProcedure work, final int flags ) { super( context, name ); if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> ( ~Flags.CONFIG_FLAGS_MASK & flags ) == 0, () -> "Arez-0224: Task named '" + name + "' passed invalid flags: " + ( ~Flags.CONFIG_FLAGS_MASK & flags ) ); } _work = Objects.requireNonNull( work ); _flags = flags | Flags.STATE_IDLE | Flags.runType( flags ) | Flags.priority( flags ); if ( Arez.areRegistriesEnabled() && 0 == ( _flags & Flags.NO_REGISTER_TASK ) ) { getContext().registerTask( this ); } } Task( @Nullable final ArezContext context, @Nullable final String name, @Nonnull final SafeProcedure work, final int flags ); void schedule(); @Override void dispose(); @Override boolean isDisposed(); }### Answer: @Test public void asInfo_spyDisabled() { ArezTestUtil.disableSpies(); final Task task = Arez.context().task( ValueUtil::randomString ); assertInvariantFailure( task::asInfo, "Arez-0130: Task.asInfo() invoked but Arez.areSpiesEnabled() returned false." ); }
### Question: Task extends Node { @Nonnull Priority getPriority() { return Priority.values()[ getPriorityIndex() ]; } Task( @Nullable final ArezContext context, @Nullable final String name, @Nonnull final SafeProcedure work, final int flags ); void schedule(); @Override void dispose(); @Override boolean isDisposed(); }### Answer: @Test public void getPriority() { assertEquals( Task.Flags.getPriorityIndex( Task.Flags.PRIORITY_HIGHEST | Task.Flags.STATE_QUEUED ), 0 ); assertEquals( Task.Flags.getPriorityIndex( Task.Flags.PRIORITY_HIGH | Task.Flags.STATE_QUEUED ), 1 ); assertEquals( Task.Flags.getPriorityIndex( Task.Flags.PRIORITY_NORMAL | Task.Flags.STATE_QUEUED ), 2 ); assertEquals( Task.Flags.getPriorityIndex( Task.Flags.PRIORITY_LOW | Task.Flags.STATE_QUEUED ), 3 ); assertEquals( Task.Flags.getPriorityIndex( Task.Flags.PRIORITY_LOWEST | Task.Flags.STATE_QUEUED ), 4 ); }
### Question: ActionFlags { static boolean isVerifyActionRuleValid( final int flags ) { return VERIFY_ACTION_REQUIRED == ( flags & VERIFY_ACTION_MASK ) || NO_VERIFY_ACTION_REQUIRED == ( flags & VERIFY_ACTION_MASK ); } private ActionFlags(); static final int READ_ONLY; static final int READ_WRITE; static final int NO_REPORT_RESULT; static final int REQUIRE_NEW_TRANSACTION; static final int VERIFY_ACTION_REQUIRED; static final int NO_VERIFY_ACTION_REQUIRED; }### Answer: @Test public void isVerifyActionRuleValid() { assertTrue( ActionFlags.isVerifyActionRuleValid( ActionFlags.VERIFY_ACTION_REQUIRED ) ); assertTrue( ActionFlags.isVerifyActionRuleValid( ActionFlags.NO_VERIFY_ACTION_REQUIRED ) ); assertFalse( ActionFlags.isVerifyActionRuleValid( 0 ) ); assertFalse( ActionFlags.isVerifyActionRuleValid( ActionFlags.VERIFY_ACTION_REQUIRED | ActionFlags.NO_VERIFY_ACTION_REQUIRED ) ); }
### Question: ActionFlags { static int verifyActionRule( final int flags ) { return Arez.shouldCheckApiInvariants() ? 0 != ( flags & VERIFY_ACTION_MASK ) ? 0 : VERIFY_ACTION_REQUIRED : 0; } private ActionFlags(); static final int READ_ONLY; static final int READ_WRITE; static final int NO_REPORT_RESULT; static final int REQUIRE_NEW_TRANSACTION; static final int VERIFY_ACTION_REQUIRED; static final int NO_VERIFY_ACTION_REQUIRED; }### Answer: @Test public void verifyActionRule() { assertEquals( ActionFlags.verifyActionRule( ActionFlags.VERIFY_ACTION_REQUIRED ), 0 ); assertEquals( ActionFlags.verifyActionRule( ActionFlags.NO_VERIFY_ACTION_REQUIRED ), 0 ); assertEquals( ActionFlags.verifyActionRule( 0 ), ActionFlags.VERIFY_ACTION_REQUIRED ); assertEquals( ActionFlags.verifyActionRule( ActionFlags.REQUIRE_NEW_TRANSACTION ), ActionFlags.VERIFY_ACTION_REQUIRED ); }
### Question: Transaction { long getStartedAt() { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areSpiesEnabled, () -> "Arez-0134: Transaction.getStartedAt() invoked when Arez.areSpiesEnabled() is false" ); } return _startedAt; } Transaction( @Nullable final ArezContext context, @Nullable final Transaction previous, @Nullable final String name, final boolean mutation, @Nullable final Observer tracker, final boolean zoneActivated ); @Nonnull @Override String toString(); }### Answer: @Test public void construction_whenSpyDisabled() { ArezTestUtil.disableSpies(); final Transaction transaction = new Transaction( Arez.context(), null, ValueUtil.randomString(), false, null, false ); ArezTestUtil.enableSpies(); assertEquals( transaction.getStartedAt(), 0 ); }
### Question: ComputableValueInfoImpl implements ComputableValueInfo { @Nullable @Override public ComponentInfo getComponent() { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areNativeComponentsEnabled, () -> "Arez-0109: Spy.getComponent invoked when Arez.areNativeComponentsEnabled() returns false." ); } final Component component = _computableValue.getComponent(); return null == component ? null : component.asInfo(); } ComputableValueInfoImpl( @Nonnull final ComputableValue<?> computableValue ); @Nonnull @Override String getName(); @Override boolean isComputing(); @Nonnull @Override Priority getPriority(); @Override boolean isActive(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @OmitSymbol( unless = "arez.enable_property_introspection" ) @Nullable @Override Object getValue(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void getComponent_ComputableValue_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final ComputableValue<Object> computableValue = context.computable( () -> "" ); assertInvariantFailure( () -> computableValue.asInfo().getComponent(), "Arez-0109: Spy.getComponent invoked when Arez.areNativeComponentsEnabled() returns false." ); }
### Question: Transaction { void beginTracking() { if ( null != _tracker ) { if ( Arez.shouldCheckInvariants() ) { _tracker.invariantDependenciesBackLink( "Pre beginTracking" ); } if ( !_tracker.isDisposing() ) { _tracker.setState( Observer.Flags.STATE_UP_TO_DATE ); } _tracker.markDependenciesLeastStaleObserverAsUpToDate(); } } Transaction( @Nullable final ArezContext context, @Nullable final Transaction previous, @Nullable final String name, final boolean mutation, @Nullable final Observer tracker, final boolean zoneActivated ); @Nonnull @Override String toString(); }### Answer: @Test public void beginTracking() { final ArezContext context = Arez.context(); final Observer tracker = context.computable( () -> "" ).getObserver(); final Transaction transaction = new Transaction( context, null, ValueUtil.randomString(), false, tracker, false ); Transaction.setTransaction( transaction ); ensureDerivationHasObserver( tracker ); tracker.setState( Observer.Flags.STATE_STALE ); assertEquals( tracker.getState(), Observer.Flags.STATE_STALE ); final ObservableValue<?> observableValue = context.observable(); observableValue.setLeastStaleObserverState( Observer.Flags.STATE_STALE ); tracker.getDependencies().add( observableValue ); observableValue.rawAddObserver( tracker ); transaction.beginTracking(); assertEquals( tracker.getState(), Observer.Flags.STATE_UP_TO_DATE ); assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE ); }
### Question: Transaction { @Nonnull String getName() { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areNamesEnabled, () -> "Arez-0133: Transaction.getName() invoked when Arez.areNamesEnabled() is false" ); } assert null != _name; return _name; } Transaction( @Nullable final ArezContext context, @Nullable final Transaction previous, @Nullable final String name, final boolean mutation, @Nullable final Observer tracker, final boolean zoneActivated ); @Nonnull @Override String toString(); }### Answer: @Test public void processPendingDeactivations_calledOnNonRootTransaction() { final ArezContext context = Arez.context(); final Transaction transaction1 = new Transaction( context, null, ValueUtil.randomString(), false, null, false ); final Transaction transaction2 = new Transaction( context, transaction1, ValueUtil.randomString(), false, null, false ); assertInvariantFailure( transaction2::processPendingDeactivations, "Arez-0138: Invoked processPendingDeactivations on transaction named '" + transaction2.getName() + "' which is not the root transaction." ); } @Test public void getPreviousInSameContext_zonesNotEnabled() { ArezTestUtil.disableZones(); final Transaction transaction = new Transaction( null, null, ValueUtil.randomString(), false, null, false ); assertInvariantFailure( transaction::getPreviousInSameContext, "Arez-0137: Attempted to invoke getPreviousInSameContext() on transaction named '" + transaction.getName() + "' when zones are not enabled." ); }
### Question: Transaction { void verifyWriteAllowed( @Nonnull final ObservableValue<?> observableValue ) { if ( Arez.shouldEnforceTransactionType() && Arez.shouldCheckInvariants() ) { if ( isComputableValueTracker() ) { invariant( () -> observableValue.isComputableValue() && observableValue.getObserver() == _tracker, () -> "Arez-0153: Transaction named '" + getName() + "' attempted to change" + " ObservableValue named '" + observableValue.getName() + "' and the transaction mode is " + "READ_WRITE_OWNED but the ObservableValue has not been created by the transaction." ); } else if ( !isMutation() ) { fail( () -> "Arez-0152: Transaction named '" + getName() + "' attempted to change ObservableValue named '" + observableValue.getName() + "' but the transaction mode is READ_ONLY." ); } } } Transaction( @Nullable final ArezContext context, @Nullable final Transaction previous, @Nullable final String name, final boolean mutation, @Nullable final Observer tracker, final boolean zoneActivated ); @Nonnull @Override String toString(); }### Answer: @Test public void verifyWriteAllowed_withReadOnlyTransaction_enforceTransactionType_set_to_false() { ArezTestUtil.noEnforceTransactionType(); final ArezContext context = Arez.context(); final Transaction transaction = new Transaction( context, null, ValueUtil.randomString(), false, null, false ); final ObservableValue<?> observableValue = context.observable(); transaction.verifyWriteAllowed( observableValue ); } @Test public void verifyWriteAllowed_withReadWriteTransaction() { final ArezContext context = Arez.context(); final Transaction transaction = new Transaction( context, null, ValueUtil.randomString(), true, null, false ); final ObservableValue<?> observableValue = context.observable(); transaction.verifyWriteAllowed( observableValue ); }
### Question: Transaction { @Nonnull static Transaction current() { if ( Arez.shouldCheckInvariants() ) { invariant( () -> null != c_transaction, () -> "Arez-0117: Attempting to get current transaction but no transaction is active." ); } assert null != c_transaction; return c_transaction; } Transaction( @Nullable final ArezContext context, @Nullable final Transaction previous, @Nullable final String name, final boolean mutation, @Nullable final Observer tracker, final boolean zoneActivated ); @Nonnull @Override String toString(); }### Answer: @Test public void current() { final ArezContext context = Arez.context(); final Transaction transaction = new Transaction( context, null, ValueUtil.randomString(), false, null, false ); transaction.begin(); Transaction.setTransaction( transaction ); assertEquals( Transaction.current(), transaction ); }
### Question: Transaction { static boolean isTransactionActive( @Nonnull final ArezContext context ) { return null != c_transaction && ( !Arez.areZonesEnabled() || c_transaction.getContext() == context ); } Transaction( @Nullable final ArezContext context, @Nullable final Transaction previous, @Nullable final String name, final boolean mutation, @Nullable final Observer tracker, final boolean zoneActivated ); @Nonnull @Override String toString(); }### Answer: @Test public void isTransactionActive() { final ArezContext context = Arez.context(); final Transaction transaction = new Transaction( context, null, ValueUtil.randomString(), false, null, false ); transaction.begin(); assertFalse( Transaction.isTransactionActive( context ) ); Transaction.setTransaction( transaction ); assertTrue( Transaction.isTransactionActive( context ) ); }
### Question: Transaction { void reportDispose( @Nonnull final Disposable disposable ) { if ( Arez.shouldCheckInvariants() ) { invariant( disposable::isNotDisposed, () -> "Arez-0176: Invoked reportDispose on transaction named '" + getName() + "' where the element is disposed." ); invariant( () -> !Arez.shouldEnforceTransactionType() || isMutation(), () -> "Arez-0177: Invoked reportDispose on transaction named '" + getName() + "' but the transaction mode is not READ_WRITE but is READ_ONLY." ); } } Transaction( @Nullable final ArezContext context, @Nullable final Transaction previous, @Nullable final String name, final boolean mutation, @Nullable final Observer tracker, final boolean zoneActivated ); @Nonnull @Override String toString(); }### Answer: @Test public void reportDispose() { final Transaction transaction = new Transaction( Arez.context(), null, ValueUtil.randomString(), true, null, false ); final MyDisposable node = new MyDisposable(); transaction.reportDispose( node ); node.dispose(); assertInvariantFailure( () -> transaction.reportDispose( node ), "Arez-0176: Invoked reportDispose on transaction named '" + transaction.getName() + "' where the element is disposed." ); }
### Question: ComputableValueInfoImpl implements ComputableValueInfo { @Override public boolean isActive() { return _computableValue.getObserver().isActive(); } ComputableValueInfoImpl( @Nonnull final ComputableValue<?> computableValue ); @Nonnull @Override String getName(); @Override boolean isComputing(); @Nonnull @Override Priority getPriority(); @Override boolean isActive(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @OmitSymbol( unless = "arez.enable_property_introspection" ) @Nullable @Override Object getValue(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void isActive() { final ArezContext context = Arez.context(); final Spy spy = context.getSpy(); final ComputableValue<String> computableValue = context.computable( () -> "" ); assertFalse( spy.asComputableValueInfo( computableValue ).isActive() ); setupReadOnlyTransaction( context ); computableValue.getObserver().setState( Observer.Flags.STATE_UP_TO_DATE ); assertTrue( spy.asComputableValueInfo( computableValue ).isActive() ); }
### Question: Arez { @Nonnull public static ArezContext context() { return areZonesEnabled() ? ZoneHolder.context() : ArezContextHolder.context(); } private Arez(); @OmitSymbol static boolean areZonesEnabled(); @OmitSymbol static boolean areNamesEnabled(); @OmitSymbol static boolean isVerifyEnabled(); @OmitSymbol static boolean areSpiesEnabled(); @OmitSymbol static boolean areReferencesEnabled(); @OmitSymbol static boolean areCollectionsPropertiesUnmodifiable(); @OmitSymbol static boolean arePropertyIntrospectorsEnabled(); @OmitSymbol static boolean areRegistriesEnabled(); @OmitSymbol static boolean areNativeComponentsEnabled(); @OmitSymbol static boolean areObserverErrorHandlersEnabled(); @OmitSymbol static boolean isTaskInterceptorEnabled(); @OmitSymbol static boolean shouldCheckInvariants(); @OmitSymbol static boolean shouldCheckApiInvariants(); @OmitSymbol static boolean purgeTasksWhenRunawayDetected(); @Nonnull static ArezContext context(); @OmitSymbol( unless = "arez.enable_zones" ) @Nonnull static Zone createZone(); }### Answer: @Test public void context_when_zones_disabled() { ArezTestUtil.disableZones(); final ArezContext context1 = Arez.context(); assertNotNull( context1 ); final ArezContext context2 = Arez.context(); assertSame( context1, context2 ); }
### Question: Arez { @OmitSymbol( unless = "arez.enable_zones" ) static void activateZone( @Nonnull final Zone zone ) { ZoneHolder.activateZone( zone ); } private Arez(); @OmitSymbol static boolean areZonesEnabled(); @OmitSymbol static boolean areNamesEnabled(); @OmitSymbol static boolean isVerifyEnabled(); @OmitSymbol static boolean areSpiesEnabled(); @OmitSymbol static boolean areReferencesEnabled(); @OmitSymbol static boolean areCollectionsPropertiesUnmodifiable(); @OmitSymbol static boolean arePropertyIntrospectorsEnabled(); @OmitSymbol static boolean areRegistriesEnabled(); @OmitSymbol static boolean areNativeComponentsEnabled(); @OmitSymbol static boolean areObserverErrorHandlersEnabled(); @OmitSymbol static boolean isTaskInterceptorEnabled(); @OmitSymbol static boolean shouldCheckInvariants(); @OmitSymbol static boolean shouldCheckApiInvariants(); @OmitSymbol static boolean purgeTasksWhenRunawayDetected(); @Nonnull static ArezContext context(); @OmitSymbol( unless = "arez.enable_zones" ) @Nonnull static Zone createZone(); }### Answer: @Test public void activateZone_whenZonesNotEnabled() { ArezTestUtil.disableZones(); assertInvariantFailure( () -> Arez.activateZone( new Zone() ), "Arez-0002: Invoked Arez.activateZone() but zones are not enabled." ); }
### Question: Arez { @OmitSymbol( unless = "arez.enable_zones" ) static void deactivateZone( @Nonnull final Zone zone ) { ZoneHolder.deactivateZone( zone ); } private Arez(); @OmitSymbol static boolean areZonesEnabled(); @OmitSymbol static boolean areNamesEnabled(); @OmitSymbol static boolean isVerifyEnabled(); @OmitSymbol static boolean areSpiesEnabled(); @OmitSymbol static boolean areReferencesEnabled(); @OmitSymbol static boolean areCollectionsPropertiesUnmodifiable(); @OmitSymbol static boolean arePropertyIntrospectorsEnabled(); @OmitSymbol static boolean areRegistriesEnabled(); @OmitSymbol static boolean areNativeComponentsEnabled(); @OmitSymbol static boolean areObserverErrorHandlersEnabled(); @OmitSymbol static boolean isTaskInterceptorEnabled(); @OmitSymbol static boolean shouldCheckInvariants(); @OmitSymbol static boolean shouldCheckApiInvariants(); @OmitSymbol static boolean purgeTasksWhenRunawayDetected(); @Nonnull static ArezContext context(); @OmitSymbol( unless = "arez.enable_zones" ) @Nonnull static Zone createZone(); }### Answer: @Test public void deactivateZone_whenZonesNotEnabled() { ArezTestUtil.disableZones(); assertInvariantFailure( () -> Arez.deactivateZone( new Zone() ), "Arez-0003: Invoked Arez.deactivateZone() but zones are not enabled." ); } @Test public void deactivateZone_whenNotActive() { ArezTestUtil.enableZones(); assertInvariantFailure( () -> Arez.deactivateZone( new Zone() ), "Arez-0004: Attempted to deactivate zone that is not active." ); }
### Question: TransactionInfoImpl implements TransactionInfo { @Nonnull @Override public String getName() { return getTransaction().getName(); } TransactionInfoImpl( @Nonnull final Transaction transaction ); @Nonnull @Override String getName(); @Override boolean isReadOnly(); @Nullable @Override TransactionInfo getParent(); @Override boolean isTracking(); @Nonnull @Override ObserverInfo getTracker(); }### Answer: @Test public void getTracker_whenNoTracker() { final ArezContext context = Arez.context(); final Transaction transaction = new Transaction( context, null, ValueUtil.randomString(), true, null, false ); final TransactionInfo info = transaction.asInfo(); assertInvariantFailure( info::getTracker, "Invoked getTracker on TransactionInfo named '" + transaction.getName() + "' but no tracker exists." ); }
### Question: TaskInfoImpl implements TaskInfo { @Override public int hashCode() { return _task.hashCode(); } TaskInfoImpl( @Nonnull final Task task ); @Nonnull @Override String getName(); @Override boolean isIdle(); @Override boolean isScheduled(); @Nonnull @Override Priority getPriority(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void equalsAndHashCode() { final ArezContext context = Arez.context(); final Task task1 = context.task( ValueUtil::randomString ); final Task task2 = context.task( ValueUtil::randomString ); final TaskInfo info1a = task1.asInfo(); final TaskInfo info1b = new TaskInfoImpl( task1 ); final TaskInfo info2 = task2.asInfo(); assertNotEquals( "", info1a ); assertEquals( info1a, info1a ); assertEquals( info1a, info1b ); assertNotEquals( info1a, info2 ); assertEquals( info1b, info1a ); assertEquals( info1b, info1b ); assertNotEquals( info1b, info2 ); assertNotEquals( info2, info1a ); assertNotEquals( info2, info1b ); assertEquals( info2, info2 ); assertEquals( info1a.hashCode(), task1.hashCode() ); assertEquals( info1a.hashCode(), info1b.hashCode() ); assertEquals( info2.hashCode(), task2.hashCode() ); }
### Question: ObservableValueInfoImpl implements ObservableValueInfo { @Override public ComputableValueInfo asComputableValue() { return _observableValue.getObserver().getComputableValue().asInfo(); } ObservableValueInfoImpl( @Nonnull final ObservableValue<?> observableValue ); @Nonnull @Override String getName(); @Override boolean isComputableValue(); @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @Override boolean hasAccessor(); @Nullable @Override Object getValue(); @Override boolean hasMutator(); @SuppressWarnings( { "unchecked", "rawtypes" } ) @Override void setValue( @Nullable final Object value ); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void asComputableValue() { final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final ComputableValue<String> computableValue = context.computable( name, () -> "" ); final ObservableValue<String> observableValue = computableValue.getObservableValue(); final ObservableValueInfo info = observableValue.asInfo(); assertEquals( info.getName(), name ); assertTrue( info.isComputableValue() ); assertEquals( info.asComputableValue().getName(), computableValue.getName() ); }
### Question: ObservableValueInfoImpl implements ObservableValueInfo { @Override public int hashCode() { return _observableValue.hashCode(); } ObservableValueInfoImpl( @Nonnull final ObservableValue<?> observableValue ); @Nonnull @Override String getName(); @Override boolean isComputableValue(); @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @Override boolean hasAccessor(); @Nullable @Override Object getValue(); @Override boolean hasMutator(); @SuppressWarnings( { "unchecked", "rawtypes" } ) @Override void setValue( @Nullable final Object value ); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @SuppressWarnings( "EqualsWithItself" ) @Test public void equalsAndHashCode() { final ArezContext context = Arez.context(); final ObservableValue<Object> observableValue1 = context.observable(); final ObservableValue<Object> observableValue2 = context.observable(); final ObservableValueInfo info1a = observableValue1.asInfo(); final ObservableValueInfo info1b = new ObservableValueInfoImpl( observableValue1 ); final ObservableValueInfo info2 = observableValue2.asInfo(); assertNotEquals( info1a, "" ); assertEquals( info1a, info1a ); assertEquals( info1b, info1a ); assertNotEquals( info2, info1a ); assertEquals( info1a, info1b ); assertEquals( info1b, info1b ); assertNotEquals( info2, info1b ); assertNotEquals( info1a, info2 ); assertNotEquals( info1b, info2 ); assertEquals( info2, info2 ); assertEquals( info1a.hashCode(), observableValue1.hashCode() ); assertEquals( info1a.hashCode(), info1b.hashCode() ); assertEquals( info2.hashCode(), observableValue2.hashCode() ); }
### Question: ObservableValueInfoImpl implements ObservableValueInfo { @Override public boolean isComputableValue() { return _observableValue.isComputableValue(); } ObservableValueInfoImpl( @Nonnull final ObservableValue<?> observableValue ); @Nonnull @Override String getName(); @Override boolean isComputableValue(); @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @Override boolean hasAccessor(); @Nullable @Override Object getValue(); @Override boolean hasMutator(); @SuppressWarnings( { "unchecked", "rawtypes" } ) @Override void setValue( @Nullable final Object value ); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void isComputableValue() { final ArezContext context = Arez.context(); final Spy spy = context.getSpy(); assertTrue( spy.asObservableValueInfo( context.computable( () -> "" ).getObservableValue() ).isComputableValue() ); assertFalse( spy.asObservableValueInfo( context.observable() ).isComputableValue() ); }
### Question: ObservableValueInfoImpl implements ObservableValueInfo { @Nullable @Override public ComponentInfo getComponent() { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areNativeComponentsEnabled, () -> "Arez-0107: Spy.getComponent invoked when Arez.areNativeComponentsEnabled() returns false." ); } final Component component = _observableValue.getComponent(); return null == component ? null : component.asInfo(); } ObservableValueInfoImpl( @Nonnull final ObservableValue<?> observableValue ); @Nonnull @Override String getName(); @Override boolean isComputableValue(); @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @Override boolean hasAccessor(); @Nullable @Override Object getValue(); @Override boolean hasMutator(); @SuppressWarnings( { "unchecked", "rawtypes" } ) @Override void setValue( @Nullable final Object value ); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void getComponent_Observable_nativeComponentsDisabled() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final ObservableValue<Object> value = context.observable(); assertInvariantFailure( () -> value.asInfo().getComponent(), "Arez-0107: Spy.getComponent invoked when Arez.areNativeComponentsEnabled() returns false." ); }
### Question: ComputableValueInfoImpl implements ComputableValueInfo { @Nonnull @Override public List<ObserverInfo> getObservers() { return ObserverInfoImpl.asUnmodifiableInfos( _computableValue.getObservableValue().getObservers() ); } ComputableValueInfoImpl( @Nonnull final ComputableValue<?> computableValue ); @Nonnull @Override String getName(); @Override boolean isComputing(); @Nonnull @Override Priority getPriority(); @Override boolean isActive(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @OmitSymbol( unless = "arez.enable_property_introspection" ) @Nullable @Override Object getValue(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void getObservers() { final ArezContext context = Arez.context(); final Spy spy = context.getSpy(); final ComputableValue<?> computableValue = context.computable( () -> "" ); assertEquals( spy.asComputableValueInfo( computableValue ).getObservers().size(), 0 ); final Observer observer = context.observer( new CountAndObserveProcedure() ); observer.getDependencies().add( computableValue.getObservableValue() ); computableValue.getObservableValue().getObservers().add( observer ); assertEquals( spy.asComputableValueInfo( computableValue ).getObservers().size(), 1 ); assertEquals( computableValue.getObservableValue().getObservers().size(), 1 ); assertUnmodifiable( spy.asComputableValueInfo( computableValue ).getObservers() ); }
### Question: SpyEventHandlerSupport { void removeSpyEventHandler( @Nonnull final SpyEventHandler handler ) { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> _spyEventHandlers.contains( handler ), () -> "Arez-0103: Attempting to remove handler " + handler + " that is not " + "in the list of spy handlers." ); } _spyEventHandlers.remove( Objects.requireNonNull( handler ) ); } }### Answer: @Test public void removeSpyEventHandler_noExists() { final SpyEventHandlerSupport support = new SpyEventHandlerSupport(); final SpyEventHandler handler = new TestSpyEventHandler( Arez.context() ); assertInvariantFailure( () -> support.removeSpyEventHandler( handler ), "Arez-0103: Attempting to remove handler " + handler + " that is not in the list of spy handlers." ); }
### Question: ObservableValueInfoImpl implements ObservableValueInfo { @Nullable @Override public Object getValue() throws Throwable { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::arePropertyIntrospectorsEnabled, () -> "Arez-0111: Spy.getValue invoked when Arez.arePropertyIntrospectorsEnabled() returns false." ); } final PropertyAccessor<?> accessor = _observableValue.getAccessor(); if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> null != accessor, () -> "Arez-0112: Spy.getValue invoked on ObservableValue named '" + _observableValue.getName() + "' but ObservableValue has no property accessor." ); } assert null != accessor; return accessor.get(); } ObservableValueInfoImpl( @Nonnull final ObservableValue<?> observableValue ); @Nonnull @Override String getName(); @Override boolean isComputableValue(); @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @Override boolean hasAccessor(); @Nullable @Override Object getValue(); @Override boolean hasMutator(); @SuppressWarnings( { "unchecked", "rawtypes" } ) @Override void setValue( @Nullable final Object value ); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void observable_getValue_introspectorsDisabled() { ArezTestUtil.disablePropertyIntrospectors(); final ArezContext context = Arez.context(); final ObservableValue<Integer> computableValue1 = context.observable(); assertInvariantFailure( () -> context.action( () -> computableValue1.asInfo().getValue() ), "Arez-0111: Spy.getValue invoked when Arez.arePropertyIntrospectorsEnabled() returns false." ); }
### Question: ObservableValueInfoImpl implements ObservableValueInfo { @Override public boolean hasAccessor() { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::arePropertyIntrospectorsEnabled, () -> "Arez-0110: Spy.hasAccessor invoked when Arez.arePropertyIntrospectorsEnabled() returns false." ); } return null != _observableValue.getAccessor(); } ObservableValueInfoImpl( @Nonnull final ObservableValue<?> observableValue ); @Nonnull @Override String getName(); @Override boolean isComputableValue(); @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @Override boolean hasAccessor(); @Nullable @Override Object getValue(); @Override boolean hasMutator(); @SuppressWarnings( { "unchecked", "rawtypes" } ) @Override void setValue( @Nullable final Object value ); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void observable_hasAccessor_introspectorsDisabled() { ArezTestUtil.disablePropertyIntrospectors(); final ArezContext context = Arez.context(); final ObservableValue<Integer> observableValue = context.observable(); assertInvariantFailure( () -> context.action( () -> observableValue.asInfo().hasAccessor() ), "Arez-0110: Spy.hasAccessor invoked when Arez.arePropertyIntrospectorsEnabled() returns false." ); }
### Question: ObservableValueInfoImpl implements ObservableValueInfo { @Override public boolean hasMutator() { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::arePropertyIntrospectorsEnabled, () -> "Arez-0113: Spy.hasMutator invoked when Arez.arePropertyIntrospectorsEnabled() returns false." ); } return null != _observableValue.getMutator(); } ObservableValueInfoImpl( @Nonnull final ObservableValue<?> observableValue ); @Nonnull @Override String getName(); @Override boolean isComputableValue(); @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @Override boolean hasAccessor(); @Nullable @Override Object getValue(); @Override boolean hasMutator(); @SuppressWarnings( { "unchecked", "rawtypes" } ) @Override void setValue( @Nullable final Object value ); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void observable_hasMutator_introspectorsDisabled() { ArezTestUtil.disablePropertyIntrospectors(); final ArezContext context = Arez.context(); final ObservableValue<Integer> observableValue = context.observable(); assertInvariantFailure( () -> context.action( () -> observableValue.asInfo().hasMutator() ), "Arez-0113: Spy.hasMutator invoked when Arez.arePropertyIntrospectorsEnabled() returns false." ); }
### Question: ObservableValueInfoImpl implements ObservableValueInfo { @SuppressWarnings( { "unchecked", "rawtypes" } ) @Override public void setValue( @Nullable final Object value ) throws Throwable { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::arePropertyIntrospectorsEnabled, () -> "Arez-0114: Spy.setValue invoked when Arez.arePropertyIntrospectorsEnabled() returns false." ); } final PropertyMutator mutator = _observableValue.getMutator(); if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> null != mutator, () -> "Arez-0115: Spy.setValue invoked on ObservableValue named '" + _observableValue.getName() + "' but ObservableValue has no property mutator." ); } assert null != mutator; mutator.set( value ); } ObservableValueInfoImpl( @Nonnull final ObservableValue<?> observableValue ); @Nonnull @Override String getName(); @Override boolean isComputableValue(); @Override ComputableValueInfo asComputableValue(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @Override boolean hasAccessor(); @Nullable @Override Object getValue(); @Override boolean hasMutator(); @SuppressWarnings( { "unchecked", "rawtypes" } ) @Override void setValue( @Nullable final Object value ); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void observable_setValue_introspectorsDisabled() { ArezTestUtil.disablePropertyIntrospectors(); final ArezContext context = Arez.context(); final ObservableValue<Integer> observableValue = context.observable(); assertInvariantFailure( () -> context.action( () -> observableValue.asInfo().setValue( 44 ) ), "Arez-0114: Spy.setValue invoked when Arez.arePropertyIntrospectorsEnabled() returns false." ); }
### Question: ComputableValue extends Node { @Nonnull Observer getObserver() { return _observer; } ComputableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nonnull final SafeFunction<T> function, @Nullable final Procedure onActivate, @Nullable final Procedure onDeactivate, final int flags ); T get(); void reportPossiblyChanged(); @Override void dispose(); @Override boolean isDisposed(); @Nonnull Disposable keepAlive(); }### Answer: @Test public void highPriorityComputableValue() { final ComputableValue<String> computableValue = Arez.context().computable( () -> "", ComputableValue.Flags.PRIORITY_HIGH ); assertEquals( computableValue.getObserver().getTask().getPriority(), Priority.HIGH ); }
### Question: ComputableValue extends Node { T computeValue() { if ( Arez.shouldCheckInvariants() ) { _computing = true; } try { return _function.call(); } finally { if ( Arez.shouldCheckInvariants() ) { _computing = false; } } } ComputableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nonnull final SafeFunction<T> function, @Nullable final Procedure onActivate, @Nullable final Procedure onDeactivate, final int flags ); T get(); void reportPossiblyChanged(); @Override void dispose(); @Override boolean isDisposed(); @Nonnull Disposable keepAlive(); }### Answer: @Test public void computeValue() { final ArezContext context = Arez.context(); final AtomicReference<String> value = new AtomicReference<>(); final AtomicReference<ComputableValue<String>> ref = new AtomicReference<>(); value.set( "" ); final SafeFunction<String> function = () -> { observeADependency(); assertTrue( ref.get().isComputing() ); return value.get(); }; final ComputableValue<String> computableValue = context.computable( function ); ref.set( computableValue ); setCurrentTransaction( computableValue.getObserver() ); assertEquals( computableValue.computeValue(), "" ); value.set( "XXX" ); assertEquals( computableValue.computeValue(), "XXX" ); }
### Question: ComputableValue extends Node { @Override public void dispose() { if ( isNotDisposed() ) { if ( Arez.shouldCheckInvariants() ) { getContext().safeAction( Arez.areNamesEnabled() ? getName() + ".dispose" : null, () -> getContext().getTransaction().reportDispose( this ), ActionFlags.NO_VERIFY_ACTION_REQUIRED ); } _disposed = true; _value = null; _error = null; if ( willPropagateSpyEvents() ) { reportSpyEvent( new ComputableValueDisposeEvent( asInfo() ) ); } if ( null != _component ) { _component.removeComputableValue( this ); } else if ( Arez.areRegistriesEnabled() ) { getContext().deregisterComputableValue( this ); } _observableValue.dispose(); if ( !_observer.isDisposing() ) { _observer.dispose(); } } } ComputableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nonnull final SafeFunction<T> function, @Nullable final Procedure onActivate, @Nullable final Procedure onDeactivate, final int flags ); T get(); void reportPossiblyChanged(); @Override void dispose(); @Override boolean isDisposed(); @Nonnull Disposable keepAlive(); }### Answer: @Test public void dispose() { final ArezContext context = Arez.context(); final ComputableValue<String> computableValue = context.computable( () -> "" ); final Observer observer = computableValue.getObserver(); setCurrentTransaction( observer ); observer.setState( Observer.Flags.STATE_UP_TO_DATE ); assertFalse( observer.isDisposed() ); Transaction.setTransaction( null ); computableValue.dispose(); assertTrue( observer.isDisposed() ); assertEquals( observer.getState(), Observer.Flags.STATE_DISPOSED ); }
### Question: ComputableValue extends Node { @SuppressWarnings( "ConstantConditions" ) @OmitSymbol( unless = "arez.enable_spies" ) @Nonnull ComputableValueInfo asInfo() { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areSpiesEnabled, () -> "Arez-0195: ComputableValue.asInfo() invoked but Arez.areSpiesEnabled() returned false." ); } if ( Arez.areSpiesEnabled() && null == _info ) { _info = new ComputableValueInfoImpl( this ); } return Arez.areSpiesEnabled() ? _info : null; } ComputableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nonnull final SafeFunction<T> function, @Nullable final Procedure onActivate, @Nullable final Procedure onDeactivate, final int flags ); T get(); void reportPossiblyChanged(); @Override void dispose(); @Override boolean isDisposed(); @Nonnull Disposable keepAlive(); }### Answer: @Test public void asInfo() { final ArezContext context = Arez.context(); final SafeFunction<String> function = () -> { observeADependency(); return ""; }; final ComputableValue<String> computableValue = context.computable( function ); final ComputableValueInfo info = computableValue.asInfo(); assertEquals( info.getName(), computableValue.getName() ); }
### Question: ComputableValue extends Node { @OmitSymbol void setKeepAliveRefCount( final int keepAliveRefCount ) { _keepAliveRefCount = keepAliveRefCount; } ComputableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nonnull final SafeFunction<T> function, @Nullable final Procedure onActivate, @Nullable final Procedure onDeactivate, final int flags ); T get(); void reportPossiblyChanged(); @Override void dispose(); @Override boolean isDisposed(); @Nonnull Disposable keepAlive(); }### Answer: @Test public void incrementKeepAliveRefCount_badInitialRefCount() { final ArezContext context = Arez.context(); final ObservableValue<Object> observable = context.observable(); final SafeFunction<String> function = () -> { observable.reportObserved(); return ""; }; final ComputableValue<String> computableValue = context.computable( function ); final int keepAliveRefCount = -Math.abs( ValueUtil.randomInt() ); computableValue.setKeepAliveRefCount( keepAliveRefCount ); assertInvariantFailure( computableValue::incrementKeepAliveRefCount, "Arez-0165: KeepAliveRefCount on ComputableValue named 'ComputableValue@2' " + "has an invalid value " + keepAliveRefCount ); }
### Question: ArezProcessor extends AbstractStandardProcessor { @Nonnull @Override protected String getOptionPrefix() { return "arez"; } @Override boolean process( @Nonnull final Set<? extends TypeElement> annotations, @Nonnull final RoundEnvironment env ); }### Answer: @Test public void unresolvedComponent() { final JavaFileObject source1 = fixture( "unresolved/com/example/component/UnresolvedComponent.java" ); final List<JavaFileObject> inputs = Collections.singletonList( source1 ); assertFailedCompileResource( inputs, "ArezProcessor unable to process com.example.component.UnresolvedComponent because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code." ); assert_().about( JavaSourcesSubjectFactory.javaSources() ). that( inputs ). withCompilerOptions( "-Xlint:all,-processing", "-implicit:none", "-A" + getOptionPrefix() + ".defer.errors=false", "-A" + getOptionPrefix() + ".defer.unresolved=false" ). processedWith( processor(), additionalProcessors() ). compilesWithoutWarnings(); }
### Question: ComputableValueInfoImpl implements ComputableValueInfo { @Override public int hashCode() { return _computableValue.hashCode(); } ComputableValueInfoImpl( @Nonnull final ComputableValue<?> computableValue ); @Nonnull @Override String getName(); @Override boolean isComputing(); @Nonnull @Override Priority getPriority(); @Override boolean isActive(); @Nonnull @Override List<ObservableValueInfo> getDependencies(); @Nonnull @Override List<ObserverInfo> getObservers(); @Nullable @Override ComponentInfo getComponent(); @OmitSymbol( unless = "arez.enable_property_introspection" ) @Nullable @Override Object getValue(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @SuppressWarnings( "EqualsWithItself" ) @Test public void equalsAndHashCode() { final ArezContext context = Arez.context(); final ComputableValue<Object> computableValue1 = context.computable( () -> "1" ); final ComputableValue<Object> computableValue2 = context.computable( () -> "2" ); final ComputableValueInfo info1a = computableValue1.asInfo(); final ComputableValueInfo info1b = new ComputableValueInfoImpl( computableValue1 ); final ComputableValueInfo info2 = computableValue2.asInfo(); assertNotEquals( info1a, "" ); assertEquals( info1a, info1a ); assertEquals( info1b, info1a ); assertNotEquals( info2, info1a ); assertEquals( info1a, info1b ); assertEquals( info1b, info1b ); assertNotEquals( info2, info1b ); assertNotEquals( info1a, info2 ); assertNotEquals( info1b, info2 ); assertEquals( info2, info2 ); assertEquals( info1a.hashCode(), computableValue1.hashCode() ); assertEquals( info1a.hashCode(), info1b.hashCode() ); assertEquals( info2.hashCode(), computableValue2.hashCode() ); }
### Question: AggregateLocator implements Locator { @Nonnull Disposable registerLocator( @Nonnull final Locator locator ) { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> !_locators.contains( locator ), () -> "Arez-0189: Attempting to register locator " + locator + " when the " + "Locator is already present." ); } _locators.add( locator ); return new LocatorEntry( locator ); } @Nullable @Override T findById( @Nonnull final Class<T> type, @Nonnull final Object id ); }### Answer: @Test public void registerLookup_duplicate() { final TypeBasedLocator locator1 = new TypeBasedLocator(); final AggregateLocator locator = new AggregateLocator(); locator.registerLocator( locator1 ); assertInvariantFailure( () -> locator.registerLocator( locator1 ), "Arez-0189: Attempting to register locator " + locator1 + " when the Locator is already present." ); }
### Question: ComponentInfoImpl implements ComponentInfo { @Override public int hashCode() { return _component.hashCode(); } ComponentInfoImpl( @Nonnull final Component component ); @Nonnull @Override String getType(); @Nonnull @Override Object getId(); @Nonnull @Override String getName(); @Override List<ObservableValueInfo> getObservableValues(); @Override List<ObserverInfo> getObservers(); @Override List<ComputableValueInfo> getComputableValues(); @Override boolean isDisposed(); @Override String toString(); @Override boolean equals( final Object o ); @Override int hashCode(); }### Answer: @Test public void equalsAndHashCode() { final ArezContext context = Arez.context(); final Component component1 = context.component( ValueUtil.randomString(), ValueUtil.randomString() ); final Component component2 = context.component( ValueUtil.randomString(), ValueUtil.randomString() ); final ComponentInfo info1a = component1.asInfo(); final ComponentInfo info1b = new ComponentInfoImpl( component1 ); final ComponentInfo info2 = component2.asInfo(); assertNotEquals( info1a, "" ); assertEquals( info1a, info1a ); assertEquals( info1b, info1a ); assertNotEquals( info2, info1a ); assertEquals( info1a, info1b ); assertEquals( info1b, info1b ); assertNotEquals( info2, info1b ); assertNotEquals( info1a, info2 ); assertNotEquals( info1b, info2 ); assertEquals( info2, info2 ); assertEquals( info1a.hashCode(), component1.hashCode() ); assertEquals( info1a.hashCode(), info1b.hashCode() ); assertEquals( info2.hashCode(), component2.hashCode() ); }
### Question: TaskQueue { void queueTask( @Nonnull final Task task ) { queueTask( task.getPriorityIndex(), task ); } @SuppressWarnings( { "unchecked", "rawtypes", "RedundantSuppression" } ) TaskQueue( final int priorityCount, final int initialCapacity ); }### Answer: @Test public void queueTask_badPriority() { final TaskQueue queue = new TaskQueue( 3, 10 ); final ArezContext context = Arez.context(); assertInvariantFailure( () -> queue.queueTask( -1, context.task( "A", ValueUtil::randomString ) ), "Arez-0215: Attempting to queue task named 'A' but passed an invalid priority -1." ); assertInvariantFailure( () -> queue.queueTask( 77, context.task( "B", ValueUtil::randomString ) ), "Arez-0215: Attempting to queue task named 'B' but passed an invalid priority 77." ); } @Test public void queueTask_direct_alreadyQueued() { final TaskQueue queue = new TaskQueue( 3, 10 ); final ArezContext context = Arez.context(); final Task task = context.task( "A", ValueUtil::randomString, Task.Flags.RUN_LATER ); task.markAsIdle(); queue.queueTask( 0, task ); task.markAsIdle(); assertInvariantFailure( () -> queue.queueTask( 2, task ), "Arez-0099: Attempting to queue task named 'A' when task is already queued." ); } @Test public void queueTask_alreadyQueued() { final TaskQueue queue = new TaskQueue( 3, 10 ); final ArezContext context = Arez.context(); final Task task = context.task( "A", ValueUtil::randomString, Task.Flags.RUN_LATER ); assertInvariantFailure( () -> queue.queueTask( task ), "Arez-0128: Attempting to queue task named 'A' when task is not idle." ); }
### Question: TaskQueue { @Nonnull Collection<Task> clear() { final List<Task> tasks = new ArrayList<>(); for ( int i = 0; i < _buffers.length; i++ ) { final CircularBuffer<Task> buffer = _buffers[ i ]; Task task; while ( null != ( task = buffer.pop() ) ) { tasks.add( task ); task.markAsIdle(); } } return tasks; } @SuppressWarnings( { "unchecked", "rawtypes", "RedundantSuppression" } ) TaskQueue( final int priorityCount, final int initialCapacity ); }### Answer: @Test public void clear() { final ArezContext context = Arez.context(); final TaskQueue queue = context.getTaskQueue(); context.task( "A", ValueUtil::randomString, Task.Flags.RUN_LATER | Task.Flags.PRIORITY_HIGHEST ); context.task( "B", ValueUtil::randomString, Task.Flags.RUN_LATER | Task.Flags.PRIORITY_HIGH ); context.task( "C", ValueUtil::randomString, Task.Flags.RUN_LATER | Task.Flags.PRIORITY_LOWEST ); context.task( "D", ValueUtil::randomString, Task.Flags.RUN_LATER | Task.Flags.PRIORITY_LOWEST ); context.task( "E", ValueUtil::randomString, Task.Flags.RUN_LATER | Task.Flags.PRIORITY_NORMAL ); context.task( "F", ValueUtil::randomString, Task.Flags.RUN_LATER | Task.Flags.PRIORITY_HIGH ); assertEquals( queue.getQueueSize(), 6 ); final Collection<Task> tasks = queue.clear(); assertEquals( queue.getQueueSize(), 0 ); assertEquals( tasks.stream().map( Task::getName ).collect( Collectors.joining( "," ) ), "A,B,F,E,C,D" ); }
### Question: ArezUtil { @Nonnull @OmitSymbol( unless = "arez.enable_names" ) static String safeGetString( @Nonnull final Supplier<String> message ) { try { return message.get(); } catch ( final Throwable t ) { return "Exception generated whilst attempting to get supplied message.\n" + throwableToString( t ); } } private ArezUtil(); }### Answer: @Test public void safeGetString() { assertEquals( ArezUtil.safeGetString( () -> "My String" ), "My String" ); } @Test public void safeGetString_generatesError() { final String text = ArezUtil.safeGetString( () -> { throw new RuntimeException( "X" ); } ); assertTrue( text.startsWith( "Exception generated whilst attempting to get supplied message.\n" + "java.lang.RuntimeException: X\n" ) ); }
### Question: ObservableValue extends Node { void setLeastStaleObserverState( final int leastStaleObserverState ) { if ( Arez.shouldCheckInvariants() ) { invariant( () -> getContext().isTransactionActive(), () -> "Arez-0074: Attempt to invoke setLeastStaleObserverState on ObservableValue named '" + getName() + "' when there is no active transaction." ); invariant( () -> Observer.Flags.isActive( leastStaleObserverState ), () -> "Arez-0075: Attempt to invoke setLeastStaleObserverState on ObservableValue named '" + getName() + "' with invalid value " + Observer.Flags.getStateName( leastStaleObserverState ) + "." ); } _leastStaleObserverState = leastStaleObserverState; } ObservableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable final Observer observer, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ); @Override void dispose(); @Override boolean isDisposed(); void reportObserved(); void reportObservedIfTrackingTransactionActive(); @OmitSymbol( unless = "arez.check_invariants" ) void preReportChanged(); void reportChanged(); }### Answer: @Test public void setLeastStaleObserverState() { final ArezContext context = Arez.context(); final Observer observer = context.observer( new CountAndObserveProcedure() ); final ObservableValue<?> observableValue = context.observable(); setCurrentTransaction( observer ); assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE ); observableValue.setLeastStaleObserverState( Observer.Flags.STATE_UP_TO_DATE ); assertEquals( observableValue.getLeastStaleObserverState(), Observer.Flags.STATE_UP_TO_DATE ); }
### Question: ObservableValue extends Node { @Nonnull Observer getObserver() { assert null != _observer; return _observer; } ObservableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable final Observer observer, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ); @Override void dispose(); @Override boolean isDisposed(); void reportObserved(); void reportObservedIfTrackingTransactionActive(); @OmitSymbol( unless = "arez.check_invariants" ) void preReportChanged(); void reportChanged(); }### Answer: @Test public void invariantOwner_badObservableLink() { ArezTestUtil.disableRegistries(); final ArezContext context = Arez.context(); setupReadOnlyTransaction( context ); final Observer observer = context.computable( () -> "" ).getObserver(); final ObservableValue<?> observableValue = new ObservableValue<>( context, null, observer.getName(), observer, null, null ); assertInvariantFailure( observableValue::invariantOwner, "Arez-0076: ObservableValue named '" + observableValue.getName() + "' has owner " + "specified but owner does not link to ObservableValue as derived value." ); }
### Question: ObservableValue extends Node { boolean isPendingDeactivation() { return _pendingDeactivation; } ObservableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable final Observer observer, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ); @Override void dispose(); @Override boolean isDisposed(); void reportObserved(); void reportObservedIfTrackingTransactionActive(); @OmitSymbol( unless = "arez.check_invariants" ) void preReportChanged(); void reportChanged(); }### Answer: @Test public void queueForDeactivation_observableIsNotAbleToBeDeactivated() { final ArezContext context = Arez.context(); setupReadOnlyTransaction( context ); final ObservableValue<?> observableValue = context.observable(); assertFalse( observableValue.isPendingDeactivation() ); assertInvariantFailure( observableValue::queueForDeactivation, "Arez-0072: Attempted to invoke queueForDeactivation() on ObservableValue named '" + observableValue.getName() + "' but ObservableValue is not able to be deactivated." ); }
### Question: ObservableValue extends Node { void resetPendingDeactivation() { _pendingDeactivation = false; } ObservableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable final Observer observer, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ); @Override void dispose(); @Override boolean isDisposed(); void reportObserved(); void reportObservedIfTrackingTransactionActive(); @OmitSymbol( unless = "arez.check_invariants" ) void preReportChanged(); void reportChanged(); }### Answer: @Test public void resetPendingDeactivation() { final ArezContext context = Arez.context(); setupReadOnlyTransaction( context ); final ComputableValue<String> computableValue = context.computable( () -> "" ); final Observer observer = computableValue.getObserver(); final ObservableValue<?> observableValue = computableValue.getObservableValue(); observer.setState( Observer.Flags.STATE_UP_TO_DATE ); observableValue.markAsPendingDeactivation(); assertTrue( observableValue.isPendingDeactivation() ); observableValue.resetPendingDeactivation(); assertFalse( observableValue.isPendingDeactivation() ); }
### Question: ObservableValue extends Node { boolean canDeactivate() { return isComputableValue() && !getObserver().isKeepAlive(); } ObservableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable final Observer observer, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ); @Override void dispose(); @Override boolean isDisposed(); void reportObserved(); void reportObservedIfTrackingTransactionActive(); @OmitSymbol( unless = "arez.check_invariants" ) void preReportChanged(); void reportChanged(); }### Answer: @Test public void canDeactivate() { final ArezContext context = Arez.context(); final Observer randomObserver = context.observer( new CountAndObserveProcedure() ); setCurrentTransaction( randomObserver ); final ComputableValue<String> computableValue = context.computable( () -> "" ); final Observer observer = computableValue.getObserver(); final ObservableValue<?> observableValue = computableValue.getObservableValue(); observer.setState( Observer.Flags.STATE_UP_TO_DATE ); assertTrue( observableValue.canDeactivate() ); assertTrue( observableValue.canDeactivateNow() ); observableValue.addObserver( randomObserver ); randomObserver.getDependencies().add( observableValue ); assertTrue( observableValue.canDeactivate() ); assertFalse( observableValue.canDeactivateNow() ); observableValue.removeObserver( randomObserver ); randomObserver.getDependencies().remove( observableValue ); assertTrue( observableValue.canDeactivate() ); assertTrue( observableValue.canDeactivateNow() ); final Disposable keepAliveLock = computableValue.keepAlive(); assertTrue( observableValue.canDeactivate() ); assertFalse( observableValue.canDeactivateNow() ); keepAliveLock.dispose(); assertTrue( observableValue.canDeactivate() ); assertTrue( observableValue.canDeactivateNow() ); }
### Question: ObservableValue extends Node { void activate() { if ( Arez.shouldCheckInvariants() ) { invariant( () -> getContext().isTransactionActive(), () -> "Arez-0062: Attempt to invoke activate on ObservableValue named '" + getName() + "' when there is no active transaction." ); invariant( () -> null != _observer, () -> "Arez-0063: Invoked activate on ObservableValue named '" + getName() + "' when owner is null." ); assert null != _observer; invariant( _observer::isInactive, () -> "Arez-0064: Invoked activate on ObservableValue named '" + getName() + "' when " + "ObservableValue is already active." ); } assert null != _observer; _observer.setState( Observer.Flags.STATE_UP_TO_DATE ); if ( willPropagateSpyEvents() ) { reportSpyEvent( new ComputableValueActivateEvent( _observer.getComputableValue().asInfo() ) ); } } ObservableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable final Observer observer, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ); @Override void dispose(); @Override boolean isDisposed(); void reportObserved(); void reportObservedIfTrackingTransactionActive(); @OmitSymbol( unless = "arez.check_invariants" ) void preReportChanged(); void reportChanged(); }### Answer: @Test public void activate() { final ArezContext context = Arez.context(); setupReadOnlyTransaction( context ); final ComputableValue<String> computableValue = context.computable( () -> "" ); final Observer observer = computableValue.getObserver(); observer.setState( Observer.Flags.STATE_INACTIVE ); final ObservableValue<?> observableValue = computableValue.getObservableValue(); assertEquals( observer.getState(), Observer.Flags.STATE_INACTIVE ); observableValue.activate(); assertEquals( observer.getState(), Observer.Flags.STATE_UP_TO_DATE ); }
### Question: ObservableValue extends Node { public void reportObserved() { getContext().getTransaction().observe( this ); } ObservableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable final Observer observer, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ); @Override void dispose(); @Override boolean isDisposed(); void reportObserved(); void reportObservedIfTrackingTransactionActive(); @OmitSymbol( unless = "arez.check_invariants" ) void preReportChanged(); void reportChanged(); }### Answer: @Test public void reportObserved() { final ArezContext context = Arez.context(); setupReadOnlyTransaction( context ); final ObservableValue<?> observableValue = context.observable(); assertNotEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() ); assertEquals( context.getTransaction().safeGetObservables().size(), 0 ); observableValue.reportObserved(); assertEquals( observableValue.getLastTrackerTransactionId(), context.getTransaction().getId() ); assertEquals( context.getTransaction().safeGetObservables().size(), 1 ); assertTrue( context.getTransaction().safeGetObservables().contains( observableValue ) ); }
### Question: ObservableValue extends Node { public void reportObservedIfTrackingTransactionActive() { if ( getContext().isTrackingTransactionActive() ) { reportObserved(); } } ObservableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable final Observer observer, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ); @Override void dispose(); @Override boolean isDisposed(); void reportObserved(); void reportObservedIfTrackingTransactionActive(); @OmitSymbol( unless = "arez.check_invariants" ) void preReportChanged(); void reportChanged(); }### Answer: @Test public void reportObservedIfTrackingTransactionActive() { final ArezContext context = Arez.context(); final ObservableValue<?> observableValue = context.observable(); observableValue.reportObservedIfTrackingTransactionActive(); context.safeAction( observableValue::reportObservedIfTrackingTransactionActive, ActionFlags.NO_VERIFY_ACTION_REQUIRED ); assertThrows( () -> context.safeAction( observableValue::reportObservedIfTrackingTransactionActive ) ); final Observer observer = context.observer( observableValue::reportObservedIfTrackingTransactionActive ); assertTrue( observer.getDependencies().contains( observableValue ) ); }
### Question: ObservableValue extends Node { @OmitSymbol( unless = "arez.check_invariants" ) public void preReportChanged() { if ( Arez.shouldCheckInvariants() ) { getContext().getTransaction().preReportChanged( this ); } } ObservableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable final Observer observer, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ); @Override void dispose(); @Override boolean isDisposed(); void reportObserved(); void reportObservedIfTrackingTransactionActive(); @OmitSymbol( unless = "arez.check_invariants" ) void preReportChanged(); void reportChanged(); }### Answer: @Test public void preReportChanged() { final ArezContext context = Arez.context(); final Observer observer = newReadWriteObserver( context ); setCurrentTransaction( observer ); final ObservableValue<?> observableValue = context.observable(); observableValue.preReportChanged(); }
### Question: ObservableValue extends Node { void setWorkState( final int workState ) { _workState = workState; } ObservableValue( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable final Observer observer, @Nullable final PropertyAccessor<T> accessor, @Nullable final PropertyMutator<T> mutator ); @Override void dispose(); @Override boolean isDisposed(); void reportObserved(); void reportObservedIfTrackingTransactionActive(); @OmitSymbol( unless = "arez.check_invariants" ) void preReportChanged(); void reportChanged(); }### Answer: @Test public void preReportChanged_onDisposedObservable() { final ArezContext context = Arez.context(); setCurrentTransaction( newReadWriteObserver( context ) ); final ObservableValue<?> observableValue = context.observable(); observableValue.setWorkState( ObservableValue.DISPOSED ); assertInvariantFailure( observableValue::preReportChanged, "Arez-0144: Invoked reportChanged on transaction named '" + Transaction.current().getName() + "' for ObservableValue named '" + observableValue.getName() + "' where the ObservableValue is disposed." ); }