src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ViewInfoStore { @Nullable ItemHolderInfo popFromPreLayout(ViewHolder vh) { return popFromLayoutStep(vh, FLAG_PRE); } void onViewDetached(ViewHolder viewHolder); }
@Test public void popFromPreLayout() { assertEquals(0, sizeOf(FLAG_PRE)); RecyclerView.ViewHolder vh = new MockViewHolder(); MockInfo info = new MockInfo(); mStore.addToPreLayout(vh, info); assertSame(info, mStore.popFromPreLayout(vh)); assertNull(mStore.popFromPreLayout(vh)); }
ViewInfoStore { void addToOldChangeHolders(long key, ViewHolder holder) { mOldChangedHolders.put(key, holder); } void onViewDetached(ViewHolder viewHolder); }
@Test public void addToOldChangeHolders() { RecyclerView.ViewHolder vh = new MockViewHolder(); mStore.addToOldChangeHolders(1, vh); assertSame(vh, mStore.getFromOldChangeHolders(1)); mStore.removeViewHolder(vh); assertNull(mStore.getFromOldChangeHolders(1)); }
Animator implements TickListener { public static void setDefaultTimingSource(@Nullable TimingSource timingSource) { Builder.setDefaultTimingSource(timingSource); } @Unique("return") Animator(String debugName, long duration, @NonNull TimeUnit durationTimeUnit, @NonNull EndBehavior endBehavior, @NonNull Interpolator interpolator, @NonNull RepeatBehavior repeatBehavior, long repeatCount, @NonNull Direction startDirection, long startDelay, @NonNull TimeUnit startDelayTimeUnit, @NonNull TimingSource timingSource, boolean disposeTimingSource, @NonNull Collection<TimingTarget> targets); static void setDefaultTimingSource(@Nullable TimingSource timingSource); @Nullable static TimingSource getDefaultTimingSource(); @Nullable @RegionEffects("reads Instance") String getDebugName(); @RegionEffects("reads Instance") long getDuration(); @NonNull @RegionEffects("reads Instance") TimeUnit getDurationTimeUnit(); @NonNull @RegionEffects("reads Instance") EndBehavior getEndBehavior(); @NonNull Interpolator getInterpolator(); @NonNull @RegionEffects("reads Instance") RepeatBehavior getRepeatBehavior(); @RegionEffects("reads Instance") long getRepeatCount(); @NonNull @RegionEffects("reads Instance") Direction getStartDirection(); @RegionEffects("reads Instance") long getStartDelay(); @NonNull @RegionEffects("reads Instance") TimeUnit getStartDelayTimeUnit(); @NonNull @RegionEffects("reads Instance") TimingSource getTimingSource(); @RegionEffects("reads Instance") boolean getDisposeTimingSource(); void addTarget(final TimingTarget target); void addTargets(Collection<TimingTarget> targets); void addTargets(TimingTarget... targets); void removeTarget(TimingTarget target); void removeTargets(Collection<TimingTarget> targets); void removeTargets(TimingTarget... targets); ArrayList<TimingTarget> getTargets(); void clearTargets(); void start(); void restart(); void startReverse(); void restartReverse(); @RegionEffects("reads Instance") boolean isRunning(); @NonNull @RegionEffects("reads Instance") Direction getCurrentDirection(); boolean stop(); void stopAndAwait(); boolean cancel(); void cancelAndAwait(); void pause(); boolean isPaused(); void resume(); boolean reverseNow(); void await(); long getCycleElapsedTime(); @RegionEffects("reads Instance") long getCycleElapsedTime(long currentTimeNanos); long getTotalElapsedTime(); @RegionEffects("reads Instance") long getTotalElapsedTime(long currentTimeNanos); @Override @NonNull @RegionEffects("reads Instance") @Vouch("Uses StringBuilder") String toString(); void timingSourceTick(TimingSource source, long nanoTime); static final long INFINITE; }
@Test(expected = IllegalArgumentException.class) public void noTimingSource2() { Animator.setDefaultTimingSource(new ManualTimingSource()); try { new Animator.Builder().build(); } catch (IllegalArgumentException e) { Assert.fail("An Animator built with a non-null default TimingSource should be okay."); } Animator.setDefaultTimingSource(null); new Animator.Builder().build(); }
PropertySetter { public static <T> TimingTargetAdapter getTarget(Object object, String propertyName, KeyFrames<T> keyFrames) { return getTargetHelper(object, propertyName, keyFrames, false); } private PropertySetter(); static TimingTargetAdapter getTarget(Object object, String propertyName, KeyFrames<T> keyFrames); static TimingTargetAdapter getTarget(Object object, String propertyName, T... values); static TimingTargetAdapter getTarget(Object object, String propertyName, Interpolator interpolator, T... values); static TimingTargetAdapter getTargetTo(Object object, String propertyName, KeyFrames<T> keyFrames); static TimingTargetAdapter getTargetTo(Object object, String propertyName, T... values); static TimingTargetAdapter getTargetTo(Object object, String propertyName, Interpolator interpolator, T... values); }
@Test public void valueSetInBegin() { MyProps pt = new MyProps(); TimingTarget tt = PropertySetter.getTarget(pt, "value", 1, 2); ValueTarget vt = new ValueTarget(pt); ManualTimingSource ts = new ManualTimingSource(); Animator a = new Animator.Builder(ts).addTarget(tt).addTarget(vt).build(); pt.setValue(-999); a.start(); ts.tick(); Assert.assertEquals(1, vt.valueAtBegin); while (a.isRunning()) ts.tick(); Assert.assertEquals(2, pt.getValue()); } @Test public void forwardStartCalled() throws InterruptedException { MyProps pt = new MyProps(); TimingTarget tt = PropertySetter.getTarget(pt, "value", 1, 50); ValueTarget vt = new ValueTarget(pt); TimingSource ts = new ScheduledExecutorTimingSource(); ts.init(); Animator a = new Animator.Builder(ts).addTarget(tt).addTarget(vt).setStartDirection(Direction.FORWARD).build(); pt.setValue(-999); a.start(); a.await(); ts.dispose(); Assert.assertEquals(1, vt.valueAtBegin); Assert.assertSame(vt.startDirectionAtBegin, Direction.FORWARD); Assert.assertSame(vt.currentDirectionAtBegin, Direction.FORWARD); Assert.assertTrue(vt.valueAtFirstTimingEvent < 4); Assert.assertSame(vt.currentDirectionAtFirstTimingEvent, Direction.FORWARD); Assert.assertEquals(50, pt.getValue()); } @Test public void backwardStartCalled() throws InterruptedException { MyProps pt = new MyProps(); TimingTarget tt = PropertySetter.getTarget(pt, "value", 1, 50); ValueTarget vt = new ValueTarget(pt); TimingSource ts = new ScheduledExecutorTimingSource(); ts.init(); Animator a = new Animator.Builder(ts).addTarget(tt).addTarget(vt).setStartDirection(Direction.BACKWARD).build(); pt.setValue(-999); a.start(); a.await(); ts.dispose(); Assert.assertEquals(50, vt.valueAtBegin); Assert.assertSame(vt.startDirectionAtBegin, Direction.BACKWARD); Assert.assertSame(vt.currentDirectionAtBegin, Direction.BACKWARD); Assert.assertTrue(vt.valueAtFirstTimingEvent > 46); Assert.assertSame(vt.currentDirectionAtFirstTimingEvent, Direction.BACKWARD); Assert.assertEquals(1, pt.getValue()); } @Test public void forwardStartReverseCalled() throws InterruptedException { MyProps pt = new MyProps(); TimingTarget tt = PropertySetter.getTarget(pt, "value", 1, 50); ValueTarget vt = new ValueTarget(pt); TimingSource ts = new ScheduledExecutorTimingSource(); ts.init(); Animator a = new Animator.Builder(ts).addTarget(tt).addTarget(vt).setStartDirection(Direction.FORWARD).build(); pt.setValue(-999); a.startReverse(); a.await(); ts.dispose(); Assert.assertEquals(50, vt.valueAtBegin); Assert.assertSame(vt.startDirectionAtBegin, Direction.FORWARD); Assert.assertSame(vt.currentDirectionAtBegin, Direction.BACKWARD); Assert.assertTrue(vt.valueAtFirstTimingEvent > 46); Assert.assertSame(vt.currentDirectionAtFirstTimingEvent, Direction.BACKWARD); Assert.assertEquals(1, pt.getValue()); } @Test public void backwardStartReverseCalled() throws InterruptedException { MyProps pt = new MyProps(); TimingTarget tt = PropertySetter.getTarget(pt, "value", 1, 50); ValueTarget vt = new ValueTarget(pt); TimingSource ts = new ScheduledExecutorTimingSource(); ts.init(); Animator a = new Animator.Builder(ts).addTarget(tt).addTarget(vt).setStartDirection(Direction.BACKWARD).build(); pt.setValue(-999); a.startReverse(); a.await(); ts.dispose(); Assert.assertEquals(1, vt.valueAtBegin); Assert.assertSame(vt.startDirectionAtBegin, Direction.BACKWARD); Assert.assertSame(vt.currentDirectionAtBegin, Direction.FORWARD); Assert.assertTrue(vt.valueAtFirstTimingEvent < 4); Assert.assertSame(vt.currentDirectionAtFirstTimingEvent, Direction.FORWARD); Assert.assertEquals(50, pt.getValue()); } @Test(expected = IllegalArgumentException.class) public void noSuchProperty1() { MyProps pt = new MyProps(); PropertySetter.getTarget(pt, "wrong", 1, 2, 3); } @Test public void valueProperty() { MyProps pt = new MyProps(); TimingTarget tt = PropertySetter.getTarget(pt, "value", 1, 2, 3); ManualTimingSource ts = new ManualTimingSource(); Animator a = new Animator.Builder(ts).addTarget(tt).build(); a.start(); ts.tick(); Assert.assertEquals(1, pt.getValue()); while (a.isRunning()) ts.tick(); Assert.assertEquals(3, pt.getValue()); } @Test public void byteValueProperty() { MyProps pt = new MyProps(); TimingTarget tt = PropertySetter.getTarget(pt, "byteValue", (byte) 1, (byte) 2, (byte) 3); ManualTimingSource ts = new ManualTimingSource(); Animator a = new Animator.Builder(ts).addTarget(tt).build(); a.start(); ts.tick(); Assert.assertEquals((byte) 1, pt.sneakyGetByteValue()); while (a.isRunning()) ts.tick(); Assert.assertEquals((byte) 3, pt.sneakyGetByteValue()); } @Test public void byteValueToIntProperty() { MyProps pt = new MyProps(); TimingTarget tt = PropertySetter.getTarget(pt, "value", (byte) 1, (byte) 2, (byte) 3); ManualTimingSource ts = new ManualTimingSource(); Animator a = new Animator.Builder(ts).addTarget(tt).build(); a.start(); ts.tick(); Assert.assertEquals(1, pt.getValue()); while (a.isRunning()) ts.tick(); Assert.assertEquals(3, pt.getValue()); }
TimingSource { public final void addTickListener(TickListener listener) { if (listener == null) return; f_tickListeners.add(listener); } abstract void init(); abstract void dispose(); abstract boolean isDisposed(); final void addTickListener(TickListener listener); final void removeTickListener(TickListener listener); final void addPostTickListener(PostTickListener listener); final void removePostTickListener(PostTickListener listener); final void submit(Runnable task); void runPerTick(); }
@Test public void tick1() { final ManualTimingSource ts = new ManualTimingSource(); tickCounter = 0; ts.addTickListener(new TickListener() { public void timingSourceTick(TimingSource source, long nanoTime) { tickCounter++; Assert.assertSame(ts, source); } }); Assert.assertEquals(0, tickCounter); } @Test public void tick2() { final ManualTimingSource ts = new ManualTimingSource(); tickCounter = 0; ts.addTickListener(new TickListener() { public void timingSourceTick(TimingSource source, long nanoTime) { tickCounter++; Assert.assertSame(ts, source); } }); ts.tick(); Assert.assertEquals(1, tickCounter); } @Test public void tick3() { final ManualTimingSource ts = new ManualTimingSource(); tickCounter = 0; ts.addTickListener(new TickListener() { public void timingSourceTick(TimingSource source, long nanoTime) { tickCounter++; Assert.assertSame(ts, source); } }); ts.tick(); ts.tick(); Assert.assertEquals(2, tickCounter); } @Test public void tick4() { final ManualTimingSource ts = new ManualTimingSource(); tickCounter = 0; ts.addTickListener(new TickListener() { public void timingSourceTick(TimingSource source, long nanoTime) { tickCounter++; Assert.assertSame(ts, source); } }); for (int i = 0; i < 1000; i++) ts.tick(); Assert.assertEquals(1000, tickCounter); }
TimingSource { public final void addPostTickListener(PostTickListener listener) { if (listener == null) return; f_postTickListeners.add(listener); } abstract void init(); abstract void dispose(); abstract boolean isDisposed(); final void addTickListener(TickListener listener); final void removeTickListener(TickListener listener); final void addPostTickListener(PostTickListener listener); final void removePostTickListener(PostTickListener listener); final void submit(Runnable task); void runPerTick(); }
@Test public void postTick1() { final ManualTimingSource ts = new ManualTimingSource(); postTickCounter = 0; ts.addPostTickListener(new PostTickListener() { public void timingSourcePostTick(TimingSource source, long nanoTime) { postTickCounter++; Assert.assertSame(ts, source); } }); Assert.assertEquals(0, postTickCounter); } @Test public void postTick2() { final ManualTimingSource ts = new ManualTimingSource(); postTickCounter = 0; ts.addPostTickListener(new PostTickListener() { public void timingSourcePostTick(TimingSource source, long nanoTime) { postTickCounter++; Assert.assertSame(ts, source); } }); ts.tick(); Assert.assertEquals(1, postTickCounter); } @Test public void postTick3() { final ManualTimingSource ts = new ManualTimingSource(); postTickCounter = 0; ts.addPostTickListener(new PostTickListener() { public void timingSourcePostTick(TimingSource source, long nanoTime) { postTickCounter++; Assert.assertSame(ts, source); } }); ts.tick(); ts.tick(); Assert.assertEquals(2, postTickCounter); } @Test public void postTick4() { final ManualTimingSource ts = new ManualTimingSource(); postTickCounter = 0; ts.addPostTickListener(new PostTickListener() { public void timingSourcePostTick(TimingSource source, long nanoTime) { postTickCounter++; Assert.assertSame(ts, source); } }); for (int i = 0; i < 1000; i++) ts.tick(); Assert.assertEquals(1000, postTickCounter); }
Animator implements TickListener { public void start() { startHelper(f_startDirection, "start()"); } @Unique("return") Animator(String debugName, long duration, @NonNull TimeUnit durationTimeUnit, @NonNull EndBehavior endBehavior, @NonNull Interpolator interpolator, @NonNull RepeatBehavior repeatBehavior, long repeatCount, @NonNull Direction startDirection, long startDelay, @NonNull TimeUnit startDelayTimeUnit, @NonNull TimingSource timingSource, boolean disposeTimingSource, @NonNull Collection<TimingTarget> targets); static void setDefaultTimingSource(@Nullable TimingSource timingSource); @Nullable static TimingSource getDefaultTimingSource(); @Nullable @RegionEffects("reads Instance") String getDebugName(); @RegionEffects("reads Instance") long getDuration(); @NonNull @RegionEffects("reads Instance") TimeUnit getDurationTimeUnit(); @NonNull @RegionEffects("reads Instance") EndBehavior getEndBehavior(); @NonNull Interpolator getInterpolator(); @NonNull @RegionEffects("reads Instance") RepeatBehavior getRepeatBehavior(); @RegionEffects("reads Instance") long getRepeatCount(); @NonNull @RegionEffects("reads Instance") Direction getStartDirection(); @RegionEffects("reads Instance") long getStartDelay(); @NonNull @RegionEffects("reads Instance") TimeUnit getStartDelayTimeUnit(); @NonNull @RegionEffects("reads Instance") TimingSource getTimingSource(); @RegionEffects("reads Instance") boolean getDisposeTimingSource(); void addTarget(final TimingTarget target); void addTargets(Collection<TimingTarget> targets); void addTargets(TimingTarget... targets); void removeTarget(TimingTarget target); void removeTargets(Collection<TimingTarget> targets); void removeTargets(TimingTarget... targets); ArrayList<TimingTarget> getTargets(); void clearTargets(); void start(); void restart(); void startReverse(); void restartReverse(); @RegionEffects("reads Instance") boolean isRunning(); @NonNull @RegionEffects("reads Instance") Direction getCurrentDirection(); boolean stop(); void stopAndAwait(); boolean cancel(); void cancelAndAwait(); void pause(); boolean isPaused(); void resume(); boolean reverseNow(); void await(); long getCycleElapsedTime(); @RegionEffects("reads Instance") long getCycleElapsedTime(long currentTimeNanos); long getTotalElapsedTime(); @RegionEffects("reads Instance") long getTotalElapsedTime(long currentTimeNanos); @Override @NonNull @RegionEffects("reads Instance") @Vouch("Uses StringBuilder") String toString(); void timingSourceTick(TimingSource source, long nanoTime); static final long INFINITE; }
@Test(expected = IllegalStateException.class) public void start1() { Animator a = new Animator.Builder(new ManualTimingSource()).build(); a.start(); a.start(); }
TimingSource { public final void submit(Runnable task) { if (task == null) return; final WrappedRunnable wrapped = new WrappedRunnable(task); f_oneShotQueue.add(wrapped); } abstract void init(); abstract void dispose(); abstract boolean isDisposed(); final void addTickListener(TickListener listener); final void removeTickListener(TickListener listener); final void addPostTickListener(PostTickListener listener); final void removePostTickListener(PostTickListener listener); final void submit(Runnable task); void runPerTick(); }
@Test public void runTask() { final ManualTimingSource ts = new ManualTimingSource(); taskCounter = 0; ts.submit(new Runnable() { public void run() { taskCounter++; } }); ts.tick(); Assert.assertEquals(1, taskCounter); }
KeyFrames implements Iterable<Frame<T>> { @Borrowed("this") @RegionEffects("reads this:Instance") public int size() { return f_frames.length; } @RegionEffects("none") KeyFrames(@Unique Frame<T>[] frames, Evaluator<T> evaluator); @Borrowed("this") @RegionEffects("reads this:Instance") int size(); @NonNull Frame<T> getFrame(int index); @NonNull Class<?> getClassOfValue(); @Borrowed("this") @RegionEffects("reads this:Instance") @Unique("return") Iterator<Frame<T>> iterator(); @RegionEffects("reads any(org.jdesktop.core.animation.timing.KeyFrames.Frame):Instance, this:Instance") int getFrameIndexAt(double fraction); T getInterpolatedValueAt(double fraction); }
@Test public void builder1iterator() { final KeyFrames.Builder<Integer> b = new KeyFrames.Builder<Integer>(1); b.addFrame(2); final KeyFrames<Integer> kf = b.build(); Assert.assertEquals(2, kf.size()); int value = 1; double timeFraction = 0; final double fractionPerFrame = 1.0 / (kf.size() - 1); for (KeyFrames.Frame<Integer> f : kf) { if (value == 1) Assert.assertNull(f.getInterpolator()); else Assert.assertSame(LinearInterpolator.getInstance(), f.getInterpolator()); Assert.assertEquals(value++, f.getValue().intValue()); Assert.assertEquals(timeFraction, f.getTimeFraction(), 1e-9); timeFraction += fractionPerFrame; } Assert.assertEquals(3, value); } @Test public void builder2iterator() { final KeyFrames.Builder<Integer> b = new KeyFrames.Builder<Integer>(1); b.addFrame(2); b.addFrame(3); final KeyFrames<Integer> kf = b.build(); Assert.assertEquals(3, kf.size()); int value = 1; double timeFraction = 0; final double fractionPerFrame = 1.0 / (kf.size() - 1); for (KeyFrames.Frame<Integer> f : kf) { if (value == 1) Assert.assertNull(f.getInterpolator()); else Assert.assertSame(LinearInterpolator.getInstance(), f.getInterpolator()); Assert.assertEquals(value++, f.getValue().intValue()); Assert.assertEquals(timeFraction, f.getTimeFraction(), 1e-9); timeFraction += fractionPerFrame; } Assert.assertEquals(4, value); } @Test public void builder3iterator() { final int size = 10000; final KeyFrames.Builder<Integer> b = new KeyFrames.Builder<Integer>(1); for (int i = 2; i <= size; i++) { b.addFrame(i); } final KeyFrames<Integer> kf = b.build(); Assert.assertEquals(size, kf.size()); int value = 1; double timeFraction = 0; final double fractionPerFrame = 1.0 / (kf.size() - 1); for (KeyFrames.Frame<Integer> f : kf) { if (value == 1) Assert.assertNull(f.getInterpolator()); else Assert.assertSame(LinearInterpolator.getInstance(), f.getInterpolator()); Assert.assertEquals(value++, f.getValue().intValue()); Assert.assertEquals(timeFraction, f.getTimeFraction(), 1e-9); timeFraction += fractionPerFrame; } Assert.assertEquals(size + 1, value); }
KeyFrames implements Iterable<Frame<T>> { @NonNull public Frame<T> getFrame(int index) { return f_frames[index]; } @RegionEffects("none") KeyFrames(@Unique Frame<T>[] frames, Evaluator<T> evaluator); @Borrowed("this") @RegionEffects("reads this:Instance") int size(); @NonNull Frame<T> getFrame(int index); @NonNull Class<?> getClassOfValue(); @Borrowed("this") @RegionEffects("reads this:Instance") @Unique("return") Iterator<Frame<T>> iterator(); @RegionEffects("reads any(org.jdesktop.core.animation.timing.KeyFrames.Frame):Instance, this:Instance") int getFrameIndexAt(double fraction); T getInterpolatedValueAt(double fraction); }
@Test public void timeFraction() { final KeyFrames.Builder<Integer> b = new KeyFrames.Builder<Integer>(1); b.addFrame(2, 0.3); b.addFrame(3, 0.4); b.addFrame(4, 1); final KeyFrames<Integer> kf = b.build(); Assert.assertEquals(1, kf.getFrame(0).getValue().intValue()); Assert.assertEquals(2, kf.getFrame(1).getValue().intValue()); Assert.assertEquals(3, kf.getFrame(2).getValue().intValue()); Assert.assertEquals(4, kf.getFrame(3).getValue().intValue()); Assert.assertEquals(0.0, kf.getFrame(0).getTimeFraction(), 1e-9); Assert.assertEquals(0.3, kf.getFrame(1).getTimeFraction(), 1e-9); Assert.assertEquals(0.4, kf.getFrame(2).getTimeFraction(), 1e-9); Assert.assertEquals(1.0, kf.getFrame(3).getTimeFraction(), 1e-9); Assert.assertNull(kf.getFrame(0).getInterpolator()); Assert.assertSame(LinearInterpolator.getInstance(), kf.getFrame(1).getInterpolator()); Assert.assertSame(LinearInterpolator.getInstance(), kf.getFrame(2).getInterpolator()); Assert.assertSame(LinearInterpolator.getInstance(), kf.getFrame(3).getInterpolator()); } @Test public void allThree() { final Interpolator i = new SplineInterpolator(0, 1, 0, 1); final Interpolator a = new AccelerationInterpolator(0.1, 0.1); final KeyFrames.Builder<Integer> b = new KeyFrames.Builder<Integer>(1); b.addFrame(2, 0.3, i); b.addFrame(3, 0.4, a); b.addFrame(4, 1, DiscreteInterpolator.getInstance()); final KeyFrames<Integer> kf = b.build(); Assert.assertEquals(1, kf.getFrame(0).getValue().intValue()); Assert.assertEquals(2, kf.getFrame(1).getValue().intValue()); Assert.assertEquals(3, kf.getFrame(2).getValue().intValue()); Assert.assertEquals(4, kf.getFrame(3).getValue().intValue()); Assert.assertEquals(0.0, kf.getFrame(0).getTimeFraction(), 1e-9); Assert.assertEquals(0.3, kf.getFrame(1).getTimeFraction(), 1e-9); Assert.assertEquals(0.4, kf.getFrame(2).getTimeFraction(), 1e-9); Assert.assertEquals(1.0, kf.getFrame(3).getTimeFraction(), 1e-9); Assert.assertNull(kf.getFrame(0).getInterpolator()); Assert.assertSame(i, kf.getFrame(1).getInterpolator()); Assert.assertSame(a, kf.getFrame(2).getInterpolator()); Assert.assertSame(DiscreteInterpolator.getInstance(), kf.getFrame(3).getInterpolator()); } @Test public void frame2() { KeyFrames.Frame<Integer> f1 = new KeyFrames.Frame<Integer>(2, 0.3); KeyFrames.Frame<Integer> f2 = new KeyFrames.Frame<Integer>(3, 0.4); KeyFrames.Frame<Integer> f3 = new KeyFrames.Frame<Integer>(4, 1); final KeyFrames.Builder<Integer> b = new KeyFrames.Builder<Integer>(1); b.addFrame(f1); b.addFrame(f2); b.addFrame(f3); final KeyFrames<Integer> kf = b.build(); Assert.assertEquals(1, kf.getFrame(0).getValue().intValue()); Assert.assertEquals(2, kf.getFrame(1).getValue().intValue()); Assert.assertEquals(3, kf.getFrame(2).getValue().intValue()); Assert.assertEquals(4, kf.getFrame(3).getValue().intValue()); Assert.assertEquals(0.0, kf.getFrame(0).getTimeFraction(), 1e-9); Assert.assertEquals(0.3, kf.getFrame(1).getTimeFraction(), 1e-9); Assert.assertEquals(0.4, kf.getFrame(2).getTimeFraction(), 1e-9); Assert.assertEquals(1.0, kf.getFrame(3).getTimeFraction(), 1e-9); Assert.assertNull(kf.getFrame(0).getInterpolator()); Assert.assertSame(LinearInterpolator.getInstance(), kf.getFrame(1).getInterpolator()); Assert.assertSame(LinearInterpolator.getInstance(), kf.getFrame(2).getInterpolator()); Assert.assertSame(LinearInterpolator.getInstance(), kf.getFrame(3).getInterpolator()); } @Test public void frame4() { final Interpolator i = new SplineInterpolator(0, 1, 0, 1); final Interpolator a = new AccelerationInterpolator(0.1, 0.1); KeyFrames.Frame<Integer> f1 = new KeyFrames.Frame<Integer>(2, 0.3, i); KeyFrames.Frame<Integer> f2 = new KeyFrames.Frame<Integer>(3, 0.4, a); KeyFrames.Frame<Integer> f3 = new KeyFrames.Frame<Integer>(4, 1, DiscreteInterpolator.getInstance()); final KeyFrames.Builder<Integer> b = new KeyFrames.Builder<Integer>(1); b.addFrame(f1); b.addFrame(f2); b.addFrame(f3); final KeyFrames<Integer> kf = b.build(); Assert.assertEquals(1, kf.getFrame(0).getValue().intValue()); Assert.assertEquals(2, kf.getFrame(1).getValue().intValue()); Assert.assertEquals(3, kf.getFrame(2).getValue().intValue()); Assert.assertEquals(4, kf.getFrame(3).getValue().intValue()); Assert.assertEquals(0.0, kf.getFrame(0).getTimeFraction(), 1e-9); Assert.assertEquals(0.3, kf.getFrame(1).getTimeFraction(), 1e-9); Assert.assertEquals(0.4, kf.getFrame(2).getTimeFraction(), 1e-9); Assert.assertEquals(1.0, kf.getFrame(3).getTimeFraction(), 1e-9); Assert.assertNull(kf.getFrame(0).getInterpolator()); Assert.assertSame(i, kf.getFrame(1).getInterpolator()); Assert.assertSame(a, kf.getFrame(2).getInterpolator()); Assert.assertSame(DiscreteInterpolator.getInstance(), kf.getFrame(3).getInterpolator()); }
Animator implements TickListener { public void startReverse() { startHelper(f_startDirection.getOppositeDirection(), "startReverse()"); } @Unique("return") Animator(String debugName, long duration, @NonNull TimeUnit durationTimeUnit, @NonNull EndBehavior endBehavior, @NonNull Interpolator interpolator, @NonNull RepeatBehavior repeatBehavior, long repeatCount, @NonNull Direction startDirection, long startDelay, @NonNull TimeUnit startDelayTimeUnit, @NonNull TimingSource timingSource, boolean disposeTimingSource, @NonNull Collection<TimingTarget> targets); static void setDefaultTimingSource(@Nullable TimingSource timingSource); @Nullable static TimingSource getDefaultTimingSource(); @Nullable @RegionEffects("reads Instance") String getDebugName(); @RegionEffects("reads Instance") long getDuration(); @NonNull @RegionEffects("reads Instance") TimeUnit getDurationTimeUnit(); @NonNull @RegionEffects("reads Instance") EndBehavior getEndBehavior(); @NonNull Interpolator getInterpolator(); @NonNull @RegionEffects("reads Instance") RepeatBehavior getRepeatBehavior(); @RegionEffects("reads Instance") long getRepeatCount(); @NonNull @RegionEffects("reads Instance") Direction getStartDirection(); @RegionEffects("reads Instance") long getStartDelay(); @NonNull @RegionEffects("reads Instance") TimeUnit getStartDelayTimeUnit(); @NonNull @RegionEffects("reads Instance") TimingSource getTimingSource(); @RegionEffects("reads Instance") boolean getDisposeTimingSource(); void addTarget(final TimingTarget target); void addTargets(Collection<TimingTarget> targets); void addTargets(TimingTarget... targets); void removeTarget(TimingTarget target); void removeTargets(Collection<TimingTarget> targets); void removeTargets(TimingTarget... targets); ArrayList<TimingTarget> getTargets(); void clearTargets(); void start(); void restart(); void startReverse(); void restartReverse(); @RegionEffects("reads Instance") boolean isRunning(); @NonNull @RegionEffects("reads Instance") Direction getCurrentDirection(); boolean stop(); void stopAndAwait(); boolean cancel(); void cancelAndAwait(); void pause(); boolean isPaused(); void resume(); boolean reverseNow(); void await(); long getCycleElapsedTime(); @RegionEffects("reads Instance") long getCycleElapsedTime(long currentTimeNanos); long getTotalElapsedTime(); @RegionEffects("reads Instance") long getTotalElapsedTime(long currentTimeNanos); @Override @NonNull @RegionEffects("reads Instance") @Vouch("Uses StringBuilder") String toString(); void timingSourceTick(TimingSource source, long nanoTime); static final long INFINITE; }
@Test(expected = IllegalStateException.class) public void startReverse1() { Animator a = new Animator.Builder(new ManualTimingSource()).build(); a.startReverse(); a.startReverse(); }
PropertySetter { public static <T> TimingTargetAdapter getTargetTo(Object object, String propertyName, KeyFrames<T> keyFrames) { return getTargetHelper(object, propertyName, keyFrames, true); } private PropertySetter(); static TimingTargetAdapter getTarget(Object object, String propertyName, KeyFrames<T> keyFrames); static TimingTargetAdapter getTarget(Object object, String propertyName, T... values); static TimingTargetAdapter getTarget(Object object, String propertyName, Interpolator interpolator, T... values); static TimingTargetAdapter getTargetTo(Object object, String propertyName, KeyFrames<T> keyFrames); static TimingTargetAdapter getTargetTo(Object object, String propertyName, T... values); static TimingTargetAdapter getTargetTo(Object object, String propertyName, Interpolator interpolator, T... values); }
@Test(expected = IllegalArgumentException.class) public void noSuchPropertyTo1() { MyProps pt = new MyProps(); PropertySetter.getTargetTo(pt, "wrong", 1, 2, 3); } @Test(expected = IllegalArgumentException.class) public void noSuchPropertyTo2() { MyProps pt = new MyProps(); PropertySetter.getTargetTo(pt, "byteValue", (byte) 1, (byte) 2, (byte) 3); } @Test public void valuePropertyTo() { MyProps pt = new MyProps(); pt.setValue(100); TimingTarget tt = PropertySetter.getTargetTo(pt, "value", 1, 2, 3); ManualTimingSource ts = new ManualTimingSource(); Animator a = new Animator.Builder(ts).addTarget(tt).build(); a.start(); ts.tick(); Assert.assertEquals(100, pt.getValue()); while (a.isRunning()) ts.tick(); Assert.assertEquals(3, pt.getValue()); }
FileSystemPathRelative implements FileSystemPath { @Override public final Path path() { if (fromPath.equals(artifactPath)) return artifactPath.path(); return fromPath.path().relativize(artifactPath.path()); } FileSystemPathRelative(Path fromPath, String artifactPath); FileSystemPathRelative(String fromPath, String artifactPath); FileSystemPathRelative(FileSystemPath fromPath, FileSystemPath artifactPath); @Override final Path path(); @Override final boolean exist(); }
@Test public void asStringForParentWithSlashInTheEnd() { MatcherAssert.assertThat( new FileSystemPathRelative("/a/b/", "/a/b/c").path(), Matchers.is(new PathMatcher("c"))); } @Test public void asStringForParentWithoutSlashInTheEnd() { MatcherAssert.assertThat( new FileSystemPathRelative("/a/b", "/a/b/c").path(), Matchers.is(new PathMatcher("c"))); } @Test public void asStringWhenParentIsEqualsToFull() { MatcherAssert.assertThat( new FileSystemPathRelative("/a/b/c", "/a/b/c").path(), Matchers.is(new PathMatcher("/a/b/c"))); } @Test public void asStringForRelativeParentWithSlashInTheEnd() { MatcherAssert.assertThat( new FileSystemPathRelative("a/b/", "a/b/c").path(), Matchers.is(new PathMatcher("c"))); } @Test public void asStringForRelativeParentWithoutSlashInTheEnd() { MatcherAssert.assertThat( new FileSystemPathRelative("a/b", "a/b/c").path(), Matchers.is(new PathMatcher("c"))); }
DirectoryWithAutomaticDeletion implements Directory { @Override public final void create() throws IOException { Runtime.getRuntime() .addShutdownHook( new Thread("ds") { @Override public void run() { try { directory.remove(); } catch (IOException e) { throw new RuntimeException(e); } } }); directory.create(); } DirectoryWithAutomaticDeletion(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }
@Test public void create() throws IOException { final java.io.File file = testFolder.getRoot(); new DirectoryWithAutomaticDeletion(new Directory.Fake(file.toPath())).create(); MatcherAssert.assertThat("The directory wasn't created", file.exists()); }
DirectoryWithAutomaticDeletion implements Directory { @Override public final void remove() throws IOException { directory.remove(); } DirectoryWithAutomaticDeletion(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }
@Test public void remove() throws IOException { final java.io.File file = testFolder.getRoot(); new DirectoryWithAutomaticDeletion(new Directory.Fake(file.toPath())).remove(); MatcherAssert.assertThat("The directory exists", file.exists()); }
DirectoryWithAutomaticDeletion implements Directory { @Override public final boolean exist() { return directory.exist(); } DirectoryWithAutomaticDeletion(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }
@Test public void exist() { MatcherAssert.assertThat( "The directory isn't present", new DirectoryWithAutomaticDeletion( new Directory.Fake(testFolder.getRoot().toPath(), true)) .exist()); }
DirectoryWithAutomaticDeletion implements Directory { @Override public final Path path() { return directory.path(); } DirectoryWithAutomaticDeletion(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }
@Test public void path() { final Path file = testFolder.getRoot().toPath(); MatcherAssert.assertThat( new DirectoryWithAutomaticDeletion(new Directory.Fake(file)).path(), Matchers.equalTo(file)); }
FileSystemFiltered implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { return fileSystem.files().stream() .filter(f -> condition.applicable(f.path().toString())) .collect(Collectors.toList()); } FileSystemFiltered(FileSystem fileSystem, Condition condition); @Override List<FileSystemPath> files(); }
@Test public void files() throws FileSystemException { MatcherAssert.assertThat( new FileSystemFiltered( new FileSystem.Fake( Collections.singletonList(new FileSystemPath.Fake())), new Condition.Fake(false)) .files(), Matchers.hasSize(0)); }
RegexCondition implements Condition { @Override public final boolean applicable(String identity) { return regex.matcher(identity).matches(); } RegexCondition(); RegexCondition(String regex); RegexCondition(Pattern regex); @Override final boolean applicable(String identity); }
@Test public void applicable() { MatcherAssert.assertThat( "Regex doesn't work for " + this.className, new RegexCondition().applicable(this.className)); }
SunshineSuitePrintable implements SunshineSuite { @Override public final List<SunshineTest> tests() throws SuiteException { final List<SunshineTest> tests = this.sunshineSuite.tests(); final StringBuilder message = new StringBuilder(); message.append("Sunshine found ") .append(tests.size()) .append( " classes by the specified pattern. They all will be passed to appropriate xUnit engine.") .append("\nClasses:"); tests.forEach(c -> message.append("\n- ").append(c)); System.out.println(message); return tests; } SunshineSuitePrintable(SunshineSuite sunshineSuite); @Override final List<SunshineTest> tests(); }
@Test public void tests() throws SuiteException { final SunshineTest.Fake test = new SunshineTest.Fake(); MatcherAssert.assertThat( new SunshineSuitePrintable(new SunshineSuite.Fake(test)).tests(), Matchers.contains(test)); }
Sun implements Star { @Override public final void shine() { try { final Status status = this.core.status(); System.out.println( new StringBuilder("\n===============================================\n") .append("Total tests run: ") .append(status.runCount()) .append(", Failures: ") .append(status.failureCount()) .append(", Skips: ") .append(status.ignoreCount()) .append("\n===============================================\n")); System.exit(status.code()); } catch (KernelException e) { e.printStackTrace(System.out); System.exit(Sun.SUNSHINE_ERROR); } } Sun(Kernel<?> kernel); @Override final void shine(); }
@Test public void shine() { exit.expectSystemExitWithStatus(0); new Sun(new Kernel.Fake(new Fake())).shine(); }
FileSystemOfClasspathClasses implements FileSystem { @Override public final List<FileSystemPath> files() throws FileSystemException { return fileSystem.files(); } FileSystemOfClasspathClasses(); private FileSystemOfClasspathClasses(FileSystem fileSystem); @Override final List<FileSystemPath> files(); }
@Test public void files() throws FileSystemException { MatcherAssert.assertThat( new FileSystemOfClasspathClasses().files(), Matchers.not(Matchers.empty())); }
FileSystemOfPath implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { try { List<FileSystemPath> files = new ArrayList<>(); Files.walkFileTree( path, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs) { files.add(new FileSystemPathRelative(path, dir.toString())); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { files.add(new FileSystemPathRelative(path, file.toString())); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return FileVisitResult.CONTINUE; } }); return files; } catch (IOException e) { throw new FileSystemException(e); } } FileSystemOfPath(String path); FileSystemOfPath(Path path); @Override List<FileSystemPath> files(); }
@Test public void files() throws FileSystemException { CustomTypeSafeMatcher<Integer> matcher = new CustomTypeSafeMatcher<Integer>("Has at least one item") { @Override protected boolean matchesSafely(Integer item) { return item > 0; } }; MatcherAssert.assertThat( new FileSystemOfPath(RESOURCES).files(), Matchers.hasSize(matcher)); }
SequentialExecution implements Kernel<Listener> { @Override public Status status() throws KernelException { final List<Status> results = new ArrayList<>(); for (Kernel<Listener> kernel : this.elements) { results.add(kernel.status()); } return new CompositeStatus(results); } @SafeVarargs SequentialExecution(Kernel<Listener>... kernels); SequentialExecution(List<Kernel<Listener>> kernels); @Override Status status(); @Override Kernel<Listener> with(Listener... listeners); }
@Test public void testStatus() throws KernelException { MatcherAssert.assertThat( new SequentialExecution<Object>( new Kernel.Fake(new Status.Fake()), new Kernel.Fake(new Status.Fake((short) 1, 2, 1, 1))) .status() .code(), Matchers.is((short) 1)); }
SequentialExecution implements Kernel<Listener> { @Override public Kernel<Listener> with(Listener... listeners) { return new SequentialExecution<>( this.elements.stream() .map(listenerKernel -> listenerKernel.with(listeners)) .collect(Collectors.toList())); } @SafeVarargs SequentialExecution(Kernel<Listener>... kernels); SequentialExecution(List<Kernel<Listener>> kernels); @Override Status status(); @Override Kernel<Listener> with(Listener... listeners); }
@Test public void testWithListeners() { final List<Object> listeners = new ArrayList<>(); new SequentialExecution<Object>(new Kernel.Fake(new Status.Fake(), listeners)) .with(new Object()); MatcherAssert.assertThat(listeners, Matchers.hasSize(1)); }
FileSystemOfFileSystems implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { List<FileSystemPath> files = new ArrayList<>(); for (FileSystem fileSystem : fileSystems) { files.addAll(fileSystem.files()); } return files; } FileSystemOfFileSystems(List<FileSystem> fileSystems); FileSystemOfFileSystems(FileSystem... fileSystems); @Override List<FileSystemPath> files(); }
@Test public void files() throws FileSystemException { List<FileSystem> fileSystems = Arrays.asList( new FileSystem.Fake(Collections.singletonList(new FileSystemPath.Fake())), new FileSystem.Fake(Collections.singletonList(new FileSystemPath.Fake()))); MatcherAssert.assertThat( new FileSystemOfFileSystems(fileSystems).files(), Matchers.hasSize(2)); }
FileSystemPathBase implements FileSystemPath { @Override public final Path path() { return directory.resolve(file); } FileSystemPathBase(String path); FileSystemPathBase(String directory, String file); FileSystemPathBase(Path path); FileSystemPathBase(Directory directory, String fsPath); FileSystemPathBase(Path directory, String file); @Override final Path path(); @Override final boolean exist(); }
@Test public void path() { final String path = "aa"; MatcherAssert.assertThat( new FileSystemPathBase(path).path(), Matchers.equalTo(Paths.get(path))); } @Test public void pathWithFolder() { final String directory = "aa"; final String file = "file"; MatcherAssert.assertThat( new FileSystemPathBase(directory, file).path(), Matchers.equalTo(Paths.get(directory + "/" + file))); }
FileSystemPathBase implements FileSystemPath { @Override public final boolean exist() { return Files.exists(path()); } FileSystemPathBase(String path); FileSystemPathBase(String directory, String file); FileSystemPathBase(Path path); FileSystemPathBase(Directory directory, String fsPath); FileSystemPathBase(Path directory, String file); @Override final Path path(); @Override final boolean exist(); }
@Test public void exist() { MatcherAssert.assertThat( "File is absent", new FileSystemPathBase( "src/main/java/org/tatools/sunshine/core/FileSystemPathBase.java") .exist()); }
DirectoryBase implements Directory { @Override public final void create() throws IOException { Files.createDirectory(fileSystemPath.path()); } DirectoryBase(String path); DirectoryBase(Path path); DirectoryBase(FileSystemPath fileSystemPath); @Override final void create(); @Override final void remove(); @Override final boolean exist(); @Override final Path path(); }
@Test public void create() throws IOException { final FileSystemPathBase path = new FileSystemPathBase(testFolder.getRoot().getAbsolutePath(), "a"); new DirectoryBase(path).create(); MatcherAssert.assertThat("The directory wasn't created", path.exist()); }
DirectoryBase implements Directory { @Override public final void remove() throws IOException { Files.walk(fileSystemPath.path(), FileVisitOption.FOLLOW_LINKS) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(java.io.File::delete); } DirectoryBase(String path); DirectoryBase(Path path); DirectoryBase(FileSystemPath fileSystemPath); @Override final void create(); @Override final void remove(); @Override final boolean exist(); @Override final Path path(); }
@Test public void remove() throws IOException { java.io.File file = testFolder.newFolder(); final FileSystemPathBase path = new FileSystemPathBase(file.toString()); new DirectoryBase(path).remove(); MatcherAssert.assertThat("The directory exists", !path.exist()); }
DirectoryBase implements Directory { @Override public final boolean exist() { return fileSystemPath.exist(); } DirectoryBase(String path); DirectoryBase(Path path); DirectoryBase(FileSystemPath fileSystemPath); @Override final void create(); @Override final void remove(); @Override final boolean exist(); @Override final Path path(); }
@Test public void exist() { MatcherAssert.assertThat( "The directory isn't present", new DirectoryBase(new FileSystemPathBase(testFolder.getRoot().getAbsolutePath())) .exist()); }
DirectoryBase implements Directory { @Override public final Path path() { return fileSystemPath.path(); } DirectoryBase(String path); DirectoryBase(Path path); DirectoryBase(FileSystemPath fileSystemPath); @Override final void create(); @Override final void remove(); @Override final boolean exist(); @Override final Path path(); }
@Test public void path() { final String path = "a"; MatcherAssert.assertThat(new DirectoryBase(path).path(), Matchers.equalTo(Paths.get(path))); }
VerboseRegex implements Condition { @Override public final boolean applicable(String identity) { if (say[0]) { this.printer.println( String.format( "The following pattern will be used for classes filtering: %s", this.regexCondition.regex.pattern())); Arrays.fill(say, false); } return this.regexCondition.applicable(identity); } VerboseRegex(RegexCondition condition); VerboseRegex(RegexCondition regexCondition, PrintStream printer); @Override final boolean applicable(String identity); }
@Test public void testIfMessageIsDisplayedOnce() { final ByteArrayOutputStream result = new ByteArrayOutputStream(); final VerboseRegex regex = new VerboseRegex(new RegexCondition("ddd"), new PrintStream(result)); regex.applicable("a"); regex.applicable("b"); MatcherAssert.assertThat( new String(result.toByteArray()), Matchers.is("The following pattern will be used for classes filtering: ddd\n")); }
DirectoryWithAutomaticCreation implements Directory { @Override public final void create() throws IOException { this.directory.create(); } DirectoryWithAutomaticCreation(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }
@Test public void create() throws IOException { final FileSystemPathBase path = new FileSystemPathBase(testFolder.newFolder().toString(), "a"); new DirectoryWithAutomaticCreation(new DirectoryBase(path)).create(); MatcherAssert.assertThat("The directory wasn't created", path.exist()); }
DirectoryWithAutomaticCreation implements Directory { @Override public final void remove() throws IOException { this.directory.remove(); } DirectoryWithAutomaticCreation(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }
@Test public void remove() throws IOException { final FileSystemPathBase path = new FileSystemPathBase(testFolder.newFolder().toString()); new DirectoryWithAutomaticCreation(new DirectoryBase(path)).remove(); MatcherAssert.assertThat("The directory wasn't removed", !path.exist()); }
DirectoryWithAutomaticCreation implements Directory { @Override public final boolean exist() { try { this.create(); return true; } catch (IOException e) { throw new RuntimeException(e); } } DirectoryWithAutomaticCreation(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }
@Test public void exist() throws IOException { final FileSystemPathBase path = new FileSystemPathBase(testFolder.newFolder().toString(), "a"); new DirectoryWithAutomaticCreation(new DirectoryBase(path)).exist(); MatcherAssert.assertThat("The directory wasn't created", path.exist()); }
DirectoryWithAutomaticCreation implements Directory { @Override public final Path path() { try { this.create(); return this.directory.path(); } catch (IOException e) { throw new RuntimeException(e); } } DirectoryWithAutomaticCreation(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }
@Test public void path() throws IOException { final FileSystemPathBase path = new FileSystemPathBase(testFolder.newFolder().toString(), "a"); new DirectoryWithAutomaticCreation(new DirectoryBase(path)).path(); MatcherAssert.assertThat("The directory wasn't created", path.exist()); }
SuiteFromClasses implements SunshineSuite { @Override public final List<SunshineTest> tests() throws SuiteException { return Arrays.stream(this.classes).map(TestFromClass::new).collect(Collectors.toList()); } SuiteFromClasses(Class... clazz); @Override final List<SunshineTest> tests(); }
@Test public void tests() throws SuiteException { MatcherAssert.assertThat( new SuiteFromClasses(SuiteFromClasses.class).tests(), Matchers.hasSize(1)); }
FileSystemOfClasses implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { return fileSystem.files(); } FileSystemOfClasses(FileSystem fileSystem); @Override List<FileSystemPath> files(); }
@Test public void onlyFilesInFileSystem() throws FileSystemException { MatcherAssert.assertThat( new FileSystemOfClasses( new FileSystem.Fake( Arrays.asList( new FileSystemPath.Fake("SomeTest.class"), new FileSystemPath.Fake("some-file.txt")))) .files(), Matchers.hasSize(1)); } @Test public void filesAndJarsInFileSystem() throws FileSystemException { MatcherAssert.assertThat( new FileSystemOfClasses(new FileSystemOfJarFile("build/sample-tests.jar")).files(), Matchers.hasSize(5)); }
Junit4Kernel implements Kernel<RunListener> { @Override public final Status status() throws KernelException { try { return new JunitStatus(this.junit.run(new Computer(), this.suiteForRun.tests())); } catch (SuiteException e) { throw new KernelException("Some problem occurs in the JUnit 4 kernel", e); } } Junit4Kernel(Suite<Class<?>[]> suite); private Junit4Kernel(JUnitCore jUnitCore, Suite<Class<?>[]> suite); @Override final Status status(); @Override final Junit4Kernel with(RunListener... listeners); }
@Test public void run() throws KernelException { MatcherAssert.assertThat( new Junit4Kernel(() -> new Class[] {}).status().code(), Matchers.equalTo((short) 0)); } @Test(expected = KernelException.class) public void runWithFail() throws KernelException { new Junit4Kernel( () -> { throw new SuiteException("Fail"); }) .status(); }
Junit4Kernel implements Kernel<RunListener> { @Override public final Junit4Kernel with(RunListener... listeners) { final JUnitCore jUnitCore = new JUnitCore(); Arrays.stream(listeners).forEach(jUnitCore::addListener); return new Junit4Kernel(jUnitCore, this.suiteForRun); } Junit4Kernel(Suite<Class<?>[]> suite); private Junit4Kernel(JUnitCore jUnitCore, Suite<Class<?>[]> suite); @Override final Status status(); @Override final Junit4Kernel with(RunListener... listeners); }
@Test public void with() throws KernelException { final Listener l1 = new Listener(); final Listener l2 = new Listener(); new Junit4Kernel(() -> new Class[] {}).with(l1).with(l2).status(); MatcherAssert.assertThat(l1, Matchers.not(Matchers.equalTo(l2))); }
JunitSuite implements Suite<Class<?>[]> { @Override public final Class<?>[] tests() throws SuiteException { List<Class<?>> tests = new ArrayList<>(); for (SunshineTest test : this.suite.tests()) { try { tests.add(test.object()); } catch (TestException e) { throw new SuiteException(e); } } return tests.toArray(new Class[] {}); } JunitSuite(Condition filter); JunitSuite(FileSystem fileSystem, Condition filter); JunitSuite(SunshineSuite classesAsSuite); @Override final Class<?>[] tests(); }
@Test public void testDefaultSuite() throws SuiteException { MatcherAssert.assertThat( new JunitSuite(() -> Collections.emptyList()).tests(), Matchers.arrayWithSize(0)); } @Test public void testDefaultFileSystemAndTestsFilter() throws SuiteException { MatcherAssert.assertThat( new JunitSuite(new FileSystem.Fake(), new Condition.Fake(false)).tests(), Matchers.arrayWithSize(0)); } @Test public void testDefaultTestsFilter() throws SuiteException { MatcherAssert.assertThat( new JunitSuite(new Condition.Fake(false)).tests(), Matchers.arrayWithSize(0)); }
JunitStatus implements Status { @Override public final short code() { if (this.status.wasSuccessful()) { return (short) 0; } return (short) 1; } JunitStatus(Result result); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }
@Test public void codeIfPassed() { MatcherAssert.assertThat( new JunitStatus(new FakeResult(true, 0, 0, 0)).code(), Matchers.is((short) 0)); } @Test public void codeIfFailed() { MatcherAssert.assertThat( new JunitStatus(new FakeResult(false, 0, 0, 0)).code(), Matchers.is((short) 1)); }
JunitStatus implements Status { @Override public final int runCount() { return status.getRunCount(); } JunitStatus(Result result); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }
@Test public void runCount() { MatcherAssert.assertThat( new JunitStatus(new FakeResult(false, 3, 0, 0)).runCount(), Matchers.is(3)); }
JunitStatus implements Status { @Override public final int failureCount() { return status.getFailureCount(); } JunitStatus(Result result); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }
@Test public void failureCount() { MatcherAssert.assertThat( new JunitStatus(new FakeResult(false, 0, 2, 0)).failureCount(), Matchers.is(2)); }
JunitStatus implements Status { @Override public final int ignoreCount() { return status.getIgnoreCount(); } JunitStatus(Result result); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }
@Test public void ignoreCount() { MatcherAssert.assertThat( new JunitStatus(new FakeResult(false, 0, 0, 5)).ignoreCount(), Matchers.is(5)); }
Junit5Status implements Status { @Override public final short code() { return this.summary.getTotalFailureCount() == 0 ? this.passed : this.failed; } Junit5Status(TestExecutionSummary testExecutionSummary); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }
@Test void codePassed() { MatcherAssert.assertThat( new Junit5Status(new Summary(1, 0, 0, 0)).code(), Matchers.is((short) 0)); } @Test void codeFailed() { MatcherAssert.assertThat( new Junit5Status(new Summary(1, 0, 0, 1)).code(), Matchers.is((short) 1)); }
Junit5Status implements Status { @Override public final int runCount() { return Math.toIntExact(this.summary.getTestsFoundCount()); } Junit5Status(TestExecutionSummary testExecutionSummary); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }
@Test void runCount() { MatcherAssert.assertThat( new Junit5Status(new Summary(5, 4, 3, 1)).runCount(), Matchers.is(5)); }
Junit5Status implements Status { @Override public final int failureCount() { return Math.toIntExact(this.summary.getTestsFailedCount()); } Junit5Status(TestExecutionSummary testExecutionSummary); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }
@Test void failureCount() { MatcherAssert.assertThat( new Junit5Status(new Summary(5, 4, 3, 1)).failureCount(), Matchers.is(4)); }
Junit5Status implements Status { @Override public final int ignoreCount() { return Math.toIntExact(this.summary.getTestsSkippedCount()); } Junit5Status(TestExecutionSummary testExecutionSummary); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }
@Test void ignoreCount() { MatcherAssert.assertThat( new Junit5Status(new Summary(5, 4, 3, 1)).ignoreCount(), Matchers.is(3)); }
Junit5Kernel implements Kernel<TestExecutionListener> { @Override public final Status status() throws KernelException { try { launcher.execute( LauncherDiscoveryRequestBuilder.request() .selectors( tests.tests().stream() .map( sunshineTest -> DiscoverySelectors.selectClass( sunshineTest.toString())) .toArray(DiscoverySelector[]::new)) .build()); return new Junit5Status(this.reporter.getSummary()); } catch (SuiteException e) { throw new KernelException("Some problem occurs in the Junit5Kernel", e); } } Junit5Kernel(SunshineSuite sunshineSuite); private Junit5Kernel(Launcher launcher, SunshineSuite sunshineSuite); @Override final Status status(); @Override final Kernel<TestExecutionListener> with( TestExecutionListener... testExecutionListeners); }
@Test public void run() throws KernelException { MatcherAssert.assertThat( new Junit5Kernel(ArrayList::new).status().code(), Matchers.equalTo((short) 0)); }
Junit5Kernel implements Kernel<TestExecutionListener> { @Override public final Kernel<TestExecutionListener> with( TestExecutionListener... testExecutionListeners) { final Launcher fork = LauncherFactory.create(); fork.registerTestExecutionListeners(testExecutionListeners); return new Junit5Kernel(fork, this.tests); } Junit5Kernel(SunshineSuite sunshineSuite); private Junit5Kernel(Launcher launcher, SunshineSuite sunshineSuite); @Override final Status status(); @Override final Kernel<TestExecutionListener> with( TestExecutionListener... testExecutionListeners); }
@Test public void with() throws KernelException { final Listener l1 = new Listener(); final Listener l2 = new Listener(); new Junit5Kernel(ArrayList::new).with(l1).with(l2).status(); MatcherAssert.assertThat(l1, Matchers.not(Matchers.equalTo(l2))); }
FileSystemOfJarFile implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { try { List<FileSystemPath> data = new ArrayList<>(); ZipInputStream zip = new ZipInputStream(new FileInputStream(jarPath)); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { data.add(new FileSystemPathBase(entry.getName())); } return data; } catch (IOException e) { throw new FileSystemException(e); } } FileSystemOfJarFile(FileSystemPath jarPath); FileSystemOfJarFile(String jarPath); @Override List<FileSystemPath> files(); }
@Test public void files() throws FileSystemException { MatcherAssert.assertThat( new FileSystemOfJarFile("build/sample-tests.jar").files(), Matchers.hasItem(new FileSystemPathBase("org/tatools/testng/Test1.class"))); } @Test(expected = FileSystemException.class) public void incorrectPath() throws FileSystemException { new FileSystemOfJarFile("faffasfas").files(); }
SuiteFromFileSystem implements SunshineSuite { @Override public final List<SunshineTest> tests() throws SuiteException { try { return fileSystem.files().stream() .map(f -> new TestFromFile(f.path().toString())) .collect(Collectors.toList()); } catch (FileSystemException e) { throw new SuiteException(e); } } SuiteFromFileSystem(FileSystem fileSystem); @Override final List<SunshineTest> tests(); }
@Test public void tests() throws SuiteException { MatcherAssert.assertThat( new SuiteFromFileSystem(new FileSystem.Fake(new FileSystemPath.Fake("a"))).tests(), Matchers.hasSize(1)); }
FileBase implements File { @Override public final void write(String data) throws IOException { Files.write(this.path(), data.getBytes()); } FileBase(Directory directory, String file); FileBase(String directory, String file); FileBase(Path directory, String file); FileBase(FileSystemPath fileSystemPath); @Override final Path path(); @Override final boolean exist(); @Override final void write(String data); }
@Test public void write() throws IOException { final FileBase file = new FileBase(testFolder.getRoot().getAbsolutePath(), "ccc"); file.write("dasd"); MatcherAssert.assertThat(Files.exists(file.path()), Matchers.is(true)); }
FileSystemOfJarFiles implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { return new FileSystemOfFileSystems(mapping.objects(fileSystem)).files(); } FileSystemOfJarFiles(FileSystem fileSystem); private FileSystemOfJarFiles(FileSystem fileSystem, Mapping mapping); @Override List<FileSystemPath> files(); }
@Test public void files() throws FileSystemException { MatcherAssert.assertThat( new FileSystemOfJarFiles( new FileSystem.Fake( new FileSystemPath.Fake("build/sample-tests.jar"), new FileSystemPath.Fake("build/sample-tests.jar"))) .files(), Matchers.hasSize(20)); }
ObjectClassNameBuilder { public String build() { final StringBuilder nameBuilder = new StringBuilder(); Collections.reverse(enclosingClassSimpleNames); for (String enclosingClassSimpleName : enclosingClassSimpleNames) { nameBuilder.append(enclosingClassSimpleName).append("$"); } return nameBuilder + targetClassSimpleName + RETAINER_CLASS_SUFFIX; } ObjectClassNameBuilder(String targetClassSimpleName); ObjectClassNameBuilder addEnclosingClassSimpleName(String enclosingClassSimpleName); String build(); }
@Test public void testBuild() { final String objectClassName = new ObjectClassNameBuilder("TargetClass").build(); assertEquals("TargetClass_Retainer", objectClassName); }
Lyra { @NonNull public static Lyra instance() { if (!isInitialized()) { throw new NullPointerException("Instance not initialized. You have to build it in your application."); } return instance; } @SuppressLint("NewApi") private Lyra(@NonNull Application application, @NonNull CoderRetriever coderRetriever, @NonNull FieldsRetriever fieldsRetriever, boolean autoSaveActivities); static Builder with(@NonNull Application application); @SuppressLint("NewApi") static void destroy(); static boolean isInitialized(); @NonNull static Lyra instance(); @NonNull static String getKeyFromField(@NonNull Field field); void saveState(@NonNull Object stateHolder, @NonNull Bundle state); void restoreState(@NonNull Object stateHolder, @Nullable Bundle state); Parcelable saveState(@NonNull View stateHolder, @Nullable Parcelable state); Parcelable restoreState(@NonNull View stateHolder, @Nullable Parcelable state); static final String SUB_BUNDLE_KEY; static final String VIEW_SUPER_STATE_BUNDLE_KEY; }
@Test public void testInstanceNotNull() { assertNotNull(Lyra.instance()); }
DefaultFieldsRetriever implements FieldsRetriever { public Field[] getFields(@NonNull Class<?> cls) { Field[] cachedFields = mCachedFields.get(cls); if (cachedFields != null) return cachedFields; Class<?> currentClass = cls; final List<Field> futureCachedFields = new LinkedList<>(); do { Field[] declaredFields = currentClass.getDeclaredFields(); for (int i = 0; i < currentClass.getDeclaredFields().length; i++) { final Field field = declaredFields[i]; final Annotation annotation = field.getAnnotation(SaveState.class); if (annotation == null) continue; futureCachedFields.add(field); } } while ((currentClass = currentClass.getSuperclass()) != null); cachedFields = futureCachedFields.toArray(new Field[futureCachedFields.size()]); mCachedFields.put(cls, cachedFields); return cachedFields; } DefaultFieldsRetriever(); Field[] getFields(@NonNull Class<?> cls); }
@Test public void testRetrieveAnnotatedFieldsWithAllModifiers() { Field[] fields = mRetriever.getFields(TestModels.AllModifiersAnnotatedFields.class); assertNotNull(fields); assertThat(fields, FieldMatcher.haveNames("a", "b", "c", "d")); } @Test public void testRetrieveAnnotatedFieldsInheritance() { Field[] fields = mRetriever.getFields(TestModels.SubClassAllModifiersAnnotatedFields.class); assertNotNull(fields); assertThat(fields, FieldMatcher.haveNames("a", "b", "c", "d", "e", "f", "g", "h")); } @Test public void testRetrieveCachedAnnotatedFieldsInheritance() { Field[] fields = mRetriever.getFields(TestModels.SubClassAllModifiersAnnotatedFields.class); assertNotNull(fields); assertThat(fields, FieldMatcher.haveNames("a", "b", "c", "d", "e", "f", "g", "h")); fields = mRetriever.getFields(TestModels.SubClassAllModifiersAnnotatedFields.class); assertNotNull(fields); assertThat(fields, FieldMatcher.haveNames("a", "b", "c", "d", "e", "f", "g", "h")); } @Test public void testRetrieveZeroFields() { Field[] fields = mRetriever.getFields(TestModels.ZeroFields.class); assertNotNull(fields); assertEquals(fields.length, 0); } @Test public void testRetrieveZeroAnnotatedFields() { Field[] fields = mRetriever.getFields(TestModels.ZeroAnnotatedFields.class); assertNotNull(fields); assertEquals(fields.length, 0); } @Test public void testRetrievePublicAnnotatedFields() { Field[] fields = mRetriever.getFields(TestModels.PublicAnnotatedFields.class); assertNotNull(fields); assertThat(fields, FieldMatcher.haveNames("a", "b")); } @Test public void testRetrieveMixedAnnotatedFields() { Field[] fields = mRetriever.getFields(TestModels.MixedPublicFields.class); assertNotNull(fields); assertThat(fields, FieldMatcher.haveNames("b")); }
DefaultCoderRetriever implements CoderRetriever { @NonNull @Override public StateCoder getCoder(@NonNull SaveState saveState, @NonNull Class<?> annotatedFieldClass) throws CoderNotFoundException { StateCoder stateCoder; final Class<? extends StateCoder> stateSDClass = saveState.value(); if (stateSDClass == StateCoder.class) { stateCoder = mCachedCoders.get(annotatedFieldClass); if (stateCoder != null) return stateCoder; stateCoder = StateCoderUtils.getBasicCoderForClass(annotatedFieldClass); mCachedCoders.put(annotatedFieldClass, stateCoder); } else { try { Constructor<? extends StateCoder> constructor = stateSDClass.getConstructor(); boolean accessible = constructor.isAccessible(); if (!accessible) { constructor.setAccessible(true); } stateCoder = constructor.newInstance(); if (!accessible) { constructor.setAccessible(false); } } catch (Exception e) { throw new RuntimeException("Cannot instantiate a " + StateCoder.class.getSimpleName() + " of class " + stateSDClass.getName()); } } return stateCoder; } DefaultCoderRetriever(); @NonNull @Override StateCoder getCoder(@NonNull SaveState saveState, @NonNull Class<?> annotatedFieldClass); }
@Test public void testRetrieveBasicCoder() throws CoderNotFoundException { Class fieldClass = String.class; SaveState mockedSaveState = mock(SaveState.class); when(mockedSaveState.value()).thenAnswer(new Answer<Class<? extends StateCoder>>() { @Override public Class<? extends StateCoder> answer(InvocationOnMock invocationOnMock) throws Throwable { return StateCoder.class; } }); StateCoder retrieverCoder = mRetriever.getCoder(mockedSaveState, fieldClass); assertNotNull(retrieverCoder); StateCoder basicCoder = StateCoderUtils.getBasicCoderForClass(fieldClass); assertEquals(retrieverCoder.getClass(), basicCoder.getClass()); } @Test public void testRetrieveBasicCachedCoder() throws CoderNotFoundException { Class fieldClass = String.class; SaveState mockedSaveState = mock(SaveState.class); when(mockedSaveState.value()).thenAnswer(new Answer<Class<? extends StateCoder>>() { @Override public Class<? extends StateCoder> answer(InvocationOnMock invocationOnMock) throws Throwable { return StateCoder.class; } }); StateCoder retrieverCoder = mRetriever.getCoder(mockedSaveState, fieldClass); assertNotNull(retrieverCoder); StateCoder basicCoder = StateCoderUtils.getBasicCoderForClass(fieldClass); assertEquals(retrieverCoder.getClass(), basicCoder.getClass()); retrieverCoder = mRetriever.getCoder(mockedSaveState, fieldClass); assertNotNull(retrieverCoder); assertEquals(retrieverCoder.getClass(), basicCoder.getClass()); } @Test public void testRetrieveCustomCoder() throws CoderNotFoundException { Class fieldClass = String.class; SaveState mockedSaveState = mock(SaveState.class); when(mockedSaveState.value()).thenAnswer(new Answer<Class<? extends StateCoder>>() { @Override public Class<? extends StateCoder> answer(InvocationOnMock invocationOnMock) throws Throwable { return CustomStateCoder.class; } }); StateCoder retrieverCoder = mRetriever.getCoder(mockedSaveState, fieldClass); assertNotNull(retrieverCoder); assertEquals(retrieverCoder.getClass(), CustomStateCoder.class); }
StateCoderUtils { @NonNull public static StateCoder getBasicCoderForClass(@NonNull Class<?> cls) throws CoderNotFoundException { if (boolean.class == cls || Boolean.class == cls) return new BooleanCoder(); if (boolean[].class == cls) return new BooleanArrayCoder(); if (byte.class == cls || Byte.class == cls) return new ByteCoder(); if (byte[].class == cls) return new ByteArrayCoder(); if (char.class == cls || Character.class == cls) return new CharCoder(); if (char[].class == cls) return new CharArrayCoder(); if (CharSequence.class == cls) return new CharSequenceCoder(); if (CharSequence[].class == cls) return new CharSequenceArrayCoder(); if (double.class == cls || Double.class == cls) return new DoubleCoder(); if (double[].class == cls) return new DoubleArrayCoder(); if (float.class == cls || Float.class == cls) return new FloatCoder(); if (float[].class == cls) return new FloatArrayCoder(); if (IBinder.class == cls) return new IBinderCoder(); if (int.class == cls || Integer.class == cls) return new IntCoder(); if (int[].class == cls) return new IntArrayCoder(); if (long.class == cls || Long.class == cls) return new LongCoder(); if (long[].class == cls) return new LongArrayCoder(); if (Parcelable.class == cls) return new ParcelableCoder(); if (Parcelable[].class == cls) return new ParcelableArrayCoder(); if (Serializable.class == cls) return new SerializableCoder(); if (short.class == cls || Short.class == cls) return new ShortCoder(); if (short[].class == cls) return new ShortArrayCoder(); if (String.class == cls) return new StringCoder(); if (String[].class == cls) return new StringArrayCoder(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (Size.class == cls) return new SizeCoder(); if (SizeF.class == cls) return new SizeFCoder(); } return getBasicCoderForInheritedClass(cls); } private StateCoderUtils(); @NonNull static StateCoder getBasicCoderForClass(@NonNull Class<?> cls); }
@Test public void testRightCoderForInheritedBasicSupportedType() throws CoderNotFoundException { StateCoder coder = StateCoderUtils.getBasicCoderForClass(String.class); assertEquals(StringCoder.class, coder.getClass()); }
ShortCoder extends BaseCoder<Short> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Short fieldValue) { state.putShort(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Short fieldValue); }
@Test public void testSerializeShortPrimitive() { short expectedValue = 9; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getShort(randomKey())); } @Test public void testSerializeShortObject() { Short expectedValue = 9; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, (Short) bundle().getShort(randomKey())); }
CharArrayCoder extends BaseCoder<char[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull char[] fieldValue) { state.putCharArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull char[] fieldValue); }
@Test public void testSerializeCharArray() { char[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getCharArray(randomKey())); }
Lyra { @SuppressLint("NewApi") public static void destroy() { if (isInitialized()) { if (instance.mAutomaticSaveStateManager != null) { instance.mApplication.unregisterActivityLifecycleCallbacks(instance.mAutomaticSaveStateManager); } instance.mApplication = null; instance = null; } } @SuppressLint("NewApi") private Lyra(@NonNull Application application, @NonNull CoderRetriever coderRetriever, @NonNull FieldsRetriever fieldsRetriever, boolean autoSaveActivities); static Builder with(@NonNull Application application); @SuppressLint("NewApi") static void destroy(); static boolean isInitialized(); @NonNull static Lyra instance(); @NonNull static String getKeyFromField(@NonNull Field field); void saveState(@NonNull Object stateHolder, @NonNull Bundle state); void restoreState(@NonNull Object stateHolder, @Nullable Bundle state); Parcelable saveState(@NonNull View stateHolder, @Nullable Parcelable state); Parcelable restoreState(@NonNull View stateHolder, @Nullable Parcelable state); static final String SUB_BUNDLE_KEY; static final String VIEW_SUPER_STATE_BUNDLE_KEY; }
@Test public void testDestroy() { Lyra.destroy(); assertFalse(Lyra.isInitialized()); }
StringCoder extends BaseCoder<String> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull String fieldValue) { state.putString(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull String fieldValue); }
@Test public void testSerializeString() { String expectedValue = "test"; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getString(randomKey())); }
SizeFCoder extends BaseCoder<SizeF> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull SizeF fieldValue) { state.putSizeF(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull SizeF fieldValue); }
@Test public void testSerializeSizeF() { SizeF expectedValue = new SizeF(9, 5); mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getSizeF(randomKey())); }
SizeCoder extends BaseCoder<Size> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Size fieldValue) { state.putSize(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Size fieldValue); }
@SuppressWarnings("NewApi") @Test public void testSerializeSize() { Size expectedValue = new Size(9, 5); mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getSize(randomKey())); }
StringArrayCoder extends BaseCoder<String[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull String[] fieldValue) { state.putStringArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull String[] fieldValue); }
@Test public void testSerializeStringArray() { String[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getStringArray(randomKey())); }
CharCoder extends BaseCoder<Character> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Character fieldValue) { state.putChar(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Character fieldValue); }
@Test public void testSerializeCharPrimitive() { char expectedValue = 'x'; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getChar(randomKey())); } @Test public void testSerializeCharObject() { Character expectedValue = 'x'; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, ((Character) bundle().getChar(randomKey()))); }
FloatArrayCoder extends BaseCoder<float[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull float[] fieldValue) { state.putFloatArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull float[] fieldValue); }
@Test public void testSerializeFloatArray() { float[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getFloatArray(randomKey())); }
BooleanArrayCoder extends BaseCoder<boolean[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull boolean[] fieldValue) { state.putBooleanArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull boolean[] fieldValue); }
@Test public void testSerializeBooleanArray() { boolean[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getBooleanArray(randomKey())); }
ByteCoder extends BaseCoder<Byte> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Byte fieldValue) { state.putByte(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Byte fieldValue); }
@Test public void testSerializeBytePrimitive() { byte expectedValue = 2; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getByte(randomKey())); } @Test public void testSerializeByteObject() { Byte expectedValue = 2; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, ((Byte) bundle().getByte(randomKey()))); }
Lyra { public static boolean isInitialized() { return instance != null; } @SuppressLint("NewApi") private Lyra(@NonNull Application application, @NonNull CoderRetriever coderRetriever, @NonNull FieldsRetriever fieldsRetriever, boolean autoSaveActivities); static Builder with(@NonNull Application application); @SuppressLint("NewApi") static void destroy(); static boolean isInitialized(); @NonNull static Lyra instance(); @NonNull static String getKeyFromField(@NonNull Field field); void saveState(@NonNull Object stateHolder, @NonNull Bundle state); void restoreState(@NonNull Object stateHolder, @Nullable Bundle state); Parcelable saveState(@NonNull View stateHolder, @Nullable Parcelable state); Parcelable restoreState(@NonNull View stateHolder, @Nullable Parcelable state); static final String SUB_BUNDLE_KEY; static final String VIEW_SUPER_STATE_BUNDLE_KEY; }
@Test public void testIsInitialized() { assertTrue(Lyra.isInitialized()); }
LongArrayCoder extends BaseCoder<long[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull long[] fieldValue) { state.putLongArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull long[] fieldValue); }
@Test public void testSerializeLongArray() { long[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getLongArray(randomKey())); }
ByteArrayCoder extends BaseCoder<byte[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull byte[] fieldValue) { state.putByteArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull byte[] fieldValue); }
@Test public void testSerializeByteArray() { byte[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getByteArray(randomKey())); }
DoubleCoder extends BaseCoder<Double> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Double fieldValue) { state.putDouble(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Double fieldValue); }
@Test public void testSerializeDoublePrimitive() { double expectedValue = 9.0; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getDouble(randomKey()), 0); } @Test public void testSerializeDoubleObject() { Double expectedValue = 9.0; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getDouble(randomKey())); }
IBinderCoder extends BaseCoder<IBinder> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull IBinder fieldValue) { BundleCompat.putBinder(state, key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull IBinder fieldValue); }
@Test public void testSerializeIBinder() { IBinder expectedValue = new Binder(); mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, BundleCompat.getBinder(bundle(), randomKey())); }
IntCoder extends BaseCoder<Integer> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Integer fieldValue) { state.putInt(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Integer fieldValue); }
@Test public void testSerializeIntPrimitive() { int expectedValue = 9; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getInt(randomKey())); } @Test public void testSerializeIntObject() { Integer expectedValue = 9; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, (Integer) bundle().getInt(randomKey())); }
DoubleArrayCoder extends BaseCoder<double[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull double[] fieldValue) { state.putDoubleArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull double[] fieldValue); }
@Test public void testSerializeDoubleArray() { double[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getDoubleArray(randomKey())); }
ParcelableArrayCoder extends BaseCoder<Parcelable[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Parcelable[] fieldValue) { state.putParcelableArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Parcelable[] fieldValue); }
@Test public void testSerializeParcelableArray() { Parcelable[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getParcelableArray(randomKey())); }
LongCoder extends BaseCoder<Long> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Long fieldValue) { state.putLong(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Long fieldValue); }
@Test public void testSerializeLongPrimitive() { long expectedValue = 9L; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getLong(randomKey())); } @Test public void testSerializeLongObject() { Long expectedValue = 9L; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, ((Long) bundle().getLong(randomKey()))); }
Lyra { @NonNull public static String getKeyFromField(@NonNull Field field) { return field.getDeclaringClass().getName() + '#' + field.getName(); } @SuppressLint("NewApi") private Lyra(@NonNull Application application, @NonNull CoderRetriever coderRetriever, @NonNull FieldsRetriever fieldsRetriever, boolean autoSaveActivities); static Builder with(@NonNull Application application); @SuppressLint("NewApi") static void destroy(); static boolean isInitialized(); @NonNull static Lyra instance(); @NonNull static String getKeyFromField(@NonNull Field field); void saveState(@NonNull Object stateHolder, @NonNull Bundle state); void restoreState(@NonNull Object stateHolder, @Nullable Bundle state); Parcelable saveState(@NonNull View stateHolder, @Nullable Parcelable state); Parcelable restoreState(@NonNull View stateHolder, @Nullable Parcelable state); static final String SUB_BUNDLE_KEY; static final String VIEW_SUPER_STATE_BUNDLE_KEY; }
@Test public void testKeyFromFieldNotNull() { Field field = TestModels.MixedPublicFields.class.getDeclaredFields()[0]; assertNotNull(Lyra.getKeyFromField(field)); }
SerializableCoder extends BaseCoder<Serializable> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Serializable fieldValue) { state.putSerializable(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Serializable fieldValue); }
@Test public void testSerializeSerializable() { Serializable expectedValue = TestModels.ImplementedSerializable.getDefault(); mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getSerializable(randomKey())); }
BooleanCoder extends BaseCoder<Boolean> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Boolean fieldValue) { state.putBoolean(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Boolean fieldValue); }
@SuppressWarnings("ConstantConditions") @Test public void testSerializeBooleanPrimitive() { boolean expectedValue = true; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getBoolean(randomKey())); } @SuppressWarnings("ConstantConditions") @Test public void testSerializeBooleanObject() { Boolean expectedValue = true; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, ((Boolean) bundle().getBoolean(randomKey()))); }
ShortArrayCoder extends BaseCoder<short[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull short[] fieldValue) { state.putShortArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull short[] fieldValue); }
@Test public void testSerializeShortArray() { short[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getShortArray(randomKey())); }
FloatCoder extends BaseCoder<Float> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Float fieldValue) { state.putFloat(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Float fieldValue); }
@Test public void testSerializeFloatPrimitive() { float expectedValue = 9.0f; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getFloat(randomKey()), 0); } @Test public void testSerializeFloatObject() { Float expectedValue = 9.0f; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getFloat(randomKey())); }
ParcelableCoder extends BaseCoder<Parcelable> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Parcelable fieldValue) { state.putParcelable(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Parcelable fieldValue); }
@Test public void testSerializeParcelable() { Parcelable expectedValue = TestModels.ImplementedParcelable.getDefault(); mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getParcelable(randomKey())); }
CharSequenceArrayCoder extends BaseCoder<CharSequence[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull CharSequence[] fieldValue) { state.putCharSequenceArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull CharSequence[] fieldValue); }
@Test public void testSerializeCharSequenceArray() { CharSequence[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getCharSequenceArray(randomKey())); }
CharSequenceCoder extends BaseCoder<CharSequence> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull CharSequence fieldValue) { state.putCharSequence(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull CharSequence fieldValue); }
@Test public void testSerializeCharSequence() { CharSequence expectedValue = "test"; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getCharSequence(randomKey())); }
Lyra { public void saveState(@NonNull Object stateHolder, @NonNull Bundle state) { final Lyra lyra = instance(); Field[] fields = lyra.mFieldsRetriever.getFields(stateHolder.getClass()); Bundle lyraBundle = new Bundle(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; SaveState saveState = getSaveStateAnnotation(field); boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } final Object fieldValue; try { fieldValue = field.get(stateHolder); } catch (IllegalAccessException e) { throw runtimeIllegalAccessException(field); } if (fieldValue != null) { final StateCoder stateCoder; try { stateCoder = lyra.mCoderRetriever.getCoder(saveState, field.getType()); } catch (CoderNotFoundException e) { throw new RuntimeException(e); } stateCoder.serialize(lyraBundle, getKeyFromField(field), fieldValue); } if (!accessible) { field.setAccessible(false); } } state.putBundle(SUB_BUNDLE_KEY, lyraBundle); } @SuppressLint("NewApi") private Lyra(@NonNull Application application, @NonNull CoderRetriever coderRetriever, @NonNull FieldsRetriever fieldsRetriever, boolean autoSaveActivities); static Builder with(@NonNull Application application); @SuppressLint("NewApi") static void destroy(); static boolean isInitialized(); @NonNull static Lyra instance(); @NonNull static String getKeyFromField(@NonNull Field field); void saveState(@NonNull Object stateHolder, @NonNull Bundle state); void restoreState(@NonNull Object stateHolder, @Nullable Bundle state); Parcelable saveState(@NonNull View stateHolder, @Nullable Parcelable state); Parcelable restoreState(@NonNull View stateHolder, @Nullable Parcelable state); static final String SUB_BUNDLE_KEY; static final String VIEW_SUPER_STATE_BUNDLE_KEY; }
@Test public void testSaveState() throws Exception { final TestModels.SubClassAllModifiersAnnotatedFields saveStateObject = new TestModels.SubClassAllModifiersAnnotatedFields(); final Bundle stateBundle = new Bundle(); final DefaultFieldsRetriever retriever = new DefaultFieldsRetriever(); Field[] fields = retriever.getFields(saveStateObject.getClass()); for (Field field : fields) { new FieldAccessibleRunner(field) { @Override public void runWithField(@NonNull Field field) throws Exception { field.set(saveStateObject, mRandomizer.nextObject(field.getType())); } }; } Lyra.instance().saveState(saveStateObject, stateBundle); List<Object> fieldValues = listOfValuesFromFields(saveStateObject, fields); List<Object> savedValues = new ArrayList<>(fieldValues.size()); Bundle lyraBundle = stateBundle.getBundle(Lyra.SUB_BUNDLE_KEY); assertNotNull(lyraBundle); for (String key : lyraBundle.keySet()) { savedValues.add(lyraBundle.get(key)); } assertThat(savedValues, containsInAnyOrder(fieldValues.toArray())); }
IntArrayCoder extends BaseCoder<int[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull int[] fieldValue) { state.putIntArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull int[] fieldValue); }
@Test public void testSerializeIntArray() { int[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getIntArray(randomKey())); }
DefaultGsonCoderRetriever extends DefaultCoderRetriever { @NonNull @Override public StateCoder getCoder(@NonNull SaveState saveState, @NonNull Class<?> annotatedFieldClass) throws CoderNotFoundException { StateCoder stateCoder; final Class<? extends StateCoder> stateSDClass = saveState.value(); if (GsonCoder.class.isAssignableFrom(stateSDClass)) { try { Constructor<? extends StateCoder> constructor; constructor = stateSDClass.getConstructor(Gson.class); boolean accessible = constructor.isAccessible(); if (!accessible) { constructor.setAccessible(true); } stateCoder = constructor.newInstance(mGson); if (!accessible) { constructor.setAccessible(false); } } catch (Exception e) { throw new RuntimeException("You must provide an instance of " + GsonCoder.class.getName()); } } else { stateCoder = super.getCoder(saveState, annotatedFieldClass); } return stateCoder; } DefaultGsonCoderRetriever(); DefaultGsonCoderRetriever(@NonNull Gson gson); @NonNull @Override StateCoder getCoder(@NonNull SaveState saveState, @NonNull Class<?> annotatedFieldClass); }
@Test public void testRetrieveBasicCoder() throws CoderNotFoundException { Class fieldClass = String.class; SaveState mockedSaveState = mock(SaveState.class); when(mockedSaveState.value()).thenAnswer(new Answer<Class<? extends StateCoder>>() { @Override public Class<? extends StateCoder> answer(InvocationOnMock invocationOnMock) throws Throwable { return StateCoder.class; } }); StateCoder retrieverCoder = mRetriever.getCoder(mockedSaveState, fieldClass); assertNotNull(retrieverCoder); StateCoder basicCoder = StateCoderUtils.getBasicCoderForClass(fieldClass); assertEquals(retrieverCoder.getClass(), basicCoder.getClass()); } @Test public void testRetrieveBasicCachedCoder() throws CoderNotFoundException { Class fieldClass = String.class; SaveState mockedSaveState = mock(SaveState.class); when(mockedSaveState.value()).thenAnswer(new Answer<Class<? extends StateCoder>>() { @Override public Class<? extends StateCoder> answer(InvocationOnMock invocationOnMock) throws Throwable { return StateCoder.class; } }); StateCoder retrieverCoder = mRetriever.getCoder(mockedSaveState, fieldClass); assertNotNull(retrieverCoder); StateCoder basicCoder = StateCoderUtils.getBasicCoderForClass(fieldClass); assertEquals(retrieverCoder.getClass(), basicCoder.getClass()); retrieverCoder = mRetriever.getCoder(mockedSaveState, fieldClass); assertNotNull(retrieverCoder); assertEquals(retrieverCoder.getClass(), basicCoder.getClass()); } @Test public void testRetrieveCustomCoder() throws CoderNotFoundException { Class fieldClass = String.class; SaveState mockedSaveState = mock(SaveState.class); when(mockedSaveState.value()).thenAnswer(new Answer<Class<? extends StateCoder>>() { @Override public Class<? extends StateCoder> answer(InvocationOnMock invocationOnMock) throws Throwable { return CustomStateCoder.class; } }); StateCoder retrieverCoder = mRetriever.getCoder(mockedSaveState, fieldClass); assertNotNull(retrieverCoder); assertEquals(retrieverCoder.getClass(), CustomStateCoder.class); } @Test public void testRetrieveGsonCoder() throws CoderNotFoundException { Class fieldClass = String.class; SaveState mockedSaveState = mock(SaveState.class); when(mockedSaveState.value()).thenAnswer(new Answer<Class<? extends StateCoder>>() { @Override public Class<? extends StateCoder> answer(InvocationOnMock invocationOnMock) throws Throwable { return DefaultGsonCoder.class; } }); StateCoder retrieverCoder = mRetriever.getCoder(mockedSaveState, fieldClass); assertNotNull(retrieverCoder); assertEquals(retrieverCoder.getClass(), DefaultGsonCoder.class); }
Lyra { public void restoreState(@NonNull Object stateHolder, @Nullable Bundle state) { Bundle lyraBundle; if (state == null || (lyraBundle = state.getBundle(SUB_BUNDLE_KEY)) == null) return; final Lyra lyra = instance(); Field[] fields = lyra.mFieldsRetriever.getFields(stateHolder.getClass()); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; SaveState saveState = getSaveStateAnnotation(field); boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } final StateCoder stateCoder; try { stateCoder = lyra.mCoderRetriever.getCoder(saveState, field.getType()); } catch (CoderNotFoundException e) { throw new RuntimeException(e); } final Object fieldValue = stateCoder.deserialize(lyraBundle, getKeyFromField(field)); if (fieldValue != null) { try { field.set(stateHolder, fieldValue); } catch (IllegalAccessException e) { throw runtimeIllegalAccessException(field); } } if (!accessible) { field.setAccessible(false); } } } @SuppressLint("NewApi") private Lyra(@NonNull Application application, @NonNull CoderRetriever coderRetriever, @NonNull FieldsRetriever fieldsRetriever, boolean autoSaveActivities); static Builder with(@NonNull Application application); @SuppressLint("NewApi") static void destroy(); static boolean isInitialized(); @NonNull static Lyra instance(); @NonNull static String getKeyFromField(@NonNull Field field); void saveState(@NonNull Object stateHolder, @NonNull Bundle state); void restoreState(@NonNull Object stateHolder, @Nullable Bundle state); Parcelable saveState(@NonNull View stateHolder, @Nullable Parcelable state); Parcelable restoreState(@NonNull View stateHolder, @Nullable Parcelable state); static final String SUB_BUNDLE_KEY; static final String VIEW_SUPER_STATE_BUNDLE_KEY; }
@Test public void testRestoreState() throws Exception { final TestModels.SubClassAllModifiersAnnotatedFields saveStateObject = new TestModels.SubClassAllModifiersAnnotatedFields(); final Bundle stateBundle = new Bundle(); final Bundle lyraBundle = new Bundle(); final DefaultFieldsRetriever retriever = new DefaultFieldsRetriever(); final DefaultCoderRetriever coderRetriever = new DefaultCoderRetriever(); Field[] fields = retriever.getFields(saveStateObject.getClass()); List<Object> savedValues = new ArrayList<>(fields.length); for (Field field : fields) { SaveState saveState = field.getAnnotation(SaveState.class); Class<?> fieldType = field.getType(); StateCoder stateCoder = coderRetriever.getCoder(saveState, fieldType); Object randomObj = mRandomizer.nextObject(fieldType); savedValues.add(randomObj); stateCoder.serialize(lyraBundle, Lyra.getKeyFromField(field), randomObj); } stateBundle.putBundle(Lyra.SUB_BUNDLE_KEY, lyraBundle); Lyra.instance().restoreState(saveStateObject, stateBundle); List<Object> fieldValues = listOfValuesFromFields(saveStateObject, fields); assertThat(savedValues, containsInAnyOrder(fieldValues.toArray())); }
Tileset implements Disposable { public int getTileId(int x, int y) { return tilesetSource.getTileId(x, y, firstGid); } Tileset(int firstGid, TilesetSource tilesetSource); boolean containsProperty(String propertyName); String getProperty(String propertyName); void setProperty(String propertyName, String value); ObjectMap<String, String> getProperties(); void drawTile(Graphics g, int tileId, int renderX, int renderY); void drawTileset(Graphics g, int renderX, int renderY); Tile getTile(int tileId); Tile getTile(int x, int y); Array<AssetDescriptor> getDependencies(FileHandle tmxPath); boolean isTextureLoaded(); void loadTexture(FileHandle tmxPath); void loadTexture(AssetManager assetManager, FileHandle tmxPath); void loadTexture(TextureAtlas textureAtlas); @Override void dispose(); boolean contains(int tileId); int getTileId(int x, int y); int getTileX(int tileId); int getTileY(int tileId); int getWidthInTiles(); int getHeightInTiles(); int getWidth(); int getHeight(); int getTileWidth(); int getTileHeight(); int getSpacing(); int getMargin(); int getFirstGid(); String getSourceInternalUuid(); }
@Test public void testGetTileId() { tileset = new Tileset(1, new ImageTilesetSource(128, 128, 32, 32, 0, 0)); Assert.assertEquals(1, tileset.getTileId(0, 0)); Assert.assertEquals(5, tileset.getTileId(0, 1)); tileset = new Tileset(1, new ImageTilesetSource(1936, 1052, 32, 32, 2, 0)); Assert.assertEquals(1, tileset.getTileId(0, 0)); Assert.assertEquals(343, tileset.getTileId(0, 6)); Assert.assertEquals(345, tileset.getTileId(2, 6)); }
ConcurrentIntSet extends IntSet implements ConcurrentCollection { @Override public boolean remove(int key) { lock.lockWrite(); boolean b = super.remove(key); lock.unlockWrite(); return b; } ConcurrentIntSet(); ConcurrentIntSet(int initialCapacity); ConcurrentIntSet(int initialCapacity, float loadFactor); ConcurrentIntSet(IntSet set); @Override boolean add(int key); @Override void addAll(IntArray array, int offset, int length); @Override void addAll(int[] array, int offset, int length); @Override void addAll(IntSet set); @Override boolean remove(int key); @Override boolean notEmpty(); @Override boolean isEmpty(); @Override void shrink(int maximumCapacity); @Override void clear(int maximumCapacity); @Override void clear(); @Override boolean contains(int key); @Override int first(); @Override void ensureCapacity(int additionalCapacity); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override IntSetIterator iterator(); @Override ReadWriteLock getLock(); }
@Test public void testRemove(){ ConcurrentIntSet set = new ConcurrentIntSet(); for (int i = 0; i < 10000; i++) { set.add(i); } CountDownLatch latch = new CountDownLatch(1000); createStartAndJoinThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 10; i++) { set.lock.lockWrite(); int key = set.first(); assertTrue(set.contains(key)); set.remove(key); assertFalse(set.contains(key)); set.lock.unlockWrite(); } } }, 1000); assertEquals(0, set.size); }
ConcurrentBooleanArray extends BooleanArray implements ConcurrentCollection { @Override public void add(boolean value) { lock.lockWrite(); super.add(value); lock.unlockWrite(); } ConcurrentBooleanArray(); ConcurrentBooleanArray(int capacity); ConcurrentBooleanArray(boolean ordered, int capacity); ConcurrentBooleanArray(BooleanArray array); ConcurrentBooleanArray(boolean[] array); ConcurrentBooleanArray(boolean ordered, boolean[] array, int startIndex, int count); @Override void add(boolean value); @Override void add(boolean value1, boolean value2); @Override void add(boolean value1, boolean value2, boolean value3); @Override void add(boolean value1, boolean value2, boolean value3, boolean value4); @Override void addAll(boolean[] array, int offset, int length); @Override boolean get(int index); @Override void set(int index, boolean value); @Override void insert(int index, boolean value); @Override void swap(int first, int second); @Override boolean removeIndex(int index); @Override void removeRange(int start, int end); @Override boolean pop(); @Override boolean peek(); @Override boolean first(); @Override boolean notEmpty(); @Override boolean isEmpty(); @Override void clear(); @Override boolean[] shrink(); @Override boolean[] ensureCapacity(int additionalCapacity); @Override boolean[] setSize(int newSize); @Override void reverse(); @Override void shuffle(); @Override void truncate(int newSize); @Override boolean random(); @Override void addAll(BooleanArray array, int offset, int length); @Override boolean removeAll(BooleanArray array); @Override boolean[] toArray(); @Override int hashCode(); @Override boolean equals(Object object); @Override String toString(); @Override String toString(String separator); @Override ReadWriteLock getLock(); }
@Test public void testAddItems() { ConcurrentBooleanArray a = new ConcurrentBooleanArray(); CountDownLatch latch = new CountDownLatch(10); createStartAndJoinThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 1000; i++) { a.add(i % 2 == 0); } } }, 10); assertEquals(a.size, 10*1000); }
ConcurrentOrderedSet extends OrderedSet<T> implements ConcurrentCollection { @Override public boolean add(T key) { lock.lockWrite(); boolean b = super.add(key); lock.unlockWrite(); return b; } ConcurrentOrderedSet(); ConcurrentOrderedSet(int initialCapacity); ConcurrentOrderedSet(int initialCapacity, float loadFactor); ConcurrentOrderedSet(OrderedSet<? extends T> set); @Override boolean add(T key); @Override void addAll(Array<? extends T> array, int offset, int length); @Override void addAll(T[] array, int offset, int length); @Override void addAll(ObjectSet<T> set); @Override boolean remove(T key); @Override boolean notEmpty(); @Override boolean isEmpty(); @Override void shrink(int maximumCapacity); @Override void clear(int maximumCapacity); @Override void clear(); @Override boolean contains(T key); @Override T get(T key); @Override T first(); @Override boolean add(T key, int index); @Override T removeIndex(int index); @Override Array<T> orderedItems(); @Override void ensureCapacity(int additionalCapacity); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override String toString(String separator); @Override OrderedSetIterator<T> iterator(); @Override ReadWriteLock getLock(); }
@Test public void testAdd() { ConcurrentOrderedSet<Integer> set = new ConcurrentOrderedSet<>(); Random r = new Random(); CountDownLatch latch = new CountDownLatch(1000); createStartAndJoinThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } while (!set.add(r.nextInt())){ } } }, 1000); assertEquals(1000, set.size); }
ConcurrentOrderedSet extends OrderedSet<T> implements ConcurrentCollection { @Override public boolean remove(T key) { lock.lockWrite(); boolean b = super.remove(key); lock.unlockWrite(); return b; } ConcurrentOrderedSet(); ConcurrentOrderedSet(int initialCapacity); ConcurrentOrderedSet(int initialCapacity, float loadFactor); ConcurrentOrderedSet(OrderedSet<? extends T> set); @Override boolean add(T key); @Override void addAll(Array<? extends T> array, int offset, int length); @Override void addAll(T[] array, int offset, int length); @Override void addAll(ObjectSet<T> set); @Override boolean remove(T key); @Override boolean notEmpty(); @Override boolean isEmpty(); @Override void shrink(int maximumCapacity); @Override void clear(int maximumCapacity); @Override void clear(); @Override boolean contains(T key); @Override T get(T key); @Override T first(); @Override boolean add(T key, int index); @Override T removeIndex(int index); @Override Array<T> orderedItems(); @Override void ensureCapacity(int additionalCapacity); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override String toString(String separator); @Override OrderedSetIterator<T> iterator(); @Override ReadWriteLock getLock(); }
@Test public void testRemove(){ ConcurrentOrderedSet<Integer> set = new ConcurrentOrderedSet<>(); for (int i = 0; i < 10000; i++) { set.add(i); } CountDownLatch latch = new CountDownLatch(1000); createStartAndJoinThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 10; i++) { set.lock.lockWrite(); int key = set.first(); assertTrue(set.contains(key)); set.remove(key); assertFalse(set.contains(key)); set.lock.unlockWrite(); } } }, 1000); assertEquals(0, set.size); }
ConcurrentLongArray extends LongArray implements ConcurrentCollection { @Override public void add(long value) { lock.lockWrite(); super.add(value); lock.unlockWrite(); } ConcurrentLongArray(); ConcurrentLongArray(int capacity); ConcurrentLongArray(boolean ordered, int capacity); ConcurrentLongArray(LongArray array); ConcurrentLongArray(long[] array); ConcurrentLongArray(boolean ordered, long[] array, int startIndex, int count); @Override void add(long value); @Override void add(long value1, long value2); @Override void add(long value1, long value2, long value3); @Override void add(long value1, long value2, long value3, long value4); @Override void addAll(LongArray array, int offset, int length); @Override void addAll(long[] array, int offset, int length); @Override long get(int index); @Override void set(int index, long value); @Override void incr(int index, long value); @Override void mul(int index, long value); @Override void insert(int index, long value); @Override void swap(int first, int second); @Override boolean contains(long value); @Override int indexOf(long value); @Override int lastIndexOf(char value); @Override boolean removeValue(long value); @Override long removeIndex(int index); @Override void removeRange(int start, int end); @Override boolean removeAll(LongArray array); @Override long pop(); @Override long peek(); @Override long first(); @Override boolean notEmpty(); @Override boolean isEmpty(); @Override void clear(); @Override long[] shrink(); @Override long[] ensureCapacity(int additionalCapacity); @Override long[] setSize(int newSize); @Override void sort(); @Override void reverse(); @Override void shuffle(); @Override void truncate(int newSize); @Override long random(); @Override long[] toArray(); @Override int hashCode(); @Override boolean equals(Object object); @Override String toString(); @Override String toString(String separator); @Override ReadWriteLock getLock(); }
@Test public void testAddItems() { ConcurrentLongArray a = new ConcurrentLongArray(); CountDownLatch latch = new CountDownLatch(10); createStartAndJoinThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 1000; i++) { a.add(i); } } }, 10); assertEquals(a.size, 10*1000); }
ConcurrentPooledLinkedList extends PooledLinkedList<T> implements ConcurrentCollection { @Override public void add(T object) { lock.lockWrite(); super.add(object); lock.unlockWrite(); } ConcurrentPooledLinkedList(int maxPoolSize); @Override void add(T object); @Override void addFirst(T object); @Override int size(); @Override void iter(); @Override void iterReverse(); @Override T next(); @Override T previous(); @Override void remove(); @Override T removeLast(); @Override void clear(); @Override ReadWriteLock getLock(); }
@Test public void testAdd() { ConcurrentPooledLinkedList<Integer> l = new ConcurrentPooledLinkedList<>(2000); l.iter(); CountDownLatch latch = new CountDownLatch(200); Thread[] addThread = createAndStartThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 10; i++) { l.add(i); } } }, 100); Thread[] addFirstThread = createAndStartThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 10; i++) { l.addFirst(i); } } }, 100); joinAll(addThread, addFirstThread); assertEquals(2000, l.size()); }