method2testcases
stringlengths 118
6.63k
|
---|
### Question:
Matrix implements Serializable { public static Matrix zeros(@NonNull int... shape) { checkNotNull(shape); checkExpression( shape.length == 2, "Shape is incorrect"); return new Matrix(new double[shape[0] * shape[1]], shape[0], shape[1]); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testZeros() { final Matrix matrix = Matrix.zeros(2, 3); assertEquals(matrix.getRow(), 2); assertEquals(matrix.getCol(), 3); assertArrayEquals(matrix.getArray(), new double[]{ 0D, 0D, 0D, 0D, 0D, 0D }, 0); } |
### Question:
Matrix implements Serializable { public static Matrix randn(int row, int col) { checkDimensions(row, col); final Matrix matrix = Matrix.zeros(row, col); final double[] array = matrix.getArray(); final Random random = new Random(System.currentTimeMillis()); for (int i = 0, len = array.length; i < len; ++i) { array[i] = random.nextGaussian(); } return matrix; } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testRandn() { final Matrix a = Matrix.randn(2, 3); assertEquals(a.getRow(), 2); assertEquals(a.getCol(), 3); } |
### Question:
Matrix implements Serializable { public Matrix transpose() { return Matrix.transpose(this); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testTranspose() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 2); final Matrix b = a.transpose(); assertEquals(b.getRow(), 3); assertEquals(b.getCol(), 2); assertArrayEquals(b.getArray(), new double[]{ 1, 4, 2, 5, 3, 6 }, 0); } |
### Question:
Matrix implements Serializable { public Matrix plus(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.plus(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testPlus() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix b = Matrix.array(new double[]{ 6, 5, 4, 3, 2, 1 }, 3); final Matrix c = a.plus(b); assertNotSame(c, a); assertEquals(c.getRow(), 3); assertEquals(c.getCol(), 2); assertArrayEquals(c.getArray(), new double[]{ 7, 7, 7, 7, 7, 7 }, 0); } |
### Question:
Matrix implements Serializable { public Matrix plusTo(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.plusTo(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testPlusTo() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix b = Matrix.array(new double[]{ 6, 5, 4, 3, 2, 1 }, 3); final Matrix c = a.plusTo(b); assertSame(c, a); assertArrayEquals(a.getArray(), new double[]{ 7, 7, 7, 7, 7, 7 }, 0); } |
### Question:
Matrix implements Serializable { public Matrix minus(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.minus(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testMinus() { final Matrix a = Matrix.array(new double[]{ 6, 6, 6, 6, 6, 6 }, 2); final Matrix b = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 2); final Matrix c = a.minus(b); assertNotSame(a, c); assertEquals(c.getRow(), 2); assertEquals(c.getCol(), 3); assertArrayEquals(c.getArray(), new double[]{ 5, 4, 3, 2, 1, 0 }, 0); } |
### Question:
Matrix implements Serializable { public Matrix minusTo(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.minusTo(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testMinusTo() { final Matrix a = Matrix.array(new double[]{ 6, 6, 6, 6, 6, 6 }, 2); final Matrix b = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 2); final Matrix c = a.minusTo(b); assertSame(c, a); assertArrayEquals(a.getArray(), new double[]{ 5, 4, 3, 2, 1, 0 }, 0); } |
### Question:
Matrix implements Serializable { public Matrix times(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.times(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testTimes() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix b = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix c = a.times(b); assertNotSame(c, a); assertEquals(c.getRow(), 3); assertEquals(c.getCol(), 2); assertArrayEquals(c.getArray(), new double[]{ 1, 4, 9, 16, 25, 36 }, 0); } |
### Question:
Matrix implements Serializable { public Matrix timesTo(double num) { return Matrix.timesTo(this, num); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testTimesTo() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix b = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); final Matrix c = a.timesTo(b); assertSame(c, a); assertArrayEquals(a.getArray(), new double[]{ 1, 4, 9, 16, 25, 36 }, 0); } |
### Question:
Matrix implements Serializable { public double get(int i, int j) { checkExpression(i >= 0 && i < mRow && j >= 0 && j < mCol, "Row or col is out of bounds"); return mArray[i * mCol + j]; } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testGet() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); assertEquals(a.get(2,1), 6, 0); } |
### Question:
Matrix implements Serializable { public void set(int i, int j, double value) { checkExpression(i >= 0 && i < mRow && j >= 0 && j < mCol, "Row or col is out of bounds"); mArray[i * mCol + j] = value; } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testSet() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); a.set(1, 1, 666); assertEquals(a.get(1, 1), 666, 0); } |
### Question:
Matrix implements Serializable { public Matrix dot(@NonNull Matrix matrix) { checkNotNull(matrix); return Matrix.dot(this, matrix); } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testDot() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 2); final Matrix b = Matrix.array(new double[]{ 1, 2, 9, 4, 5, 7 }, 3); final Matrix c = a.dot(b); assertEquals(c.getRow(), 2); assertEquals(c.getCol(), 2); assertArrayEquals(c.getArray(), new double[]{ 34, 31, 79, 70 }, 0); } |
### Question:
MatrixChecker { static void checkDimensions(int row, int col) { checkExpression(row > 0 && col > 0, "Row and column should be positive"); } }### Answer:
@Test(expected = IllegalArgumentException.class) public void testCheckDimensions() { MatrixChecker.checkDimensions(-1, 0); }
@Test public void testCheckDimensions1() { MatrixChecker.checkDimensions( 2, 3); }
@Test public void testCheckDimensions2() { final Matrix a = Matrix.zeros(2, 3); final Matrix b = a.copy(); MatrixChecker.checkDimensions(a, b); }
@Test(expected = IllegalArgumentException.class) public void testCheckDimensions3() { final Matrix a = Matrix.zeros(2, 3); final Matrix b = Matrix.zeros(3, 3); MatrixChecker.checkDimensions(a, b); } |
### Question:
MatrixChecker { static void checkInnerDimensions(@NonNull Matrix a, @NonNull Matrix b) { checkExpression(a.getCol() == b.getRow(), "Matrix inner dimensions must agree"); } }### Answer:
@Test public void testCheckInnerDimension() { final Matrix a = Matrix.zeros(2, 3); final Matrix b = Matrix.zeros(3, 2); MatrixChecker.checkInnerDimensions(a, b); }
@Test(expected = IllegalArgumentException.class) public void testCheckInnerDimension2() { final Matrix a = Matrix.zeros(2, 3); final Matrix b = Matrix.zeros(3, 3); MatrixChecker.checkInnerDimensions(b, a); } |
### Question:
Matrix implements Serializable { public int[] shape() { return new int[]{mRow, mCol}; } private Matrix(double[] array, int row, int col); int[] shape(); double[] getArray(); double[][] getArrays(); Matrix copy(); int getRow(); int getCol(); double get(int i, int j); void set(int i, int j, double value); Matrix times(@NonNull Matrix matrix); Matrix times(double num); Matrix timesTo(double num); Matrix timesTo(@NonNull Matrix matrix); Matrix plus(@NonNull Matrix matrix); Matrix plusTo(@NonNull Matrix matrix); Matrix minus(@NonNull Matrix matrix); Matrix minusTo(@NonNull Matrix matrix); Matrix dot(@NonNull Matrix matrix); Matrix transpose(); static Matrix array(@NonNull double[][] arrays); static Matrix array(@NonNull double[] array, int row); static Matrix randn(int row, int col); static Matrix plus(@NonNull Matrix a, @NonNull Matrix b); static Matrix plusTo(@NonNull Matrix a,@NonNull Matrix b); static Matrix minus(@NonNull Matrix a,@NonNull Matrix b); static Matrix minusTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix a, @NonNull Matrix b); static Matrix times(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix matrix, double num); static Matrix timesTo(@NonNull Matrix a, @NonNull Matrix b); static Matrix dot(@NonNull Matrix a, @NonNull Matrix b); static Matrix transpose(@NonNull Matrix a); static Matrix zeroLike(Matrix matrix); static Matrix zeros(@NonNull int... shape); }### Answer:
@Test public void testShape() { final Matrix a = Matrix.array(new double[]{ 1, 2, 3, 4, 5, 6 }, 3); assertArrayEquals(a.shape(), new int[]{ 3, 2 }); } |
### Question:
IpBlockFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { initializeReloadCommandParamName(filterConfig); createIpBlocker(filterConfig); } @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void destroy(); static final String RELOAD_COMMAND_PARAM_NAME_CONFIG_NAME; static final String DEFAULT_RELOAD_COMMAND_PARAM_NAME_VALUE; }### Answer:
@Test public void filterInit() throws ServletException, IOException { assertFalse(FakeIpBlocker.created); filter.init(mockFilterConfig); assertTrue(FakeIpBlocker.created); } |
### Question:
ConfigIpFilter implements IpFilter { @Override public boolean accept(String ip) { if (allowFirst) return accepAllowFirst(ip); else return acceptDenyFirst(ip); } ConfigIpFilter(Config config); @Override boolean accept(String ip); }### Answer:
@Test public void shouldReturnTrueDupIpInAllowAndDenyListWhenAllowFirst() { Config config = new Config(); config.setAllowFirst(true); config.allow("1.2.3.4"); config.deny("1.2.3.4"); IpFilter ipFilter = new ConfigIpFilter(config); assertTrue(ipFilter.accept("1.2.3.4")); }
@Test public void shouldReturnFalseDupIpInAllowAndDenyListWhenDenyFirst() { Config config = new Config(); config.setAllowFirst(false); config.allow("1.2.3.4"); config.deny("1.2.3.4"); IpFilter ipFilter = new ConfigIpFilter(config); assertFalse(ipFilter.accept("1.2.3.4")); } |
### Question:
IpFilters { public static IpFilter create(Config config) { return new ConfigIpFilter(config); } static IpFilter create(Config config); static IpFilter createCached(Config config); }### Answer:
@Test public void createIpFilterWithConfig() { IpFilter filter = IpFilters.create(createConfig()); assertTrue(filter instanceof ConfigIpFilter); } |
### Question:
IpFilters { public static IpFilter createCached(Config config) { return new CachedIpFilter(create(config)); } static IpFilter create(Config config); static IpFilter createCached(Config config); }### Answer:
@Test public void createCachedIpFilterWithConfig() { IpFilter filter = IpFilters.createCached(createConfig()); assertTrue(filter instanceof CachedIpFilter); } |
### Question:
NumberNode { public boolean isSimpleNumber() { return isSimpleNumber; } NumberNode(String number); NumberNode createOrGetChildNumber(String numberPattern); NumberNode findMatchingChild(String number); boolean isMatch(String number); boolean isSimpleNumber(); boolean isAllAccept(); }### Answer:
@Test public void createSimpleNode() { NumberNode node = new NumberNode("10"); assertTrue(node.isSimpleNumber()); }
@Test public void createPatternNodeWith128_25() { NumberNode node = new NumberNode("128/25"); assertFalse(node.isSimpleNumber()); assertNodeMatch(node, 128, 255, true); assertNodeMatch(node, 0, 127, false); }
@Test public void createPatternNodeWith8_30() { NumberNode node = new NumberNode("8/30"); assertFalse(node.isSimpleNumber()); assertNodeMatch(node, 8, 11, true); assertNodeMatch(node, 0, 7, false); assertNodeMatch(node, 12, 255, false); } |
### Question:
IpBlockFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (ipBlocker.accept(request.getRemoteAddr())) processDoFilter(request, response, chain); else sendNotFoundResponse((HttpServletResponse) response); } @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void destroy(); static final String RELOAD_COMMAND_PARAM_NAME_CONFIG_NAME; static final String DEFAULT_RELOAD_COMMAND_PARAM_NAME_VALUE; }### Answer:
@Test public void shouldRunChainWhenIpIsNotBlocked() throws ServletException, IOException { filterInit(); when(mockRequest.getRemoteAddr()).thenReturn(FakeIpBlocker.ALLOW_IP); filter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(mockFilterChain, only()).doFilter(mockRequest, mockResponse); }
@Test public void shouldResponse404WhenIpIsBlocked() throws ServletException, IOException { filterInit(); when(mockRequest.getRemoteAddr()).thenReturn(DENY_IP); filter.doFilter(mockRequest, mockResponse, mockFilterChain); verify(mockFilterChain, never()).doFilter(mockRequest, mockResponse); verify(mockResponse, only()).sendError(HttpServletResponse.SC_NOT_FOUND); }
@Test public void shouldReloadWhenRequestHasReloadParameter() throws ServletException, IOException { filterInit(); when(mockRequest.getRemoteAddr()).thenReturn(FakeIpBlocker.ALLOW_IP); filter.doFilter(mockRequest, mockResponse, mockFilterChain); assertFalse(FakeIpBlocker.reloaded); when(mockRequest.getParameter("IBFRM")).thenReturn("true"); filter.doFilter(mockRequest, mockResponse, mockFilterChain); assertTrue(FakeIpBlocker.reloaded); } |
### Question:
ConfigFactory { public static ConfigFactory getInstance(String type) { if (type.equals("text")) return new TextConfigFactory(); if (type.equals("file")) return new FileConfigFactory(); if (type.equals("classpath")) return new ClasspathConfigFactory(); return null; } static ConfigFactory getInstance(String type); abstract Config create(String value); abstract boolean isReloadSupported(); }### Answer:
@Test public void getFileConfigFactory() { ConfigFactory factory = ConfigFactory.getInstance("file"); assertTrue(factory instanceof FileConfigFactory); }
@Test public void getClasspathConfigFactory() { ConfigFactory factory = ConfigFactory.getInstance("classpath"); assertTrue(factory instanceof ClasspathConfigFactory); }
@Test public void getTextConfigFactory() { ConfigFactory factory = ConfigFactory.getInstance("text"); assertTrue(factory instanceof TextConfigFactory); } |
### Question:
IpBlockerFactoryImpl extends IpBlockerFactory { @Override public IpBlocker create(Map<String, String> config) { try { IpBlockerImpl ipBlocker = new IpBlockerImpl(); ipBlocker.init(config); return ipBlocker; } catch (Exception ex) { throw new IpBlockerCreationException(ex); } } @Override IpBlocker create(Map<String, String> config); }### Answer:
@Test public void shouldCreateIpBlockerImplInstance() { IpBlocker ipBlocker = new IpBlockerFactoryImpl().create(ConfigMapUtil.getTextConfigMap()); assertTrue(ipBlocker instanceof IpBlockerImpl); } |
### Question:
CachedIpFilter implements IpFilter { @Override public boolean accept(String ip) { if (cachedMap.containsKey(ip)) return cachedMap.get(ip); Boolean result = delegate.accept(ip); cachedMap.put(ip, result); return result; } CachedIpFilter(IpFilter delegate); @Override boolean accept(String ip); }### Answer:
@Test public void shouldCacheDupIp() { IpFilter mockFilter = mock(IpFilter.class); String ip = "1.2.3.4"; when(mockFilter.accept(ip)).thenReturn(true); CachedIpFilter filter = new CachedIpFilter(mockFilter); filter.accept(ip); verify(mockFilter, only()).accept(ip); filter.accept(ip); verify(mockFilter, only()).accept(ip); } |
### Question:
IpTree { public void add(String ip) { String[] ipNumbers = ip.split("\\."); NumberNode node = root; for (String number : ipNumbers) node = node.createOrGetChildNumber(number); } void add(String ip); boolean containsIp(String ip); }### Answer:
@Test public void level4StarIpTree() { ipTree.add("10.20.30.*"); assertIpTreeContainsIp(ipTree, "10.20.30", 0, 255, true); } |
### Question:
Store { List<String> read(String name) { final List<String> allKeys = new ArrayList<>(sharedPreferences.getAll().keySet()); Collections.sort(allKeys); final Pattern pattern = Pattern.compile("^[0-9]+" + Pattern.quote("_" + name) + "$"); final List<String> result = new ArrayList<>(); for (String key : allKeys) { if (pattern.matcher(key).matches()) { result.add(sharedPreferences.getString(key, AutoFiller.EMPTY_FIELD)); } } return result; } Store(SharedPreferences sharedPreferences); }### Answer:
@Test public void read_without_saves_returns_empty_list() throws Exception { assertEquals(Collections.emptyList(), store.read("t")); } |
### Question:
Phial { public static void setKey(String key, String value) { DEFAULT_CATEGORY.setKey(key, value); } static void setKey(String key, String value); static void setKey(@NonNull String key, @Nullable Object value); static void removeKey(String key); static Category category(String name); static void removeCategory(String name); static void addSaver(Saver saver); static void removeSaver(Saver saver); }### Answer:
@Test public void setKey_call_setKey_for_all_savers() throws Exception { Phial.setKey("key", "value"); savers.forEach(saver -> verify(saver).save(anyString(), eq("key"), eq("value")) ); } |
### Question:
Phial { public static void removeKey(String key) { DEFAULT_CATEGORY.removeKey(key); } static void setKey(String key, String value); static void setKey(@NonNull String key, @Nullable Object value); static void removeKey(String key); static Category category(String name); static void removeCategory(String name); static void addSaver(Saver saver); static void removeSaver(Saver saver); }### Answer:
@Test public void removeKey_call_removeKey_for_all_savers() throws Exception { Phial.removeKey("key"); savers.forEach(saver -> verify(saver).remove(anyString(), eq("key")) ); } |
### Question:
Phial { public static void removeSaver(Saver saver) { SAVERS.remove(saver); } static void setKey(String key, String value); static void setKey(@NonNull String key, @Nullable Object value); static void removeKey(String key); static Category category(String name); static void removeCategory(String name); static void addSaver(Saver saver); static void removeSaver(Saver saver); }### Answer:
@Test public void removeSaver() { savers.forEach(Phial::removeSaver); Phial.setKey("key", "value"); Phial.removeKey("key"); Phial.category("category").setKey("key", "value"); Phial.category("category").removeKey("key"); savers.forEach(Mockito::verifyZeroInteractions); } |
### Question:
FileUtil { public static void write(String text, File target) throws IOException { BufferedWriter bw = null; FileWriter fw = null; try { fw = new FileWriter(target); bw = new BufferedWriter(fw); bw.write(text); } finally { if (bw != null) { bw.close(); } if (fw != null) { fw.close(); } } } private FileUtil(); static void write(String text, File target); static Uri getUri(Context context, String authority, File file); static void saveBitmap(Bitmap bitmap, File targetFile, int quality); static void saveBitmap(Bitmap bitmap, File targetFile, Bitmap.CompressFormat format, int quality); static void zip(List<File> sources, File target); static List<File> walk(File source); static List<File> walk(List<File> sources); static String uniqueName(File source, Set<String> taken); static String getFileExtension(File file); static String getFileNameWithoutExtention(File file); }### Answer:
@Test public void write() throws Exception { FileUtil.write("test text", file); Assert.assertEquals( "test text", Files.lines(Paths.get(FILE_NAME)).reduce("", (l, r) -> l + r) ); } |
### Question:
FileUtil { public static void saveBitmap(Bitmap bitmap, File targetFile, int quality) throws IOException { saveBitmap(bitmap, targetFile, Bitmap.CompressFormat.JPEG, quality); } private FileUtil(); static void write(String text, File target); static Uri getUri(Context context, String authority, File file); static void saveBitmap(Bitmap bitmap, File targetFile, int quality); static void saveBitmap(Bitmap bitmap, File targetFile, Bitmap.CompressFormat format, int quality); static void zip(List<File> sources, File target); static List<File> walk(File source); static List<File> walk(List<File> sources); static String uniqueName(File source, Set<String> taken); static String getFileExtension(File file); static String getFileNameWithoutExtention(File file); }### Answer:
@Test public void saveBitmap() throws Exception { final Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); FileUtil.saveBitmap(bitmap, file, 100); final Bitmap result = BitmapFactory.decodeFile(FILE_NAME); Assert.assertEquals(100, result.getHeight()); Assert.assertEquals(100, result.getWidth()); }
@Test public void saveBitmapWithConfig() throws Exception { final Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565); FileUtil.saveBitmap(bitmap, file, Bitmap.CompressFormat.PNG, 100); final BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inPreferredConfig = Bitmap.Config.RGB_565; final Bitmap result = BitmapFactory.decodeFile(FILE_NAME, opts); Assert.assertEquals(100, result.getHeight()); Assert.assertEquals(100, result.getWidth()); Assert.assertEquals(bitmap.getPixel(0, 0), result.getPixel(0, 0)); } |
### Question:
FileUtil { public static List<File> walk(File source) { if (!source.isDirectory()) { return Collections.singletonList(source); } final File[] files = source.listFiles(); return walk(Arrays.asList(files)); } private FileUtil(); static void write(String text, File target); static Uri getUri(Context context, String authority, File file); static void saveBitmap(Bitmap bitmap, File targetFile, int quality); static void saveBitmap(Bitmap bitmap, File targetFile, Bitmap.CompressFormat format, int quality); static void zip(List<File> sources, File target); static List<File> walk(File source); static List<File> walk(List<File> sources); static String uniqueName(File source, Set<String> taken); static String getFileExtension(File file); static String getFileNameWithoutExtention(File file); }### Answer:
@Test public void walk() { final File dir1 = createDirectories("dir1"); final File dir12 = createDirectories("dir1", "dir2"); final File dir2 = createDirectories("dir2"); final File dir3 = createDirectories("dir3"); createFiles(dir1, "f1.txt", "f2.txt", "f3.txt"); createFiles(dir12, "f1.txt", "f4.txt"); createFiles(dir2); createFiles(dir3, "f1.txt"); Assert.assertEquals(CollectionUtils.asSet( new File(dir1, "f1.txt"), new File(dir1, "f2.txt"), new File(dir1, "f3.txt"), new File(dir12, "f1.txt"), new File(dir12, "f4.txt"), new File(dir3, "f1.txt")), new HashSet<>(FileUtil.walk(file)) ); } |
### Question:
FileUtil { public static String uniqueName(File source, Set<String> taken) { String name = source.getName(); for (int i = 1; taken.contains(name); i++) { name = getFileNameWithoutExtention(source) + "_" + i; final String extension = getFileExtension(source); if (!extension.isEmpty()) { name += "." + extension; } } return name; } private FileUtil(); static void write(String text, File target); static Uri getUri(Context context, String authority, File file); static void saveBitmap(Bitmap bitmap, File targetFile, int quality); static void saveBitmap(Bitmap bitmap, File targetFile, Bitmap.CompressFormat format, int quality); static void zip(List<File> sources, File target); static List<File> walk(File source); static List<File> walk(List<File> sources); static String uniqueName(File source, Set<String> taken); static String getFileExtension(File file); static String getFileNameWithoutExtention(File file); }### Answer:
@Test public void uniqueName_returns_same_if_not_taken() { final File file = new File("f.txt"); Assert.assertEquals("f.txt", FileUtil.uniqueName(file, new HashSet<>())); }
@Test public void uniqueName_returns_new_name_if_taken() { final File file = new File("f.txt"); Assert.assertEquals("f_2.txt", FileUtil.uniqueName(file, CollectionUtils.asSet("f.txt", "f_1.txt"))); }
@Test public void uniqueName_returns_new_name_if_taken_file_without_extension() { final File file = new File("f"); Assert.assertEquals("f_2", FileUtil.uniqueName(file, CollectionUtils.asSet("f", "f_1"))); }
@Test public void uniqueName_returns_new_name_if_taken_file_starts_with_dot() { final File file = new File(".ignore"); Assert.assertEquals(".ignore_2", FileUtil.uniqueName(file, CollectionUtils.asSet(".ignore", ".ignore_1"))); } |
### Question:
ConfigManager { List<FillOption> getOptions() { final List<FillOption> savedOptions = readConfigsFromStore(); final List<FillOption> result = new ArrayList<>(fillConfig.getOptions().size() + savedOptions.size()); result.addAll(savedOptions); result.addAll(fillConfig.getOptions()); return result; } ConfigManager(FillConfig fillConfig, Store store); }### Answer:
@Test public void getOptions_returns_all_options() throws Exception { when(store.read(eq(ConfigManager.ORDER))).thenReturn(Collections.singletonList("n1")); when(store.read(eq(ConfigManager.KEY_PREFIX + "n1"))).thenReturn(Arrays.asList("v1", "v2")); final List<FillOption> expected = new ArrayList<>(); expected.add(new FillOption("n1", Arrays.asList("v1", "v2"))); expected.addAll(simpleOptions("opt1", "opt2")); assertEquals(expected, configManager.getOptions()); }
@Test public void getOptions_not_include_options_with_bad_size() throws Exception { when(store.read(eq(ConfigManager.ORDER))).thenReturn(Arrays.asList("n1", "n2")); when(store.read(eq(ConfigManager.KEY_PREFIX + "n1"))).thenReturn(Collections.singletonList("v1")); when(store.read(eq(ConfigManager.KEY_PREFIX + "n1"))).thenReturn(Arrays.asList("v1", "v2", "v3")); assertEquals(simpleOptions("opt1", "opt2"), configManager.getOptions()); }
@Test public void getOptions_with_empty_custom_options_returns_options_from_config_only() throws Exception { when(store.read(eq(ConfigManager.ORDER))).thenReturn(Collections.emptyList()); assertEquals(simpleOptions("opt1", "opt2"), configManager.getOptions()); verify(store, times(1)).read(anyString()); } |
### Question:
FileUtil { public static void zip(List<File> sources, File target) throws IOException { ZipOutputStream out = null; try { out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target))); final Set<String> takenNames = new HashSet<>(); final List<File> files = walk(sources); for (File file : files) { final String uniqueName = uniqueName(file, takenNames); zipSingleFile(file, uniqueName, out); takenNames.add(uniqueName); } } finally { if (out != null) { out.close(); } } } private FileUtil(); static void write(String text, File target); static Uri getUri(Context context, String authority, File file); static void saveBitmap(Bitmap bitmap, File targetFile, int quality); static void saveBitmap(Bitmap bitmap, File targetFile, Bitmap.CompressFormat format, int quality); static void zip(List<File> sources, File target); static List<File> walk(File source); static List<File> walk(List<File> sources); static String uniqueName(File source, Set<String> taken); static String getFileExtension(File file); static String getFileNameWithoutExtention(File file); }### Answer:
@Test public void zip_all_files_in_directory() throws Exception { file.mkdirs(); final File target = new File(file, "target.zip"); final File dir1 = createDirectories("dir", "dir1"); final File dir12 = createDirectories("dir", "dir1", "dir2"); final File dir2 = createDirectories("dir", "dir2"); final File dir3 = createDirectories("dir", "dir3"); createFiles(dir1, "f1.txt", "f2.txt", "f3.txt"); createFiles(dir12, "f1.txt", "f4.txt"); createFiles(dir2); createFiles(dir3, "f1.txt"); FileUtil.zip(Collections.singletonList(new File(file, "dir")), target); Set<String> names = new HashSet<>(); try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(target))) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { names.add(entry.getName()); } } Assert.assertEquals(CollectionUtils.asSet("f1.txt", "f2.txt", "f3.txt", "f1_1.txt", "f4.txt", "f1_2.txt"), names); } |
### Question:
CurrentActivityProvider extends SimpleActivityLifecycleCallbacks { public Activity getActivity() { return activity; } @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); Activity getActivity(); void addListener(AppStateListener listener); void removeListener(AppStateListener listener); }### Answer:
@Test public void getActivity_returns_null_at_start() throws Exception { assertNull(provider.getActivity()); } |
### Question:
AnimatorFactory { static int calcRadius(int width, int height) { return (int) Math.round(Math.sqrt((float) width * width + height * height)); } AnimatorFactory(View startView); static AnimatorFactory createFactory(View startView); abstract Animator createAppearAnimator(View targetView); abstract Animator createDisappearAnimator(View targetView); }### Answer:
@Test public void calRadius_returns_correct_radius() throws Exception { final int radius = AnimatorFactory.calcRadius(3, 4); assertEquals(5, radius); } |
### Question:
CollectionUtils { public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { ArrayList<L> result = new ArrayList<L>(); for (L element : list) { if (predicate.apply(element)) { result.add(element); } } return result; } private CollectionUtils(); static ArrayList<L> filter(List<L> list, Predicate<L> predicate); static ArrayList<T> map(List<G> input, Function1<T, G> function); static Set<T> map(Set<G> input, Function1<T, G> function); static boolean isNullOrEmpty(Collection<?> input); static List<Integer> asList(int... ids); static Set<T> asSet(T... items); }### Answer:
@Test public void filter() { final List<String> strings = Arrays.asList("a", "aa", "aa", "aaa", "aaa", "aaaa"); Assert.assertEquals( Arrays.asList("aaa", "aaa", "aaaa"), CollectionUtils.filter(strings, str -> str.length() > 2) ); } |
### Question:
CollectionUtils { public static boolean isNullOrEmpty(Collection<?> input) { return input == null || input.isEmpty(); } private CollectionUtils(); static ArrayList<L> filter(List<L> list, Predicate<L> predicate); static ArrayList<T> map(List<G> input, Function1<T, G> function); static Set<T> map(Set<G> input, Function1<T, G> function); static boolean isNullOrEmpty(Collection<?> input); static List<Integer> asList(int... ids); static Set<T> asSet(T... items); }### Answer:
@Test public void isNullOrEmpty() { final List<String> strings = Arrays.asList("a", "aa", "aaa", "aaaa"); Assert.assertFalse(CollectionUtils.isNullOrEmpty(strings)); Assert.assertTrue(CollectionUtils.isNullOrEmpty(null)); Assert.assertTrue(CollectionUtils.isNullOrEmpty(Collections.emptyList())); } |
### Question:
CollectionUtils { public static List<Integer> asList(int... ids) { final List<Integer> result = new ArrayList<>(ids.length); for (int id : ids) { result.add(id); } return result; } private CollectionUtils(); static ArrayList<L> filter(List<L> list, Predicate<L> predicate); static ArrayList<T> map(List<G> input, Function1<T, G> function); static Set<T> map(Set<G> input, Function1<T, G> function); static boolean isNullOrEmpty(Collection<?> input); static List<Integer> asList(int... ids); static Set<T> asSet(T... items); }### Answer:
@Test public void asList() throws Exception { final int[] ints = IntStream.range(0, 5).toArray(); final List<Integer> expected = IntStream.range(0, 5).boxed().collect(Collectors.toList()); Assert.assertEquals(expected, CollectionUtils.asList(ints)); } |
### Question:
CollectionUtils { public static <T> Set<T> asSet(T... items) { final HashSet<T> result = new HashSet<>(items.length); result.addAll(Arrays.asList(items)); return Collections.unmodifiableSet(result); } private CollectionUtils(); static ArrayList<L> filter(List<L> list, Predicate<L> predicate); static ArrayList<T> map(List<G> input, Function1<T, G> function); static Set<T> map(Set<G> input, Function1<T, G> function); static boolean isNullOrEmpty(Collection<?> input); static List<Integer> asList(int... ids); static Set<T> asSet(T... items); }### Answer:
@Test public void asSet() throws Exception { final Set<Integer> expected = IntStream.range(0, 5).boxed().collect(Collectors.toSet()); Assert.assertEquals(expected, CollectionUtils.asSet(0, 1, 2, 3, 4)); } |
### Question:
KVJsonSerializer { @VisibleForTesting @NonNull JSONObject createCategoryObject(KVCategory category) throws JSONException { final JSONObject categoryJsonObject = new JSONObject(); categoryJsonObject.put(NAME_KEY, category.getName()); final JSONArray entriesJsonArray = new JSONArray(); for (KVSaver.KVEntry entry : category.entries()) { final JSONObject entryJsonObject = new JSONObject(); entryJsonObject.put(NAME_KEY, entry.getName()); entryJsonObject.put(VALUE_KEY, entry.getValue()); entriesJsonArray.put(entryJsonObject); } categoryJsonObject.put(ENTRIES_KEY, entriesJsonArray); return categoryJsonObject; } }### Answer:
@Test public void createCategoryObject() throws Exception { final KVSaver.KVCategory testCategory = new KVSaver.KVCategory("cat", Arrays.asList( new KVSaver.KVEntry("k1", "v1"), new KVSaver.KVEntry("k2", "v2") )); final JSONObject category = serializer.createCategoryObject(testCategory); assertEquals("cat", category.getString(NAME_KEY)); final JSONArray entries = category.getJSONArray(ENTRIES_KEY); assertEquals(2, entries.length()); assertEquals("k1", entries.getJSONObject(0).getString(NAME_KEY)); assertEquals("v1", entries.getJSONObject(0).getString(VALUE_KEY)); assertEquals("k2", entries.getJSONObject(1).getString(NAME_KEY)); assertEquals("v2", entries.getJSONObject(1).getString(VALUE_KEY)); } |
### Question:
KVJsonSerializer { @VisibleForTesting @NonNull JSONArray createCategoriesArray(List<KVCategory> categories) throws JSONException { final JSONArray categoriesJsonArray = new JSONArray(); for (KVCategory category : categories) { if (category.isEmpty()) { continue; } final JSONObject categoryJsonObject = createCategoryObject(category); categoriesJsonArray.put(categoryJsonObject); } return categoriesJsonArray; } }### Answer:
@Test public void createCategoriesArray_returns_empty_array_for_empty_collection() throws Exception { final JSONArray array = serializer.createCategoriesArray(Collections.emptyList()); assertEquals(0, array.length()); }
@Test public void createCategoriesArray_returns_correct_json_object() throws Exception { final List<KVSaver.KVCategory> testCategories = Arrays.asList( new KVSaver.KVCategory("cat", Collections.singletonList( new KVSaver.KVEntry("k1", "v1"))), new KVSaver.KVCategory("cat", Collections.emptyList()) ); final JSONArray categories = serializer.createCategoriesArray(testCategories); assertEquals(1, categories.length()); assertEquals("cat", categories.getJSONObject(0).getString(NAME_KEY)); } |
### Question:
KVSaver extends Observable implements Saver { List<KVCategory> getData() { final List<KVCategory> categories = new ArrayList<>(); synchronized (items) { for (Map.Entry<String, Map<String, String>> categoryEntry : items.entrySet()) { final String categoryName = categoryEntry.getKey(); final List<KVEntry> entries = new ArrayList<>(); for (Map.Entry<String, String> keyValEntry : categoryEntry.getValue().entrySet()) { final String key = keyValEntry.getKey(); final String value = keyValEntry.getValue(); entries.add(new KVEntry(key, value)); } categories.add(new KVCategory(categoryName, entries)); } } return categories; } @Override void save(String category, String key, String value); @Override void remove(String category, String key); @Override void remove(String category); }### Answer:
@Test public void get_data_when_empty_returns_empty_collection() { assertTrue("collection should be empty", saver.getData().isEmpty()); } |
### Question:
KVSaver extends Observable implements Saver { @Override public void save(String category, String key, String value) { synchronized (items) { Map<String, String> keyValues = items.get(category); if (keyValues == null) { keyValues = new LinkedHashMap<>(); items.put(category, keyValues); } keyValues.put(key, value); } setChanged(); notifyObservers(); } @Override void save(String category, String key, String value); @Override void remove(String category, String key); @Override void remove(String category); }### Answer:
@Test public void save_notifies_about_change() { final Observer observable = Mockito.mock(Observer.class); saver.addObserver(observable); saver.save("cat", "key1", "val1"); Mockito.verify(observable).update(Mockito.eq(saver), Mockito.any()); }
@Test public void update_notifies_about_change() { final Observer observable = Mockito.mock(Observer.class); saver.save("cat", "key1", "val1"); saver.addObserver(observable); saver.save("cat", "key1", "val2"); Mockito.verify(observable).update(Mockito.eq(saver), Mockito.any()); } |
### Question:
SelectedPageStorage { @Nullable String getSelectedPage() { return preferences.getString(KEY_SELECTED_PAGE_ID, null); } SelectedPageStorage(SharedPreferences preferences); }### Answer:
@Test public void getSelectedPage_returns_null_if_nothing_stored() { assertNull(pageStorage.getSelectedPage()); } |
### Question:
ExpandedView extends FrameLayout { public void displayPages(List<Page> pages, Page selected, boolean animated) { setVisibility(VISIBLE); setupIcons(pages, selected, animated); setupPage(selected); title.setText(selected.getTitle()); } ExpandedView(@NonNull Context context); ExpandedView(@NonNull Context context, ExpandedViewCallback callback); ExpandedView(@NonNull Context context, @Nullable AttributeSet attrs); ExpandedView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr); void displayPages(List<Page> pages, Page selected, boolean animated); void setSelected(Page selected); void setCallback(ExpandedViewCallback callback); void destroyContentAnimated(@Nullable Runnable runnable); void destroyContent(); @Override boolean dispatchKeyEvent(KeyEvent event); static final int BACGROUND_TRANSPARENT_COLOR_RES; }### Answer:
@Test public void displayPages() throws Exception { View pageView1 = mock(View.class, withSettings().extraInterfaces(PageView.class)); View pageView2 = mock(View.class, withSettings().extraInterfaces(PageView.class)); List<Page> pages = ImmutableList.of( new Page("page1", R.drawable.ic_share, "page1", (context, overlayCallback) -> pageView1), new Page("page2", R.drawable.ic_share, "page2", (context, overlayCallback) -> pageView2) ); Page selectedPage = pages.get(0); view.displayPages(pages, selectedPage, false); ViewGroup iconHolder = view.findViewById(R.id.tab_icons_holder); assertEquals(pages.size() + 1, iconHolder.getChildCount()); for (int i = 0; i < iconHolder.getChildCount(); i++) { View child = iconHolder.getChildAt(i); assertTrue(child.isSelected() == ObjectUtil.equals(child.getTag(), selectedPage.getId())); } ViewGroup container = view.findViewById(R.id.content); assertEquals(1, container.getChildCount()); assertEquals(View.VISIBLE, view.getVisibility()); } |
### Question:
ExpandedView extends FrameLayout { public void setSelected(Page selected) { final int childCount = iconsHolder.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = iconsHolder.getChildAt(i); final boolean isSelected = ObjectUtil.equals(child.getTag(), selected.getId()); child.setSelected(isSelected); if (isSelected) { setupArrowPosition(child); } } setupPage(selected); title.setText(selected.getTitle()); } ExpandedView(@NonNull Context context); ExpandedView(@NonNull Context context, ExpandedViewCallback callback); ExpandedView(@NonNull Context context, @Nullable AttributeSet attrs); ExpandedView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr); void displayPages(List<Page> pages, Page selected, boolean animated); void setSelected(Page selected); void setCallback(ExpandedViewCallback callback); void destroyContentAnimated(@Nullable Runnable runnable); void destroyContent(); @Override boolean dispatchKeyEvent(KeyEvent event); static final int BACGROUND_TRANSPARENT_COLOR_RES; }### Answer:
@Test public void setSelected() throws Exception { View pageView1 = mock(View.class, withSettings().extraInterfaces(PageView.class)); View pageView2 = mock(View.class, withSettings().extraInterfaces(PageView.class)); List<Page> pages = ImmutableList.of( new Page("page1", R.drawable.ic_share, "page1", (context, overlayCallback) -> pageView1), new Page("page2", R.drawable.ic_share, "page2", (context, overlayCallback) -> pageView2) ); view.displayPages(pages, pages.get(0), false); ViewGroup iconHolder = view.findViewById(R.id.tab_icons_holder); Page selectedPage = pages.get(1); view.setSelected(selectedPage); for (int i = 0; i < iconHolder.getChildCount(); i++) { View child = iconHolder.getChildAt(i); assertTrue(child.isSelected() == ObjectUtil.equals(child.getTag(), selectedPage.getId())); } View selectedView = iconHolder.findViewWithTag(selectedPage.getId()); assertEquals(selectedPage.getId(), selectedView.getTag()); } |
### Question:
ExpandedView extends FrameLayout { public void destroyContent() { animator.cancel(); setVisibility(INVISIBLE); content = null; contentContainer.removeAllViews(); disposable.dispose(); } ExpandedView(@NonNull Context context); ExpandedView(@NonNull Context context, ExpandedViewCallback callback); ExpandedView(@NonNull Context context, @Nullable AttributeSet attrs); ExpandedView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr); void displayPages(List<Page> pages, Page selected, boolean animated); void setSelected(Page selected); void setCallback(ExpandedViewCallback callback); void destroyContentAnimated(@Nullable Runnable runnable); void destroyContent(); @Override boolean dispatchKeyEvent(KeyEvent event); static final int BACGROUND_TRANSPARENT_COLOR_RES; }### Answer:
@Test public void destroyContent() throws Exception { view.destroyContent(); assertEquals(View.INVISIBLE, view.getVisibility()); ViewGroup container = view.findViewById(R.id.content); assertEquals(0, container.getChildCount()); } |
### Question:
PhialButton extends View { @VisibleForTesting static int getIconSize(int maxSize, int intrinsicSize) { if (intrinsicSize == -1 || intrinsicSize > maxSize) { return maxSize; } return intrinsicSize; } PhialButton(Context context); PhialButton(Context context, @Nullable AttributeSet attrs); PhialButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr); void setIcon(Drawable drawable); void setIcon(Bitmap bitmap); Drawable getIcon(); void setIcon(@DrawableRes int iconId); void setSuggestedSize(int size); void setShadowSize(int size); @ColorInt int getBackgroundColor(); @ColorInt int getIconColor(); int getShadowColor(); int getShadowSize(); int getSuggestedSize(); }### Answer:
@Test public void getIconSize_returns_correct_size() { assertEquals(10, PhialButton.getIconSize(10, -1)); assertEquals(10, PhialButton.getIconSize(10, 20)); } |
### Question:
OverlayPresenter extends SimpleActivityLifecycleCallbacks implements ScreenTracker.ScreenListener { @Override public void onActivityStarted(Activity activity) { if (!isExpanded) { view.showButton(activity, false); } } OverlayPresenter(
OverlayView view,
List<Page> allPages,
SelectedPageStorage selectedPageStorage,
ScreenTracker screenTracker,
PhialNotifier notifier); @Override void onActivityStarted(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onScreenChanged(Screen screen); @Nullable View findViewById(int id); void destroy(); }### Answer:
@Test public void onActivityStarted_adds_button() { presenter.onActivityStarted(activity); verify(view).showButton(eq(activity), eq(false)); } |
### Question:
OverlayPresenter extends SimpleActivityLifecycleCallbacks implements ScreenTracker.ScreenListener { @Override public void onActivityStopped(Activity activity) { if (!isExpanded) { view.removeButton(activity); } } OverlayPresenter(
OverlayView view,
List<Page> allPages,
SelectedPageStorage selectedPageStorage,
ScreenTracker screenTracker,
PhialNotifier notifier); @Override void onActivityStarted(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onScreenChanged(Screen screen); @Nullable View findViewById(int id); void destroy(); }### Answer:
@Test public void onActivityStopped_removes_button() { presenter.onActivityStopped(activity); verify(view).removeButton(eq(activity)); } |
### Question:
OverlayPresenter extends SimpleActivityLifecycleCallbacks implements ScreenTracker.ScreenListener { @Override public void onActivityResumed(Activity activity) { curActivity = activity; if (isExpanded) { final List<Page> visiblePages = calcVisiblePages(); if (!visiblePages.isEmpty()) { view.showExpandedView(activity, visiblePages, findSelected(visiblePages), false); return; } isExpanded = false; view.freeExpandedContent(); notifier.fireDebugWindowHide(); view.showButton(activity, false); } } OverlayPresenter(
OverlayView view,
List<Page> allPages,
SelectedPageStorage selectedPageStorage,
ScreenTracker screenTracker,
PhialNotifier notifier); @Override void onActivityStarted(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onScreenChanged(Screen screen); @Nullable View findViewById(int id); void destroy(); }### Answer:
@Test public void onActivityResumed_does_noting_if_not_expanded() { verifyNoMoreInteractions(view); presenter.onActivityResumed(activity); } |
### Question:
OverlayPresenter extends SimpleActivityLifecycleCallbacks implements ScreenTracker.ScreenListener { @Override public void onActivityPaused(Activity activity) { if (ObjectUtil.equals(activity, curActivity)) { if (isExpanded) { view.removeExpandedView(curActivity); } curActivity = null; } } OverlayPresenter(
OverlayView view,
List<Page> allPages,
SelectedPageStorage selectedPageStorage,
ScreenTracker screenTracker,
PhialNotifier notifier); @Override void onActivityStarted(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onScreenChanged(Screen screen); @Nullable View findViewById(int id); void destroy(); }### Answer:
@Test public void onActivityPaused_does_noting_if_not_expanded() { verifyNoMoreInteractions(view); presenter.onActivityPaused(activity); } |
### Question:
OverlayPresenter extends SimpleActivityLifecycleCallbacks implements ScreenTracker.ScreenListener { @VisibleForTesting @NonNull List<Page> calcVisiblePages() { final List<Page> visiblePages = new ArrayList<>(allPages.size()); for (Page page : allPages) { final boolean shouldShowPage = screenTracker.matchesAny(page.getTargetScreens()); if (shouldShowPage) { visiblePages.add(page); } } return visiblePages; } OverlayPresenter(
OverlayView view,
List<Page> allPages,
SelectedPageStorage selectedPageStorage,
ScreenTracker screenTracker,
PhialNotifier notifier); @Override void onActivityStarted(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onScreenChanged(Screen screen); @Nullable View findViewById(int id); void destroy(); }### Answer:
@Test public void calcVisiblePages() throws Exception { addPages(2); when(screenTracker.matchesAny(any())).thenReturn(true, false); assertEquals(Collections.singletonList(pages.get(0)), presenter.calcVisiblePages()); } |
### Question:
OverlayPresenter extends SimpleActivityLifecycleCallbacks implements ScreenTracker.ScreenListener { @VisibleForTesting @NonNull Page findSelected(List<Page> visible) { final String selectedPageId = selectedPageStorage.getSelectedPage(); for (Page page : visible) { if (ObjectUtil.equals(selectedPageId, page.getId())) { return page; } } return visible.get(0); } OverlayPresenter(
OverlayView view,
List<Page> allPages,
SelectedPageStorage selectedPageStorage,
ScreenTracker screenTracker,
PhialNotifier notifier); @Override void onActivityStarted(Activity activity); @Override void onActivityStopped(Activity activity); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onScreenChanged(Screen screen); @Nullable View findViewById(int id); void destroy(); }### Answer:
@Test public void findSelected() { addPages(2); mockStoreToSelect(pages.get(1)); assertEquals(pages.get(1), presenter.findSelected(pages)); } |
### Question:
OverlayView implements ExpandedView.ExpandedViewCallback { void showExpandedView(Activity activity, List<Page> pages, Page selected, boolean animated) { expandedView.displayPages(pages, selected, animated); activity.getWindowManager().addView(expandedView, wrap(EXPANDED_VIEW_PARAMS)); } OverlayView(Context context, DragHelper dragHelper, ExpandedView expandedView); @Override void finish(); @Nullable @Override View findViewById(int id); @Override void onPageSelected(Page page); }### Answer:
@Test public void showExpandedView() { final List<Page> pages = IntStream.range(0, 5).mapToObj(this::createPage).collect(Collectors.toList()); view.showExpandedView(activity, pages, pages.get(1), false); verify(windowManager).addView(eq(expandedView), any()); verify(expandedView).displayPages(eq(pages), eq(pages.get(1)), eq(false)); } |
### Question:
OverlayView implements ExpandedView.ExpandedViewCallback { void updateExpandedView(List<Page> pages, Page selected) { expandedView.displayPages(pages, selected, false); } OverlayView(Context context, DragHelper dragHelper, ExpandedView expandedView); @Override void finish(); @Nullable @Override View findViewById(int id); @Override void onPageSelected(Page page); }### Answer:
@Test public void updateExpandedView() { final List<Page> pages = IntStream.range(0, 5).mapToObj(this::createPage).collect(Collectors.toList()); view.updateExpandedView(pages, pages.get(1)); verify(expandedView).displayPages(eq(pages), eq(pages.get(1)), eq(false)); } |
### Question:
OverlayView implements ExpandedView.ExpandedViewCallback { void removeExpandedView(Activity activity) { activity.getWindowManager().removeView(expandedView); } OverlayView(Context context, DragHelper dragHelper, ExpandedView expandedView); @Override void finish(); @Nullable @Override View findViewById(int id); @Override void onPageSelected(Page page); }### Answer:
@Test public void removeExpandedView() { view.removeExpandedView(activity); verify(windowManager).removeView(eq(expandedView)); } |
### Question:
OverlayView implements ExpandedView.ExpandedViewCallback { void setSelectedPage(Page page) { expandedView.setSelected(page); } OverlayView(Context context, DragHelper dragHelper, ExpandedView expandedView); @Override void finish(); @Nullable @Override View findViewById(int id); @Override void onPageSelected(Page page); }### Answer:
@Test public void setSelectedPage() { final Page page = createPage(1); view.setSelectedPage(page); verify(expandedView).setSelected(eq(page)); } |
### Question:
ScreenTracker extends SimpleActivityLifecycleCallbacks implements PhialScopeNotifier.OnScopeChangedListener { @Override public void onActivityResumed(Activity activity) { currentScreen.setActivity(activity); fireOnScreenChanged(); } void addListener(ScreenListener listener); void removeListener(ScreenListener listener); Screen getCurrentScreen(); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onEnterScope(String scopeName, View view); @Override void onExitScope(String scopeName); boolean matchesAny(Set<TargetScreen> targetScreen); View findTarget(int id); }### Answer:
@Test public void onActivityResumed() throws Exception { ScreenListener listener = mock(ScreenListener.class); screenTracker.addListener(listener); Activity activity = mock(Activity.class); screenTracker.onActivityResumed(activity); ArgumentCaptor<Screen> screenCaptor = ArgumentCaptor.forClass(Screen.class); verify(listener).onScreenChanged(screenCaptor.capture()); Screen screen = screenCaptor.getValue(); assertEquals(activity, screen.getActivity()); } |
### Question:
ConfigManager { void saveOption(String name, List<String> values) { if (!hasSameSizeAsConfig(values)) { throw new IllegalArgumentException("unexpected size of options!. Should be " + fillConfig.getTargetIds().size() + "; But was " + values.size() ); } final List<String> optionNames = store.read(ORDER); if (!optionNames.contains(name)) { List<String> newOptions = new ArrayList<>(optionNames); newOptions.add(name); store.save(ORDER, newOptions); } store.save(KEY_PREFIX + name, values); } ConfigManager(FillConfig fillConfig, Store store); }### Answer:
@Test public void saveOption_add_options_in_store() throws Exception { when(store.read(eq(ConfigManager.ORDER))).thenReturn(Collections.singletonList("old")); configManager.saveOption("new", Arrays.asList("1", "2")); InOrder inOrder = Mockito.inOrder(store); inOrder.verify(store).save(eq(ConfigManager.ORDER), eq(Arrays.asList("old", "new"))); inOrder.verify(store).save(eq(ConfigManager.KEY_PREFIX + "new"), eq(Arrays.asList("1", "2"))); }
@Test public void saveOption_updates_option_in_store() throws Exception { when(store.read(eq(ConfigManager.ORDER))).thenReturn(Collections.singletonList("old")); configManager.saveOption("old", Arrays.asList("1", "2")); verify(store).save(eq(ConfigManager.KEY_PREFIX + "old"), eq(Arrays.asList("1", "2"))); verify(store).save(anyString(), any()); }
@Test(expected = Exception.class) public void saveOption_throws_on_bad_size() throws Exception { when(store.read(eq(ConfigManager.ORDER))).thenReturn(Collections.emptyList()); configManager.saveOption("test", Collections.singletonList("1")); } |
### Question:
ScreenTracker extends SimpleActivityLifecycleCallbacks implements PhialScopeNotifier.OnScopeChangedListener { @Override public void onActivityPaused(Activity activity) { if (ObjectUtil.equals(activity, currentScreen.getActivity())) { currentScreen.clearActivity(); fireOnScreenChanged(); } } void addListener(ScreenListener listener); void removeListener(ScreenListener listener); Screen getCurrentScreen(); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onEnterScope(String scopeName, View view); @Override void onExitScope(String scopeName); boolean matchesAny(Set<TargetScreen> targetScreen); View findTarget(int id); }### Answer:
@Test public void onActivityPaused() throws Exception { ScreenListener listener = mock(ScreenListener.class); screenTracker.addListener(listener); Activity activity = mock(Activity.class); screenTracker.onActivityResumed(activity); screenTracker.onActivityPaused(activity); ArgumentCaptor<Screen> screenCaptor = ArgumentCaptor.forClass(Screen.class); verify(listener, times(2)).onScreenChanged(screenCaptor.capture()); Screen screen = screenCaptor.getValue(); assertNull(screen.getActivity()); } |
### Question:
ScreenTracker extends SimpleActivityLifecycleCallbacks implements PhialScopeNotifier.OnScopeChangedListener { @Override public void onEnterScope(String scopeName, View view) { currentScreen.enterScope(scopeName, view); fireOnScreenChanged(); } void addListener(ScreenListener listener); void removeListener(ScreenListener listener); Screen getCurrentScreen(); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onEnterScope(String scopeName, View view); @Override void onExitScope(String scopeName); boolean matchesAny(Set<TargetScreen> targetScreen); View findTarget(int id); }### Answer:
@Test public void onEnterScope() throws Exception { ScreenListener listener = mock(ScreenListener.class); screenTracker.addListener(listener); screenTracker.onEnterScope("scope", mock(View.class)); verify(listener).onScreenChanged(any()); } |
### Question:
ScreenTracker extends SimpleActivityLifecycleCallbacks implements PhialScopeNotifier.OnScopeChangedListener { @Override public void onExitScope(String scopeName) { currentScreen.exitScope(scopeName); fireOnScreenChanged(); } void addListener(ScreenListener listener); void removeListener(ScreenListener listener); Screen getCurrentScreen(); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onEnterScope(String scopeName, View view); @Override void onExitScope(String scopeName); boolean matchesAny(Set<TargetScreen> targetScreen); View findTarget(int id); }### Answer:
@Test public void onExitScope() throws Exception { ScreenListener listener = mock(ScreenListener.class); screenTracker.addListener(listener); screenTracker.onExitScope("scope"); verify(listener).onScreenChanged(any()); } |
### Question:
ScreenTracker extends SimpleActivityLifecycleCallbacks implements PhialScopeNotifier.OnScopeChangedListener { void destroy() { listeners.clear(); currentScreen.clearActivity(); } void addListener(ScreenListener listener); void removeListener(ScreenListener listener); Screen getCurrentScreen(); @Override void onActivityResumed(Activity activity); @Override void onActivityPaused(Activity activity); @Override void onEnterScope(String scopeName, View view); @Override void onExitScope(String scopeName); boolean matchesAny(Set<TargetScreen> targetScreen); View findTarget(int id); }### Answer:
@Test public void destroy() throws Exception { screenTracker.destroy(); assertNull(screenTracker.getCurrentScreen().getActivity()); } |
### Question:
Screen { public boolean matchesAny(Collection<TargetScreen> screens) { if (CollectionUtils.isNullOrEmpty(screens)) { return true; } for (TargetScreen targetScreen : screens) { if (matches(targetScreen)) { return true; } } return false; } Screen(Activity activity, String scopeName); boolean matches(TargetScreen screen); boolean matchesAny(Collection<TargetScreen> screens); @Nullable View findTarget(int id); }### Answer:
@Test public void matchesAny() throws Exception { Collection<TargetScreen> targetScreens = ImmutableList.of( TargetScreen.forScope("scope0"), TargetScreen.forScope("scope1") ); screen.setActivity(Robolectric.buildActivity(ActivityA.class).get()); screen.enterScope("scope1", null); assertTrue(screen.matchesAny(targetScreens)); } |
### Question:
Screen { @Nullable public View findTarget(int id) { View resultView = null; for (WeakReference<View> weakRefView : scopes.values()) { View scopeView = weakRefView.get(); if (scopeView != null) { resultView = scopeView.findViewById(id); } if (resultView != null) { return resultView; } } if (activity != null) { resultView = activity.findViewById(id); } return resultView; } Screen(Activity activity, String scopeName); boolean matches(TargetScreen screen); boolean matchesAny(Collection<TargetScreen> screens); @Nullable View findTarget(int id); }### Answer:
@Test public void findTarget() { screen.setActivity(mock(Activity.class)); assertNull(screen.findTarget(1)); } |
### Question:
ConfigManager { List<Integer> getTargetIds() { return fillConfig.getTargetIds(); } ConfigManager(FillConfig fillConfig, Store store); }### Answer:
@Test public void getTargetIds() throws Exception { assertEquals(config.getTargetIds(), configManager.getTargetIds()); } |
### Question:
AutoFillerBuilder { public AutoFillerBuilder fill(int... ids) { Precondition.notEmpty(ids, "ids should not be empty"); this.targetIds = CollectionUtils.asList(ids); return this; } AutoFillerBuilder(TargetScreen targetScreen); AutoFillerBuilder fill(int... ids); FillConfig withOptions(FillOption... options); FillConfig withoutOptions(); }### Answer:
@Test(expected = Exception.class) public void empty_fill_rises_exception() { builder.fill(); } |
### Question:
AutoFillerBuilder { public FillConfig withOptions(FillOption... options) { this.options = Arrays.asList(options); return this.build(); } AutoFillerBuilder(TargetScreen targetScreen); AutoFillerBuilder fill(int... ids); FillConfig withOptions(FillOption... options); FillConfig withoutOptions(); }### Answer:
@Test(expected = Exception.class) public void withOptions_without_calling_fill_rises_exception() { builder.withOptions(Mockito.mock(FillOption.class)); } |
### Question:
StripPrefixFilter extends HttpInboundSyncFilter { @Override public boolean shouldFilter(HttpRequestMessage msg) { for (String target: prefixPatterns) { if (msg.getPath().matches(target)) { return true; } } return false; } StripPrefixFilter(List<String> prefixPatterns); @Override HttpRequestMessage apply(HttpRequestMessage input); @Override int filterOrder(); @Override boolean shouldFilter(HttpRequestMessage msg); }### Answer:
@Test public void testShouldFilter() { StripPrefixFilter filter = new StripPrefixFilter(Arrays.asList("/path1/.*")); assertThat(filter.shouldFilter(sampleHttpMessage("/path1/testRemaining?query1=val1"))).isTrue(); assertThat(filter.shouldFilter(sampleHttpMessage("/path2/testRemaining?query1=val1"))).isFalse(); } |
### Question:
SagaInstanceFactory { public <SagaData> SagaInstance create(Saga<SagaData> saga, SagaData data) { SagaManager<SagaData> sagaManager = (SagaManager<SagaData>)sagaManagers.get(saga); if (sagaManager == null) throw new RuntimeException(("No SagaManager for " + saga)); return sagaManager.create(data); } SagaInstanceFactory(SagaManagerFactory sagaManagerFactory, Collection<Saga<?>> sagas); SagaInstance create(Saga<SagaData> saga, SagaData data); }### Answer:
@Test public void shouldCreateSagaInstance() { when(sagaManager.create(sagaData1)).thenReturn(expectedSi1); when(sagaManager.create(sagaData2)).thenReturn(expectedSi2); SagaInstance si1 = sagaInstanceFactory.create(saga, sagaData1); assertEquals(expectedSi1, si1); verify(sagaManagerFactory, times(1)).make(saga); SagaInstance si2 = sagaInstanceFactory.create(saga, sagaData2); assertEquals(expectedSi2, si2); verify(sagaManagerFactory, times(1)).make(saga); } |
### Question:
SagaManagerImpl implements SagaManager<Data> { private void handleReply(Message message) { if (!isReplyForThisSagaType(message)) return; logger.debug("Handle reply: {}", message); String sagaId = message.getRequiredHeader(SagaReplyHeaders.REPLY_SAGA_ID); String sagaType = message.getRequiredHeader(SagaReplyHeaders.REPLY_SAGA_TYPE); SagaInstance sagaInstance = sagaInstanceRepository.find(sagaType, sagaId); Data sagaData = SagaDataSerde.deserializeSagaData(sagaInstance.getSerializedSagaData()); message.getHeader(SagaReplyHeaders.REPLY_LOCKED).ifPresent(lockedTarget -> { String destination = message.getRequiredHeader(CommandMessageHeaders.inReply(CommandMessageHeaders.DESTINATION)); sagaInstance.addDestinationsAndResources(singleton(new DestinationAndResource(destination, lockedTarget))); }); String currentState = sagaInstance.getStateName(); logger.info("Current state={}", currentState); SagaActions<Data> actions = getStateDefinition().handleReply(currentState, sagaData, message); logger.info("Handled reply. Sending commands {}", actions.getCommands()); processActions(sagaId, sagaInstance, sagaData, actions); } SagaManagerImpl(Saga<Data> saga,
SagaInstanceRepository sagaInstanceRepository,
CommandProducer commandProducer,
MessageConsumer messageConsumer,
SagaLockManager sagaLockManager,
SagaCommandProducer sagaCommandProducer); void setSagaCommandProducer(SagaCommandProducer sagaCommandProducer); void setSagaInstanceRepository(SagaInstanceRepository sagaInstanceRepository); void setCommandProducer(CommandProducer commandProducer); void setMessageConsumer(MessageConsumer messageConsumer); void setSagaLockManager(SagaLockManager sagaLockManager); @Override SagaInstance create(Data sagaData); @Override SagaInstance create(Data data, Class targetClass, Object targetId); @Override SagaInstance create(Data sagaData, Optional<String> resource); @PostConstruct void subscribeToReplyChannel(); void handleMessage(Message message); }### Answer:
@Test public void shouldExecuteSagaSuccessfully() { initializeSagaManager(); startSaga(); reset(sagaInstanceRepository, sagaCommandProducer); handleReply(false); verify(testSaga).onSagaCompletedSuccessfully(eq(sagaId), any(TestSagaData.class)); reset(sagaInstanceRepository, sagaCommandProducer); }
@Test public void shouldExecuteSagaRolledBack() { initializeSagaManager(); startSaga(); reset(sagaInstanceRepository, sagaCommandProducer); handleReply(true); verify(testSaga).onSagaRolledBack(eq(sagaId), any(TestSagaData.class)); reset(sagaInstanceRepository, sagaCommandProducer); } |
### Question:
Money { public boolean isGreaterThanOrEqual(Money other) { return amount.compareTo(other.amount) >= 0; } private Money(); Money(BigDecimal amount); Money(String s); Money(int i); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); Money add(Money delta); boolean isGreaterThanOrEqual(Money other); String asString(); Money multiply(int x); Long asLong(); static Money ZERO; }### Answer:
@Test public void shouldCompare() { assertTrue(m2.isGreaterThanOrEqual(m2)); assertTrue(m2.isGreaterThanOrEqual(m1)); assertFalse(m1.isGreaterThanOrEqual(m2)); } |
### Question:
Money { public Money add(Money delta) { return new Money(amount.add(delta.amount)); } private Money(); Money(BigDecimal amount); Money(String s); Money(int i); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); Money add(Money delta); boolean isGreaterThanOrEqual(Money other); String asString(); Money multiply(int x); Long asLong(); static Money ZERO; }### Answer:
@Test public void shouldAdd() { assertEquals(new Money(M1_AMOUNT + M2_AMOUNT), m1.add(m2)); } |
### Question:
Money { public Money multiply(int x) { return new Money(amount.multiply(new BigDecimal(x))); } private Money(); Money(BigDecimal amount); Money(String s); Money(int i); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); Money add(Money delta); boolean isGreaterThanOrEqual(Money other); String asString(); Money multiply(int x); Long asLong(); static Money ZERO; }### Answer:
@Test public void shouldMultiply() { int multiplier = 12; assertEquals(new Money(M2_AMOUNT * multiplier), m2.multiply(multiplier)); } |
### Question:
ConsumerController { @RequestMapping(method= RequestMethod.GET, path="/{consumerId}") public ResponseEntity<GetConsumerResponse> get(@PathVariable long consumerId) { return consumerService.findById(consumerId) .map(consumer -> new ResponseEntity<>(new GetConsumerResponse(consumer.getName()), HttpStatus.OK)) .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); } ConsumerController(ConsumerService consumerService); @RequestMapping(method= RequestMethod.POST) CreateConsumerResponse create(@RequestBody CreateConsumerRequest request); @RequestMapping(method= RequestMethod.GET, path="/{consumerId}") ResponseEntity<GetConsumerResponse> get(@PathVariable long consumerId); }### Answer:
@Test public void shouldGetConsumer() throws IOException { Mockito.when(consumerService.findById(1)).thenReturn(Optional.of(consumer)); given(). standaloneSetup(configureControllers(consumerController)). when(). get("/consumers/1"). then(). statusCode(200) ; } |
### Question:
OrderHistoryController { @RequestMapping(path = "/{orderId}", method = RequestMethod.GET) public ResponseEntity<GetOrderResponse> getOrder(@PathVariable String orderId) { return orderHistoryDao.findOrder(orderId) .map(order -> new ResponseEntity<>(makeGetOrderResponse(order), HttpStatus.OK)) .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); } OrderHistoryController(OrderHistoryDao orderHistoryDao); @RequestMapping(method = RequestMethod.GET) ResponseEntity<GetOrdersResponse> getOrders(@RequestParam(name = "consumerId") String consumerId); @RequestMapping(path = "/{orderId}", method = RequestMethod.GET) ResponseEntity<GetOrderResponse> getOrder(@PathVariable String orderId); }### Answer:
@Test public void testGetOrder() { when(orderHistoryDao.findOrder("1")).thenReturn(Optional.of(new Order("1", null, null, null, null, 101L, "Ajanta"))); given(). standaloneSetup(configureControllers(orderHistoryController)). when(). get("/orders/1"). then(). statusCode(200). body("restaurantName", equalTo("Ajanta")) ; } |
### Question:
DeliveryService { public void createDelivery(long orderId, long restaurantId, Address deliveryAddress) { Restaurant restaurant = restaurantRepository.findById(restaurantId).get(); deliveryRepository.save(Delivery.create(orderId, restaurantId, restaurant.getAddress(), deliveryAddress)); } DeliveryService(RestaurantRepository restaurantRepository, DeliveryRepository deliveryRepository, CourierRepository courierRepository); void createRestaurant(long restaurantId, String restaurantName, Address address); void createDelivery(long orderId, long restaurantId, Address deliveryAddress); void scheduleDelivery(long orderId, LocalDateTime readyBy); void cancelDelivery(long orderId); @Transactional void updateAvailability(long courierId, boolean available); @Transactional Optional<DeliveryStatus> getDeliveryInfo(long deliveryId); }### Answer:
@Test public void shouldCreateDelivery() { when(restaurantRepository.findById(RESTAURANT_ID)).thenReturn(Optional.of(restaurant)); when(restaurant.getAddress()).thenReturn(DeliveryServiceTestData.PICKUP_ADDRESS); deliveryService.createDelivery(ORDER_ID, RESTAURANT_ID, DeliveryServiceTestData.DELIVERY_ADDRESS); ArgumentCaptor<Delivery> arg = ArgumentCaptor.forClass(Delivery.class); verify(deliveryRepository).save(arg.capture()); Delivery delivery = arg.getValue(); assertNotNull(delivery); assertEquals(ORDER_ID, delivery.getId()); assertEquals(DeliveryState.PENDING, delivery.getState()); assertEquals(RESTAURANT_ID, delivery.getRestaurantId()); assertEquals(DeliveryServiceTestData.PICKUP_ADDRESS, delivery.getPickupAddress()); assertEquals(DeliveryServiceTestData.DELIVERY_ADDRESS, delivery.getDeliveryAddress()); } |
### Question:
DeliveryService { public void scheduleDelivery(long orderId, LocalDateTime readyBy) { Delivery delivery = deliveryRepository.findById(orderId).get(); List<Courier> couriers = courierRepository.findAllAvailable(); Courier courier = couriers.get(random.nextInt(couriers.size())); courier.addAction(Action.makePickup(delivery.getId(), delivery.getPickupAddress(), readyBy)); courier.addAction(Action.makeDropoff(delivery.getId(), delivery.getDeliveryAddress(), readyBy.plusMinutes(30))); delivery.schedule(readyBy, courier.getId()); } DeliveryService(RestaurantRepository restaurantRepository, DeliveryRepository deliveryRepository, CourierRepository courierRepository); void createRestaurant(long restaurantId, String restaurantName, Address address); void createDelivery(long orderId, long restaurantId, Address deliveryAddress); void scheduleDelivery(long orderId, LocalDateTime readyBy); void cancelDelivery(long orderId); @Transactional void updateAvailability(long courierId, boolean available); @Transactional Optional<DeliveryStatus> getDeliveryInfo(long deliveryId); }### Answer:
@Test public void shouldScheduleDelivery() { Delivery delivery = Delivery.create(ORDER_ID, RESTAURANT_ID, DeliveryServiceTestData.PICKUP_ADDRESS, DeliveryServiceTestData.DELIVERY_ADDRESS); when(deliveryRepository.findById(ORDER_ID)).thenReturn(Optional.of(delivery)); when(courierRepository.findAllAvailable()).thenReturn(Collections.singletonList(courier)); deliveryService.scheduleDelivery(ORDER_ID, READY_BY); assertEquals(DeliveryState.SCHEDULED, delivery.getState()); assertSame(courier.getId(), delivery.getAssignedCourier()); List<Action> actions = courier.getPlan().getActions(); assertEquals(2, actions.size()); assertEquals(DeliveryActionType.PICKUP, actions.get(0).getType()); assertEquals(DeliveryServiceTestData.PICKUP_ADDRESS, actions.get(0).getAddress()); assertEquals(DeliveryActionType.DROPOFF, actions.get(1).getType()); assertEquals(DeliveryServiceTestData.DELIVERY_ADDRESS, actions.get(1).getAddress()); } |
### Question:
Order { public OrderState getState() { return state; } private Order(); Order(long consumerId, long restaurantId, DeliveryInformation deliveryInformation, List<OrderLineItem> orderLineItems); static ResultWithDomainEvents<Order, OrderDomainEvent> createOrder(long consumerId, Restaurant restaurant, DeliveryInformation deliveryInformation, List<OrderLineItem> orderLineItems); Long getId(); void setId(Long id); DeliveryInformation getDeliveryInformation(); Money getOrderTotal(); List<OrderDomainEvent> cancel(); List<OrderDomainEvent> undoPendingCancel(); List<OrderDomainEvent> noteCancelled(); List<OrderDomainEvent> noteApproved(); List<OrderDomainEvent> noteRejected(); List<OrderDomainEvent> noteReversingAuthorization(); ResultWithDomainEvents<LineItemQuantityChange, OrderDomainEvent> revise(OrderRevision orderRevision); List<OrderDomainEvent> rejectRevision(); List<OrderDomainEvent> confirmRevision(OrderRevision orderRevision); Long getVersion(); List<OrderLineItem> getLineItems(); OrderState getState(); long getRestaurantId(); Long getConsumerId(); }### Answer:
@Test public void shouldCreateOrder() { assertEquals(singletonList(new OrderCreatedEvent(CHICKEN_VINDALOO_ORDER_DETAILS, OrderDetailsMother.DELIVERY_ADDRESS, RestaurantMother.AJANTA_RESTAURANT_NAME)), createResult.events); assertEquals(OrderState.APPROVAL_PENDING, order.getState()); } |
### Question:
Order { public Money getOrderTotal() { return orderLineItems.orderTotal(); } private Order(); Order(long consumerId, long restaurantId, DeliveryInformation deliveryInformation, List<OrderLineItem> orderLineItems); static ResultWithDomainEvents<Order, OrderDomainEvent> createOrder(long consumerId, Restaurant restaurant, DeliveryInformation deliveryInformation, List<OrderLineItem> orderLineItems); Long getId(); void setId(Long id); DeliveryInformation getDeliveryInformation(); Money getOrderTotal(); List<OrderDomainEvent> cancel(); List<OrderDomainEvent> undoPendingCancel(); List<OrderDomainEvent> noteCancelled(); List<OrderDomainEvent> noteApproved(); List<OrderDomainEvent> noteRejected(); List<OrderDomainEvent> noteReversingAuthorization(); ResultWithDomainEvents<LineItemQuantityChange, OrderDomainEvent> revise(OrderRevision orderRevision); List<OrderDomainEvent> rejectRevision(); List<OrderDomainEvent> confirmRevision(OrderRevision orderRevision); Long getVersion(); List<OrderLineItem> getLineItems(); OrderState getState(); long getRestaurantId(); Long getConsumerId(); }### Answer:
@Test public void shouldCalculateTotal() { assertEquals(CHICKEN_VINDALOO_PRICE.multiply(CHICKEN_VINDALOO_QUANTITY), order.getOrderTotal()); } |
### Question:
OrderService { @Transactional public Order createOrder(long consumerId, long restaurantId, DeliveryInformation deliveryInformation, List<MenuItemIdAndQuantity> lineItems) { Restaurant restaurant = restaurantRepository.findById(restaurantId) .orElseThrow(() -> new RestaurantNotFoundException(restaurantId)); List<OrderLineItem> orderLineItems = makeOrderLineItems(lineItems, restaurant); ResultWithDomainEvents<Order, OrderDomainEvent> orderAndEvents = Order.createOrder(consumerId, restaurant, deliveryInformation, orderLineItems); Order order = orderAndEvents.result; orderRepository.save(order); orderAggregateEventPublisher.publish(order, orderAndEvents.events); OrderDetails orderDetails = new OrderDetails(consumerId, restaurantId, orderLineItems, order.getOrderTotal()); CreateOrderSagaState data = new CreateOrderSagaState(order.getId(), orderDetails); sagaInstanceFactory.create(createOrderSaga, data); meterRegistry.ifPresent(mr -> mr.counter("placed_orders").increment()); return order; } OrderService(SagaInstanceFactory sagaInstanceFactory,
OrderRepository orderRepository,
DomainEventPublisher eventPublisher,
RestaurantRepository restaurantRepository,
CreateOrderSaga createOrderSaga,
CancelOrderSaga cancelOrderSaga,
ReviseOrderSaga reviseOrderSaga,
OrderDomainEventPublisher orderAggregateEventPublisher,
Optional<MeterRegistry> meterRegistry); @Transactional Order createOrder(long consumerId, long restaurantId, DeliveryInformation deliveryInformation,
List<MenuItemIdAndQuantity> lineItems); Optional<Order> confirmChangeLineItemQuantity(Long orderId, OrderRevision orderRevision); void noteReversingAuthorization(Long orderId); @Transactional Order cancel(Long orderId); void approveOrder(long orderId); void rejectOrder(long orderId); void beginCancel(long orderId); void undoCancel(long orderId); void confirmCancelled(long orderId); @Transactional Order reviseOrder(long orderId, OrderRevision orderRevision); Optional<RevisedOrder> beginReviseOrder(long orderId, OrderRevision revision); void undoPendingRevision(long orderId); void confirmRevision(long orderId, OrderRevision revision); void createMenu(long id, String name, List<MenuItem> menuItems); void reviseMenu(long id, List<MenuItem> menuItems); }### Answer:
@Test public void shouldCreateOrder() { when(restaurantRepository.findById(AJANTA_ID)).thenReturn(Optional.of(AJANTA_RESTAURANT)); when(orderRepository.save(any(Order.class))).then(invocation -> { Order order = (Order) invocation.getArguments()[0]; order.setId(ORDER_ID); return order; }); Order order = orderService.createOrder(CONSUMER_ID, AJANTA_ID, OrderDetailsMother.DELIVERY_INFORMATION, CHICKEN_VINDALOO_MENU_ITEMS_AND_QUANTITIES); verify(orderRepository).save(same(order)); verify(orderAggregateEventPublisher).publish(order, Collections.singletonList(new OrderCreatedEvent(CHICKEN_VINDALOO_ORDER_DETAILS, OrderDetailsMother.DELIVERY_ADDRESS, RestaurantMother.AJANTA_RESTAURANT_NAME))); verify(sagaInstanceFactory).create(createOrderSaga, new CreateOrderSagaState(ORDER_ID, CHICKEN_VINDALOO_ORDER_DETAILS)); } |
### Question:
Tools { public static boolean isClassAccessChange(final int oldAccess, final int newAccess) { if ( not(oldAccess, Opcodes.ACC_ABSTRACT) && has(newAccess, Opcodes.ACC_ABSTRACT) ) { return true; } else if ( not(oldAccess, Opcodes.ACC_FINAL) && has(newAccess, Opcodes.ACC_FINAL) ) { return true; } else { final int compatibleChanges = Opcodes.ACC_ABSTRACT | Opcodes.ACC_FINAL ; final int oldAccess2 = oldAccess & ~compatibleChanges; final int newAccess2 = newAccess & ~compatibleChanges; return oldAccess2 != newAccess2; } } private Tools(); static final String getClassName(String internalName); static boolean isAccessChange(int oldAccess, int newAccess); static boolean isClassAccessChange(final int oldAccess, final int newAccess); static boolean isFieldAccessChange(final int oldAccess, final int newAccess); static boolean isMethodAccessChange(final int oldAccess, final int newAccess); }### Answer:
@Test public void isClassAccessChange() { assertTrue(Tools.isClassAccessChange(0, Opcodes.ACC_FINAL)); assertTrue(Tools.isClassAccessChange(0, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL)); assertFalse(Tools.isClassAccessChange(Opcodes.ACC_FINAL, 0)); assertFalse(Tools.isClassAccessChange(Opcodes.ACC_FINAL + Opcodes.ACC_PUBLIC, Opcodes.ACC_PUBLIC)); assertTrue(Tools.isClassAccessChange(Opcodes.ACC_FINAL + Opcodes.ACC_PUBLIC, 0)); assertTrue(Tools.isClassAccessChange(Opcodes.ACC_PUBLIC, Opcodes.ACC_PROTECTED)); assertFalse(Tools.isClassAccessChange(Opcodes.ACC_ABSTRACT, 0)); assertFalse(Tools.isClassAccessChange(Opcodes.ACC_ABSTRACT + Opcodes.ACC_PUBLIC, Opcodes.ACC_PUBLIC)); assertFalse(Tools.isClassAccessChange(Opcodes.ACC_ABSTRACT + Opcodes.ACC_PROTECTED, Opcodes.ACC_PROTECTED)); assertTrue(Tools.isClassAccessChange(0, Opcodes.ACC_ABSTRACT)); assertTrue(Tools.isClassAccessChange(Opcodes.ACC_PUBLIC, Opcodes.ACC_PUBLIC + Opcodes.ACC_ABSTRACT)); assertTrue(Tools.isClassAccessChange(Opcodes.ACC_PROTECTED, Opcodes.ACC_PROTECTED + Opcodes.ACC_ABSTRACT)); } |
### Question:
Tools { public static boolean isFieldAccessChange(final int oldAccess, final int newAccess) { if (isAccessIncompatible(oldAccess, newAccess)) { return true; } if ( not(oldAccess, Opcodes.ACC_FINAL) && has(newAccess, Opcodes.ACC_FINAL) ) { return true; } else { final int compatibleChanges = Opcodes.ACC_FINAL | Opcodes.ACC_TRANSIENT; final int accessPermissions = Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE; final int oldAccess2 = oldAccess & ~compatibleChanges & ~accessPermissions; final int newAccess2 = newAccess & ~compatibleChanges & ~accessPermissions; return oldAccess2 != newAccess2; } } private Tools(); static final String getClassName(String internalName); static boolean isAccessChange(int oldAccess, int newAccess); static boolean isClassAccessChange(final int oldAccess, final int newAccess); static boolean isFieldAccessChange(final int oldAccess, final int newAccess); static boolean isMethodAccessChange(final int oldAccess, final int newAccess); }### Answer:
@Test public void isFieldAccessChange() { assertTrue(Tools.isFieldAccessChange(0, Opcodes.ACC_FINAL)); assertTrue(Tools.isFieldAccessChange(0, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL)); assertFalse(Tools.isFieldAccessChange(Opcodes.ACC_FINAL, 0)); assertFalse(Tools.isFieldAccessChange(Opcodes.ACC_FINAL + Opcodes.ACC_PUBLIC, Opcodes.ACC_PUBLIC)); assertFalse(Tools.isFieldAccessChange(Opcodes.ACC_PROTECTED, Opcodes.ACC_PUBLIC)); assertFalse(Tools.isFieldAccessChange(0, Opcodes.ACC_PUBLIC)); assertFalse(Tools.isFieldAccessChange(0, Opcodes.ACC_PROTECTED)); assertFalse(Tools.isFieldAccessChange(Opcodes.ACC_PRIVATE, Opcodes.ACC_PUBLIC)); assertFalse(Tools.isFieldAccessChange(Opcodes.ACC_PRIVATE, Opcodes.ACC_PROTECTED)); assertFalse(Tools.isFieldAccessChange(Opcodes.ACC_PRIVATE, 0)); assertTrue(Tools.isFieldAccessChange(Opcodes.ACC_FINAL + Opcodes.ACC_PUBLIC, 0)); assertTrue(Tools.isFieldAccessChange(Opcodes.ACC_PUBLIC, Opcodes.ACC_PROTECTED)); assertTrue(Tools.isFieldAccessChange(Opcodes.ACC_PUBLIC, Opcodes.ACC_PRIVATE)); assertTrue(Tools.isFieldAccessChange(Opcodes.ACC_PROTECTED, 0)); assertTrue(Tools.isFieldAccessChange(Opcodes.ACC_PROTECTED, Opcodes.ACC_PRIVATE)); assertTrue(Tools.isFieldAccessChange(0, Opcodes.ACC_PRIVATE)); assertTrue(Tools.isFieldAccessChange(Opcodes.ACC_STATIC, 0)); assertTrue(Tools.isFieldAccessChange(Opcodes.ACC_STATIC + Opcodes.ACC_PUBLIC, Opcodes.ACC_PUBLIC)); assertTrue(Tools.isFieldAccessChange(Opcodes.ACC_VOLATILE, 0)); assertTrue(Tools.isFieldAccessChange(Opcodes.ACC_VOLATILE + Opcodes.ACC_PUBLIC, Opcodes.ACC_PUBLIC)); assertFalse(Tools.isFieldAccessChange(0, Opcodes.ACC_TRANSIENT)); assertFalse(Tools.isFieldAccessChange(Opcodes.ACC_PUBLIC, Opcodes.ACC_PUBLIC + Opcodes.ACC_TRANSIENT)); assertFalse(Tools.isFieldAccessChange(Opcodes.ACC_TRANSIENT, 0)); assertFalse(Tools.isFieldAccessChange(Opcodes.ACC_PUBLIC + Opcodes.ACC_TRANSIENT, Opcodes.ACC_PUBLIC)); } |
### Question:
Delta { @Nonnull public static Version inferNextVersion(@Nonnull final Version version, @Nonnull final CompatibilityType compatibilityType) { if (version == null) { throw new IllegalArgumentException("null version"); } if (compatibilityType == null) { throw new IllegalArgumentException("null compatibilityType"); } switch (compatibilityType) { case BACKWARD_COMPATIBLE_IMPLEMENTER: return version.next(Version.Element.PATCH); case BACKWARD_COMPATIBLE_USER: return version.next(Version.Element.MINOR); case NON_BACKWARD_COMPATIBLE: return version.next(Version.Element.MAJOR); default: throw new IllegalArgumentException("Unknown type <"+compatibilityType+">"); } } Delta(@Nonnull final Set<? extends Difference> differences); @Nonnull final Set<Difference> getDifferences(); @Nonnull final CompatibilityType computeCompatibilityType(); @Nonnull static Version inferNextVersion(@Nonnull final Version version, @Nonnull final CompatibilityType compatibilityType); @Nonnull final Version infer(@Nonnull final Version previous); final boolean validate(@Nonnull final Version previous, @Nonnull final Version current); }### Answer:
@Test public void inferVersion() { final int major = 1; final int minor = 2; final int patch = 3; final Version version = new Version(major, minor, patch); assertEquals(version.next(MAJOR), inferNextVersion(version, NON_BACKWARD_COMPATIBLE)); assertEquals(version.next(MINOR), inferNextVersion(version, BACKWARD_COMPATIBLE_USER)); assertEquals(version.next(PATCH), inferNextVersion(version, BACKWARD_COMPATIBLE_IMPLEMENTER)); }
@Test(expected=IllegalArgumentException.class) public void shouldInferWithNullVersionFail() { inferNextVersion(null, BACKWARD_COMPATIBLE_IMPLEMENTER); }
@Test(expected=IllegalArgumentException.class) public void shouldInferWithNullCompatibilityTypeFail() { inferNextVersion(new Version(1, 0, 0), null); } |
### Question:
Delta { @Nonnull public final Version infer(@Nonnull final Version previous) { if (previous == null) { throw new IllegalArgumentException("null previous"); } if (previous.isInDevelopment()) { throw new IllegalArgumentException("Cannot infer for in development version <"+previous+">"); } final CompatibilityType compatibilityType = computeCompatibilityType(); return inferNextVersion(previous, compatibilityType); } Delta(@Nonnull final Set<? extends Difference> differences); @Nonnull final Set<Difference> getDifferences(); @Nonnull final CompatibilityType computeCompatibilityType(); @Nonnull static Version inferNextVersion(@Nonnull final Version version, @Nonnull final CompatibilityType compatibilityType); @Nonnull final Version infer(@Nonnull final Version previous); final boolean validate(@Nonnull final Version previous, @Nonnull final Version current); }### Answer:
@Test(expected=IllegalArgumentException.class) public void shouldNullVersionNotBeInferable() { new Delta(EMPTY_DIFFERENCES).infer(null); }
@Test(expected=IllegalArgumentException.class) public void shouldDevelopmentVersionNotBeInferable() { new Delta(EMPTY_DIFFERENCES).infer(new Version(0, 0, 0)); }
@Test public void shouldEmptyDeltaBeImplementerBackwardCompatible() { final int major = 1; final int minor = 2; final int patch = 3; final Version version = new Version(major, minor, patch); final Version inferedVersion = new Delta(EMPTY_DIFFERENCES).infer(version); assertEquals(new Version(major, minor, patch+1), inferedVersion); }
@Test public void shouldDeltaWithAddsBeUserBackwardCompatible() { final int major = 1; final int minor = 2; final int patch = 3; final Version version = new Version(major, minor, patch); final Version inferedVersion = new Delta(Collections.singleton(new Delta.Add("class", new FieldInfo(0, "", "", "", null)))).infer(version); assertEquals(new Version(major, minor+1, 0), inferedVersion); }
@Test public void shouldDeltaWithChangesBeNonBackwardCompatible() { final int major = 1; final int minor = 2; final int patch = 3; final Version version = new Version(major, minor, patch); final Version inferedVersion = new Delta(Collections.singleton(new Delta.Change("class", new FieldInfo(0, "", "", "", null), new FieldInfo(0, "", "", "", null)))).infer(version); assertEquals(new Version(major+1, 0, 0), inferedVersion); }
@Test public void shouldDeltaWithRemovesBeNonBackwardCompatible() { final int major = 1; final int minor = 2; final int patch = 3; final Version version = new Version(major, minor, patch); final Version inferedVersion = new Delta(Collections.singleton(new Delta.Remove("class", new FieldInfo(0, "", "", "", null)))).infer(version); assertEquals(new Version(major+1, 0, 0), inferedVersion); } |
### Question:
Delta { public final boolean validate(@Nonnull final Version previous, @Nonnull final Version current) { if (previous == null) { throw new IllegalArgumentException("null previous"); } if (current == null) { throw new IllegalArgumentException("null current"); } if (current.compareTo(previous) <= 0) { throw new IllegalArgumentException("Current version <"+previous+"> must be more recent than previous version <"+current+">."); } if (current.isInDevelopment()) { return true; } final Version inferredVersion = infer(previous); return current.toReleaseVersion().compareTo(inferredVersion) >= 0; } Delta(@Nonnull final Set<? extends Difference> differences); @Nonnull final Set<Difference> getDifferences(); @Nonnull final CompatibilityType computeCompatibilityType(); @Nonnull static Version inferNextVersion(@Nonnull final Version version, @Nonnull final CompatibilityType compatibilityType); @Nonnull final Version infer(@Nonnull final Version previous); final boolean validate(@Nonnull final Version previous, @Nonnull final Version current); }### Answer:
@Test(expected=IllegalArgumentException.class) public void shouldValidateWithNullPreviousVersionFail() { new Delta(EMPTY_DIFFERENCES).validate(null, new Version(1, 0, 0)); }
@Test(expected=IllegalArgumentException.class) public void shouldValidateWithNullCurrentVersionFail() { new Delta(EMPTY_DIFFERENCES).validate(new Version(1, 0, 0), null); }
@Test public void shouldValidateWithCurrentVersionInDevelopmentSucceed() { validate(EMPTY_DIFFERENCES, new Version(0, 0, 0), new Version(0, 0, 1), true); }
@Test(expected=IllegalArgumentException.class) public void shouldValidateWithPreviousVersionNextCurrentVersionFail() { new Delta(EMPTY_DIFFERENCES).validate(new Version(1, 1, 0), new Version(1, 0, 0)); }
@Test(expected=IllegalArgumentException.class) public void shouldValidateWithPreviousVersionEqualsCurrentVersionFail() { new Delta(EMPTY_DIFFERENCES).validate(new Version(1, 0, 0), new Version(1, 0, 0)); }
@Test public void shouldValidateWithCorrectVersionsSucceed() { validate(EMPTY_DIFFERENCES, new Version(1, 1, 0), new Version(1, 1, 1), true); }
@Test public void shouldValidateWithCorrectPreVersionsSucceed() { validate(EMPTY_DIFFERENCES, new Version(1, 1, 0, "-", "rc1"), new Version(1, 1, 0, "-", "rc2"), true); }
@Test public void shouldValidateWithIncorrectVersionFail() { validate(Collections.singleton(new Delta.Remove("class", new FieldInfo(0, "", "", "", null))), new Version(1, 1, 0), new Version(1, 1, 1), false); }
@Test public void upgradeMinorVersionOnClassDeprecated() { validate(singleton(new Delta.Deprecate("class", new ClassInfo(1, 0, "", "", "", null, null, null), new ClassInfo(1, 0, "", "", "", null, null, null))), new Version(1, 1, 0), new Version(1, 2, 0), true); }
@Test public void upgradeMinorVersionOnFieldDeprecated() { validate(singleton(new Delta.Deprecate("class", new FieldInfo(0, "", "", "", null), new FieldInfo(0, "", "", "", null))), new Version(1, 1, 0), new Version(1, 2, 0), true); }
@Test public void upgradeMinorVersionOnMethodDeprecated() { validate(singleton(new Delta.Deprecate("class", new MethodInfo(0, "", "", "", null), new MethodInfo(0, "", "", "", null))), new Version(1, 1, 0), new Version(1, 2, 0), true); } |
### Question:
Version implements Comparable<Version> { public static Version parse(@Nonnull final String version) { final Matcher matcher = Version.PATTERN.matcher(version); if (!matcher.matches()) { throw new IllegalArgumentException("<"+version+"> does not match format "+Version.FORMAT); } final int major = Integer.valueOf(matcher.group(1)); final int minor = Integer.valueOf(matcher.group(2)); final int patch; final String patchMatch = matcher.group(3); if (StringUtils.isNotEmpty(patchMatch)) { patch = Integer.valueOf(patchMatch); } else { patch = 0; } final String separator = matcher.group(4); final String special = matcher.group(5); return new Version(major, minor, patch, separator, "".equals(special) ? null : special); } Version(@Nonnegative final int major, @Nonnegative final int minor, @Nonnegative final int patch); Version(@Nonnegative final int major, @Nonnegative final int minor, @Nonnegative final int patch, @Nullable final String separator, @Nullable final String special); static Version parse(@Nonnull final String version); Version next(@Nonnull final Version.Element element); Version toReleaseVersion(); boolean isInDevelopment(); boolean isStable(); boolean isSnapshot(); boolean isCompatible(Version version); @Override int hashCode(); @Override boolean equals(@Nullable final Object object); @Override int compareTo(final Version other); @Override String toString(); }### Answer:
@Test public void shouldValidVersionBeParsed() { Version.parse("1.2"); Version.parse("1.2.3"); Version.parse("10.20.30"); Version.parse("1.2.3beta"); Version.parse("1.2.3.DEV"); Version.parse("1.2.3.DEV-SNAPSHOT"); Version.parse("1.2-SNAPSHOT"); Version.parse("1.2.3-SNAPSHOT"); Version.parse("1.2.3-RC-SNAPSHOT"); Version.parse("1.2-RC-SNAPSHOT"); }
@Test(expected=IllegalArgumentException.class) public void shouldInvalidVersion1NotBeParsed() { Version.parse("invalid"); }
@Test(expected=IllegalArgumentException.class) public void shouldInvalidVersion2NotBeParsed() { Version.parse("a.2.3"); } |
### Question:
Version implements Comparable<Version> { public Version next(@Nonnull final Version.Element element) { if (element == null) { throw new IllegalArgumentException("null element"); } switch (element) { case MAJOR: if (special == null || this.minor != 0 || this.patch != 0) { return new Version(this.major + 1, 0, 0); } else { return new Version(this.major, 0, 0); } case MINOR: if (special == null || this.patch != 0) { return new Version(this.major, this.minor + 1, 0); } else { return new Version(this.major, this.minor, 0); } case PATCH: if (special == null) { return new Version(this.major, this.minor, this.patch + 1); } else { return new Version(this.major, this.minor, this.patch); } default: throw new IllegalArgumentException("Unknown element <"+element+">"); } } Version(@Nonnegative final int major, @Nonnegative final int minor, @Nonnegative final int patch); Version(@Nonnegative final int major, @Nonnegative final int minor, @Nonnegative final int patch, @Nullable final String separator, @Nullable final String special); static Version parse(@Nonnull final String version); Version next(@Nonnull final Version.Element element); Version toReleaseVersion(); boolean isInDevelopment(); boolean isStable(); boolean isSnapshot(); boolean isCompatible(Version version); @Override int hashCode(); @Override boolean equals(@Nullable final Object object); @Override int compareTo(final Version other); @Override String toString(); }### Answer:
@Test public void next() { final int major = 1; final int minor = 2; final int patch = 3; final Version version = new Version(major, minor, patch); Assert.assertEquals(version.next(Version.Element.MAJOR), new Version(major+1, 0, 0)); Assert.assertEquals(version.next(Version.Element.MINOR), new Version(major, minor+1, 0)); Assert.assertEquals(version.next(Version.Element.PATCH), new Version(major, minor, patch+1)); }
@Test public void nextFromPre() { final Version version1 = new Version(1, 0, 0, "-", "rc1"); Assert.assertEquals(new Version(1, 0, 0), version1.next(Version.Element.MAJOR)); Assert.assertEquals(new Version(1, 0, 0), version1.next(Version.Element.MINOR)); Assert.assertEquals(new Version(1, 0, 0), version1.next(Version.Element.PATCH)); final Version version2 = new Version(1, 1, 0, "-", "rc1"); Assert.assertEquals(new Version(2, 0, 0), version2.next(Version.Element.MAJOR)); Assert.assertEquals(new Version(1, 1, 0), version2.next(Version.Element.MINOR)); Assert.assertEquals(new Version(1, 1, 0), version2.next(Version.Element.PATCH)); final Version version3 = new Version(1, 1, 1, "-", "rc1"); Assert.assertEquals(new Version(2, 0, 0), version3.next(Version.Element.MAJOR)); Assert.assertEquals(new Version(1, 2, 0), version3.next(Version.Element.MINOR)); Assert.assertEquals(new Version(1, 1, 1), version3.next(Version.Element.PATCH)); }
@Test(expected=IllegalArgumentException.class) public void shouldNextWithNullComparisonTypeFail() { final int major = 1; final int minor = 2; final int patch = 3; final Version version = new Version(major, minor, patch); version.next(null); } |
### Question:
ExtensibleFirefoxDriver extends FirefoxDriver { public void uninstallAddon(AddonUninstallRequest request) throws IOException { addonSupport.uninstallAddon(request); } ExtensibleFirefoxDriver(GeckoDriverService service, FirefoxOptions options); void installAddon(AddonInstallRequest request); void uninstallAddon(AddonUninstallRequest request); static ArtifactInfo getArtifactInfo(); static ArtifactInfo getParentArtifactInfo(); }### Answer:
@Test public void uninstallAddon() throws Exception { File sampleExtensionZipFile = buildSampleExtension(); AddonInstallRequest installRequest = AddonInstallRequest.fromFile(sampleExtensionZipFile, AddonPersistence.TEMPORARY); BehaviorVerifier<Void> verifier = (driver, baseUri) -> { AddonUninstallRequest uninstallRequest = AddonUninstallRequest.fromId(SAMPLE_EXTENSION_ID); driver.uninstallAddon(uninstallRequest); driver.get(baseUri.toString()); try { new WebDriverWait(driver, 3).until(ExpectedConditions.presenceOfElementLocated(By.id("injected"))); fail("extension still installed it seems"); } catch (org.openqa.selenium.TimeoutException ignore) { } return (Void) null; }; testInstallAddon(installRequest, verifier); } |
### Question:
YahooOutputProcessor implements OutputProcessor { @Override public void process(Reader reader, Writer writer) throws IOException { final JavaScriptCompressor javaScriptCompressor = new JavaScriptCompressor(reader, new ErrorReporter() { public void warning(final String message, final String sourceName, final int line, final String lineSource, final int lineOffset) { if (!logWarn) { return; } if (line < 0) { logger.warn("\n[WARNING] " + message); } else { logger.warn("\n[WARNING] " + line + ':' + lineOffset + ':' + message); } } public void error(final String message, final String sourceName, final int line, final String lineSource, final int lineOffset) { if (!logError) { return; } if (line < 0) { logger.error("\n[ERROR] " + message); } else { logger.error("\n[ERROR] " + line + ':' + lineOffset + ':' + message); } } public EvaluatorException runtimeError(final String message, final String sourceName, final int line, final String lineSource, final int lineOffset) { error(message, sourceName, line, lineSource, lineOffset); return new EvaluatorException(message); } }); javaScriptCompressor.compress(writer, linebreakpos, munge, verbose, preserveAllSemiColons, disableOptimizations); } @Override void process(Reader reader, Writer writer); void setMunge(final boolean munge); void setVerbose(final boolean verbose); void setPreserveAllSemiColons(final boolean preserveAllSemiColons); void setDisableOptimizations(final boolean disableOptimizations); void setLogWarn(final boolean logWarn); void setLogError(final boolean logError); void setLinebreakpos(int linebreakpos); }### Answer:
@Test public void testSimpleJs() throws Exception { final String js = "function myFunction()\n" + "{\n" + "var x=\"\",i;\n" + "for (i=0;i<5;i++)\n" + " {\n" + " x=x + \"The number is \" + i + \"<br>\";\n" + " }\n" + "document.getElementById(\"demo\").innerHTML=x;\n" + "}"; final StringReader reader = new StringReader(js); final StringWriter writer = new StringWriter(); yahooOutputProcessor.process(reader, writer); final String expected = "function myFunction(){var x=\"\",i;for(i=0;i<5;i++){x=x+\"The number is \"+i+\"<br>\";}document.getElementById(\"demo\").innerHTML=x;}"; final String compiled = writer.getBuffer().toString(); assertEquals(expected, compiled); } |
### Question:
MD5HashFileGenerator implements HashFileGenerator, InitializingBean { @Override public Optional<String> hash(final Optional<URL> url) throws IOException { if (!url.isPresent()) { return Optional.absent(); } logger.debug("Calculating md5 hash, url:{}", url); if (isHotReloadModeOff()) { final String md5 = cache.getIfPresent(url.get()); logger.debug("md5 hash:{}", md5); if (md5 != null) { return Optional.of(md5); } } final InputStream is = url.get().openStream(); final String md5 = getMD5Checksum(is); if (isHotReloadModeOff()) { logger.debug("caching url:{} with hash:{}", url, md5); cache.put(url.get(), md5); } return Optional.fromNullable(md5); } void afterPropertiesSet(); @Override Optional<String> hash(final Optional<URL> url); @Override Optional<String> hashMulti(final Collection<URL> urls); static String getMD5Checksum(final InputStream is); void setHotReloadMode(boolean hotReloadMode); void setCacheMaxSize(int cacheMaxSize); void setExpireAfterWrite(int expireAfterWrite); void setExpireAfterWriteUnit(String expireAfterWriteUnit); boolean isHotReloadMode(); int getCacheMaxSize(); int getExpireAfterWrite(); String getExpireAfterWriteUnit(); }### Answer:
@Test public void testAbsentUrlReturnsAbsentHash() throws Exception { Assert.assertFalse("absent url results in absent hash", hashFileGenerator.hash(Optional.<URL>absent()).isPresent()); }
@Test public void testReturnedHashMatchesDebugOff() throws Exception { final URL url = getClass().getClassLoader().getResource("templates/template1.soy"); final Optional<String> hash = hashFileGenerator.hash(Optional.of(url)); Assert.assertTrue(hash.isPresent()); Assert.assertEquals("md5 hash should match", "db9e0c4790bafb99c8c8cb9462279a75", hash.get()); }
@Test public void testReturnedHashMatchesDebugOffCacheSound() throws Exception { final URL url = getClass().getClassLoader().getResource("templates/template1.soy"); hashFileGenerator.hash(Optional.of(url)); Assert.assertEquals("a cache size should be 1", 1L, hashFileGenerator.cache.size()); Assert.assertEquals("cache should contain an entry", "db9e0c4790bafb99c8c8cb9462279a75", hashFileGenerator.cache.getIfPresent(url)); } |
### Question:
EmptyHashFileGenerator implements HashFileGenerator { @Override public Optional<String> hash(final Optional<URL> url) throws IOException { return Optional.absent(); } @Override Optional<String> hash(final Optional<URL> url); @Override Optional<String> hashMulti(Collection<URL> urls); }### Answer:
@Test public void defaultHashOneNotNull() throws Exception { Assert.assertNotNull("should not be null", emptyHashFileGenerator.hash(null)); }
@Test public void defaultHashOneAbsent() throws Exception { Assert.assertFalse("should be absent", emptyHashFileGenerator.hash(null).isPresent()); }
@Test public void defaultHashOneAbsentWithValue() throws Exception { Assert.assertFalse("should be absent", emptyHashFileGenerator.hash(Optional.of(new URL("file: } |
### Question:
EmptyHashFileGenerator implements HashFileGenerator { @Override public Optional<String> hashMulti(Collection<URL> urls) throws IOException { return Optional.absent(); } @Override Optional<String> hash(final Optional<URL> url); @Override Optional<String> hashMulti(Collection<URL> urls); }### Answer:
@Test public void defaultHashMultiNotNull() throws Exception { Assert.assertNotNull("should not be null", emptyHashFileGenerator.hashMulti(null)); }
@Test public void defaultHashMultiAbsent() throws Exception { Assert.assertFalse("should be absent", emptyHashFileGenerator.hashMulti(null).isPresent()); }
@Test public void defaultHashMultiEmptyNotNull() throws Exception { Assert.assertNotNull("should not be null", emptyHashFileGenerator.hashMulti(Collections.EMPTY_LIST)); }
@Test public void defaultHashMultiEmptyNotNullAbsentWithValue() throws Exception { Assert.assertNotNull("should not be null", emptyHashFileGenerator.hashMulti(Lists.newArrayList(new URL("file: }
@Test public void defaultHashMultiEmptyAbsent() throws Exception { Assert.assertFalse("should be absent", emptyHashFileGenerator.hashMulti(Collections.EMPTY_LIST).isPresent()); } |
### Question:
GoogleClosureOutputProcessor implements OutputProcessor { @Override public void process(final Reader reader, final Writer writer) throws IOException { final String originalJsSourceCode = IOUtils.toString(reader); try { Compiler.setLoggingLevel(Level.SEVERE); final Compiler compiler = new Compiler(); final CompilerOptions compilerOptions = newCompilerOptions(); compilationLevel.setOptionsForCompilationLevel(compilerOptions); compiler.disableThreads(); compiler.initOptions(compilerOptions); final SourceFile input = SourceFile.fromInputStream("dummy.js", new ByteArrayInputStream(originalJsSourceCode.getBytes(getEncoding()))); final Result result = compiler.compile(Lists.<SourceFile>newArrayList(), Lists.newArrayList(input), compilerOptions); logWarningsAndErrors(result); boolean origFallback = false; if (result.success) { final String minifiedJsSourceCode = compiler.toSource(); if (StringUtils.isEmpty(minifiedJsSourceCode)) { origFallback = true; } else { writer.write(minifiedJsSourceCode); } } else { origFallback = true; } if (origFallback) { writer.write(originalJsSourceCode); } } finally { reader.close(); writer.close(); } } @Override void process(final Reader reader, final Writer writer); String getEncoding(); void setEncoding(String encoding); void setCompilationLevel(String compilationLevel); CompilationLevel getCompilationLevel(); void setLogCompilerErrors(boolean logCompilerErrors); void setLogCompilerWarnings(boolean logCompilerWarnings); }### Answer:
@Test public void testSimpleJs() throws Exception { final String js = "function myFunction()\n" + "{\n" + "var x=\"\",i;\n" + "for (i=0;i<5;i++)\n" + " {\n" + " x=x + \"The number is \" + i + \"<br>\";\n" + " }\n" + "document.getElementById(\"demo\").innerHTML=x;\n" + "}"; final StringReader reader = new StringReader(js); final StringWriter writer = new StringWriter(); googleClosureOutputProcessor.process(reader, writer); final String expected = "function myFunction(){var b=\"\",a;for(a=0;5>a;a++)b=b+\"The number is \"+a+\"\\x3cbr\\x3e\";document.getElementById(\"demo\").innerHTML=b};"; final String compiled = writer.getBuffer().toString(); assertEquals(expected, compiled); } |
### Question:
EmptyModelAdjuster implements ModelAdjuster { @Override public @Nullable Object adjust(@Nullable Object obj) { return obj; } @Override @Nullable Object adjust(@Nullable Object obj); }### Answer:
@Test public void nullReturnsNull() throws Exception { Assert.assertNull("null returns null", emptyModelAdjuster.adjust(null)); }
@Test public void sameObject() throws Exception { final Object obj = new Object(); Assert.assertEquals("return the same object", obj, emptyModelAdjuster.adjust(obj)); } |
### Question:
SpringModelAdjuster implements ModelAdjuster { public String getModelKey() { return modelKey; } @Override @Nullable Object adjust(@Nullable final Object obj); void setModelKey(final String modelKey); String getModelKey(); }### Answer:
@Test public void defaultModelKey() throws Exception { Assert.assertEquals("model key should be 'model'", "model", springModelAdjuster.getModelKey()); } |
### Question:
SpringModelAdjuster implements ModelAdjuster { public void setModelKey(final String modelKey) { this.modelKey = modelKey; } @Override @Nullable Object adjust(@Nullable final Object obj); void setModelKey(final String modelKey); String getModelKey(); }### Answer:
@Test public void setModelKey() throws Exception { springModelAdjuster.setModelKey("newModelKey"); Assert.assertEquals("model key should be 'newModelKey'", "newModelKey", springModelAdjuster.getModelKey()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.