method2testcases
stringlengths
118
3.08k
### Question: PathUtil { public static String getRelativePath(Path sourceRootPath, Path childPath) { String childPathString = childPath.toUri().getPath(); String sourceRootPathString = sourceRootPath.toUri().getPath(); return "/".equals(sourceRootPathString) ? childPathString : childPathString.substring(sourceRootPathString.length()); } private PathUtil(); static String getRelativePath(Path sourceRootPath, Path childPath); static String toString(Path path); static String toBucketName(URI uri); static String toBucketKey(URI uri); static boolean isFile(URI path); }### Answer: @Test public void getRelativePathRoot() { Path root = new Path("/"); Path child = new Path("/a"); assertThat(PathUtil.getRelativePath(root, child), is("/a")); } @Test public void relativePath() { Path root = new Path("/tmp/abc"); Path child = new Path("/tmp/abc/xyz/file"); assertThat(PathUtil.getRelativePath(root, child), is("/xyz/file")); }
### Question: PathUtil { public static String toString(Path path) { return path == null ? null : path.toUri().toString(); } private PathUtil(); static String getRelativePath(Path sourceRootPath, Path childPath); static String toString(Path path); static String toBucketName(URI uri); static String toBucketKey(URI uri); static boolean isFile(URI path); }### Answer: @Test public void nullPathToString() { assertThat(PathUtil.toString(null), is(nullValue())); } @Test public void pathToString() { assertThat(PathUtil.toString(new Path("/foo/bar/")), is("/foo/bar")); assertThat(PathUtil.toString(new Path("s3: }
### Question: PathUtil { public static String toBucketName(URI uri) { String authority = uri.getAuthority(); if (authority == null) { throw new IllegalArgumentException("URI " + uri + " has no authority part"); } return authority; } private PathUtil(); static String getRelativePath(Path sourceRootPath, Path childPath); static String toString(Path path); static String toBucketName(URI uri); static String toBucketKey(URI uri); static boolean isFile(URI path); }### Answer: @Test(expected = NullPointerException.class) public void nullUriToBucketName() { PathUtil.toBucketName(null); } @Test(expected = IllegalArgumentException.class) public void protocolOnlyUriToBucketName() { PathUtil.toBucketName(URI.create("s3: } @Test(expected = IllegalArgumentException.class) public void uriWithNoAuthorityToBucketName() { PathUtil.toBucketName(URI.create("/foo/bar")); } @Test public void uriToBucketName() { assertThat(PathUtil.toBucketName(URI.create("s3: } @Test(expected = IllegalArgumentException.class) public void protocolOnlyUriToBucketKey() { PathUtil.toBucketName(URI.create("s3: }
### Question: PathUtil { public static String toBucketKey(URI uri) { String key = uri.getPath().substring(1); if (key.isEmpty()) { throw new IllegalArgumentException("URI " + uri + " has no path part"); } return key; } private PathUtil(); static String getRelativePath(Path sourceRootPath, Path childPath); static String toString(Path path); static String toBucketName(URI uri); static String toBucketKey(URI uri); static boolean isFile(URI path); }### Answer: @Test(expected = NullPointerException.class) public void nullUriToBucketKey() { PathUtil.toBucketKey(null); } @Test public void uriWithNoAuthorityToBucketKey() { assertThat(PathUtil.toBucketKey(URI.create("/foo/bar")), is("foo/bar")); } @Test public void uriToBucketKey() { assertThat(PathUtil.toBucketKey(URI.create("s3: } @Test(expected = IllegalArgumentException.class) public void uriWithNoPathToBucketKey() { PathUtil.toBucketKey(URI.create("s3: }
### Question: PathUtil { public static boolean isFile(URI path) { return !path.toString().endsWith("/"); } private PathUtil(); static String getRelativePath(Path sourceRootPath, Path childPath); static String toString(Path path); static String toBucketName(URI uri); static String toBucketKey(URI uri); static boolean isFile(URI path); }### Answer: @Test public void isFile() { assertThat(PathUtil.isFile(URI.create("s3: assertThat(PathUtil.isFile(URI.create("s3: } @Test public void isDirectory() { assertThat(PathUtil.isFile(URI.create("s3: }
### Question: BytesFormatter { public static String getStringDescriptionFor(long nBytes) { char[] units = { 'B', 'K', 'M', 'G', 'T', 'P' }; double current = nBytes; double prev = current; int index = 0; while ((current = current / 1024) >= 1) { prev = current; ++index; } assert index < units.length : "Too large a number."; return getFormatter().format(prev) + units[index]; } private BytesFormatter(); static DecimalFormat getFormatter(); static String getStringDescriptionFor(long nBytes); }### Answer: @Test public void bytes() { assertThat(BytesFormatter.getStringDescriptionFor(100L), is("100.0B")); } @Test public void kilobytes() { assertThat(BytesFormatter.getStringDescriptionFor(1024L), is("1.0K")); assertThat(BytesFormatter.getStringDescriptionFor(2256L), is("2.2K")); } @Test public void megabytes() { assertThat(BytesFormatter.getStringDescriptionFor(1024L * 1024L), is("1.0M")); assertThat(BytesFormatter.getStringDescriptionFor((2024L * 1024L) + (256L * 1024L)), is("2.2M")); } @Test public void gigabytes() { assertThat(BytesFormatter.getStringDescriptionFor(1024L * 1024L * 1024L), is("1.0G")); } @Test public void terabytes() { assertThat(BytesFormatter.getStringDescriptionFor(1024L * 1024L * 1024L * 1024L), is("1.0T")); } @Test public void petabytes() { assertThat(BytesFormatter.getStringDescriptionFor(1024L * 1024L * 1024L * 1024L * 1024L), is("1.0P")); }
### Question: ThrottledInputStream extends InputStream { @Override public int read() throws IOException { throttle(); int data = rawStream.read(); if (data != -1) { bytesRead++; } return data; } ThrottledInputStream(InputStream rawStream); ThrottledInputStream(InputStream rawStream, long maxBytesPerSec); @Override void close(); @Override int read(); @Override int read(byte[] b); @Override int read(byte[] b, int off, int len); int read(long position, byte[] buffer, int offset, int length); long getTotalBytesRead(); long getBytesPerSec(); long getTotalSleepTime(); @Override String toString(); }### Answer: @Test public void read() { File tmpFile; File outFile; try { tmpFile = createFile(1024); outFile = createFile(); tmpFile.deleteOnExit(); outFile.deleteOnExit(); long maxBandwidth = copyAndAssert(tmpFile, outFile, 0, 1, -1, CB.BUFFER); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.BUFFER); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.BUFF_OFFSET); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.ONE_C); } catch (IOException e) { LOG.error("Exception encountered ", e); } } @Test public void testRead() { File tmpFile; File outFile; try { tmpFile = createFile(1024); outFile = createFile(); tmpFile.deleteOnExit(); outFile.deleteOnExit(); long maxBandwidth = copyAndAssert(tmpFile, outFile, 0, 1, -1, CB.BUFFER); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.BUFFER); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.BUFF_OFFSET); copyAndAssert(tmpFile, outFile, maxBandwidth, 20, 0, CB.ONE_C); } catch (IOException e) { LOG.error("Exception encountered ", e); } }
### Question: RetriableCommand { public T execute(Object... arguments) throws Exception { Exception latestException; int counter = 0; while (true) { try { return doExecute(arguments); } catch (Exception exception) { LOG.error("Failure in Retriable command: {}", description, exception); latestException = exception; } counter++; RetryAction action = retryPolicy.shouldRetry(latestException, counter, 0, true); if (action.action == RetryPolicy.RetryAction.RetryDecision.RETRY) { ThreadUtil.sleepAtLeastIgnoreInterrupts(action.delayMillis); } else { break; } } throw new IOException("Couldn't run retriable-command: " + description, latestException); } RetriableCommand(String description); RetriableCommand(String description, RetryPolicy retryPolicy); T execute(Object... arguments); RetriableCommand<T> setRetryPolicy(RetryPolicy retryPolicy); }### Answer: @Test public void typical() { try { new MyRetriableCommand(5).execute(0); Assert.assertTrue(false); } catch (Exception e) { Assert.assertTrue(true); } try { new MyRetriableCommand(3).execute(0); Assert.assertTrue(true); } catch (Exception e) { Assert.assertTrue(false); } try { new MyRetriableCommand(5, RetryPolicies.retryUpToMaximumCountWithFixedSleep(5, 0, TimeUnit.MILLISECONDS)) .execute(0); Assert.assertTrue(true); } catch (Exception e) { Assert.assertTrue(false); } }
### Question: RegionValidator implements IParameterValidator { @Override public void validate(String name, String value) throws ParameterException { try { Region.fromValue(value); } catch (IllegalArgumentException e) { throw new ParameterException("Parameter " + name + " is not a valid AWS region (found " + value + ")", e); } } @Override void validate(String name, String value); }### Answer: @Test public void typical() { validator.validate("region", "us-west-2"); } @Test public void nullValue() { validator.validate("region", null); } @Test(expected = ParameterException.class) public void caseSensitive() { validator.validate("region", "US-WEST-2"); } @Test(expected = ParameterException.class) public void invalid() { validator.validate("region", "DEFAULT_REGION"); }
### Question: PositiveNonZeroLong implements IParameterValidator { @Override public void validate(String name, String value) throws ParameterException { long n = Long.parseLong(value); if (n <= 0) { throw new ParameterException("Parameter " + name + " should be greater than zero (found " + value + ")"); } } @Override void validate(String name, String value); }### Answer: @Test public void typical() { validator.validate("var", "123"); } @Test(expected = ParameterException.class) public void zero() { validator.validate("var", "0"); } @Test(expected = ParameterException.class) public void negative() { validator.validate("var", "-1"); } @Test(expected = NumberFormatException.class) public void invalidFormat() { validator.validate("var", "abc"); }
### Question: PositiveNonZeroInteger implements IParameterValidator { @Override public void validate(String name, String value) throws ParameterException { int n = Integer.parseInt(value); if (n <= 0) { throw new ParameterException("Parameter " + name + " should be greater than zero (found " + value + ")"); } } @Override void validate(String name, String value); }### Answer: @Test public void typical() { validator.validate("var", "123"); } @Test(expected = ParameterException.class) public void zero() { validator.validate("var", "0"); } @Test(expected = ParameterException.class) public void negative() { validator.validate("var", "-1"); } @Test(expected = NumberFormatException.class) public void invalidFormat() { validator.validate("var", "abc"); }
### Question: StorageClassValidator implements IParameterValidator { @Override public void validate(String name, String value) throws ParameterException { try { AwsUtil.toStorageClass(value); } catch (IllegalArgumentException e) { throw new ParameterException("Parameter " + name + " is not a valid AWS S3 storage class (found " + value + ")", e); } } @Override void validate(String name, String value); }### Answer: @Test public void typical() { validator.validate("storageClass", "standard"); validator.validate("storageClass", "STANDARD"); validator.validate("storageClass", "STaNDaRD"); } @Test public void nullValue() { validator.validate("storageClass", null); } @Test(expected = ParameterException.class) public void invalid() { validator.validate("storageClass", "REDUCEDREDUNDANCY"); }
### Question: PositiveLong implements IParameterValidator { @Override public void validate(String name, String value) throws ParameterException { long n = Long.parseLong(value); if (n < 0) { throw new ParameterException("Parameter " + name + " should be positive (found " + value + ")"); } } @Override void validate(String name, String value); }### Answer: @Test public void typical() { validator.validate("var", "123"); } @Test public void zero() { validator.validate("var", "0"); } @Test(expected = ParameterException.class) public void negative() { validator.validate("var", "-1"); } @Test(expected = NumberFormatException.class) public void invalidFormat() { validator.validate("var", "abc"); }
### Question: S3S3CopierOptions { public Long getMultipartCopyThreshold() { return MapUtils.getLong(copierOptions, Keys.MULTIPART_COPY_THRESHOLD.keyName(), null); } S3S3CopierOptions(); S3S3CopierOptions(Map<String, Object> copierOptions); void setMaxThreadPoolSize(int maxThreadPoolSize); int getMaxThreadPoolSize(); Long getMultipartCopyThreshold(); Long getMultipartCopyPartSize(); URI getS3Endpoint(); URI getS3Endpoint(String region); Boolean isS3ServerSideEncryption(); CannedAccessControlList getCannedAcl(); String getAssumedRole(); int getAssumedRoleCredentialDuration(); int getMaxCopyAttempts(); }### Answer: @Test public void getMultipartCopyThreshold() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.MULTIPART_COPY_THRESHOLD.keyName(), 128L); S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.getMultipartCopyThreshold(), is(128L)); } @Test public void getMultipartCopyThresholdDefaultIsNull() throws Exception { S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertNull(options.getMultipartCopyThreshold()); }
### Question: PathConverter implements IStringConverter<Path> { @Override public Path convert(String pathName) { return new Path(pathName); } @Override Path convert(String pathName); }### Answer: @Test public void typical() { assertThat(converter.convert("s3: } @Test(expected = IllegalArgumentException.class) public void invalid() { converter.convert("s3:"); }
### Question: CopyListing extends Configured { public static CopyListing getCopyListing( Configuration configuration, Credentials credentials, S3MapReduceCpOptions options) throws IOException { String copyListingClassName = configuration.get(S3MapReduceCpConstants.CONF_LABEL_COPY_LISTING_CLASS, ""); Class<? extends CopyListing> copyListingClass; try { if (!copyListingClassName.isEmpty()) { copyListingClass = configuration .getClass(S3MapReduceCpConstants.CONF_LABEL_COPY_LISTING_CLASS, SimpleCopyListing.class, CopyListing.class); } else { copyListingClass = SimpleCopyListing.class; } copyListingClassName = copyListingClass.getName(); Constructor<? extends CopyListing> constructor = copyListingClass .getDeclaredConstructor(Configuration.class, Credentials.class); return constructor.newInstance(configuration, credentials); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IOException("Unable to instantiate " + copyListingClassName, e); } } protected CopyListing(Configuration configuration, Credentials credentials); final void buildListing(Path pathToListFile, S3MapReduceCpOptions options); static CopyListing getCopyListing( Configuration configuration, Credentials credentials, S3MapReduceCpOptions options); }### Answer: @Test(timeout = 10000) public void defaultCopyListing() throws Exception { S3MapReduceCpOptions options = S3MapReduceCpOptions .builder(Arrays.asList(new Path("/tmp/in4")), new URI("/tmp/out4")) .build(); CopyListing listing = CopyListing.getCopyListing(CONFIG, CREDENTIALS, options); assertThat(listing, is(instanceOf(SimpleCopyListing.class))); }
### Question: ExponentialBackoffStrategy implements BackoffStrategy { @Override public long delayBeforeNextRetry( AmazonWebServiceRequest originalRequest, AmazonClientException exception, int retriesAttempted) { long backoffDelay = retriesAttempted * errorRetryDelay; LOG.debug("Exception caught during upload, retries attempted = {}, will retry in {} ms", retriesAttempted, backoffDelay, exception); return backoffDelay; } ExponentialBackoffStrategy(long errorRetryDelay); @Override long delayBeforeNextRetry( AmazonWebServiceRequest originalRequest, AmazonClientException exception, int retriesAttempted); }### Answer: @Test public void firstBackoff() { assertThat(strategy.delayBeforeNextRetry(originalRequest, exception, 1), is(1L * ERROR_RETRY_DELAY)); } @Test public void secondBackoff() { assertThat(strategy.delayBeforeNextRetry(originalRequest, exception, 2), is(2L * ERROR_RETRY_DELAY)); } @Test public void thirdBackoff() { assertThat(strategy.delayBeforeNextRetry(originalRequest, exception, 3), is(3L * ERROR_RETRY_DELAY)); }
### Question: S3MapreduceDataManipulatorFactory implements DataManipulatorFactory { @Override public boolean supportsSchemes(String sourceScheme, String replicaScheme) { return !S3Schemes.isS3Scheme(sourceScheme) && S3Schemes.isS3Scheme(replicaScheme); } @Autowired S3MapreduceDataManipulatorFactory(@Value("#{replicaHiveConf}") Configuration conf); @Override DataManipulator newInstance(Path path, Map<String, Object> copierOptions); @Override boolean supportsSchemes(String sourceScheme, String replicaScheme); }### Answer: @Test public void checkSupportsHdfsToS3() { sourceLocation = hdfsPath; replicaLocation = s3Path; sourceScheme = sourceLocation.toUri().getScheme(); replicaScheme = replicaLocation.toUri().getScheme(); assertTrue(dataManipulatorFactory.supportsSchemes(sourceScheme, replicaScheme)); } @Test public void checkDoesntSupportS3() { sourceLocation = s3Path; replicaLocation = s3Path; sourceScheme = sourceLocation.toUri().getScheme(); replicaScheme = replicaLocation.toUri().getScheme(); assertFalse(dataManipulatorFactory.supportsSchemes(sourceScheme, replicaScheme)); } @Test public void checkDoesntSupportHdfsToHdfs() { sourceLocation = hdfsPath; replicaLocation = hdfsPath; sourceScheme = sourceLocation.toUri().getScheme(); replicaScheme = replicaLocation.toUri().getScheme(); assertFalse(dataManipulatorFactory.supportsSchemes(sourceScheme, replicaScheme)); } @Test public void checkDoesntSupportRandomPaths() { sourceLocation = new Path("<path>"); replicaLocation = new Path("<path>"); sourceScheme = sourceLocation.toUri().getScheme(); replicaScheme = replicaLocation.toUri().getScheme(); assertFalse(dataManipulatorFactory.supportsSchemes(sourceScheme, replicaScheme)); }
### Question: CounterBasedRetryCondition implements RetryCondition { @Override public boolean shouldRetry( AmazonWebServiceRequest originalRequest, AmazonClientException exception, int retriesAttempted) { LOG.debug("Exception caught during upload, retries attempted = {} out of {}", retriesAttempted, maxErrorRetry, exception); return retriesAttempted <= maxErrorRetry; } CounterBasedRetryCondition(int maxErrorRetry); @Override boolean shouldRetry( AmazonWebServiceRequest originalRequest, AmazonClientException exception, int retriesAttempted); }### Answer: @Test public void doRetry() { assertThat(condition.shouldRetry(originalRequest, exception, MAX_ERROR_RETRY - 1), is(true)); } @Test public void doRetryWhenLimitIsReached() { assertThat(condition.shouldRetry(originalRequest, exception, MAX_ERROR_RETRY), is(true)); } @Test public void doNotRetry() { assertThat(condition.shouldRetry(originalRequest, exception, MAX_ERROR_RETRY + 1), is(false)); }
### Question: AwsUtil { public static StorageClass toStorageClass(String storageClass) { if (storageClass == null) { return null; } return StorageClass.fromValue(storageClass.toUpperCase(Locale.ROOT)); } private AwsUtil(); static StorageClass toStorageClass(String storageClass); }### Answer: @Test public void toStorageClass() { assertThat(AwsUtil.toStorageClass("REDUCED_REDUNDANCY"), is(StorageClass.ReducedRedundancy)); } @Test public void toNullStorageClass() { assertThat(AwsUtil.toStorageClass(null), is(nullValue())); } @Test public void toStorageClassCaseSensitiveness() { assertThat(AwsUtil.toStorageClass("glacier"), is(StorageClass.Glacier)); assertThat(AwsUtil.toStorageClass("gLaCiEr"), is(StorageClass.Glacier)); } @Test(expected = IllegalArgumentException.class) public void toInvalidStorageClass() { AwsUtil.toStorageClass("DEFAULT_STORAGE_CLASS"); }
### Question: SimpleCopyListing extends CopyListing { @Override protected long getNumberOfPaths() { return totalPaths; } protected SimpleCopyListing(Configuration configuration, Credentials credentials); @Override void doBuildListing(Path pathToListingFile, S3MapReduceCpOptions options); @VisibleForTesting void doBuildListing(SequenceFile.Writer fileListWriter, S3MapReduceCpOptions options); @VisibleForTesting void doBuildListing(SequenceFile.Writer fileListWriter, S3MapReduceCpOptions options, List<Path> globbedPaths); static final String CONF_LABEL_ROOT_PATH; }### Answer: @Test(timeout = 10000) public void skipFlagFiles() throws Exception { FileSystem fs = FileSystem.get(config); Path source = new Path(temporaryRoot + "/in4"); URI target = URI.create("s3: createFile(fs, new Path(source, "1/_SUCCESS")); createFile(fs, new Path(source, "1/file")); createFile(fs, new Path(source, "2")); Path listingPath = new Path(temporaryRoot + "/list4"); listing.buildListing(listingPath, options(source, target)); assertThat(listing.getNumberOfPaths(), is(2L)); Set<String> expectedRelativePaths = Sets.newHashSet("/1/file", "/2"); try (SequenceFile.Reader reader = new SequenceFile.Reader(config, SequenceFile.Reader.file(listingPath))) { CopyListingFileStatus fileStatus = new CopyListingFileStatus(); Text relativePath = new Text(); int relativePathCount = expectedRelativePaths.size(); for (int i = 0; i < relativePathCount; i++) { assertThat(reader.next(relativePath, fileStatus), is(true)); assertThat("Expected path not found " + relativePath.toString(), expectedRelativePaths.remove(relativePath.toString()), is(true)); } } assertThat("Expected relativePaths to be empty but was: " + expectedRelativePaths, expectedRelativePaths.isEmpty(), is(true)); }
### Question: SimpleCopyListing extends CopyListing { @Override public void doBuildListing(Path pathToListingFile, S3MapReduceCpOptions options) throws IOException { doBuildListing(getWriter(pathToListingFile), options); } protected SimpleCopyListing(Configuration configuration, Credentials credentials); @Override void doBuildListing(Path pathToListingFile, S3MapReduceCpOptions options); @VisibleForTesting void doBuildListing(SequenceFile.Writer fileListWriter, S3MapReduceCpOptions options); @VisibleForTesting void doBuildListing(SequenceFile.Writer fileListWriter, S3MapReduceCpOptions options, List<Path> globbedPaths); static final String CONF_LABEL_ROOT_PATH; }### Answer: @Test public void failOnCloseError() throws IOException { File inFile = File.createTempFile("TestCopyListingIn", null); inFile.deleteOnExit(); File outFile = File.createTempFile("TestCopyListingOut", null); outFile.deleteOnExit(); Path source = new Path(inFile.toURI()); Exception expectedEx = new IOException("boom"); SequenceFile.Writer writer = mock(SequenceFile.Writer.class); doThrow(expectedEx).when(writer).close(); Exception actualEx = null; try { listing.doBuildListing(writer, options(source, outFile.toURI())); } catch (Exception e) { actualEx = e; } Assert.assertNotNull("close writer didn't fail", actualEx); Assert.assertEquals(expectedEx, actualEx); }
### Question: HiveDifferences { @VisibleForTesting static TableAndMetadata sourceTableToTableAndMetadata(Table sourceTable) { return new TableAndMetadata(Warehouse.getQualifiedName(sourceTable), normaliseLocation(sourceTable.getSd().getLocation()), sourceTable); } private HiveDifferences( ComparatorRegistry comparatorRegistry, DiffListener diffListener, Table sourceTable, Iterator<Partition> sourcePartitionIterator, Optional<Table> replicaTable, Optional<? extends PartitionFetcher> replicaPartitionFetcher, Function<Path, String> checksumFunction, int partitionLimit); static Builder builder(DiffListener diffListener); void run(); }### Answer: @Test public void sourceTableToTableAndMetadata() { Table sourceTable = TestUtils.newTable("sourceDB", "sourceTable"); TableAndMetadata sourceTableAndMetadata = HiveDifferences.sourceTableToTableAndMetadata(sourceTable); assertThat(sourceTableAndMetadata.getSourceTable(), is("sourceDB.sourceTable")); assertThat(sourceTableAndMetadata.getSourceLocation(), is(sourceTable.getSd().getLocation())); assertThat(sourceTableAndMetadata.getTable(), is(sourceTable)); }
### Question: HiveDifferences { @VisibleForTesting static PartitionAndMetadata sourcePartitionToPartitionAndMetadata(Partition sourcePartition) { return new PartitionAndMetadata(sourcePartition.getDbName() + "." + sourcePartition.getTableName(), normaliseLocation(sourcePartition.getSd().getLocation()), sourcePartition); } private HiveDifferences( ComparatorRegistry comparatorRegistry, DiffListener diffListener, Table sourceTable, Iterator<Partition> sourcePartitionIterator, Optional<Table> replicaTable, Optional<? extends PartitionFetcher> replicaPartitionFetcher, Function<Path, String> checksumFunction, int partitionLimit); static Builder builder(DiffListener diffListener); void run(); }### Answer: @Test public void sourcePartitionToPartitionAndMetadata() { Partition sourcePartition = TestUtils.newPartition("sourceDB", "sourceTable", "val"); PartitionAndMetadata sourcePartitionAndMetadata = HiveDifferences .sourcePartitionToPartitionAndMetadata(sourcePartition); assertThat(sourcePartitionAndMetadata.getSourceTable(), is("sourceDB.sourceTable")); assertThat(sourcePartitionAndMetadata.getSourceLocation(), is(sourcePartition.getSd().getLocation())); assertThat(sourcePartitionAndMetadata.getPartition(), is(sourcePartition)); }
### Question: HiveDifferences { @VisibleForTesting static TableAndMetadata replicaTableToTableAndMetadata(Table replicaTable) { return new TableAndMetadata(replicaTable.getParameters().get(SOURCE_TABLE.parameterName()), normaliseLocation(replicaTable.getParameters().get(SOURCE_LOCATION.parameterName())), replicaTable); } private HiveDifferences( ComparatorRegistry comparatorRegistry, DiffListener diffListener, Table sourceTable, Iterator<Partition> sourcePartitionIterator, Optional<Table> replicaTable, Optional<? extends PartitionFetcher> replicaPartitionFetcher, Function<Path, String> checksumFunction, int partitionLimit); static Builder builder(DiffListener diffListener); void run(); }### Answer: @Test public void replicaTableToTableAndMetadata() { Table sourceTable = TestUtils.newTable("sourceDB", "sourceTable"); Table replicaTable = TestUtils.newTable("replicaDB", "replicaTable"); TestUtils.setCircusTrainSourceParameters(sourceTable, replicaTable); TableAndMetadata replicaTableAndMetadata = HiveDifferences.replicaTableToTableAndMetadata(replicaTable); assertThat(replicaTableAndMetadata.getSourceTable(), is("sourceDB.sourceTable")); assertThat(replicaTableAndMetadata.getSourceLocation(), is(sourceTable.getSd().getLocation())); assertThat(replicaTableAndMetadata.getTable(), is(replicaTable)); assertThat(replicaTableAndMetadata.getTable().getDbName(), is("replicaDB")); assertThat(replicaTableAndMetadata.getTable().getTableName(), is("replicaTable")); }
### Question: HiveDifferences { @VisibleForTesting static PartitionAndMetadata replicaPartitionToPartitionAndMetadata(Partition replicaPartition) { return new PartitionAndMetadata(replicaPartition.getParameters().get(SOURCE_TABLE.parameterName()), normaliseLocation(replicaPartition.getParameters().get(SOURCE_LOCATION.parameterName())), replicaPartition); } private HiveDifferences( ComparatorRegistry comparatorRegistry, DiffListener diffListener, Table sourceTable, Iterator<Partition> sourcePartitionIterator, Optional<Table> replicaTable, Optional<? extends PartitionFetcher> replicaPartitionFetcher, Function<Path, String> checksumFunction, int partitionLimit); static Builder builder(DiffListener diffListener); void run(); }### Answer: @Test public void replicaPartitionToPartitionAndMetadata() { Partition sourcePartition = TestUtils.newPartition("sourceDB", "sourceTable", "val"); Partition replicaPartition = TestUtils.newPartition("replicaDB", "replicaTable", "val"); TestUtils.setCircusTrainSourceParameters(sourcePartition, replicaPartition); PartitionAndMetadata replicaPartitionAndMetadata = HiveDifferences .replicaPartitionToPartitionAndMetadata(replicaPartition); assertThat(replicaPartitionAndMetadata.getSourceTable(), is("sourceDB.sourceTable")); assertThat(replicaPartitionAndMetadata.getSourceLocation(), is(sourcePartition.getSd().getLocation())); assertThat(replicaPartitionAndMetadata.getPartition(), is(replicaPartition)); assertThat(replicaPartitionAndMetadata.getPartition().getDbName(), is("replicaDB")); assertThat(replicaPartitionAndMetadata.getPartition().getTableName(), is("replicaTable")); }
### Question: HiveDifferences { public static Builder builder(DiffListener diffListener) { return new Builder(diffListener); } private HiveDifferences( ComparatorRegistry comparatorRegistry, DiffListener diffListener, Table sourceTable, Iterator<Partition> sourcePartitionIterator, Optional<Table> replicaTable, Optional<? extends PartitionFetcher> replicaPartitionFetcher, Function<Path, String> checksumFunction, int partitionLimit); static Builder builder(DiffListener diffListener); void run(); }### Answer: @Test(expected = IllegalStateException.class) public void requiredPartitionFetcher() { HiveDifferences .builder(diffListener) .comparatorRegistry(comparatorRegistry) .source(sourceConfiguration, sourceTable, sourcePartitionIterable) .replica(Optional.of(replicaTable), Optional.<PartitionFetcher> absent()) .checksumFunction(checksumFunction) .build(); }
### Question: PathDigest implements Function<PathMetadata, String> { @Override public String apply(PathMetadata pathDescriptor) { byte[] checksum = messageDigest.digest(serialize(pathDescriptor)); return Base64.encodeBase64String(checksum); } PathDigest(); PathDigest(String algorithm); @Override String apply(PathMetadata pathDescriptor); static byte[] serialize(PathMetadata pathDescriptor); static final String DEFAULT_MESSAGE_DIGEST_ALGORITHM; }### Answer: @Test public void typical() throws Exception { when(path.toUri()).thenReturn(new URI(FILE_LOCATION)); when(checksum.getAlgorithmName()).thenReturn(MD5); when(checksum.getLength()).thenReturn(1); when(checksum.getBytes()).thenReturn(new byte[] {}); PathMetadata pathDescriptor = new PathMetadata(path, LAST_MODIFIED, checksum, ImmutableList.<PathMetadata> of()); String base64Digest = function.apply(pathDescriptor); assertThat(base64Digest.matches(BASE_64_REGEX), is(true)); } @Test public void noChecksum() throws Exception { when(path.toUri()).thenReturn(new URI(FILE_LOCATION)); PathMetadata pathDescriptor = new PathMetadata(path, LAST_MODIFIED, checksum, ImmutableList.<PathMetadata> of()); String base64Digest = function.apply(pathDescriptor); assertThat(base64Digest.matches(BASE_64_REGEX), is(true)); }
### Question: ComparatorRegistry { public Comparator<?, ?> comparatorFor(Class<?> type) { return registry.get(type); } ComparatorRegistry(ComparatorType comparatorType); ComparatorType getComparatorType(); Comparator<?, ?> comparatorFor(Class<?> type); }### Answer: @Test public void typical() { Comparator<?, ?> objectComparator = comparatorRegistry.comparatorFor(FieldSchema.class); assertThat(objectComparator, is(instanceOf(FieldSchemaComparator.class))); Comparator<?, ?> integerComparator = comparatorRegistry.comparatorFor(PartitionAndMetadata.class); assertThat(integerComparator, is(instanceOf(PartitionAndMetadataComparator.class))); Comparator<?, ?> stringComparator = comparatorRegistry.comparatorFor(TableAndMetadata.class); assertThat(stringComparator, is(instanceOf(TableAndMetadataComparator.class))); assertThat(comparatorRegistry.comparatorFor(Table.class), is(nullValue())); assertThat(comparatorRegistry.comparatorFor(Partition.class), is(nullValue())); }
### Question: S3S3CopierFactory implements CopierFactory { @Override public boolean supportsSchemes(String sourceScheme, String replicaScheme) { return S3Schemes.isS3Scheme(sourceScheme) && S3Schemes.isS3Scheme(replicaScheme); } @Autowired S3S3CopierFactory( AmazonS3ClientFactory clientFactory, ListObjectsRequestFactory listObjectsRequestFactory, TransferManagerFactory transferManagerFactory, MetricRegistry runningMetricsRegistry); @Override boolean supportsSchemes(String sourceScheme, String replicaScheme); @Override Copier newInstance(CopierContext copierContext); @Override Copier newInstance( String eventId, Path sourceBaseLocation, Path replicaLocation, Map<String, Object> copierOptions); @Override Copier newInstance( String eventId, Path sourceBaseLocation, List<Path> sourceSubLocations, Path replicaLocation, Map<String, Object> copierOptions); }### Answer: @Test public void supportsSchemes() throws Exception { assertTrue(factory.supportsSchemes("s3", "s3")); assertTrue(factory.supportsSchemes("s3a", "s3a")); assertTrue(factory.supportsSchemes("s3n", "s3n")); assertTrue(factory.supportsSchemes("s3", "s3n")); } @Test public void unsupportedSchemes() throws Exception { assertFalse(factory.supportsSchemes("s3", "s345")); assertFalse(factory.supportsSchemes("s345", "s3")); assertFalse(factory.supportsSchemes("hdfs", "s3")); assertFalse(factory.supportsSchemes("s3", "hdfs")); assertFalse(factory.supportsSchemes(null, null)); assertFalse(factory.supportsSchemes("", "")); }
### Question: AbstractComparator implements Comparator<T, D> { protected boolean checkForInequality(Object left, Object right) { if (left == right) { return false; } if (left == null) { return true; } return !left.equals(right); } AbstractComparator(ComparatorRegistry comparatorRegistry, ComparatorType comparatorType); }### Answer: @Test public void checkForInequalityOfSameObject() { EqualObject object = new EqualObject(); assertThat(comparator.checkForInequality(object, object), is(false)); } @Test public void checkForInequalityLeftNull() { assertThat(comparator.checkForInequality(null, new EqualObject()), is(true)); } @Test public void checkForInequalityRightNull() { assertThat(comparator.checkForInequality(new EqualObject(), null), is(true)); } @Test public void checkForInequalityDifferentObject() { Object objectA = new Object(); Object objectB = new Object(); assertThat(comparator.checkForInequality(objectA, objectB), is(true)); } @Test public void checkForInequalityDifferentObjectEquals() { EqualObject objectA = new EqualObject(); EqualObject objectB = new EqualObject(); assertThat(comparator.checkForInequality(objectA, objectB), is(false)); }
### Question: PartitionSpecCreatingDiffListener implements DiffListener { @Override public void onNewPartition(String partitionName, Partition partition) { addPartition(partition); } PartitionSpecCreatingDiffListener(Configuration conf); @Override void onDiffStart(TableAndMetadata source, Optional<TableAndMetadata> replica); @Override void onChangedTable(List<Diff<Object, Object>> differences); @Override void onNewPartition(String partitionName, Partition partition); @Override void onChangedPartition(String partitionName, Partition partition, List<Diff<Object, Object>> differences); @Override void onDataChanged(String partitionName, Partition partition); @Override void onDiffEnd(); String getPartitionSpecFilter(); }### Answer: @Test public void onNewPartition() throws Exception { Partition partition1 = new Partition(Lists.newArrayList("val1", "val2"), DB, TABLE, 1, 1, null, null); Partition partition2 = new Partition(Lists.newArrayList("val11", "val22"), DB, TABLE, 1, 1, null, null); listener.onDiffStart(source, replica); listener.onNewPartition("p1", partition1); listener.onNewPartition("p2", partition2); assertThat(listener.getPartitionSpecFilter(), is("(p1='val1' AND p2=val2) OR (p1='val11' AND p2=val22)")); }
### Question: PartitionSpecCreatingDiffListener implements DiffListener { @Override public void onChangedPartition(String partitionName, Partition partition, List<Diff<Object, Object>> differences) { addPartition(partition); } PartitionSpecCreatingDiffListener(Configuration conf); @Override void onDiffStart(TableAndMetadata source, Optional<TableAndMetadata> replica); @Override void onChangedTable(List<Diff<Object, Object>> differences); @Override void onNewPartition(String partitionName, Partition partition); @Override void onChangedPartition(String partitionName, Partition partition, List<Diff<Object, Object>> differences); @Override void onDataChanged(String partitionName, Partition partition); @Override void onDiffEnd(); String getPartitionSpecFilter(); }### Answer: @Test public void onChangedPartition() throws Exception { Partition partition1 = new Partition(Lists.newArrayList("val1", "val2"), DB, TABLE, 1, 1, null, null); Partition partition2 = new Partition(Lists.newArrayList("val11", "val22"), DB, TABLE, 1, 1, null, null); listener.onDiffStart(source, replica); listener.onChangedPartition("p1", partition1, differences); listener.onChangedPartition("p2", partition2, differences); assertThat(listener.getPartitionSpecFilter(), is("(p1='val1' AND p2=val2) OR (p1='val11' AND p2=val22)")); }
### Question: PartitionSpecCreatingDiffListener implements DiffListener { @Override public void onDataChanged(String partitionName, Partition partition) { addPartition(partition); } PartitionSpecCreatingDiffListener(Configuration conf); @Override void onDiffStart(TableAndMetadata source, Optional<TableAndMetadata> replica); @Override void onChangedTable(List<Diff<Object, Object>> differences); @Override void onNewPartition(String partitionName, Partition partition); @Override void onChangedPartition(String partitionName, Partition partition, List<Diff<Object, Object>> differences); @Override void onDataChanged(String partitionName, Partition partition); @Override void onDiffEnd(); String getPartitionSpecFilter(); }### Answer: @Test public void onDataChanged() throws Exception { Partition partition1 = new Partition(Lists.newArrayList("val1", "val2"), DB, TABLE, 1, 1, null, null); Partition partition2 = new Partition(Lists.newArrayList("val11", "val22"), DB, TABLE, 1, 1, null, null); listener.onDiffStart(source, replica); listener.onDataChanged("p1", partition1); listener.onDataChanged("p2", partition2); assertThat(listener.getPartitionSpecFilter(), is("(p1='val1' AND p2=val2) OR (p1='val11' AND p2=val22)")); }
### Question: CircusTrainHelp { @Override public String toString() { Iterable<String> errorMessages = FluentIterable.from(errors).transform(OBJECT_ERROR_TO_TABBED_MESSAGE); StringBuilder help = new StringBuilder(500) .append("Usage: circus-train.sh --config=<config_file>[,<config_file>,...]") .append(System.lineSeparator()) .append("Errors found in the provided configuration file:") .append(System.lineSeparator()) .append(Joiner.on(System.lineSeparator()).join(errorMessages)) .append(System.lineSeparator()) .append("Configuration file help:") .append(System.lineSeparator()) .append(TAB) .append("For more information and help please refer to ") .append("https: return help.toString(); } CircusTrainHelp(List<ObjectError> errors); @Override String toString(); }### Answer: @Test public void typical() { String expectedHelpMessage = "Usage: circus-train.sh --config=<config_file>[,<config_file>,...]\n" + "Errors found in the provided configuration file:\n" + "\tError message 1\n" + "\tError message 2\n" + "Configuration file help:\n" + "\tFor more information and help please refer to https: List<ObjectError> errors = Arrays.asList(new ObjectError("object.1", "Error message 1"), new ObjectError("object.2", "Error message 2")); String help = new CircusTrainHelp(errors).toString(); assertThat(help, is(expectedHelpMessage)); }
### Question: PropertyExtensionPackageProvider implements ExtensionPackageProvider { @Override public Set<String> getPackageNames(ConfigurableEnvironment env) { @SuppressWarnings("unchecked") Set<String> packageNames = env.getProperty("extension-packages", Set.class); return packageNames == null ? Collections.<String>emptySet() : packageNames; } @Override Set<String> getPackageNames(ConfigurableEnvironment env); }### Answer: @Test public void noPackagesDeclared() { when(env.getProperty("extension-packages", Set.class)).thenReturn(ImmutableSet.of()); Set<String> packages = underTest.getPackageNames(env); assertThat(packages.size(), is(0)); } @Test public void twoPackagesDeclared() { when(env.getProperty("extension-packages", Set.class)).thenReturn(ImmutableSet.of("com.foo", "com.bar")); Set<String> packages = underTest.getPackageNames(env); assertThat(packages.size(), is(2)); Iterator<String> iterator = packages.iterator(); assertThat(iterator.next(), is("com.foo")); assertThat(iterator.next(), is("com.bar")); }
### Question: ExtensionInitializer implements ApplicationContextInitializer<AnnotationConfigApplicationContext> { @Override public void initialize(AnnotationConfigApplicationContext context) { Set<String> packageNames = provider.getPackageNames(context.getEnvironment()); if (packageNames.size() > 0) { LOG.info("Adding packageNames '{}' to component scan.", packageNames); context.scan(packageNames.toArray(new String[packageNames.size()])); } } ExtensionInitializer(); @VisibleForTesting ExtensionInitializer(ExtensionPackageProvider provider); @Override void initialize(AnnotationConfigApplicationContext context); }### Answer: @Test public void noPackage() { when(provider.getPackageNames(env)).thenReturn(Collections.<String> emptySet()); underTest.initialize(context); verify(context, never()).scan(any(String[].class)); } @Test public void singlePackages() { when(provider.getPackageNames(env)).thenReturn(Collections.singleton("com.foo.bar")); underTest.initialize(context); verify(context).scan(new String[] { "com.foo.bar" }); }
### Question: HiveEndpoint { public String getName() { return name; } @Autowired HiveEndpoint(String name, HiveConf hiveConf, Supplier<CloseableMetaStoreClient> metaStoreClientSupplier); String getName(); HiveConf getHiveConf(); String getMetaStoreUris(); Supplier<CloseableMetaStoreClient> getMetaStoreClientSupplier(); Database getDatabase(String database); Optional<Table> getTable(CloseableMetaStoreClient client, String database, String table); TableAndStatistics getTableAndStatistics(String database, String tableName); abstract TableAndStatistics getTableAndStatistics(TableReplication tableReplication); PartitionsAndStatistics getPartitions(Table table, String partitionPredicate, int maxPartitions); }### Answer: @Test public void getName() throws Exception { assertThat(hiveEndpoint.getName(), is(NAME)); }
### Question: HiveEndpoint { public HiveConf getHiveConf() { return hiveConf; } @Autowired HiveEndpoint(String name, HiveConf hiveConf, Supplier<CloseableMetaStoreClient> metaStoreClientSupplier); String getName(); HiveConf getHiveConf(); String getMetaStoreUris(); Supplier<CloseableMetaStoreClient> getMetaStoreClientSupplier(); Database getDatabase(String database); Optional<Table> getTable(CloseableMetaStoreClient client, String database, String table); TableAndStatistics getTableAndStatistics(String database, String tableName); abstract TableAndStatistics getTableAndStatistics(TableReplication tableReplication); PartitionsAndStatistics getPartitions(Table table, String partitionPredicate, int maxPartitions); }### Answer: @Test public void getHiveConf() throws Exception { assertThat(hiveEndpoint.getHiveConf(), is(hiveConf)); }
### Question: S3S3CopierFactory implements CopierFactory { @Override public Copier newInstance(CopierContext copierContext) { return new S3S3Copier(copierContext.getSourceBaseLocation(), copierContext.getSourceSubLocations(), copierContext.getReplicaLocation(), clientFactory, transferManagerFactory, listObjectsRequestFactory, runningMetricsRegistry, new S3S3CopierOptions(copierContext.getCopierOptions())); } @Autowired S3S3CopierFactory( AmazonS3ClientFactory clientFactory, ListObjectsRequestFactory listObjectsRequestFactory, TransferManagerFactory transferManagerFactory, MetricRegistry runningMetricsRegistry); @Override boolean supportsSchemes(String sourceScheme, String replicaScheme); @Override Copier newInstance(CopierContext copierContext); @Override Copier newInstance( String eventId, Path sourceBaseLocation, Path replicaLocation, Map<String, Object> copierOptions); @Override Copier newInstance( String eventId, Path sourceBaseLocation, List<Path> sourceSubLocations, Path replicaLocation, Map<String, Object> copierOptions); }### Answer: @Test public void newInstance() throws Exception { String eventId = "eventID"; Path sourceBaseLocation = new Path("source"); Path replicaLocation = new Path("replica"); Map<String, Object> copierOptions = new HashMap<>(); Copier copier = factory.newInstance(eventId, sourceBaseLocation, replicaLocation, copierOptions); assertNotNull(copier); } @Test public void newInstancePartitions() throws Exception { String eventId = "eventID"; Path sourceBaseLocation = new Path("source"); Path replicaLocation = new Path("replica"); Map<String, Object> copierOptions = new HashMap<>(); List<Path> subLocations = Lists.newArrayList(new Path(sourceBaseLocation, "sub")); Copier copier = factory.newInstance(eventId, sourceBaseLocation, subLocations, replicaLocation, copierOptions); assertNotNull(copier); }
### Question: HiveEndpoint { public Optional<Table> getTable(CloseableMetaStoreClient client, String database, String table) { Table oldReplicaTable = null; try { log.debug("Checking for existing table {}.{}", database, table); oldReplicaTable = client.getTable(database, table); log.debug("Existing table found."); } catch (NoSuchObjectException e) { log.debug("Table '{}.{}' not found.", database, table); } catch (TException e) { String message = String.format("Cannot fetch table metadata for '%s.%s'", database, table); log.error(message, e); throw new MetaStoreClientException(message, e); } return Optional.fromNullable(oldReplicaTable); } @Autowired HiveEndpoint(String name, HiveConf hiveConf, Supplier<CloseableMetaStoreClient> metaStoreClientSupplier); String getName(); HiveConf getHiveConf(); String getMetaStoreUris(); Supplier<CloseableMetaStoreClient> getMetaStoreClientSupplier(); Database getDatabase(String database); Optional<Table> getTable(CloseableMetaStoreClient client, String database, String table); TableAndStatistics getTableAndStatistics(String database, String tableName); abstract TableAndStatistics getTableAndStatistics(TableReplication tableReplication); PartitionsAndStatistics getPartitions(Table table, String partitionPredicate, int maxPartitions); }### Answer: @Test public void getTable() throws Exception { when(metaStoreClient.getTable(DATABASE, TABLE)).thenReturn(table); when(metaStoreClient.getTableColumnStatistics(DATABASE, TABLE, COLUMN_NAMES)).thenReturn(columnStatisticsObjs); TableAndStatistics sourceTable = hiveEndpoint.getTableAndStatistics(DATABASE, TABLE); assertThat(sourceTable.getTable(), is(table)); assertThat(sourceTable.getStatistics(), is(columnStatistics)); }
### Question: StrategyBasedReplicationFactory implements ReplicationFactory { @Override public Replication newInstance(TableReplication tableReplication) { if (tableReplication.getReplicationStrategy() == ReplicationStrategy.PROPAGATE_DELETES) { String eventId = eventIdFactory.newEventId(EventIdPrefix.CIRCUS_TRAIN_DESTRUCTIVE.getPrefix()); CleanupLocationManager cleanupLocationManager = CleanupLocationManagerFactory.newInstance(eventId, housekeepingListener, replicaCatalogListener, tableReplication); return new DestructiveReplication(upsertReplicationFactory, tableReplication, eventId, new DestructiveSource(sourceMetaStoreClientSupplier, tableReplication), new DestructiveReplica(replicaMetaStoreClientSupplier, cleanupLocationManager, tableReplication)); } return upsertReplicationFactory.newInstance(tableReplication); } StrategyBasedReplicationFactory( ReplicationFactoryImpl upsertReplicationFactory, Supplier<CloseableMetaStoreClient> sourceMetaStoreClientSupplier, Supplier<CloseableMetaStoreClient> replicaMetaStoreClientSupplier, HousekeepingListener housekeepingListener, ReplicaCatalogListener replicaCatalogListener); @Override Replication newInstance(TableReplication tableReplication); }### Answer: @Test public void newInstance() throws Exception { StrategyBasedReplicationFactory factory = new StrategyBasedReplicationFactory(upsertReplicationFactory, sourceMetaStoreClientSupplier, replicaMetaStoreClientSupplier, housekeepingListener, replicaCatalogListener); tableReplication.setReplicationStrategy(ReplicationStrategy.PROPAGATE_DELETES); Replication replication = factory.newInstance(tableReplication); assertThat(replication, instanceOf(DestructiveReplication.class)); } @Test public void newInstanceUpsert() throws Exception { StrategyBasedReplicationFactory factory = new StrategyBasedReplicationFactory(upsertReplicationFactory, sourceMetaStoreClientSupplier, replicaMetaStoreClientSupplier, housekeepingListener, replicaCatalogListener); tableReplication.setReplicationStrategy(ReplicationStrategy.UPSERT); factory.newInstance(tableReplication); verify(upsertReplicationFactory).newInstance(tableReplication); }
### Question: UnpartitionedTableMetadataMirrorReplication implements Replication { @Override public void replicate() throws CircusTrainException { try { replica.validateReplicaTable(replicaDatabaseName, replicaTableName); TableAndStatistics sourceTableAndStatistics = source.getTableAndStatistics(database, table); Table sourceTable = sourceTableAndStatistics.getTable(); SourceLocationManager sourceLocationManager = source.getLocationManager(sourceTable, eventId); ReplicaLocationManager replicaLocationManager = new MetadataMirrorReplicaLocationManager(sourceLocationManager, TableType.UNPARTITIONED); sourceLocationManager.cleanUpLocations(); replica .updateMetadata(eventId, sourceTableAndStatistics, replicaDatabaseName, replicaTableName, replicaLocationManager); LOG.info("Metadata mirrored for table {}.{} (no data copied).", database, table); } catch (Throwable t) { throw new CircusTrainException("Unable to replicate", t); } } UnpartitionedTableMetadataMirrorReplication( String database, String table, Source source, Replica replica, EventIdFactory eventIdFactory, String replicaDatabaseName, String replicaTableName); @Override void replicate(); @Override String name(); @Override String getEventId(); }### Answer: @Test public void typical() throws Exception { UnpartitionedTableMetadataMirrorReplication replication = new UnpartitionedTableMetadataMirrorReplication(DATABASE, TABLE, source, replica, eventIdFactory, DATABASE, TABLE); replication.replicate(); InOrder replicationOrder = inOrder(sourceLocationManager, replica); replicationOrder.verify(replica).validateReplicaTable(DATABASE, TABLE); replicationOrder.verify(sourceLocationManager).cleanUpLocations(); replicationOrder.verify(replica).updateMetadata(eq(EVENT_ID), eq(sourceTableAndStatistics), eq(DATABASE), eq(TABLE), any(ReplicaLocationManager.class)); }
### Question: SpelParsedPartitionPredicate implements PartitionPredicate { @Override public String getPartitionPredicate() { String partitionFilter = tableReplication.getSourceTable().getPartitionFilter(); String parsedPartitionFilter = expressionParser.parse(partitionFilter); if (!Objects.equals(partitionFilter, parsedPartitionFilter)) { LOG.info("Parsed partitionFilter: " + parsedPartitionFilter); } return parsedPartitionFilter; } SpelParsedPartitionPredicate(SpringExpressionParser expressionParser, TableReplication tableReplication); @Override String getPartitionPredicate(); @Override short getPartitionPredicateLimit(); }### Answer: @Test public void simpleFilter() throws Exception { when(sourceTable.getPartitionFilter()).thenReturn("filter"); when(expressionParser.parse("filter")).thenReturn("filter"); assertThat(predicate.getPartitionPredicate(), is("filter")); } @Test public void expressionParserChangedFilter() throws Exception { when(expressionParser.parse("filter")).thenReturn("filter2"); when(sourceTable.getPartitionFilter()).thenReturn("filter"); assertThat(predicate.getPartitionPredicate(), is("filter2")); }
### Question: SpelParsedPartitionPredicate implements PartitionPredicate { @Override public short getPartitionPredicateLimit() { Short partitionLimit = tableReplication.getSourceTable().getPartitionLimit(); return partitionLimit == null ? -1 : partitionLimit; } SpelParsedPartitionPredicate(SpringExpressionParser expressionParser, TableReplication tableReplication); @Override String getPartitionPredicate(); @Override short getPartitionPredicateLimit(); }### Answer: @Test public void partitionPredicateLimit() throws Exception { when(sourceTable.getPartitionLimit()).thenReturn((short) 10); assertThat(predicate.getPartitionPredicateLimit(), is((short) 10)); } @Test public void noPartitionPredicateLimitSetDefaultsToMinus1() throws Exception { when(sourceTable.getPartitionLimit()).thenReturn(null); assertThat(predicate.getPartitionPredicateLimit(), is((short) -1)); }
### Question: CompositePartitionTransformation implements PartitionTransformation { @Override public Partition transform(Partition partition) { Partition transformedPartition = partition; for (PartitionTransformation partitionTransformation : partitionTransformations) { transformedPartition = partitionTransformation.transform(transformedPartition); } return transformedPartition; } CompositePartitionTransformation(List<PartitionTransformation> partitionTransformations); @Override Partition transform(Partition partition); }### Answer: @Test public void transform() throws Exception { transformations.add(transformationOne); transformations.add(transformationTwo); partitionTransformations = new CompositePartitionTransformation(transformations); partitionTransformations.transform(null); verify(transformationOne).transform(null); verify(transformationTwo).transform(null); }
### Question: CompositeTableTransformation implements TableTransformation { @Override public Table transform(Table table) { Table transformedTable = table; for (TableTransformation tableTransformation : tableTransformations) { transformedTable = tableTransformation.transform(transformedTable); } return transformedTable; } CompositeTableTransformation(List<TableTransformation> tableTransformations); @Override Table transform(Table table); }### Answer: @Test public void transform() throws Exception { transformations.add(transformationOne); transformations.add(transformationTwo); tableTransformations = new CompositeTableTransformation(transformations); tableTransformations.transform(null); verify(transformationOne).transform(null); verify(transformationTwo).transform(null); }
### Question: DestructiveReplication implements Replication { @Override public String name() { return "destructive-" + tableReplication.getQualifiedReplicaName(); } DestructiveReplication( ReplicationFactoryImpl upsertReplicationFactory, TableReplication tableReplication, String eventId, DestructiveSource destructiveSource, DestructiveReplica destructiveReplica); @Override void replicate(); @Override String name(); @Override String getEventId(); }### Answer: @Test public void name() throws Exception { DestructiveReplication replication = new DestructiveReplication(upsertReplicationFactory, tableReplication, EVENT_ID, destructiveSource, destructiveReplica); assertThat(replication.name(), is("destructive-db.table2")); }
### Question: DestructiveReplication implements Replication { @Override public String getEventId() { return eventId; } DestructiveReplication( ReplicationFactoryImpl upsertReplicationFactory, TableReplication tableReplication, String eventId, DestructiveSource destructiveSource, DestructiveReplica destructiveReplica); @Override void replicate(); @Override String name(); @Override String getEventId(); }### Answer: @Test public void getEventId() throws Exception { DestructiveReplication replication = new DestructiveReplication(upsertReplicationFactory, tableReplication, EVENT_ID, destructiveSource, destructiveReplica); assertThat(replication.getEventId(), is(EVENT_ID)); }
### Question: TransferManagerFactory { public TransferManager newInstance(AmazonS3 targetS3Client, S3S3CopierOptions s3s3CopierOptions) { LOG .debug("Initializing transfer manager with {} threads.", s3s3CopierOptions.getMaxThreadPoolSize()); return TransferManagerBuilder.standard() .withMultipartCopyThreshold(s3s3CopierOptions.getMultipartCopyThreshold()) .withMultipartCopyPartSize(s3s3CopierOptions.getMultipartCopyPartSize()) .withExecutorFactory(() -> Executors.newFixedThreadPool(s3s3CopierOptions.getMaxThreadPoolSize())) .withS3Client(targetS3Client) .build(); } TransferManager newInstance(AmazonS3 targetS3Client, S3S3CopierOptions s3s3CopierOptions); }### Answer: @Test public void shouldCreateDefaultTransferManagerClient() { S3S3CopierOptions s3Options = new S3S3CopierOptions(new HashMap<String, Object>() {{ put(S3S3CopierOptions.Keys.MULTIPART_COPY_THRESHOLD.keyName(), MULTIPART_COPY_THRESHOLD_VALUE); put(S3S3CopierOptions.Keys.MULTIPART_COPY_PART_SIZE.keyName(), MULTIPART_COPY_PART_SIZE); }}); TransferManagerFactory factory = new TransferManagerFactory(); TransferManager transferManager = factory.newInstance(mockClient, s3Options); assertThat(transferManager.getAmazonS3Client(), is(mockClient)); TransferManagerConfiguration managerConfig = transferManager.getConfiguration(); assertThat(managerConfig.getMultipartCopyPartSize(), is(MULTIPART_COPY_PART_SIZE)); assertThat(managerConfig.getMultipartCopyThreshold(), is(MULTIPART_COPY_THRESHOLD_VALUE)); }
### Question: PartitionPredicateFactory { public PartitionPredicate newInstance(TableReplication tableReplication) { if (tableReplication.getSourceTable().isGeneratePartitionFilter()) { return new DiffGeneratedPartitionPredicate(sourceFactory.newInstance(tableReplication), replicaFactory.newInstance(tableReplication), tableReplication, checksumFunction); } else { return new SpelParsedPartitionPredicate(expressionParser, tableReplication); } } PartitionPredicateFactory( HiveEndpointFactory<? extends HiveEndpoint> sourceFactory, HiveEndpointFactory<? extends HiveEndpoint> replicaFactory, SpringExpressionParser expressionParser, Function<Path, String> checksumFunction); PartitionPredicate newInstance(TableReplication tableReplication); }### Answer: @Test public void newInstanceSpelParsedPartitionPredicate() throws Exception { when(sourceTable.isGeneratePartitionFilter()).thenReturn(false); PartitionPredicate predicate = partitionPredicateFactory.newInstance(tableReplication); assertThat(predicate, instanceOf(SpelParsedPartitionPredicate.class)); } @Test public void newInstanceDiffGeneratedPartitionPredicate() throws Exception { when(sourceTable.isGeneratePartitionFilter()).thenReturn(true); when(sourceFactory.newInstance(tableReplication)).thenReturn(source); when(replicaFactory.newInstance(tableReplication)).thenReturn(replica); PartitionPredicate predicate = partitionPredicateFactory.newInstance(tableReplication); assertThat(predicate, instanceOf(DiffGeneratedPartitionPredicate.class)); }
### Question: ExpressionParserFunctions { private static DateTime nowInZone(DateTimeZone zone) { return DateTime.now(zone); } private ExpressionParserFunctions(); static DateTime nowInZone(String zone); static DateTime nowUtc(); static DateTime nowEuropeLondon(); static DateTime nowAmericaLosAngeles(); static String zeroPadLeft(int value, int width); static String zeroPadLeft(String value, int width); }### Answer: @Test public void nowInZone() { DateTime now = ExpressionParserFunctions.nowInZone("UTC"); assertThat(now.getZone(), is(DateTimeZone.UTC)); }
### Question: ExpressionParserFunctions { public static DateTime nowUtc() { return nowInZone(DateTimeZone.UTC); } private ExpressionParserFunctions(); static DateTime nowInZone(String zone); static DateTime nowUtc(); static DateTime nowEuropeLondon(); static DateTime nowAmericaLosAngeles(); static String zeroPadLeft(int value, int width); static String zeroPadLeft(String value, int width); }### Answer: @Test public void nowUtc() { DateTime now = ExpressionParserFunctions.nowUtc(); assertThat(now.getZone(), is(DateTimeZone.UTC)); }
### Question: ExpressionParserFunctions { public static DateTime nowEuropeLondon() { return nowInZone("Europe/London"); } private ExpressionParserFunctions(); static DateTime nowInZone(String zone); static DateTime nowUtc(); static DateTime nowEuropeLondon(); static DateTime nowAmericaLosAngeles(); static String zeroPadLeft(int value, int width); static String zeroPadLeft(String value, int width); }### Answer: @Test public void nowEuropeLondon() { DateTime now = ExpressionParserFunctions.nowEuropeLondon(); assertThat(now.getZone(), is(DateTimeZone.forID("Europe/London"))); }
### Question: ExpressionParserFunctions { public static DateTime nowAmericaLosAngeles() { return nowInZone("America/Los_Angeles"); } private ExpressionParserFunctions(); static DateTime nowInZone(String zone); static DateTime nowUtc(); static DateTime nowEuropeLondon(); static DateTime nowAmericaLosAngeles(); static String zeroPadLeft(int value, int width); static String zeroPadLeft(String value, int width); }### Answer: @Test public void nowAmericaLosAngeles() { DateTime now = ExpressionParserFunctions.nowAmericaLosAngeles(); assertThat(now.getZone(), is(DateTimeZone.forID("America/Los_Angeles"))); }
### Question: HousekeepingRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) { Instant deletionCutoff = new Instant().minus(housekeeping.getExpiredPathDuration()); LOG.info("Housekeeping at instant {} has started", deletionCutoff); CompletionCode completionCode = CompletionCode.SUCCESS; try { housekeepingService.cleanUp(deletionCutoff); LOG.info("Housekeeping at instant {} has finished", deletionCutoff); } catch (Exception e) { completionCode = CompletionCode.FAILURE; LOG.error("Housekeeping at instant {} has failed", deletionCutoff, e); throw e; } finally { Map<String, Long> metricsMap = ImmutableMap .<String, Long>builder() .put("housekeeping", completionCode.getCode()) .build(); metricSender.send(metricsMap); } } @Autowired HousekeepingRunner(Housekeeping housekeeping, HousekeepingService housekeepingService, MetricSender metricSender); @Override void run(ApplicationArguments args); }### Answer: @Test public void typical() throws Exception { ArgumentCaptor<Instant> instantCaptor = ArgumentCaptor.forClass(Instant.class); runner.run(null); verify(cleanUpPathService).cleanUp(instantCaptor.capture()); Instant twoDaysAgo = new Instant().minus(TWO_DAYS_DURATION.getMillis()); assertThat(instantCaptor.getValue().getMillis(), is(lessThanOrEqualTo(twoDaysAgo.getMillis()))); } @Test(expected = IllegalStateException.class) public void rethrowException() throws Exception { doThrow(new IllegalStateException()).when(cleanUpPathService).cleanUp(any(Instant.class)); runner.run(null); }
### Question: ExpressionParserFunctions { public static String zeroPadLeft(int value, int width) { return zeroPadLeft(Integer.toString(value), width); } private ExpressionParserFunctions(); static DateTime nowInZone(String zone); static DateTime nowUtc(); static DateTime nowEuropeLondon(); static DateTime nowAmericaLosAngeles(); static String zeroPadLeft(int value, int width); static String zeroPadLeft(String value, int width); }### Answer: @Test public void zeroPadLeftString() { assertThat(ExpressionParserFunctions.zeroPadLeft("A", 3), is("00A")); assertThat(ExpressionParserFunctions.zeroPadLeft("AAA", 3), is("AAA")); assertThat(ExpressionParserFunctions.zeroPadLeft("", 1), is("0")); } @Test public void zeroPadLeftInt() { assertThat(ExpressionParserFunctions.zeroPadLeft(1, 3), is("001")); assertThat(ExpressionParserFunctions.zeroPadLeft(111, 3), is("111")); }
### Question: SpringExpressionParser { public String parse(String expressionString) { if (expressionString != null) { Expression expression = parser.parseExpression(expressionString, templateContext); expressionString = expression.getValue(evalContext).toString(); } return expressionString; } SpringExpressionParser(); SpringExpressionParser(Class<?>... functionHolders); String parse(String expressionString); }### Answer: @Test public void literal() { assertThat(parser.parse("local_hour > 0"), is("local_hour > 0")); } @Test public void empty() { assertThat(parser.parse(""), is("")); } @Test public void blank() { assertThat(parser.parse(" "), is(" ")); } @Test public void nullValue() { assertThat(parser.parse(null), is((Object) null)); } @Test public void literalWithNowFunction() { assertThat(parser.parse("local_date > #{ #now().minusDays(30).toString('yyyy-MM-dd')}"), is("local_date > 2016-02-23")); } @Test public void spaceBeforeRootContextReference() { assertThat(parser.parse("local_date >= '#{ #nowUtc().minusDays(2).toString(\"yyyy-MM-dd\") }'"), is("local_date >= '2016-03-22'")); }
### Question: HousekeepingCleanupLocationManager implements CleanupLocationManager { @Override public void scheduleLocations() throws CircusTrainException { try { List<URI> uris = new ArrayList<>(); for (CleanupLocation location : locations) { LOG.info("Scheduling old replica data for deletion for event {}: {}", eventId, location.path.toUri()); housekeepingListener .cleanUpLocation(eventId, location.pathEventId, location.path, location.replicaDatabase, location.replicaTable); uris.add(location.path.toUri()); } replicaCatalogListener.deprecatedReplicaLocations(uris); } finally { locations.clear(); } } HousekeepingCleanupLocationManager( String eventId, HousekeepingListener housekeepingListener, ReplicaCatalogListener replicaCatalogListener, String replicaDatabase, String replicaTable); @Override void scheduleLocations(); @Override void addCleanupLocation(String pathEventId, Path location); }### Answer: @Test public void scheduleLocations() throws Exception { HousekeepingCleanupLocationManager manager = new HousekeepingCleanupLocationManager(EVENT_ID, housekeepingListener, replicaCatalogListener, DATABASE, TABLE); String pathEventId = "pathEventId"; Path path = new Path("location1"); manager.addCleanupLocation(pathEventId, path); manager.scheduleLocations(); verify(housekeepingListener).cleanUpLocation(EVENT_ID, pathEventId, path, DATABASE, TABLE); List<URI> uris = Lists.newArrayList(path.toUri()); verify(replicaCatalogListener).deprecatedReplicaLocations(uris); }
### Question: ReplicaTableFactoryProvider { public ReplicaTableFactory newInstance(TableReplication tableReplication) { if (tableReplication.getSourceTable().isGeneratePartitionFilter()) { return new AddCheckSumReplicaTableFactory(sourceHiveConf, checksumFunction, tableTransformation, partitionTransformation, columnStatisticsTransformation); } return new ReplicaTableFactory(sourceHiveConf, tableTransformation, partitionTransformation, columnStatisticsTransformation); } @Autowired ReplicaTableFactoryProvider( @Value("#{sourceHiveConf}") HiveConf sourceHiveConf, @Value("#{checksumFunction}") Function<Path, String> checksumFunction, TableTransformation tableTransformation, PartitionTransformation partitionTransformation, ColumnStatisticsTransformation columnStatisticsTransformation); ReplicaTableFactory newInstance(TableReplication tableReplication); }### Answer: @Test public void newInstanceReturnsReplicaTableFactory() throws Exception { when(sourceTable.isGeneratePartitionFilter()).thenReturn(false); ReplicaTableFactory factory = picker.newInstance(tableReplication); assertThat(factory, instanceOf(ReplicaTableFactory.class)); assertThat(factory, not(instanceOf(AddCheckSumReplicaTableFactory.class))); } @Test public void newInstanceReturnsAddChecksumReplicaTableFactory() throws Exception { when(sourceTable.isGeneratePartitionFilter()).thenReturn(true); ReplicaTableFactory factory = picker.newInstance(tableReplication); assertThat(factory, instanceOf(AddCheckSumReplicaTableFactory.class)); }
### Question: AddCheckSumReplicaTableFactory extends ReplicaTableFactory { @Override Partition newReplicaPartition( String eventId, Table sourceTable, Partition sourcePartition, String replicaDatabaseName, String replicaTableName, Path replicaPartitionLocation, ReplicationMode replicationMode) { Partition replica = super.newReplicaPartition(eventId, sourceTable, sourcePartition, replicaDatabaseName, replicaTableName, replicaPartitionLocation, replicationMode); String checksum = checksumFunction.apply(locationAsPath(sourcePartition)); replica.putToParameters(PARTITION_CHECKSUM.parameterName(), checksum); return replica; } AddCheckSumReplicaTableFactory( HiveConf sourceHiveConf, Function<Path, String> checksumFunction, TableTransformation tableTransformation, PartitionTransformation partitionTransformation, ColumnStatisticsTransformation columnStatisticsTransformation); }### Answer: @Test public void newReplicaPartition() throws Exception { Path sourceTableLocationPath = new Path(sourcePartitionFile.toURI().toString()); when(checksumFunction.apply(sourceTableLocationPath)).thenReturn("checksum"); Partition partition = factory.newReplicaPartition("eventId", sourceTable, sourcePartition, "replicaDatabase", "replicaTable", replicaPartitionLocation, FULL); assertThat(partition.getParameters().get(PARTITION_CHECKSUM.parameterName()), is("checksum")); }
### Question: MetadataMirrorReplicaLocationManager implements ReplicaLocationManager { @Override public Path getTableLocation() throws CircusTrainException { return sourceLocationManager.getTableLocation(); } MetadataMirrorReplicaLocationManager(SourceLocationManager sourceLocationManager, TableType tableType); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer: @Test public void unpartitionedTableLocation() throws Exception { when(sourceLocationManager.getTableLocation()).thenReturn(TABLE_LOCATION); MetadataMirrorReplicaLocationManager replicaLocationManager = new MetadataMirrorReplicaLocationManager( sourceLocationManager, TableType.UNPARTITIONED); assertThat(replicaLocationManager.getTableLocation(), is(TABLE_LOCATION)); } @Test public void unpartitionedTableEmptyLocation() throws Exception { when(sourceLocationManager.getTableLocation()).thenReturn(null); MetadataMirrorReplicaLocationManager replicaLocationManager = new MetadataMirrorReplicaLocationManager( sourceLocationManager, TableType.UNPARTITIONED); assertThat(replicaLocationManager.getTableLocation(), is(nullValue())); }
### Question: MetadataMirrorReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionBaseLocation() throws CircusTrainException { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } return getTableLocation(); } MetadataMirrorReplicaLocationManager(SourceLocationManager sourceLocationManager, TableType tableType); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer: @Test(expected = UnsupportedOperationException.class) public void unpartitionedTableLocationThrowsExceptionOnPartitionBaseTableLocation() throws Exception { MetadataMirrorReplicaLocationManager replicaLocationManager = new MetadataMirrorReplicaLocationManager( sourceLocationManager, TableType.UNPARTITIONED); replicaLocationManager.getPartitionBaseLocation(); }
### Question: MetadataMirrorReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionLocation(Partition sourcePartition) { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } if (!LocationUtils.hasLocation(sourcePartition)) { return null; } return new Path(sourcePartition.getSd().getLocation()); } MetadataMirrorReplicaLocationManager(SourceLocationManager sourceLocationManager, TableType tableType); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer: @Test(expected = UnsupportedOperationException.class) public void unpartitionedTableLocationThrowsExceptionOnPartitionLocation() throws Exception { MetadataMirrorReplicaLocationManager replicaLocationManager = new MetadataMirrorReplicaLocationManager( sourceLocationManager, TableType.UNPARTITIONED); replicaLocationManager.getPartitionLocation(sourcePartition); }
### Question: S3S3CopierOptions { public Long getMultipartCopyPartSize() { return MapUtils.getLong(copierOptions, Keys.MULTIPART_COPY_PART_SIZE.keyName(), null); } S3S3CopierOptions(); S3S3CopierOptions(Map<String, Object> copierOptions); void setMaxThreadPoolSize(int maxThreadPoolSize); int getMaxThreadPoolSize(); Long getMultipartCopyThreshold(); Long getMultipartCopyPartSize(); URI getS3Endpoint(); URI getS3Endpoint(String region); Boolean isS3ServerSideEncryption(); CannedAccessControlList getCannedAcl(); String getAssumedRole(); int getAssumedRoleCredentialDuration(); int getMaxCopyAttempts(); }### Answer: @Test public void getMultipartCopyPartSize() throws Exception { copierOptions.put(S3S3CopierOptions.Keys.MULTIPART_COPY_PART_SIZE.keyName(), 128L); S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertThat(options.getMultipartCopyPartSize(), is(128L)); } @Test public void getMultipartCopyPartSizeDefaultIsNull() throws Exception { S3S3CopierOptions options = new S3S3CopierOptions(copierOptions); assertNull(options.getMultipartCopyPartSize()); }
### Question: HiveObjectUtils { public static Table updateSerDeUrl(Table table, String parameter, String url) { updateSerDeUrl(table.getParameters(), table.getSd().getSerdeInfo().getParameters(), parameter, url); return table; } private HiveObjectUtils(); static String getParameter(Table table, String parameter); static String getParameter(Partition partition, String parameter); static Table updateSerDeUrl(Table table, String parameter, String url); static Partition updateSerDeUrl(Partition partition, String parameter, String url); }### Answer: @Test public void updateUrlInTable() { Table table = newTable(); table.getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); table.getSd().getSerdeInfo().getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); HiveObjectUtils.updateSerDeUrl(table, AVRO_SCHEMA_URL_PARAMETER, "updatedUrl"); assertThat(table.getParameters().get(AVRO_SCHEMA_URL_PARAMETER), is("updatedUrl")); assertThat(table.getSd().getSerdeInfo().getParameters().get(AVRO_SCHEMA_URL_PARAMETER), is(nullValue())); } @Test public void updateUrlInPartition() { Partition partition = newPartition(); partition.getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); partition.getSd().getSerdeInfo().getParameters().put(AVRO_SCHEMA_URL_PARAMETER, "test"); HiveObjectUtils.updateSerDeUrl(partition, AVRO_SCHEMA_URL_PARAMETER, "updatedUrl"); assertThat(partition.getParameters().get(AVRO_SCHEMA_URL_PARAMETER), is("updatedUrl")); assertThat(partition.getSd().getSerdeInfo().getParameters().get(AVRO_SCHEMA_URL_PARAMETER), is(nullValue())); }
### Question: FullReplicationReplicaLocationManager implements ReplicaLocationManager { @Override public Path getTableLocation() { Path replicaDataLocation = new Path(tablePath); if (tableType == UNPARTITIONED) { replicaDataLocation = new Path(replicaDataLocation, eventId); } LOG.debug("Generated table data destination path: {}", replicaDataLocation.toUri()); replicaCatalogListener.resolvedReplicaLocation(replicaDataLocation.toUri()); return replicaDataLocation; } FullReplicationReplicaLocationManager( SourceLocationManager sourceLocationManager, String tablePath, String eventId, TableType tableType, CleanupLocationManager cleanupLocationManager, ReplicaCatalogListener replicaCatalogListener); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override void cleanUpLocations(); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer: @Test public void getTableOnUnpartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, UNPARTITIONED, cleanupLocationManager, replicaCatalogListener); Path path = manager.getTableLocation(); assertThat(path, is(new Path(TABLE_PATH, new Path(EVENT_ID)))); } @Test public void getTableOnPartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, PARTITIONED, cleanupLocationManager, replicaCatalogListener); Path path = manager.getTableLocation(); assertThat(path, is(new Path(TABLE_PATH))); }
### Question: FullReplicationReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionBaseLocation() { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } Path partitionBasePath = new Path(getTableLocation(), eventId); LOG.debug("Generated partition data destination base path: {}", partitionBasePath.toUri()); return partitionBasePath; } FullReplicationReplicaLocationManager( SourceLocationManager sourceLocationManager, String tablePath, String eventId, TableType tableType, CleanupLocationManager cleanupLocationManager, ReplicaCatalogListener replicaCatalogListener); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override void cleanUpLocations(); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer: @Test(expected = UnsupportedOperationException.class) public void getPartitionBaseOnUnpartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, UNPARTITIONED, cleanupLocationManager, replicaCatalogListener); manager.getPartitionBaseLocation(); } @Test public void getPartitionBaseOnPartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, PARTITIONED, cleanupLocationManager, replicaCatalogListener); Path path = manager.getPartitionBaseLocation(); assertThat(path, is(new Path(TABLE_PATH, new Path(EVENT_ID)))); }
### Question: FullReplicationReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionLocation(Partition sourcePartition) { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } Path partitionSubPath = sourceLocationManager.getPartitionSubPath(locationAsPath(sourcePartition)); Path replicaPartitionLocation = new Path(getPartitionBaseLocation(), partitionSubPath); return replicaPartitionLocation; } FullReplicationReplicaLocationManager( SourceLocationManager sourceLocationManager, String tablePath, String eventId, TableType tableType, CleanupLocationManager cleanupLocationManager, ReplicaCatalogListener replicaCatalogListener); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override void cleanUpLocations(); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer: @Test(expected = UnsupportedOperationException.class) public void getPartitionLocationOnUnpartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, UNPARTITIONED, cleanupLocationManager, replicaCatalogListener); manager.getPartitionLocation(sourcePartition); } @Test public void getPartitionLocationOnPartitionedTable() throws Exception { FullReplicationReplicaLocationManager manager = new FullReplicationReplicaLocationManager(sourceLocationManager, TABLE_PATH, EVENT_ID, PARTITIONED, cleanupLocationManager, replicaCatalogListener); when(sourcePartition.getSd()).thenReturn(sd); String partitionLocation = TABLE_PATH + "/" + EVENT_ID + "/partitionKey1=value"; when(sd.getLocation()).thenReturn(partitionLocation); when(sourceLocationManager.getPartitionSubPath(new Path(partitionLocation))) .thenReturn(new Path("partitionKey1=value")); Path path = manager.getPartitionLocation(sourcePartition); assertThat(path, is(new Path(partitionLocation))); }
### Question: MetadataUpdateReplicaLocationManager implements ReplicaLocationManager { @Override public Path getTableLocation() { return new Path(tablePath); } MetadataUpdateReplicaLocationManager( CloseableMetaStoreClient replicaMetastoreClient, TableType tableType, String tablePath, String replicaDatabaseName, String replicaTableName); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer: @Test public void unpartitionedTableLocation() throws Exception { MetadataUpdateReplicaLocationManager replicaLocationManager = new MetadataUpdateReplicaLocationManager(client, TableType.UNPARTITIONED, tableLocation, DATABASE, TABLE); assertThat(replicaLocationManager.getTableLocation(), is(tableLocationPath)); }
### Question: MetadataUpdateReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionBaseLocation() { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } return getTableLocation(); } MetadataUpdateReplicaLocationManager( CloseableMetaStoreClient replicaMetastoreClient, TableType tableType, String tablePath, String replicaDatabaseName, String replicaTableName); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer: @Test(expected = UnsupportedOperationException.class) public void unpartitionedTableLocationThrowsExceptionOnPartitionBaseTableLocation() throws Exception { MetadataUpdateReplicaLocationManager replicaLocationManager = new MetadataUpdateReplicaLocationManager(client, TableType.UNPARTITIONED, tableLocation, DATABASE, TABLE); replicaLocationManager.getPartitionBaseLocation(); }
### Question: MetadataUpdateReplicaLocationManager implements ReplicaLocationManager { @Override public Path getPartitionLocation(Partition sourcePartition) { if (tableType == UNPARTITIONED) { throw new UnsupportedOperationException("Not a partitioned table."); } try { Partition partition = replicaMetastoreClient.getPartition(replicaDatabaseName, replicaTableName, sourcePartition.getValues()); return new Path(partition.getSd().getLocation()); } catch (TException e) { throw new CircusTrainException("Partition should exist on replica but doesn't", e); } } MetadataUpdateReplicaLocationManager( CloseableMetaStoreClient replicaMetastoreClient, TableType tableType, String tablePath, String replicaDatabaseName, String replicaTableName); @Override Path getTableLocation(); @Override Path getPartitionBaseLocation(); @Override void cleanUpLocations(); @Override void addCleanUpLocation(String pathEventId, Path location); @Override Path getPartitionLocation(Partition sourcePartition); }### Answer: @Test(expected = UnsupportedOperationException.class) public void unpartitionedTableLocationThrowsExceptionOnPartitionLocation() throws Exception { MetadataUpdateReplicaLocationManager replicaLocationManager = new MetadataUpdateReplicaLocationManager(client, TableType.UNPARTITIONED, tableLocation, DATABASE, TABLE); replicaLocationManager.getPartitionLocation(sourcePartition); }
### Question: ReplicaFactory implements HiveEndpointFactory<Replica> { @Override public Replica newInstance(TableReplication tableReplication) { ReplicaTableFactory replicaTableFactory = replicaTableFactoryPicker.newInstance(tableReplication); DropTableService dropTableService = new DropTableService(); AlterTableService alterTableService = new AlterTableService(dropTableService, new CopyPartitionsOperation(), new RenameTableOperation(dropTableService)); return new Replica(replicaCatalog, replicaHiveConf, replicaMetaStoreClientSupplier, replicaTableFactory, housekeepingListener, replicaCatalogListener, tableReplication, alterTableService); } @Autowired ReplicaFactory( ReplicaCatalog replicaCatalog, @Value("#{replicaHiveConf}") HiveConf replicaHiveConf, Supplier<CloseableMetaStoreClient> replicaMetaStoreClientSupplier, HousekeepingListener housekeepingListener, ReplicaCatalogListener replicaCatalogListener, ReplicaTableFactoryProvider replicaTableFactoryProvider); @Override Replica newInstance(TableReplication tableReplication); }### Answer: @Test public void defaultReplicaTableFactory() throws Exception { Replica replica = replicaFactory.newInstance(tableReplication); assertNotNull(replica); verify(replicaTableFactoryPicker).newInstance(tableReplication); }
### Question: ViewLocationManager implements SourceLocationManager { @Override public Path getTableLocation() { return null; } @Override Path getTableLocation(); @Override void cleanUpLocations(); @Override List<Path> getPartitionLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer: @Test public void nullTableLocation() { assertThat(locationManager.getTableLocation(), is(nullValue())); }
### Question: ViewLocationManager implements SourceLocationManager { @Override public List<Path> getPartitionLocations() { return Collections.emptyList(); } @Override Path getTableLocation(); @Override void cleanUpLocations(); @Override List<Path> getPartitionLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer: @Test public void emptyPartitionLocations() { assertThat(locationManager.getPartitionLocations(), is(not(nullValue()))); }
### Question: ViewLocationManager implements SourceLocationManager { @Override public Path getPartitionSubPath(Path partitionLocation) { return null; } @Override Path getTableLocation(); @Override void cleanUpLocations(); @Override List<Path> getPartitionLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer: @Test public void nullPartitionSubPath() { assertThat(locationManager.getPartitionSubPath(new Path("whatever")), is(nullValue())); }
### Question: FilterMissingPartitionsLocationManager implements SourceLocationManager { @Override public List<Path> getPartitionLocations() throws CircusTrainException { List<Path> result = new ArrayList<>(); List<Path> paths = sourceLocationManager.getPartitionLocations(); FileSystem fileSystem = null; for (Path path : paths) { try { if (fileSystem == null) { fileSystem = path.getFileSystem(hiveConf); } if (fileSystem.exists(path)) { result.add(path); } else { LOG .warn("Source path '{}' does not exist skipping it for replication." + " WARNING: this means there is a partition in Hive that does not have a corresponding folder in" + " source file store, check your table and data.", path); } } catch (IOException e) { LOG.warn("Exception while checking path, skipping path '{}', error {}", path, e); } } return result; } FilterMissingPartitionsLocationManager(SourceLocationManager sourceLocationManager, HiveConf hiveConf); @Override Path getTableLocation(); @Override List<Path> getPartitionLocations(); @Override void cleanUpLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer: @Test public void getPartitionLocations() { List<Path> paths = Lists.newArrayList(path, missingPath); when(sourceLocationManager.getPartitionLocations()).thenReturn(paths); List<Path> filteredPaths = filterMissingPartitionsLocationManager.getPartitionLocations(); List<Path> expected = Lists.newArrayList(path); assertThat(filteredPaths, is(expected)); } @Test public void getPartitionLocationsExceptionThrowingPathIsSkipped() { List<Path> paths = Lists.newArrayList(path, exceptionThrowingPath); when(sourceLocationManager.getPartitionLocations()).thenReturn(paths); List<Path> filteredPaths = filterMissingPartitionsLocationManager.getPartitionLocations(); List<Path> expected = Lists.newArrayList(path); assertThat(filteredPaths, is(expected)); }
### Question: FilterMissingPartitionsLocationManager implements SourceLocationManager { @Override public Path getTableLocation() throws CircusTrainException { return sourceLocationManager.getTableLocation(); } FilterMissingPartitionsLocationManager(SourceLocationManager sourceLocationManager, HiveConf hiveConf); @Override Path getTableLocation(); @Override List<Path> getPartitionLocations(); @Override void cleanUpLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer: @Test public void getTableLocation() { filterMissingPartitionsLocationManager.getTableLocation(); verify(sourceLocationManager).getTableLocation(); }
### Question: FilterMissingPartitionsLocationManager implements SourceLocationManager { @Override public void cleanUpLocations() throws CircusTrainException { sourceLocationManager.cleanUpLocations(); } FilterMissingPartitionsLocationManager(SourceLocationManager sourceLocationManager, HiveConf hiveConf); @Override Path getTableLocation(); @Override List<Path> getPartitionLocations(); @Override void cleanUpLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer: @Test public void cleanUpLocations() { filterMissingPartitionsLocationManager.cleanUpLocations(); verify(sourceLocationManager).cleanUpLocations(); }
### Question: FilterMissingPartitionsLocationManager implements SourceLocationManager { @Override public Path getPartitionSubPath(Path partitionLocation) { return sourceLocationManager.getPartitionSubPath(partitionLocation); } FilterMissingPartitionsLocationManager(SourceLocationManager sourceLocationManager, HiveConf hiveConf); @Override Path getTableLocation(); @Override List<Path> getPartitionLocations(); @Override void cleanUpLocations(); @Override Path getPartitionSubPath(Path partitionLocation); }### Answer: @Test public void getPartitionSubPath() { Path partitionLocation = new Path("/tmp"); filterMissingPartitionsLocationManager.getPartitionSubPath(partitionLocation); verify(sourceLocationManager).getPartitionSubPath(partitionLocation); }
### Question: Source extends HiveEndpoint { @Override public TableAndStatistics getTableAndStatistics(String database, String table) { TableAndStatistics sourceTable = super.getTableAndStatistics(database, table); sourceCatalogListener.resolvedMetaStoreSourceTable(EventUtils.toEventTable(sourceTable.getTable())); return sourceTable; } Source( SourceCatalog sourceCatalog, HiveConf sourceHiveConf, Supplier<CloseableMetaStoreClient> sourceMetaStoreClientSupplier, SourceCatalogListener sourceCatalogListener, boolean snapshotsDisabled, String sourceTableLocation); @Override TableAndStatistics getTableAndStatistics(String database, String table); @Override PartitionsAndStatistics getPartitions(Table sourceTable, String partitionPredicate, int maxPartitions); SourceLocationManager getLocationManager(Table table, String eventId); SourceLocationManager getLocationManager( Table table, List<Partition> partitions, String eventId, Map<String, Object> copierOptions); @Override TableAndStatistics getTableAndStatistics(TableReplication tableReplication); }### Answer: @Test public void getTable() throws Exception { when(metaStoreClient.getTable(DATABASE, TABLE)).thenReturn(table); when(metaStoreClient.getTableColumnStatistics(DATABASE, TABLE, COLUMN_NAMES)).thenReturn(columnStatisticsObjs); TableAndStatistics sourceTable = source.getTableAndStatistics(DATABASE, TABLE); assertThat(sourceTable.getTable(), is(table)); assertThat(sourceTable.getStatistics(), is(columnStatistics)); } @Test public void getTableNoStats() throws Exception { when(metaStoreClient.getTable(DATABASE, TABLE)).thenReturn(table); when(metaStoreClient.getTableColumnStatistics(DATABASE, TABLE, COLUMN_NAMES)) .thenReturn(Collections.<ColumnStatisticsObj> emptyList()); TableAndStatistics sourceTable = source.getTableAndStatistics(DATABASE, TABLE); assertThat(sourceTable.getTable(), is(table)); assertThat(sourceTable.getStatistics(), is(nullValue())); }
### Question: DestructiveSource { public boolean tableExists() throws TException { try (CloseableMetaStoreClient client = sourceMetaStoreClientSupplier.get()) { return client.tableExists(databaseName, tableName); } } DestructiveSource( Supplier<CloseableMetaStoreClient> sourceMetaStoreClientSupplier, TableReplication tableReplication); boolean tableExists(); List<String> getPartitionNames(); }### Answer: @Test public void tableExists() throws Exception { when(client.tableExists(DATABASE, TABLE)).thenReturn(true); DestructiveSource source = new DestructiveSource(sourceMetaStoreClientSupplier, tableReplication); assertThat(source.tableExists(), is(true)); verify(client).close(); }
### Question: AvroStringUtils { public static String avroDestination(String pathToDestinationFolder, String eventId, String tableLocation) { checkArgument(isNotBlank(pathToDestinationFolder), "There must be a pathToDestinationFolder provided"); checkArgument(isNotBlank(eventId), "There must be a eventId provided"); pathToDestinationFolder = appendForwardSlashIfNotPresent(pathToDestinationFolder); eventId = appendForwardSlashIfNotPresent(eventId); if (tableLocation != null && pathToDestinationFolder.equals(appendForwardSlashIfNotPresent(tableLocation))) { return pathToDestinationFolder + eventId + ".schema"; } return pathToDestinationFolder + eventId; } private AvroStringUtils(); static String avroDestination(String pathToDestinationFolder, String eventId, String tableLocation); static boolean argsPresent(String... args); }### Answer: @Test public void avroDestinationTest() { assertThat(avroDestination("file: assertThat(avroDestination("file: } @Test public void avroDestinationIsSameAsReplicaLocationTest() { assertThat(avroDestination("file: assertThat(avroDestination("file: } @Test public void avroDestinationIsHiddenFolder() { String[] folders = avroDestination("dummy/url/", "123", "dummy/url").split("/"); assertThat(folders[folders.length - 1], startsWith(".")); } @Test(expected = IllegalArgumentException.class) public void nullDestinationFolderParamTest() { avroDestination(null, "123", "location"); } @Test(expected = IllegalArgumentException.class) public void emptyDestinationFolderParamTest() { avroDestination("", "123", "location"); } @Test(expected = IllegalArgumentException.class) public void nullEventIdParamTest() { avroDestination("test", null, "location"); } @Test(expected = IllegalArgumentException.class) public void emptyEventIdParamTest() { avroDestination("", null, "location"); }
### Question: DestructiveSource { public List<String> getPartitionNames() throws TException { try (CloseableMetaStoreClient client = sourceMetaStoreClientSupplier.get()) { return client.listPartitionNames(databaseName, tableName, ALL); } } DestructiveSource( Supplier<CloseableMetaStoreClient> sourceMetaStoreClientSupplier, TableReplication tableReplication); boolean tableExists(); List<String> getPartitionNames(); }### Answer: @Test public void getPartitionNames() throws Exception { List<String> expectedPartitionNames = Lists.newArrayList("partition1=value1"); when(client.listPartitionNames(DATABASE, TABLE, (short) -1)).thenReturn(expectedPartitionNames); DestructiveSource source = new DestructiveSource(sourceMetaStoreClientSupplier, tableReplication); assertThat(source.getPartitionNames(), is(expectedPartitionNames)); verify(client).close(); }
### Question: DiffGeneratedPartitionPredicate implements PartitionPredicate { @Override public String getPartitionPredicate() { if (!generated) { partitionPredicate = generate(); generated = true; } return partitionPredicate; } DiffGeneratedPartitionPredicate( @Nonnull HiveEndpoint source, @Nonnull HiveEndpoint replica, TableReplication tableReplication, Function<Path, String> checksumFunction); @Override String getPartitionPredicate(); @Override short getPartitionPredicateLimit(); }### Answer: @Test public void autogeneratePredicate() throws Exception { when(replica.getTableAndStatistics(tableReplication)).thenReturn(replicaTableAndStats); when(replicaTableAndStats.getTable()).thenReturn(table2); when(sourceTable.getPartitionLimit()).thenReturn((short) 10); predicate = new DiffGeneratedPartitionPredicate(source, replica, tableReplication, checksumFunction); assertThat(predicate.getPartitionPredicate(), is("(p1='value11' AND p2='value22') OR (p1='value1' AND p2='value2')")); } @Test public void autogeneratePredicateReplicaTableDoesNotExist() throws Exception { when(replica.getTableAndStatistics(tableReplication)).thenThrow(new CircusTrainException("Table does not exist!")); when(sourceTable.getPartitionLimit()).thenReturn((short) 10); predicate = new DiffGeneratedPartitionPredicate(source, replica, tableReplication, checksumFunction); assertThat(predicate.getPartitionPredicate(), is("(p1='value11' AND p2='value22') OR (p1='value1' AND p2='value2')")); }
### Question: DiffGeneratedPartitionPredicate implements PartitionPredicate { @Override public short getPartitionPredicateLimit() { if (Strings.isNullOrEmpty(getPartitionPredicate())) { return 0; } return partitionLimit; } DiffGeneratedPartitionPredicate( @Nonnull HiveEndpoint source, @Nonnull HiveEndpoint replica, TableReplication tableReplication, Function<Path, String> checksumFunction); @Override String getPartitionPredicate(); @Override short getPartitionPredicateLimit(); }### Answer: @Test public void partitionPredicateLimit() throws Exception { when(replica.getTableAndStatistics(tableReplication)).thenReturn(replicaTableAndStats); when(replicaTableAndStats.getTable()).thenReturn(table2); when(sourceTable.getPartitionLimit()).thenReturn((short) 10); predicate = new DiffGeneratedPartitionPredicate(source, replica, tableReplication, checksumFunction); assertThat(predicate.getPartitionPredicateLimit(), is((short) 10)); } @Test public void noPartitionPredicateLimitSetDefaultsToMinus1() throws Exception { when(replica.getTableAndStatistics(tableReplication)).thenReturn(replicaTableAndStats); when(replicaTableAndStats.getTable()).thenReturn(table2); when(sourceTable.getPartitionLimit()).thenReturn(null); predicate = new DiffGeneratedPartitionPredicate(source, replica, tableReplication, checksumFunction); assertThat(predicate.getPartitionPredicateLimit(), is((short) -1)); } @Test public void partitionPredicateLimitOverriddenToZeroWhenNoDiffs() throws Exception { when(sourceTableAndStats.getTable()).thenReturn(table2); when(replica.getTableAndStatistics(tableReplication)).thenReturn(replicaTableAndStats); when(replicaTableAndStats.getTable()).thenReturn(table2); when(sourceTable.getPartitionLimit()).thenReturn((short) 10); predicate = new DiffGeneratedPartitionPredicate(source, replica, tableReplication, checksumFunction); assertThat(predicate.getPartitionPredicateLimit(), is((short) 0)); }
### Question: Locomotive implements ApplicationRunner, ExitCodeGenerator { @VisibleForTesting String getReplicationSummary(TableReplication tableReplication) { return String.format("%s:%s to %s:%s", sourceCatalog.getName(), tableReplication.getSourceTable().getQualifiedName(), replicaCatalog.getName(), tableReplication.getQualifiedReplicaName()); } @Autowired Locomotive( SourceCatalog sourceCatalog, ReplicaCatalog replicaCatalog, Security security, TableReplications tableReplications, ReplicationFactory replicationFactory, MetricSender metricSender, LocomotiveListener locomotiveListener, TableReplicationListener tableReplicationListener); @Override void run(ApplicationArguments args); @Override int getExitCode(); }### Answer: @Test public void getReplicationSummary() { assertThat(locomotive.getReplicationSummary(tableReplication1), is("source-catalog:source-database.source-table to replica-catalog:replica-database.replica-table1")); }
### Question: MetricsListener implements TableReplicationListener, CopierListener { @Override public void tableReplicationFailure(EventTableReplication tableReplication, String eventId, Throwable t) { sendMetrics(CompletionCode.FAILURE, tableReplication.getQualifiedReplicaName(), Metrics.NULL_VALUE); } @Autowired MetricsListener( MetricSender metricSender, ScheduledReporterFactory runningMetricsReporterFactory, @Value("${metrics-reporter.period:1}") long metricsReporterPeriod, @Value("${metrics-reporter.time-unit:MINUTES}") TimeUnit metricsReporterTimeUnit); @Override void tableReplicationStart(EventTableReplication tableReplication, String eventId); @Override void tableReplicationSuccess(EventTableReplication tableReplication, String eventId); @Override void tableReplicationFailure(EventTableReplication tableReplication, String eventId, Throwable t); @Override void copierEnd(Metrics metrics); @Override void copierStart(String copierImplementation); }### Answer: @Test public void failureWithoutStartOrSuccessDoesntThrowException() { Throwable throwable = new Throwable("Test"); listener.tableReplicationFailure(tableReplication, "event-id", throwable); verify(metricSender).send(metricsCaptor.capture()); Map<String, Long> metrics = metricsCaptor.getValue(); assertThat(metrics.size(), is(3)); assertThat(metrics.get("target.replication_time"), is(-1L)); assertThat(metrics.get("target.completion_code"), is(-1L)); assertThat(metrics.get("target.bytes_replicated"), is(0L)); }
### Question: LoggingListener implements TableReplicationListener, LocomotiveListener, SourceCatalogListener, ReplicaCatalogListener, CopierListener { @Override public void tableReplicationFailure(EventTableReplication tableReplication, String eventId, Throwable t) { if (sourceCatalog != null && replicaCatalog != null) { LOG .error("[{}] Failed to replicate '{}:{}' to '{}:{}' with error '{}'", eventId, sourceCatalog.getName(), tableReplication.getSourceTable().getQualifiedName(), replicaCatalog.getName(), tableReplication.getQualifiedReplicaName(), t.getMessage()); } } @Override void tableReplicationStart(EventTableReplication tableReplication, String eventId); @Override void tableReplicationSuccess(EventTableReplication tableReplication, String eventId); @Override void tableReplicationFailure(EventTableReplication tableReplication, String eventId, Throwable t); @Override void circusTrainStartUp(String[] args, EventSourceCatalog sourceCatalog, EventReplicaCatalog replicaCatalog); @Override void resolvedMetaStoreSourceTable(EventTable table); @Override void partitionsToCreate(EventPartitions partitions); @Override void partitionsToAlter(EventPartitions partitions); @Override void copierEnd(Metrics metrics); @Override void circusTrainShutDown(CompletionCode completionCode, Map<String, Long> metrics); @Override void resolvedSourcePartitions(EventPartitions partitions); @Override void resolvedSourceLocation(URI location); @Override void resolvedReplicaLocation(URI location); @Override void existingReplicaPartitions(EventPartitions partitions); @Override void deprecatedReplicaLocations(List<URI> locations); @Override void copierStart(String copierImplementation); }### Answer: @Test public void failureWithoutStartOrSuccessDoesntThrowException() { Throwable throwable = new Throwable("Test"); listener.tableReplicationFailure(tableReplication, "event-id", throwable); }
### Question: EventUtils { public static EventTable toEventTable(Table sourceTable) { if (sourceTable == null) { return null; } return new EventTable(FieldSchemaUtils.getFieldNames(sourceTable.getPartitionKeys()), LocationUtils.hasLocation(sourceTable) ? LocationUtils.locationAsUri(sourceTable) : null); } private EventUtils(); static List<URI> toUris(List<Path> paths); static EventPartitions toEventPartitions(Table table, List<Partition> partitions); static EventTable toEventTable(Table sourceTable); static EventSourceCatalog toEventSourceCatalog(SourceCatalog sourceCatalog); static EventReplicaCatalog toEventReplicaCatalog(ReplicaCatalog replicaCatalog, Security security); static EventTableReplication toEventTableReplication(TableReplication tableReplication); static final String EVENT_ID_UNAVAILABLE; }### Answer: @Test public void toNullEventTable() { assertThat(EventUtils.toEventTable(null), is(nullValue())); } @Test public void toEventTable() { when(tableStorageDescriptor.getLocation()).thenReturn("location"); EventTable eventTable = EventUtils.toEventTable(table); assertThat(eventTable, is(not(nullValue()))); assertThat(eventTable.getPartitionKeys(), is(PARTITION_KEY_NAMES)); assertThat(eventTable.getLocation(), is(URI.create("location"))); } @Test public void toEventTableWithNullLocation() { EventTable eventTable = EventUtils.toEventTable(table); assertThat(eventTable, is(not(nullValue()))); assertThat(eventTable.getPartitionKeys(), is(PARTITION_KEY_NAMES)); assertThat(eventTable.getLocation(), is(nullValue())); }
### Question: ListenerConfig { public int getQueueSize() { return queueSize; } void setQueueSize(int queueSize); String getStartTopic(); void setStartTopic(String startTopic); String getSuccessTopic(); void setSuccessTopic(String successTopic); String getFailTopic(); void setFailTopic(String failTopic); Map<String, String> getHeaders(); void setHeaders(Map<String, String> headers); String getSubject(); void setSubject(String subject); int getQueueSize(); String getTopic(); void setTopic(String topic); String getRegion(); void setRegion(String region); }### Answer: @Test public void defaultQueueSize() { assertThat(config.getQueueSize(), is(100)); }
### Question: SnsMessage { public void clearModifiedPartitions() { if (modifiedPartitions != null) { modifiedPartitions.clear(); } } SnsMessage( SnsMessageType type, Map<String, String> headers, String startTime, String endTime, String eventId, String sourceCatalog, String replicaCatalog, String replicaMetastoreUris, String sourceTable, String replicaTable, String replicaTableLocation, LinkedHashMap<String, String> partitionKeys, List<List<String>> modifiedPartitions, Long bytesReplicated, String errorMessage); String getProtocolVersion(); SnsMessageType getType(); Map<String, String> getHeaders(); String getStartTime(); String getEndTime(); String getEventId(); String getSourceCatalog(); String getReplicaCatalog(); String getSourceTable(); String getReplicaTable(); String getReplicaTableLocation(); String getReplicaMetastoreUris(); LinkedHashMap<String, String> getPartitionKeys(); List<List<String>> getModifiedPartitions(); void clearModifiedPartitions(); Long getBytesReplicated(); String getErrorMessage(); Boolean isMessageTruncated(); void setMessageTruncated(Boolean truncated); }### Answer: @Test public void clearNullPartitions() throws JsonProcessingException { SnsMessage message = new SnsMessage(null, null, null, null, null, null, null, null, null, null, null, null, null, 0L, null); message.clearModifiedPartitions(); }
### Question: SnsConfiguration { @Bean AWSCredentialsProvider awsCredentialsProvider( @Qualifier("replicaHiveConf") org.apache.hadoop.conf.Configuration conf) { return new AWSCredentialsProviderChain(new BasicAuth(conf), InstanceProfileCredentialsProvider.getInstance()); } }### Answer: @Test public void credentials() throws IOException { when(conf.getPassword("access.key")).thenReturn("accessKey".toCharArray()); when(conf.getPassword("secret.key")).thenReturn("secretKey".toCharArray()); AWSCredentialsProvider credentialsProvider = configuration.awsCredentialsProvider(conf); AWSCredentials awsCredentials = credentialsProvider.getCredentials(); assertThat(awsCredentials.getAWSAccessKeyId(), is("accessKey")); assertThat(awsCredentials.getAWSSecretKey(), is("secretKey")); }
### Question: SnsConfiguration { @Bean AmazonSNSAsync amazonSNS(ListenerConfig config, AWSCredentialsProvider awsCredentialsProvider) { return AmazonSNSAsyncClient.asyncBuilder() .withCredentials(awsCredentialsProvider) .withRegion(config.getRegion()) .build(); } }### Answer: @Test public void snsClient() { AWSCredentialsProvider credentialsProvider = mock(AWSCredentialsProvider.class); when(credentialsProvider.getCredentials()).thenReturn(new BasicAWSCredentials("accessKey", "secretKey")); ListenerConfig config = new ListenerConfig(); config.setRegion("eu-west-1"); AmazonSNS sns = configuration.amazonSNS(config, credentialsProvider); assertThat(sns, is(not(nullValue()))); }
### Question: S3Schemes { public static boolean isS3Scheme(String scheme) { return S3_SCHEMES.contains(Strings.nullToEmpty(scheme).toLowerCase(Locale.ROOT)); } private S3Schemes(); static boolean isS3Scheme(String scheme); }### Answer: @Test public void isS3Scheme() { assertTrue(S3Schemes.isS3Scheme("s3")); assertTrue(S3Schemes.isS3Scheme("S3")); assertTrue(S3Schemes.isS3Scheme("s3a")); assertTrue(S3Schemes.isS3Scheme("S3A")); assertTrue(S3Schemes.isS3Scheme("s3n")); assertTrue(S3Schemes.isS3Scheme("S3N")); } @Test public void isNotS3Scheme() { assertFalse(S3Schemes.isS3Scheme(null)); assertFalse(S3Schemes.isS3Scheme("")); assertFalse(S3Schemes.isS3Scheme("file")); assertFalse(S3Schemes.isS3Scheme("s321")); assertFalse(S3Schemes.isS3Scheme("sss")); }
### Question: AWSBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (CommonBeans.BEAN_BASE_CONF.equals(beanName)) { Configuration baseConf = (Configuration) bean; bindS3AFileSystem.bindFileSystem(baseConf); if (baseConf.get(CREDENTIAL_PROVIDER_PATH) != null) { s3CredentialsUtils.setS3Credentials(baseConf); } return baseConf; } return bean; } @Autowired AWSBeanPostProcessor(BindS3AFileSystem bindS3AFileSystem, S3CredentialsUtils s3CredentialsUtils); @Override Object postProcessBeforeInitialization(Object bean, String beanName); @Override Object postProcessAfterInitialization(Object bean, String beanName); }### Answer: @Test public void baseConfBindFileSystem() throws Exception { Configuration conf = new Configuration(); Object result = postProcessor.postProcessAfterInitialization(conf, "baseConf"); Configuration resultConf = (Configuration) result; assertThat(resultConf, is(conf)); verify(bindS3AFileSystem).bindFileSystem(conf); verifyZeroInteractions(s3CredentialsUtils); } @Test public void baseConfs3Credentials() throws Exception { Configuration conf = new Configuration(); conf.set(CREDENTIAL_PROVIDER_PATH, "path"); Object result = postProcessor.postProcessAfterInitialization(conf, "baseConf"); Configuration resultConf = (Configuration) result; assertThat(resultConf, is(conf)); verify(bindS3AFileSystem).bindFileSystem(conf); verify(s3CredentialsUtils).setS3Credentials(conf); } @Test public void postProcessAfterInitializationReturnsBean() throws Exception { Object bean = new Object(); Object result = postProcessor.postProcessAfterInitialization(bean, "bean"); assertThat(result, is(bean)); }
### Question: AWSBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Autowired AWSBeanPostProcessor(BindS3AFileSystem bindS3AFileSystem, S3CredentialsUtils s3CredentialsUtils); @Override Object postProcessBeforeInitialization(Object bean, String beanName); @Override Object postProcessAfterInitialization(Object bean, String beanName); }### Answer: @Test public void postProcessBeforeInitializationReturnsBean() throws Exception { Object bean = new Object(); Object result = postProcessor.postProcessBeforeInitialization(bean, "bean"); assertThat(result, is(bean)); }
### Question: AssumeRoleCredentialProvider implements AWSCredentialsProvider { @Override public AWSCredentials getCredentials() { if (this.credentialsProvider == null) { initializeCredentialProvider(); } return this.credentialsProvider.getCredentials(); } AssumeRoleCredentialProvider(Configuration conf); @Override AWSCredentials getCredentials(); @Override void refresh(); static final String ASSUME_ROLE_PROPERTY_NAME; static final String ASSUME_ROLE_SESSION_DURATION_SECONDS_PROPERTY_NAME; }### Answer: @Test(expected = NullPointerException.class) public void getCredentialsThrowsNullPointerException() { AssumeRoleCredentialProvider provider = new AssumeRoleCredentialProvider(null); provider.getCredentials(); } @Test(expected = IllegalArgumentException.class) public void getCredentialsThrowsIllegalArgumentException() { AssumeRoleCredentialProvider provider = new AssumeRoleCredentialProvider(new Configuration()); provider.getCredentials(); }
### Question: AssumeRoleCredentialProvider implements AWSCredentialsProvider { @Override public void refresh() { if (this.credentialsProvider == null) { initializeCredentialProvider(); } this.credentialsProvider.refresh(); } AssumeRoleCredentialProvider(Configuration conf); @Override AWSCredentials getCredentials(); @Override void refresh(); static final String ASSUME_ROLE_PROPERTY_NAME; static final String ASSUME_ROLE_SESSION_DURATION_SECONDS_PROPERTY_NAME; }### Answer: @Test(expected = NullPointerException.class) public void refreshThrowsNullPointerException() { AssumeRoleCredentialProvider provider = new AssumeRoleCredentialProvider(null); provider.refresh(); } @Test(expected = IllegalArgumentException.class) public void refreshThrowsIllegalArgumentException() { AssumeRoleCredentialProvider provider = new AssumeRoleCredentialProvider(new Configuration()); provider.refresh(); }
### Question: AWSCredentialUtils { static String getKey(Configuration conf, String keyType) { checkNotNull(conf, "conf cannot be null"); checkNotNull(keyType, "KeyType cannot be null"); try { char[] key = conf.getPassword(keyType); if (key == null) { throw new IllegalStateException(format("Unable to get value of '%s'", keyType)); } return new String(key); } catch (IOException e) { throw new RuntimeException(format("Error getting key for '%s' from credential provider", keyType), e); } } private AWSCredentialUtils(); static Configuration configureCredentialProvider(String credentialProviderPath); static Configuration configureCredentialProvider(String credentialProviderPath, Configuration conf); }### Answer: @Test public void getAccessKeyFromConfTest() throws Exception { Configuration conf = new Configuration(); conf.set(AWSConstants.ACCESS_KEY, "access"); conf.set(AWSConstants.SECRET_KEY, "secret"); String access = AWSCredentialUtils.getKey(conf, AWSConstants.ACCESS_KEY); assertThat(access, is("access")); } @Test public void getSecretKeyFromConfTest() throws Exception { Configuration conf = new Configuration(); conf.set(AWSConstants.ACCESS_KEY, "access"); conf.set(AWSConstants.SECRET_KEY, "secret"); String secret = AWSCredentialUtils.getKey(conf, AWSConstants.SECRET_KEY); assertThat(secret, is("secret")); } @Test(expected = IllegalStateException.class) public void getKeyFromConfWhichIsntSetThrowsExceptionTest() throws Exception { Configuration conf = new Configuration(); AWSCredentialUtils.getKey(conf, AWSConstants.SECRET_KEY); } @Test(expected = RuntimeException.class) public void getKeyThrowsRuntimeExceptionTest() throws Exception { Configuration conf = mock(Configuration.class); when(conf.getPassword(anyString())).thenThrow(new IOException()); AWSCredentialUtils.getKey(conf, AWSConstants.SECRET_KEY); }