method2testcases stringlengths 118 3.08k |
|---|
### Question:
ResourceRegistrar { public static void register(XAResourceProducer producer) throws RecoveryException { try { final boolean alreadyRunning = TransactionManagerServices.isTransactionManagerRunning(); final ProducerHolder holder = alreadyRunning ? new InitializableProducerHolder(producer) : new ProducerHolder(producer); if (resources.add(holder)) { if (holder instanceof InitializableProducerHolder) { boolean recovered = false; try { if (log.isDebugEnabled()) { log.debug("Transaction manager is running, recovering resource '" + holder.getUniqueName() + "'."); } IncrementalRecoverer.recover(producer); ((InitializableProducerHolder) holder).initialize(); recovered = true; } finally { if (!recovered) { resources.remove(holder); } } } } else { throw new IllegalStateException("A resource with uniqueName '" + holder.getUniqueName() + "' has already been registered. " + "Cannot register XAResourceProducer '" + producer + "'."); } } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Cannot register the XAResourceProducer '" + producer + "' caused by invalid input.", e); } } private ResourceRegistrar(); static XAResourceProducer get(final String uniqueName); static Set<String> getResourcesUniqueNames(); static void register(XAResourceProducer producer); static void unregister(XAResourceProducer producer); static XAResourceHolder findXAResourceHolder(XAResource xaResource); final static Charset UNIQUE_NAME_CHARSET; }### Answer:
@Test(expected = IllegalStateException.class) public void testCannotRegisterSameRPTwice() throws Exception { ResourceRegistrar.register(createMockProducer("xa-rp")); }
@Test(expected = IllegalArgumentException.class) public void testCannotRegisterNonASCIIUniqueName() throws Exception { ResourceRegistrar.register(createMockProducer("äöü")); } |
### Question:
ResourceRegistrar { public static void unregister(XAResourceProducer producer) { final ProducerHolder holder = new ProducerHolder(producer); if (!resources.remove(holder)) { if (log.isDebugEnabled()) { log.debug("resource with uniqueName '{}' has not been registered", holder.getUniqueName()); } } } private ResourceRegistrar(); static XAResourceProducer get(final String uniqueName); static Set<String> getResourcesUniqueNames(); static void register(XAResourceProducer producer); static void unregister(XAResourceProducer producer); static XAResourceHolder findXAResourceHolder(XAResource xaResource); final static Charset UNIQUE_NAME_CHARSET; }### Answer:
@Test public void testUnregister() throws Exception { assertEquals(1, ResourceRegistrar.getResourcesUniqueNames().size()); ResourceRegistrar.unregister(createMockProducer("xa-rp")); assertEquals(0, ResourceRegistrar.getResourcesUniqueNames().size()); } |
### Question:
WeibullDistribution extends AbstractContinuousDistribution { @Override public double inverseCumulativeProbability(double p) { double ret; if (p < 0 || p > 1) { throw new DistributionException(DistributionException.INVALID_PROBABILITY, p); } else if (p == 0) { ret = 0.0; } else if (p == 1) { ret = Double.POSITIVE_INFINITY; } else { ret = scale * Math.pow(-Math.log1p(-p), 1.0 / shape); } return ret; } WeibullDistribution(double alpha,
double beta); double getShape(); double getScale(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double inverseCumulativeProbability(double p); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); }### Answer:
@Test void testInverseCumulativeProbabilitySmallPAccuracy() { final WeibullDistribution dist = new WeibullDistribution(2, 3); final double t = dist.inverseCumulativeProbability(1e-17); Assertions.assertEquals(9.48683298050514e-9, t, 1e-17); } |
### Question:
NormalDistribution extends AbstractContinuousDistribution { @Override public double density(double x) { return Math.exp(logDensity(x)); } NormalDistribution(double mean,
double sd); double getStandardDeviation(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double inverseCumulativeProbability(final double p); @Override double probability(double x0,
double x1); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testDensity() { final double[] x = new double[] {-2, -1, 0, 1, 2}; checkDensity(0, 1, x, new double[] {0.05399096651, 0.24197072452, 0.39894228040, 0.24197072452, 0.05399096651}); checkDensity(1.1, 1, x, new double[] {0.003266819056, 0.043983595980, 0.217852177033, 0.396952547477, 0.266085249899}); } |
### Question:
NormalDistribution extends AbstractContinuousDistribution { @Override public double inverseCumulativeProbability(final double p) { if (p < 0 || p > 1) { throw new DistributionException(DistributionException.INVALID_PROBABILITY, p); } return mean + standardDeviation * SQRT2 * InverseErf.value(2 * p - 1); } NormalDistribution(double mean,
double sd); double getStandardDeviation(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double inverseCumulativeProbability(final double p); @Override double probability(double x0,
double x1); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testMath280() { final NormalDistribution normal = new NormalDistribution(0, 1); double result = normal.inverseCumulativeProbability(0.9986501019683698); Assertions.assertEquals(3.0, result, DEFAULT_TOLERANCE); result = normal.inverseCumulativeProbability(0.841344746068543); Assertions.assertEquals(1.0, result, DEFAULT_TOLERANCE); result = normal.inverseCumulativeProbability(0.9999683287581673); Assertions.assertEquals(4.0, result, DEFAULT_TOLERANCE); result = normal.inverseCumulativeProbability(0.9772498680518209); Assertions.assertEquals(2.0, result, DEFAULT_TOLERANCE); } |
### Question:
HypergeometricDistribution extends AbstractDiscreteDistribution { @Override public double probability(int x) { final double logProbability = logProbability(x); return logProbability == Double.NEGATIVE_INFINITY ? 0 : Math.exp(logProbability); } HypergeometricDistribution(int populationSize,
int numberOfSuccesses,
int sampleSize); @Override double cumulativeProbability(int x); int getNumberOfSuccesses(); int getPopulationSize(); int getSampleSize(); @Override double probability(int x); @Override double logProbability(int x); double upperCumulativeProbability(int x); @Override double getMean(); @Override double getVariance(); @Override int getSupportLowerBound(); @Override int getSupportUpperBound(); @Override boolean isSupportConnected(); }### Answer:
@Test void testZeroTrial() { final int n = 11; final int m = 4; final int s = 0; final HypergeometricDistribution dist = new HypergeometricDistribution(n, m, 0); for (int i = 1; i <= n; i++) { final double p = dist.probability(i); Assertions.assertEquals(0, p, () -> "p=" + p); } }
@Test void testMath1356() { final int n = 11; final int m = 11; for (int s = 0; s <= n; s++) { final HypergeometricDistribution dist = new HypergeometricDistribution(n, m, s); final double p = dist.probability(s); Assertions.assertEquals(1, p, () -> "p=" + p); } } |
### Question:
LogNormalDistribution extends AbstractContinuousDistribution { @Override public double density(double x) { if (x <= 0) { return 0; } final double x0 = Math.log(x) - scale; final double x1 = x0 / shape; return Math.exp(-0.5 * x1 * x1) / (shape * SQRT2PI * x); } LogNormalDistribution(double scale,
double shape); double getScale(); double getShape(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double probability(double x0,
double x1); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testDensity() { final double[] x = new double[]{-2, -1, 0, 1, 2}; checkDensity(0, 1, x, new double[] {0.0000000000, 0.0000000000, 0.0000000000, 0.3989422804, 0.1568740193}); checkDensity(1.1, 1, x, new double[] {0.0000000000, 0.0000000000, 0.0000000000, 0.2178521770, 0.1836267118}); } |
### Question:
LogNormalDistribution extends AbstractContinuousDistribution { @Override public double cumulativeProbability(double x) { if (x <= 0) { return 0; } final double dev = Math.log(x) - scale; if (Math.abs(dev) > 40 * shape) { return dev < 0 ? 0.0d : 1.0d; } return 0.5 + 0.5 * Erf.value(dev / (shape * SQRT2)); } LogNormalDistribution(double scale,
double shape); double getScale(); double getShape(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double probability(double x0,
double x1); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testExtremeValues() { final LogNormalDistribution d = new LogNormalDistribution(0, 1); for (int i = 0; i < 1e5; i++) { final double upperTail = d.cumulativeProbability(i); if (i <= 72) { Assertions.assertTrue(upperTail < 1.0d); } else { Assertions.assertTrue(upperTail > 0.99999); } } Assertions.assertEquals(1, d.cumulativeProbability(Double.MAX_VALUE)); Assertions.assertEquals(0, d.cumulativeProbability(-Double.MAX_VALUE)); Assertions.assertEquals(1, d.cumulativeProbability(Double.POSITIVE_INFINITY)); Assertions.assertEquals(0, d.cumulativeProbability(Double.NEGATIVE_INFINITY)); } |
### Question:
UniformContinuousDistribution extends AbstractContinuousDistribution { @Override public double getSupportLowerBound() { return lower; } UniformContinuousDistribution(double lower,
double upper); @Override double density(double x); @Override double cumulativeProbability(double x); @Override double inverseCumulativeProbability(final double p); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testGetLowerBound() { final UniformContinuousDistribution distribution = makeDistribution(); Assertions.assertEquals(-0.5, distribution.getSupportLowerBound()); } |
### Question:
LogNormalDistribution extends AbstractContinuousDistribution { @Override public double getVariance() { final double s = shape; final double ss = s * s; return (Math.expm1(ss)) * Math.exp(2 * scale + ss); } LogNormalDistribution(double scale,
double shape); double getScale(); double getShape(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double probability(double x0,
double x1); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testTinyVariance() { final LogNormalDistribution dist = new LogNormalDistribution(0, 1e-9); final double t = dist.getVariance(); Assertions.assertEquals(1e-18, t, 1e-20); } |
### Question:
ConstantContinuousDistribution extends AbstractContinuousDistribution { @Override public double inverseCumulativeProbability(final double p) { if (p < 0 || p > 1) { throw new DistributionException(DistributionException.INVALID_PROBABILITY, p); } return value; } ConstantContinuousDistribution(double value); @Override double density(double x); @Override double cumulativeProbability(double x); @Override double inverseCumulativeProbability(final double p); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Override @Test void testInverseCumulativeProbabilities() { final ContinuousDistribution dist = getDistribution(); for (final double x : getCumulativeTestValues()) { Assertions.assertEquals(1, dist.inverseCumulativeProbability(x)); } } |
### Question:
ConstantContinuousDistribution extends AbstractContinuousDistribution { @Override public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { return this::getSupportLowerBound; } ConstantContinuousDistribution(double value); @Override double density(double x); @Override double cumulativeProbability(double x); @Override double inverseCumulativeProbability(final double p); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test @Override void testSampler() { final double value = 12.345; final ContinuousDistribution.Sampler sampler = new ConstantContinuousDistribution(value).createSampler(null); for (int i = 0; i < 10; i++) { Assertions.assertEquals(value, sampler.sample()); } } |
### Question:
TriangularDistribution extends AbstractContinuousDistribution { @Override public double getSupportLowerBound() { return a; } TriangularDistribution(double a,
double c,
double b); double getMode(); @Override double density(double x); @Override double cumulativeProbability(double x); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override double inverseCumulativeProbability(double p); }### Answer:
@Test void testGetLowerBound() { final TriangularDistribution distribution = makeDistribution(); Assertions.assertEquals(-3.0, distribution.getSupportLowerBound()); } |
### Question:
TriangularDistribution extends AbstractContinuousDistribution { @Override public double getSupportUpperBound() { return b; } TriangularDistribution(double a,
double c,
double b); double getMode(); @Override double density(double x); @Override double cumulativeProbability(double x); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override double inverseCumulativeProbability(double p); }### Answer:
@Test void testGetUpperBound() { final TriangularDistribution distribution = makeDistribution(); Assertions.assertEquals(12.0, distribution.getSupportUpperBound()); } |
### Question:
TriangularDistribution extends AbstractContinuousDistribution { public double getMode() { return c; } TriangularDistribution(double a,
double c,
double b); double getMode(); @Override double density(double x); @Override double cumulativeProbability(double x); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override double inverseCumulativeProbability(double p); }### Answer:
@Test void testParameterAccessors() { for (final double x : new double[] {0.1, 0.2, 0.45}) { final TriangularDistribution dist = new TriangularDistribution(0, x, 1.0); Assertions.assertEquals(x, dist.getMode()); } } |
### Question:
ChiSquaredDistribution extends AbstractContinuousDistribution { public double getDegreesOfFreedom() { return gamma.getShape() * 2; } ChiSquaredDistribution(double degreesOfFreedom); double getDegreesOfFreedom(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testParameterAccessors() { final ChiSquaredDistribution distribution = makeDistribution(); Assertions.assertEquals(5d, distribution.getDegreesOfFreedom()); } |
### Question:
UniformContinuousDistribution extends AbstractContinuousDistribution { @Override public double getSupportUpperBound() { return upper; } UniformContinuousDistribution(double lower,
double upper); @Override double density(double x); @Override double cumulativeProbability(double x); @Override double inverseCumulativeProbability(final double p); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testGetUpperBound() { final UniformContinuousDistribution distribution = makeDistribution(); Assertions.assertEquals(1.25, distribution.getSupportUpperBound()); } |
### Question:
PoissonDistribution extends AbstractDiscreteDistribution { public double normalApproximateProbability(int x) { return normal.cumulativeProbability(x + 0.5); } PoissonDistribution(double p); private PoissonDistribution(double p,
double epsilon,
int maxIterations); @Override double probability(int x); @Override double logProbability(int x); @Override double cumulativeProbability(int x); double normalApproximateProbability(int x); @Override double getMean(); @Override double getVariance(); @Override int getSupportLowerBound(); @Override int getSupportUpperBound(); @Override boolean isSupportConnected(); @Override DiscreteDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testNormalApproximateProbability() { PoissonDistribution dist = new PoissonDistribution(100); double result = dist.normalApproximateProbability(110) - dist.normalApproximateProbability(89); Assertions.assertEquals(0.706281887248, result, 1e-10); dist = new PoissonDistribution(10000); result = dist.normalApproximateProbability(10200) - dist.normalApproximateProbability(9899); Assertions.assertEquals(0.820070051552, result, 1E-10); } |
### Question:
PoissonDistribution extends AbstractDiscreteDistribution { @Override public double getMean() { return mean; } PoissonDistribution(double p); private PoissonDistribution(double p,
double epsilon,
int maxIterations); @Override double probability(int x); @Override double logProbability(int x); @Override double cumulativeProbability(int x); double normalApproximateProbability(int x); @Override double getMean(); @Override double getVariance(); @Override int getSupportLowerBound(); @Override int getSupportUpperBound(); @Override boolean isSupportConnected(); @Override DiscreteDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testParameterAccessors() { final PoissonDistribution dist = new PoissonDistribution(10.0); Assertions.assertEquals(10.0, dist.getMean()); } |
### Question:
GeometricDistribution extends AbstractDiscreteDistribution { public double getProbabilityOfSuccess() { return probabilityOfSuccess; } GeometricDistribution(double p); double getProbabilityOfSuccess(); @Override double probability(int x); @Override double logProbability(int x); @Override double cumulativeProbability(int x); @Override double getMean(); @Override double getVariance(); @Override int getSupportLowerBound(); @Override int getSupportUpperBound(); @Override boolean isSupportConnected(); @Override int inverseCumulativeProbability(double p); }### Answer:
@Test void testParameterAccessors() { for (final double x : new double[] {0.1, 0.456, 0.999}) { final GeometricDistribution dist = new GeometricDistribution(x); Assertions.assertEquals(x, dist.getProbabilityOfSuccess()); } } |
### Question:
ExponentialDistribution extends AbstractContinuousDistribution { @Override public double density(double x) { final double logDensity = logDensity(x); return logDensity == Double.NEGATIVE_INFINITY ? 0 : Math.exp(logDensity); } ExponentialDistribution(double mean); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double inverseCumulativeProbability(double p); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testDensity() { final ExponentialDistribution d1 = new ExponentialDistribution(1); Assertions.assertTrue(Precision.equals(0.0, d1.density(-1e-9), 1)); Assertions.assertTrue(Precision.equals(1.0, d1.density(0.0), 1)); Assertions.assertTrue(Precision.equals(0.0, d1.density(1000.0), 1)); Assertions.assertTrue(Precision.equals(Math.exp(-1), d1.density(1.0), 1)); Assertions.assertTrue(Precision.equals(Math.exp(-2), d1.density(2.0), 1)); final ExponentialDistribution d2 = new ExponentialDistribution(3); Assertions.assertTrue(Precision.equals(1 / 3.0, d2.density(0.0), 1)); Assertions.assertEquals(0.2388437702, d2.density(1.0), 1e-8); Assertions.assertEquals(0.1711390397, d2.density(2.0), 1e-8); } |
### Question:
ExponentialDistribution extends AbstractContinuousDistribution { @Override public double getMean() { return mean; } ExponentialDistribution(double mean); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double inverseCumulativeProbability(double p); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testMeanAccessors() { final ExponentialDistribution distribution = makeDistribution(); Assertions.assertEquals(5d, distribution.getMean()); } |
### Question:
UniformContinuousDistribution extends AbstractContinuousDistribution { @Override public double inverseCumulativeProbability(final double p) { if (p < 0 || p > 1) { throw new DistributionException(DistributionException.INVALID_PROBABILITY, p); } return p * (upper - lower) + lower; } UniformContinuousDistribution(double lower,
double upper); @Override double density(double x); @Override double cumulativeProbability(double x); @Override double inverseCumulativeProbability(final double p); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testInverseCumulativeDistribution() { final UniformContinuousDistribution dist = new UniformContinuousDistribution(0, 1e-9); Assertions.assertEquals(2.5e-10, dist.inverseCumulativeProbability(0.25)); } |
### Question:
TDistribution extends AbstractContinuousDistribution { @Override public double cumulativeProbability(double x) { if (x == 0) { return 0.5; } else { final double t = RegularizedBeta.value(degreesOfFreedom / (degreesOfFreedom + (x * x)), dofOver2, 0.5); return x < 0 ? 0.5 * t : 1 - 0.5 * t; } } TDistribution(double degreesOfFreedom); double getDegreesOfFreedom(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); }### Answer:
@Test void testCumulativeProbabilityAgainstStackOverflow() { Assertions.assertDoesNotThrow(() -> { final TDistribution td = new TDistribution(5.); td.cumulativeProbability(.1); td.cumulativeProbability(.01); }); }
@Test void testCumulativeProbablilityExtremes() { TDistribution dist; for (int i = 1; i < 11; i++) { dist = new TDistribution(i * 5); Assertions.assertEquals(1, dist.cumulativeProbability(Double.POSITIVE_INFINITY), Double.MIN_VALUE); Assertions.assertEquals(0, dist.cumulativeProbability(Double.NEGATIVE_INFINITY), Double.MIN_VALUE); } } |
### Question:
TDistribution extends AbstractContinuousDistribution { public double getDegreesOfFreedom() { return degreesOfFreedom; } TDistribution(double degreesOfFreedom); double getDegreesOfFreedom(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); }### Answer:
@Test void testParameterAccessors() { final TDistribution dist = makeDistribution(); Assertions.assertEquals(5d, dist.getDegreesOfFreedom()); } |
### Question:
ParetoDistribution extends AbstractContinuousDistribution { @Override public double density(double x) { if (x < scale) { return 0; } return Math.pow(scale, shape) / Math.pow(x, shape + 1) * shape; } ParetoDistribution(double scale,
double shape); double getScale(); double getShape(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testDensity() { final double[] x = new double[] {-2, -1, 0, 1, 2}; checkDensity(1, 1, x, new double[] {0.00, 0.00, 0.00, 1.00, 0.25}); checkDensity(1.1, 1, x, new double[] {0.000, 0.000, 0.000, 0.000, 0.275}); } |
### Question:
ParetoDistribution extends AbstractContinuousDistribution { @Override public double cumulativeProbability(double x) { if (x <= scale) { return 0; } return 1 - Math.pow(scale / x, shape); } ParetoDistribution(double scale,
double shape); double getScale(); double getShape(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testExtremeValues() { final ParetoDistribution d = new ParetoDistribution(1, 1); for (int i = 0; i < 1e5; i++) { final double upperTail = d.cumulativeProbability(i); if (i <= 1000) { Assertions.assertTrue(upperTail < 1.0d); } else { Assertions.assertTrue(upperTail > 0.999); } } Assertions.assertEquals(1, d.cumulativeProbability(Double.MAX_VALUE)); Assertions.assertEquals(0, d.cumulativeProbability(-Double.MAX_VALUE)); Assertions.assertEquals(1, d.cumulativeProbability(Double.POSITIVE_INFINITY)); Assertions.assertEquals(0, d.cumulativeProbability(Double.NEGATIVE_INFINITY)); } |
### Question:
BetaDistribution extends AbstractContinuousDistribution { @Override public double logDensity(double x) { if (x < 0 || x > 1) { return Double.NEGATIVE_INFINITY; } else if (x == 0) { if (alpha < 1) { throw new DistributionException(DistributionException.TOO_SMALL, alpha, 1.0); } return Double.NEGATIVE_INFINITY; } else if (x == 1) { if (beta < 1) { throw new DistributionException(DistributionException.TOO_SMALL, beta, 1.0); } return Double.NEGATIVE_INFINITY; } else { final double logX = Math.log(x); final double log1mX = Math.log1p(-x); return (alpha - 1) * logX + (beta - 1) * log1mX - z; } } BetaDistribution(double alpha,
double beta); double getAlpha(); double getBeta(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testLogDensityPrecondition1() { final BetaDistribution d = new BetaDistribution(0.5, 3); Assertions.assertThrows(DistributionException.class, () -> d.logDensity(0.0)); }
@Test void testLogDensityPrecondition2() { final BetaDistribution d = new BetaDistribution(2, 0.5); Assertions.assertThrows(DistributionException.class, () -> d.logDensity(1.0)); } |
### Question:
BetaDistribution extends AbstractContinuousDistribution { @Override public ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng) { return new ChengBetaSampler(rng, alpha, beta)::sample; } BetaDistribution(double alpha,
double beta); double getAlpha(); double getBeta(); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); @Override ContinuousDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testGoodnessOfFit() { final UniformRandomProvider rng = RandomSource.create(RandomSource.WELL_19937_A, 123456789L); final int numSamples = 1000; final double level = 0.01; for (final double alpha : ALPHA_BETAS) { for (final double beta : ALPHA_BETAS) { final BetaDistribution betaDistribution = new BetaDistribution(alpha, beta); final ContinuousDistribution.Sampler sampler = betaDistribution.createSampler(rng); final double[] observed = AbstractContinuousDistribution.sample(numSamples, sampler); final double gT = gTest(betaDistribution, observed); Assertions.assertFalse(gT < level, () -> "G goodness-of-fit (" + gT + ") test rejected null at alpha = " + level); } } } |
### Question:
FDistribution extends AbstractContinuousDistribution { @Override public double cumulativeProbability(double x) { if (x <= SUPPORT_LO) { return 0; } else if (x >= SUPPORT_HI) { return 1; } final double n = numeratorDegreesOfFreedom; final double m = denominatorDegreesOfFreedom; return RegularizedBeta.value((n * x) / (m + n * x), 0.5 * n, 0.5 * m); } FDistribution(double numeratorDegreesOfFreedom,
double denominatorDegreesOfFreedom); @Override double density(double x); @Override double logDensity(double x); @Override double cumulativeProbability(double x); double getNumeratorDegreesOfFreedom(); double getDenominatorDegreesOfFreedom(); @Override double getMean(); @Override double getVariance(); @Override double getSupportLowerBound(); @Override double getSupportUpperBound(); @Override boolean isSupportConnected(); }### Answer:
@Test void testLargeDegreesOfFreedom() { final FDistribution fd = new FDistribution(100000, 100000); final double p = fd.cumulativeProbability(.999); final double x = fd.inverseCumulativeProbability(p); Assertions.assertEquals(.999, x, 1.0e-5); }
@Test void testSmallDegreesOfFreedom() { FDistribution fd = new FDistribution(1, 1); double p = fd.cumulativeProbability(0.975); double x = fd.inverseCumulativeProbability(p); Assertions.assertEquals(0.975, x, 1.0e-5); fd = new FDistribution(1, 2); p = fd.cumulativeProbability(0.975); x = fd.inverseCumulativeProbability(p); Assertions.assertEquals(0.975, x, 1.0e-5); } |
### Question:
AbstractDiscreteDistribution implements DiscreteDistribution { @Override public double probability(int x0, int x1) { if (x1 < x0) { throw new DistributionException(DistributionException.TOO_SMALL, x1, x0); } return cumulativeProbability(x1) - cumulativeProbability(x0); } @Override double probability(int x0,
int x1); @Override int inverseCumulativeProbability(final double p); static int[] sample(int n,
DiscreteDistribution.Sampler sampler); @Override DiscreteDistribution.Sampler createSampler(final UniformRandomProvider rng); }### Answer:
@Test void testProbabilitiesRangeArguments() { int lower = 0; int upper = 6; for (int i = 0; i < 2; i++) { Assertions.assertEquals(1 - p * 2 * i, diceDistribution.probability(lower, upper), 1E-12); lower++; upper--; } for (int i = 0; i < 6; i++) { Assertions.assertEquals(p, diceDistribution.probability(i, i + 1), 1E-12); } } |
### Question:
Tuple implements Comparable<Tuple> { @Override public int compareTo(Tuple other) { if (this.score == other.getScore() || Arrays.equals(this.element, other.element)) { return 0; } else { return this.score < other.getScore() ? -1 : 1; } } Tuple(String element, Double score); Tuple(byte[] element, Double score); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(Tuple other); String getElement(); byte[] getBinaryElement(); double getScore(); @Override String toString(); }### Answer:
@Test public void testCompareTo() { Tuple t1 = new Tuple("foo", 1.0); Tuple t2 = new Tuple("bar", 1.0); Tuple t3 = new Tuple("elem3", 2.0); Tuple t4 = new Tuple("foo", 10.0); assertEquals(0, t1.compareTo(t2)); assertEquals(0, t2.compareTo(t1)); assertEquals(-1, t1.compareTo(t3)); assertEquals(1, t3.compareTo(t1)); assertEquals(0, t1.compareTo(t4)); assertEquals(0, t4.compareTo(t1)); } |
### Question:
ThumbnailsForCollectionAccessor extends ThumbnailsAccessor { public Map<String, String> getThumbnailsForCollection(int start, int limit, int errorHandlingPolicy) throws TechnicalRuntimeException, IOException, EuropeanaApiProblem { return getThumbnailsForCollection(CommonMetadata.EDM_FIELD_THUMBNAIL_LARGE, start, limit, errorHandlingPolicy); } ThumbnailsForCollectionAccessor(String collectionName); ThumbnailsForCollectionAccessor(String collectionName, EuropeanaApi2Client apiClient); ThumbnailsForCollectionAccessor(Api2QueryInterface query,
EuropeanaApi2Client apiClient); Map<String, String> getThumbnailsForCollection(int start, int limit, int errorHandlingPolicy); Map<String, String> getThumbnailsForCollection(int thumbnailSizeCode, int start, int limit, int errorHandlingPolicy); }### Answer:
@Test public void testGetThumbnailsForCollectionLimit() throws IOException, EuropeanaApiProblem { ThumbnailsForCollectionAccessor tca = new ThumbnailsForCollectionAccessor( TEST_COLLECTION_NAME); int resultsSize = (2 * ThumbnailsAccessor.DEFAULT_BLOCKSIZE) + 1; int startPosition = 0; Map<String, String> thumbnails = tca.getThumbnailsForCollection(startPosition, resultsSize, ThumbnailsAccessor.ERROR_POLICY_RETHROW); assertTrue(thumbnails.size() == resultsSize); } |
### Question:
AuthBrowsers { public static final AuthBrowser chrome(boolean useCustomTab, AuthBrowserVersionRange versionRange) { return new AuthBrowser(Browsers.Chrome.PACKAGE_NAME, Browsers.Chrome.SIGNATURE_SET, useCustomTab, versionRange); } static final AuthBrowser chrome(boolean useCustomTab,
AuthBrowserVersionRange versionRange); static final AuthBrowser firefox(boolean useCustomTab,
AuthBrowserVersionRange versionRange); static AuthBrowser samsung(boolean useCustomTab, AuthBrowserVersionRange versionRange); static final AuthBrowser CHROME_DEFAULT; static final AuthBrowser CHROME_CUSTOM_TAB; static final AuthBrowser FIREFOX_DEFAULT; static final AuthBrowser SAMSUNG_DEFAULT; static final AuthBrowser SAMSUNG_CUSTOM_TAB; }### Answer:
@Test public void testCustomChrome() { AuthBrowser chromeCustom = AuthBrowsers.chrome(false, AuthBrowserVersionRange.between("45", "50")); Assert.assertEquals("com.android.chrome", chromeCustom.getPackageName()); Assert.assertTrue(chromeCustom.getSignatures().contains( "7fmduHKTdHHrlMvldlEqAIlSfii1tl35bxj1OXN5Ve8c4lU6URVu4xtSHc3BVZxS6WWJnxMDhIfQN0N0K2NDJg==")); Assert.assertEquals(false, chromeCustom.isUseCustomTab()); Assert.assertEquals("45", chromeCustom.getVersionRange().getLowerBoundary()); Assert.assertEquals("50", chromeCustom.getVersionRange().getUpperBoundary()); } |
### Question:
UserPrincipalImpl implements UserPrincipal { @Override public boolean hasRealmRole(final String role) { nonEmpty(role, "role"); return roles.contains(new UserRole(role, RoleType.REALM, null)); } protected UserPrincipalImpl(final String username, final String firstName,
final String lastName, final String email, final Set<UserRole> roles,
final String identityToken, final String accessToken,
final String refreshToken); @Override boolean hasResourceRole(final String role, final String resourceId); @Override boolean hasRealmRole(final String role); @Override String getUsername(); @Override String getFirstName(); @Override String getLastName(); @Override String getName(); @Override Set<UserRole> getRoles(); @Override Set<UserRole> getRealmRoles(); @Override Set<UserRole> getResourceRoles(); @Override String getEmail(); static Builder newUser(); @Override String toString(); @Override String getIdentityToken(); @Override String getAccessToken(); @Override String getRefreshToken(); String getCustomStringAttribute(String attributeName); Boolean getCustomBooleanAttribute(String attributeName); Long getCustomLongAttribute(String attributeName); Integer getCustomIntegerAttribute(String attributeName); }### Answer:
@Test public void testHasRealmRoleSucceeds() { assertEquals(userPrincipalImpl.hasRealmRole("rRole"), true); }
@Test public void testHasRealmRoleFails() { assertEquals(userPrincipalImpl.hasRealmRole("notRRole"), false); } |
### Question:
UserPrincipalImpl implements UserPrincipal { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("["); final Iterator<UserRole> iterator = roles.iterator(); if (iterator.hasNext()) { sb.append(iterator.next().getName()); while (iterator.hasNext()) { sb.append(", ").append(iterator.next().getName()); } } sb.append("]"); return "UserPrincipalImpl{" + "username='" + username + '\'' + ", firstName=" + firstName + '\'' + ", lastName=" + lastName + '\'' + ", email='" + email + '\'' + ", roles=" + sb.toString() + '}'; } protected UserPrincipalImpl(final String username, final String firstName,
final String lastName, final String email, final Set<UserRole> roles,
final String identityToken, final String accessToken,
final String refreshToken); @Override boolean hasResourceRole(final String role, final String resourceId); @Override boolean hasRealmRole(final String role); @Override String getUsername(); @Override String getFirstName(); @Override String getLastName(); @Override String getName(); @Override Set<UserRole> getRoles(); @Override Set<UserRole> getRealmRoles(); @Override Set<UserRole> getResourceRoles(); @Override String getEmail(); static Builder newUser(); @Override String toString(); @Override String getIdentityToken(); @Override String getAccessToken(); @Override String getRefreshToken(); String getCustomStringAttribute(String attributeName); Boolean getCustomBooleanAttribute(String attributeName); Long getCustomLongAttribute(String attributeName); Integer getCustomIntegerAttribute(String attributeName); }### Answer:
@Test public void testToStringImpl() { Assert.assertTrue(userPrincipalImpl.toString().contains("cRole")); Assert.assertTrue(userPrincipalImpl.toString().contains("rRole")); } |
### Question:
UserPrincipalImpl implements UserPrincipal { @Override public boolean hasResourceRole(final String role, final String resourceId) { nonEmpty(role, "role"); return roles.contains(new UserRole(role, RoleType.RESOURCE, resourceId)); } protected UserPrincipalImpl(final String username, final String firstName,
final String lastName, final String email, final Set<UserRole> roles,
final String identityToken, final String accessToken,
final String refreshToken); @Override boolean hasResourceRole(final String role, final String resourceId); @Override boolean hasRealmRole(final String role); @Override String getUsername(); @Override String getFirstName(); @Override String getLastName(); @Override String getName(); @Override Set<UserRole> getRoles(); @Override Set<UserRole> getRealmRoles(); @Override Set<UserRole> getResourceRoles(); @Override String getEmail(); static Builder newUser(); @Override String toString(); @Override String getIdentityToken(); @Override String getAccessToken(); @Override String getRefreshToken(); String getCustomStringAttribute(String attributeName); Boolean getCustomBooleanAttribute(String attributeName); Long getCustomLongAttribute(String attributeName); Integer getCustomIntegerAttribute(String attributeName); }### Answer:
@Test public void testHasResourceRoleFails() { assertEquals(userPrincipalImpl.hasResourceRole("cRole", "notid"), false); assertEquals(userPrincipalImpl.hasResourceRole("notCRole", "ID-123456"), false); assertEquals(userPrincipalImpl.hasResourceRole("notCRole", "notid"), false); }
@Test public void testHasResourceRoleSucceeds() { assertEquals(userPrincipalImpl.hasResourceRole("cRole", "ID-123456"), true); } |
### Question:
UserPrincipalImpl implements UserPrincipal { @Override public Set<UserRole> getRoles() { return roles; } protected UserPrincipalImpl(final String username, final String firstName,
final String lastName, final String email, final Set<UserRole> roles,
final String identityToken, final String accessToken,
final String refreshToken); @Override boolean hasResourceRole(final String role, final String resourceId); @Override boolean hasRealmRole(final String role); @Override String getUsername(); @Override String getFirstName(); @Override String getLastName(); @Override String getName(); @Override Set<UserRole> getRoles(); @Override Set<UserRole> getRealmRoles(); @Override Set<UserRole> getResourceRoles(); @Override String getEmail(); static Builder newUser(); @Override String toString(); @Override String getIdentityToken(); @Override String getAccessToken(); @Override String getRefreshToken(); String getCustomStringAttribute(String attributeName); Boolean getCustomBooleanAttribute(String attributeName); Long getCustomLongAttribute(String attributeName); Integer getCustomIntegerAttribute(String attributeName); }### Answer:
@Test public void testGetRoles() { assertEquals(userPrincipalImpl.getRoles().size(), 2); } |
### Question:
UserPrincipalImpl implements UserPrincipal { @Override public Set<UserRole> getRealmRoles() { return getSpecificRoles(RoleType.REALM); } protected UserPrincipalImpl(final String username, final String firstName,
final String lastName, final String email, final Set<UserRole> roles,
final String identityToken, final String accessToken,
final String refreshToken); @Override boolean hasResourceRole(final String role, final String resourceId); @Override boolean hasRealmRole(final String role); @Override String getUsername(); @Override String getFirstName(); @Override String getLastName(); @Override String getName(); @Override Set<UserRole> getRoles(); @Override Set<UserRole> getRealmRoles(); @Override Set<UserRole> getResourceRoles(); @Override String getEmail(); static Builder newUser(); @Override String toString(); @Override String getIdentityToken(); @Override String getAccessToken(); @Override String getRefreshToken(); String getCustomStringAttribute(String attributeName); Boolean getCustomBooleanAttribute(String attributeName); Long getCustomLongAttribute(String attributeName); Integer getCustomIntegerAttribute(String attributeName); }### Answer:
@Test public void testGetRealmRoles() { assertEquals(userPrincipalImpl.getRealmRoles().size(), 1); } |
### Question:
UserPrincipalImpl implements UserPrincipal { @Override public Set<UserRole> getResourceRoles() { return getSpecificRoles(RoleType.RESOURCE); } protected UserPrincipalImpl(final String username, final String firstName,
final String lastName, final String email, final Set<UserRole> roles,
final String identityToken, final String accessToken,
final String refreshToken); @Override boolean hasResourceRole(final String role, final String resourceId); @Override boolean hasRealmRole(final String role); @Override String getUsername(); @Override String getFirstName(); @Override String getLastName(); @Override String getName(); @Override Set<UserRole> getRoles(); @Override Set<UserRole> getRealmRoles(); @Override Set<UserRole> getResourceRoles(); @Override String getEmail(); static Builder newUser(); @Override String toString(); @Override String getIdentityToken(); @Override String getAccessToken(); @Override String getRefreshToken(); String getCustomStringAttribute(String attributeName); Boolean getCustomBooleanAttribute(String attributeName); Long getCustomLongAttribute(String attributeName); Integer getCustomIntegerAttribute(String attributeName); }### Answer:
@Test public void testGetResourceRoles() { assertEquals(userPrincipalImpl.getResourceRoles().size(), 1); } |
### Question:
UserPrincipalImpl implements UserPrincipal { public String getCustomStringAttribute(String attributeName) { String attribute = null; JSONObject jwt = getRawIdentityToken(); if (customAttributeExists(attributeName)) { attribute = jwt.optString(attributeName); } return attribute; } protected UserPrincipalImpl(final String username, final String firstName,
final String lastName, final String email, final Set<UserRole> roles,
final String identityToken, final String accessToken,
final String refreshToken); @Override boolean hasResourceRole(final String role, final String resourceId); @Override boolean hasRealmRole(final String role); @Override String getUsername(); @Override String getFirstName(); @Override String getLastName(); @Override String getName(); @Override Set<UserRole> getRoles(); @Override Set<UserRole> getRealmRoles(); @Override Set<UserRole> getResourceRoles(); @Override String getEmail(); static Builder newUser(); @Override String toString(); @Override String getIdentityToken(); @Override String getAccessToken(); @Override String getRefreshToken(); String getCustomStringAttribute(String attributeName); Boolean getCustomBooleanAttribute(String attributeName); Long getCustomLongAttribute(String attributeName); Integer getCustomIntegerAttribute(String attributeName); }### Answer:
@Test public void testGetCustomStringAttributes() { assertEquals("string", userPrincipalImpl.getCustomStringAttribute("string")); assertEquals(null, userPrincipalImpl.getCustomStringAttribute("nonExistentCustomAttribute")); } |
### Question:
UserPrincipalImpl implements UserPrincipal { public Boolean getCustomBooleanAttribute(String attributeName) { boolean attribute = false; JSONObject jwt = getRawIdentityToken(); if (customAttributeExists(attributeName)) { attribute = jwt.optBoolean(attributeName); } return attribute; } protected UserPrincipalImpl(final String username, final String firstName,
final String lastName, final String email, final Set<UserRole> roles,
final String identityToken, final String accessToken,
final String refreshToken); @Override boolean hasResourceRole(final String role, final String resourceId); @Override boolean hasRealmRole(final String role); @Override String getUsername(); @Override String getFirstName(); @Override String getLastName(); @Override String getName(); @Override Set<UserRole> getRoles(); @Override Set<UserRole> getRealmRoles(); @Override Set<UserRole> getResourceRoles(); @Override String getEmail(); static Builder newUser(); @Override String toString(); @Override String getIdentityToken(); @Override String getAccessToken(); @Override String getRefreshToken(); String getCustomStringAttribute(String attributeName); Boolean getCustomBooleanAttribute(String attributeName); Long getCustomLongAttribute(String attributeName); Integer getCustomIntegerAttribute(String attributeName); }### Answer:
@Test public void testGetCustomBooleanAttributes() { assertEquals(true, userPrincipalImpl.getCustomBooleanAttribute("boolean")); assertEquals(false, userPrincipalImpl.getCustomBooleanAttribute("nonExistentCustomAttribute")); } |
### Question:
UserPrincipalImpl implements UserPrincipal { public Integer getCustomIntegerAttribute(String attributeName) { int attribute = 0; JSONObject jwt = getRawIdentityToken(); if (customAttributeExists(attributeName)) { attribute = jwt.optInt(attributeName); } return attribute; } protected UserPrincipalImpl(final String username, final String firstName,
final String lastName, final String email, final Set<UserRole> roles,
final String identityToken, final String accessToken,
final String refreshToken); @Override boolean hasResourceRole(final String role, final String resourceId); @Override boolean hasRealmRole(final String role); @Override String getUsername(); @Override String getFirstName(); @Override String getLastName(); @Override String getName(); @Override Set<UserRole> getRoles(); @Override Set<UserRole> getRealmRoles(); @Override Set<UserRole> getResourceRoles(); @Override String getEmail(); static Builder newUser(); @Override String toString(); @Override String getIdentityToken(); @Override String getAccessToken(); @Override String getRefreshToken(); String getCustomStringAttribute(String attributeName); Boolean getCustomBooleanAttribute(String attributeName); Long getCustomLongAttribute(String attributeName); Integer getCustomIntegerAttribute(String attributeName); }### Answer:
@Test public void testGetCustomIntegerAttributes() { assertEquals(new Integer(1), userPrincipalImpl.getCustomIntegerAttribute("int")); assertEquals(new Integer(0), userPrincipalImpl.getCustomIntegerAttribute("nonExistentCustomAttribute")); } |
### Question:
AuthBrowsers { public static final AuthBrowser firefox(boolean useCustomTab, AuthBrowserVersionRange versionRange) { return new AuthBrowser(Browsers.Firefox.PACKAGE_NAME, Browsers.Firefox.SIGNATURE_SET, useCustomTab, versionRange); } static final AuthBrowser chrome(boolean useCustomTab,
AuthBrowserVersionRange versionRange); static final AuthBrowser firefox(boolean useCustomTab,
AuthBrowserVersionRange versionRange); static AuthBrowser samsung(boolean useCustomTab, AuthBrowserVersionRange versionRange); static final AuthBrowser CHROME_DEFAULT; static final AuthBrowser CHROME_CUSTOM_TAB; static final AuthBrowser FIREFOX_DEFAULT; static final AuthBrowser SAMSUNG_DEFAULT; static final AuthBrowser SAMSUNG_CUSTOM_TAB; }### Answer:
@Test public void testCustomFirefox() { AuthBrowser customFirefox = AuthBrowsers.firefox(false, AuthBrowserVersionRange.atLeast("55")); Assert.assertEquals("org.mozilla.firefox", customFirefox.getPackageName()); Assert.assertTrue(customFirefox.getSignatures().contains( "2gCe6pR_AO_Q2Vu8Iep-4AsiKNnUHQxu0FaDHO_qa178GByKybdT_BuE8_dYk99G5Uvx_gdONXAOO2EaXidpVQ==")); Assert.assertEquals(false, customFirefox.isUseCustomTab()); Assert.assertEquals("55", customFirefox.getVersionRange().getLowerBoundary()); Assert.assertEquals(null, customFirefox.getVersionRange().getUpperBoundary()); } |
### Question:
UserPrincipalImpl implements UserPrincipal { public Long getCustomLongAttribute(String attributeName) { long attribute = 0; JSONObject jwt = getRawIdentityToken(); if (customAttributeExists(attributeName)) { attribute = jwt.optLong(attributeName); } return attribute; } protected UserPrincipalImpl(final String username, final String firstName,
final String lastName, final String email, final Set<UserRole> roles,
final String identityToken, final String accessToken,
final String refreshToken); @Override boolean hasResourceRole(final String role, final String resourceId); @Override boolean hasRealmRole(final String role); @Override String getUsername(); @Override String getFirstName(); @Override String getLastName(); @Override String getName(); @Override Set<UserRole> getRoles(); @Override Set<UserRole> getRealmRoles(); @Override Set<UserRole> getResourceRoles(); @Override String getEmail(); static Builder newUser(); @Override String toString(); @Override String getIdentityToken(); @Override String getAccessToken(); @Override String getRefreshToken(); String getCustomStringAttribute(String attributeName); Boolean getCustomBooleanAttribute(String attributeName); Long getCustomLongAttribute(String attributeName); Integer getCustomIntegerAttribute(String attributeName); }### Answer:
@Test public void testGetCustomLongAttributes() { assertEquals(new Long(1L), userPrincipalImpl.getCustomLongAttribute("long")); assertEquals(new Long(0L), userPrincipalImpl.getCustomLongAttribute("nonExistentCustomAttribute")); } |
### Question:
JwksManager { public boolean fetchJwksIfNeeded(final KeycloakConfiguration keycloakConfiguration, final boolean forceFetch) { if (forceFetch || shouldRequestJwks(keycloakConfiguration)) { fetchJwks(keycloakConfiguration, null); return true; } return false; } JwksManager(@NonNull final Context context, @NonNull final MobileCore mobileCore,
@NonNull final AuthServiceConfiguration authServiceConfiguration); JsonWebKeySet load(final KeycloakConfiguration keyCloakConfig); boolean fetchJwksIfNeeded(final KeycloakConfiguration keycloakConfiguration,
final boolean forceFetch); void fetchJwks(@NonNull final KeycloakConfiguration keycloakConfiguration,
@Nullable final Callback<JsonWebKeySet> cb); static final String TAG; }### Answer:
@Test public void testFetchJwksIfNeeded() throws InterruptedException { JwksManager jwksManager = new JwksManager(ctx, mobileCore, authServiceConfiguration); when(sharedPrefs.getLong(anyString(), anyLong())).thenReturn(0L, System.currentTimeMillis()); boolean fetched = jwksManager.fetchJwksIfNeeded(keycloakConfiguration, false); Assert.assertTrue(fetched); fetched = jwksManager.fetchJwksIfNeeded(keycloakConfiguration, false); Assert.assertFalse(fetched); } |
### Question:
OIDCCredentials { public String serialize() { try { final JSONObject jsonCredential = new JSONObject().put("authState", this.authState.jsonSerializeString()); return jsonCredential.toString(); } catch (JSONException e) { throw new IllegalStateException(e); } } OIDCCredentials(final String serialisedCredential); OIDCCredentials(); String getAccessToken(); String getIdentityToken(); String getRefreshToken(); AuthState getAuthState(); boolean verifyClaims(final JsonWebKeySet jwks,
final KeycloakConfiguration keycloakConfig); boolean isExpired(); boolean getNeedsRenewal(); void setNeedsRenewal(); boolean isAuthorized(); String serialize(); static OIDCCredentials deserialize(final String serializedCredential); boolean checkValidAuth(); boolean renew(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testSerialize() throws JSONException { OIDCCredentials testCredential = new OIDCCredentials(CREDENTIAL_AUTH_STATE); JSONObject serializedCredential = new JSONObject(testCredential.serialize()); assertEquals(serializedCredential.get("authState"), CREDENTIAL_AUTH_STATE); } |
### Question:
OIDCCredentials { public boolean renew() throws AuthenticationException { throw new UnsupportedOperationException("Not yet implemented"); } OIDCCredentials(final String serialisedCredential); OIDCCredentials(); String getAccessToken(); String getIdentityToken(); String getRefreshToken(); AuthState getAuthState(); boolean verifyClaims(final JsonWebKeySet jwks,
final KeycloakConfiguration keycloakConfig); boolean isExpired(); boolean getNeedsRenewal(); void setNeedsRenewal(); boolean isAuthorized(); String serialize(); static OIDCCredentials deserialize(final String serializedCredential); boolean checkValidAuth(); boolean renew(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testRenew() throws AuthenticationException { OIDCCredentials testCredential = new OIDCCredentials(CREDENTIAL_AUTH_STATE); testCredential.renew(); } |
### Question:
OIDCCredentials { public static OIDCCredentials deserialize(final String serializedCredential) { nonEmpty(serializedCredential, "serializedCredential"); try { final JSONObject jsonCredential = new JSONObject(serializedCredential); final String serializedAuthState = jsonCredential.getString("authState"); return new OIDCCredentials(serializedAuthState); } catch (JSONException e) { throw new IllegalArgumentException(e); } } OIDCCredentials(final String serialisedCredential); OIDCCredentials(); String getAccessToken(); String getIdentityToken(); String getRefreshToken(); AuthState getAuthState(); boolean verifyClaims(final JsonWebKeySet jwks,
final KeycloakConfiguration keycloakConfig); boolean isExpired(); boolean getNeedsRenewal(); void setNeedsRenewal(); boolean isAuthorized(); String serialize(); static OIDCCredentials deserialize(final String serializedCredential); boolean checkValidAuth(); boolean renew(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testDeserialize() { OIDCCredentials testCredential = new OIDCCredentials(CREDENTIAL_AUTH_STATE); String serialized = testCredential.serialize(); OIDCCredentials deserialised = OIDCCredentials.deserialize(serialized); Assert.assertTrue(testCredential.equals(deserialised)); } |
### Question:
AuthStateManager { public OIDCCredentials load() { final String currentState = prefs.getString(KEY_STATE, null); if (currentState == null) { return new OIDCCredentials(); } return OIDCCredentials.deserialize(currentState); } private AuthStateManager(final Context context); OIDCCredentials load(); synchronized void save(final OIDCCredentials authState); synchronized void clear(); static AuthStateManager getInstance(); }### Answer:
@Test public void testLoadWithEmptyStore() { OIDCCredentials authState = authStateManager.load(); assertNull(authState.getAccessToken()); assertNull(authState.getIdentityToken()); assertNull(authState.getRefreshToken()); } |
### Question:
AuthStateManager { public synchronized void save(final OIDCCredentials authState) { if (authState == null) { clear(); } else { SharedPreferences.Editor e = prefs.edit().putString(KEY_STATE, authState.serialize()); if (!e.commit()) { throw new IllegalStateException("Failed to update state from shared preferences"); } } } private AuthStateManager(final Context context); OIDCCredentials load(); synchronized void save(final OIDCCredentials authState); synchronized void clear(); static AuthStateManager getInstance(); }### Answer:
@Test public void testSaveNull() { when(mockSharedPreferencesEditor.remove(anyString())) .thenReturn(mockSharedPreferencesEditor); when(mockSharedPreferencesEditor.commit()).thenReturn(true); authStateManager.save(null); verify(mockSharedPreferencesEditor, times(1)).remove(anyString()); }
@Test public void testSaveWithState() { when(mockOIDCCredentials.serialize()).thenReturn("TEST"); when(mockSharedPreferencesEditor.putString(anyString(), anyString())) .thenReturn(mockSharedPreferencesEditor); when(mockSharedPreferencesEditor.commit()).thenReturn(true); authStateManager.save(mockOIDCCredentials); verify(mockSharedPreferencesEditor, times(1)).putString(anyString(), eq("TEST")); } |
### Question:
AuthBrowsers { public static AuthBrowser samsung(boolean useCustomTab, AuthBrowserVersionRange versionRange) { return new AuthBrowser(Browsers.SBrowser.PACKAGE_NAME, Browsers.SBrowser.SIGNATURE_SET, useCustomTab, versionRange); } static final AuthBrowser chrome(boolean useCustomTab,
AuthBrowserVersionRange versionRange); static final AuthBrowser firefox(boolean useCustomTab,
AuthBrowserVersionRange versionRange); static AuthBrowser samsung(boolean useCustomTab, AuthBrowserVersionRange versionRange); static final AuthBrowser CHROME_DEFAULT; static final AuthBrowser CHROME_CUSTOM_TAB; static final AuthBrowser FIREFOX_DEFAULT; static final AuthBrowser SAMSUNG_DEFAULT; static final AuthBrowser SAMSUNG_CUSTOM_TAB; }### Answer:
@Test public void testCustomSamsung() { AuthBrowser customSamsung = AuthBrowsers.samsung(true, AuthBrowserVersionRange.atMost("6.0")); Assert.assertEquals("com.sec.android.app.sbrowser", customSamsung.getPackageName()); Assert.assertTrue(customSamsung.getSignatures().contains( "ABi2fbt8vkzj7SJ8aD5jc4xJFTDFntdkMrYXL3itsvqY1QIw-dZozdop5rgKNxjbrQAd5nntAGpgh9w84O1Xgg==")); Assert.assertEquals(true, customSamsung.isUseCustomTab()); Assert.assertEquals(null, customSamsung.getVersionRange().getLowerBoundary()); Assert.assertEquals("6.0", customSamsung.getVersionRange().getUpperBoundary()); } |
### Question:
UserIdentityParser { public UserPrincipalImpl parseUser() { return UserPrincipalImpl.newUser().withEmail(parseEmail()).withFirstName(parseFirstName()) .withLastName(parseLastName()).withUsername(parseUsername()) .withRoles(parseRoles()).withIdentityToken(credential.getIdentityToken()) .withAccessToken(credential.getAccessToken()) .withRefreshToken(credential.getRefreshToken()).build(); } UserIdentityParser(final OIDCCredentials credential,
final KeycloakConfiguration keycloakConfiguration); UserPrincipalImpl parseUser(); }### Answer:
@Test public void testParsers_WithCredentials() { String expectedUsername = "user1"; String expectedEmail = "user1@feedhenry.org"; UserRole expectedRealmRole = new UserRole("mobile-user", RoleType.REALM, null); UserRole expectedResourceRole = new UserRole("ios-access", RoleType.RESOURCE, "client-app"); UserPrincipal user = parser.parseUser(); String actualUsername = user.getUsername(); String actualEmail = user.getEmail(); Set<UserRole> actualRoles = user.getRoles(); Set<UserRole> realmRoles = user.getRealmRoles(); Set<UserRole> resourceRoles = user.getResourceRoles(); assertEquals(expectedUsername, actualUsername); assertEquals(expectedEmail, actualEmail); assertEquals(1, realmRoles.size()); assertEquals(1, resourceRoles.size()); assertTrue(actualRoles.contains(expectedRealmRole)); assertTrue(actualRoles.contains(expectedResourceRole)); } |
### Question:
AuthBrowser { public String getPackageName() { return packageName; } AuthBrowser(final String packageName, final Set<String> signatures,
final boolean useCustomTab, final AuthBrowserVersionRange versionRange); String getPackageName(); Set<String> getSignatures(); boolean isUseCustomTab(); AuthBrowserVersionRange getVersionRange(); }### Answer:
@Test public void testPackageName() { Assert.assertEquals("test.package.name", authBrowser.getPackageName()); } |
### Question:
AuthBrowser { public Set<String> getSignatures() { return signatures; } AuthBrowser(final String packageName, final Set<String> signatures,
final boolean useCustomTab, final AuthBrowserVersionRange versionRange); String getPackageName(); Set<String> getSignatures(); boolean isUseCustomTab(); AuthBrowserVersionRange getVersionRange(); }### Answer:
@Test public void testSignatures() { Assert.assertTrue(authBrowser.getSignatures().contains( "7fmduHKTdHHrlMvldlEqAIlSfii1tl35bxj1OXN5Ve8c4lU6URVu4xtSHc3BVZxS6WWJnxMDhIfQN0N0K2NDJg")); } |
### Question:
AuthBrowser { public boolean isUseCustomTab() { return useCustomTab; } AuthBrowser(final String packageName, final Set<String> signatures,
final boolean useCustomTab, final AuthBrowserVersionRange versionRange); String getPackageName(); Set<String> getSignatures(); boolean isUseCustomTab(); AuthBrowserVersionRange getVersionRange(); }### Answer:
@Test public void testCustomTab() { Assert.assertEquals(true, authBrowser.isUseCustomTab()); } |
### Question:
AuthBrowser { public AuthBrowserVersionRange getVersionRange() { return versionRange; } AuthBrowser(final String packageName, final Set<String> signatures,
final boolean useCustomTab, final AuthBrowserVersionRange versionRange); String getPackageName(); Set<String> getSignatures(); boolean isUseCustomTab(); AuthBrowserVersionRange getVersionRange(); }### Answer:
@Test public void testVersionRange() { Assert.assertEquals(null, authBrowser.getVersionRange().getLowerBoundary()); Assert.assertEquals(null, authBrowser.getVersionRange().getUpperBoundary()); } |
### Question:
BrowserConfiguration { public AppAuthConfiguration getAppAuthConfig() { return appAuthConfig; } private BrowserConfiguration(final BrowserConfigurationBuilder builder); AppAuthConfiguration getAppAuthConfig(); }### Answer:
@Test public void testChromeCustomTabBlackListSuccess() { AuthBrowser chromeCustomTab = AuthBrowsers.CHROME_CUSTOM_TAB; BrowserConfiguration browserConfiguration = new BrowserConfiguration.BrowserConfigurationBuilder().blackList() .browser(chromeCustomTab).build(); AppAuthConfiguration appAuthConfiguration = browserConfiguration.getAppAuthConfig(); BrowserBlacklist browserMatcher = (BrowserBlacklist) browserConfiguration.getAppAuthConfig() .getBrowserMatcher(); Assert.assertNotNull(appAuthConfiguration); Assert.assertNotNull(browserMatcher); }
@Test(expected = ClassCastException.class) public void testChromeCustomTabBlackListFail() { AuthBrowser chromeCustomTab = AuthBrowsers.CHROME_CUSTOM_TAB; BrowserConfiguration browserConfiguration = new BrowserConfiguration.BrowserConfigurationBuilder().blackList() .browser(chromeCustomTab).build(); BrowserWhitelist browserMatcher = (BrowserWhitelist) browserConfiguration.getAppAuthConfig() .getBrowserMatcher(); } |
### Question:
MulgaraConnector extends TriplestoreConnector { @Override public TriplestoreReader getReader() { if (m_reader == null){ try{ open(); } catch(TrippiException e){ logger.error(e.toString(),e); } } return m_reader; } @Override void close(); @Override GraphElementFactory getElementFactory(); @Override TriplestoreReader getReader(); @Override TriplestoreWriter getWriter(); @Deprecated @Override void init(Map<String, String> config); @Override void setConfiguration(Map<String, String> config); @Override void setTripleIteratorFactory(TripleIteratorFactory factory); @Override Map<String,String> getConfiguration(); @Override void open(); }### Answer:
@Test public void testGetReader() throws Exception { TriplestoreReader reader = _connector.getReader(); assertEquals(0, reader.countTriples(null, null, null, -1)); } |
### Question:
MulgaraConnector extends TriplestoreConnector { @Override public TriplestoreWriter getWriter() { if (m_reader == null){ try{ open(); } catch(TrippiException e){ logger.error(e.toString(),e); } } if (m_writer == null) { throw new UnsupportedOperationException( "This MulgaraConnector is read-only!"); } else { return m_writer; } } @Override void close(); @Override GraphElementFactory getElementFactory(); @Override TriplestoreReader getReader(); @Override TriplestoreWriter getWriter(); @Deprecated @Override void init(Map<String, String> config); @Override void setConfiguration(Map<String, String> config); @Override void setTripleIteratorFactory(TripleIteratorFactory factory); @Override Map<String,String> getConfiguration(); @Override void open(); }### Answer:
@Test public void testGetWriter() throws Exception { List<Triple> triples = new ArrayList<Triple>(); triples.add(getTriple("foo", "bar", "baz")); TriplestoreWriter writer = _connector.getWriter(); writer.add(triples, true); assertEquals(1, writer.countTriples(null, null, null, 10)); writer.delete(triples, true); assertEquals(0, writer.countTriples(null, null, null, 10)); writer.close(); } |
### Question:
Name implements Supplier<String> { public static Name of(String name) { return new Name(name); } private Name(String value); @Override String get(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); static Name of(String name); }### Answer:
@Test public void shouldReturnErrorWhenTheValueIsNull() { assertThrows(NullPointerException.class, () -> { Name.of(null); }); } |
### Question:
EmailPool { public static EmailPool getInstance(){ if(instance == null){ instance = new EmailPool(); } return instance; } private EmailPool(); ProgramInfo getProgramInfo(); static EmailPool getInstance(); void sendEmail(final MailWorker.Builder builder); }### Answer:
@Test @SuppressWarnings("all") public void initPool(){ EmailPool.getInstance(); } |
### Question:
FidDecoder { public static Fid build(String fid) throws Exception { return Fid.parseFrom(Base64.decode(fid, Base64.DEFAULT)); } static Fid build(String fid); static int version(byte[] bytes); static int compress(byte[] bytes); static long storageName(byte[] bytes); static String uuid(byte[] bytes); static long time(byte[] bytes); static String duration(InputStream input); static long offset(byte[] offsetByte); static long size(byte[] sizeByte); static List<Integer> serverId(InputStream input); }### Answer:
@Test public void testDecoderFids(){ String fid = "CAAQABgAIiA0ZGY4MTgwOTMxYTY0ZjNlYTVmYzQwMjEzY2NjZDdkMijqwd37+ywwwM8kOgIyMjoCMjBAqIFLSIeQAw=="; System.out.println("fid length "+fid.length()); int count = 1000000; FileDataProtos.Fid fids = null; long start = System.currentTimeMillis(); for(int i = 0;i <count;i++){ try{ fids = FidDecoder.build(fid); } catch(Exception e){ e.printStackTrace(); } } long end = System.currentTimeMillis(); System.out.println("count : "+ count+ " ,time :"+(end -start) + "ms"); } |
### Question:
Response { public Response() { } Response(); Response(final OutputSpeech outputSpeech); Response(final OutputSpeech outputSpeech, final Card card); Response(final OutputSpeech outputSpeech, final Card card, final Reprompt reprompt); Reprompt getReprompt(); void setReprompt(final Reprompt reprompt); OutputSpeech getOutputSpeech(); void setOutputSpeech(final OutputSpeech outputSpeech); Card getCard(); void setCard(final Card card); Resource getResource(); void setResource(Resource resource); }### Answer:
@Test public void testResponse() { response = new Response(); } |
### Question:
ResponseEncapsulation { public String getVersion() { return version; } ResponseEncapsulation(); ResponseEncapsulation(ResponseBody responseBody); ResponseEncapsulation(final Context context, final Session session, final ResponseBody responseBody); String getVersion(); Context getContext(); void setContext(final Context context); Session getSession(); void setSession(final Session session); ResponseBody getResponse(); void setResponse(final ResponseBody response); }### Answer:
@Test public void testGetVersion() { fail("Not yet implemented"); } |
### Question:
ResponseEncapsulation { public Context getContext() { return context; } ResponseEncapsulation(); ResponseEncapsulation(ResponseBody responseBody); ResponseEncapsulation(final Context context, final Session session, final ResponseBody responseBody); String getVersion(); Context getContext(); void setContext(final Context context); Session getSession(); void setSession(final Session session); ResponseBody getResponse(); void setResponse(final ResponseBody response); }### Answer:
@Test public void testGetContext() { fail("Not yet implemented"); } |
### Question:
ResponseEncapsulation { public void setContext(final Context context) { this.context = context; } ResponseEncapsulation(); ResponseEncapsulation(ResponseBody responseBody); ResponseEncapsulation(final Context context, final Session session, final ResponseBody responseBody); String getVersion(); Context getContext(); void setContext(final Context context); Session getSession(); void setSession(final Session session); ResponseBody getResponse(); void setResponse(final ResponseBody response); }### Answer:
@Test public void testSetContext() { fail("Not yet implemented"); } |
### Question:
ResponseEncapsulation { public Session getSession() { return session; } ResponseEncapsulation(); ResponseEncapsulation(ResponseBody responseBody); ResponseEncapsulation(final Context context, final Session session, final ResponseBody responseBody); String getVersion(); Context getContext(); void setContext(final Context context); Session getSession(); void setSession(final Session session); ResponseBody getResponse(); void setResponse(final ResponseBody response); }### Answer:
@Test public void testGetSession() { fail("Not yet implemented"); } |
### Question:
ResponseEncapsulation { public void setSession(final Session session) { this.session = session; } ResponseEncapsulation(); ResponseEncapsulation(ResponseBody responseBody); ResponseEncapsulation(final Context context, final Session session, final ResponseBody responseBody); String getVersion(); Context getContext(); void setContext(final Context context); Session getSession(); void setSession(final Session session); ResponseBody getResponse(); void setResponse(final ResponseBody response); }### Answer:
@Test public void testSetSession() { fail("Not yet implemented"); } |
### Question:
ResponseEncapsulation { public ResponseBody getResponse() { return response; } ResponseEncapsulation(); ResponseEncapsulation(ResponseBody responseBody); ResponseEncapsulation(final Context context, final Session session, final ResponseBody responseBody); String getVersion(); Context getContext(); void setContext(final Context context); Session getSession(); void setSession(final Session session); ResponseBody getResponse(); void setResponse(final ResponseBody response); }### Answer:
@Test public void testGetResponse() { fail("Not yet implemented"); } |
### Question:
ResponseEncapsulation { public void setResponse(final ResponseBody response) { this.response = response; } ResponseEncapsulation(); ResponseEncapsulation(ResponseBody responseBody); ResponseEncapsulation(final Context context, final Session session, final ResponseBody responseBody); String getVersion(); Context getContext(); void setContext(final Context context); Session getSession(); void setSession(final Session session); ResponseBody getResponse(); void setResponse(final ResponseBody response); }### Answer:
@Test public void testSetResponse() { fail("Not yet implemented"); } |
### Question:
Certificate { private static boolean verify(String body, String signature, PublicKey publicKey) { try { Signature sign = Signature.getInstance("SHA1WithRSA"); sign.initVerify(publicKey); sign.update(body.getBytes("UTF-8")); return sign.verify(Base64.decodeBase64(signature.getBytes("UTF-8"))); } catch (Exception e) { return false; } } Certificate(final String signature, final String signaturecerturl, final String message); Certificate(HttpServletRequest request); static boolean verify(ConcurrentHashMap<String, PublicKey> cache, Certificate certificate); static PublicKey getPublicKeyFromUrl(String signaturecerturl); String getSignature(); String getSignaturecerturl(); String getMessage(); }### Answer:
@Test public void testVerify() { fail("Not yet implemented"); } |
### Question:
Certificate { public static PublicKey getPublicKeyFromUrl(String signaturecerturl) { if (!isBaiduDomain(signaturecerturl)) { return null; } try { URL url = new URL(signaturecerturl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(3 * 1000); InputStream inputStream = connection.getInputStream(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream); PublicKey publicKey = certificate.getPublicKey(); return publicKey; } catch (Exception e) { return null; } } Certificate(final String signature, final String signaturecerturl, final String message); Certificate(HttpServletRequest request); static boolean verify(ConcurrentHashMap<String, PublicKey> cache, Certificate certificate); static PublicKey getPublicKeyFromUrl(String signaturecerturl); String getSignature(); String getSignaturecerturl(); String getMessage(); }### Answer:
@Test public void testGetPublicKeyFromUrl() { fail("Not yet implemented"); } |
### Question:
Certificate { public String getSignature() { return signature; } Certificate(final String signature, final String signaturecerturl, final String message); Certificate(HttpServletRequest request); static boolean verify(ConcurrentHashMap<String, PublicKey> cache, Certificate certificate); static PublicKey getPublicKeyFromUrl(String signaturecerturl); String getSignature(); String getSignaturecerturl(); String getMessage(); }### Answer:
@Test public void testGetSignature() { fail("Not yet implemented"); } |
### Question:
Response { public Reprompt getReprompt() { return reprompt; } Response(); Response(final OutputSpeech outputSpeech); Response(final OutputSpeech outputSpeech, final Card card); Response(final OutputSpeech outputSpeech, final Card card, final Reprompt reprompt); Reprompt getReprompt(); void setReprompt(final Reprompt reprompt); OutputSpeech getOutputSpeech(); void setOutputSpeech(final OutputSpeech outputSpeech); Card getCard(); void setCard(final Card card); Resource getResource(); void setResource(Resource resource); }### Answer:
@Test public void testGetReprompt() { response = new Response(); response.setReprompt(reprompt); Assert.assertEquals(response.getReprompt(), reprompt); } |
### Question:
Certificate { public String getSignaturecerturl() { return signaturecerturl; } Certificate(final String signature, final String signaturecerturl, final String message); Certificate(HttpServletRequest request); static boolean verify(ConcurrentHashMap<String, PublicKey> cache, Certificate certificate); static PublicKey getPublicKeyFromUrl(String signaturecerturl); String getSignature(); String getSignaturecerturl(); String getMessage(); }### Answer:
@Test public void testGetSignaturecerturl() { fail("Not yet implemented"); } |
### Question:
Certificate { public String getMessage() { return message; } Certificate(final String signature, final String signaturecerturl, final String message); Certificate(HttpServletRequest request); static boolean verify(ConcurrentHashMap<String, PublicKey> cache, Certificate certificate); static PublicKey getPublicKeyFromUrl(String signaturecerturl); String getSignature(); String getSignaturecerturl(); String getMessage(); }### Answer:
@Test public void testGetMessage() { fail("Not yet implemented"); } |
### Question:
Response { public void setReprompt(final Reprompt reprompt) { this.reprompt = reprompt; } Response(); Response(final OutputSpeech outputSpeech); Response(final OutputSpeech outputSpeech, final Card card); Response(final OutputSpeech outputSpeech, final Card card, final Reprompt reprompt); Reprompt getReprompt(); void setReprompt(final Reprompt reprompt); OutputSpeech getOutputSpeech(); void setOutputSpeech(final OutputSpeech outputSpeech); Card getCard(); void setCard(final Card card); Resource getResource(); void setResource(Resource resource); }### Answer:
@Test public void testSetReprompt() { response = new Response(); response.setReprompt(reprompt); Assert.assertEquals(reprompt, response.getReprompt()); } |
### Question:
Response { public OutputSpeech getOutputSpeech() { return outputSpeech; } Response(); Response(final OutputSpeech outputSpeech); Response(final OutputSpeech outputSpeech, final Card card); Response(final OutputSpeech outputSpeech, final Card card, final Reprompt reprompt); Reprompt getReprompt(); void setReprompt(final Reprompt reprompt); OutputSpeech getOutputSpeech(); void setOutputSpeech(final OutputSpeech outputSpeech); Card getCard(); void setCard(final Card card); Resource getResource(); void setResource(Resource resource); }### Answer:
@Test public void testGetOutputSpeech() { response = new Response(outputSpeech); Assert.assertEquals(response.getOutputSpeech(), outputSpeech); } |
### Question:
Response { public void setOutputSpeech(final OutputSpeech outputSpeech) { this.outputSpeech = outputSpeech; } Response(); Response(final OutputSpeech outputSpeech); Response(final OutputSpeech outputSpeech, final Card card); Response(final OutputSpeech outputSpeech, final Card card, final Reprompt reprompt); Reprompt getReprompt(); void setReprompt(final Reprompt reprompt); OutputSpeech getOutputSpeech(); void setOutputSpeech(final OutputSpeech outputSpeech); Card getCard(); void setCard(final Card card); Resource getResource(); void setResource(Resource resource); }### Answer:
@Test public void testSetOutputSpeech() { response = new Response(); response.setOutputSpeech(outputSpeech); Assert.assertEquals(response.getOutputSpeech(), outputSpeech); } |
### Question:
Response { public Card getCard() { return card; } Response(); Response(final OutputSpeech outputSpeech); Response(final OutputSpeech outputSpeech, final Card card); Response(final OutputSpeech outputSpeech, final Card card, final Reprompt reprompt); Reprompt getReprompt(); void setReprompt(final Reprompt reprompt); OutputSpeech getOutputSpeech(); void setOutputSpeech(final OutputSpeech outputSpeech); Card getCard(); void setCard(final Card card); Resource getResource(); void setResource(Resource resource); }### Answer:
@Test public void testGetCard() { response = new Response(outputSpeech, card, reprompt); Assert.assertEquals(response.getCard(), card); } |
### Question:
Response { public void setCard(final Card card) { this.card = card; } Response(); Response(final OutputSpeech outputSpeech); Response(final OutputSpeech outputSpeech, final Card card); Response(final OutputSpeech outputSpeech, final Card card, final Reprompt reprompt); Reprompt getReprompt(); void setReprompt(final Reprompt reprompt); OutputSpeech getOutputSpeech(); void setOutputSpeech(final OutputSpeech outputSpeech); Card getCard(); void setCard(final Card card); Resource getResource(); void setResource(Resource resource); }### Answer:
@Test public void testSetCard() { response = new Response(); response.setCard(card); Assert.assertEquals(response.getCard(), card); } |
### Question:
Response { public Resource getResource() { return resource; } Response(); Response(final OutputSpeech outputSpeech); Response(final OutputSpeech outputSpeech, final Card card); Response(final OutputSpeech outputSpeech, final Card card, final Reprompt reprompt); Reprompt getReprompt(); void setReprompt(final Reprompt reprompt); OutputSpeech getOutputSpeech(); void setOutputSpeech(final OutputSpeech outputSpeech); Card getCard(); void setCard(final Card card); Resource getResource(); void setResource(Resource resource); }### Answer:
@Test public void testGetResource() { fail("Not yet implemented"); } |
### Question:
Response { public void setResource(Resource resource) { this.resource = resource; } Response(); Response(final OutputSpeech outputSpeech); Response(final OutputSpeech outputSpeech, final Card card); Response(final OutputSpeech outputSpeech, final Card card, final Reprompt reprompt); Reprompt getReprompt(); void setReprompt(final Reprompt reprompt); OutputSpeech getOutputSpeech(); void setOutputSpeech(final OutputSpeech outputSpeech); Card getCard(); void setCard(final Card card); Resource getResource(); void setResource(Resource resource); }### Answer:
@Test public void testSetResource() { fail("Not yet implemented"); } |
### Question:
ResponseEncapsulation { public ResponseEncapsulation() { } ResponseEncapsulation(); ResponseEncapsulation(ResponseBody responseBody); ResponseEncapsulation(final Context context, final Session session, final ResponseBody responseBody); String getVersion(); Context getContext(); void setContext(final Context context); Session getSession(); void setSession(final Session session); ResponseBody getResponse(); void setResponse(final ResponseBody response); }### Answer:
@Test public void testResponseEncapsulation() { fail("Not yet implemented"); } |
### Question:
SudachiSurfaceFormFilterFactory extends TokenFilterFactory { @Override public TokenStream create(TokenStream tokenStream) { return new SudachiSurfaceFormFilter(tokenStream); } SudachiSurfaceFormFilterFactory(Map<String, String> args); @Override TokenStream create(TokenStream tokenStream); }### Answer:
@Test public void testEmptyTerm() throws IOException { analyzer = new Analyzer() { @Override protected TokenStreamComponents createComponents(String s) { Tokenizer tokenizer = new KeywordTokenizer(); return new TokenStreamComponents(tokenizer, new SudachiSurfaceFormFilterFactory(Collections.emptyMap()).create(tokenizer)); } }; checkOneTerm(analyzer, "", ""); analyzer.close(); } |
### Question:
NoteResource { @GET @Transactional public Note get() { try { return manager.createQuery("select n from Note n", Note.class).getSingleResult(); } catch (NoResultException e) { Note note = new Note(); note.setContent("Default message"); manager.persist(note); return note; } } @GET @Transactional Note get(); @POST @Transactional void put(Note newNote); }### Answer:
@Test public void shouldStoreNote() throws Exception { Note note = new Note(); note.setContent("Hello World!"); RestAssured.given().port(address.getPort()) .when().contentType(ContentType.JSON).body(note).post("/note") .then().statusCode(204); RestAssured.given().port(address.getPort()) .when().get("/note") .then().content(equalTo("{\"content\":\"Hello World!\"}")); } |
### Question:
DataTypesAction implements Action<GetDataTypes, DataTypes> { @Override public Class<GetDataTypes> getRequestType() { return GetDataTypes.class; } @Inject DataTypesAction(AuthServiceProviderRegistry registry, Monitor monitor); @Override Class<GetDataTypes> getRequestType(); @Override DataTypes handle(GetDataTypes request); }### Answer:
@Test public void testGetRequestType() { AuthServiceProviderRegistry registry = mock(AuthServiceProviderRegistry.class); DataTypesAction dataTypesAction = new DataTypesAction(registry, new Monitor() {}); Class<GetDataTypes> actual = dataTypesAction.getRequestType(); Assert.assertNotEquals(actual, null); Assert.assertEquals(actual, GetDataTypes.class); } |
### Question:
DataTypesAction implements Action<GetDataTypes, DataTypes> { @Override public DataTypes handle(GetDataTypes request) { Set<String> transferDataTypes = registry.getTransferDataTypes(); if (transferDataTypes.isEmpty()) { monitor.severe( () -> "No transfer data types were registered in " + AuthServiceProviderRegistry.class.getName()); } return new DataTypes(transferDataTypes); } @Inject DataTypesAction(AuthServiceProviderRegistry registry, Monitor monitor); @Override Class<GetDataTypes> getRequestType(); @Override DataTypes handle(GetDataTypes request); }### Answer:
@Test public void testHandle() { AuthServiceProviderRegistry registry = mock(AuthServiceProviderRegistry.class); Set<String> dataTypes = new HashSet<>(Arrays.asList("CONTACTS", "PHOTOS")); when(registry.getTransferDataTypes()).thenReturn(dataTypes); DataTypesAction dataTypesAction = new DataTypesAction(registry, new Monitor() {}); GetDataTypes request = mock(GetDataTypes.class); DataTypes actual = dataTypesAction.handle(request); Assert.assertEquals(actual.getDataTypes(), dataTypes); } |
### Question:
GoogleMailImporter implements Importer<TokensAndUrlAuthData, MailContainerResource> { @Override public ImportResult importItem( UUID id, IdempotentImportExecutor idempotentExecutor, TokensAndUrlAuthData authData, MailContainerResource data) throws Exception { Supplier<Map<String, String>> allDestinationLabels = allDestinationLabelsSupplier(authData); importLabels(authData, idempotentExecutor, allDestinationLabels, data.getFolders()); importDTPLabel(authData, idempotentExecutor, allDestinationLabels); importLabelsForMessages( authData, idempotentExecutor, allDestinationLabels, data.getMessages()); importMessages(authData, idempotentExecutor, data.getMessages()); return ImportResult.OK; } GoogleMailImporter(GoogleCredentialFactory credentialFactory, Monitor monitor); @VisibleForTesting GoogleMailImporter(
GoogleCredentialFactory credentialFactory, Gmail gmail, Monitor monitor); @Override ImportResult importItem(
UUID id,
IdempotentImportExecutor idempotentExecutor,
TokensAndUrlAuthData authData,
MailContainerResource data); }### Answer:
@Test public void importMessage() throws Exception { MailContainerResource resource = new MailContainerResource(null, Collections.singletonList(MESSAGE_MODEL)); ImportResult result = googleMailImporter.importItem(JOB_ID, executor, null, resource); verify(labelsList, atLeastOnce()).execute(); ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class); verify(messages).insert(eq(GoogleMailImporter.USER), messageArgumentCaptor.capture()); assertThat(messageArgumentCaptor.getValue().getRaw()).isEqualTo(MESSAGE_RAW); } |
### Question:
FacebookVideosExporter implements Exporter<TokensAndUrlAuthData, VideosContainerResource> { @Override public ExportResult<VideosContainerResource> export( UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation) throws CopyExceptionWithFailureReason { Preconditions.checkNotNull(authData); return exportVideos( authData, exportInformation.map(e -> (StringPaginationToken) e.getPaginationData())); } FacebookVideosExporter(AppCredentials appCredentials, Monitor monitor); @VisibleForTesting FacebookVideosExporter(
AppCredentials appCredentials, FacebookVideosInterface videosInterface, Monitor monitor); @Override ExportResult<VideosContainerResource> export(
UUID jobId, TokensAndUrlAuthData authData, Optional<ExportInformation> exportInformation); }### Answer:
@Test public void testExportVideo() throws CopyExceptionWithFailureReason { ExportResult<VideosContainerResource> result = facebookVideosExporter.export( uuid, new TokensAndUrlAuthData("accessToken", null, null), Optional.of(new ExportInformation(null, null))); assertEquals(ExportResult.ResultType.END, result.getType()); VideosContainerResource exportedData = result.getExportedData(); assertEquals(1, exportedData.getVideos().size()); assertEquals( new VideoObject( VIDEO_ID + ".mp4", VIDEO_SOURCE, VIDEO_NAME, "video/mp4", VIDEO_ID, null, false), exportedData.getVideos().toArray()[0]); } |
### Question:
FacebookVideosImporter implements Importer<TokensAndUrlAuthData, VideosContainerResource> { void importSingleVideo(FacebookClient client, VideoObject video) { ArrayList<Parameter> params = new ArrayList<>(); params.add(Parameter.with("file_url", video.getContentUrl().toString())); if (video.getDescription() != null) params.add(Parameter.with("description", video.getDescription())); String endpoint = "me/videos"; client.publish(endpoint, GraphResponse.class, params.toArray(new Parameter[0])); } FacebookVideosImporter(AppCredentials appCredentials); @Override ImportResult importItem(
UUID jobId,
IdempotentImportExecutor executor,
TokensAndUrlAuthData authData,
VideosContainerResource data); }### Answer:
@Test public void testImportSingleVideo() { importer.importSingleVideo( client, new VideoObject( "title", VIDEO_URL, VIDEO_DESCRIPTION, "video/mp4", "videoId", null, false)); Parameter[] params = { Parameter.with("file_url", VIDEO_URL), Parameter.with("description", VIDEO_DESCRIPTION) }; verify(client).publish("me/videos", GraphResponse.class, params); } |
### Question:
KoofrClient { public String ensureRootFolder() throws IOException, InvalidTokenException { if (!rootEnsured) { ensureFolder("/", ROOT_NAME); rootEnsured = true; } return "/" + ROOT_NAME; } KoofrClient(
String baseUrl,
OkHttpClient client,
OkHttpClient fileUploadClient,
ObjectMapper objectMapper,
Monitor monitor,
KoofrCredentialFactory credentialFactory); boolean fileExists(String path); void ensureFolder(String parentPath, String name); void addDescription(String path, String description); @SuppressWarnings("unchecked") String uploadFile(
String parentPath,
String name,
InputStream inputStream,
String mediaType,
Date modified,
String description); String ensureRootFolder(); String ensureVideosFolder(); Credential getOrCreateCredential(TokensAndUrlAuthData authData); static String trimDescription(String description); }### Answer:
@Test public void testEnsureRootFolder() throws Exception { server.enqueue(new MockResponse().setResponseCode(200)); client.ensureRootFolder(); Assert.assertEquals(1, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals("/api/v2/mounts/primary/files/folder?path=%2F", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals("{\"name\":\"Data transfer\"}", recordedRequest.getBody().readUtf8()); client.ensureRootFolder(); Assert.assertEquals(1, server.getRequestCount()); } |
### Question:
KoofrClient { public String ensureVideosFolder() throws IOException, InvalidTokenException { String rootFolder = ensureRootFolder(); if (!videosEnsured) { ensureFolder(rootFolder, VIDEOS_NAME); videosEnsured = true; } return rootFolder + "/" + VIDEOS_NAME; } KoofrClient(
String baseUrl,
OkHttpClient client,
OkHttpClient fileUploadClient,
ObjectMapper objectMapper,
Monitor monitor,
KoofrCredentialFactory credentialFactory); boolean fileExists(String path); void ensureFolder(String parentPath, String name); void addDescription(String path, String description); @SuppressWarnings("unchecked") String uploadFile(
String parentPath,
String name,
InputStream inputStream,
String mediaType,
Date modified,
String description); String ensureRootFolder(); String ensureVideosFolder(); Credential getOrCreateCredential(TokensAndUrlAuthData authData); static String trimDescription(String description); }### Answer:
@Test public void testEnsureVideosFolder() throws Exception { server.enqueue(new MockResponse().setResponseCode(200)); client.ensureRootFolder(); Assert.assertEquals(1, server.getRequestCount()); server.takeRequest(); server.enqueue(new MockResponse().setResponseCode(200)); client.ensureVideosFolder(); Assert.assertEquals(2, server.getRequestCount()); final RecordedRequest recordedRequest = server.takeRequest(); Assert.assertEquals("POST", recordedRequest.getMethod()); Assert.assertEquals( "/api/v2/mounts/primary/files/folder?path=%2FData+transfer", recordedRequest.getPath()); Assert.assertEquals("Bearer acc", recordedRequest.getHeader("Authorization")); Assert.assertEquals("2.1", recordedRequest.getHeader("X-Koofr-Version")); Assert.assertEquals( "application/json; charset=utf-8", recordedRequest.getHeader("Content-Type")); Assert.assertEquals("{\"name\":\"Videos\"}", recordedRequest.getBody().readUtf8()); client.ensureVideosFolder(); Assert.assertEquals(2, server.getRequestCount()); } |
### Question:
KoofrTransmogrificationConfig extends TransmogrificationConfig { public static String getAlbumName(String name) { if (name.equals("")) { return ALBUM_NAME_DEFAULT; } if (name.equals(".") || name.equals("..")) { return ALBUM_NAME_DEFAULT + " " + name; } return name; } @Override String getPhotoTitleForbiddenCharacters(); @Override String getAlbumNameForbiddenCharacters(); static String getAlbumName(String name); }### Answer:
@Test public void testGetAlbumName() { KoofrTransmogrificationConfig config = new KoofrTransmogrificationConfig(); Assert.assertEquals("Valid name", config.getAlbumName("Valid name")); Assert.assertEquals("Album", config.getAlbumName("")); Assert.assertEquals("Album .", config.getAlbumName(".")); Assert.assertEquals("Album ..", config.getAlbumName("..")); } |
### Question:
ToCalendarAttendeeModelTransformer implements BiFunction<Map<String, Object>, TransformerContext, CalendarAttendeeModel> { @Override @SuppressWarnings("unchecked") public CalendarAttendeeModel apply(Map<String, Object> attendee, TransformerContext context) { if (attendee == null) { return null; } boolean optional = !attendee.getOrDefault("type", "false").equals("required"); Map<String, ?> emailAddress = (Map<String, ?>) attendee.get("emailAddress"); String displayName = TransformerHelper.getString("name", emailAddress).orElse(""); String email = TransformerHelper.getString("address", emailAddress).orElse(""); return new CalendarAttendeeModel(displayName, email, optional); } @Override @SuppressWarnings("unchecked") CalendarAttendeeModel apply(Map<String, Object> attendee, TransformerContext context); }### Answer:
@Test public void testTransform() { Map<String, Object> attendeeMap = new HashMap<>(); attendeeMap.put("type", "required"); Map<String, String> addressMap = new HashMap<>(); addressMap.put("name", "Test Test1"); addressMap.put("address", "foo@foo.com"); attendeeMap.put("emailAddress", addressMap); CalendarAttendeeModel attendee = transformer.apply(attendeeMap, new TestTransformerContext()); Assert.assertFalse(attendee.getOptional()); Assert.assertEquals("Test Test1", attendee.getDisplayName()); Assert.assertEquals("foo@foo.com", attendee.getEmail()); } |
### Question:
ToCalendarModelTransformer implements BiFunction<Map<String, Object>, TransformerContext, CalendarModel> { @Override public CalendarModel apply(Map<String, Object> calendar, TransformerContext context) { String id = (String) calendar.get("id"); if (id == null) { context.problem("Calendar id not found"); return null; } String name = (String) calendar.get("name"); if (name == null) { context.problem("Calendar name not found"); return null; } return new CalendarModel( id, name, name); } @Override CalendarModel apply(Map<String, Object> calendar, TransformerContext context); }### Answer:
@Test @SuppressWarnings("unchecked") public void testTransform() throws IOException { Map<String, Object> rawEvent = mapper.readValue(SAMPLE_CALENDAR, Map.class); CalendarModel calendar = transformer.apply(rawEvent, context); Assert.assertEquals("123", calendar.getId()); Assert.assertEquals("Calendar", calendar.getName()); Assert.assertEquals("Calendar", calendar.getDescription()); } |
### Question:
ToCalendarEventTimeTransformer implements BiFunction<
Map<String, String>, TransformerContext, CalendarEventModel.CalendarEventTime> { @Override public CalendarEventModel.CalendarEventTime apply( Map<String, String> time, TransformerContext context) { if (time == null) { return null; } String dateTimeValue = time.get("dateTime"); String timeZone = time.get("timeZone"); if (dateTimeValue == null || timeZone == null) { return null; } try { OffsetDateTime dateTime = ZonedDateTime.of(LocalDateTime.parse(dateTimeValue), ZoneId.of(timeZone)) .toOffsetDateTime(); return new CalendarEventModel.CalendarEventTime(dateTime, false); } catch (DateTimeException e) { context.problem(e.getMessage()); return null; } } @Override CalendarEventModel.CalendarEventTime apply(
Map<String, String> time, TransformerContext context); }### Answer:
@Test public void testTransform() { Map<String, String> map = new HashMap<>(); map.put("dateTime", "2018-02-14T18:00:00.0000000"); map.put("timeZone", "UTC"); CalendarEventModel.CalendarEventTime time = transformer.apply(map, new TestTransformerContext()); Assert.assertEquals(18, time.getDateTime().getHour()); Assert.assertEquals(2018, time.getDateTime().getYear()); Assert.assertEquals(14, time.getDateTime().getDayOfMonth()); } |
### Question:
DataChunk { public static List<DataChunk> splitData(InputStream inputStream) throws IOException { ArrayList<DataChunk> chunksToSend = new ArrayList(); byte[] data = new byte[CHUNK_SIZE]; int totalFileSize = 0; int quantityToSend; int roomLeft = CHUNK_SIZE; int offset = 0; int chunksRead = 0; while ((quantityToSend = inputStream.read(data, offset, roomLeft)) != -1) { offset += quantityToSend; roomLeft -= quantityToSend; if (roomLeft == 0) { chunksToSend.add(new DataChunk(data, CHUNK_SIZE, chunksRead * CHUNK_SIZE)); chunksRead++; roomLeft = CHUNK_SIZE; offset = 0; totalFileSize += CHUNK_SIZE; data = new byte[CHUNK_SIZE]; } } if (offset != 0) { chunksToSend.add(new DataChunk(data, offset, chunksRead * CHUNK_SIZE)); totalFileSize += offset; chunksRead++; } return chunksToSend; } DataChunk(byte[] data, int size, int rangeStart); int getSize(); byte[] getData(); int getStart(); int getEnd(); static List<DataChunk> splitData(InputStream inputStream); }### Answer:
@Test public void testSplitDataEmpty() throws IOException { inputStream = new ByteArrayInputStream(new byte[0]); List<DataChunk> l = DataChunk.splitData(inputStream); assertThat(l).hasSize(0); } |
### Question:
FlickrPhotosExporter implements Exporter<AuthData, PhotosContainerResource> { @VisibleForTesting static PhotoModel toCommonPhoto(Photo p, String albumId) { Preconditions.checkArgument( !Strings.isNullOrEmpty(p.getOriginalSize().getSource()), "Photo [" + p.getId() + "] has a null authUrl"); return new PhotoModel( p.getTitle(), p.getOriginalSize().getSource(), p.getDescription(), toMimeType(p.getOriginalFormat()), p.getId(), albumId, false); } FlickrPhotosExporter(AppCredentials appCredentials, TransferServiceConfig serviceConfig); @VisibleForTesting FlickrPhotosExporter(Flickr flickr, TransferServiceConfig serviceConfig); @Override ExportResult<PhotosContainerResource> export(
UUID jobId, AuthData authData, Optional<ExportInformation> exportInformation); }### Answer:
@Test public void toCommonPhoto() { Photo photo = FlickrTestUtils.initializePhoto(PHOTO_TITLE, FETCHABLE_URL, PHOTO_DESCRIPTION, MEDIA_TYPE); PhotoModel photoModel = FlickrPhotosExporter.toCommonPhoto(photo, ALBUM_ID); assertThat(photoModel.getAlbumId()).isEqualTo(ALBUM_ID); assertThat(photoModel.getFetchableUrl()).isEqualTo(FETCHABLE_URL); assertThat(photoModel.getTitle()).isEqualTo(PHOTO_TITLE); assertThat(photoModel.getDescription()).isEqualTo(PHOTO_DESCRIPTION); assertThat(photoModel.getMediaType()).isEqualTo("image/jpeg"); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.