src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
Nexus extends HorizontalTrack { @Override public boolean allowsConnection(Direction direction) { return !Direction.TOP.equals(direction); } Nexus(NexusContext context); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); NexusContext getContext(); } | @Test public void allowsConnectionLeft() { assertThat(nexus.allowsConnection(Direction.LEFT)).isTrue(); }
@Test public void allowsConnectionRight() { assertThat(nexus.allowsConnection(Direction.RIGHT)).isTrue(); }
@Test public void allowsConnectionBottom() { assertThat(nexus.allowsConnection(Direction.BOTTOM)).isTrue(); }
@Test public void disallowsConnectionTop() { assertThat(nexus.allowsConnection(Direction.TOP)).isFalse(); } |
Nexus extends HorizontalTrack { @Override public boolean accepts(Direction direction, Marble marble) { return super.allowsConnection(direction); } Nexus(NexusContext context); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); NexusContext getContext(); } | @Test public void acceptsLeft() { assertThat(nexus.accepts(Direction.LEFT, marble)).isTrue(); }
@Test public void acceptsRight() { assertThat(nexus.accepts(Direction.RIGHT, marble)).isTrue(); }
@Test public void notAcceptsTop() { assertThat(nexus.accepts(Direction.TOP, marble)).isFalse(); }
@Test public void notAcceptsBottom() { assertThat(nexus.accepts(Direction.BOTTOM, marble)).isFalse(); } |
Nexus extends HorizontalTrack { public NexusContext getContext() { return context; } Nexus(NexusContext context); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); NexusContext getContext(); } | @Test public void getContext() { assertThat(nexus.getContext()).isEqualTo(context); } |
Progress implements ReceptorListener { public boolean isWon() { return unmarked.isEmpty(); } boolean isWon(); int getScore(); void setScore(int score); void score(int points); void track(Grid grid); @Override void receptorMarked(Receptor receptor); } | @Test public void testWonFalse() { assertThat(progress.isWon()).isFalse(); } |
HardLevelTwo extends AbstractHardLevel { @Override public int getIndex() { return 2; } @Override GameSession create(Configuration config); @Override int getIndex(); } | @Test public void getIndex() { assertThat(level.getIndex()).isEqualTo(2); } |
HardLevelOne extends AbstractHardLevel { @Override public int getIndex() { return 1; } @Override GameSession create(Configuration config); @Override int getIndex(); } | @Test public void getIndex() { assertThat(level.getIndex()).isEqualTo(1); } |
HardLevelFactory extends LevelFactory { public AbstractHardLevel create(int level) { switch (level) { case 1: return new HardLevelOne(); case 2: return new HardLevelTwo(); case 3: return new HardLevelThree(); default: return null; } } AbstractHardLevel create(int level); } | @Test public void createLevelOne() { assertThat(factory.create(1)).isInstanceOf(HardLevelOne.class); }
@Test public void createLevelTwo() { assertThat(factory.create(2)).isInstanceOf(HardLevelTwo.class); }
@Test public void createLevelThree() { assertThat(factory.create(3)).isInstanceOf(HardLevelThree.class); } |
HardLevelThree extends AbstractHardLevel { @Override public int getIndex() { return 3; } @Override GameSession create(Configuration config); @Override int getIndex(); } | @Test public void getIndex() { assertThat(level.getIndex()).isEqualTo(3); } |
EasyLevelTwo extends AbstractEasyLevel { @Override public int getIndex() { return 2; } @Override GameSession create(Configuration config); @Override int getIndex(); } | @Test public void getIndex() { assertThat(level.getIndex()).isEqualTo(2); } |
EasyLevelOne extends AbstractEasyLevel { @Override public int getIndex() { return 1; } @Override GameSession create(Configuration config); @Override int getIndex(); } | @Test public void getIndex() { assertThat(level.getIndex()).isEqualTo(1); } |
EasyLevelFactory extends LevelFactory { public AbstractEasyLevel create(int level) { switch (level) { case 1: return new EasyLevelOne(); case 2: return new EasyLevelTwo(); case 3: return new EasyLevelThree(); default: return null; } } AbstractEasyLevel create(int level); } | @Test public void createLevelOne() { assertThat(factory.create(1)).isInstanceOf(EasyLevelOne.class); }
@Test public void createLevelTwo() { assertThat(factory.create(2)).isInstanceOf(EasyLevelTwo.class); }
@Test public void createLevelThree() { assertThat(factory.create(3)).isInstanceOf(EasyLevelThree.class); } |
EasyLevelThree extends AbstractEasyLevel { @Override public int getIndex() { return 3; } @Override GameSession create(Configuration config); @Override int getIndex(); } | @Test public void getIndex() { assertThat(level.getIndex()).isEqualTo(3); } |
LevelFactory { public abstract Level create(int level); abstract Level create(int level); } | @Test public void getFirst() { assertThat(factory.create(1)).isNotNull(); }
@Test public void getSecond() { assertThat(factory.create(2)).isNotNull(); }
@Test public void getThird() { assertThat(factory.create(3)).isNotNull(); }
@Test public void getFourth() { assertThat(factory.create(4)).isNull(); } |
MediumLevelThree extends AbstractMediumLevel { @Override public int getIndex() { return 3; } @Override GameSession create(Configuration config); @Override int getIndex(); } | @Test public void getIndex() { assertThat(level.getIndex()).isEqualTo(3); } |
MediumLevelOne extends AbstractMediumLevel { @Override public int getIndex() { return 1; } @Override GameSession create(Configuration config); @Override int getIndex(); } | @Test public void getIndex() { assertThat(level.getIndex()).isEqualTo(1); } |
MediumLevelFactory extends LevelFactory { public AbstractMediumLevel create(int level) { switch (level) { case 1: return new MediumLevelOne(); case 2: return new MediumLevelTwo(); case 3: return new MediumLevelThree(); default: return null; } } AbstractMediumLevel create(int level); } | @Test public void createLevelOne() { assertThat(factory.create(1)).isInstanceOf(MediumLevelOne.class); }
@Test public void createLevelTwo() { assertThat(factory.create(2)).isInstanceOf(MediumLevelTwo.class); }
@Test public void createLevelThree() { assertThat(factory.create(3)).isInstanceOf(MediumLevelThree.class); } |
MediumLevelTwo extends AbstractMediumLevel { @Override public int getIndex() { return 2; } @Override GameSession create(Configuration config); @Override int getIndex(); } | @Test public void getIndex() { assertThat(level.getIndex()).isEqualTo(2); } |
Tile implements Entity { public boolean isOccupied() { return !(tileable instanceof Empty); } Tile(); Tileable getTileable(); boolean isOccupied(); Tile get(Direction direction); abstract int getX(); abstract int getY(); abstract Grid getGrid(); } | @Test public void isOccupied() { assertThat(grid.get(0,0).isOccupied()).isTrue(); } |
Tile implements Entity { public Tile get(Direction direction) { Grid grid = getGrid(); int x = getX(); int y = getY(); if (direction == null) { throw new IllegalArgumentException(); } Tile result = null; switch (direction) { case TOP: result = grid.get(x, y + 1); break; case RIGHT: result = grid.get(x + 1, y); break; case BOTTOM: result = grid.get(x, y - 1); break; case LEFT: result = grid.get(x - 1, y); break; default: } return result; } Tile(); Tileable getTileable(); boolean isOccupied(); Tile get(Direction direction); abstract int getX(); abstract int getY(); abstract Grid getGrid(); } | @Test public void getDirectionNull() { assertThatThrownBy(() -> grid.get(1,0).get(null)) .isInstanceOf(IllegalArgumentException.class); } |
Tile implements Entity { public abstract Grid getGrid(); Tile(); Tileable getTileable(); boolean isOccupied(); Tile get(Direction direction); abstract int getX(); abstract int getY(); abstract Grid getGrid(); } | @Test public void getGridTest() { assertThat(grid.get(0,0).getGrid()).isEqualTo(grid); } |
Grid implements Entity { public boolean onGrid(int x, int y) { return x >= 0 && x < width && y >= 0 && y < height; } Grid(GameSession session, int width, int height); int getWidth(); int getHeight(); GameSession getSession(); void place(int x, int y, Tileable tileable); Tile get(int x, int y); boolean onGrid(int x, int y); } | @Test public void onGridInPointsTest() { Grid grid = new Grid(session, 3, 2); for (int x = 0; x < 3; x++) { for (int y = 0; y < 2; y++) { assertThat(grid.onGrid(x,y)).isTrue(); } } }
@Test public void onGridOutPointsTest() { Grid grid = new Grid(session, 3, 2); int x = -1; int y = -1; while (y < 2) { while (x < 4) { assertThat(grid.onGrid(x, y)).isFalse(); x++; } x = -1; y += 3; } x = -1; y = -1; while (x < 4) { while (y < 3) { assertThat(grid.onGrid(x, y)).isFalse(); y++; } y = -1; x += 4; } } |
Grid implements Entity { public void place(int x, int y, Tileable tileable) { if (!onGrid(x, y)) { throw new IllegalArgumentException("The given coordinates do not exist on this grid"); } Tile tile = tiles[y][x]; tile.tileable = tileable; tileable.setTile(tile); } Grid(GameSession session, int width, int height); int getWidth(); int getHeight(); GameSession getSession(); void place(int x, int y, Tileable tileable); Tile get(int x, int y); boolean onGrid(int x, int y); } | @Test public void placeInvalid() { Grid grid = new Grid(session, 3, 1); assertThatThrownBy(() -> grid.place(-1, -1, null)) .isInstanceOf(IllegalArgumentException.class); } |
Grid implements Entity { public GameSession getSession() { return session; } Grid(GameSession session, int width, int height); int getWidth(); int getHeight(); GameSession getSession(); void place(int x, int y, Tileable tileable); Tile get(int x, int y); boolean onGrid(int x, int y); } | @Test public void getSession() { Grid grid = new Grid(session, 1, 1); assertThat(grid.getSession()).isEqualTo(session); } |
Tileable implements Entity { public boolean isConnected(Direction direction) { if (tile == null) { throw new IllegalStateException(TILEABLE_UNPLACED); } else if (!allowsConnection(direction)) { return false; } Tile neighbour = tile.get(direction); return neighbour != null && neighbour.getTileable().allowsConnection(direction.inverse()); } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void isConnected() { Tileable tileable = grid.get(0, 0).getTileable(); assertThat(tileable.isConnected(Direction.RIGHT)).isTrue(); }
@Test public void isConnectedInverse() { Tileable tileable = grid.get(1, 0).getTileable(); assertThat(tileable.isConnected(Direction.LEFT)).isTrue(); }
@Test public void isNotConnected() { Tileable tileable = grid.get(0, 0).getTileable(); assertThat(tileable.isConnected(Direction.LEFT)).isFalse(); }
@Test public void doesNotAllowConnections() { Tileable tileable = grid.get(1, 1).getTileable(); assertThat(tileable.isConnected(Direction.TOP)).isFalse(); }
@Test public void neighbourDoesNotAllowConnections() { Tileable tileable = grid.get(0, 1).getTileable(); assertThat(tileable.isConnected(Direction.RIGHT)).isFalse(); }
@Test public void unplacedNotConnected() { Track track = new HorizontalTrack(); assertThatThrownBy(() -> track.isConnected(Direction.RIGHT)) .isInstanceOf(IllegalStateException.class); } |
Tileable implements Entity { public boolean isReleasable(Direction direction, Marble marble) { if (tile == null) { throw new IllegalStateException(TILEABLE_UNPLACED); } Tile neighbour = tile.get(direction); return neighbour != null && neighbour.getTileable().accepts(direction.inverse(), marble); } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void isReleasable() { Tileable tileable = grid.get(0, 0).getTileable(); assertThat(tileable.isReleasable(Direction.RIGHT, marble)).isTrue(); }
@Test public void isNotReleasable() { Tileable tileable = grid.get(0, 0).getTileable(); assertThat(tileable.isReleasable(Direction.LEFT, marble)).isFalse(); }
@Test public void neighbourDoesNotAllowReleasing() { Tileable tileable = grid.get(0, 1).getTileable(); assertThat(tileable.isReleasable(Direction.RIGHT, marble)).isFalse(); }
@Test public void unplacedNotReleasable() { Track track = new HorizontalTrack(); assertThatThrownBy(() -> track.isReleasable(Direction.RIGHT, marble)) .isInstanceOf(IllegalStateException.class); } |
Tileable implements Entity { public void release(Direction direction, Marble marble) { if (tile == null) { throw new IllegalStateException(TILEABLE_UNPLACED); } Tile neighbour = tile.get(direction); if (neighbour != null) { informRelease(direction, marble); neighbour.getTileable().accept(direction.inverse(), marble); } } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void unplacedRelease() { Track track = new HorizontalTrack(); assertThatThrownBy(() -> track.release(Direction.RIGHT, new Marble(MarbleType.BLUE))) .isInstanceOf(IllegalStateException.class); } |
Tileable implements Entity { public boolean onGrid() { return tile != null; } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void onGrid() { Tileable tileable = grid.get(0, 0).getTileable(); assertThat(tileable.onGrid()).isTrue(); }
@Test public void notOnGrid() { Tileable tileable = new HorizontalTrack(); assertThat(tileable.onGrid()).isFalse(); } |
Tileable implements Entity { public Tile getTile() { return tile; } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void getTile() { Tile tile = grid.get(0, 0); Tileable tileable = tile.getTileable(); assertThat(tileable.getTile()).isEqualTo(tile); } |
Tileable implements Entity { public Set<TileableListener> getListeners() { return listeners; } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void getListeners() { Tileable tileable = new HorizontalTrack(); assertThat(tileable.getListeners()).isEmpty(); } |
Tileable implements Entity { public boolean addListener(TileableListener listener) { return listeners.add(listener); } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void addListener() { TileableListener listener = mock(TileableListener.class); Tileable tileable = new HorizontalTrack(); tileable.addListener(listener); assertThat(tileable.getListeners()).containsExactly(listener); } |
Tileable implements Entity { public boolean removeListener(TileableListener listener) { return listeners.remove(listener); } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void removeListener() { TileableListener listener = mock(TileableListener.class); Tileable tileable = new HorizontalTrack(); tileable.addListener(listener); tileable.removeListener(listener); assertThat(tileable.getListeners()).isEmpty(); } |
Tileable implements Entity { protected void informAcceptation(Direction direction, Marble marble) { for (TileableListener listener : listeners) { listener.ballAccepted(this, direction, marble); } } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void informAcceptation() { TileableListener listener = mock(TileableListener.class); Tileable tileable = new HorizontalTrack(); Direction direction = Direction.RIGHT; Marble marble = new Marble(MarbleType.BLUE); tileable.addListener(listener); tileable.informAcceptation(direction, marble); verify(listener, times(1)).ballAccepted(tileable, direction, marble); } |
Tileable implements Entity { protected void informRelease(Direction direction, Marble marble) { for (TileableListener listener : listeners) { listener.ballReleased(this, direction, marble); } } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void informRelease() { TileableListener listener = mock(TileableListener.class); Tileable tileable = new HorizontalTrack(); Direction direction = Direction.RIGHT; Marble marble = new Marble(MarbleType.BLUE); tileable.addListener(listener); tileable.informRelease(direction, marble); verify(listener, times(1)).ballReleased(tileable, direction, marble); } |
Tileable implements Entity { protected void informDispose(Direction direction, Marble marble) { for (TileableListener listener : listeners) { listener.ballDisposed(this, direction, marble); } } abstract boolean allowsConnection(Direction direction); abstract boolean accepts(Direction direction, Marble marble); abstract void accept(Direction direction, Marble marble); boolean isConnected(Direction direction); boolean isReleasable(Direction direction, Marble marble); void release(Direction direction, Marble marble); Tile getTile(); void setTile(Tile tile); Set<TileableListener> getListeners(); boolean addListener(TileableListener listener); boolean removeListener(TileableListener listener); boolean onGrid(); } | @Test public void informDispose() { TileableListener listener = mock(TileableListener.class); Tileable tileable = new HorizontalTrack(); Direction direction = Direction.RIGHT; Marble marble = new Marble(MarbleType.BLUE); tileable.addListener(listener); tileable.informDispose(direction, marble); verify(listener, times(1)).ballDisposed(tileable, direction, marble); } |
LightbendConfiguration implements Configuration { @Override @SuppressWarnings("unchecked") public <T> T get(Property<T> property, T defaultValue) { Class<T> type = property.getType(); String key = property.getKey(); Object value = property instanceof ListProperty ? getList((ListProperty) property) : getValue(key, type); if (value == null) { return defaultValue; } return property.map((T) value); } LightbendConfiguration(Config api); @Override @SuppressWarnings("unchecked") T get(Property<T> property, T defaultValue); @Override boolean exists(Property<?> property); } | @Test public void getUnsupportedProperty() { Object object = new Object(); assertThat(config.get(new Property<Object>(Object.class, "", object) {})) .isEqualTo(object); }
@Test public void getBooleanProperty() throws Exception { when(api.getBoolean("a")).thenReturn(true); assertThat(config.get(new BooleanProperty("a", false))).isTrue(); }
@Test public void getDefaultBooleanProperty() throws Exception { when(api.getBoolean(anyString())).thenThrow(new ConfigException.BadPath("", "")); assertThat(config.get(new BooleanProperty("a", false))).isFalse(); }
@Test public void getDoubleProperty() throws Exception { when(api.getDouble("a")).thenReturn(1.0); assertThat(config.get(new DoubleProperty("a"))).isEqualTo(1.0); }
@Test public void getDefaultDoubleProperty() throws Exception { when(api.getDouble(anyString())).thenThrow(new ConfigException.BadPath("", "")); assertThat(config.get(new DoubleProperty("a", 1.0))).isEqualTo(1.0); }
@Test public void getIntegerProperty() throws Exception { when(api.getInt("a")).thenReturn(1); assertThat(config.get(new IntegerProperty("a"))).isEqualTo(1); }
@Test public void getDefaultIntegerProperty() throws Exception { when(api.getInt(anyString())).thenThrow(new ConfigException.BadPath("", "")); assertThat(config.get(new IntegerProperty("a", 1))).isEqualTo(1); }
@Test public void getStringProperty() throws Exception { when(api.getString("a")).thenReturn("b"); assertThat(config.get(new StringProperty("a", "c"))).isEqualTo("b"); }
@Test public void getDefaultStringProperty() throws Exception { when(api.getString(anyString())).thenThrow(new ConfigException.BadPath("", "")); assertThat(config.get(new StringProperty("a", "c"))).isEqualTo("c"); }
@Test public void getUnsupportedListProperty() throws Exception { List<Object> list = Lists.newArrayList(new Object()); assertThat(config.get(new ListProperty<>(Object.class, "a", list))).isEqualTo(list); }
@Test public void getBooleanListProperty() throws Exception { List<Boolean> list = Lists.newArrayList(false, true); when(api.getBooleanList("a")).thenReturn(list); assertThat(config.get(new ListProperty<>(Boolean.class, "a", Lists.emptyList()))) .isEqualTo(list); }
@Test public void getDefaultBooleanListProperty() throws Exception { when(api.getDoubleList(anyString())).thenThrow(new ConfigException.BadPath("", "")); assertThat(config.get(new ListProperty<>(Boolean.class,"a", Lists.emptyList()))) .isEqualTo(Lists.emptyList()); }
@Test public void getDoubleListProperty() throws Exception { List<Double> list = Lists.newArrayList(1.0, 2.0); when(api.getDoubleList("a")).thenReturn(list); assertThat(config.get(new ListProperty<>(Double.class, "a", Lists.emptyList()))) .isEqualTo(list); }
@Test public void getDefaultDoubleListProperty() throws Exception { when(api.getDoubleList(anyString())).thenThrow(new ConfigException.BadPath("", "")); assertThat(config.get(new ListProperty<>(Double.class,"a", Lists.emptyList()))) .isEqualTo(Lists.emptyList()); }
@Test public void getIntegerListProperty() throws Exception { List<Integer> list = Lists.newArrayList(1, 2); when(api.getIntList("a")).thenReturn(list); assertThat(config.get(new ListProperty<>(Integer.class, "a", Lists.emptyList()))) .isEqualTo(list); }
@Test public void getDefaultIntegerListProperty() throws Exception { when(api.getIntList(anyString())).thenThrow(new ConfigException.BadPath("", "")); assertThat(config.get(new ListProperty<>(Integer.class,"a", Lists.emptyList()))) .isEqualTo(Lists.emptyList()); }
@Test public void getStringListProperty() throws Exception { List<String> list = Lists.newArrayList("a", "b"); when(api.getStringList("a")).thenReturn(list); assertThat(config.get(new ListProperty<>(String.class, "a", Lists.emptyList()))) .isEqualTo(list); }
@Test public void getDefaultStringListProperty() throws Exception { when(api.getStringList(anyString())).thenThrow(new ConfigException.BadPath("", "")); assertThat(config.get(new ListProperty<>(String.class,"a", Lists.emptyList()))) .isEqualTo(Lists.emptyList()); }
@Test public void getBoundedIntegerPropertyDefault() throws Exception { when(api.getInt("a")).thenThrow(new ConfigException.BadPath("", "")); assertThat(config.get(new BoundedProperty<>(new IntegerProperty("a", -1), 0, 100))) .isEqualTo(-1); }
@Test public void getBoundedIntegerPropertyInner() throws Exception { when(api.getInt("a")).thenReturn(50); assertThat(config.get(new BoundedProperty<>(new IntegerProperty("a"), 0, 100))) .isEqualTo(50); }
@Test public void getBoundedIntegerPropertyLower() throws Exception { when(api.getInt("a")).thenReturn(-1); assertThat(config.get(new BoundedProperty<>(new IntegerProperty("a"), 0, 100))) .isEqualTo(0); }
@Test public void getBoundedIntegerPropertyUpper() throws Exception { when(api.getInt("a")).thenReturn(200); assertThat(config.get(new BoundedProperty<>(new IntegerProperty("a"), 0, 100))) .isEqualTo(100); } |
LightbendConfiguration implements Configuration { @Override public boolean exists(Property<?> property) { return api.hasPath(property.getKey()); } LightbendConfiguration(Config api); @Override @SuppressWarnings("unchecked") T get(Property<T> property, T defaultValue); @Override boolean exists(Property<?> property); } | @Test public void propertyExists() throws Exception { when(api.hasPath("test")).thenReturn(true); assertThat(config.exists(new StringProperty("test", ""))).isTrue(); }
@Test public void propertyNotExists() throws Exception { when(api.getString(anyString())).thenThrow(new ConfigException.BadPath("", "")); assertThat(config.exists(new StringProperty("test", ""))).isFalse(); } |
LightbendConfigurationLoader implements ConfigurationLoader { @Override public Configuration load(File file) throws FileNotFoundException { if (!file.exists()) { throw new FileNotFoundException("The given file does not exist"); } return new LightbendConfiguration(ConfigFactory.parseFile(file)); } @Override Configuration load(File file); @Override Configuration load(InputStream input); } | @Test public void nonExistentFile() throws Exception { File file = mock(File.class); when(file.exists()).thenReturn(false); assertThatThrownBy(() -> loader.load(file)).isInstanceOf(FileNotFoundException.class); }
@Test public void existentFile() throws Exception { File file = File.createTempFile("lightbend", "test"); String content = "a = 1"; Files.write(file.toPath(), content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE); assertThat(loader.load(file).get(new IntegerProperty("a"))).isEqualTo(1); file.deleteOnExit(); }
@Test public void validStream() throws Exception { String content = "a = 1"; InputStream input = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); assertThat(loader.load(input).get(new IntegerProperty("a"))).isEqualTo(1); }
@Test public void invalidStream() throws Exception { InputStream input = mock(InputStream.class); when(input.read(any())).thenThrow(new IOException()); assertThatThrownBy(() -> loader.load(input)).isInstanceOf(IOException.class); } |
DesktopLauncher implements Runnable { public static void main(String[] args) { getInstance().run(); } private DesktopLauncher(); static DesktopLauncher getInstance(); static void main(String[] args); @Override void run(); } | @Test public void smokeTest() { assertThatCode(() -> { DesktopLauncher.main(new String[] {}); Thread.sleep(2000); ((LwjglApplication) Gdx.app).stop(); }).doesNotThrowAnyException(); } |
MusicActor extends Actor implements Disposable { public void play(Music theme) { if (this.theme != null) { this.theme.stop(); } this.theme = theme; this.theme.setLooping(true); this.theme.play(); } void play(Music theme); @Override void dispose(); } | @Test public void testPlay() { Music theme = mock(Music.class); actor.play(theme); verify(theme, times(1)).play(); verify(theme, times(1)).setLooping(true); }
@Test public void testPlaySecond() { Music first = mock(Music.class); Music second = mock(Music.class); actor.play(first); reset(first); actor.play(second); verify(first, times(1)).stop(); verify(second, times(1)).play(); verify(second, times(1)).setLooping(true); } |
ReceptorActor extends TileableActor<Receptor> implements ReceptorListener { @Override public void ballDisposed(Tileable tileable, Direction direction, Marble marble) { Actor actor = getContext().actor(marble); if (actor != null) { actor.remove(); } } ReceptorActor(Receptor receptor, ActorContext context); @Override TextureRegion getTileTexture(); @Override void draw(Batch batch, float parentAlpha); @Override void act(float deltaTime); @Override void receptorMarked(Receptor receptor); @Override void receptorAssigned(Receptor receptor); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); } | @Test public void disposeUnknown() throws Exception { assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); assertThatCode(() -> actor.ballDisposed(receptor, Direction.LEFT, new Marble(MarbleType.BLUE)) ).doesNotThrowAnyException(); } |
NexusActor extends TransportingActor<Nexus> implements TileableListener { @Override public void ballAccepted(Tileable tileable, Direction direction, Marble marble) { MarbleActor actor = MarbleActor.get(marble, getContext()); addActor(actor); Nexus nexus = getTileable(); Vector2 origin = getOrigin(direction); Vector2 center = getCenter(); Vector2 target = getTarget(direction); actor.setPosition(origin.x, origin.y, Align.center); actor.setDirection(direction.inverse()); Action moveCenter = Actions.moveToAligned(center.x, center.y, Align.center, origin.dst(center) * TRAVEL_TIME); Action moveTarget = Actions.moveToAligned(target.x, target.y, Align.center, target.dst(center) * TRAVEL_TIME); SequenceAction animation = new SequenceAction(); animation.addAction(moveCenter); animation.addAction(Actions.run(() -> { Direction out = Direction.BOTTOM; if (nexus.isReleasable(out, marble)) { actor.removeAction(animation); actor.setDirection(out); nexus.release(out, marble); nexus.getContext().setOccupied(false); } })); animation.addAction(moveTarget); animation.addAction(Actions.run(() -> { Direction inverse = direction.inverse(); if (!nexus.isReleasable(inverse, marble)) { ballAccepted(tileable, inverse, marble); return; } nexus.release(inverse, marble); })); actor.addAction(animation); } NexusActor(Nexus nexus, ActorContext context); @Override TextureRegion getTileTexture(); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void act(float deltaTime); } | @Test public void testSpawn() throws Exception { assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); latch = new CountDownLatch(2); TileableListener listener = spy(new TileableListener() { @Override public void ballAccepted(Tileable tileable, Direction direction, Marble marble) { latch.countDown(); } }); nexus.addListener(listener); assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); verify(listener, atLeast(2)).ballAccepted(any(), any(), any()); }
@Test public void testInvalidDirection() throws Exception { assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(() -> actor.ballAccepted(nexus, Direction.TOP, new Marble(MarbleType.BLUE)) ).isInstanceOf(IllegalArgumentException.class); } |
TrackActor extends TransportingActor<Track> implements TileableListener { @Override public void ballAccepted(Tileable tileable, Direction direction, Marble marble) { MarbleActor actor = (MarbleActor) getContext().actor(marble); Vector2 origin = stageToLocalCoordinates(actor.localToStageCoordinates( new Vector2(actor.getWidth() / 2.f, actor.getHeight() / 2.f))); prepareActor(actor, direction, origin); if (getTileable().passesMidpoint(direction, marble)) { travelAnimation(actor, direction, origin); } else { bounceTravelAnimation(actor, direction, origin); } addActorBefore(modifier, actor); } TrackActor(Track tileable, ActorContext context); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); } | @Test public void testFilterJoker() throws Exception { assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); latch = new CountDownLatch(2); Marble marble = new Marble(MarbleType.JOKER); JokerMarbleActor jokerActor = new JokerMarbleActor(marble, context); jokerActor.addActor(new Actor()); context.register(marble, jokerActor); FilterTrack track = (FilterTrack) grid.get(0, 1).getTileable(); TrackActor actor = (TrackActor) context.actor(track); Direction direction = Direction.TOP; TileableListener listener = spy(new TileableListener() { @Override public void ballReleased(Tileable tileable, Direction direction, Marble marble) { latch.countDown(); } }); track.addListener(listener); app.postRunnable(() -> { actor.addActor(context.actor(marble)); track.accept(direction, marble); latch.countDown(); }); assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); Thread.sleep(200); verify(listener, atLeastOnce()).ballAccepted(any(), eq(direction), any()); verify(listener, atLeastOnce()).ballReleased(any(), eq(direction.inverse()), any()); } |
ScreenStack extends Stack { public void push(Actor screen) { Action runnable = Actions.run(() -> { add(screen); getStage().setKeyboardFocus(screen); }); addAction(runnable); } void replace(Actor screen); void push(Actor screen); void pop(int n); @Override void act(float deltaTime); } | @Test public void testPush() throws Exception { Actor screen = spy(new Actor()); latch = new CountDownLatch(1); app.postRunnable(() -> { actor.push(screen); latch.countDown(); }); assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); Thread.sleep(500); verify(screen, atLeastOnce()).draw(any(), anyFloat()); verify(screen, atLeastOnce()).act(anyFloat()); } |
ScreenStack extends Stack { public void replace(Actor screen) { Action runnable = Actions.run(() -> { if (hasChildren()) { getChildren().pop(); } add(screen); getStage().setKeyboardFocus(screen); }); addAction(runnable); } void replace(Actor screen); void push(Actor screen); void pop(int n); @Override void act(float deltaTime); } | @Test public void testReplace() throws Exception { Actor screenA = spy(new Actor()); Actor screenB = spy(new Actor()); latch = new CountDownLatch(1); app.postRunnable(() -> { actor.push(screenA); actor.replace(screenB); latch.countDown(); }); assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); reset(screenA); Thread.sleep(500); verify(screenA, never()).draw(any(), anyFloat()); verify(screenA, never()).act(anyFloat()); verify(screenB, atLeastOnce()).draw(any(), anyFloat()); verify(screenB, atLeastOnce()).act(anyFloat()); assertThat(stage.getKeyboardFocus()).isEqualTo(screenB); } |
ScreenStack extends Stack { public void pop(int n) { addAction(Actions.run(() -> { if (!hasChildren() || n == 0) { return; } SnapshotArray<Actor> children = getChildren(); int size = children.size; children.removeRange(Math.max(0, size - n), size - 1); if (size - n > 0) { getStage().setKeyboardFocus(children.peek()); } })); } void replace(Actor screen); void push(Actor screen); void pop(int n); @Override void act(float deltaTime); } | @Test public void testPopNoChildren() throws Exception { latch = new CountDownLatch(1); app.postRunnable(() -> { actor.pop(1); latch.countDown(); }); assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); Thread.sleep(500); assertThat(actor.hasChildren()).isFalse(); } |
ScreenStack extends Stack { @Override public void act(float deltaTime) { Array<Action> actions = this.getActions(); Stage stage = getStage(); if (actions.size > 0) { if (stage != null) { if (stage.getActionsRequestRendering()) { Gdx.graphics.requestRendering(); } } for (int i = 0; i < actions.size; i++) { Action action = actions.get(i); if (action.act(deltaTime)) { actions.removeIndex(i); action.setActor(null); i--; } } } if (hasChildren()) { getChildren().peek().act(deltaTime); } } void replace(Actor screen); void push(Actor screen); void pop(int n); @Override void act(float deltaTime); } | @Test @SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") public void testActionsNoStage() throws Exception { Graphics real = Gdx.graphics; Gdx.graphics = spy(real); latch = new CountDownLatch(1); app.postRunnable(() -> { actor.remove(); actor.addAction(Actions.delay(1)); actor.act(1); latch.countDown(); }); assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); Thread.sleep(200); verify(Gdx.graphics, times(1)).requestRendering(); Gdx.graphics = real; } |
StackableStage extends Stage { public void push(Actor screen) { stack.push(screen); } StackableStage(Viewport viewport, ScreenStack stack); StackableStage(Viewport viewport); ScreenStack getScreenStack(); void replace(Actor screen); void push(Actor screen); void pop(int n); } | @Test public void push() { Actor screen = mock(Actor.class); stage.push(screen); verify(stack).push(eq(screen)); } |
DefProConfiguration implements Configuration { @Override public boolean exists(Property<?> property) { try { return api.getStringValueOf(property.getKey()) != null; } catch (NotExistingVariableException ignored) { return false; } } DefProConfiguration(IDefProAPI api); @Override @SuppressWarnings("unchecked") T get(Property<T> property, T defaultValue); @Override boolean exists(Property<?> property); } | @Test public void propertyExists() throws Exception { when(api.getStringValueOf("test")).thenReturn(""); assertThat(config.exists(new StringProperty("test", ""))).isTrue(); }
@Test public void propertyNotExists() throws Exception { when(api.getStringValueOf(anyString())).thenThrow(new NotExistingVariableException("")); assertThat(config.exists(new StringProperty("test", ""))).isFalse(); }
@Test public void propertyNullNotExists() throws Exception { when(api.getStringValueOf(anyString())).thenReturn(null); assertThat(config.exists(new StringProperty("test", ""))).isFalse(); } |
StackableStage extends Stage { public void replace(Actor screen) { stack.replace(screen); } StackableStage(Viewport viewport, ScreenStack stack); StackableStage(Viewport viewport); ScreenStack getScreenStack(); void replace(Actor screen); void push(Actor screen); void pop(int n); } | @Test public void replace() { Actor screen = mock(Actor.class); stage.replace(screen); verify(stack).replace(eq(screen)); } |
StackableStage extends Stage { public void pop(int n) { stack.pop(n); } StackableStage(Viewport viewport, ScreenStack stack); StackableStage(Viewport viewport); ScreenStack getScreenStack(); void replace(Actor screen); void push(Actor screen); void pop(int n); } | @Test public void pop() { stage.pop(2); verify(stack).pop(eq(2)); } |
Receptor extends Tileable { public boolean isMarked() { return marked; } void rotate(int turns); int getRotation(); Slot getSlot(Direction direction); boolean isMarked(); boolean isLocked(); void lock(); void unlock(); PowerUp getPowerUp(); void setPowerUp(PowerUp powerUp); @Override boolean isReleasable(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); } | @Test public void notMarkedOnStart() { Receptor receptor = new Receptor(); assertThat(receptor.isMarked()).isFalse(); } |
Receptor extends Tileable { @Override public boolean accepts(Direction direction, Marble marble) { return !locked && !getSlot(direction).isOccupied(); } void rotate(int turns); int getRotation(); Slot getSlot(Direction direction); boolean isMarked(); boolean isLocked(); void lock(); void unlock(); PowerUp getPowerUp(); void setPowerUp(PowerUp powerUp); @Override boolean isReleasable(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); } | @Test public void acceptsWhenSlotEmpty() { Receptor receptor = new Receptor(); assertThat(receptor.accepts(Direction.LEFT, marble)).isTrue(); } |
Receptor extends Tileable { @Override public boolean allowsConnection(Direction direction) { return true; } void rotate(int turns); int getRotation(); Slot getSlot(Direction direction); boolean isMarked(); boolean isLocked(); void lock(); void unlock(); PowerUp getPowerUp(); void setPowerUp(PowerUp powerUp); @Override boolean isReleasable(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); } | @Test public void allowsConnectionLeft() { assertThat(receptor.allowsConnection(Direction.LEFT)).isTrue(); }
@Test public void allowsConnectionRight() { assertThat(receptor.allowsConnection(Direction.RIGHT)).isTrue(); }
@Test public void allowsConnectionTop() { assertThat(receptor.allowsConnection(Direction.TOP)).isTrue(); }
@Test public void allowsConnectionBottom() { assertThat(receptor.allowsConnection(Direction.BOTTOM)).isTrue(); } |
Receptor extends Tileable { public void lock() { this.locked = true; } void rotate(int turns); int getRotation(); Slot getSlot(Direction direction); boolean isMarked(); boolean isLocked(); void lock(); void unlock(); PowerUp getPowerUp(); void setPowerUp(PowerUp powerUp); @Override boolean isReleasable(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); } | @Test public void lock() { receptor.lock(); assertThat(receptor.isLocked()).isTrue(); } |
Receptor extends Tileable { public void unlock() { this.locked = false; } void rotate(int turns); int getRotation(); Slot getSlot(Direction direction); boolean isMarked(); boolean isLocked(); void lock(); void unlock(); PowerUp getPowerUp(); void setPowerUp(PowerUp powerUp); @Override boolean isReleasable(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); } | @Test public void unlock() { receptor.unlock(); assertThat(receptor.isLocked()).isFalse(); } |
Receptor extends Tileable { @Override public boolean isReleasable(Direction direction, Marble marble) { return !isLocked() && super.isReleasable(direction, marble); } void rotate(int turns); int getRotation(); Slot getSlot(Direction direction); boolean isMarked(); boolean isLocked(); void lock(); void unlock(); PowerUp getPowerUp(); void setPowerUp(PowerUp powerUp); @Override boolean isReleasable(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); } | @Test public void unlockedReceptorIsNotReleasable() { Grid grid = new Grid(null,1, 1); grid.place(0, 0, receptor); assertThat(receptor.isReleasable(Direction.LEFT, marble)).isFalse(); }
@Test public void isReleasable() { Grid grid = new Grid(null,2, 1); grid.place(0, 0, new HorizontalTrack()); grid.place(1, 0, receptor); assertThat(receptor.isReleasable(Direction.LEFT, marble)).isTrue(); } |
Receptor extends Tileable { public Slot getSlot(Direction direction) { return slots[Math.floorMod(direction.ordinal() - rotation, directions.length)]; } void rotate(int turns); int getRotation(); Slot getSlot(Direction direction); boolean isMarked(); boolean isLocked(); void lock(); void unlock(); PowerUp getPowerUp(); void setPowerUp(PowerUp powerUp); @Override boolean isReleasable(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); } | @Test public void isNotCompatibleB() { Grid grid = new Grid(null, 1, 1); grid.place(0, 0, receptor); assertThat(receptor.getSlot(Direction.LEFT) .isCompatible(receptor.getSlot(Direction.RIGHT))).isFalse(); }
@Test public void getReceptor() { assertThat(receptor.getSlot(Direction.LEFT).getReceptor()).isEqualTo(receptor); }
@Test public void releaseUnoccupiedSlot() { Receptor.Slot slot = receptor.getSlot(Direction.LEFT); assertThatThrownBy(slot::release) .isInstanceOf(IllegalStateException.class) .hasMessage("The slot is not occupied"); } |
Receptor extends Tileable { @Override public void accept(Direction direction, Marble marble) { getSlot(direction).accept(marble); } void rotate(int turns); int getRotation(); Slot getSlot(Direction direction); boolean isMarked(); boolean isLocked(); void lock(); void unlock(); PowerUp getPowerUp(); void setPowerUp(PowerUp powerUp); @Override boolean isReleasable(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); } | @Test public void acceptWhenSlotOccupied() { receptor.accept(Direction.TOP, new Marble(MarbleType.BLUE)); assertThatThrownBy(() -> receptor.accept(Direction.TOP, new Marble(MarbleType.BLUE))) .isInstanceOf(IllegalStateException.class) .hasMessage("The slot is already occupied"); }
@Test public void notMark() { ReceptorListener listener = mock(ReceptorListener.class); ReceptorListener stub = new ReceptorListener() {}; TileableListener tileableListener = mock(TileableListener.class); receptor.addListener(listener); receptor.addListener(stub); receptor.addListener(tileableListener); Progress progress = mock(Progress.class); GameSession session = mock(GameSession.class); when(session.getProgress()).thenReturn(progress); Grid grid = new Grid(session, 2, 1); grid.place(0, 0, receptor); receptor.accept(Direction.TOP, new Marble(MarbleType.GREEN)); receptor.accept(Direction.RIGHT, new Marble(MarbleType.JOKER)); receptor.accept(Direction.BOTTOM, new Marble(MarbleType.BLUE)); receptor.accept(Direction.LEFT, new Marble(MarbleType.BLUE)); verify(listener, never()).receptorMarked(receptor); verify(progress, never()).score(anyInt()); } |
Receptor extends Tileable { private void mark() { marked = true; getTile().getGrid().getSession().getProgress().score(multiplier); for (Slot slot : slots) { slot.dispose(); } informMarked(); if (powerUp != null) { powerUp.activate(this); setPowerUp(null); } } void rotate(int turns); int getRotation(); Slot getSlot(Direction direction); boolean isMarked(); boolean isLocked(); void lock(); void unlock(); PowerUp getPowerUp(); void setPowerUp(PowerUp powerUp); @Override boolean isReleasable(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); } | @Test public void mark() { ReceptorListener listener = mock(ReceptorListener.class); ReceptorListener stub = new ReceptorListener() {}; TileableListener tileableListener = mock(TileableListener.class); receptor.addListener(listener); receptor.addListener(stub); receptor.addListener(tileableListener); Progress progress = mock(Progress.class); GameSession session = mock(GameSession.class); when(session.getProgress()).thenReturn(progress); Grid grid = new Grid(session, 2, 1); grid.place(0, 0, receptor); for (Direction direction : Direction.values()) { receptor.accept(direction, new Marble(MarbleType.GREEN)); } verify(listener, times(1)).receptorMarked(receptor); verify(progress, times(1)).score(anyInt()); } |
Receptor extends Tileable { public void setPowerUp(PowerUp powerUp) { this.powerUp = powerUp; informAssigned(); } void rotate(int turns); int getRotation(); Slot getSlot(Direction direction); boolean isMarked(); boolean isLocked(); void lock(); void unlock(); PowerUp getPowerUp(); void setPowerUp(PowerUp powerUp); @Override boolean isReleasable(Direction direction, Marble marble); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); } | @Test public void assigned() { ReceptorListener listener = mock(ReceptorListener.class); ReceptorListener stub = new ReceptorListener() {}; TileableListener tileableListener = mock(TileableListener.class); receptor.addListener(listener); receptor.addListener(stub); receptor.addListener(tileableListener); receptor.setPowerUp(null); verify(listener, times(1)).receptorAssigned(receptor); } |
RandomPowerUpFactory extends PowerUpFactory { @Override public PowerUp create() { return cdf.floorEntry(random.nextDouble()).getValue().create(); } RandomPowerUpFactory(Random random, NavigableMap<Double, PowerUpFactory> cdf); @Override PowerUp create(); } | @Test public void createA() { NavigableMap<Double, PowerUpFactory> cdf = new TreeMap<>(); cdf.put(0.0, new BonusPowerUpFactory()); cdf.put(0.6, new JokerPowerUpFactory()); PowerUpFactory factory = new RandomPowerUpFactory(random, cdf); when(random.nextDouble()).thenReturn(0.4); assertThat(factory.create()).isInstanceOf(BonusPowerUp.class); }
@Test public void createB() { NavigableMap<Double, PowerUpFactory> cdf = new TreeMap<>(); cdf.put(0.0, new BonusPowerUpFactory()); cdf.put(0.6, new JokerPowerUpFactory()); PowerUpFactory factory = new RandomPowerUpFactory(random, cdf); when(random.nextDouble()).thenReturn(0.7); assertThat(factory.create()).isInstanceOf(JokerPowerUp.class); } |
BonusPowerUp implements PowerUp { @Override public void activate(Receptor receptor) { receptor.getTile().getGrid().getSession().getProgress().score(100); } @Override void activate(Receptor receptor); } | @Test public void activate() { receptor.setPowerUp(powerUp); for (Direction direction : Direction.values()) { receptor.accept(direction, new Marble(MarbleType.BLUE)); } assertThat(session.getProgress().getScore()).isEqualTo(200); } |
JokerPowerUp implements PowerUp { @Override public void activate(Receptor receptor) { NexusContext context = receptor.getTile().getGrid().getSession().getNexusContext(); context.add(MarbleType.JOKER, MarbleType.JOKER); } @Override void activate(Receptor receptor); } | @Test public void activate() { receptor.setPowerUp(powerUp); for (Direction direction : Direction.values()) { receptor.accept(direction, new Marble(MarbleType.BLUE)); } verify(context).add(MarbleType.JOKER, MarbleType.JOKER); } |
Teleporter extends Tileable implements TileableListener { @Override public boolean allowsConnection(Direction direction) { return track.allowsConnection(direction); } Teleporter(Track track); void setDestination(Teleporter destination); Track getTrack(); Teleporter getDestination(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); } | @Test public void allowsLeft() { assertThat(teleporter1.allowsConnection(Direction.LEFT)).isTrue(); }
@Test public void allowsRight() { assertThat(teleporter1.allowsConnection(Direction.RIGHT)).isTrue(); }
@Test public void disallowsTop() { assertThat(teleporter1.allowsConnection(Direction.TOP)).isFalse(); }
@Test public void disallowsBottom() { assertThat(teleporter1.allowsConnection( Direction.BOTTOM)).isFalse(); } |
Teleporter extends Tileable implements TileableListener { @Override public boolean accepts(Direction direction, Marble marble) { return track.accepts(direction, marble); } Teleporter(Track track); void setDestination(Teleporter destination); Track getTrack(); Teleporter getDestination(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); } | @Test public void acceptsLeft() { assertThat(teleporter1.accepts(Direction.LEFT, new Marble( MarbleType.GREEN))).isTrue(); } |
Teleporter extends Tileable implements TileableListener { public Track getTrack() { return track; } Teleporter(Track track); void setDestination(Teleporter destination); Track getTrack(); Teleporter getDestination(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); } | @Test public void getTrack() { assertThat(teleporter1.getTrack()).isEqualTo(inner); } |
Teleporter extends Tileable implements TileableListener { public Teleporter getDestination() { return destination; } Teleporter(Track track); void setDestination(Teleporter destination); Track getTrack(); Teleporter getDestination(); @Override boolean allowsConnection(Direction direction); @Override boolean accepts(Direction direction, Marble marble); @Override void accept(Direction direction, Marble marble); @Override void ballAccepted(Tileable tileable, Direction direction, Marble marble); @Override void ballDisposed(Tileable tileable, Direction direction, Marble marble); @Override void ballReleased(Tileable tileable, Direction direction, Marble marble); } | @Test public void getDestination() { assertThat(teleporter1.getDestination()).isEqualTo(teleporter2); assertThat(teleporter2.getDestination()).isEqualTo(teleporter1); } |
UriUtils { public static void checkUrlIsValid(String url) throws IllegalArgumentException { logger.debug("Url is : {}",url); boolean urlIsValid; Pattern p = Pattern.compile(URL_PATTERN); Matcher m = p.matcher(url); if (!m.matches()) { p = Pattern.compile(IP_ADDRESS_PATTERN); m = p.matcher(url); urlIsValid = m.matches(); }else{ urlIsValid = true; } if(!urlIsValid){ throw new IllegalArgumentException("Url is not valid"); } URI.create(url); logger.debug("urlIsValid : {}",urlIsValid); } static void checkUrlIsValid(String url); final static String URL_PATTERN; final static String IP_ADDRESS_PATTERN; } | @Test public void checkUriIsValidTest() { String url = "http: UriUtils.checkUrlIsValid(url); url = "https: UriUtils.checkUrlIsValid(url); url = "http: UriUtils.checkUrlIsValid(url); url = "https: UriUtils.checkUrlIsValid(url); url = "http: UriUtils.checkUrlIsValid(url); url = "http: UriUtils.checkUrlIsValid(url); url = "http: UriUtils.checkUrlIsValid(url); url = "https: UriUtils.checkUrlIsValid(url); }
@Test(expected=IllegalArgumentException.class) public void spaceIsNotValidTest(){ String url = "http: UriUtils.checkUrlIsValid(url); }
@Test(expected=IllegalArgumentException.class) public void noHttpIsNotValidTest(){ String url = "badurl.net"; UriUtils.checkUrlIsValid(url); }
@Test(expected=IllegalArgumentException.class) public void plainStringIsNotValidTest(){ String url = "toto"; UriUtils.checkUrlIsValid(url); } |
G2Client { public void loginToGallery(String galleryUrl, String user, String password) throws ImpossibleToLoginException { sessionCookies.clear(); sessionCookies.add(new BasicClientCookie("", "")); List<NameValuePair> sb = new ArrayList<NameValuePair>(); sb.add(LOGIN_CMD_NAME_VALUE_PAIR); sb.add(new BasicNameValuePair("g2_form[uname]", "" + user)); sb.add(new BasicNameValuePair("g2_form[password]", "" + password)); HashMap<String, String> properties; try { properties = sendCommandToGallery(galleryUrl, sb, null); } catch (GalleryConnectionException e) { throw new ImpossibleToLoginException(e); } authToken = null; if (properties.get("status") != null) { if (properties.get("status").equals(GR_STAT_SUCCESS)) { authToken = properties.get("auth_token"); } else { throw new ImpossibleToLoginException( properties.get("status_text")); } } if(properties.isEmpty()){ throw new ImpossibleToLoginException("The Gallery did not return login properties; check your gallery installation and/or your settings" ); } } G2Client(String userAgent); HashMap<String, String> fetchImages(String galleryUrl, int albumName); HashMap<String, String> fetchAlbums(String galleryUrl); void loginToGallery(String galleryUrl, String user, String password); InputStream getInputStreamFromUrl(String url); int createNewAlbum(String galleryUrl, int parentAlbumName,
String albumName, String albumTitle, String albumDescription); int sendImageToGallery(String galleryUrl, int albumName,
File imageFile, String imageName, String summary, String description); String getAuthToken(); void setAuthToken(String authToken); List<Cookie> getSessionCookies(); Collection<G2Picture> extractG2PicturesFromProperties(
HashMap<String, String> fetchImages); Map<Integer, Album> getAllAlbums(String galleryUrl); Map<Integer, G2Album> extractAlbumFromProperties(
HashMap<String, String> albumsProperties); Album organizeAlbumsHierarchy(Map<Integer, G2Album> albums); void setRootAlbum(G2Album rootAlbum); G2Album getRootAlbum(); } | @Test(expected = ImpossibleToLoginException.class) public void loginToGalleryTestFailBecauseUrlIsWrong() throws GalleryConnectionException { g2ConnectionUtils.loginToGallery("http: "hackerPassword"); }
@Test public void loginToGalleryTest() throws GalleryConnectionException { g2ConnectionUtils .loginToGallery(galleryUrl, user, password); HashMap<String, String> fetchAlbums = g2ConnectionUtils .fetchAlbums(galleryUrl); boolean found = false; for (Entry<String, String> entry : fetchAlbums.entrySet()) { if (entry.getValue().equals("G2AndroidSecretAlbum")) { found = true; } } assertEquals(true, found); }
@Test(expected=ImpossibleToLoginException.class) public void loginToGalleryTest__badPassword() throws GalleryConnectionException { g2ConnectionUtils.loginToGallery(galleryUrl, "hacker", "hackerPassword"); }
@Test(expected=ImpossibleToLoginException.class) public void loginToGalleryTest__galleryDoesNotAnswerWithProperties__issue24() throws GalleryConnectionException { g2ConnectionUtils.loginToGallery("http: "g2android", "g2android"); } |
G2Client { public int sendImageToGallery(String galleryUrl, int albumName, File imageFile, String imageName, String summary, String description) throws GalleryConnectionException { int imageCreatedName = 0; MultipartEntity multiPartEntity = createMultiPartEntityForSendImageToGallery( albumName, imageFile, imageName, summary, description); HashMap<String, String> properties = sendCommandToGallery(galleryUrl, null, multiPartEntity); for (Entry<String, String> entry : properties.entrySet()) { if (entry.getKey().equals(ITEM_NAME)) { imageCreatedName = new Integer(entry.getValue()).intValue(); break; } if (entry.getValue().contains(FAILED)) { throw new GalleryConnectionException(UPLOAD_FAILED); } } return imageCreatedName; } G2Client(String userAgent); HashMap<String, String> fetchImages(String galleryUrl, int albumName); HashMap<String, String> fetchAlbums(String galleryUrl); void loginToGallery(String galleryUrl, String user, String password); InputStream getInputStreamFromUrl(String url); int createNewAlbum(String galleryUrl, int parentAlbumName,
String albumName, String albumTitle, String albumDescription); int sendImageToGallery(String galleryUrl, int albumName,
File imageFile, String imageName, String summary, String description); String getAuthToken(); void setAuthToken(String authToken); List<Cookie> getSessionCookies(); Collection<G2Picture> extractG2PicturesFromProperties(
HashMap<String, String> fetchImages); Map<Integer, Album> getAllAlbums(String galleryUrl); Map<Integer, G2Album> extractAlbumFromProperties(
HashMap<String, String> albumsProperties); Album organizeAlbumsHierarchy(Map<Integer, G2Album> albums); void setRootAlbum(G2Album rootAlbum); G2Album getRootAlbum(); } | @Test @Ignore public void sendImageToGalleryTest() throws GalleryConnectionException { g2ConnectionUtils.loginToGallery(galleryUrl, user, password); File imageFile = new File("image.png"); int newItemId = g2ConnectionUtils.sendImageToGallery(galleryUrl, 174, imageFile, "plouf", "Summary from test", "Description from test"); assertTrue(newItemId != 0); } |
G2Client { public int createNewAlbum(String galleryUrl, int parentAlbumName, String albumName, String albumTitle, String albumDescription) throws GalleryConnectionException { int newAlbumName = 0; List<NameValuePair> nameValuePairsFetchImages = new ArrayList<NameValuePair>(); nameValuePairsFetchImages.add(CREATE_ALBUM_CMD_NAME_VALUE_PAIR); nameValuePairsFetchImages.add(new BasicNameValuePair( "g2_form[set_albumName]", "" + parentAlbumName)); nameValuePairsFetchImages.add(new BasicNameValuePair( "g2_form[newAlbumName]", albumName)); nameValuePairsFetchImages.add(new BasicNameValuePair( "g2_form[newAlbumTitle]", albumTitle)); nameValuePairsFetchImages.add(new BasicNameValuePair( "g2_form[newAlbumDesc]", albumDescription)); HashMap<String, String> properties = sendCommandToGallery(galleryUrl, nameValuePairsFetchImages, null); for (Entry<String, String> entry : properties.entrySet()) { if (entry.getKey().equals(ALBUM_NAME)) { newAlbumName = new Integer(entry.getValue()).intValue(); } } return newAlbumName; } G2Client(String userAgent); HashMap<String, String> fetchImages(String galleryUrl, int albumName); HashMap<String, String> fetchAlbums(String galleryUrl); void loginToGallery(String galleryUrl, String user, String password); InputStream getInputStreamFromUrl(String url); int createNewAlbum(String galleryUrl, int parentAlbumName,
String albumName, String albumTitle, String albumDescription); int sendImageToGallery(String galleryUrl, int albumName,
File imageFile, String imageName, String summary, String description); String getAuthToken(); void setAuthToken(String authToken); List<Cookie> getSessionCookies(); Collection<G2Picture> extractG2PicturesFromProperties(
HashMap<String, String> fetchImages); Map<Integer, Album> getAllAlbums(String galleryUrl); Map<Integer, G2Album> extractAlbumFromProperties(
HashMap<String, String> albumsProperties); Album organizeAlbumsHierarchy(Map<Integer, G2Album> albums); void setRootAlbum(G2Album rootAlbum); G2Album getRootAlbum(); } | @Test public void createNewAlbumTest() throws GalleryConnectionException { g2ConnectionUtils.loginToGallery(galleryUrl, user, password); Random random = new Random(); int randomInt = random.nextInt(); String albumName = "UnitTestAlbumNumber" + randomInt; String albumTitle = "Unit Test Album"; String albumDescription = "Yet another Unit Test Album !"; int newAlbumName = g2ConnectionUtils.createNewAlbum(galleryUrl, 174, albumName, albumTitle, albumDescription); assertTrue(newAlbumName != 0); } |
G2Client { public Collection<G2Picture> extractG2PicturesFromProperties( HashMap<String, String> fetchImages) throws GalleryConnectionException { Map<Integer, G2Picture> picturesMap = new HashMap<Integer, G2Picture>(); List<Integer> tmpImageNumbers = new ArrayList<Integer>(); int imageNumber = 0; for (Entry<String, String> entry : fetchImages.entrySet()) { if (entry.getKey().contains("image") && !entry.getKey().contains("image_count")) { imageNumber = new Integer(entry.getKey().substring( entry.getKey().lastIndexOf(".") + 1)); G2Picture picture = null; if (!tmpImageNumbers.contains(imageNumber)) { picture = new G2Picture(); picture.setId(imageNumber); picturesMap.put(imageNumber, picture); tmpImageNumbers.add(imageNumber); } else { picture = picturesMap.get(imageNumber); } try { if (entry.getKey().contains("image.title.")) { picture.setTitle(entry.getValue()); } else if (entry.getKey().contains("image.thumbName.")) { picture.setThumbName(entry.getValue()); } else if (entry.getKey().contains("image.thumb_width.")) { picture.setThumbWidth(new Integer(entry.getValue())); } else if (entry.getKey().contains("image.thumb_height.")) { picture.setThumbHeight(new Integer(entry.getValue())); } else if (entry.getKey().contains("image.resizedName.")) { picture.setResizedName(entry.getValue()); } else if (entry.getKey().contains("image.resized_width.")) { picture.setResizedWidth(new Integer(entry.getValue())); } else if (entry.getKey().contains("image.resized_height.")) { picture.setResizedHeight(new Integer(entry.getValue())); } else if (entry.getKey().contains("image.name.")) { picture.setName( entry.getValue()); } else if (entry.getKey().contains("image.raw_width.")) { picture.setRawWidth(new Integer(entry.getValue())); } else if (entry.getKey().contains("image.raw_height.")) { picture.setRawHeight(new Integer(entry.getValue())); } else if (entry.getKey().contains("image.raw_filesize.")) { picture.setRawFilesize(new Integer(entry.getValue())); } else if (entry.getKey().contains("image.caption.")) { picture.setCaption(entry.getValue()); } else if (entry.getKey().contains("image.forceExtension.")) { picture.setForceExtension(entry.getValue()); } else if (entry.getKey().contains("image.hidden.")) { picture.setHidden(Boolean.valueOf(entry.getValue())); } } catch (NumberFormatException nfe) { throw new GalleryConnectionException(nfe); } } } return picturesMap.values(); } G2Client(String userAgent); HashMap<String, String> fetchImages(String galleryUrl, int albumName); HashMap<String, String> fetchAlbums(String galleryUrl); void loginToGallery(String galleryUrl, String user, String password); InputStream getInputStreamFromUrl(String url); int createNewAlbum(String galleryUrl, int parentAlbumName,
String albumName, String albumTitle, String albumDescription); int sendImageToGallery(String galleryUrl, int albumName,
File imageFile, String imageName, String summary, String description); String getAuthToken(); void setAuthToken(String authToken); List<Cookie> getSessionCookies(); Collection<G2Picture> extractG2PicturesFromProperties(
HashMap<String, String> fetchImages); Map<Integer, Album> getAllAlbums(String galleryUrl); Map<Integer, G2Album> extractAlbumFromProperties(
HashMap<String, String> albumsProperties); Album organizeAlbumsHierarchy(Map<Integer, G2Album> albums); void setRootAlbum(G2Album rootAlbum); G2Album getRootAlbum(); } | @Test public void extractG2PictureFromPropertiesTest() throws GalleryConnectionException { HashMap<String, String> fetchImages = new HashMap<String, String>(); fetchImages.put("image.thumb_height.393", "150"); fetchImages.put("image.title.393", "picture.jpg"); fetchImages.put("image.resizedName.393", "12600"); fetchImages.put("image.resized_width.393", "800"); fetchImages.put("image.resized_height.393", "600"); fetchImages.put("image.raw_height.393", "2848"); fetchImages.put("image.caption.393", ""); fetchImages.put("image.name.393", "12598"); fetchImages.put("image.thumbName.393", "12599"); fetchImages.put("image.thumb_width.393", "150"); fetchImages.put("image.raw_width.393", "4288"); fetchImages.put("image.raw_filesize.393", "3400643"); fetchImages.put("image.caption.393", "caption"); fetchImages.put("image.forceExtension.393", "jpg"); fetchImages.put("image.hidden.393", "true"); fetchImages.put("image.clicks.393", "45"); fetchImages.put("image.capturedate.year.393", "2009"); fetchImages.put("image.capturedate.mon.393", "10"); fetchImages.put("image.capturedate.mday.393", "19"); fetchImages.put("image.capturedate.hours.393", "22"); fetchImages.put("image.capturedate.minutes.393", "45"); fetchImages.put("image.capturedate.seconds.393", "48"); fetchImages.put("image_count", "437"); fetchImages .put("baseurl", "http: Collection<G2Picture> pictures = g2ConnectionUtils .extractG2PicturesFromProperties(fetchImages); G2Picture picture = pictures.iterator().next(); assertEquals(150, picture.getThumbHeight()); assertEquals("picture.jpg", picture.getTitle()); assertEquals("12600", picture.getResizedName()); assertEquals(800, picture.getResizedWidth()); assertEquals(2848, picture.getRawHeight()); assertEquals("12598", picture.getName()); assertEquals("12599", picture.getThumbName()); assertEquals(150, picture.getThumbWidth()); assertEquals(4288, picture.getRawWidth()); assertEquals("caption", picture.getCaption()); assertEquals("jpg", picture.getForceExtension()); assertEquals(true, picture.isHidden()); } |
G2Client { public Map<Integer, G2Album> extractAlbumFromProperties( HashMap<String, String> albumsProperties) throws GalleryConnectionException { int albumNumber = 0; Map<Integer, G2Album> albumsMap = new HashMap<Integer, G2Album>(); List<Integer> tmpAlbumNumbers = new ArrayList<Integer>(); for (Entry<String, String> entry : albumsProperties.entrySet()) { if (entry.getKey().contains("album") && !entry.getKey().contains("debug") && !entry.getKey().contains("album_count")) { albumNumber = new Integer(entry.getKey().substring( entry.getKey().lastIndexOf(".") + 1)); G2Album album = null; if (!tmpAlbumNumbers.contains(albumNumber)) { album = new G2Album(); album.setId(albumNumber); albumsMap.put(albumNumber, album); tmpAlbumNumbers.add(albumNumber); } else { album = albumsMap.get(albumNumber); } try { if (entry.getKey().contains("album.title.")) { String title = StringEscapeUtils.unescapeHtml(entry .getValue()); title = StringEscapeUtils.unescapeJava(title); album.setTitle(title); } else if (entry.getKey().contains("album.name.")) { album.setName(new Integer(entry.getValue())); } else if (entry.getKey().contains("album.summary.")) { album.setSummary(entry.getValue()); } else if (entry.getKey().contains("album.parent.")) { album.setParentName(new Integer(entry.getValue())); } else if (entry.getKey().contains( "album.info.extrafields.")) { album.setExtrafields(entry.getValue()); } } catch (NumberFormatException nfe) { throw new GalleryConnectionException(nfe); } } } return albumsMap; } G2Client(String userAgent); HashMap<String, String> fetchImages(String galleryUrl, int albumName); HashMap<String, String> fetchAlbums(String galleryUrl); void loginToGallery(String galleryUrl, String user, String password); InputStream getInputStreamFromUrl(String url); int createNewAlbum(String galleryUrl, int parentAlbumName,
String albumName, String albumTitle, String albumDescription); int sendImageToGallery(String galleryUrl, int albumName,
File imageFile, String imageName, String summary, String description); String getAuthToken(); void setAuthToken(String authToken); List<Cookie> getSessionCookies(); Collection<G2Picture> extractG2PicturesFromProperties(
HashMap<String, String> fetchImages); Map<Integer, Album> getAllAlbums(String galleryUrl); Map<Integer, G2Album> extractAlbumFromProperties(
HashMap<String, String> albumsProperties); Album organizeAlbumsHierarchy(Map<Integer, G2Album> albums); void setRootAlbum(G2Album rootAlbum); G2Album getRootAlbum(); } | @Test public void extractAlbumFromPropertiesTest() throws GalleryConnectionException { HashMap<String, String> albumsProperties = new HashMap<String, String>(); albumsProperties.put("album.name.1", "10726"); albumsProperties.put("album.title.1", "Brunch"); albumsProperties.put("album.summary.1", "Le Dimanche de 11h à 15h avait lieu le brunch"); albumsProperties.put("album.parent.1", "7"); albumsProperties.put("album.perms.add.1", "false"); albumsProperties.put("album.perms.write.1", "false"); albumsProperties.put("album.perms.del_alb.1", "false"); albumsProperties.put("album.perms.create_sub.1", "false"); albumsProperties.put("album.info.extrafields.1", "Summary,Description"); albumsProperties.put("debug_time_generate", "0,075s"); albumsProperties.put("can_create_root", "false"); albumsProperties.put("album_count", "9"); albumsProperties.put("status", "0"); Collection<G2Album> albums = g2ConnectionUtils.extractAlbumFromProperties( albumsProperties).values(); G2Album album = albums.iterator().next(); assertEquals(1, album.getId()); assertEquals("Brunch", album.getTitle()); assertEquals(10726, album.getName()); assertEquals("Le Dimanche de 11h à 15h avait lieu le brunch", album .getSummary()); assertEquals(7, album.getParentName()); assertEquals("Summary,Description", album.getExtrafields()); } |
G2Client { public Album organizeAlbumsHierarchy(Map<Integer, G2Album> albums) { Album rootAlbum = null; Map<Integer, Album> albumss = new HashMap<Integer, Album>(); for (Integer key : albums.keySet()) { albumss.put(key, G2ConvertUtils.g2AlbumToAlbum(albums.get(key))); } for (Album album : albumss.values()) { if (album.getParentName() == 0) { rootAlbum = album; } int parentName = album.getParentName(); int parentId = 0; for (Album album2 : albumss.values()) { if (album2.getName() == parentName) { parentId = album2.getId(); break; } } Album parent = albumss.get(parentId); album.setParent(parent); if (parent != null) { parent.getSubAlbums().add(album); } } return rootAlbum; } G2Client(String userAgent); HashMap<String, String> fetchImages(String galleryUrl, int albumName); HashMap<String, String> fetchAlbums(String galleryUrl); void loginToGallery(String galleryUrl, String user, String password); InputStream getInputStreamFromUrl(String url); int createNewAlbum(String galleryUrl, int parentAlbumName,
String albumName, String albumTitle, String albumDescription); int sendImageToGallery(String galleryUrl, int albumName,
File imageFile, String imageName, String summary, String description); String getAuthToken(); void setAuthToken(String authToken); List<Cookie> getSessionCookies(); Collection<G2Picture> extractG2PicturesFromProperties(
HashMap<String, String> fetchImages); Map<Integer, Album> getAllAlbums(String galleryUrl); Map<Integer, G2Album> extractAlbumFromProperties(
HashMap<String, String> albumsProperties); Album organizeAlbumsHierarchy(Map<Integer, G2Album> albums); void setRootAlbum(G2Album rootAlbum); G2Album getRootAlbum(); } | @Test public void organizeAlbumsHierarchy() throws Exception { Map<Integer, G2Album> albums = new HashMap<Integer, G2Album>(); G2Album album = new G2Album(); album.setName(6); album.setId(600); album.setParentName(20); albums.put(album.getId(), album); album = new G2Album(); album.setName(3); album.setId(300); album.setParentName(10); albums.put(album.getId(), album); album = new G2Album(); album.setName(4); album.setId(400); album.setParentName(10); albums.put(album.getId(), album); album = new G2Album(); album.setName(10); album.setId(100); album.setParentName(0); albums.put(album.getId(), album); album = new G2Album(); album.setName(5); album.setId(500); album.setParentName(20); albums.put(album.getId(), album); album = new G2Album(); album.setName(20); album.setId(200); album.setParentName(10); albums.put(album.getId(), album); Album finalAlbum = g2ConnectionUtils.organizeAlbumsHierarchy(albums); Collections.sort(finalAlbum.getSubAlbums(), new Comparator<Album>() { public int compare(final Album albumA, final Album albumB) { return Integer.valueOf(albumA.getName()).compareTo(Integer.valueOf(albumB.getName())); } }); assertEquals(10, finalAlbum.getName()); assertEquals(3, finalAlbum.getSubAlbums().get(0).getName()); assertEquals(4, finalAlbum.getSubAlbums().get(1).getName()); assertEquals(20, finalAlbum.getSubAlbums().get(2).getName()); assertEquals(5, finalAlbum.getSubAlbums().get(2).getSubAlbums().get(0).getName()); assertEquals(6, finalAlbum.getSubAlbums().get(2).getSubAlbums().get(1).getName()); } |
G2ConvertUtils { public static Album g2AlbumToAlbum(G2Album g2Album) { if(g2Album==null){ return null; } Album album = new Album(); album.setId(g2Album.getId()); album.setName(g2Album.getName()); album.setTitle(g2Album.getTitle()); album.setSummary(g2Album.getSummary()); album.setParentName(g2Album.getParentName()); return album; } static Album g2AlbumToAlbum(G2Album g2Album); static Picture g2PictureToPicture(G2Picture g2Picture, String galleryUrl); static String getBaseUrl(String galleryUrl); static boolean isEmbeddedGallery(String url); } | @Test public void g2AlbumToAlbum() throws IOException, JSONException { G2Album g2Album = new G2Album(); g2Album.setId(1024); g2Album.setTitle("Title"); g2Album.setName(12); g2Album.setSummary("Summary"); g2Album.setParentName(1); g2Album.setExtrafields("extrafields"); Album album = G2ConvertUtils.g2AlbumToAlbum(g2Album); Album expectedAlbum = new Album(); expectedAlbum.setId(1024); expectedAlbum.setTitle("Title"); expectedAlbum.setName(12); expectedAlbum.setSummary("Summary"); expectedAlbum.setParentName(1); expectedAlbum.setExtrafields("extrafields"); Assert.assertEquals(expectedAlbum, album); } |
G2ConvertUtils { public static Picture g2PictureToPicture(G2Picture g2Picture, String galleryUrl) { if(g2Picture==null ){ return null; } String baseUrl = getBaseUrl(galleryUrl); Picture picture = new Picture(); picture.setId(g2Picture.getId()); picture.setTitle(g2Picture.getCaption()); picture.setFileName(g2Picture.getTitle()); picture.setThumbUrl( baseUrl + g2Picture.getThumbName()); picture.setThumbWidth(g2Picture.getThumbWidth()); picture.setThumbHeight(g2Picture.getThumbHeight()); if(g2Picture.getResizedName()!=null){ picture.setResizedUrl(baseUrl +g2Picture.getResizedName()); } picture.setResizedWidth(g2Picture.getResizedWidth()); picture.setResizedHeight(g2Picture.getResizedHeight()); picture.setFileUrl(baseUrl +g2Picture.getName()); picture.setPublicUrl(baseUrl +g2Picture.getName()); picture.setFileSize(g2Picture.getRawFilesize()); picture.setHeight(g2Picture.getRawHeight()); picture.setWidth(g2Picture.getRawWidth()); return picture; } static Album g2AlbumToAlbum(G2Album g2Album); static Picture g2PictureToPicture(G2Picture g2Picture, String galleryUrl); static String getBaseUrl(String galleryUrl); static boolean isEmbeddedGallery(String url); } | @Test public void g2PictureToPicture() throws IOException, JSONException { G2Picture g2Picture = new G2Picture(); g2Picture.setTitle("Title.jpg"); g2Picture.setId(10214); g2Picture.setName("1"); g2Picture.setThumbName("2"); g2Picture.setThumbWidth(320); g2Picture.setThumbHeight(480); g2Picture.setResizedName("3"); g2Picture.setResizedWidth(480); g2Picture.setResizedHeight(640); g2Picture.setRawWidth(768); g2Picture.setRawHeight(1024); g2Picture.setRawFilesize(10241024); g2Picture.setCaption("Title"); g2Picture.setForceExtension("true"); g2Picture.setHidden(true); String galleryUrl = "http: Picture picture = G2ConvertUtils.g2PictureToPicture(g2Picture, galleryUrl); Picture expectedPicture = new Picture(); expectedPicture.setId(10214L); expectedPicture.setTitle("Title"); expectedPicture.setFileName("Title.jpg"); expectedPicture.setFileUrl(galleryUrl + "/" + G2ConvertUtils.BASE_URL_DEF + 1); expectedPicture.setWidth(768); expectedPicture.setHeight(1024); expectedPicture.setFileSize(10241024); expectedPicture.setThumbUrl(galleryUrl + "/" + G2ConvertUtils.BASE_URL_DEF + 2); expectedPicture.setThumbWidth(320); expectedPicture.setThumbHeight(480); expectedPicture.setResizedUrl(galleryUrl + "/" + G2ConvertUtils.BASE_URL_DEF + 3); expectedPicture.setResizedWidth(480); expectedPicture.setResizedHeight(640); expectedPicture.setPublicUrl(galleryUrl + "/" + G2ConvertUtils.BASE_URL_DEF + 1); Assert.assertEquals(expectedPicture, picture); }
@Test public void g2PictureToPicture__noresize() throws IOException, JSONException { G2Picture g2Picture = new G2Picture(); g2Picture.setTitle("Title.jpg"); g2Picture.setId(10214); g2Picture.setName("1"); g2Picture.setThumbName("2"); g2Picture.setThumbWidth(320); g2Picture.setThumbHeight(480); g2Picture.setResizedName(null); g2Picture.setResizedWidth(480); g2Picture.setResizedHeight(640); g2Picture.setRawWidth(768); g2Picture.setRawHeight(1024); g2Picture.setRawFilesize(10241024); g2Picture.setCaption("Title"); g2Picture.setForceExtension("true"); g2Picture.setHidden(true); String galleryUrl = "http: Picture picture = G2ConvertUtils.g2PictureToPicture(g2Picture, galleryUrl); Picture expectedPicture = new Picture(); expectedPicture.setId(10214L); expectedPicture.setTitle("Title"); expectedPicture.setFileName("Title.jpg"); expectedPicture.setFileUrl(galleryUrl + "/" + G2ConvertUtils.BASE_URL_DEF + 1); expectedPicture.setWidth(768); expectedPicture.setHeight(1024); expectedPicture.setFileSize(10241024); expectedPicture.setThumbUrl(galleryUrl + "/" + G2ConvertUtils.BASE_URL_DEF + 2); expectedPicture.setThumbWidth(320); expectedPicture.setThumbHeight(480); expectedPicture.setResizedUrl(null); expectedPicture.setResizedWidth(480); expectedPicture.setResizedHeight(640); expectedPicture.setPublicUrl(galleryUrl + "/" + G2ConvertUtils.BASE_URL_DEF + 1); Assert.assertEquals(expectedPicture, picture); } |
JiwigoConvertUtils { public static Album jiwigoCategoryToAlbum(Category jiwigoCategory) { if(jiwigoCategory==null){ return null; } Album album = new Album(); album.setId(jiwigoCategory.getIdentifier()); album.setName(jiwigoCategory.getIdentifier()); album.setTitle(jiwigoCategory.getName()); album.setParentName(jiwigoCategory.getDirectParent()==null?0:jiwigoCategory.getDirectParent()); return album; } static Album jiwigoCategoryToAlbum(Category jiwigoCategory); static Picture jiwigoImageToPicture(Image jiwigoImage); static Album categoriesToAlbum(List<Category> categories); } | @Test public void jiwigoCategoryToAlbum() { Category jiwigoCategory = new Category(); jiwigoCategory.setIdentifier(43); jiwigoCategory.setName("MyAlbum"); jiwigoCategory.setDirectParent(1); Album album = JiwigoConvertUtils.jiwigoCategoryToAlbum(jiwigoCategory); Album expectedAlbum = new Album(); expectedAlbum.setId(43); expectedAlbum.setName(43); expectedAlbum.setTitle("MyAlbum"); expectedAlbum.setParentName(1); Assert.assertEquals(expectedAlbum, album); } |
JiwigoConvertUtils { public static Picture jiwigoImageToPicture(Image jiwigoImage) { if(jiwigoImage==null ){ return null; } Picture picture = new Picture(); picture.setId(jiwigoImage.getIdentifier()); picture.setTitle(jiwigoImage.getName()); picture.setFileName(jiwigoImage.getFile()); picture.setThumbUrl(jiwigoImage.getThumbnailUrl()); picture.setFileUrl(jiwigoImage.getUrl()); picture.setPublicUrl(jiwigoImage.getUrl()); picture.setHeight(jiwigoImage.getHeight()); picture.setWidth(jiwigoImage.getWidth()); return picture; } static Album jiwigoCategoryToAlbum(Category jiwigoCategory); static Picture jiwigoImageToPicture(Image jiwigoImage); static Album categoriesToAlbum(List<Category> categories); } | @Test public void jiwigoImageToPicture() { Image jiwigoImage = new Image(); jiwigoImage.setName("Title"); jiwigoImage.setFile("Title.jpg"); jiwigoImage.setIdentifier(10214); jiwigoImage .setThumbnailUrl("http: jiwigoImage.setWidth(768); jiwigoImage.setHeight(1024); jiwigoImage .setUrl("http: Picture picture = JiwigoConvertUtils.jiwigoImageToPicture(jiwigoImage); Picture expectedPicture = new Picture(); expectedPicture.setId(10214L); expectedPicture.setTitle("Title"); expectedPicture.setFileName("Title.jpg"); expectedPicture .setFileUrl("http: expectedPicture .setPublicUrl("http: expectedPicture.setWidth(768); expectedPicture.setHeight(1024); expectedPicture .setThumbUrl("http: Assert.assertEquals(expectedPicture, picture); } |
JiwigoConvertUtils { public static Album categoriesToAlbum(List<Category> categories){ Album resultAlbum = new Album(); resultAlbum.setName(0); resultAlbum.setId(0); Album album; for (Category category : categories) { album = jiwigoCategoryToAlbum(category); if(category.getParentCategories().size()==0){ resultAlbum.getSubAlbums().add(album); } else{ Album parentAlbum = AlbumUtils.findAlbumFromAlbumName(resultAlbum, category.getParentCategories().get(0).getIdentifier()); parentAlbum.getSubAlbums().add(album); } } return resultAlbum; } static Album jiwigoCategoryToAlbum(Category jiwigoCategory); static Picture jiwigoImageToPicture(Image jiwigoImage); static Album categoriesToAlbum(List<Category> categories); } | @Test public void categoriesToAlbum() { List<Category> categories = new ArrayList<Category>(); Category coaticook = new Category(); coaticook.setName("coaticook"); coaticook.setIdentifier(1); Category barrage = new Category(); barrage.setName("barrage"); barrage.setIdentifier(2); Category barrage2 = new Category(); barrage2.setName("barrage2"); barrage2.setIdentifier(20); Category sousBarrage = new Category(); sousBarrage.setName("sous barrage"); sousBarrage.setIdentifier(3); coaticook.getChildCategories().add(barrage); coaticook.getChildCategories().add(barrage2); barrage.getChildCategories().add(sousBarrage); sousBarrage.getParentCategories().add(barrage); barrage.getParentCategories().add(coaticook); barrage2.getParentCategories().add(coaticook); categories.add(coaticook); categories.add(barrage); categories.add(barrage2); categories.add(sousBarrage); Album resultAlbum = JiwigoConvertUtils.categoriesToAlbum(categories); Assert.assertEquals(0, resultAlbum.getName()); Assert.assertEquals(1, resultAlbum.getSubAlbums().get(0).getName()); Assert.assertEquals(2, resultAlbum.getSubAlbums().get(0).getSubAlbums().get(0).getName()); Assert.assertEquals(20, resultAlbum.getSubAlbums().get(0).getSubAlbums().get(1).getName()); Assert.assertEquals(3, resultAlbum.getSubAlbums().get(0).getSubAlbums().get(0).getSubAlbums().get(0).getName()); } |
G3Client implements IG3Client { public Item getItem(int itemId) throws G3GalleryException { Item item = null; String stringResult = sendHttpRequest(INDEX_PHP_REST_ITEM + itemId, new ArrayList<NameValuePair>(), GET, null); try { JSONObject jsonResult = (JSONObject) new JSONTokener(stringResult) .nextValue(); item = ItemUtils.parseJSONToItem(jsonResult); } catch (JSONException e) { throw new G3GalleryException(e.getMessage()); }catch (ClassCastException e) { throw new G3GalleryException("The Gallery returned an unexpected result when trying to load albums/photos; please check for info on the ReGalAndroid project page"+e.getMessage()); } return item; } G3Client(String galleryUrl, String userAgent); Item getItem(int itemId); int createItem(Entity entity, File file); void updateItem(Entity entity); void deleteItem(int itemId); String getApiKey(); List<Item> getAlbumAndSubAlbumsAndPictures(int albumId); List<Item> getAlbumAndSubAlbums(int albumId); List<Item> getPictures(int albumId); InputStream getPhotoInputStream(String url); void setPassword(String password); void setUsername(String username); void setExistingApiKey(String existingApiKey); String getExistingApiKey(); boolean isUsingRewrittenUrls(); void setUsingRewrittenUrls(boolean isUsingRewrittenUrls); } | @Test public void getItemTest__album() throws G3GalleryException { Item item1 = itemClient.getItem(1); assertEquals("Gallery", item1.getEntity().getTitle()); } |
G3Client implements IG3Client { public String getApiKey() throws G3GalleryException { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("user", username)); nameValuePairs.add(new BasicNameValuePair("password", password)); String jsonResult = sendHttpRequest(INDEX_PHP_REST, nameValuePairs, POST, null); String key = ItemUtils.convertJsonResultToApiKey(jsonResult); if(!key.matches("[a-fA-F0-9]+")){ throw new G3GalleryException("The Gallery returned an unexpected result when trying to login; please check for info on the ReGalAndroid project page"); } return key; } G3Client(String galleryUrl, String userAgent); Item getItem(int itemId); int createItem(Entity entity, File file); void updateItem(Entity entity); void deleteItem(int itemId); String getApiKey(); List<Item> getAlbumAndSubAlbumsAndPictures(int albumId); List<Item> getAlbumAndSubAlbums(int albumId); List<Item> getPictures(int albumId); InputStream getPhotoInputStream(String url); void setPassword(String password); void setUsername(String username); void setExistingApiKey(String existingApiKey); String getExistingApiKey(); boolean isUsingRewrittenUrls(); void setUsingRewrittenUrls(boolean isUsingRewrittenUrls); } | @Test public void getApiKey() throws G3GalleryException { String apiKey = itemClient.getApiKey(); assertNotNull(apiKey); } |
G3Client implements IG3Client { public int createItem(Entity entity, File file) throws G3GalleryException { String resultUrl; NameValuePair nameValuePair; try { if (file == null) { nameValuePair = new BasicNameValuePair("entity", ItemUtils.convertAlbumEntityToJSON(entity)); } else { nameValuePair = new BasicNameValuePair("entity", ItemUtils.convertPhotoEntityToJSON(entity)); } List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(nameValuePair); resultUrl = sendHttpRequest( INDEX_PHP_REST_ITEM + entity.getParent(), nameValuePairs, POST, file); resultUrl = ItemUtils.convertJsonStringToUrl(resultUrl); } catch (JSONException e) { throw new G3GalleryException(e.getMessage()); } return ItemUtils.getItemIdFromUrl(resultUrl); } G3Client(String galleryUrl, String userAgent); Item getItem(int itemId); int createItem(Entity entity, File file); void updateItem(Entity entity); void deleteItem(int itemId); String getApiKey(); List<Item> getAlbumAndSubAlbumsAndPictures(int albumId); List<Item> getAlbumAndSubAlbums(int albumId); List<Item> getPictures(int albumId); InputStream getPhotoInputStream(String url); void setPassword(String password); void setUsername(String username); void setExistingApiKey(String existingApiKey); String getExistingApiKey(); boolean isUsingRewrittenUrls(); void setUsingRewrittenUrls(boolean isUsingRewrittenUrls); } | @Test public void createAlbum() throws G3GalleryException { Entity albumToCreate = new Entity(); albumToCreate.setName("AlbumName" + System.currentTimeMillis()); albumToCreate.setTitle("New Album"); albumToCreate.setParent(G2ANDROID_SECRET_ALBUM); createdAlbumId = itemClient.createItem(albumToCreate, null); assertNotNull(createdAlbumId); }
@Ignore @Test(expected = G3BadRequestException.class) public void createAlbum__already_exists() throws G3GalleryException { long albumSuffix = System.currentTimeMillis(); Entity albumToCreate = new Entity(); albumToCreate.setName("AlbumName" + albumSuffix); albumToCreate.setTitle("New Album"); albumToCreate.setParent(G2ANDROID_SECRET_ALBUM); itemClient.createItem(albumToCreate, null); itemClient.createItem(albumToCreate, null); } |
G3Client implements IG3Client { public List<Item> getAlbumAndSubAlbums(int albumId) throws G3GalleryException { List<Item> items = new ArrayList<Item>(); Item item = getItems(albumId, items, "album"); items.add(0, item); return items; } G3Client(String galleryUrl, String userAgent); Item getItem(int itemId); int createItem(Entity entity, File file); void updateItem(Entity entity); void deleteItem(int itemId); String getApiKey(); List<Item> getAlbumAndSubAlbumsAndPictures(int albumId); List<Item> getAlbumAndSubAlbums(int albumId); List<Item> getPictures(int albumId); InputStream getPhotoInputStream(String url); void setPassword(String password); void setUsername(String username); void setExistingApiKey(String existingApiKey); String getExistingApiKey(); boolean isUsingRewrittenUrls(); void setUsingRewrittenUrls(boolean isUsingRewrittenUrls); } | @Test public void getAlbumAndSubAlbumsTest() throws G3GalleryException { List<Item> subAlbums = itemClient.getAlbumAndSubAlbums(11); boolean foundRecentlyAddedAlbum = false; for (Item album : subAlbums) { if (album.getEntity().getId() == createdAlbumId) { foundRecentlyAddedAlbum = true; } } assertTrue(foundRecentlyAddedAlbum); subAlbums = itemClient.getAlbumAndSubAlbums(172); for (Item album : subAlbums) { if (!album.getEntity().getType().equals("album")) { fail("found some other types than album"); } } } |
G3Client implements IG3Client { public List<Item> getAlbumAndSubAlbumsAndPictures(int albumId) throws G3GalleryException { List<Item> items = getTree(albumId, "photo,album"); return items; } G3Client(String galleryUrl, String userAgent); Item getItem(int itemId); int createItem(Entity entity, File file); void updateItem(Entity entity); void deleteItem(int itemId); String getApiKey(); List<Item> getAlbumAndSubAlbumsAndPictures(int albumId); List<Item> getAlbumAndSubAlbums(int albumId); List<Item> getPictures(int albumId); InputStream getPhotoInputStream(String url); void setPassword(String password); void setUsername(String username); void setExistingApiKey(String existingApiKey); String getExistingApiKey(); boolean isUsingRewrittenUrls(); void setUsingRewrittenUrls(boolean isUsingRewrittenUrls); } | @Test public void getAlbumAndSubAlbumsAndPicturesTest() throws G3GalleryException { List<Item> albumAndSubAlbumsAndPictures = itemClient.getAlbumAndSubAlbumsAndPictures(172); Map<Integer,String> actual = new HashMap<Integer, String>(); for (Item album : albumAndSubAlbumsAndPictures) { actual.put(album.getEntity().getId(), album.getEntity().getName()); } Map<Integer,String> expected = new HashMap<Integer, String>(); expected.put(172, "Ottawa"); expected.put(173, "GP7AEU~V.JPG"); expected.put(178, "G3LKDB~A.JPG"); expected.put(179, "Canadian-parliament"); expected.put(180, "Canal Rideau"); assertEquals(expected, actual); } |
G3Client implements IG3Client { public List<Item> getPictures(int albumId) throws G3GalleryException { List<Item> items = new ArrayList<Item>(); getItems(albumId, items, "photo"); return items; } G3Client(String galleryUrl, String userAgent); Item getItem(int itemId); int createItem(Entity entity, File file); void updateItem(Entity entity); void deleteItem(int itemId); String getApiKey(); List<Item> getAlbumAndSubAlbumsAndPictures(int albumId); List<Item> getAlbumAndSubAlbums(int albumId); List<Item> getPictures(int albumId); InputStream getPhotoInputStream(String url); void setPassword(String password); void setUsername(String username); void setExistingApiKey(String existingApiKey); String getExistingApiKey(); boolean isUsingRewrittenUrls(); void setUsingRewrittenUrls(boolean isUsingRewrittenUrls); } | @Test public void getPicturesTest() throws G3GalleryException { List<Item> pictures = itemClient.getPictures(11); pictures = itemClient.getPictures(172); for (Item picture : pictures) { if (!picture.getEntity().getType().equals("photo")) { fail("found some other types than photo"); } if (picture.getEntity().getResizeHeight() == 0) { fail("could not found a resize_height info"); } } } |
G3Client implements IG3Client { public InputStream getPhotoInputStream(String url) throws G3GalleryException { InputStream content = null; String appendToGalleryUrl = url.substring(url.indexOf(galleryItemUrl)+galleryItemUrl.length()); try { content = requestToResponseEntity(appendToGalleryUrl, null, GET, null).getContent(); } catch (IllegalStateException e) { throw new G3GalleryException(e); } catch (UnsupportedEncodingException e) { throw new G3GalleryException(e); } catch (ClientProtocolException e) { throw new G3GalleryException(e); } catch (IOException e) { throw new G3GalleryException(e); } return content; } G3Client(String galleryUrl, String userAgent); Item getItem(int itemId); int createItem(Entity entity, File file); void updateItem(Entity entity); void deleteItem(int itemId); String getApiKey(); List<Item> getAlbumAndSubAlbumsAndPictures(int albumId); List<Item> getAlbumAndSubAlbums(int albumId); List<Item> getPictures(int albumId); InputStream getPhotoInputStream(String url); void setPassword(String password); void setUsername(String username); void setExistingApiKey(String existingApiKey); String getExistingApiKey(); boolean isUsingRewrittenUrls(); void setUsingRewrittenUrls(boolean isUsingRewrittenUrls); } | @Test public void getPhotoInputStream() throws IOException, G3GalleryException, MagicParseException, MagicMatchNotFoundException, MagicException { try { itemClient.getItem(createdPhotoId); }catch(G3ItemNotFoundException ex){ addPhoto(); } Item item1 = itemClient.getItem(createdPhotoId); String url = item1.getEntity().getFileUrl(); InputStream inputStream = itemClient.getPhotoInputStream(url); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteStreams.copy(inputStream, outputStream); byte[] photoDownloadedAsAByteArray = outputStream.toByteArray(); String contentType = Magic.getMagicMatch(photoDownloadedAsAByteArray).getMimeType(); assertEquals("image/png", contentType); } |
G3ConvertUtils { public static Album itemToAlbum(Item item) { if(item==null ||item.getEntity()==null){ return null; } Album album = new Album(); album.setId(item.getEntity().getId()); album.setName(item.getEntity().getId()); album.setTitle(item.getEntity().getTitle()); album.setSummary(item.getEntity().getDescription()); album.setAlbumUrl(item.getEntity().getWebUrl()); album.setAlbumCoverUrl(item.getEntity().getThumbUrl()); return album; } static Album itemToAlbum(Item item); static Picture itemToPicture(Item item); } | @Test public void itemToAlbum() throws IOException, JSONException { URL resource = Resources.getResource("get-album-1.json"); String string = Resources.toString(resource, Charsets.UTF_8); JSONObject jsonResult = (JSONObject) new JSONTokener(string) .nextValue(); Item albumItem = ItemUtils.parseJSONToItem(jsonResult); Album itemToAlbum = G3ConvertUtils.itemToAlbum(albumItem ); Album expectedAlbum = new Album(); expectedAlbum.setId(1); expectedAlbum.setName(1); expectedAlbum.setTitle("Gallery"); expectedAlbum.setSummary(""); expectedAlbum.setAlbumUrl("http: assertEquals(expectedAlbum, itemToAlbum); assertEquals("http: } |
G3ConvertUtils { public static Picture itemToPicture(Item item) { if(item==null ||item.getEntity()==null){ return null; } Picture picture = new Picture(); picture.setId(item.getEntity().getId()); picture.setTitle(item.getEntity().getTitle()); picture.setFileName(item.getEntity().getName()); picture.setThumbUrl(item.getEntity().getThumbUrl()); picture.setThumbWidth(item.getEntity().getThumbWidth()); picture.setThumbHeight(item.getEntity().getThumbHeight()); picture.setThumbSize(item.getEntity().getThumbSize()); picture.setResizedUrl(item.getEntity().getResizeUrl()); picture.setResizedWidth(item.getEntity().getResizeWidth()); picture.setResizedHeight(item.getEntity().getResizeHeight()); picture.setResizedSize(item.getEntity().getResizeSize()); picture.setFileUrl(item.getEntity().getFileUrl()); picture.setFileSize(item.getEntity().getFileSize()); picture.setHeight(item.getEntity().getHeight()); picture.setWidth(item.getEntity().getWidth()); picture.setPublicUrl(item.getEntity().getWebUrl()); return picture; } static Album itemToAlbum(Item item); static Picture itemToPicture(Item item); } | @Test public void itemToPicture() throws IOException, JSONException { URL resource = Resources.getResource("get-photo-2.json"); String string = Resources.toString(resource, Charsets.UTF_8); JSONObject jsonResult = (JSONObject) new JSONTokener(string) .nextValue(); Item pictureItem = ItemUtils.parseJSONToItem(jsonResult); Picture itemToPicture = G3ConvertUtils.itemToPicture(pictureItem ); Picture expectedPicture = new Picture(); expectedPicture.setId(2); expectedPicture.setTitle("March\u00e9 Bon secours"); expectedPicture.setFileName("marche-bonsecours.JPG"); expectedPicture.setThumbUrl("http: expectedPicture.setThumbWidth(150); expectedPicture.setThumbHeight(200); expectedPicture.setThumbSize(17151); expectedPicture.setResizedUrl("http: expectedPicture.setResizedWidth(480); expectedPicture.setResizedHeight(640); expectedPicture.setResizedSize(58309); expectedPicture.setFileUrl("http: expectedPicture.setWidth(2304); expectedPicture.setHeight(3072); expectedPicture.setFileSize(675745); expectedPicture.setPublicUrl("http: assertEquals(expectedPicture, itemToPicture); }
@Test public void itemToPicture__bug3_resize_size_false() throws IOException, JSONException { URL resource = Resources.getResource("get-photo-bug3_resize_size_false.json"); String string = Resources.toString(resource, Charsets.UTF_8); JSONObject jsonResult = (JSONObject) new JSONTokener(string) .nextValue(); Item pictureItem = ItemUtils.parseJSONToItem(jsonResult); Picture itemToPicture = G3ConvertUtils.itemToPicture(pictureItem ); Picture expectedPicture = new Picture(); expectedPicture.setId(502); expectedPicture.setTitle("graduation pics 427"); expectedPicture.setFileName("graduation pics 427.jpg"); expectedPicture.setResizedUrl("http: expectedPicture.setFileUrl("http: expectedPicture.setWidth(2576); expectedPicture.setHeight(1932); expectedPicture.setFileSize(1144458); expectedPicture.setPublicUrl("http: assertEquals(expectedPicture, itemToPicture); } |
ItemUtils { public static List<Item> parseJSONToMultipleItems(JSONObject jsonResult) throws JSONException{ JSONArray entityArrayJSON = jsonResult.getJSONArray("entity"); List<Item> list = new ArrayList<Item>(); for (int i = 0; i < entityArrayJSON.length(); i++) { Item item = new Item(); item.setUrl(((JSONObject) entityArrayJSON.get(i)).getString("url")); item.setEntity(parseJSONToEntity((JSONObject) entityArrayJSON.get(i))); list.add(item); } return list; } static Item parseJSONToItem(JSONObject jsonResult); static List<Item> parseJSONToMultipleItems(JSONObject jsonResult); static String convertAlbumEntityToJSON(Entity entity); static String convertPhotoEntityToJSON(Entity entity); static NameValuePair convertJSONStringToNameValuePair(String value); static String convertJsonResultToApiKey(String jsonResult); static String convertJsonStringToUrl(String jsonResult); static Integer getItemIdFromUrl(String createdAlbumUrl); } | @Test public void parseJSONToMultipleItems() throws IOException, JSONException { URL resource = Resources.getResource("tree-album-1.json"); String string = Resources.toString(resource, Charsets.UTF_8); JSONObject jsonResult = (JSONObject) new JSONTokener(string) .nextValue(); List<Item> items = ItemUtils.parseJSONToMultipleItems(jsonResult); assertEquals("http: assertEquals(1311332015,items.get(0).getEntity().getUpdated() ); assertEquals("http: assertEquals(1311332144,items.get(1).getEntity().getUpdated() ); assertEquals("http: assertEquals(1319238331,items.get(2).getEntity().getUpdated() ); } |
ItemUtils { public static Item parseJSONToItem(JSONObject jsonResult) throws JSONException { logger.debug("parseJSONToItem jsonResult: {}",jsonResult); Item item = new Item(); item.setUrl(jsonResult.getString("url")); item.setEntity(parseJSONToEntity(jsonResult)); item.setRelationships(parseJSONToRelationShips(jsonResult)); if (item.getEntity().getType().equals("album")) { JSONArray jsonArray = jsonResult.getJSONArray("members"); item.getMembers().addAll(convertJSONArrayToList(jsonArray)); } logger.debug("item : {}",item); return item; } static Item parseJSONToItem(JSONObject jsonResult); static List<Item> parseJSONToMultipleItems(JSONObject jsonResult); static String convertAlbumEntityToJSON(Entity entity); static String convertPhotoEntityToJSON(Entity entity); static NameValuePair convertJSONStringToNameValuePair(String value); static String convertJsonResultToApiKey(String jsonResult); static String convertJsonStringToUrl(String jsonResult); static Integer getItemIdFromUrl(String createdAlbumUrl); } | @Test public void parseJSONTest__album() throws IOException, JSONException { URL resource = Resources.getResource("get-album-1.json"); String string = Resources.toString(resource, Charsets.UTF_8); JSONObject jsonResult = (JSONObject) new JSONTokener(string) .nextValue(); Item item = ItemUtils.parseJSONToItem(jsonResult); assertEquals("http: Entity entity = item.getEntity(); assertEquals(1,entity.getId()); assertEquals(0,entity.getCaptured()); assertEquals(1276227460,entity.getCreated()); assertEquals("",entity.getDescription()); assertEquals(0,entity.getHeight()); assertEquals(1,entity.getLevel()); assertEquals(null,entity.getMimeType()); assertEquals(null,entity.getName()); assertEquals(2,entity.getOwnerId()); assertEquals(0f,entity.getRandKey(),0); assertEquals(0,entity.getResizeHeight()); assertEquals(0,entity.getResizeWidth()); assertEquals(null,entity.getSlug()); assertEquals("weight",entity.getSortColumn()); assertEquals("ASC",entity.getSortOrder()); assertEquals(200,entity.getThumbHeight()); assertEquals(150,entity.getThumbWidth()); assertEquals("Gallery",entity.getTitle()); assertEquals("album",entity.getType()); assertEquals(1276227718,entity.getUpdated()); assertEquals(8,entity.getViewCount()); assertEquals(0,entity.getWidth()); assertEquals(1,entity.getView1()); assertEquals(1,entity.getView2()); assertEquals("http: assertEquals("http: assertEquals("http: assertEquals(17151,entity.getThumbSize()); assertEquals("http: assertEquals(false,entity.isCanEdit()); RelationShips relationShips = item.getRelationships(); assertEquals("http: assertEquals(new HashSet<String>(),relationShips.getTags().getMembers()); assertEquals("http: Collection<String> members = new HashSet<String>(); members.add("http: members.add("http: assertEquals(members, item.getMembers()); }
@Test public void parseJSONTest_issue32() throws IOException, JSONException{ URL resource = Resources.getResource("get-album-bug32_owner-id-null.json"); String string = Resources.toString(resource, Charsets.UTF_8); JSONObject jsonResult = (JSONObject) new JSONTokener(string) .nextValue(); Item item = ItemUtils.parseJSONToItem(jsonResult); Entity entity = item.getEntity(); RelationShips relationShips = item.getRelationships(); }
@Test public void parseJSONTest_issue38() throws IOException, JSONException{ URL resource = Resources.getResource("get-albums-no-relationships-38.json"); String string = Resources.toString(resource, Charsets.UTF_8); JSONObject jsonResult = (JSONObject) new JSONTokener(string) .nextValue(); Item item = ItemUtils.parseJSONToItem(jsonResult); Entity entity = item.getEntity(); RelationShips relationShips = item.getRelationships(); }
@Test public void parseJSONTest_issue83() throws IOException, JSONException{ URL resource = Resources.getResource("get-albums-no-comments-issue82.json"); String string = Resources.toString(resource, Charsets.UTF_8); JSONObject jsonResult = (JSONObject) new JSONTokener(string) .nextValue(); Item item = ItemUtils.parseJSONToItem(jsonResult); Entity entity = item.getEntity(); RelationShips relationShips = item.getRelationships(); } |
ItemUtils { public static String convertAlbumEntityToJSON(Entity entity) throws JSONException { JSONObject entityJSON = new JSONObject(); entityJSON.put("title", entity.getTitle()); entityJSON.put("type", "album"); entityJSON.put("name", entity.getName()); return entityJSON.toString(); } static Item parseJSONToItem(JSONObject jsonResult); static List<Item> parseJSONToMultipleItems(JSONObject jsonResult); static String convertAlbumEntityToJSON(Entity entity); static String convertPhotoEntityToJSON(Entity entity); static NameValuePair convertJSONStringToNameValuePair(String value); static String convertJsonResultToApiKey(String jsonResult); static String convertJsonStringToUrl(String jsonResult); static Integer getItemIdFromUrl(String createdAlbumUrl); } | @Test public void convertAlbumEntityToJSON() throws JSONException{ Entity albumEntity = new Entity(); albumEntity.setTitle("This is my Sample Album"); albumEntity.setName("Sample Album"); String convertEntityToJSON = ItemUtils.convertAlbumEntityToJSON(albumEntity); assertTrue("invalid JSON", new JSONObject(convertEntityToJSON) != null); assertTrue("missing title attribute", convertEntityToJSON.contains("\"title\":\"This is my Sample Album\"")); assertTrue("missing name attribute", convertEntityToJSON.contains("\"name\":\"Sample Album\"")); assertTrue("missing type attribute", convertEntityToJSON.contains("\"type\":\"album\"")); } |
ItemUtils { public static NameValuePair convertJSONStringToNameValuePair(String value) { NameValuePair nameValuePair = new BasicNameValuePair("entity", value); return nameValuePair; } static Item parseJSONToItem(JSONObject jsonResult); static List<Item> parseJSONToMultipleItems(JSONObject jsonResult); static String convertAlbumEntityToJSON(Entity entity); static String convertPhotoEntityToJSON(Entity entity); static NameValuePair convertJSONStringToNameValuePair(String value); static String convertJsonResultToApiKey(String jsonResult); static String convertJsonStringToUrl(String jsonResult); static Integer getItemIdFromUrl(String createdAlbumUrl); } | @Test public void convertItemToNameValuePair(){ Item item = new Item(); Entity albumEntity = new Entity(); albumEntity.setTitle("New Album"); albumEntity.setName("AlbumName"); item.setEntity(albumEntity ); String value = "{\"title\":\"This is my Sample Album\",\"name\":\"Sample Album\",\"type\":\"album\"}"; BasicNameValuePair basicNameValuePair = new BasicNameValuePair("entity",value); assertEquals(basicNameValuePair, ItemUtils.convertJSONStringToNameValuePair(value)); } |
ItemUtils { public static String convertJsonResultToApiKey(String jsonResult) { String apiKey; apiKey = jsonResult.replaceAll("\"", "").replaceAll("\n", ""); return apiKey; } static Item parseJSONToItem(JSONObject jsonResult); static List<Item> parseJSONToMultipleItems(JSONObject jsonResult); static String convertAlbumEntityToJSON(Entity entity); static String convertPhotoEntityToJSON(Entity entity); static NameValuePair convertJSONStringToNameValuePair(String value); static String convertJsonResultToApiKey(String jsonResult); static String convertJsonStringToUrl(String jsonResult); static Integer getItemIdFromUrl(String createdAlbumUrl); } | @Test public void convertJsonStringToApiKey() { String expectedKey = "e3450cdda082e6a2bddf5114a2bcc14d"; String jsonResult="\"e3450cdda082e6a2bddf5114a2bcc14d\n\""; String key = ItemUtils.convertJsonResultToApiKey(jsonResult); assertEquals(expectedKey, key); } |
ItemUtils { public static String convertJsonStringToUrl(String jsonResult) throws JSONException { JSONObject jsonObject = new JSONObject(jsonResult); return (String) jsonObject.get("url"); } static Item parseJSONToItem(JSONObject jsonResult); static List<Item> parseJSONToMultipleItems(JSONObject jsonResult); static String convertAlbumEntityToJSON(Entity entity); static String convertPhotoEntityToJSON(Entity entity); static NameValuePair convertJSONStringToNameValuePair(String value); static String convertJsonResultToApiKey(String jsonResult); static String convertJsonStringToUrl(String jsonResult); static Integer getItemIdFromUrl(String createdAlbumUrl); } | @Test public void convertJsonStringToUrl() throws JSONException{ String jsonResult="{\"url\":\"http:\\/\\/g3.dahanne.net\\/index.php\\/rest\\/item\\/34\"}"; String expectedString = "http: String urlString = ItemUtils.convertJsonStringToUrl(jsonResult); assertEquals(expectedString, urlString); } |
AlbumUtils { public static Album findAlbumFromAlbumName(Album rootAlbum, int albumName) { logger.debug("rootAlbum is : {} -- albumName is : {}",rootAlbum,albumName); Album albumFound=null; if (rootAlbum.getName() == albumName&& !rootAlbum.isFakeAlbum()) { albumFound= rootAlbum; } for (Album album : rootAlbum.getSubAlbums()) { if (album.getName() == albumName && !album.isFakeAlbum()) { albumFound= album; break; } Album fromAlbumName = findAlbumFromAlbumName(album, albumName); if (fromAlbumName != null && !fromAlbumName.isFakeAlbum()) { albumFound= fromAlbumName; } } logger.debug("albumFound is : {}",albumFound); return albumFound; } static Album findAlbumFromAlbumName(Album rootAlbum, int albumName); } | @Test public void findAlbumFromAlbumNameTest() { Album rootAlbum = new Album(); rootAlbum.setName(999); Album album1 = new Album(); album1.setName(1); rootAlbum.getSubAlbums().add(album1); Album album2 = new Album(); album2.setName(2); rootAlbum.getSubAlbums().add(album2); Album album3 = new Album(); album3.setName(3); rootAlbum.getSubAlbums().add(album3); Album album4 = new Album(); album4.setName(4); rootAlbum.getSubAlbums().add(album4); Album album31 = new Album(); album31.setName(31); album3.getSubAlbums().add(album31); Album album311 = new Album(); album311.setName(311); album311.setId(12); album31.getSubAlbums().add(album311); Album album311_fake = new Album(); album311_fake.setName(311); album311_fake.setFakeAlbum(true); album311.getSubAlbums().add(album311_fake); Album albumFound = AlbumUtils.findAlbumFromAlbumName(rootAlbum, 311); assertEquals(album311, albumFound); assertNull(AlbumUtils.findAlbumFromAlbumName(rootAlbum, 312)); } |
G2Client { public HashMap<String, String> fetchImages(String galleryUrl, int albumName) throws GalleryConnectionException { List<NameValuePair> nameValuePairsFetchImages = new ArrayList<NameValuePair>(); nameValuePairsFetchImages.add(FETCH_ALBUMS_IMAGES_CMD_NAME_VALUE_PAIR); nameValuePairsFetchImages.add(new BasicNameValuePair( "g2_form[set_albumName]", "" + albumName)); HashMap<String, String> properties = sendCommandToGallery(galleryUrl, nameValuePairsFetchImages, null); return properties; } G2Client(String userAgent); HashMap<String, String> fetchImages(String galleryUrl, int albumName); HashMap<String, String> fetchAlbums(String galleryUrl); void loginToGallery(String galleryUrl, String user, String password); InputStream getInputStreamFromUrl(String url); int createNewAlbum(String galleryUrl, int parentAlbumName,
String albumName, String albumTitle, String albumDescription); int sendImageToGallery(String galleryUrl, int albumName,
File imageFile, String imageName, String summary, String description); String getAuthToken(); void setAuthToken(String authToken); List<Cookie> getSessionCookies(); Collection<G2Picture> extractG2PicturesFromProperties(
HashMap<String, String> fetchImages); Map<Integer, Album> getAllAlbums(String galleryUrl); Map<Integer, G2Album> extractAlbumFromProperties(
HashMap<String, String> albumsProperties); Album organizeAlbumsHierarchy(Map<Integer, G2Album> albums); void setRootAlbum(G2Album rootAlbum); G2Album getRootAlbum(); } | @Test public void fetchImagesTest() throws GalleryConnectionException { HashMap<String, String> fetchImages = g2ConnectionUtils.fetchImages( galleryUrl, 11); assertTrue("no pictures found",fetchImages.size() != 0); assertTrue("the string image_count could not be found",fetchImages.containsKey("image_count")); assertFalse("the value of image_count was 0",fetchImages.get("image_count").equals("0")); fetchImages = g2ConnectionUtils.fetchImages(galleryUrl, 9999); assertTrue("there were not 3 pictures",fetchImages.size() == 3); }
@Test(expected = GalleryConnectionException.class) public void fetchImagesTest__exception() throws GalleryConnectionException { g2ConnectionUtils.fetchImages("http: 11); } |
InRepaymentCardViewEntityMapper implements Function<CreditDraft, InRepaymentCardViewEntity> { @NonNull public InRepaymentCardViewEntity apply(@NonNull final CreditDraft draft) throws Exception { assertCorrectStatus(draft.status()); final CreditRepaymentInfo repaymentInfo = orThrowUnsafe(draft.creditRepaymentInfo(), new IllegalStateException(TAG + ": RepaymentInformation missing.")); return InRepaymentCardViewEntity.builder() .id(draft.id()) .title(draft.purpose()) .formattedAmount(currencyUtils.formatAmount(draft.amount())) .nextPaymentLabel(mapToNextPaymentLabel(repaymentInfo.totalPaid())) .formattedPaidOutDate(mapToFormattedPaidOutDate(repaymentInfo.disbursedDate())) .formattedTotalRepaid(currencyUtils.formatAmount(repaymentInfo.totalPaid())) .formattedNextPayment(mapToNextPaymentInfo(repaymentInfo.nextPayment(), repaymentInfo.nextPaymentDate())) .build(); } @Inject InRepaymentCardViewEntityMapper(@NonNull final StringProvider stringProvider,
@NonNull final TimeUtils timeUtils,
@NonNull final CurrencyUtils currencyUtils); @NonNull InRepaymentCardViewEntity apply(@NonNull final CreditDraft draft); } | @Test public void mapDraft() throws Exception { new ArrangeBuilder().withStringFromProvider("something") .withSubstitutionStringFromProvider("other something") .withFormattedDate("Some date") .withFormattedCurrency("500,00"); CreditDraft draft = CreditDataTestUtils.creditDraftTestBuilder() .id("10") .purpose("Electronics") .amount(500) .status(IN_REPAYMENT) .build(); InRepaymentCardViewEntity viewModel = mapper.apply(draft); assertThat(viewModel.id()).isEqualTo("10"); assertThat(viewModel.formattedAmount()).isEqualTo("500,00"); assertThat(viewModel.title()).isEqualTo("Electronics"); }
@Test public void pendingEsignStateThrowsIllegalStateException() throws Exception { thrown.expect(IllegalStateException.class); thrown.expectMessage("Invalid draft status for in repayment card:"); CreditDraft testDraft = CreditDataTestUtils.creditDraftTestBuilder().status(PENDING_ESIGN).build(); mapper.apply(testDraft); }
@Test public void waitingForDisbursementStateThrowsIllegalStateException() throws Exception { thrown.expect(IllegalStateException.class); thrown.expectMessage("Invalid draft status for in repayment card:"); CreditDraft testDraft = CreditDataTestUtils.creditDraftTestBuilder().status(WAITING_FOR_DISBURSEMENT).build(); mapper.apply(testDraft); }
@Test public void unexpectedStateThrowsIllegalStateException() throws Exception { thrown.expect(IllegalStateException.class); thrown.expectMessage("Invalid draft status for in repayment card:"); CreditDraft testDraft = CreditDataTestUtils.creditDraftTestBuilder().status(UNEXPECTED).build(); mapper.apply(testDraft); }
@Test public void missingRepaymentInfoThrows() throws Exception { thrown.expect(IllegalStateException.class); thrown.expectMessage("RepaymentInformation missing."); CreditDraft draft = CreditDataTestUtils.creditDraftTestBuilder() .status(IN_REPAYMENT) .creditRepaymentInfo(Option.none()) .build(); mapper.apply(draft); }
@Test public void mapRepaymentInfoFormattedPaidOut() throws Exception { new ArrangeBuilder().withStringFromProvider("something") .withSubstitutionStringFromProvider("paid out date") .withFormattedDate("Some date") .withFormattedCurrency("500,00"); CreditRepaymentInfo repaymentInfo = CreditDataTestUtils.creditRepaymentInfoTestBuilder() .disbursedDate("2017-08-07T17:53:55.07+02:00") .build(); CreditDraft draft = CreditDataTestUtils.creditDraftTestBuilder() .status(IN_REPAYMENT) .creditRepaymentInfo(Option.ofObj(repaymentInfo)) .build(); InRepaymentCardViewEntity viewModel = mapper.apply(draft); Mockito.verify(timeUtils).formatDateString("2017-08-07T17:53:55.07+02:00", DASHBOARD_DATE_FORMAT_PAID_OUT); Mockito.verify(stringProvider).getStringAndApplySubstitutions( R.string.credit_dashboard_repayment_paid_out, Pair.create("date", "Some date")); assertThat(viewModel.formattedPaidOutDate()).isEqualTo("paid out date"); }
@Test public void mapRepaymentInfoTotalRepaid() throws Exception { new ArrangeBuilder().withStringFromProvider("something") .withSubstitutionStringFromProvider("other something") .withFormattedDate("Some date") .withFormattedCurrency("500,00"); CreditRepaymentInfo repaymentInfo = CreditDataTestUtils.creditRepaymentInfoTestBuilder() .totalPaid(500.0) .build(); CreditDraft draft = CreditDataTestUtils.creditDraftTestBuilder() .status(IN_REPAYMENT) .creditRepaymentInfo(Option.ofObj(repaymentInfo)) .build(); InRepaymentCardViewEntity viewModel = mapper.apply(draft); Mockito.verify(currencyUtils).formatAmount(500.0); assertThat(viewModel.formattedTotalRepaid()).isEqualTo("500,00"); }
@Test public void mapRepaymentInfoNextPayment() throws Exception { new ArrangeBuilder().withStringFromProvider("something") .withSubstitutionStringFromProvider("next payment") .withFormattedDate("Some date") .withFormattedCurrency("500,00"); CreditRepaymentInfo repaymentInfo = CreditDataTestUtils.creditRepaymentInfoTestBuilder() .nextPaymentDate("2017-08-07T17:53:55.07+02:00") .nextPayment(500.0) .build(); CreditDraft draft = CreditDataTestUtils.creditDraftTestBuilder() .status(IN_REPAYMENT) .creditRepaymentInfo(Option.ofObj(repaymentInfo)) .build(); InRepaymentCardViewEntity viewModel = mapper.apply(draft); Mockito.verify(timeUtils).formatDateString("2017-08-07T17:53:55.07+02:00", DASHBOARD_DATE_FORMAT_PAID_OUT); Mockito.verify(currencyUtils).formatAmount(500.0); Mockito.verify(stringProvider).getStringAndApplySubstitutions( R.string.credit_dashboard_repayment_text, Pair.create("amount", "500,00"), Pair.create("date", "Some date")); assertThat(viewModel.formattedNextPayment()).isEqualTo("next payment"); }
@Test public void mapRepaymentInfoNextPaymentLabelIsFirstPaymentWhenTotalRepaidIsZero() throws Exception { new ArrangeBuilder().withStringFromProvider("First payment") .withSubstitutionStringFromProvider("other something") .withFormattedDate("Some date") .withFormattedCurrency("500,00"); CreditRepaymentInfo repaymentInfo = CreditDataTestUtils.creditRepaymentInfoTestBuilder() .totalPaid(0d) .build(); CreditDraft draft = CreditDataTestUtils.creditDraftTestBuilder() .status(IN_REPAYMENT) .creditRepaymentInfo(Option.ofObj(repaymentInfo)) .build(); InRepaymentCardViewEntity viewModel = mapper.apply(draft); Mockito.verify(stringProvider).getString(R.string.credit_dashboard_repayment_payment_first); assertThat(viewModel.nextPaymentLabel()).isEqualTo("First payment"); }
@Test public void mapRepaymentInfoNextPaymentLabelIsNextPaymentWhenTotalRepaidIsNotZero() throws Exception { new ArrangeBuilder().withStringFromProvider("Next payment") .withSubstitutionStringFromProvider("other something") .withFormattedDate("Some date") .withFormattedCurrency("500,00"); CreditRepaymentInfo repaymentInfo = CreditDataTestUtils.creditRepaymentInfoTestBuilder() .totalPaid(100d) .build(); CreditDraft draft = CreditDataTestUtils.creditDraftTestBuilder() .status(IN_REPAYMENT) .creditRepaymentInfo(Option.ofObj(repaymentInfo)) .build(); InRepaymentCardViewEntity viewModel = mapper.apply(draft); Mockito.verify(stringProvider).getString(R.string.credit_dashboard_repayment_payment_next); assertThat(viewModel.nextPaymentLabel()).isEqualTo("Next payment"); }
@Test public void initialisedStateThrowsIllegalStateException() throws Exception { thrown.expect(IllegalStateException.class); thrown.expectMessage("Invalid draft status for in repayment card:"); CreditDraft testDraft = CreditDataTestUtils.creditDraftTestBuilder().status(INITIALISED).build(); mapper.apply(testDraft); }
@Test public void pendingProviderApprovalStateThrowsIllegalStateException() throws Exception { thrown.expect(IllegalStateException.class); thrown.expectMessage("Invalid draft status for in repayment card:"); CreditDraft testDraft = CreditDataTestUtils.creditDraftTestBuilder().status(PENDING_PROVIDER_APPROVAL).build(); mapper.apply(testDraft); }
@Test public void contractProcessingStateThrowsIllegalStateException() throws Exception { thrown.expect(IllegalStateException.class); thrown.expectMessage("Invalid draft status for in repayment card:"); CreditDraft testDraft = CreditDataTestUtils.creditDraftTestBuilder().status(CONTRACT_PROCESSING).build(); mapper.apply(testDraft); } |
CreditDashboardViewModel extends ViewModel { @NonNull LiveData<List<DisplayableItem>> getCreditListLiveData() { return creditListLiveData; } @Inject CreditDashboardViewModel(@NonNull final RetrieveCreditDraftList retrieveCreditDraftList,
@NonNull final CreditDisplayableItemMapper creditDisplayableItemMapper); } | @Test public void displayableItemsGoIntoLiveDataWhenInteractorEmitsCreditDrafts() throws Exception { List<DisplayableItem> displayableItems = Collections.singletonList(Mockito.mock(DisplayableItem.class)); List<CreditDraft> creditDrafts = Collections.singletonList(Mockito.mock(CreditDraft.class)); arrangeBuilder.withMappedDisplayableItems(displayableItems) .interactorEmitsCreditDrafts(creditDrafts); assertThat(viewModel.getCreditListLiveData().getValue()).isEqualTo(displayableItems); } |
CreditDisplayableItemMapper implements Function<List<CreditDraft>, List<DisplayableItem>> { @Override public List<DisplayableItem> apply(@NonNull final List<CreditDraft> creditDrafts) throws Exception { return Observable.fromIterable(creditDrafts) .map(inRepaymentCardViewEntityMapper) .map(this::wrapInDisplayableItem) .toList() .blockingGet(); } @Inject CreditDisplayableItemMapper(@NonNull final InRepaymentCardViewEntityMapper inRepaymentCardViewEntityMapper); @Override List<DisplayableItem> apply(@NonNull final List<CreditDraft> creditDrafts); } | @Test public void creditDraftsAreMappedToViewEntities() throws Exception { CreditDraft creditDraft = Mockito.mock(CreditDraft.class); new ArrangeBuilder().withMappedViewEntity(Mockito.mock(InRepaymentCardViewEntity.class)); displayableItemMapper.apply(Collections.singletonList(creditDraft)); Mockito.verify(viewEntityMapper).apply(creditDraft); }
@Test public void viewEntityIsWrappedInDisplayableItem() throws Exception { CreditDraft creditDraft = Mockito.mock(CreditDraft.class); InRepaymentCardViewEntity viewEntity = Mockito.mock(InRepaymentCardViewEntity.class); new ArrangeBuilder().withMappedViewEntity(viewEntity); List<DisplayableItem> items = displayableItemMapper.apply(Collections.singletonList(creditDraft)); List<DisplayableItem> expected = Collections.singletonList(DisplayableItem.toDisplayableItem(viewEntity, IN_REPAYMENT)); assertThat(items).isEqualTo(expected); } |
CreditDraftMapper implements Function<CreditDraftRaw, CreditDraft> { @Override @SuppressWarnings("ConstantConditions") public CreditDraft apply(@NonNull final CreditDraftRaw raw) throws Exception { assertEssentialParams(raw); return CreditDraft.builder() .id(raw.id()) .purpose(raw.purposeName()) .amount(raw.amount()) .status(toStatus(raw.status())) .creditRepaymentInfo(mapRepaymentInfo(raw.repaymentInfo())) .imageUrl(raw.imageUrl()) .purposeId(raw.purposeId()) .build(); } @Inject CreditDraftMapper(); @Override @SuppressWarnings("ConstantConditions") CreditDraft apply(@NonNull final CreditDraftRaw raw); } | @Test public void essentialParamMissingExceptionIsThrownWhenTheMandatoryParamsAreMissing() throws Exception { thrown.expect(EssentialParamMissingException.class); thrown.expectMessage("status id purpose imageUrl"); mapper.apply(CreditDataTestUtils.creditDraftRawTestBuilder() .status(null) .id(null) .purposeName(null) .imageUrl(null) .build()); }
@Test public void amountIsMappedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .amount(10.0) .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.amount()).isEqualTo(10.0); }
@Test public void idIsMappedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .id("10") .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.id()).isEqualTo("10"); }
@Test public void purposeIsMappedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .purposeName("Electronics") .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.purpose()).isEqualTo("Electronics"); }
@Test public void purposeIdIsMappedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .purposeId(5) .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.purposeId()).isEqualTo(5); }
@Test public void imageUrlIsMappedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .imageUrl("imageUrl") .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.imageUrl()).isEqualTo("imageUrl"); }
@Test public void noRepaymentInfoIsMappedToNone() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .repaymentInfo(null) .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.creditRepaymentInfo()).isEqualTo(Option.none()); }
@Test public void repaymentInfoIsMappedAndWrappedInOption() throws Exception { CreditRepaymentInfoRaw repaymentInfoRaw = CreditDataTestUtils.creditRepaymentInfoRawTestBuilder().build(); CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .repaymentInfo(repaymentInfoRaw) .build(); CreditDraft draft = mapper.apply(raw); CreditRepaymentInfo expected = CreditRepaymentInfoMapper.processRaw(repaymentInfoRaw); assertThat(draft.creditRepaymentInfo()).isEqualTo(Option.ofObj(expected)); }
@Test public void contractProcessingStateIsParsedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .status(RawDraftStatus.CONTRACT_PROCESSING) .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.status()).isEqualTo(CreditDraftStatus.CONTRACT_PROCESSING); }
@Test public void inRepaymentStateIsParsedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .status(RawDraftStatus.IN_REPAYMENT) .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.status()).isEqualTo(CreditDraftStatus.IN_REPAYMENT); }
@Test public void initialisedStateIsParsedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .status(RawDraftStatus.INITIALISED) .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.status()).isEqualTo(CreditDraftStatus.INITIALISED); }
@Test public void pendingEsignStateIsParsedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .status(RawDraftStatus.PENDING_ESIGN) .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.status()).isEqualTo(CreditDraftStatus.PENDING_ESIGN); }
@Test public void pendingProviderApprovalStateIsParsedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .status(RawDraftStatus.PENDING_PROVIDER_APPROVAL) .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.status()).isEqualTo(CreditDraftStatus.PENDING_PROVIDER_APPROVAL); }
@Test public void waitingForDisbursementStateIsParsedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .status(RawDraftStatus.WAITING_FOR_DISBURSEMENT) .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.status()).isEqualTo(CreditDraftStatus.WAITING_FOR_DISBURSEMENT); }
@Test public void additionalAccountRequiredStateIsParsedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .status(RawDraftStatus.ADDITIONAL_ACCOUNT_REQUIRED) .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.status()).isEqualTo(CreditDraftStatus.ADDITIONAL_ACCOUNT_REQUIRED); }
@Test public void unexpectedStateIsParsedCorrectly() throws Exception { CreditDraftRaw raw = CreditDataTestUtils.creditDraftRawTestBuilder() .status("UNEXPECTED") .build(); CreditDraft draft = mapper.apply(raw); assertThat(draft.status()).isEqualTo(CreditDraftStatus.UNEXPECTED); } |
Subsets and Splits