method2testcases
stringlengths 118
6.63k
|
---|
### Question:
GlusterFileChannel extends FileChannel { void guardClosed() throws ClosedChannelException { if (closed) { throw new ClosedChannelException(); } } @Override int read(ByteBuffer byteBuffer); @Override long read(ByteBuffer[] byteBuffers, int offset, int length); @Override int write(ByteBuffer byteBuffer); @Override long write(ByteBuffer[] byteBuffers, int offset, int length); @Override long position(); @Override FileChannel position(long offset); @Override long size(); @Override FileChannel truncate(long l); @Override void force(boolean b); @Override long transferTo(long l, long l2, WritableByteChannel writableByteChannel); @Override long transferFrom(ReadableByteChannel readableByteChannel, long l, long l2); @Override int read(ByteBuffer byteBuffer, long position); @Override int write(ByteBuffer byteBuffer, long position); @Override MappedByteBuffer map(MapMode mapMode, long l, long l2); @Override FileLock lock(long l, long l2, boolean b); @Override FileLock tryLock(long l, long l2, boolean b); static final Map<StandardOpenOption, Integer> optionMap; static final Map<PosixFilePermission, Integer> perms; }### Answer:
@Test public void testGuardClosed_whenNotClosed() throws ClosedChannelException { channel.setClosed(false); channel.guardClosed(); }
@Test(expected = ClosedChannelException.class) public void testGuardClosed_whenClosed() throws ClosedChannelException { channel.setClosed(true); channel.guardClosed(); } |
### Question:
GlusterFileChannel extends FileChannel { @Override public long position() throws IOException { guardClosed(); return position; } @Override int read(ByteBuffer byteBuffer); @Override long read(ByteBuffer[] byteBuffers, int offset, int length); @Override int write(ByteBuffer byteBuffer); @Override long write(ByteBuffer[] byteBuffers, int offset, int length); @Override long position(); @Override FileChannel position(long offset); @Override long size(); @Override FileChannel truncate(long l); @Override void force(boolean b); @Override long transferTo(long l, long l2, WritableByteChannel writableByteChannel); @Override long transferFrom(ReadableByteChannel readableByteChannel, long l, long l2); @Override int read(ByteBuffer byteBuffer, long position); @Override int write(ByteBuffer byteBuffer, long position); @Override MappedByteBuffer map(MapMode mapMode, long l, long l2); @Override FileLock lock(long l, long l2, boolean b); @Override FileLock tryLock(long l, long l2, boolean b); static final Map<StandardOpenOption, Integer> optionMap; static final Map<PosixFilePermission, Integer> perms; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testSetPosition_whenNegative() throws IOException { long position = -1l; channel.position(position); } |
### Question:
GlusterFileChannel extends FileChannel { @Override public void force(boolean b) throws IOException { guardClosed(); int fsync = GLFS.glfs_fsync(fileptr); if (0 != fsync) { throw new IOException("Unable to fsync"); } } @Override int read(ByteBuffer byteBuffer); @Override long read(ByteBuffer[] byteBuffers, int offset, int length); @Override int write(ByteBuffer byteBuffer); @Override long write(ByteBuffer[] byteBuffers, int offset, int length); @Override long position(); @Override FileChannel position(long offset); @Override long size(); @Override FileChannel truncate(long l); @Override void force(boolean b); @Override long transferTo(long l, long l2, WritableByteChannel writableByteChannel); @Override long transferFrom(ReadableByteChannel readableByteChannel, long l, long l2); @Override int read(ByteBuffer byteBuffer, long position); @Override int write(ByteBuffer byteBuffer, long position); @Override MappedByteBuffer map(MapMode mapMode, long l, long l2); @Override FileLock lock(long l, long l2, boolean b); @Override FileLock tryLock(long l, long l2, boolean b); static final Map<StandardOpenOption, Integer> optionMap; static final Map<PosixFilePermission, Integer> perms; }### Answer:
@Test(expected = IOException.class) public void testForce_whenFailing() throws IOException { long fileptr = 1234l; channel.setFileptr(fileptr); mockStatic(GLFS.class); when(GLFS.glfs_fsync(fileptr)).thenReturn(-1); channel.force(true); }
@Test public void testForce() throws IOException { doNothing().when(channel).guardClosed(); long fileptr = 1234l; channel.setFileptr(fileptr); mockStatic(GLFS.class); when(GLFS.glfs_fsync(fileptr)).thenReturn(0); channel.force(true); verify(channel).guardClosed(); verifyStatic(); GLFS.glfs_fsync(fileptr); } |
### Question:
GlusterFileChannel extends FileChannel { @Override protected void implCloseChannel() throws IOException { if (!closed) { int close = GLFS.glfs_close(fileptr); if (0 != close) { throw new IOException("Close returned nonzero"); } closed = true; } } @Override int read(ByteBuffer byteBuffer); @Override long read(ByteBuffer[] byteBuffers, int offset, int length); @Override int write(ByteBuffer byteBuffer); @Override long write(ByteBuffer[] byteBuffers, int offset, int length); @Override long position(); @Override FileChannel position(long offset); @Override long size(); @Override FileChannel truncate(long l); @Override void force(boolean b); @Override long transferTo(long l, long l2, WritableByteChannel writableByteChannel); @Override long transferFrom(ReadableByteChannel readableByteChannel, long l, long l2); @Override int read(ByteBuffer byteBuffer, long position); @Override int write(ByteBuffer byteBuffer, long position); @Override MappedByteBuffer map(MapMode mapMode, long l, long l2); @Override FileLock lock(long l, long l2, boolean b); @Override FileLock tryLock(long l, long l2, boolean b); static final Map<StandardOpenOption, Integer> optionMap; static final Map<PosixFilePermission, Integer> perms; }### Answer:
@Test(expected = IOException.class) public void testImplCloseChannel_whenFailing() throws IOException { long fileptr = 1234l; channel.setFileptr(fileptr); mockStatic(GLFS.class); when(GLFS.glfs_close(fileptr)).thenReturn(1); channel.implCloseChannel(); }
@Test public void testImplCloseChannel_whenAlreadyClosed() throws IOException { channel.setClosed(true); long fileptr = 1234l; channel.setFileptr(fileptr); mockStatic(GLFS.class); when(GLFS.glfs_close(fileptr)).thenReturn(0); channel.implCloseChannel(); assertTrue(channel.isClosed()); verifyStatic(never()); GLFS.glfs_close(fileptr); }
@Test public void testImplCloseChannel() throws IOException { long fileptr = 1234l; channel.setFileptr(fileptr); mockStatic(GLFS.class); when(GLFS.glfs_close(fileptr)).thenReturn(0); channel.implCloseChannel(); assertTrue(channel.isClosed()); verifyStatic(); GLFS.glfs_close(fileptr); } |
### Question:
GlusterFileChannel extends FileChannel { @Override public long size() throws IOException { stat stat = new stat(); int retval = GLFS.glfs_fstat(fileptr, stat); if (0 != retval) { throw new IOException("fstat failed"); } return stat.st_size; } @Override int read(ByteBuffer byteBuffer); @Override long read(ByteBuffer[] byteBuffers, int offset, int length); @Override int write(ByteBuffer byteBuffer); @Override long write(ByteBuffer[] byteBuffers, int offset, int length); @Override long position(); @Override FileChannel position(long offset); @Override long size(); @Override FileChannel truncate(long l); @Override void force(boolean b); @Override long transferTo(long l, long l2, WritableByteChannel writableByteChannel); @Override long transferFrom(ReadableByteChannel readableByteChannel, long l, long l2); @Override int read(ByteBuffer byteBuffer, long position); @Override int write(ByteBuffer byteBuffer, long position); @Override MappedByteBuffer map(MapMode mapMode, long l, long l2); @Override FileLock lock(long l, long l2, boolean b); @Override FileLock tryLock(long l, long l2, boolean b); static final Map<StandardOpenOption, Integer> optionMap; static final Map<PosixFilePermission, Integer> perms; }### Answer:
@Test public void testSize() throws Exception { long fileptr = 1234l; channel.setFileptr(fileptr); long actualSize = 321l; stat stat = new stat(); stat.st_size = actualSize; PowerMockito.whenNew(stat.class).withNoArguments().thenReturn(stat); mockStatic(GLFS.class); when(GLFS.glfs_fstat(fileptr, stat)).thenReturn(0); long size = channel.size(); assertEquals(actualSize, size); verifyStatic(); GLFS.glfs_fstat(fileptr, stat); }
@Test(expected = IOException.class) public void testSize_whenFailing() throws Exception { long fileptr = 1234l; channel.setFileptr(fileptr); long actualSize = 321l; stat stat = new stat(); stat.st_size = actualSize; PowerMockito.whenNew(stat.class).withNoArguments().thenReturn(stat); mockStatic(GLFS.class); when(GLFS.glfs_fstat(fileptr, stat)).thenReturn(-1); long size = channel.size(); } |
### Question:
GlusterWatchKey implements WatchKey { public boolean update() { DirectoryStream<Path> paths; try { paths = Files.newDirectoryStream(path); } catch (IOException e) { return false; } List<Path> files = new LinkedList<>(); boolean newEvents = false; for (Path f : paths) { newEvents |= processExistingFile(files, f); } for (Path f : events.keySet()) { newEvents |= checkDeleted(files, f); } return newEvents; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testUpdate_whenIOException() throws IOException { PowerMockito.mockStatic(Files.class); when(Files.newDirectoryStream(mockPath)).thenThrow(new IOException()); assertFalse(key.update()); PowerMockito.verifyStatic(); Files.newDirectoryStream(mockPath); } |
### Question:
GlusterWatchKey implements WatchKey { boolean processExistingFile(List<Path> files, Path f) { if (Files.isDirectory(f)) { return false; } files.add(f); long lastModified; try { lastModified = Files.getLastModifiedTime(f).toMillis(); } catch (IOException e) { return false; } GlusterWatchEvent event = events.get(f); if (null != event) { return checkModified(event, lastModified); } else { return checkCreated(f, lastModified); } } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testProcessExistingFile() { } |
### Question:
GlusterWatchService implements WatchService { @Override public void close() throws IOException { if (running) { running = false; for (GlusterWatchKey k : paths) { k.cancel(); } } } WatchKey registerPath(GlusterPath path, WatchEvent.Kind... kinds); @Override void close(); @Override WatchKey poll(); @Override WatchKey poll(long timeout, TimeUnit unit); @Override WatchKey take(); static final int MILLIS_PER_SECOND; static final int MILLIS_PER_MINUTE; static final int MILLIS_PER_HOUR; static final int MILLIS_PER_DAY; static long PERIOD; }### Answer:
@Test public void testClose_whenNotRunning() throws IOException { watchService.setRunning(false); GlusterWatchKey mockKey = mock(GlusterWatchKey.class); watchService.getPaths().add(mockKey); watchService.close(); Mockito.verify(mockKey, Mockito.never()).cancel(); }
@Test public void testClose() throws IOException { watchService.setRunning(true); GlusterWatchKey mockKey = mock(GlusterWatchKey.class); watchService.getPaths().add(mockKey); watchService.close(); Mockito.verify(mockKey).cancel(); assertFalse(watchService.isRunning()); } |
### Question:
GlusterWatchKey implements WatchKey { boolean checkDeleted(List<Path> files, Path f) { GlusterWatchEvent event = events.get(f); if (!files.contains(f) && !StandardWatchEventKinds.ENTRY_DELETE.name().equals(event.kind().name())) { event.setLastModified((new Date()).getTime()); event.setKind(StandardWatchEventKinds.ENTRY_DELETE); event.setCount(event.getCount() + 1); return true; } return false; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testCheckDeleted() { } |
### Question:
GlusterWatchKey implements WatchKey { boolean checkCreated(Path f, long lastModified) { GlusterWatchEvent event = new GlusterWatchEvent(f.getFileName()); event.setLastModified(lastModified); events.put(f, event); return (lastModified > lastPolled); } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testCheckCreated() { } |
### Question:
GlusterWatchKey implements WatchKey { boolean checkModified(GlusterWatchEvent event, long lastModified) { if (lastModified > event.getLastModified()) { event.setLastModified(lastModified); if (event.kind().name().equals(StandardWatchEventKinds.ENTRY_DELETE.name())) { event.setKind(StandardWatchEventKinds.ENTRY_CREATE); event.setCount(0); } else { event.setKind(StandardWatchEventKinds.ENTRY_MODIFY); event.setCount(event.getCount() + 1); } return true; } return false; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testCheckModified() { } |
### Question:
GlusterWatchKey implements WatchKey { boolean kindsContains(WatchEvent.Kind kind) { for (WatchEvent.Kind k : kinds) { if (k.name().equals(kind.name())) { return true; } } return false; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testKindsContains() { } |
### Question:
GlusterWatchKey implements WatchKey { @Override synchronized public List<WatchEvent<?>> pollEvents() { if (!ready) { return new LinkedList<>(); } ready = false; return findPendingEvents(); } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testPollEvents_whenNotReady() { key.setReady(false); assertTrue(key.pollEvents().isEmpty()); } |
### Question:
GlusterWatchKey implements WatchKey { LinkedList<WatchEvent<?>> findPendingEvents() { long maxModifiedTime = lastPolled; LinkedList<WatchEvent<?>> pendingEvents = new LinkedList<>(); for (Path p : events.keySet()) { long lastModified = queueEventIfPending(pendingEvents, p); maxModifiedTime = Math.max(maxModifiedTime, lastModified); } lastPolled = maxModifiedTime; return pendingEvents; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testFindPendingEvents() { } |
### Question:
GlusterWatchKey implements WatchKey { @Override synchronized public boolean reset() { if (!valid || ready) { return false; } else { ready = true; return true; } } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testReset_whenInvalid() { key.setValid(false); Assert.assertFalse(key.reset()); }
@Test public void testReset_whenReady() { WatchEvent.Kind[] kinds = new WatchEvent.Kind[]{mock(WatchEvent.Kind.class)}; GlusterPath path = mock(GlusterPath.class); GlusterWatchKey key = new GlusterWatchKey(path, kinds); key.setValid(true); key.setReady(true); Assert.assertFalse(key.reset()); } |
### Question:
GlusterWatchKey implements WatchKey { @Override public void cancel() { valid = false; } @Override boolean isValid(); boolean update(); @Override synchronized List<WatchEvent<?>> pollEvents(); @Override synchronized boolean reset(); @Override void cancel(); @Override Watchable watchable(); }### Answer:
@Test public void testCancel() { WatchEvent.Kind[] kinds = new WatchEvent.Kind[]{mock(WatchEvent.Kind.class)}; GlusterPath path = mock(GlusterPath.class); GlusterWatchKey key = new GlusterWatchKey(path, kinds); key.setValid(true); key.setReady(false); assertTrue(key.reset()); assertTrue(key.isReady()); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public String getScheme() { return GLUSTER; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testGetScheme() { GlusterFileSystemProvider p = new GlusterFileSystemProvider(); assertEquals("gluster", p.getScheme()); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public FileSystem newFileSystem(URI uri, Map<String, ?> stringMap) throws IOException { String authorityString = uri.getAuthority(); String[] authority = parseAuthority(authorityString); String volname = authority[1]; long volptr = glfsNew(volname); glfsSetVolfileServer(authority[0], volptr); glfsInit(authorityString, volptr); GlusterFileSystem fileSystem = new GlusterFileSystem(this, authority[0], volname, volptr); cache.put(authorityString, fileSystem); return fileSystem; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testNewFileSystem() throws IOException, URISyntaxException { String authority = SERVER + ":" + VOLNAME; doReturn(new String[]{SERVER, VOLNAME}).when(provider).parseAuthority(authority); long volptr = 1234l; doReturn(volptr).when(provider).glfsNew(VOLNAME); doNothing().when(provider).glfsSetVolfileServer(SERVER, volptr); doNothing().when(provider).glfsInit(authority, volptr); URI uri = new URI("gluster: FileSystem fileSystem = provider.newFileSystem(uri, null); verify(provider).parseAuthority(authority); verify(provider).glfsNew(VOLNAME); verify(provider).glfsSetVolfileServer(SERVER, volptr); verify(provider).glfsInit(authority, volptr); assertTrue(provider.getCache().containsKey(authority)); assertEquals(fileSystem, provider.getCache().get(authority)); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { String[] parseAuthority(String authority) { if (!authority.contains(":")) { throw new IllegalArgumentException("URI must be of the form 'gluster: } String[] aarr = authority.split(":"); if (aarr.length != 2 || aarr[0].isEmpty() || aarr[1].isEmpty()) { throw new IllegalArgumentException("URI must be of the form 'gluster: } return aarr; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testParseAuthority_whenNoColon() { provider.parseAuthority("a"); }
@Test(expected = IllegalArgumentException.class) public void testParseAuthority_whenEmptyHost() { provider.parseAuthority(":b"); }
@Test(expected = IllegalArgumentException.class) public void testParseAuthority_whenEmptyVolume() { provider.parseAuthority("a:"); }
@Test(expected = IllegalArgumentException.class) public void testParseAuthority_whenBadSplit() { provider.parseAuthority("a:b:c"); }
@Test public void testParseAuthority() { String[] actual = provider.parseAuthority("a:b"); assertEquals("a", actual[0]); assertEquals("b", actual[1]); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { long glfsNew(String volname) { long volptr = glfs_new(volname); if (0 == volptr) { throw new IllegalArgumentException("Failed to create new client for volume: " + volname); } return volptr; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGlfsNew_whenBad() { mockStatic(GLFS.class); when(GLFS.glfs_new(VOLNAME)).thenReturn(0l); provider.glfsNew(VOLNAME); }
@Test public void testGlfsNew() { mockStatic(GLFS.class); when(GLFS.glfs_new(VOLNAME)).thenReturn(123l); long l = provider.glfsNew(VOLNAME); verifyStatic(); GLFS.glfs_new(VOLNAME); assertEquals(l, 123l); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { void glfsSetVolfileServer(String host, long volptr) { int setServer = glfs_set_volfile_server(volptr, TCP, host, GLUSTERD_PORT); if (0 != setServer) { throw new IllegalArgumentException("Failed to set server address: " + host); } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGlfsSetVolfileServer_whenBad() { mockStatic(GLFS.class); String host = "123.45.67.89"; when(GLFS.glfs_set_volfile_server(123l, "tcp", host, 24007)).thenReturn(-1); provider.glfsSetVolfileServer(host, 123l); }
@Test public void testGlfsSetVolfileServer() { mockStatic(GLFS.class); String host = "123.45.67.89"; when(GLFS.glfs_set_volfile_server(123l, "tcp", host, 24007)).thenReturn(0); provider.glfsSetVolfileServer(host, 123l); verifyStatic(); GLFS.glfs_set_volfile_server(123l, "tcp", host, 24007); } |
### Question:
GlusterWatchService implements WatchService { WatchKey popPending() { Iterator<GlusterWatchKey> iterator = pendingPaths.iterator(); try { GlusterWatchKey key = iterator.next(); iterator.remove(); return key; } catch (NoSuchElementException e) { return null; } } WatchKey registerPath(GlusterPath path, WatchEvent.Kind... kinds); @Override void close(); @Override WatchKey poll(); @Override WatchKey poll(long timeout, TimeUnit unit); @Override WatchKey take(); static final int MILLIS_PER_SECOND; static final int MILLIS_PER_MINUTE; static final int MILLIS_PER_HOUR; static final int MILLIS_PER_DAY; static long PERIOD; }### Answer:
@Test public void testPopPending_whenNonePending() { WatchKey key = watchService.popPending(); assertEquals(null, key); assertEquals(0, watchService.getPendingPaths().size()); }
@Test public void testPopPending() { GlusterPath mockPath = mock(GlusterPath.class); GlusterWatchKey keyFix = new GlusterWatchKey(mockPath, new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_CREATE}); watchService.getPendingPaths().add(keyFix); WatchKey key = watchService.popPending(); assertEquals(keyFix, key); assertEquals(0, watchService.getPendingPaths().size()); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { void glfsInit(String authorityString, long volptr) { int init = glfs_init(volptr); if (0 != init) { throw new IllegalArgumentException("Failed to initialize glusterfs client: " + authorityString); } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGlfsInit_whenBad() { mockStatic(GLFS.class); String host = "123.45.67.89"; when(GLFS.glfs_init(123l)).thenReturn(-1); provider.glfsInit(host, 123l); }
@Test public void testGlfsInit() { mockStatic(GLFS.class); String host = "123.45.67.89"; when(GLFS.glfs_init(123l)).thenReturn(0); provider.glfsInit(host, 123l); verifyStatic(); GLFS.glfs_init(123l); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public FileSystem getFileSystem(URI uri) { if (!cache.containsKey(uri.getAuthority())) { throw new FileSystemNotFoundException("No cached filesystem for: " + uri.getAuthority()); } return cache.get(uri.getAuthority()); } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = FileSystemNotFoundException.class) public void testGetFileSystem_whenNotFound() throws URISyntaxException { provider.getFileSystem(new URI("gluster: }
@Test public void testGetFileSystem() throws URISyntaxException { provider.getCache().put("foo:bar", mockFileSystem); assertEquals(mockFileSystem, provider.getFileSystem(new URI("gluster: } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { return newFileChannelHelper(path, options, attrs); } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testNewFileChannel() throws Exception { FileAttribute<?>[] attrs = new FileAttribute[0]; Set<? extends OpenOption> opts = new HashSet<OpenOption>(); doReturn(mockChannel).when(provider).newFileChannelHelper(mockPath, opts, attrs); FileChannel fileChannel = provider.newFileChannel(mockPath, opts, attrs); verify(provider).newFileChannelHelper(mockPath, opts, attrs); assertEquals(mockChannel, fileChannel); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes) throws IOException { return newFileChannelHelper(path, openOptions, fileAttributes); } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testNewByteChannel() throws Exception { FileAttribute<?>[] attrs = new FileAttribute[0]; Set<? extends OpenOption> opts = new HashSet<OpenOption>(); doReturn(mockChannel).when(provider).newFileChannelHelper(mockPath, opts, attrs); ByteChannel fileChannel = provider.newByteChannel(mockPath, opts, attrs); verify(provider).newFileChannelHelper(mockPath, opts, attrs); assertEquals(mockChannel, fileChannel); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { FileChannel newFileChannelHelper(Path path, Set<? extends OpenOption> options, FileAttribute<?>[] attrs) throws IOException { GlusterFileChannel channel = new GlusterFileChannel(); channel.init((GlusterFileSystem) getFileSystem(path.toUri()), path, options, attrs); return channel; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testNewFileChannelHelper() throws Exception { Set<? extends OpenOption> options = new HashSet<OpenOption>(); FileAttribute<?> attrs[] = new FileAttribute[0]; URI uri = new URI("foo: doReturn(uri).when(mockPath).toUri(); doReturn(mockFileSystem).when(provider).getFileSystem(uri); whenNew(GlusterFileChannel.class).withNoArguments().thenReturn(mockChannel); doNothing().when(mockChannel).init(mockFileSystem, mockPath, options, attrs); FileChannel channel = provider.newFileChannel(mockPath, options, attrs); verify(mockChannel).init(mockFileSystem, mockPath, options, attrs); verify(provider).getFileSystem(uri); verify(mockPath).toUri(); verifyNew(GlusterFileChannel.class).withNoArguments(); assertEquals(mockChannel, channel); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public Path getPath(URI uri) { if (!uri.getScheme().equals(getScheme())) { throw new IllegalArgumentException("No support for scheme: " + uri.getScheme()); } try { FileSystem fileSystem = getFileSystem(uri); return fileSystem.getPath(uri.getPath()); } catch (FileSystemNotFoundException e) { } try { return newFileSystem(uri, null).getPath(uri.getPath()); } catch (IOException e) { throw new FileSystemNotFoundException("Unable to open a connection to " + uri.getAuthority()); } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetPath_whenSchemeIsUnknown() throws URISyntaxException { URI uri = new URI("fluster: provider.getPath(uri); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... linkOptions) throws IOException { if (type.equals(DosFileAttributes.class)) { throw new UnsupportedOperationException(type + " attribute type is not supported, only PosixFileAttributes & its superinterfaces"); } stat stat = new stat(); boolean followSymlinks = true; for (LinkOption lo : linkOptions) { if (lo.equals(LinkOption.NOFOLLOW_LINKS)) { followSymlinks = false; break; } } int ret; String pathString = ((GlusterPath) path).getString(); if (followSymlinks) { ret = GLFS.glfs_stat(((GlusterFileSystem) path.getFileSystem()).getVolptr(), pathString, stat); } else { ret = GLFS.glfs_lstat(((GlusterFileSystem) path.getFileSystem()).getVolptr(), pathString, stat); } if (-1 == ret) { throw new NoSuchFileException(""); } return (A) GlusterFileAttributes.fromStat(stat); } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testReadAttributes_whenDosAttributes() throws IOException { provider.readAttributes(mockPath, DosFileAttributes.class); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { boolean directoryIsEmpty(Path path) throws IOException { try (DirectoryStream<Path> stream = newDirectoryStream(path, null)) { if (stream.iterator().hasNext()) { return false; } return true; } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testDirectoryIsEmpty() throws IOException { doReturn(mockStream).when(provider).newDirectoryStream(mockPath, null); doReturn(mockIterator).when(mockStream).iterator(); doReturn(false).when(mockIterator).hasNext(); boolean ret = provider.directoryIsEmpty(mockPath); assertEquals(ret, true); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public void delete(Path path) throws IOException { if (!Files.exists(path)) { throw new NoSuchFileException(path.toString()); } if (Files.isDirectory(path)) { if(!directoryIsEmpty(path)) { throw new DirectoryNotEmptyException(path.toString()); } int ret = GLFS.glfs_rmdir(((GlusterFileSystem)path.getFileSystem()).getVolptr(), path.toString()); if (ret < 0) { throw new IOException(path.toString()); } } else { int ret = GLFS.glfs_unlink(((GlusterFileSystem) path.getFileSystem()).getVolptr(), path.toString()); if (ret < 0) { throw new IOException(path.toString()); } } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = NoSuchFileException.class) public void testDelete_whenFileDoesNotExist() throws IOException { mockStatic(Files.class); when(Files.exists(mockPath)).thenReturn(false); provider.delete(mockPath); }
@Test public void testDelete() throws IOException { } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public boolean isHidden(Path path) throws IOException { return ((GlusterPath) path.getFileName()).getParts()[0].startsWith("."); } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testIsHidden_whenNotHidden() throws IOException { GlusterPath pathName = Mockito.mock(GlusterPath.class); doReturn(new String[]{"foo"}).when(pathName).getParts(); doReturn(pathName).when(mockPath).getFileName(); boolean hidden = provider.isHidden(mockPath); assertFalse(hidden); verify(pathName).getParts(); verify(mockPath).getFileName(); }
@Test public void testIsHidden_whenHidden() throws IOException { GlusterPath pathName = Mockito.mock(GlusterPath.class); doReturn(new String[]{".foo"}).when(pathName).getParts(); doReturn(pathName).when(mockPath).getFileName(); boolean hidden = provider.isHidden(mockPath); assertTrue(hidden); verify(pathName).getParts(); verify(mockPath).getFileName(); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public void checkAccess(Path path, AccessMode... accessModes) throws IOException { long volptr = ((GlusterFileSystem) path.getFileSystem()).getVolptr(); String pathString = ((GlusterPath) path).getString(); stat stat = new stat(); int ret = GLFS.glfs_lstat(volptr, pathString, stat); if (-1 == ret) { throw new NoSuchFileException(""); } for (AccessMode m : accessModes) { int access = GLFS.glfs_access(volptr, pathString, modeInt(m)); if (-1 == access) { throw new AccessDeniedException(pathString); } } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testCheckAccess() throws IOException { long volptr = 1234l; doReturn(mockFileSystem).when(mockPath).getFileSystem(); doReturn(volptr).when(mockFileSystem).getVolptr(); String path = "/foo/bar"; doReturn(path).when(mockPath).getString(); int mode = 4; stat stat = new stat(); PowerMockito.mockStatic(GLFS.class); when(GLFS.glfs_lstat(volptr, path, stat)).thenReturn(0); when(GLFS.glfs_access(volptr, path, mode)).thenReturn(0); AccessMode accessMode = AccessMode.READ; provider.checkAccess(mockPath, accessMode); PowerMockito.verifyStatic(); GLFS.glfs_access(volptr, path, mode); verify(mockPath).getFileSystem(); verify(mockFileSystem).getVolptr(); verify(mockPath).getString(); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { long getTotalSpace(long volptr) throws IOException { statvfs buf = new statvfs(); GLFS.glfs_statvfs(volptr, "/", buf); return buf.f_bsize * buf.f_blocks; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testGetTotalSpace() throws Exception { mockStatic(GLFS.class); long volptr = 1234l; String path = "/"; statvfs buf = new statvfs(); buf.f_bsize = 2; buf.f_blocks = 1000000l; whenNew(statvfs.class).withNoArguments().thenReturn(buf); when(GLFS.glfs_statvfs(volptr, path, buf)).thenReturn(0); long totalSpace = provider.getTotalSpace(volptr); verifyStatic(); GLFS.glfs_statvfs(volptr, path, buf); verifyNew(statvfs.class).withNoArguments(); assertEquals(buf.f_bsize * buf.f_blocks, totalSpace); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { long getUsableSpace(long volptr) throws IOException { statvfs buf = new statvfs(); GLFS.glfs_statvfs(volptr, "/", buf); return buf.f_bsize * buf.f_bavail; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testGetUsableSpace() throws Exception { mockStatic(GLFS.class); long volptr = 1234l; String path = "/"; statvfs buf = new statvfs(); buf.f_bsize = 2; buf.f_bavail = 1000000l; whenNew(statvfs.class).withNoArguments().thenReturn(buf); when(GLFS.glfs_statvfs(volptr, path, buf)).thenReturn(0); long usableSpace = provider.getUsableSpace(volptr); verifyStatic(); GLFS.glfs_statvfs(volptr, path, buf); verifyNew(statvfs.class).withNoArguments(); assertEquals(buf.f_bsize * buf.f_bavail, usableSpace); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { long getUnallocatedSpace(long volptr) throws IOException { statvfs buf = new statvfs(); GLFS.glfs_statvfs(volptr, "/", buf); return buf.f_bsize * buf.f_bfree; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testGetUnallocatedSpace() throws Exception { mockStatic(GLFS.class); long volptr = 1234l; String path = "/"; statvfs buf = new statvfs(); buf.f_bsize = 2; buf.f_bfree = 1000000l; whenNew(statvfs.class).withNoArguments().thenReturn(buf); when(GLFS.glfs_statvfs(volptr, path, buf)).thenReturn(0); long unallocatedSpace = provider.getUnallocatedSpace(volptr); verifyStatic(); GLFS.glfs_statvfs(volptr, path, buf); verifyNew(statvfs.class).withNoArguments(); assertEquals(buf.f_bsize * buf.f_bfree, unallocatedSpace); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { void copyFileContent(Path path, Path path2) throws IOException { Set<StandardOpenOption> options = new HashSet<>(); options.add(StandardOpenOption.READ); byte[] readBytes = new byte[8192]; FileChannel channel = newFileChannel(path, options); ByteBuffer readBuffer = ByteBuffer.wrap(readBytes); boolean writtenTo = false; int read = channel.read(readBuffer); while (read > 0) { byte[] writeBytes = Arrays.copyOf(readBytes, read); if (!writtenTo) { Files.write(path2, writeBytes, StandardOpenOption.TRUNCATE_EXISTING); writtenTo = true; } else { Files.write(path2, writeBytes, StandardOpenOption.APPEND); } read = channel.read(readBuffer); } channel.close(); } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testCopyFileContent() throws IOException { Set<StandardOpenOption> options = new HashSet<>(); options.add(StandardOpenOption.READ); byte[] bytes = new byte[8192]; doReturn(mockChannel).when(provider).newFileChannel(mockPath, options); when(mockChannel.read(any(ByteBuffer.class))).thenReturn(10, 10, 0); mockStatic(Arrays.class); when(Arrays.copyOf(bytes, 10)).thenReturn(bytes); mockStatic(Files.class); when(Files.write(mockPath, bytes, StandardOpenOption.TRUNCATE_EXISTING)).thenReturn(mockPath); when(Files.write(mockPath, bytes, StandardOpenOption.APPEND)).thenReturn(mockPath); doNothing().when(mockChannel).close(); provider.copyFileContent(mockPath, mockPath); verify(mockChannel).close(); verifyStatic(); Files.write(mockPath, bytes, StandardOpenOption.APPEND); verifyStatic(); Files.write(mockPath, bytes, StandardOpenOption.TRUNCATE_EXISTING); verifyStatic(times(2)); Arrays.copyOf(bytes, 10); verify(mockChannel, times(3)).read(any(ByteBuffer.class)); verify(provider).newFileChannel(mockPath, options); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter) throws IOException { if (!Files.isDirectory(path)) { throw new NotDirectoryException("Not a directory! " + path.toString()); } GlusterPath glusterPath = (GlusterPath) path; GlusterDirectoryStream stream = new GlusterDirectoryStream(); stream.setFileSystem(glusterPath.getFileSystem()); stream.open(glusterPath); stream.setFilter(filter); return stream; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = NotDirectoryException.class) public void testNewDirectoryStream_whenNotDirectory() throws IOException { mockStatic(Files.class); when(Files.isDirectory(mockPath)).thenReturn(false); provider.newDirectoryStream(mockPath, mockFilter); }
@Test public void testNewDirectoryStream() throws Exception { mockStatic(Files.class); when(Files.isDirectory(mockPath)).thenReturn(true); whenNew(GlusterDirectoryStream.class).withNoArguments().thenReturn(mockStream); doReturn(mockFileSystem).when(mockPath).getFileSystem(); doNothing().when(mockStream).setFileSystem(mockFileSystem); doNothing().when(mockStream).open(mockPath); doNothing().when(mockStream).setFilter(mockFilter); DirectoryStream<Path> stream = provider.newDirectoryStream(mockPath, mockFilter); assertEquals(mockStream, stream); verify(mockStream).setFileSystem(mockFileSystem); verify(mockStream).open(mockPath); verify(mockStream).setFilter(mockFilter); verify(mockPath).getFileSystem(); verifyNew(GlusterDirectoryStream.class).withNoArguments(); verifyStatic(); Files.isDirectory(mockPath); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs) throws IOException { String linkPath = link.toString(); if (Files.exists(link, LinkOption.NOFOLLOW_LINKS)) { throw new FileAlreadyExistsException(linkPath); } if (null != attrs && attrs.length > 0) { throw new UnsupportedOperationException("glfs_symlink does not support atomic mode/perms"); } GlusterFileSystem fileSystem = (GlusterFileSystem) link.getFileSystem(); long volptr = fileSystem.getVolptr(); int ret = GLFS.glfs_symlink(volptr, target.toString(), linkPath); if (0 != ret) { throw new IOException("Unknown error creating symlink: " + linkPath); } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = FileAlreadyExistsException.class) public void testCreateSymlink_whenExists() throws IOException { Mockito.doReturn("mockpath").when(mockPath).toString(); mockStatic(Files.class); when(Files.exists(mockPath, LinkOption.NOFOLLOW_LINKS)).thenReturn(true); provider.createSymbolicLink(mockPath, targetPath); }
@Test(expected = UnsupportedOperationException.class) public void testCreateSymlink_whenAttrs() throws IOException { Mockito.doReturn("mockpath").when(mockPath).toString(); mockStatic(Files.class); when(Files.exists(mockPath, LinkOption.NOFOLLOW_LINKS)).thenReturn(false); FileAttribute<Object>[] attrs = new FileAttribute[1]; provider.createSymbolicLink(mockPath, targetPath, attrs); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public void createDirectory(Path path, FileAttribute<?>... fileAttributes) throws IOException { if (Files.exists(path)) { throw new FileAlreadyExistsException(path.toString()); } if (!Files.exists(path.getParent())) { throw new IOException(); } int mode = 0775; if (fileAttributes.length > 0) { mode = GlusterFileAttributes.parseAttrs(fileAttributes); } int ret = GLFS.glfs_mkdir(((GlusterFileSystem) path.getFileSystem()).getVolptr(), path.toString(), mode); if (ret < 0) { throw new IOException(path.toString()); } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = FileAlreadyExistsException.class) public void testCreateDirectory_whenFileOrDirectoryExists() throws IOException { mockStatic(Files.class); when(Files.exists(mockPath)).thenReturn(true); provider.createDirectory(mockPath); }
@Test(expected = IOException.class) public void testCreateDirectory_whenParentDirectoryDoesNotExist() throws IOException { mockStatic(Files.class); GlusterPath parentPath = Mockito.mock(GlusterPath.class); doReturn(parentPath).when(mockPath).getParent(); when(Files.exists(parentPath)).thenReturn(false); provider.createDirectory(mockPath); }
@Test public void testCreateDirectory() throws IOException { helperCreateDirectory(false, false); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public FileStore getFileStore(Path path) throws IOException { if (Files.exists(path)) { return path.getFileSystem().getFileStores().iterator().next(); } else { throw new NoSuchFileException(path.toString()); } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = NoSuchFileException.class) public void testGetFileStore_whenFileDoesNotExist() throws IOException { mockStatic(Files.class); when(Files.exists(mockPath)).thenReturn(false); provider.getFileStore(mockPath); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { @Override public boolean isSameFile(Path path, Path path2) throws IOException { if (path.equals(path2)) { return true; } if (!path.getFileSystem().equals(path2.getFileSystem())) { return false; } guardFileExists(path); guardFileExists(path2); stat stat1 = statPath(path); stat stat2 = statPath(path2); return stat1.st_ino == stat2.st_ino; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testIsSameFile_whenSamePaths() throws IOException { doReturn("/").when(mockFileSystem).getSeparator(); GlusterPath path = new GlusterPath(mockFileSystem, "/foo/bar"); boolean ret = provider.isSameFile(path, path); assertTrue(ret); verify(mockFileSystem, times(3)).getSeparator(); }
@Test public void testIsSameFile_whenPathsEqual() throws IOException { doReturn("/").when(mockFileSystem).getSeparator(); GlusterPath path1 = new GlusterPath(mockFileSystem, "/foo/bar"); GlusterPath path2 = new GlusterPath(mockFileSystem, "/foo/bar"); boolean ret = provider.isSameFile(path1, path2); assertTrue(ret); verify(mockFileSystem, times(6)).getSeparator(); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { stat statPath(Path path) throws IOException { stat stat = new stat(); String pathString = ((GlusterPath) path).getString(); int ret = GLFS.glfs_stat(((GlusterFileSystem) path.getFileSystem()).getVolptr(), pathString, stat); if (ret != 0) { throw new IOException("Stat failed for " + pathString); } return stat; } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test public void testStatPath() throws Exception { long volptr = 1234L; stat stat = new stat(); whenNew(stat.class).withNoArguments().thenReturn(stat); mockStatic(GLFS.class); String pathString = "/foo"; when(GLFS.glfs_stat(volptr, pathString, stat)).thenReturn(0); doReturn(mockFileSystem).when(mockPath).getFileSystem(); doReturn(volptr).when(mockFileSystem).getVolptr(); doReturn(pathString).when(mockPath).getString(); stat ret = provider.statPath(mockPath); assertTrue(ret == stat); verify(mockPath).getFileSystem(); verify(mockFileSystem).getVolptr(); verify(mockPath).getString(); verifyStatic(); GLFS.glfs_stat(volptr, pathString, stat); verifyNew(stat.class).withNoArguments(); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { void guardFileExists(Path path) throws NoSuchFileException { if (!Files.exists(path)) { throw new NoSuchFileException(path.toString()); } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = NoSuchFileException.class) public void testGuardFileExists_whenDoesNotExist() throws NoSuchFileException { mockStatic(Files.class); PowerMockito.when(Files.exists(mockPath)).thenReturn(false); provider.guardFileExists(mockPath); }
@Test public void testGuardFileExists_whenDoesExist() throws NoSuchFileException { mockStatic(Files.class); PowerMockito.when(Files.exists(mockPath)).thenReturn(true); provider.guardFileExists(mockPath); verifyStatic(); Files.exists(mockPath); } |
### Question:
GlusterFileSystemProvider extends FileSystemProvider { void guardAbsolutePath(Path p) { if (!p.isAbsolute()) { throw new UnsupportedOperationException("Relative paths not supported: " + p); } } @Override String getScheme(); @Override FileSystem newFileSystem(URI uri, Map<String, ?> stringMap); @Override FileSystem getFileSystem(URI uri); @Override Path getPath(URI uri); @Override SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> openOptions, FileAttribute<?>... fileAttributes); @Override FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs); @Override DirectoryStream<Path> newDirectoryStream(Path path, DirectoryStream.Filter<? super Path> filter); @Override void createDirectory(Path path, FileAttribute<?>... fileAttributes); @Override void delete(Path path); @Override void copy(Path path, Path path2, CopyOption... copyOptions); @Override void move(Path path, Path path2, CopyOption... copyOptions); @Override boolean isSameFile(Path path, Path path2); @Override boolean isHidden(Path path); @Override FileStore getFileStore(Path path); @Override void checkAccess(Path path, AccessMode... accessModes); @Override V getFileAttributeView(Path path, Class<V> vClass, LinkOption... linkOptions); @Override A readAttributes(Path path, Class<A> type, LinkOption... linkOptions); @Override Map<String, Object> readAttributes(Path path, String s, LinkOption... linkOptions); @Override void setAttribute(Path path, String s, Object o, LinkOption... linkOptions); @Override Path readSymbolicLink(Path link); @Override void createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs); static final String GLUSTER; static final int GLUSTERD_PORT; static final String TCP; }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testGuardAbsolutePath_whenRelative() { doReturn(false).when(mockPath).isAbsolute(); provider.guardAbsolutePath(mockPath); }
@Test public void testGuardAbsolutePath_whenAbsolute() { doReturn(true).when(mockPath).isAbsolute(); provider.guardAbsolutePath(mockPath); verify(mockPath).isAbsolute(); } |
### Question:
GlusterFileSystem extends FileSystem { @Override public FileSystemProvider provider() { return provider; } @Override FileSystemProvider provider(); @Override void close(); @Override boolean isOpen(); @Override boolean isReadOnly(); @Override String getSeparator(); @Override Iterable<Path> getRootDirectories(); @Override Iterable<FileStore> getFileStores(); @Override Set<String> supportedFileAttributeViews(); @Override Path getPath(String s, String... strings); @Override PathMatcher getPathMatcher(String s); @Override UserPrincipalLookupService getUserPrincipalLookupService(); @Override WatchService newWatchService(); String toString(); }### Answer:
@Test public void testProvider() { assertEquals(mockFileSystemProvider, fileSystem.provider()); } |
### Question:
GlusterFileSystem extends FileSystem { @Override public void close() throws IOException { if (isOpen()) { int fini = provider.close(volptr); if (0 != fini) { throw new IOException("Unable to close filesystem: " + volname); } volptr = -1; } } @Override FileSystemProvider provider(); @Override void close(); @Override boolean isOpen(); @Override boolean isReadOnly(); @Override String getSeparator(); @Override Iterable<Path> getRootDirectories(); @Override Iterable<FileStore> getFileStores(); @Override Set<String> supportedFileAttributeViews(); @Override Path getPath(String s, String... strings); @Override PathMatcher getPathMatcher(String s); @Override UserPrincipalLookupService getUserPrincipalLookupService(); @Override WatchService newWatchService(); String toString(); }### Answer:
@Test(expected = IOException.class) public void testClose_whenFailing() throws IOException { doReturn(11).when(mockFileSystemProvider).close(VOLPTR); fileSystem.close(); }
@Test public void testClose() throws IOException { doReturn(0).when(mockFileSystemProvider).close(VOLPTR); fileSystem.close(); verify(mockFileSystemProvider).close(VOLPTR); assertEquals(-1, fileSystem.getVolptr()); } |
### Question:
RegisterEmailActivity extends AppCompatBase implements
CheckEmailFragment.CheckEmailListener { @Override public void onNewUser(User user) { TextInputLayout emailLayout = (TextInputLayout) findViewById(R.id.email_layout); if (mActivityHelper.getFlowParams().allowNewEmailAccounts) { RegisterEmailFragment fragment = RegisterEmailFragment.newInstance( mActivityHelper.getFlowParams(), user); FragmentTransaction ft = getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_register_email, fragment, RegisterEmailFragment.TAG); if (emailLayout != null) ft.addSharedElement(emailLayout, "email_field"); ft.disallowAddToBackStack().commit(); } else { emailLayout.setError(getString(R.string.error_email_does_not_exist)); } } static Intent createIntent(Context context, FlowParameters flowParams); static Intent createIntent(Context context, FlowParameters flowParams, String email); @Override void onExistingEmailUser(User user); @Override void onExistingIdpUser(User user); @Override void onNewUser(User user); static final int RC_WELCOME_BACK_IDP; }### Answer:
@Test public void testSignUpButton_validatesFields() { RegisterEmailActivity registerEmailActivity = createActivity(); registerEmailActivity.onNewUser(new User.Builder(TestConstants.EMAIL).build()); Button button = (Button) registerEmailActivity.findViewById(R.id.button_create); button.performClick(); TextInputLayout nameLayout = (TextInputLayout) registerEmailActivity.findViewById(R.id.name_layout); TextInputLayout passwordLayout = (TextInputLayout) registerEmailActivity.findViewById(R.id.password_layout); assertEquals( registerEmailActivity.getString(R.string.required_field), nameLayout.getError().toString()); assertEquals( String.format( registerEmailActivity.getResources().getQuantityString( R.plurals.error_weak_password, R.integer.min_password_length), registerEmailActivity.getResources() .getInteger(R.integer.min_password_length) ), passwordLayout.getError().toString()); }
@Test @Config(shadows = {BaseHelperShadow.class, ActivityHelperShadow.class}) public void testSignUpButton_successfulRegistrationShouldContinueToSaveCredentials() { new BaseHelperShadow(); reset(BaseHelperShadow.sSaveSmartLock); TestHelper.initializeApp(RuntimeEnvironment.application); RegisterEmailActivity registerEmailActivity = createActivity(); registerEmailActivity.onNewUser(new User.Builder(TestConstants.EMAIL) .setName(TestConstants.NAME) .setPhotoUri(TestConstants.PHOTO_URI) .build()); EditText name = (EditText) registerEmailActivity.findViewById(R.id.name); EditText password = (EditText) registerEmailActivity.findViewById(R.id.password); name.setText(TestConstants.NAME); password.setText(TestConstants.PASSWORD); when(BaseHelperShadow.sFirebaseUser.updateProfile(any(UserProfileChangeRequest.class))) .thenReturn(new AutoCompleteTask<Void>(null, true, null)); when(BaseHelperShadow.sFirebaseAuth .createUserWithEmailAndPassword( TestConstants.EMAIL, TestConstants.PASSWORD)) .thenReturn(new AutoCompleteTask<>(FakeAuthResult.INSTANCE, true, null)); Button button = (Button) registerEmailActivity.findViewById(R.id.button_create); button.performClick(); TestHelper.verifySmartLockSave( EmailAuthProvider.PROVIDER_ID, TestConstants.EMAIL, TestConstants.PASSWORD); } |
### Question:
PhoneNumber { public static boolean isValid(PhoneNumber phoneNumber) { return phoneNumber != null && !EMPTY_PHONE_NUMBER.equals(phoneNumber) && !TextUtils .isEmpty(phoneNumber.getPhoneNumber()) && !TextUtils.isEmpty(phoneNumber .getCountryCode()) && !TextUtils.isEmpty(phoneNumber.getCountryIso()); } PhoneNumber(String phoneNumber, String countryIso, String countryCode); static PhoneNumber emptyPhone(); String getCountryCode(); String getPhoneNumber(); String getCountryIso(); static boolean isValid(PhoneNumber phoneNumber); static boolean isCountryValid(PhoneNumber phoneNumber); }### Answer:
@Test public void testIsValid_nullPhone() throws Exception { assertFalse(PhoneNumber.isValid(null)); }
@Test public void testIsValid_emptyMembers() throws Exception { PhoneNumber invalidPhoneNumber = new PhoneNumber("", PhoneTestConstants.US_ISO2, PhoneTestConstants .US_COUNTRY_CODE); assertFalse(PhoneNumber.isValid(invalidPhoneNumber)); invalidPhoneNumber = new PhoneNumber(PhoneTestConstants.PHONE, "", PhoneTestConstants .US_COUNTRY_CODE); assertFalse(PhoneNumber.isValid(invalidPhoneNumber)); invalidPhoneNumber = new PhoneNumber(PhoneTestConstants.PHONE, PhoneTestConstants.US_ISO2, ""); assertFalse(PhoneNumber.isValid(invalidPhoneNumber)); }
@Test public void testIsValid() throws Exception { final PhoneNumber validPhoneNumber = new PhoneNumber(PhoneTestConstants.PHONE, PhoneTestConstants .US_ISO2, PhoneTestConstants.US_COUNTRY_CODE); assertTrue(PhoneNumber.isValid(validPhoneNumber)); } |
### Question:
PhoneNumber { public static boolean isCountryValid(PhoneNumber phoneNumber) { return phoneNumber != null && !EMPTY_PHONE_NUMBER.equals(phoneNumber) && !TextUtils .isEmpty(phoneNumber.getCountryCode()) && !TextUtils.isEmpty(phoneNumber .getCountryIso()); } PhoneNumber(String phoneNumber, String countryIso, String countryCode); static PhoneNumber emptyPhone(); String getCountryCode(); String getPhoneNumber(); String getCountryIso(); static boolean isValid(PhoneNumber phoneNumber); static boolean isCountryValid(PhoneNumber phoneNumber); }### Answer:
@Test public void testIsCountryValid_nullPhone() throws Exception { assertFalse(PhoneNumber.isCountryValid(null)); }
@Test public void testIsCountryValid_emptyMembers() throws Exception { PhoneNumber invalidPhoneNumber = new PhoneNumber("", "", PhoneTestConstants.US_COUNTRY_CODE); assertFalse(PhoneNumber.isCountryValid(invalidPhoneNumber)); invalidPhoneNumber = new PhoneNumber("", PhoneTestConstants.US_ISO2, ""); assertFalse(PhoneNumber.isCountryValid(invalidPhoneNumber)); }
@Test public void testIsCountryValid() throws Exception { final PhoneNumber validPhoneNumber = new PhoneNumber("", PhoneTestConstants.US_ISO2, PhoneTestConstants.US_COUNTRY_CODE); assertTrue(PhoneNumber.isCountryValid(validPhoneNumber)); } |
### Question:
BucketedTextChangeListener implements TextWatcher { @SuppressLint("SetTextI18n") @Override public void onTextChanged(CharSequence s, int ignoredParam1, int ignoredParam2, int ignoredParam3) { final String numericContents = s.toString().replaceAll(" ", "").replaceAll(placeHolder, ""); final int enteredContentLength = Math.min(numericContents.length(), expectedContentLength); final String enteredContent = numericContents.substring(0, enteredContentLength); editText.removeTextChangedListener(this); editText.setText(enteredContent + postFixes[expectedContentLength - enteredContentLength]); editText.setSelection(enteredContentLength); editText.addTextChangedListener(this); if (enteredContentLength == expectedContentLength && callback != null) { callback.whileComplete(); } else if (callback != null) { callback.whileIncomplete(); } } BucketedTextChangeListener(EditText editText, int expectedContentLength, String
placeHolder, ContentChangeCallback callback); @Override void beforeTextChanged(CharSequence s, int start, int count, int after); @SuppressLint("SetTextI18n") @Override void onTextChanged(CharSequence s, int ignoredParam1, int ignoredParam2, int
ignoredParam3); @Override void afterTextChanged(Editable s); }### Answer:
@Test public void testTextChange_empty() { textChangeListener.onTextChanged("------", anyInt, anyInt, anyInt); testListener(editText, "------", 0, false); }
@Test public void testTextChange_atIndex0() { textChangeListener.onTextChanged("1------", anyInt, anyInt, anyInt); testListener(editText, "1-----", 1, false); }
@Test public void testTextChange_atIndex1() { textChangeListener.onTextChanged("12-----", anyInt, anyInt, anyInt); testListener(editText, "12----", 2, false); }
@Test public void testTextChange_atIndex5() { textChangeListener.onTextChanged("123456-", anyInt, anyInt, anyInt); testListener(editText, "123456", 6, true); }
@Test public void testTextChange_exceedingMaxLength() { textChangeListener.onTextChanged("1234567", anyInt, anyInt, anyInt); testListener(editText, "123456", 6, true); }
@Test public void testTextChange_onClear() { textChangeListener.onTextChanged("", anyInt, anyInt, anyInt); testListener(editText, "------", 0, false); }
@Test public void testTextChange_onPartialClear() { textChangeListener.onTextChanged("123", anyInt, anyInt, anyInt); testListener(editText, "123---", 3, false); }
@Test public void testTextChange_onIncorrectInsertion() { textChangeListener.onTextChanged("1--3--", anyInt, anyInt, anyInt); testListener(editText, "13----", 2, false); } |
### Question:
SpacedEditText extends AppCompatEditText { @Override public void setText(CharSequence text, BufferType type) { originalText = new SpannableStringBuilder(text); final SpannableStringBuilder spacedOutString = getSpacedOutString(text); super.setText(spacedOutString, BufferType.SPANNABLE); } SpacedEditText(Context context); SpacedEditText(Context context, AttributeSet attrs); @Override void setText(CharSequence text, BufferType type); @Override void setSelection(int index); Editable getUnspacedText(); }### Answer:
@Test public void testSpacedEditText_setTextEmpty() throws Exception { spacedEditText.setText(""); testSpacing("", "", spacedEditText); }
@Test public void testSpacedEditText_setTextNonEmpty() throws Exception { spacedEditText.setText("123456"); testSpacing("1 2 3 4 5 6", "123456", spacedEditText); }
@Test public void testSpacedEditText_setTextWithOneCharacter() throws Exception { spacedEditText.setText("1"); testSpacing("1", "1", spacedEditText); }
@Test public void testSpacedEditText_setTextWithExistingSpaces() throws Exception { spacedEditText.setText("1 2 3"); testSpacing("1 2 3", "1 2 3", spacedEditText); } |
### Question:
PhoneVerificationActivity extends AppCompatBase { public static Intent createIntent(Context context, FlowParameters flowParams, String phone) { return BaseHelper.createBaseIntent(context, PhoneVerificationActivity.class, flowParams) .putExtra(ExtraConstants.EXTRA_PHONE, phone); } static Intent createIntent(Context context, FlowParameters flowParams, String phone); @Override void onBackPressed(); void submitConfirmationCode(String confirmationCode); }### Answer:
@Test public void testPhoneNumberFromSmartlock_prePopulatesPhoneNumberInBundle() { Intent startIntent = PhoneVerificationActivity.createIntent(RuntimeEnvironment .application, TestHelper.getFlowParameters(Collections.singletonList(AuthUI .PHONE_VERIFICATION_PROVIDER)), YE_RAW_PHONE); mActivity = Robolectric.buildActivity(PhoneVerificationActivity.class).withIntent (startIntent).create(new Bundle()).start().visible().get(); VerifyPhoneNumberFragment verifyPhoneNumberFragment = (VerifyPhoneNumberFragment) mActivity.getSupportFragmentManager().findFragmentByTag(VerifyPhoneNumberFragment .TAG); assertNotNull(verifyPhoneNumberFragment); mPhoneEditText = (EditText) mActivity.findViewById(R.id.phone_number); mCountryListSpinner = (CountryListSpinner) mActivity.findViewById(R.id.country_list); assertEquals(PHONE_NO_COUNTRY_CODE, mPhoneEditText.getText().toString()); assertEquals(YE_COUNTRY_CODE, String.valueOf(((CountryInfo) mCountryListSpinner.getTag()) .countryCode)); } |
### Question:
PhoneVerificationActivity extends AppCompatBase { @VisibleForTesting(otherwise = VisibleForTesting.NONE) protected AlertDialog getAlertDialog() { return mAlertDialog; } static Intent createIntent(Context context, FlowParameters flowParams, String phone); @Override void onBackPressed(); void submitConfirmationCode(String confirmationCode); }### Answer:
@Test @Config(shadows = {BaseHelperShadow.class, ActivityHelperShadow.class}) public void testSubmitCode_badCodeShowsAlertDialog() { reset(BaseHelperShadow.sPhoneAuthProvider); when(ActivityHelperShadow.sFirebaseAuth.signInWithCredential(any(AuthCredential.class))) .thenReturn(new AutoCompleteTask<AuthResult>(null, true, new FirebaseAuthInvalidCredentialsException(ERROR_INVALID_VERIFICATION, "any_msg"))); testSendConfirmationCode(); SpacedEditText mConfirmationCodeEditText = (SpacedEditText) mActivity.findViewById(R.id .confirmation_code); Button mSubmitConfirmationButton = (Button) mActivity.findViewById(R.id .submit_confirmation_code); mConfirmationCodeEditText.setText("123456"); mSubmitConfirmationButton.performClick(); assertEquals(mActivity.getString(R.string.incorrect_code_dialog_body), getAlertDialogMessage()); android.support.v7.app.AlertDialog a = mActivity.getAlertDialog(); Button ok = (Button) a.findViewById(android.R.id.button1); ok.performClick(); assertEquals("- - - - - -", mConfirmationCodeEditText.getText().toString()); } |
### Question:
PhoneVerificationActivity extends AppCompatBase { void verifyPhoneNumber(String phoneNumber, boolean forceResend) { sendCode(phoneNumber, forceResend); if (forceResend) { showLoadingDialog(getString(R.string.resending)); } else { showLoadingDialog(getString(R.string.verifying)); } } static Intent createIntent(Context context, FlowParameters flowParams, String phone); @Override void onBackPressed(); void submitConfirmationCode(String confirmationCode); }### Answer:
@Test @Config(shadows = {BaseHelperShadow.class, ActivityHelperShadow.class}) public void testresendCode_invokesUpstream() { reset(BaseHelperShadow.sPhoneAuthProvider); testSendConfirmationCode(); TextView r = (TextView) mActivity.findViewById(R.id.resend_code); assertEquals(View.GONE, r.getVisibility()); SubmitConfirmationCodeFragment fragment = (SubmitConfirmationCodeFragment) mActivity .getSupportFragmentManager().findFragmentByTag(SubmitConfirmationCodeFragment.TAG); fragment.getmCountdownTimer().onFinish(); assertEquals(View.VISIBLE, r.getVisibility()); r.performClick(); assertEquals(View.GONE, r.getVisibility()); verify(ActivityHelperShadow.sPhoneAuthProvider).verifyPhoneNumber(eq(PHONE), eq (AUTO_RETRIEVAL_TIMEOUT_MILLIS), eq(TimeUnit.MILLISECONDS), eq(mActivity), callbacksArgumentCaptor.capture(), eq(forceResendingToken)); }
@Test @Config(shadows = {BaseHelperShadow.class, ActivityHelperShadow.class}) public void testAutoVerify() { reset(BaseHelperShadow.sPhoneAuthProvider); reset(BaseHelperShadow.sSaveSmartLock); reset(BaseHelperShadow.sFirebaseAuth); when(BaseHelperShadow.sFirebaseUser.getPhoneNumber()).thenReturn(PHONE); when(BaseHelperShadow.sFirebaseUser.getEmail()).thenReturn(null); when(ActivityHelperShadow.sFirebaseAuth.signInWithCredential(any(AuthCredential.class))) .thenReturn(new AutoCompleteTask(FakeAuthResult.INSTANCE , true, null)); mActivity.verifyPhoneNumber(PHONE, false); verify(ActivityHelperShadow.sPhoneAuthProvider).verifyPhoneNumber(eq(PHONE), eq (AUTO_RETRIEVAL_TIMEOUT_MILLIS), eq(TimeUnit.MILLISECONDS), eq(mActivity), callbacksArgumentCaptor.capture(), isNull(PhoneAuthProvider.ForceResendingToken .class)); PhoneAuthProvider.OnVerificationStateChangedCallbacks onVerificationStateChangedCallbacks = callbacksArgumentCaptor.getValue(); onVerificationStateChangedCallbacks.onVerificationCompleted(credential); verify(ActivityHelperShadow.sFirebaseAuth).signInWithCredential(any(AuthCredential.class)); } |
### Question:
PhoneNumberUtils { protected static PhoneNumber getPhoneNumber(@NonNull String providedPhoneNumber) { String countryCode = DEFAULT_COUNTRY_CODE; String countryIso = DEFAULT_LOCALE.getCountry(); String phoneNumber = providedPhoneNumber; if (providedPhoneNumber.startsWith("+")) { countryCode = countryCodeForPhoneNumber(providedPhoneNumber); countryIso = countryIsoForCountryCode(countryCode); phoneNumber = stripCountryCode(providedPhoneNumber, countryCode); } return new PhoneNumber(phoneNumber, countryIso, countryCode); } @Nullable static Integer getCountryCode(String countryIso); }### Answer:
@Test public void testGetPhoneNumber() throws Exception { final PhoneNumber number = getPhoneNumber(RAW_PHONE); assertEquals(PhoneTestConstants.PHONE_NO_COUNTRY_CODE, number.getPhoneNumber()); assertEquals(PhoneTestConstants.US_COUNTRY_CODE, number.getCountryCode()); assertEquals(PhoneTestConstants.US_ISO2, number.getCountryIso()); } |
### Question:
PhoneNumberUtils { @Nullable public static Integer getCountryCode(String countryIso) { return countryIso == null ? null : CountryCodeByIsoMap.get(countryIso.toUpperCase(Locale.getDefault())); } @Nullable static Integer getCountryCode(String countryIso); }### Answer:
@Test public void testGetCountryCode() throws Exception { assertEquals(new Integer(86), getCountryCode(Locale.CHINA.getCountry())); assertEquals(null, getCountryCode(null)); assertEquals(null, getCountryCode(new Locale("", "DJJZ").getCountry())); } |
### Question:
PhoneNumberUtils { @Nullable static String formatPhoneNumber(@NonNull String phoneNumber, @NonNull CountryInfo countryInfo) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return android.telephony.PhoneNumberUtils .formatNumberToE164(phoneNumber, countryInfo.locale.getCountry()); } return phoneNumber.startsWith("+") ? phoneNumber : ("+" + String.valueOf(countryInfo.countryCode) + phoneNumber.replaceAll("[^\\d.]", "")); } @Nullable static Integer getCountryCode(String countryIso); }### Answer:
@Test @Config(constants = BuildConfig.class, sdk = 21) public void testFormatNumberToE164_aboveApi21() { String validPhoneNumber = "+919994947354"; CountryInfo indiaCountryInfo = new CountryInfo(new Locale("", "IN"), 91); assertEquals(validPhoneNumber, formatPhoneNumber("9994947354", indiaCountryInfo)); assertEquals(validPhoneNumber, formatPhoneNumber("919994947354", indiaCountryInfo)); assertEquals(validPhoneNumber, formatPhoneNumber("+919994947354", indiaCountryInfo)); assertEquals(validPhoneNumber, formatPhoneNumber("+91-(999)-(49)-(47354)", indiaCountryInfo)); assertEquals(validPhoneNumber, formatPhoneNumber("+91 99949 47354", indiaCountryInfo)); assertEquals(validPhoneNumber, formatPhoneNumber("91 99949 47354", indiaCountryInfo)); assertEquals(validPhoneNumber, formatPhoneNumber("(99949) 47-354", indiaCountryInfo)); assertEquals(validPhoneNumber, formatPhoneNumber("+919994947354", new CountryInfo( new Locale("", "US"), 1))); assertNull(formatPhoneNumber("999474735", indiaCountryInfo)); assertNull(validPhoneNumber, formatPhoneNumber("919994947354", new CountryInfo( new Locale("", "US"), 1))); assertNull(formatPhoneNumber("+914349873457", new CountryInfo( new Locale("", "US"), 1))); }
@Test @Config(constants = BuildConfig.class, sdk = 16) public void testFormatNumberToE164_belowApi21() { String validPhoneNumber = "+919994947354"; CountryInfo indiaCountryInfo = new CountryInfo(new Locale("", "IN"), 91); assertEquals(validPhoneNumber, formatPhoneNumber("9994947354", indiaCountryInfo)); assertEquals(validPhoneNumber, formatPhoneNumber("+919994947354", indiaCountryInfo)); assertEquals(validPhoneNumber, formatPhoneNumber("(99949) 47-354", indiaCountryInfo)); } |
### Question:
PhoneNumberUtils { @NonNull static CountryInfo getCurrentCountryInfo(@NonNull Context context) { Locale locale = getSimBasedLocale(context); if (locale == null) { locale = getOSLocale(); } if (locale == null) { return DEFAULT_COUNTRY; } Integer countryCode = PhoneNumberUtils.getCountryCode(locale.getCountry()); return countryCode == null ? DEFAULT_COUNTRY : new CountryInfo(locale, countryCode); } @Nullable static Integer getCountryCode(String countryIso); }### Answer:
@Test public void testGetCurrentCountryInfo_fromSim() { Context context = mock(Context.class); TelephonyManager telephonyManager = mock(TelephonyManager.class); when(context.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(telephonyManager); when(telephonyManager.getSimCountryIso()).thenReturn("IN"); assertEquals(new CountryInfo(new Locale("", "IN"), 91), getCurrentCountryInfo(context)); } |
### Question:
FileTaskAccessor implements TaskAccessor { @Override public List<Task> loadTasks() { List<Task> tasks = new ArrayList<>(); File[] taskFiles = FileAccessSupport.getTaskFiles(DEFAULT_TASK_PATH); for (File taskFile : taskFiles) { Task task = FileParser.parseTask(taskFile, false); tasks.add(task); } return tasks; } @Override List<Task> loadTasks(); @Override Task loadTaskByName(String taskName); @Override Host loadHostById(String hostId); @Override void createSnapshot(HostSnapshot snapshot); @Override void saveCrawledResult(CrawledResult crawledResult, List<ErrorPageDTO> errorPages); @Override HostResult getHostResult(String hostId); @Override List<ErrorPageDTO> getErrorPages(String hostId, int startPos, int size); @Override int getErrorPageNum(String hostId); @Override void rollbackHost(String hostId); }### Answer:
@Test public void loadTasks() { List<Task> tasks = fileTaskLoader.loadTasks(); Assert.assertEquals(1, tasks.size()); } |
### Question:
DescriptorExtractor { public static List<FieldDescriptor> extract(AbstractFieldsSnippet snippet) { try { Method getFieldDescriptors = AbstractFieldsSnippet.class.getDeclaredMethod("getFieldDescriptors"); getFieldDescriptors.setAccessible(true); return (List<FieldDescriptor>) getFieldDescriptors.invoke(snippet); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { e.printStackTrace(); } return emptyList(); } static List<FieldDescriptor> extract(AbstractFieldsSnippet snippet); static List<LinkDescriptor> extract(LinksSnippet snippet); static List<HeaderDescriptor> extract(AbstractHeadersSnippet snippet); static List<ParameterDescriptor> extract(AbstractParametersSnippet snippet); }### Answer:
@Test public void should_extract_request_field_descriptors() { RequestFieldsSnippet snippet = requestFields( fieldWithPath("object.field").description("Is documented!") ); List<FieldDescriptor> descriptors = extract(snippet); then(descriptors).hasSize(1); then(descriptors.get(0).getPath()).isEqualTo("object.field"); then(descriptors.get(0).getDescription()).isEqualTo("Is documented!"); }
@Test public void should_extract_response_field_descriptors() { ResponseFieldsSnippet snippet = responseFields( fieldWithPath("object.field").description("Is documented!"), fieldWithPath("object.anotherField").description("Is documented, too!") ); List<FieldDescriptor> descriptors = extract(snippet); then(descriptors).hasSize(2); then(descriptors.stream().map(FieldDescriptor::getPath).collect(toList())) .containsExactly("object.field", "object.anotherField"); then(descriptors.stream().map(AbstractDescriptor::getDescription).collect(toList())) .containsExactly("Is documented!", "Is documented, too!"); }
@Test public void should_extract_link_descriptors() { LinksSnippet snippet = links( linkWithRel("self").description("Is documented!") ); List<LinkDescriptor> descriptors = extract(snippet); then(descriptors).hasSize(1); then(descriptors.get(0).getRel()).isEqualTo("self"); then(descriptors.get(0).getDescription()).isEqualTo("Is documented!"); }
@Test public void should_extract_request_parameter_descriptors() { RequestParametersSnippet snippet = requestParameters( parameterWithName("page").description("Is documented!"), parameterWithName("elementsPerPage").description("Is documented!") ); List<ParameterDescriptor> descriptors = extract(snippet); then(descriptors).hasSize(2); then(descriptors.stream().map(ParameterDescriptor::getName).collect(toList())) .containsExactly("page", "elementsPerPage"); then(descriptors.stream().map(AbstractDescriptor::getDescription).collect(toList())) .containsExactly("Is documented!", "Is documented!"); } |
### Question:
FieldDescriptors { public FieldDescriptors and(FieldDescriptor... additionalDescriptors) { return andWithPrefix("", additionalDescriptors); } FieldDescriptors(FieldDescriptor... fieldDescriptors); FieldDescriptors and(FieldDescriptor... additionalDescriptors); FieldDescriptors andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors); }### Answer:
@Test public void should_combine_descriptors() { fieldDescriptors = givenFieldDescriptors(); then(fieldDescriptors.and(fieldWithPath("c")).getFieldDescriptors()) .extracting(FieldDescriptor::getPath).contains("a", "b", "c"); } |
### Question:
FieldDescriptors { public FieldDescriptors andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors) { List<FieldDescriptor> combinedDescriptors = new ArrayList<>(fieldDescriptors); combinedDescriptors.addAll(applyPathPrefix(pathPrefix, Arrays.asList(additionalDescriptors))); return new FieldDescriptors(combinedDescriptors); } FieldDescriptors(FieldDescriptor... fieldDescriptors); FieldDescriptors and(FieldDescriptor... additionalDescriptors); FieldDescriptors andWithPrefix(String pathPrefix, FieldDescriptor... additionalDescriptors); }### Answer:
@Test public void should_combine_descriptors_with_prefix() { fieldDescriptors = givenFieldDescriptors(); then(fieldDescriptors.andWithPrefix("d.", fieldWithPath("c")).getFieldDescriptors()) .extracting(FieldDescriptor::getPath).contains("a", "b", "d.c"); } |
### Question:
BujintMojo extends AbstractMojo { String nowTimeImageUrl() throws Exception { String time = DateFormatUtils.format(new Date(), "hhmm"); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = buildDefaultHttpMessage(new HttpGet("http: httpget.setHeader("Referer", "http: HttpResponse response = httpclient.execute(httpget); if (response.getStatusLine().getStatusCode() != 200) { getLog().error("美人時計忙しいらしいよ。なんか200じゃないの返してくる。"); return null; } String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); httpclient.getConnectionManager().shutdown(); return "http: } void execute(); }### Answer:
@Test public void testNowTimeImageUrl() throws Exception { BujintMojo target = new BujintMojo(); String result = target.nowTimeImageUrl(); System.out.println(result); } |
### Question:
BujintMojo extends AbstractMojo { String getImagePath(String str) throws Exception { DOMParser parser = new DOMParser(); parser.parse(new InputSource(new StringReader(str))); NodeList nodeList = XPathAPI.selectNodeList(parser.getDocument(), "/HTML/BODY/TABLE/TR/TH[1]/IMG"); String path = null; for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); path = element.getAttribute("src"); } return path; } void execute(); }### Answer:
@Test public void testGetImagePath() throws Exception { InputStream is = getClass().getClassLoader().getResourceAsStream( "test.html"); String str = IOUtils.toString(is, "UTF-8"); BujintMojo target = new BujintMojo(); assertEquals("結果が不正です", "/jp/img/clk/6976221_31.jpg", target .getImagePath(str)); } |
### Question:
BujintMojo extends AbstractMojo { BufferedImage getFittingImage(String url) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = buildDefaultHttpMessage(new HttpGet(url)); httpget.setHeader("Referer", "http: HttpResponse response = httpclient.execute(httpget); BufferedImage image = ImageIO.read(response.getEntity().getContent()); httpclient.getConnectionManager().shutdown(); int width = image.getWidth() / 10 * 4; int height = image.getHeight() / 10 * 4; BufferedImage resizedImage = null; resizedImage = new BufferedImage(width, height, image.getType()); resizedImage.getGraphics().drawImage( image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING), 0, 0, width, height, null); return resizedImage; } void execute(); }### Answer:
@Test public void testGetFittingImage() throws Exception { BujintMojo target = new BujintMojo(); BufferedImage image = target.getFittingImage(target.nowTimeImageUrl()); ImageIO.write(image, "jpg", new File("test.jpg")); } |
### Question:
BujintMojo extends AbstractMojo { public void execute() throws MojoExecutionException { try { String imgUrl = nowTimeImageUrl(); if (imgUrl == null) { return; } getLog().info("\n" + getAsciiArt(getFittingImage(imgUrl))); } catch (Exception e) { e.printStackTrace(); throw new MojoExecutionException("なんかエラー", e); } } void execute(); }### Answer:
@Test public void testExecute() throws Exception { BujintMojo target = new BujintMojo(); target.execute(); } |
### Question:
XLSXSample { public void makeXlsxFile() throws Exception { String fileName = "test.xlsx"; FileOutputStream fileOut = new FileOutputStream(fileName); Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("test"); Row row = sheet.createRow((short)0); Cell cell = row.createCell(0); cell.setCellValue("日本語は通る?"); wb.write(fileOut); fileOut.close(); } void makeXlsxFile(); }### Answer:
@Test public void test() throws Exception { XLSXSample target = new XLSXSample(); target.makeXlsxFile(); } |
### Question:
DatabaseAccess { public void dbSelect() throws Exception { Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql: Connection con = DriverManager.getConnection(url, "np", "npnpnp"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(getPlainSQL()); rs.close(); stmt.close(); con.close(); } void dbSelect(); }### Answer:
@Test public void testSimple() throws Exception { DatabaseAccess da = new DatabaseAccess(); da.dbSelect(); } |
### Question:
DataAccessSampleLogic { public void insertData() { Connection con = null; Statement stmt = null; try { con = ds.getConnection(); stmt = con.createStatement(); int count = sampleLogic.plus(1, 5); for (int i = 0; i < count; i++) { stmt.executeUpdate("INSERT INTO EMP (id, name) values (" + i + ", 'test')"); } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (Exception ex) { throw new RuntimeException(ex); } } } List<EmpDto> getEmpAllRecord(); void insertData(); public DataSource ds; public SampleLogic sampleLogic; }### Answer:
@Mock(target = SampleLogic.class, pointcut = "plus", returnValue = "new Integer(10)") @Test public void testInsertData() throws Exception { target.insertData(); DataTable actual = dataAccessor.readDbByTable("emp"); DataSet expected = testContext.getExpected(); assertEquals(expected.getTable("emp"), actual); } |
### Question:
DataAccessSampleLogic { public List<EmpDto> getEmpAllRecord() { Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = ds.getConnection(); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM EMP"); List<EmpDto> list = new ArrayList<EmpDto>(); while (rs.next()) { EmpDto dto = new EmpDto(); dto.id = rs.getInt(1); dto.name = rs.getString(2); list.add(dto); } return list; } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (Exception ex) { throw new RuntimeException(ex); } } } List<EmpDto> getEmpAllRecord(); void insertData(); public DataSource ds; public SampleLogic sampleLogic; }### Answer:
@Test public void testGetEmpAllRecord() throws Exception { List<EmpDto> actual = target.getEmpAllRecord(); assertEquals(10, actual.size()); } |
### Question:
DIMACSExporter extends AbstractBaseExporter<V, E> implements GraphExporter<V, E> { public DIMACSFormat getFormat() { return format; } DIMACSExporter(); DIMACSExporter(ComponentNameProvider<V> vertexIDProvider); DIMACSExporter(ComponentNameProvider<V> vertexIDProvider, DIMACSFormat format); @Override void exportGraph(Graph<V, E> g, Writer writer); boolean isParameter(Parameter p); void setParameter(Parameter p, boolean value); DIMACSFormat getFormat(); void setFormat(DIMACSFormat format); static final DIMACSFormat DEFAULT_DIMACS_FORMAT; }### Answer:
@Test public void testDefaultFormat() { DIMACSExporter<String, DefaultWeightedEdge> exporter = new DIMACSExporter<>(); assertEquals(DIMACSFormat.MAX_CLIQUE, exporter.getFormat()); } |
### Question:
Coreness implements VertexScoringAlgorithm<V, Integer> { @Override public Integer getVertexScore(V v) { if (!g.containsVertex(v)) { throw new IllegalArgumentException("Cannot return score of unknown vertex"); } lazyRun(); return scores.get(v); } Coreness(Graph<V, E> g); @Override Map<V, Integer> getScores(); @Override Integer getVertexScore(V v); int getDegeneracy(); }### Answer:
@Test public void testNonExistantVertex() { SimpleGraph<String, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); g.addVertex("a"); VertexScoringAlgorithm<String, Integer> pr = new Coreness<>(g); try { pr.getVertexScore("unknown"); fail("No!"); } catch (IllegalArgumentException e) { } } |
### Question:
GraphWalk implements GraphPath<V, E> { public GraphWalk<V, E> reverse() { return this.reverse(null); } GraphWalk(Graph<V, E> graph, V startVertex, V endVertex, List<E> edgeList, double weight); GraphWalk(Graph<V, E> graph, List<V> vertexList, double weight); GraphWalk(
Graph<V, E> graph, V startVertex, V endVertex, List<V> vertexList, List<E> edgeList,
double weight); @Override Graph<V, E> getGraph(); @Override V getStartVertex(); @Override V getEndVertex(); @Override List<E> getEdgeList(); @Override List<V> getVertexList(); @Override double getWeight(); void setWeight(double weight); @Override int getLength(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); GraphWalk<V, E> reverse(); GraphWalk<V, E> reverse(Function<GraphWalk<V, E>, Double> walkWeightCalculator); GraphWalk<V, E> concat(
GraphWalk<V, E> extension, Function<GraphWalk<V, E>, Double> walkWeightCalculator); boolean isEmpty(); void verify(); static GraphWalk<V, E> emptyWalk(Graph<V, E> graph); static GraphWalk<V, E> singletonWalk(Graph<V, E> graph, V v); static GraphWalk<V, E> singletonWalk(Graph<V, E> graph, V v, double weight); }### Answer:
@Test(expected = InvalidGraphWalkException.class) public void testReverseInvalidPathDirected() { Graph<Integer, DefaultEdge> graph = new SimpleDirectedGraph<>(DefaultEdge.class); Graphs.addAllVertices(graph, Arrays.asList(0, 1, 2, 3)); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 3); GraphWalk<Integer, DefaultEdge> gw1 = new GraphWalk<>(graph, 0, 3, Arrays.asList(0, 1, 2, 3), null, 0); gw1.reverse(gw -> gw.edgeList.stream().mapToDouble(gw.graph::getEdgeWeight).sum()); } |
### Question:
MaskSubgraph extends AbstractGraph<V, E> implements Serializable { @Override public GraphType getType() { return baseType.asUnmodifiable(); } MaskSubgraph(Graph<V, E> base, Predicate<V> vertexMask, Predicate<E> edgeMask); @Override E addEdge(V sourceVertex, V targetVertex); @Override boolean addEdge(V sourceVertex, V targetVertex, E edge); @Override boolean addVertex(V v); @Override boolean containsEdge(E e); @Override boolean containsVertex(V v); @Override Set<E> edgeSet(); @Override Set<E> edgesOf(V vertex); @Override int degreeOf(V vertex); @Override Set<E> incomingEdgesOf(V vertex); @Override int inDegreeOf(V vertex); @Override Set<E> outgoingEdgesOf(V vertex); @Override int outDegreeOf(V vertex); @Override Set<E> getAllEdges(V sourceVertex, V targetVertex); @Override E getEdge(V sourceVertex, V targetVertex); @Override EdgeFactory<V, E> getEdgeFactory(); @Override V getEdgeSource(E edge); @Override V getEdgeTarget(E edge); @Override GraphType getType(); @Override double getEdgeWeight(E edge); @Override void setEdgeWeight(E edge, double weight); @Override boolean removeAllEdges(Collection<? extends E> edges); @Override Set<E> removeAllEdges(V sourceVertex, V targetVertex); @Override boolean removeAllVertices(Collection<? extends V> vertices); @Override boolean removeEdge(E e); @Override E removeEdge(V sourceVertex, V targetVertex); @Override boolean removeVertex(V v); @Override Set<V> vertexSet(); }### Answer:
@Test public void testUnmodifiable() { Graph<Integer, DefaultEdge> g = new Pseudograph<>(DefaultEdge.class); assertFalse(new MaskSubgraph<>(g, v -> v.equals(5), e -> false).getType().isModifiable()); } |
### Question:
DirectedAcyclicGraph extends SimpleDirectedGraph<V, E> implements Iterable<V> { public Iterator<V> iterator() { return new TopoIterator(); } DirectedAcyclicGraph(Class<? extends E> edgeClass); DirectedAcyclicGraph(Class<? extends E> edgeClass, boolean weighted); DirectedAcyclicGraph(EdgeFactory<V, E> ef); DirectedAcyclicGraph(EdgeFactory<V, E> ef, boolean weighted); protected DirectedAcyclicGraph(
EdgeFactory<V, E> ef, VisitedStrategyFactory visitedStrategyFactory,
TopoOrderMap<V> topoOrderMap, boolean weighted); static GraphBuilder<V, E, ? extends DirectedAcyclicGraph<V, E>> createBuilder(
Class<? extends E> edgeClass); static GraphBuilder<V, E, ? extends DirectedAcyclicGraph<V, E>> createBuilder(
EdgeFactory<V, E> ef); @Override GraphType getType(); @Override boolean addVertex(V v); @Override boolean removeVertex(V v); @Override E addEdge(V sourceVertex, V targetVertex); @Override boolean addEdge(V sourceVertex, V targetVertex, E e); Set<V> getAncestors(V vertex); Set<V> getDescendants(V vertex); Iterator<V> iterator(); }### Answer:
@Test public void testTopoIterationOrderLinearGraph() { DirectedAcyclicGraph<Long, DefaultEdge> dag = new DirectedAcyclicGraph<>(DefaultEdge.class); LinearGraphGenerator<Long, DefaultEdge> graphGen = new LinearGraphGenerator<>(100); graphGen.generateGraph(dag, new LongVertexFactory(), null); Iterator<Long> internalTopoIter = dag.iterator(); TopologicalOrderIterator<Long, DefaultEdge> comparTopoIter = new TopologicalOrderIterator<>(dag); while (comparTopoIter.hasNext()) { Long compareNext = comparTopoIter.next(); Long myNext = null; if (internalTopoIter.hasNext()) { myNext = internalTopoIter.next(); } assertSame(compareNext, myNext); assertEquals(comparTopoIter.hasNext(), internalTopoIter.hasNext()); } }
@Test public void testTopoIterationOrderComplexGraph() { for (int seed = 0; seed < 20; seed++) { DirectedAcyclicGraph<Long, DefaultEdge> dag = new DirectedAcyclicGraph<>(DefaultEdge.class); RepeatableRandomGraphGenerator<Long, DefaultEdge> graphGen = new RepeatableRandomGraphGenerator<>(100, 500, seed); graphGen.generateGraph(dag, new LongVertexFactory(), null); ConnectivityInspector<Long, DefaultEdge> connectivityInspector = new ConnectivityInspector<>(dag); Iterator<Long> internalTopoIter = dag.iterator(); List<Long> previousVertices = new ArrayList<>(); while (internalTopoIter.hasNext()) { Long vertex = internalTopoIter.next(); for (Long previousVertex : previousVertices) { connectivityInspector.pathExists(vertex, previousVertex); } previousVertices.add(vertex); } } } |
### Question:
DirectedAcyclicGraph extends SimpleDirectedGraph<V, E> implements Iterable<V> { @Override public E addEdge(V sourceVertex, V targetVertex) { assertVertexExist(sourceVertex); assertVertexExist(targetVertex); E result; try { updateDag(sourceVertex, targetVertex); result = super.addEdge(sourceVertex, targetVertex); } catch (CycleFoundException e) { throw new IllegalArgumentException(EDGE_WOULD_INDUCE_A_CYCLE); } return result; } DirectedAcyclicGraph(Class<? extends E> edgeClass); DirectedAcyclicGraph(Class<? extends E> edgeClass, boolean weighted); DirectedAcyclicGraph(EdgeFactory<V, E> ef); DirectedAcyclicGraph(EdgeFactory<V, E> ef, boolean weighted); protected DirectedAcyclicGraph(
EdgeFactory<V, E> ef, VisitedStrategyFactory visitedStrategyFactory,
TopoOrderMap<V> topoOrderMap, boolean weighted); static GraphBuilder<V, E, ? extends DirectedAcyclicGraph<V, E>> createBuilder(
Class<? extends E> edgeClass); static GraphBuilder<V, E, ? extends DirectedAcyclicGraph<V, E>> createBuilder(
EdgeFactory<V, E> ef); @Override GraphType getType(); @Override boolean addVertex(V v); @Override boolean removeVertex(V v); @Override E addEdge(V sourceVertex, V targetVertex); @Override boolean addEdge(V sourceVertex, V targetVertex, E e); Set<V> getAncestors(V vertex); Set<V> getDescendants(V vertex); Iterator<V> iterator(); }### Answer:
@Test public void testWhenVertexIsNotInGraph_Then_ThowException() { DirectedAcyclicGraph<Long, DefaultEdge> dag = new DirectedAcyclicGraph<>(DefaultEdge.class); try { dag.addEdge(1l, 2l); } catch (IllegalArgumentException e) { return; } fail("No exception 'IllegalArgumentException' catched"); } |
### Question:
GeneralizedPetersenGraphGenerator implements GraphGenerator<V, E, List<V>> { @Override public void generateGraph( Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, List<V>> resultMap) { List<V> verticesU = new ArrayList<>(n); List<V> verticesV = new ArrayList<>(n); for (int i = 0; i < n; i++) { verticesU.add(vertexFactory.createVertex()); verticesV.add(vertexFactory.createVertex()); } Graphs.addAllVertices(target, verticesU); Graphs.addAllVertices(target, verticesV); for (int i = 0; i < n; i++) { target.addEdge(verticesU.get(i), verticesU.get((i + 1) % n)); target.addEdge(verticesU.get(i), verticesV.get(i)); target.addEdge(verticesV.get(i), verticesV.get((i + k) % n)); } if (resultMap != null) { resultMap.put(REGULAR, verticesU); resultMap.put(STAR, verticesV); } } GeneralizedPetersenGraphGenerator(int n, int k); @Override void generateGraph(
Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, List<V>> resultMap); final String STAR; final String REGULAR; }### Answer:
@Test public void testCubicalGraph() { Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); GeneralizedPetersenGraphGenerator<Integer, DefaultEdge> gpgg = new GeneralizedPetersenGraphGenerator<>(4, 1); gpgg.generateGraph(g, new IntegerVertexFactory(), null); this.validateBasics(g, 8, 12, 3, 3, 4); assertTrue(GraphTests.isBipartite(g)); assertTrue(GraphTests.isCubic(g)); } |
### Question:
LinearizedChordDiagramGraphGenerator implements GraphGenerator<V, E, V> { @Override public void generateGraph( Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, V> resultMap) { List<V> nodes = new ArrayList<>(2 * n * m); for (int t = 0; t < n; t++) { V vt = vertexFactory.createVertex(); if (!target.addVertex(vt)) { throw new IllegalArgumentException("Invalid vertex factory"); } for (int j = 0; j < m; j++) { nodes.add(vt); V vs = nodes.get(rng.nextInt(nodes.size())); if (target.addEdge(vt, vs) == null) { throw new IllegalArgumentException("Graph does not permit parallel-edges."); } nodes.add(vs); } } } LinearizedChordDiagramGraphGenerator(int n, int m); LinearizedChordDiagramGraphGenerator(int n, int m, long seed); LinearizedChordDiagramGraphGenerator(int n, int m, Random rng); @Override void generateGraph(
Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, V> resultMap); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testMultiGraph() { final long seed = 5; GraphGenerator<Integer, DefaultEdge, Integer> gen = new LinearizedChordDiagramGraphGenerator<>(10, 2, seed); Graph<Integer, DefaultEdge> g = new Multigraph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); }
@Test(expected = IllegalArgumentException.class) public void testSimpleGraph() { final long seed = 5; GraphGenerator<Integer, DefaultEdge, Integer> gen = new LinearizedChordDiagramGraphGenerator<>(10, 2, seed); Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); }
@Test(expected = IllegalArgumentException.class) public void testDirectedMultiGraph() { final long seed = 5; GraphGenerator<Integer, DefaultEdge, Integer> gen = new LinearizedChordDiagramGraphGenerator<>(10, 2, seed); Graph<Integer, DefaultEdge> g = new DirectedMultigraph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); }
@Test(expected = IllegalArgumentException.class) public void testDirectedSimpleGraph() { final long seed = 5; GraphGenerator<Integer, DefaultEdge, Integer> gen = new LinearizedChordDiagramGraphGenerator<>(10, 2, seed); Graph<Integer, DefaultEdge> g = new SimpleDirectedGraph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); }
@Test public void testUndirected() { final long seed = 5; GraphGenerator<Integer, DefaultEdge, Integer> gen = new LinearizedChordDiagramGraphGenerator<>(20, 1, seed); Graph<Integer, DefaultEdge> g = new Pseudograph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); assertEquals(20, g.vertexSet().size()); }
@Test public void testUndirectedTwoEdges() { final long seed = 5; GraphGenerator<Integer, DefaultEdge, Integer> gen = new LinearizedChordDiagramGraphGenerator<>(20, 2, seed); Graph<Integer, DefaultEdge> g = new Pseudograph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); assertEquals(20, g.vertexSet().size()); }
@Test public void testDirected() { final long seed = 5; GraphGenerator<Integer, DefaultEdge, Integer> gen = new LinearizedChordDiagramGraphGenerator<>(20, 1, seed); Graph<Integer, DefaultEdge> g = new DirectedPseudograph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); assertEquals(20, g.vertexSet().size()); } |
### Question:
Graph6Sparse6Importer extends AbstractBaseImporter<V,E> implements GraphImporter<V,E> { @Override public void importGraph(Graph<V, E> g, Reader input) throws ImportException { BufferedReader in; if (input instanceof BufferedReader) { in = (BufferedReader) input; } else { in = new BufferedReader(input); } String g6=""; try { g6=in.readLine(); } catch (IOException e) { e.printStackTrace(); } if(g6.isEmpty()) throw new ImportException("Failed to read graph"); this.importGraph(g, g6); } Graph6Sparse6Importer(
VertexProvider<V> vertexProvider, EdgeProvider<V, E> edgeProvider, double defaultWeight); Graph6Sparse6Importer(VertexProvider<V> vertexProvider, EdgeProvider<V, E> edgeProvider); @Override void importGraph(Graph<V, E> g, Reader input); void importGraph(Graph<V, E> g, String g6); }### Answer:
@Test public void testFromFile() throws ImportException, IOException { InputStream fstream = getClass().getClassLoader().getResourceAsStream("ellinghamHorton78Graph.s6"); Graph<Integer, DefaultEdge> g= new Pseudograph<>(DefaultEdge.class); Graph6Sparse6Importer<Integer, DefaultEdge> importer = new Graph6Sparse6Importer<>( (l, a) -> Integer.parseInt(l), (f, t, l, a) -> g.getEdgeFactory().createEdge(f, t)); importer.importGraph(g, fstream); this.compare(NamedGraphGenerator.ellinghamHorton78Graph(), g); } |
### Question:
BarabasiAlbertGraphGenerator implements GraphGenerator<V, E, V> { @Override public void generateGraph( Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, V> resultMap) { Set<V> oldNodes = new HashSet<>(target.vertexSet()); Set<V> newNodes = new HashSet<>(); new CompleteGraphGenerator<V, E>(m0).generateGraph(target, vertexFactory, resultMap); target.vertexSet().stream().filter(v -> !oldNodes.contains(v)).forEach(newNodes::add); List<V> nodes = new ArrayList<>(n * m); nodes.addAll(newNodes); for (int i = 0; i < m0 - 2; i++) { nodes.addAll(newNodes); } for (int i = m0; i < n; i++) { V v = vertexFactory.createVertex(); if (!target.addVertex(v)) { throw new IllegalArgumentException("Invalid vertex factory"); } List<V> newEndpoints = new ArrayList<>(); int added = 0; while (added < m) { V u = nodes.get(rng.nextInt(nodes.size())); if (!target.containsEdge(v, u)) { target.addEdge(v, u); added++; newEndpoints.add(v); if (i > 1) { newEndpoints.add(u); } } } nodes.addAll(newEndpoints); } } BarabasiAlbertGraphGenerator(int m0, int m, int n); BarabasiAlbertGraphGenerator(int m0, int m, int n, long seed); BarabasiAlbertGraphGenerator(int m0, int m, int n, Random rng); @Override void generateGraph(
Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, V> resultMap); }### Answer:
@Test public void testUndirected() { final long seed = 5; GraphGenerator<Integer, DefaultEdge, Integer> gen = new BarabasiAlbertGraphGenerator<>(3, 2, 10, seed); Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); assertEquals(10, g.vertexSet().size()); }
@Test public void testUndirectedWithOneInitialNode() { final long seed = 7; GraphGenerator<Integer, DefaultEdge, Integer> gen = new BarabasiAlbertGraphGenerator<>(1, 1, 20, seed); Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); assertEquals(20, g.vertexSet().size()); }
@Test public void testDirected() { final long seed = 5; GraphGenerator<Integer, DefaultEdge, Integer> gen = new BarabasiAlbertGraphGenerator<>(3, 2, 10, seed); Graph<Integer, DefaultEdge> g = new SimpleDirectedGraph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); assertEquals(10, g.vertexSet().size()); }
@Test public void testDirectedWithOneInitialNode() { final long seed = 13; GraphGenerator<Integer, DefaultEdge, Integer> gen = new BarabasiAlbertGraphGenerator<>(1, 1, 20, seed); Graph<Integer, DefaultEdge> g = new SimpleDirectedGraph<>(DefaultEdge.class); gen.generateGraph(g, new IntegerVertexFactory(), null); assertEquals(20, g.vertexSet().size()); }
@Test public void testUndirectedWithGraphWhichAlreadyHasSomeVertices() { final long seed = 5; GraphGenerator<Integer, DefaultEdge, Integer> gen = new BarabasiAlbertGraphGenerator<>(3, 2, 10, seed); Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); g.addVertex(1000); gen.generateGraph(g, new IntegerVertexFactory(), null); assertEquals(11, g.vertexSet().size()); } |
### Question:
Graphs { public static <V, E> void addOutgoingEdges(Graph<V, E> graph, V source, Iterable<V> targets) { if (!graph.containsVertex(source)) { graph.addVertex(source); } for (V target : targets) { if (!graph.containsVertex(target)) { graph.addVertex(target); } graph.addEdge(source, target); } } static E addEdge(Graph<V, E> g, V sourceVertex, V targetVertex, double weight); static E addEdgeWithVertices(Graph<V, E> g, V sourceVertex, V targetVertex); static boolean addEdgeWithVertices(Graph<V, E> targetGraph, Graph<V, E> sourceGraph, E edge); static E addEdgeWithVertices(Graph<V, E> g, V sourceVertex, V targetVertex, double weight); static boolean addGraph(Graph<? super V, ? super E> destination, Graph<V, E> source); static void addGraphReversed(Graph<? super V, ? super E> destination, Graph<V, E> source); static boolean addAllEdges(
Graph<? super V, ? super E> destination, Graph<V, E> source, Collection<? extends E> edges); static boolean addAllVertices(
Graph<? super V, ? super E> destination, Collection<? extends V> vertices); static List<V> neighborListOf(Graph<V, E> g, V vertex); static List<V> predecessorListOf(Graph<V, E> g, V vertex); static List<V> successorListOf(Graph<V, E> g, V vertex); static Graph<V, E> undirectedGraph(Graph<V, E> g); static boolean testIncidence(Graph<V, E> g, E e, V v); static V getOppositeVertex(Graph<V, E> g, E e, V v); static boolean removeVertexAndPreserveConnectivity(Graph<V, E> graph, V vertex); static boolean removeVerticesAndPreserveConnectivity(Graph<V, E> graph, Predicate<V> predicate); static boolean removeVertexAndPreserveConnectivity(Graph<V, E> graph, Iterable<V> vertices); static void addOutgoingEdges(Graph<V, E> graph, V source, Iterable<V> targets); static void addIncomingEdges(Graph<V, E> graph, V target, Iterable<V> sources); static boolean vertexHasSuccessors(Graph<V, E> graph, V vertex); static boolean vertexHasPredecessors(Graph<V, E> graph, V vertex); }### Answer:
@Test public void addOutgoingEdges() { DefaultDirectedGraph<String, TestEdge> graph = new DefaultDirectedGraph<String, TestEdge>(TestEdge.class); String a = "A"; String b = "B"; String c = "C"; graph.addVertex(b); Graph<String, TestEdge> expectedGraph = new DefaultDirectedGraph<String, TestEdge>(TestEdge.class); expectedGraph.addVertex(a); expectedGraph.addVertex(b); expectedGraph.addVertex(c); expectedGraph.addEdge(a, b); expectedGraph.addEdge(a, c); List<String> targets = new ArrayList<String>(); targets.add(b); targets.add(c); Graphs.addOutgoingEdges(graph, a, targets); Assert.assertEquals(expectedGraph, graph); } |
### Question:
ComplementGraphGenerator implements GraphGenerator<V, E, V> { public void generateGraph(Graph<V, E> target) { this.generateGraph(target, null, null); } ComplementGraphGenerator(Graph<V, E> graph); ComplementGraphGenerator(Graph<V, E> graph, boolean generateSelfLoops); void generateGraph(Graph<V, E> target); @Override void generateGraph(
Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, V> resultMap); }### Answer:
@Test public void testEmptyGraph() { Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); Graphs.addAllVertices(g, Arrays.asList(0, 1, 2, 3)); ComplementGraphGenerator<Integer, DefaultEdge> cgg = new ComplementGraphGenerator<>(g); Graph<Integer, DefaultEdge> target = new SimpleWeightedGraph<>(DefaultEdge.class); cgg.generateGraph(target); assertTrue(GraphTests.isComplete(target)); ComplementGraphGenerator<Integer, DefaultEdge> cgg2 = new ComplementGraphGenerator<>(target); Graph<Integer, DefaultEdge> target2 = new SimpleWeightedGraph<>(DefaultEdge.class); cgg2.generateGraph(target2); assertTrue(target2.edgeSet().isEmpty()); assertTrue(target2.vertexSet().equals(g.vertexSet())); }
@Test public void testUndirectedGraph() { Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); Graphs.addAllVertices(g, Arrays.asList(0, 1, 2, 3)); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(0, 2); ComplementGraphGenerator<Integer, DefaultEdge> cgg = new ComplementGraphGenerator<>(g); Graph<Integer, DefaultEdge> target = new SimpleWeightedGraph<>(DefaultEdge.class); cgg.generateGraph(target); assertTrue(target.vertexSet().equals(new HashSet<>(Arrays.asList(0, 1, 2, 3)))); assertEquals(3, target.edgeSet().size()); assertTrue(target.containsEdge(0, 3)); assertTrue(target.containsEdge(2, 3)); assertTrue(target.containsEdge(1, 3)); }
@Test public void testDirectedGraph() { Graph<Integer, DefaultEdge> g = new SimpleDirectedGraph<>(DefaultEdge.class); Graphs.addAllVertices(g, Arrays.asList(0, 1, 2)); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(0, 2); ComplementGraphGenerator<Integer, DefaultEdge> cgg = new ComplementGraphGenerator<>(g); Graph<Integer, DefaultEdge> target = new SimpleWeightedGraph<>(DefaultEdge.class); cgg.generateGraph(target); assertTrue(target.vertexSet().equals(new HashSet<>(Arrays.asList(0, 1, 2)))); assertEquals(3, target.edgeSet().size()); assertTrue(target.containsEdge(1, 0)); assertTrue(target.containsEdge(2, 1)); assertTrue(target.containsEdge(2, 0)); }
@Test public void testGraphWithSelfLoops() { Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); Graphs.addAllVertices(g, Arrays.asList(0, 1, 2)); g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(0, 2); ComplementGraphGenerator<Integer, DefaultEdge> cgg = new ComplementGraphGenerator<>(g, true); Graph<Integer, DefaultEdge> target = new Pseudograph<>(DefaultEdge.class); cgg.generateGraph(target); assertTrue(target.vertexSet().equals(new HashSet<>(Arrays.asList(0, 1, 2)))); assertEquals(3, target.edgeSet().size()); for (Integer v : target.vertexSet()) assertTrue(target.containsEdge(v, v)); } |
### Question:
Graphs { public static <V, E> void addIncomingEdges(Graph<V, E> graph, V target, Iterable<V> sources) { if (!graph.containsVertex(target)) { graph.addVertex(target); } for (V source : sources) { if (!graph.containsVertex(source)) { graph.addVertex(source); } graph.addEdge(source, target); } } static E addEdge(Graph<V, E> g, V sourceVertex, V targetVertex, double weight); static E addEdgeWithVertices(Graph<V, E> g, V sourceVertex, V targetVertex); static boolean addEdgeWithVertices(Graph<V, E> targetGraph, Graph<V, E> sourceGraph, E edge); static E addEdgeWithVertices(Graph<V, E> g, V sourceVertex, V targetVertex, double weight); static boolean addGraph(Graph<? super V, ? super E> destination, Graph<V, E> source); static void addGraphReversed(Graph<? super V, ? super E> destination, Graph<V, E> source); static boolean addAllEdges(
Graph<? super V, ? super E> destination, Graph<V, E> source, Collection<? extends E> edges); static boolean addAllVertices(
Graph<? super V, ? super E> destination, Collection<? extends V> vertices); static List<V> neighborListOf(Graph<V, E> g, V vertex); static List<V> predecessorListOf(Graph<V, E> g, V vertex); static List<V> successorListOf(Graph<V, E> g, V vertex); static Graph<V, E> undirectedGraph(Graph<V, E> g); static boolean testIncidence(Graph<V, E> g, E e, V v); static V getOppositeVertex(Graph<V, E> g, E e, V v); static boolean removeVertexAndPreserveConnectivity(Graph<V, E> graph, V vertex); static boolean removeVerticesAndPreserveConnectivity(Graph<V, E> graph, Predicate<V> predicate); static boolean removeVertexAndPreserveConnectivity(Graph<V, E> graph, Iterable<V> vertices); static void addOutgoingEdges(Graph<V, E> graph, V source, Iterable<V> targets); static void addIncomingEdges(Graph<V, E> graph, V target, Iterable<V> sources); static boolean vertexHasSuccessors(Graph<V, E> graph, V vertex); static boolean vertexHasPredecessors(Graph<V, E> graph, V vertex); }### Answer:
@Test public void addIncomingEdges() { DefaultDirectedGraph<String, TestEdge> graph = new DefaultDirectedGraph<String, TestEdge>(TestEdge.class); String a = "A"; String b = "B"; String c = "C"; graph.addVertex(b); Graph<String, TestEdge> expectedGraph = new DefaultDirectedGraph<String, TestEdge>(TestEdge.class); expectedGraph.addVertex(a); expectedGraph.addVertex(b); expectedGraph.addVertex(c); expectedGraph.addEdge(b, a); expectedGraph.addEdge(c, a); List<String> targets = new ArrayList<String>(); targets.add(b); targets.add(c); Graphs.addIncomingEdges(graph, a, targets); Assert.assertEquals(expectedGraph, graph); } |
### Question:
GraphMLImporter extends AbstractBaseImporter<V, E> implements GraphImporter<V, E> { @Override public void importGraph(Graph<V, E> graph, Reader input) throws ImportException { try { XMLReader xmlReader = createXMLReader(); GraphMLHandler handler = new GraphMLHandler(); xmlReader.setContentHandler(handler); xmlReader.setErrorHandler(handler); xmlReader.parse(new InputSource(input)); handler.updateGraph(graph); } catch (Exception se) { throw new ImportException("Failed to parse GraphML", se); } } GraphMLImporter(VertexProvider<V> vertexProvider, EdgeProvider<V, E> edgeProvider); String getEdgeWeightAttributeName(); void setEdgeWeightAttributeName(String edgeWeightAttributeName); boolean isSchemaValidation(); void setSchemaValidation(boolean schemaValidation); @Override void importGraph(Graph<V, E> graph, Reader input); }### Answer:
@Test public void testUnsupportedGraph() throws ImportException { String input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NL + "<graphml xmlns=\"http: "xmlns:xsi=\"http: "xsi:schemaLocation=\"http: "http: "<graph id=\"G\" edgedefault=\"undirected\">" + NL + "<node id=\"1\"/>" + NL + "<node id=\"2\"/>" + NL + "<node id=\"3\"/>" + NL + "<edge source=\"1\" target=\"2\"/>" + NL + "<edge source=\"2\" target=\"3\"/>" + NL + "<edge source=\"3\" target=\"1\"/>"+ NL + "<edge source=\"3\" target=\"1\"/>"+ NL + "<edge source=\"1\" target=\"1\"/>"+ NL + "</graph>" + NL + "</graphml>"; final Graph<String, DefaultEdge> g = new SimpleGraph<String, DefaultEdge>(DefaultEdge.class); try { GraphMLImporter<String, DefaultEdge> importer = new GraphMLImporter<>( (label, attributes) -> label, (from, to, label, attributes) -> g.getEdgeFactory().createEdge(from, to)); importer.importGraph(g, new StringReader(input)); fail("No!"); } catch (Exception e) { } } |
### Question:
GraphMetrics { public static <V, E> double getDiameter(Graph<V, E> graph) { return new GraphMeasurer<>(graph).getDiameter(); } static double getDiameter(Graph<V, E> graph); static double getRadius(Graph<V, E> graph); static int getGirth(Graph<V, E> graph); }### Answer:
@Test public void testGraphDiameter() { Graph<Integer, DefaultWeightedEdge> g = new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class); Graphs.addEdgeWithVertices(g, 0, 1, 10); Graphs.addEdgeWithVertices(g, 1, 0, 12); double diameter = GraphMetrics.getDiameter(g); assertEquals(12.0, diameter, EPSILON); } |
### Question:
GraphMetrics { public static <V, E> double getRadius(Graph<V, E> graph) { return new GraphMeasurer<>(graph).getRadius(); } static double getDiameter(Graph<V, E> graph); static double getRadius(Graph<V, E> graph); static int getGirth(Graph<V, E> graph); }### Answer:
@Test public void testGraphRadius() { Graph<Integer, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); double radius = GraphMetrics.getRadius(g); assertEquals(0.0, radius, EPSILON); } |
### Question:
Graphs { public static <V, E> E addEdgeWithVertices(Graph<V, E> g, V sourceVertex, V targetVertex) { g.addVertex(sourceVertex); g.addVertex(targetVertex); return g.addEdge(sourceVertex, targetVertex); } static E addEdge(Graph<V, E> g, V sourceVertex, V targetVertex, double weight); static E addEdgeWithVertices(Graph<V, E> g, V sourceVertex, V targetVertex); static boolean addEdgeWithVertices(Graph<V, E> targetGraph, Graph<V, E> sourceGraph, E edge); static E addEdgeWithVertices(Graph<V, E> g, V sourceVertex, V targetVertex, double weight); static boolean addGraph(Graph<? super V, ? super E> destination, Graph<V, E> source); static void addGraphReversed(Graph<? super V, ? super E> destination, Graph<V, E> source); static boolean addAllEdges(
Graph<? super V, ? super E> destination, Graph<V, E> source, Collection<? extends E> edges); static boolean addAllVertices(
Graph<? super V, ? super E> destination, Collection<? extends V> vertices); static List<V> neighborListOf(Graph<V, E> g, V vertex); static List<V> predecessorListOf(Graph<V, E> g, V vertex); static List<V> successorListOf(Graph<V, E> g, V vertex); static Graph<V, E> undirectedGraph(Graph<V, E> g); static boolean testIncidence(Graph<V, E> g, E e, V v); static V getOppositeVertex(Graph<V, E> g, E e, V v); static boolean removeVertexAndPreserveConnectivity(Graph<V, E> graph, V vertex); static boolean removeVerticesAndPreserveConnectivity(Graph<V, E> graph, Predicate<V> predicate); static boolean removeVertexAndPreserveConnectivity(Graph<V, E> graph, Iterable<V> vertices); static void addOutgoingEdges(Graph<V, E> graph, V source, Iterable<V> targets); static void addIncomingEdges(Graph<V, E> graph, V target, Iterable<V> sources); static boolean vertexHasSuccessors(Graph<V, E> graph, V vertex); static boolean vertexHasPredecessors(Graph<V, E> graph, V vertex); }### Answer:
@Test public void testIsCubic() { assertTrue(GraphTests.isCubic(NamedGraphGenerator.petersenGraph())); Graph<Integer, DefaultEdge> triangle = new SimpleGraph<>(DefaultEdge.class); Graphs.addEdgeWithVertices(triangle, 1, 2); Graphs.addEdgeWithVertices(triangle, 2, 3); Graphs.addEdgeWithVertices(triangle, 3, 1); assertFalse(GraphTests.isCubic(triangle)); } |
### Question:
TopologicalOrderIterator extends AbstractGraphIterator<V, E> { @Override public boolean hasNext() { if (cur != null) { return true; } cur = advance(); if (cur != null && nListeners != 0) { fireVertexTraversed(createVertexTraversalEvent(cur)); } return cur != null; } TopologicalOrderIterator(Graph<V, E> graph); @Deprecated TopologicalOrderIterator(Graph<V, E> graph, Queue<V> queue); TopologicalOrderIterator(Graph<V, E> graph, Comparator<V> comparator); @Override boolean isCrossComponentTraversal(); @Override void setCrossComponentTraversal(boolean crossComponentTraversal); @Override boolean hasNext(); @Override V next(); }### Answer:
@Test public void testEmptyGraph() { Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class); Iterator<String> iter = new TopologicalOrderIterator<>(graph); assertFalse(iter.hasNext()); } |
### Question:
TopologicalOrderIterator extends AbstractGraphIterator<V, E> { @Override public void setCrossComponentTraversal(boolean crossComponentTraversal) { if (!crossComponentTraversal) { throw new IllegalArgumentException("Iterator is always cross-component"); } } TopologicalOrderIterator(Graph<V, E> graph); @Deprecated TopologicalOrderIterator(Graph<V, E> graph, Queue<V> queue); TopologicalOrderIterator(Graph<V, E> graph, Comparator<V> comparator); @Override boolean isCrossComponentTraversal(); @Override void setCrossComponentTraversal(boolean crossComponentTraversal); @Override boolean hasNext(); @Override V next(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testTryToDisableCrossComponent() { Graph<Integer, DefaultEdge> graph = new DirectedPseudograph<>(DefaultEdge.class); new TopologicalOrderIterator<>(graph).setCrossComponentTraversal(false); } |
### Question:
BaseBronKerboschCliqueFinder implements MaximalCliqueEnumerationAlgorithm<V, E> { public Iterator<Set<V>> maximumIterator() { lazyRun(); return allMaximalCliques.stream().filter(c -> c.size() == maxSize).iterator(); } BaseBronKerboschCliqueFinder(Graph<V, E> graph, long timeout, TimeUnit unit); @Override Iterator<Set<V>> iterator(); Iterator<Set<V>> maximumIterator(); boolean isTimeLimitReached(); }### Answer:
@Test public void testFindBiggest() { SimpleGraph<String, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); createGraph(g); BaseBronKerboschCliqueFinder<String, DefaultEdge> finder = createFinder1(g); Collection<Set<String>> cliques = new HashSet<>(); finder.maximumIterator().forEachRemaining(cliques::add); assertEquals(2, cliques.size()); Set<Set<String>> expected = new HashSet<>(); Set<String> set = new HashSet<>(); set.add(V1); set.add(V2); set.add(V3); set.add(V4); expected.add(set); set = new HashSet<>(); set.add(V1); set.add(V2); set.add(V9); set.add(V10); expected.add(set); Set<Set<String>> actual = new HashSet<>(cliques); assertEquals(expected, actual); } |
### Question:
BaseBronKerboschCliqueFinder implements MaximalCliqueEnumerationAlgorithm<V, E> { @Override public Iterator<Set<V>> iterator() { lazyRun(); return allMaximalCliques.iterator(); } BaseBronKerboschCliqueFinder(Graph<V, E> graph, long timeout, TimeUnit unit); @Override Iterator<Set<V>> iterator(); Iterator<Set<V>> maximumIterator(); boolean isTimeLimitReached(); }### Answer:
@Test public void testFindAll() { SimpleGraph<String, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); createGraph(g); MaximalCliqueEnumerationAlgorithm<String, DefaultEdge> finder = createFinder1(g); Collection<Set<String>> cliques = new HashSet<>(); finder.iterator().forEachRemaining(cliques::add); assertEquals(5, cliques.size()); Set<Set<String>> expected = new HashSet<>(); Set<String> set = new HashSet<>(); set.add(V1); set.add(V2); set.add(V3); set.add(V4); expected.add(set); set = new HashSet<>(); set.add(V5); set.add(V6); set.add(V7); expected.add(set); set = new HashSet<>(); set.add(V3); set.add(V4); set.add(V5); expected.add(set); set = new HashSet<>(); set.add(V7); set.add(V8); expected.add(set); set = new HashSet<>(); set.add(V1); set.add(V2); set.add(V9); set.add(V10); expected.add(set); Set<Set<String>> actual = new HashSet<>(cliques); assertEquals(expected, actual); }
@Test(expected = IllegalArgumentException.class) public void testNonSimple() { Graph<String, DefaultEdge> g = new Pseudograph<>(DefaultEdge.class); g.addVertex("1"); g.addVertex("2"); g.addEdge("1", "2"); g.addEdge("1", "2"); MaximalCliqueEnumerationAlgorithm<String, DefaultEdge> finder = createFinder1(g); Iterator<Set<String>> it = finder.iterator(); while (it.hasNext()) { it.next(); } }
@Test public void testComplete() { final int size = 6; Graph<Object, DefaultEdge> g = new SimpleGraph<>(DefaultEdge.class); CompleteGraphGenerator<Object, DefaultEdge> completeGraphGenerator = new CompleteGraphGenerator<>(size); completeGraphGenerator.generateGraph(g, new ClassBasedVertexFactory<>(Object.class), null); MaximalCliqueEnumerationAlgorithm<Object, DefaultEdge> finder = createFinder2(g); Set<Set<Object>> cliques = new HashSet<>(); finder.iterator().forEachRemaining(cliques::add); assertEquals(1, cliques.size()); cliques.stream().forEach(clique -> assertEquals(size, clique.size())); } |
### Question:
Pair implements Serializable { public Pair(A a, B b) { this.first = a; this.second = b; } Pair(A a, B b); A getFirst(); B getSecond(); boolean hasElement(E e); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Pair<A, B> of(A a, B b); }### Answer:
@Test public void testPair() { Pair<String, Custom> p = Pair.of(CUSTOM, new Custom(1)); assertEquals(CUSTOM, p.getFirst()); assertNotEquals(ANOTHER, p.getFirst()); assertEquals(new Custom(1), p.getSecond()); assertNotEquals(new Custom(2), p.getSecond()); assertTrue(p.hasElement(CUSTOM)); assertFalse(p.hasElement(ANOTHER)); assertTrue(p.hasElement(new Custom(1))); assertFalse(p.hasElement(new Custom(2))); assertFalse(p.hasElement(null)); } |
### Question:
AliasMethodSampler { public int next() { double u = rng.nextDouble() * prob.length; int j = (int) Math.floor(u); if (comparator.compare(u - j, prob[j]) <= 0) { return j; } else { return alias[j]; } } AliasMethodSampler(double[] p); AliasMethodSampler(double[] p, long seed); AliasMethodSampler(double[] p, Random rng); AliasMethodSampler(double[] p, Random rng, double epsilon); int next(); }### Answer:
@Test public void test1() { final long seed = 5; double[] prob = { 0.1, 0.2, 0.3, 0.4 }; AliasMethodSampler am = new AliasMethodSampler(prob, new Random(seed)); int[] counts = new int[4]; for (int i = 0; i < 1000000; i++) { counts[am.next()]++; } assertEquals(100033, counts[0]); assertEquals(200069, counts[1]); assertEquals(299535, counts[2]); assertEquals(400363, counts[3]); }
@Test public void test2() { final long seed = 17; double[] prob = { 0.05, 0.05, 0.05, 0.05, 0.8 }; AliasMethodSampler am = new AliasMethodSampler(prob, new Random(seed)); int[] counts = new int[5]; for (int i = 0; i < 1000000; i++) { counts[am.next()]++; } assertEquals(49949, counts[0]); assertEquals(49726, counts[1]); assertEquals(50441, counts[2]); assertEquals(49894, counts[3]); assertEquals(799990, counts[4]); } |
### Question:
NeighborCache implements GraphListener<V, E> { public Set<V> neighborsOf(V v) { return fetch(v, neighbors, k -> new Neighbors<>(Graphs.neighborListOf(graph, v))); } NeighborCache(Graph<V, E> graph); Set<V> predecessorsOf(V v); Set<V> successorsOf(V v); Set<V> neighborsOf(V v); List<V> neighborListOf(V v); @Override void edgeAdded(GraphEdgeChangeEvent<V, E> e); @Override void edgeRemoved(GraphEdgeChangeEvent<V, E> e); @Override void vertexAdded(GraphVertexChangeEvent<V> e); @Override void vertexRemoved(GraphVertexChangeEvent<V> e); }### Answer:
@Test public void testNeighborSet() { ListenableGraph<String, Object> g = new DefaultListenableGraph<>(new SimpleGraph<>(Object.class)); NeighborCache<String, Object> cache = new NeighborCache<>(g); g.addGraphListener(cache); g.addVertex(V1); g.addVertex(V2); g.addEdge(V1, V2); Set<String> neighbors1 = cache.neighborsOf(V1); assertEquals(1, neighbors1.size()); assertEquals(true, neighbors1.contains(V2)); g.addVertex(V3); g.addEdge(V3, V1); Set<String> neighbors3 = cache.neighborsOf(V3); assertEquals(2, neighbors1.size()); assertEquals(true, neighbors1.contains(V3)); assertEquals(1, neighbors3.size()); assertEquals(true, neighbors3.contains(V1)); g.removeEdge(V3, V1); assertEquals(1, neighbors1.size()); assertEquals(false, neighbors1.contains(V3)); assertEquals(0, neighbors3.size()); g.removeVertex(V2); assertEquals(0, neighbors1.size()); }
@Test public void testVertexRemoval() { ListenableGraph<String, DefaultEdge> graph = new DefaultListenableGraph<>(new SimpleGraph<>(DefaultEdge.class)); final String A = "A"; final String B = "B"; final String C = "C"; final String D = "D"; NeighborCache<String, DefaultEdge> cache = new NeighborCache<>(graph); graph.addGraphListener(cache); graph.addVertex(A); graph.addVertex(B); graph.addVertex(C); graph.addVertex(D); graph.addEdge(D, A); graph.addEdge(D, B); graph.addEdge(D, C); Set<String> neighborsOfD = cache.neighborsOf(D); Set<String> neighborsOfC = cache.neighborsOf(C); Set<String> neighborsOfB = cache.neighborsOf(B); Set<String> neighborsOfA = cache.neighborsOf(A); assertThat(neighborsOfD, hasItems(A, B, C)); assertThat(neighborsOfA.size(), is(1)); assertThat(neighborsOfB.size(), is(1)); assertThat(neighborsOfC.size(), is(1)); graph.removeVertex(D); assertTrue(neighborsOfD.isEmpty()); assertThat(neighborsOfA.size(), is(0)); assertThat(neighborsOfB.size(), is(0)); assertThat(neighborsOfC.size(), is(0)); } |
### Question:
NeighborCache implements GraphListener<V, E> { public List<V> neighborListOf(V v) { Neighbors<V> nbrs = neighbors.get(v); if (nbrs == null) { nbrs = new Neighbors<>(Graphs.neighborListOf(graph, v)); neighbors.put(v, nbrs); } return nbrs.getNeighborList(); } NeighborCache(Graph<V, E> graph); Set<V> predecessorsOf(V v); Set<V> successorsOf(V v); Set<V> neighborsOf(V v); List<V> neighborListOf(V v); @Override void edgeAdded(GraphEdgeChangeEvent<V, E> e); @Override void edgeRemoved(GraphEdgeChangeEvent<V, E> e); @Override void vertexAdded(GraphVertexChangeEvent<V> e); @Override void vertexRemoved(GraphVertexChangeEvent<V> e); }### Answer:
@Test public void testNeighborListCreation() { ListenableGraph<String, DefaultEdge> graph = new DefaultListenableGraph<>(new SimpleGraph<>(DefaultEdge.class)); final String A = "A"; final String B = "B"; final String C = "C"; final String D = "D"; NeighborCache<String, DefaultEdge> cache = new NeighborCache<>(graph); graph.addGraphListener(cache); graph.addVertex(A); graph.addVertex(B); graph.addVertex(C); graph.addVertex(D); graph.addEdge(D, A); graph.addEdge(D, B); graph.addEdge(D, C); assertThat(cache.neighborListOf(B), hasItems(D)); assertThat(cache.neighborListOf(B).size(), is(1)); graph.addEdge(A, B); assertThat(cache.neighborListOf(B), hasItems(A, D)); assertThat(cache.neighborListOf(B).size(), is(2)); graph.removeEdge(D, B); assertThat(cache.neighborListOf(B), hasItems(A)); assertThat(cache.neighborListOf(B).size(), is(1)); graph.removeVertex(B); exception.expect(IllegalArgumentException.class); exception.expectMessage("no such vertex"); cache.neighborListOf(B); } |
### Question:
TarjanLowestCommonAncestor { public V calculate(V start, V a, V b) { List<LcaRequestResponse<V>> list = new LinkedList<>(); list.add(new LcaRequestResponse<>(a, b)); return calculate(start, list).get(0); } TarjanLowestCommonAncestor(Graph<V, E> g); V calculate(V start, V a, V b); List<V> calculate(V start, List<LcaRequestResponse<V>> lrr); }### Answer:
@Test public void testBinaryTree() { Graph<String, DefaultEdge> g = new DefaultDirectedGraph<>(DefaultEdge.class); g.addVertex("a"); g.addVertex("b"); g.addVertex("c"); g.addVertex("d"); g.addVertex("e"); g.addEdge("a", "b"); g.addEdge("b", "c"); g.addEdge("b", "d"); g.addEdge("d", "e"); Assert.assertEquals("b", new TarjanLowestCommonAncestor<>(g).calculate("a", "c", "e")); Assert.assertEquals("b", new TarjanLowestCommonAncestor<>(g).calculate("a", "b", "d")); Assert.assertEquals("d", new TarjanLowestCommonAncestor<>(g).calculate("a", "d", "e")); }
@Test public void testNonBinaryTree() { Graph<String, DefaultEdge> g = new DefaultDirectedGraph<>(DefaultEdge.class); g.addVertex("a"); g.addVertex("b"); g.addVertex("c"); g.addVertex("d"); g.addVertex("e"); g.addVertex("f"); g.addVertex("g"); g.addVertex("h"); g.addVertex("i"); g.addVertex("j"); g.addEdge("a", "b"); g.addEdge("b", "c"); g.addEdge("c", "d"); g.addEdge("d", "e"); g.addEdge("b", "f"); g.addEdge("b", "g"); g.addEdge("c", "h"); g.addEdge("c", "i"); g.addEdge("i", "j"); Assert.assertEquals("b", new TarjanLowestCommonAncestor<>(g).calculate("a", "b", "h")); Assert.assertEquals("b", new TarjanLowestCommonAncestor<>(g).calculate("a", "j", "f")); Assert.assertEquals("c", new TarjanLowestCommonAncestor<>(g).calculate("a", "j", "h")); LcaRequestResponse<String> bg = new LcaRequestResponse<>("b", "h"); LcaRequestResponse<String> ed = new LcaRequestResponse<>("j", "f"); LcaRequestResponse<String> fd = new LcaRequestResponse<>("j", "h"); List<LcaRequestResponse<String>> list = new LinkedList<>(); list.add(bg); list.add(ed); list.add(fd); List<String> result = new TarjanLowestCommonAncestor<>(g).calculate("a", list); Assert.assertEquals("b", bg.getLca()); Assert.assertEquals("b", ed.getLca()); Assert.assertEquals("c", fd.getLca()); Assert.assertEquals(Arrays.asList(new String[] { "b", "b", "c" }), result); Assert.assertEquals("b", new TarjanLowestCommonAncestor<>(g).calculate("b", "h", "b")); }
@Test public void testOneNode() { Graph<String, DefaultEdge> g = new DefaultDirectedGraph<>(DefaultEdge.class); g.addVertex("a"); Assert.assertEquals("a", new TarjanLowestCommonAncestor<>(g).calculate("a", "a", "a")); } |
### Question:
KuhnMunkresMinimalWeightBipartitePerfectMatching implements MatchingAlgorithm<V, E> { @Override public Matching<V, E> getMatching() { if (partition1.size() != partition2.size()) { throw new IllegalArgumentException( "Graph supplied isn't complete bipartite with equally sized partitions!"); } if (!GraphTests.isBipartitePartition(graph, partition1, partition2)) { throw new IllegalArgumentException("Invalid bipartite partition provided"); } int partition = partition1.size(); int edges = graph.edgeSet().size(); if (edges != (partition * partition)) { throw new IllegalArgumentException( "Graph supplied isn't complete bipartite with equally sized partitions!"); } if (!GraphTests.isSimple(graph)) { throw new IllegalArgumentException("Only simple graphs supported"); } List<? extends V> firstPartition = new ArrayList<>(partition1); List<? extends V> secondPartition = new ArrayList<>(partition2); int[] matching; if (graph.vertexSet().isEmpty()) { matching = new int[] {}; } else { matching = new KuhnMunkresMatrixImplementation<>(graph, firstPartition, secondPartition) .buildMatching(); } Set<E> edgeSet = new HashSet<>(); double weight = 0d; for (int i = 0; i < matching.length; ++i) { E e = graph.getEdge(firstPartition.get(i), secondPartition.get(matching[i])); weight += graph.getEdgeWeight(e); edgeSet.add(e); } return new MatchingImpl<>(graph, edgeSet, weight); } KuhnMunkresMinimalWeightBipartitePerfectMatching(
Graph<V, E> graph, Set<? extends V> partition1, Set<? extends V> partition2); @Override Matching<V, E> getMatching(); }### Answer:
@Test public void testForEmptyGraph() { Graph<V, WeightedEdge> graph = new SimpleWeightedGraph<>(WeightedEdge.class); Set<? extends V> emptyList = Collections.emptySet(); MatchingAlgorithm<V, WeightedEdge> alg = new KuhnMunkresMinimalWeightBipartitePerfectMatching<>(graph, emptyList, emptyList); Assert.assertTrue(alg.getMatching().getEdges().isEmpty()); } |
### Question:
VF2GraphIsomorphismInspector extends VF2AbstractIsomorphismInspector<V, E> { @Override public VF2GraphMappingIterator<V, E> getMappings() { return new VF2GraphMappingIterator<>( ordering1, ordering2, vertexComparator, edgeComparator); } VF2GraphIsomorphismInspector(
Graph<V, E> graph1, Graph<V, E> graph2, Comparator<V> vertexComparator,
Comparator<E> edgeComparator, boolean cacheEdges); VF2GraphIsomorphismInspector(
Graph<V, E> graph1, Graph<V, E> graph2, Comparator<V> vertexComparator,
Comparator<E> edgeComparator); VF2GraphIsomorphismInspector(Graph<V, E> graph1, Graph<V, E> graph2, boolean cacheEdges); VF2GraphIsomorphismInspector(Graph<V, E> graph1, Graph<V, E> graph2); @Override VF2GraphMappingIterator<V, E> getMappings(); }### Answer:
@Test public void testAutomorphism() { SimpleGraph<String, DefaultEdge> g1 = new SimpleGraph<>(DefaultEdge.class); String v1 = "v1", v2 = "v2", v3 = "v3"; g1.addVertex(v1); g1.addVertex(v2); g1.addVertex(v3); g1.addEdge(v1, v2); g1.addEdge(v2, v3); g1.addEdge(v3, v1); VF2GraphIsomorphismInspector<String, DefaultEdge> vf2 = new VF2GraphIsomorphismInspector<>(g1, g1); Iterator<GraphMapping<String, DefaultEdge>> iter = vf2.getMappings(); Set<String> mappings = new HashSet<>( Arrays.asList( "[v1=v1 v2=v2 v3=v3]", "[v1=v1 v2=v3 v3=v2]", "[v1=v2 v2=v1 v3=v3]", "[v1=v2 v2=v3 v3=v1]", "[v1=v3 v2=v1 v3=v2]", "[v1=v3 v2=v2 v3=v1]")); assertEquals(true, mappings.remove(iter.next().toString())); assertEquals(true, mappings.remove(iter.next().toString())); assertEquals(true, mappings.remove(iter.next().toString())); assertEquals(true, mappings.remove(iter.next().toString())); assertEquals(true, mappings.remove(iter.next().toString())); assertEquals(true, mappings.remove(iter.next().toString())); assertEquals(false, iter.hasNext()); DefaultDirectedGraph<Integer, DefaultEdge> g2 = new DefaultDirectedGraph<>(DefaultEdge.class); g2.addVertex(1); g2.addVertex(2); g2.addVertex(3); g2.addEdge(1, 2); g2.addEdge(3, 2); VF2GraphIsomorphismInspector<Integer, DefaultEdge> vf3 = new VF2GraphIsomorphismInspector<>(g2, g2); Iterator<GraphMapping<Integer, DefaultEdge>> iter2 = vf3.getMappings(); Set<String> mappings2 = new HashSet<>(Arrays.asList("[1=1 2=2 3=3]", "[1=3 2=2 3=1]")); assertEquals(true, mappings2.remove(iter2.next().toString())); assertEquals(true, mappings2.remove(iter2.next().toString())); assertEquals(false, iter2.hasNext()); } |
### Question:
SaturationDegreeColoring implements VertexColoringAlgorithm<V> { @Override @SuppressWarnings("unchecked") public Coloring<V> getColoring() { int n = graph.vertexSet().size(); int maxColor = -1; Map<V, Integer> colors = new HashMap<>(n); Map<V, BitSet> adjColors = new HashMap<>(n); Map<V, Integer> saturation = new HashMap<>(n); int maxDegree = 0; Map<V, Integer> degree = new HashMap<>(n); for (V v : graph.vertexSet()) { int d = graph.edgesOf(v).size(); degree.put(v, d); maxDegree = Math.max(maxDegree, d); adjColors.put(v, new BitSet()); saturation.put(v, 0); } Heap heap = new Heap(n, new DSaturComparator(saturation, degree)); Map<V, HeapHandle> handles = new HashMap<>(); for (V v : graph.vertexSet()) { handles.put(v, new HeapHandle(v)); } heap.bulkInsert( handles.values().toArray((HeapHandle[]) Array.newInstance(HeapHandle.class, 0))); while (heap.size() > 0) { V v = heap.deleteMin().vertex; BitSet used = adjColors.get(v); int c = used.nextClearBit(0); maxColor = Math.max(maxColor, c); colors.put(v, c); adjColors.remove(v); for (E e : graph.edgesOf(v)) { V u = Graphs.getOppositeVertex(graph, e, v); if (!colors.containsKey(u)) { int uSaturation = saturation.get(u); BitSet uAdjColors = adjColors.get(u); HeapHandle uHandle = handles.get(u); if (uAdjColors.get(c)) { heap.delete(uHandle); degree.put(u, degree.get(u) - 1); heap.insert(uHandle); } else { uAdjColors.set(c); saturation.put(u, uSaturation + 1); degree.put(u, degree.get(u) - 1); heap.fixup(uHandle); } } } } return new ColoringImpl<>(colors, maxColor + 1); } SaturationDegreeColoring(Graph<V, E> graph); @Override @SuppressWarnings("unchecked") Coloring<V> getColoring(); }### Answer:
@Test public void testSaturationDegree() { Graph<Integer, DefaultEdge> g = new Pseudograph<>(DefaultEdge.class); Graphs.addAllVertices(g, Arrays.asList(1, 2, 3, 4, 5, 6)); g.addEdge(2, 3); g.addEdge(4, 5); g.addEdge(4, 6); g.addEdge(5, 6); g.addEdge(5, 3); Coloring<Integer> coloring = new SaturationDegreeColoring<>(g).getColoring(); assertEquals(3, coloring.getNumberColors()); Map<Integer, Integer> colors = coloring.getColors(); assertEquals(0, colors.get(1).intValue()); assertEquals(0, colors.get(2).intValue()); assertEquals(1, colors.get(3).intValue()); assertEquals(1, colors.get(4).intValue()); assertEquals(0, colors.get(5).intValue()); assertEquals(2, colors.get(6).intValue()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.