code
stringlengths 23
201k
| docstring
stringlengths 17
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
72
| path
stringlengths 11
317
| url
stringlengths 57
377
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
@Test
public void testJobTypeManagerJobSetupWithJobComponentDependency() {
final JobTypeManager manager = new JobTypeManager(this.testPluginDirPath, null,
this.getClass().getClassLoader(), this.clusterRouter, null);
Props jobProps = new Props();
jobProps.put("type", "anothertestjob");
jobProps.put("propB", "b");
jobProps.put(CommonJobProperties.JOB_CLUSTER_COMPONENTS_DEPENDENCIES, "hive");
final JobParams jobParams = manager.createJobParams("anothertestjob", jobProps, LOG);
Assert.assertTrue(
jobParams.contextClassLoader instanceof HadoopSecurityManagerClassLoader);
final Job job = JobTypeManager.createJob("anothertestjob", jobParams, LOG);
jobProps = ((FakeJavaJob) job).getJobProps();
final String clusterClassPath = jobProps
.getString(CommonJobProperties.TARGET_CLUSTER_CLASSPATH);
Assert.assertTrue(clusterClassPath.contains("hive"));
Assert.assertTrue(clusterClassPath.contains("hadoop"));
final String jvmArgs = jobProps.getString(CommonJobProperties.TARGET_CLUSTER_NATIVE_LIB);
Assert.assertTrue(jvmArgs.contains("hadoop"));
Assert.assertTrue(jvmArgs.contains("hive"));
}
|
Unit test of JobTypeManager's setup for jobs with 'job.dependency.components' specified.
|
testJobTypeManagerJobSetupWithJobComponentDependency
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
Apache-2.0
|
@Test
public void testJobTypeManagerJobSetupWithoutJobtypeComponentDependency() {
final JobTypeManager manager = new JobTypeManager(this.testPluginDirPath, null,
this.getClass().getClassLoader(), this.clusterRouter, null);
Props jobProps = new Props();
jobProps.put("type", "testjob");
jobProps.put("propA", "a");
jobProps.put(CommonJobProperties.JOB_CLUSTER_COMPONENTS_DEPENDENCIES, "hadoop");
final JobParams jobParams = manager.createJobParams("testjob", jobProps, LOG);
Assert.assertTrue(
jobParams.contextClassLoader instanceof HadoopSecurityManagerClassLoader);
final Job job = JobTypeManager.createJob("testjob", jobParams, LOG);
jobProps = ((FakeJavaJob2) job).getJobProps();
final String clusterClassPath = jobProps
.getString(CommonJobProperties.TARGET_CLUSTER_CLASSPATH);
Assert.assertFalse(clusterClassPath.contains("hive"));
Assert.assertTrue(clusterClassPath.contains("hadoop"));
final String jvmArgs = jobProps.getString(CommonJobProperties.TARGET_CLUSTER_NATIVE_LIB);
Assert.assertFalse(jvmArgs.contains("hive"));
Assert.assertTrue(jvmArgs.contains("hadoop"));
}
|
Unit test of JobTypeManager's setup for jobs that depend on only a subset of
components of the default cluster.
|
testJobTypeManagerJobSetupWithoutJobtypeComponentDependency
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
Apache-2.0
|
@Test (expected = JobTypeManagerException.class)
public void testJobTypeManagerJobSetupWithUnknownClusterComponents() {
final JobTypeManager manager = new JobTypeManager(this.testPluginDirPath, null,
this.getClass().getClassLoader(), this.clusterRouter, null);
final Props jobProps = new Props();
jobProps.put("type", "anothertestjob");
jobProps.put("propB", "b");
jobProps.put(CommonJobProperties.JOB_CLUSTER_COMPONENTS_DEPENDENCIES, "unknown");
manager.createJobParams("anothertestjob", jobProps, LOG);
}
|
Unit test of JobTypeManager's setup for jobs that depend on only a subset of
components of the default cluster.
|
testJobTypeManagerJobSetupWithUnknownClusterComponents
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
Apache-2.0
|
@Test
public void testJobTypeManagerJobSetupWithoutAnyComponentDependency() {
final JobTypeManager manager = new JobTypeManager(this.testPluginDirPath, null,
this.getClass().getClassLoader(), this.clusterRouter, null);
Props jobProps = new Props();
jobProps.put("type", "testjob");
jobProps.put("propA", "a");
final JobParams jobParams = manager.createJobParams("testjob", jobProps, LOG);
Assert.assertFalse(
jobParams.contextClassLoader instanceof HadoopSecurityManagerClassLoader);
final Job job = JobTypeManager.createJob("testjob", jobParams, LOG);
jobProps = ((FakeJavaJob2) job).getJobProps();
Assert.assertNull(jobProps.get(CommonJobProperties.TARGET_CLUSTER_CLASSPATH));
Assert.assertNull(jobProps.get(CommonJobProperties.TARGET_CLUSTER_NATIVE_LIB));
}
|
Unit test of JobTypeManager's setup for jobs that depend on no components of the
default cluster.
|
testJobTypeManagerJobSetupWithoutAnyComponentDependency
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
Apache-2.0
|
@Test
public void testJobParamsPrecedenceOverClusterParams() {
final JobTypeManager manager = new JobTypeManager(this.testPluginDirPath, null,
this.getClass().getClassLoader(), this.clusterRouter, null);
Props jobProps = new Props();
jobProps.put("type", "testjob");
jobProps.put(PIG_HOME, "/user/pig/path");
jobProps.put(CommonJobProperties.JOB_CLUSTER_COMPONENTS_DEPENDENCIES, "hadoop");
final JobParams jobParams = manager.createJobParams("testjob", jobProps, LOG);
Assert.assertTrue(
jobParams.contextClassLoader instanceof HadoopSecurityManagerClassLoader);
final Job job = JobTypeManager.createJob("testjob", jobParams, LOG);
jobProps = ((FakeJavaJob2) job).getJobProps();
Assert.assertEquals("/user/pig/path", jobProps.get(PIG_HOME));
}
|
Unit test of JobTypeManager's setup for jobs that depend on no components of the
default cluster.
|
testJobParamsPrecedenceOverClusterParams
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
Apache-2.0
|
@Test
public void testJobRunnerObservesClusterSpecificParams() {
final JobTypeManager manager = new JobTypeManager(this.testPluginDirPath, null,
this.getClass().getClassLoader(), this.clusterRouter, null);
Props jobProps = new Props();
jobProps.put("type", "anothertestjob");
manager.createJobParams("anothertestjob", jobProps, LOG);
// verify the jobProps also observe the parameters injected in JobTypeManager
jobProps = PropsUtils.resolveProps(jobProps);
Assert.assertEquals("valB", jobProps.getString("PropA"));
}
|
Verify that cluster-specific params can be observed by JobRunner through
the passed-in parameter, `jobParams` to JobTypeManager.createJobParams() call.
|
testJobRunnerObservesClusterSpecificParams
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
Apache-2.0
|
@Test
public void testPluginLoadPropsOverrideByClusterSpecificParams() {
final JobTypeManager manager = new JobTypeManager(this.testPluginDirPath, null,
this.getClass().getClassLoader(), this.clusterRouter, null);
Props jobProps = new Props();
jobProps.put("type", "testjob");
jobProps.put(PIG_HOME, "/user/pig/path");
jobProps.put(CommonJobProperties.JOB_CLUSTER_COMPONENTS_DEPENDENCIES, "hadoop");
final JobParams jobParams = manager.createJobParams("testjob", jobProps, LOG);
Assert.assertTrue(
jobParams.contextClassLoader instanceof HadoopSecurityManagerClassLoader);
final Job job = JobTypeManager.createJob("testjob", jobParams, LOG);
Props sysProps = ((FakeJavaJob2) job).getSysProps();
Assert.assertEquals(null, sysProps.get("PropA"));
// Create JobTypeManager again but with pluginOverrideProps this time.
final String pluginLoadOverrideProps = "PropC,PropB";
final JobTypeManager manager1 = new JobTypeManager(this.testPluginDirPath, null,
this.getClass().getClassLoader(), this.clusterRouter, pluginLoadOverrideProps);
final JobParams jobParams1 = manager1.createJobParams("testjob", jobProps, LOG);
final Job job1 = JobTypeManager.createJob("testjob", jobParams1, LOG);
sysProps = ((FakeJavaJob2) job1).getSysProps();
Assert.assertEquals("valC", sysProps.get("PropC"));
Assert.assertEquals("valB", sysProps.get("PropB"));
}
|
Verify that overidden plugin load props are indeed overridden.
|
testPluginLoadPropsOverrideByClusterSpecificParams
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
Apache-2.0
|
@Test
public void testPluginLoadPropsOverrideByClusterSpecificParamsNegative() {
final Props jobProps = new Props();
jobProps.put("type", "testjob");
jobProps.put(PIG_HOME, "/user/pig/path");
jobProps.put(CommonJobProperties.JOB_CLUSTER_COMPONENTS_DEPENDENCIES, "hadoop");
// Create JobTypeManager with pluginOverrideProps, however, add propD which
// is not a valid property in cluster props.
final String pluginLoadOverrideProps = "PropC,PropD";
final JobTypeManager manager = new JobTypeManager(this.testPluginDirPath, null,
this.getClass().getClassLoader(), this.clusterRouter, pluginLoadOverrideProps);
final JobParams jobParams = manager.createJobParams("testjob", jobProps, LOG);
final Job job = JobTypeManager.createJob("testjob", jobParams, LOG);
final Props sysProps = ((FakeJavaJob2) job).getSysProps();
Assert.assertEquals("valC", sysProps.get("PropC"));
Assert.assertEquals(null, sysProps.get("PropD"));
}
|
Verify that overidden plugin load props and ignores if a property
is missing.
|
testPluginLoadPropsOverrideByClusterSpecificParamsNegative
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/jobtype/JobTypeManagerWithDynamicClusterTest.java
|
Apache-2.0
|
@Override
public Props process(Props jobProps) {
jobProps.put(INJECTED_ADDITION_PROP, INJECTED_ADDITION_PROP);
return jobProps;
}
|
A test implementation of {@link JobPropsProcessor} that injects a
new property into jobs.
|
process
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/jobtype/TestJobPropsProcessor.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/jobtype/TestJobPropsProcessor.java
|
Apache-2.0
|
@Override
public void uploadLogFile(final int execId, final String name, final int attempt,
final File... files)
throws ExecutorManagerException {
for (final File file : files) {
try {
final String logs = FileUtils.readFileToString(file, "UTF-8");
LOGGER.info("Uploaded log for [" + name + "]:[" + execId + "]:\n" + logs);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
}
|
Used in unit tests to mock the "DB layer" (the real implementation is JdbcExecutionsLogLoader).
Captures status updates of jobs and flows (in memory) so that they can be checked in tests.
|
uploadLogFile
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/logs/MockExecutionLogsLoader.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/logs/MockExecutionLogsLoader.java
|
Apache-2.0
|
@Override
public LogData fetchLogs(final int execId, final String name, final int attempt,
final int startByte, final int endByte, final long flowStartTime, final long flowEndTime) throws ExecutorManagerException {
// TODO Auto-generated method stub
return null;
}
|
Used in unit tests to mock the "DB layer" (the real implementation is JdbcExecutionsLogLoader).
Captures status updates of jobs and flows (in memory) so that they can be checked in tests.
|
fetchLogs
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/logs/MockExecutionLogsLoader.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/logs/MockExecutionLogsLoader.java
|
Apache-2.0
|
@Override
public int removeExecutionLogsByTime(final long millis, final int recordCleanupLimit)
throws ExecutorManagerException {
// TODO Auto-generated method stub
return 0;
}
|
Used in unit tests to mock the "DB layer" (the real implementation is JdbcExecutionsLogLoader).
Captures status updates of jobs and flows (in memory) so that they can be checked in tests.
|
removeExecutionLogsByTime
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/logs/MockExecutionLogsLoader.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/logs/MockExecutionLogsLoader.java
|
Apache-2.0
|
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.metricManager == null) ? 0 : this.metricManager.hashCode());
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
result = prime * result + ((this.type == null) ? 0 : this.type.hashCode());
result = prime * result + ((this.value == null) ? 0 : this.value.hashCode());
return result;
}
|
Dummy Metric to test Azkaban Metrics
|
hashCode
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/metric/FakeMetric.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/metric/FakeMetric.java
|
Apache-2.0
|
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof FakeMetric)) {
return false;
}
final FakeMetric other = (FakeMetric) obj;
if (this.metricManager == null) {
if (other.metricManager != null) {
return false;
}
} else if (!this.metricManager.equals(other.metricManager)) {
return false;
}
if (this.name == null) {
if (other.name != null) {
return false;
}
} else if (!this.name.equals(other.name)) {
return false;
}
if (this.type == null) {
if (other.type != null) {
return false;
}
} else if (!this.type.equals(other.type)) {
return false;
}
if (this.value == null) {
if (other.value != null) {
return false;
}
} else if (!this.value.equals(other.value)) {
return false;
}
return true;
}
|
Dummy Metric to test Azkaban Metrics
|
equals
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/metric/FakeMetric.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/metric/FakeMetric.java
|
Apache-2.0
|
@Test
public void managerStatusTest() {
assertNotNull("Singleton Failed to instantiate", this.manager);
assertTrue("Failed to enable metric manager", MetricReportManager.isAvailable());
this.manager.disableManager();
assertFalse("Failed to disable metric manager", MetricReportManager.isAvailable());
this.manager.enableManager();
assertTrue("Failed to enable metric manager", MetricReportManager.isAvailable());
}
|
Test enable disable and status methods
|
managerStatusTest
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/metric/MetricManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/metric/MetricManagerTest.java
|
Apache-2.0
|
@Test
public void managerMetricMaintenanceTest() {
assertEquals("Failed to add metric", this.manager.getAllMetrics().size(), 1);
assertTrue("Failed to add metric", this.manager.getAllMetrics().contains(this.metric));
assertEquals("Failed to get metric by Name", this.manager.getMetricFromName("FakeMetric"),
this.metric);
}
|
Test adding and accessing metric methods
|
managerMetricMaintenanceTest
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/metric/MetricManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/metric/MetricManagerTest.java
|
Apache-2.0
|
@Test
public void testParseStartupDependencies() throws Exception {
Set<Dependency> finalDependencies = new HashSet<>();
try {
// Get a raw json which contains null along with other valid dependencies
String rawJson = getRawJSONDepsNullAndABC();
finalDependencies = parseStartupDependencies(rawJson);
} catch (NullPointerException npe) {
// If NullPointerException is thrown by parseStartupDependencies() it means the
// method tried to create a Dependency object without checking for null.
// Fail the test since it should always check for null before creating Dependency
// object.
fail("Received NullPointerException while parsing startup dependencies");
}
// The Set of dependencies returned by parseStartupDependencies() should be without null
// and same as Set of dependencies created by the test for valid dependencies in the
// raw json.
assertEquals(finalDependencies, getDepSetABC());
}
|
Test parsing of startup dependencies functionality. Even if json containing startup
dependencies for a project contains a 'null' in the list, parseStartupDependencies
should check for it and remove it from the final set of dependencies.
@throws Exception
|
testParseStartupDependencies
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/ThinArchiveUtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/ThinArchiveUtilsTest.java
|
Apache-2.0
|
@Test
public void testWriteStartupDependencies() throws Exception {
// Pass Set containing null and valid dependencies to writeStartupDependencies()
writeStartupDependencies(startupDepsJsonFile, depSetABCAndNull);
// Read the file that was written above to check if contains null
String rawJson = FileUtils.readFileToString(startupDepsJsonFile);
List<Map<String, String>> rawParseResult =
((HashMap<String, List<Map<String, String>>>) JSONUtils.parseJSONFromString(rawJson))
.get("dependencies");
if (rawParseResult == null) {
// Fail the test if the file does not contain "dependencies" key
fail("Could not find 'dependencies' key in startup-dependencies.json file.");
}
Set<Dependency> dependenciesFromFile = parseStartupDependencies(startupDepsJsonFile);
for (Map<String, String> rawDependency : rawParseResult) {
if (rawDependency != null) {
dependenciesFromFile.add(new Dependency(rawDependency));
} else {
// Fail the test if file contains a null
fail("Found a null entry in startup-dependencies.json file.");
}
}
// The Set of dependencies returned by parseStartupDependencies() should be without null
// and same as Set of dependencies created by the test for valid dependencies.
assertEquals(dependenciesFromFile, getDepSetABC());
}
|
Test writing of startup dependencies to file.
When Set of dependencies containing 'null' along with valid Dependency objects is
passed to writeStartupDependencies(), the method should filter out null before
writing the dependencies to the file.
After writing to file, the test reads the file to check if any null is present.
@throws Exception
|
testWriteStartupDependencies
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/ThinArchiveUtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/ThinArchiveUtilsTest.java
|
Apache-2.0
|
@Test
public void testAddWarnLevelInfoMsg() {
final ValidationReport report = new ValidationReport();
final String msg = "test warn level info message.";
report.addWarnLevelInfoMsg(msg);
for (final String info : report.getInfoMsgs()) {
assertEquals("Info message added through addWarnLevelInfoMsg should have level set to WARN",
ValidationReport.getInfoMsgLevel(info), ValidationStatus.WARN);
assertEquals("Retrieved info message does not match the original one.",
ValidationReport.getInfoMsg(info), msg);
}
}
|
Test adding messages to {@link ValidationReport}
|
testAddWarnLevelInfoMsg
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/validator/ValidationReportTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/validator/ValidationReportTest.java
|
Apache-2.0
|
@Test
public void testAddErrorLevelInfoMsg() {
final ValidationReport report = new ValidationReport();
final String msg = "test error level error message.";
report.addErrorLevelInfoMsg(msg);
for (final String info : report.getInfoMsgs()) {
assertEquals("Info message added through addErrorLevelInfoMsg should have level set to ERROR",
ValidationReport.getInfoMsgLevel(info), ValidationStatus.ERROR);
assertEquals("Retrieved info message does not match the original one.",
ValidationReport.getInfoMsg(info), msg);
}
}
|
Test adding messages to {@link ValidationReport}
|
testAddErrorLevelInfoMsg
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/validator/ValidationReportTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/validator/ValidationReportTest.java
|
Apache-2.0
|
@Test
public void testAddMsgs() {
final ValidationReport report = new ValidationReport();
final Set<String> msgs = new HashSet<>();
msgs.add("test msg 1.");
msgs.add("test msg 2.");
report.addWarningMsgs(msgs);
assertEquals("Level of severity is not warn.",
report.getStatus(), ValidationStatus.WARN);
report.addErrorMsgs(msgs);
assertEquals("Number of error messages retrieved does not match.",
report.getErrorMsgs().size(), 2);
assertEquals("Number of warn messages retrieved does not match.",
report.getWarningMsgs().size(), 2);
assertEquals("Level of severity is not error.",
report.getStatus(), ValidationStatus.ERROR);
}
|
Test adding messages to {@link ValidationReport}
|
testAddMsgs
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/validator/ValidationReportTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/validator/ValidationReportTest.java
|
Apache-2.0
|
@Test
public void testAddModifiedRemovedFiles() {
final ValidationReport report = new ValidationReport();
File a = new File("/a.txt");
File b = new File("/b.txt");
File c = new File("/c.txt");
File d = new File("/d.txt");
File e = new File("/e.txt");
final Set<File> removedFiles = new HashSet<>();
removedFiles.add(a);
removedFiles.add(b);
final Set<File> modifiedFiles = new HashSet<>();
removedFiles.add(c);
// Exercise both the methods to add individual files, and methods to add collections of files.
report.addRemovedFile(d);
report.addModifiedFile(e);
report.addRemovedFiles(removedFiles);
report.addModifiedFiles(modifiedFiles);
final Set<File> expectedRemovedFiles = new HashSet<>();
expectedRemovedFiles.addAll(removedFiles);
expectedRemovedFiles.add(d);
final Set<File> expectedModifiedFiles = new HashSet<>();
expectedModifiedFiles.addAll(modifiedFiles);
expectedModifiedFiles.add(e);
assertEquals(expectedRemovedFiles, report.getRemovedFiles());
assertEquals(expectedModifiedFiles, report.getModifiedFiles());
}
|
Test adding messages to {@link ValidationReport}
|
testAddModifiedRemovedFiles
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/validator/ValidationReportTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/validator/ValidationReportTest.java
|
Apache-2.0
|
@Test
public void testNoValidatorsDir() {
final Props props = new Props(this.baseProps);
final XmlValidatorManager manager = new XmlValidatorManager(props);
assertEquals(
"XmlValidatorManager should contain 0 validator when no xml configuration "
+ "file is present.", manager.getValidatorsInfo().size(), 0);
}
|
Test that no validator directory exists when there is no xml configuration.
|
testNoValidatorsDir
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/validator/XmlValidatorManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/validator/XmlValidatorManagerTest.java
|
Apache-2.0
|
@Test(expected = ValidatorManagerException.class)
public void testValidatorDoesNotExist() {
final Props props = new Props(this.baseProps);
final URL validatorUrl = Resources.getResource("project/testValidators");
final URL configUrl = Resources.getResource("test-conf/azkaban-validators-test1.xml");
props.put(ValidatorConfigs.VALIDATOR_PLUGIN_DIR, validatorUrl.getPath());
props.put(ValidatorConfigs.XML_FILE_PARAM, configUrl.getPath());
new XmlValidatorManager(props);
}
|
Test that if the xml config file specifies a validator classname that does not exist,
XmlValidatorManager should throw an exception.
|
testValidatorDoesNotExist
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/validator/XmlValidatorManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/validator/XmlValidatorManagerTest.java
|
Apache-2.0
|
@Test
public void testLoadValidators() {
final Props props = new Props(this.baseProps);
final URL validatorUrl = Resources.getResource("project/testValidators");
final URL configUrl = Resources.getResource("test-conf/azkaban-validators-test2.xml");
props.put(ValidatorConfigs.VALIDATOR_PLUGIN_DIR, validatorUrl.getPath());
props.put(ValidatorConfigs.XML_FILE_PARAM, configUrl.getPath());
final XmlValidatorManager manager = new XmlValidatorManager(props);
assertEquals("XmlValidatorManager should contain 1 validator.",
manager.getValidatorsInfo().size(), 1);
assertEquals(
"XmlValidatorManager should contain the validator specified in the xml configuration file.",
manager.getValidatorsInfo().get(0), "Test");
}
|
Test that if the xml config file is properly set, XmlValidatorManager loads the validator
specified in the xml file. The TestValidator class specified in the xml configuration file
is located with the jar file inside test resource directory project/testValidators.
|
testLoadValidators
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/validator/XmlValidatorManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/validator/XmlValidatorManagerTest.java
|
Apache-2.0
|
@Test
public void testValidateProjectValidator() throws Exception {
final Project project = mock(Project.class);
final File projectDir = mock(File.class);
final Props props = new Props();
final ProjectValidator mockValidator = mock(ProjectValidator.class);
final XmlValidatorManager manager = new XmlValidatorManager(props);
// When we attempt to validate a project with our mock validator, return sampleReport
final ValidationReport sampleReport = new ValidationReport();
when(mockValidator.validateProject(project, projectDir, props)).thenReturn(sampleReport);
Map<String, ProjectValidator> mockedValidators = new HashMap();
mockedValidators.put("TEST", mockValidator);
// This is brittle and hacky, but we're directly setting the private validators field with our own
Field validatorsField = manager.getClass().getDeclaredField("validators");
validatorsField.setAccessible(true);
FieldSetter.setField(manager, validatorsField, mockedValidators);
Map<String, ValidationReport> expectedResultingReports = new HashMap();
expectedResultingReports.put("TEST", sampleReport);
// Make sure we get the reports back that we expect
assertEquals(expectedResultingReports, manager.validate(project, projectDir, props));
}
|
Test that if the xml config file is properly set, XmlValidatorManager loads the validator
specified in the xml file. The TestValidator class specified in the xml configuration file
is located with the jar file inside test resource directory project/testValidators.
|
testValidateProjectValidator
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/validator/XmlValidatorManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/validator/XmlValidatorManagerTest.java
|
Apache-2.0
|
@Test
public void testGetCacheKeyProjectValidatorCacheable() throws Exception {
final Project project = mock(Project.class);
final File projectDir = mock(File.class);
final Props props = new Props();
final ProjectValidatorCacheable mockValidatorCacheable = mock(ProjectValidatorCacheable.class);
final ProjectValidator mockValidator = mock(ProjectValidator.class);
final XmlValidatorManager manager = new XmlValidatorManager(props);
// When we attempt to validate a project with our mock validator, return sampleReport
final String cacheKey = "abc123";
final String expectedResultingCacheKey = HashUtils.SHA1.getHashStr(cacheKey);
when(mockValidatorCacheable.getCacheKey(project, projectDir, props)).thenReturn(cacheKey);
Map<String, ProjectValidator> mockedValidators = new HashMap();
// We add a non cacheable validator as well to ensure that it is ignored properly and no exceptions are thrown.
mockedValidators.put("NORMAL", mockValidator);
// Only this cacheable validator should contribute to the cacheKey
mockedValidators.put("CACHEABLE", mockValidatorCacheable);
// This is brittle and hacky, but we're directly setting the private validators field with our own
Field validatorsField = manager.getClass().getDeclaredField("validators");
validatorsField.setAccessible(true);
FieldSetter.setField(manager, validatorsField, mockedValidators);
// Make sure we get the cache key we expected (the SHA1 of the one cache key returned)
assertEquals(expectedResultingCacheKey, manager.getCacheKey(project, projectDir, props));
}
|
Test that if the xml config file is properly set, XmlValidatorManager loads the validator
specified in the xml file. The TestValidator class specified in the xml configuration file
is located with the jar file inside test resource directory project/testValidators.
|
testGetCacheKeyProjectValidatorCacheable
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/project/validator/XmlValidatorManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/project/validator/XmlValidatorManagerTest.java
|
Apache-2.0
|
@Before
public void setup() throws Exception {
timeStamp = System.currentTimeMillis();
}
|
Simple Auto Ramp Policy will be divided to 5 stages
stage 1: 5%
stage 2: 20%
stage 3: 50%
stage 4: 75%
stage 5: 100%
|
setup
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
Apache-2.0
|
@Test
public void Test_DisabledRamp() throws Exception {
Props sysProps = new Props();
Props privateProps = new Props();
RampPolicy policy = new SimpleAutoRampPolicy(sysProps, privateProps);
Project project = new Project(1, PROJECT_ID);
Flow flow = new Flow(FLOW_ID);
ExecutableFlow executableFlow = new ExecutableFlow(project, flow);
ExecutableRamp executableRamp = ExecutableRamp.builder(RAMP_ID, RAMP_POLICY)
.setMetadata(ExecutableRamp.Metadata.builder()
.setMaxFailureToPause(4)
.setMaxFailureToRampDown(3)
.setPercentageScaleForMaxFailure(false)
.build())
.setState(ExecutableRamp.State.builder()
.setStartTime(timeStamp)
.setEndTime(0)
.setLastUpdatedTime(timeStamp)
.setNumOfTrail(6)
.setNumOfSuccess(2)
.setNumOfFailure(0)
.setNumOfIgnored(4)
.setPaused(false)
.setRampStage(100)
.setActive(false)
.build())
.build();
Assert.assertFalse(policy.check(executableFlow, executableRamp));
}
|
Simple Auto Ramp Policy will be divided to 5 stages
stage 1: 5%
stage 2: 20%
stage 3: 50%
stage 4: 75%
stage 5: 100%
|
Test_DisabledRamp
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
Apache-2.0
|
@Test
public void Test_PausedRamp() throws Exception {
Props sysProps = new Props();
Props privateProps = new Props();
RampPolicy policy = new SimpleAutoRampPolicy(sysProps, privateProps);
Project project = new Project(1, PROJECT_ID);
Flow flow = new Flow(FLOW_ID);
ExecutableFlow executableFlow = new ExecutableFlow(project, flow);
ExecutableRamp executableRamp = ExecutableRamp.builder(RAMP_ID, RAMP_POLICY)
.setMetadata(ExecutableRamp.Metadata.builder()
.setMaxFailureToPause(4)
.setMaxFailureToRampDown(3)
.setPercentageScaleForMaxFailure(false)
.build())
.setState(ExecutableRamp.State.builder()
.setStartTime(timeStamp)
.setEndTime(0)
.setLastUpdatedTime(timeStamp)
.setNumOfTrail(6)
.setNumOfSuccess(2)
.setNumOfFailure(0)
.setNumOfIgnored(4)
.setPaused(true)
.setRampStage(5)
.setActive(true)
.build())
.build();
Assert.assertFalse(policy.check(executableFlow, executableRamp));
}
|
Simple Auto Ramp Policy will be divided to 5 stages
stage 1: 5%
stage 2: 20%
stage 3: 50%
stage 4: 75%
stage 5: 100%
|
Test_PausedRamp
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
Apache-2.0
|
@Test
public void Test_ZeroPercentRamp() throws Exception {
Props sysProps = new Props();
Props privateProps = new Props();
RampPolicy policy = new SimpleAutoRampPolicy(sysProps, privateProps);
Project project = new Project(1, PROJECT_ID);
Flow flow = new Flow(FLOW_ID);
ExecutableFlow executableFlow = new ExecutableFlow(project, flow);
ExecutableRamp executableRamp = ExecutableRamp.builder(RAMP_ID, RAMP_POLICY)
.setMetadata(ExecutableRamp.Metadata.builder()
.setMaxFailureToPause(4)
.setMaxFailureToRampDown(3)
.setPercentageScaleForMaxFailure(false)
.build())
.setState(ExecutableRamp.State.builder()
.setStartTime(timeStamp)
.setEndTime(0)
.setLastUpdatedTime(timeStamp)
.setNumOfTrail(6)
.setNumOfSuccess(2)
.setNumOfFailure(0)
.setNumOfIgnored(4)
.setPaused(false)
.setRampStage(0)
.setActive(true)
.build())
.build();
Assert.assertFalse(policy.check(executableFlow, executableRamp));
}
|
Simple Auto Ramp Policy will be divided to 5 stages
stage 1: 5%
stage 2: 20%
stage 3: 50%
stage 4: 75%
stage 5: 100%
|
Test_ZeroPercentRamp
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
Apache-2.0
|
@Test
public void Test_FullRamp() throws Exception {
Props sysProps = new Props();
Props privateProps = new Props();
RampPolicy policy = new SimpleAutoRampPolicy(sysProps, privateProps);
Project project = new Project(1, PROJECT_ID);
Flow flow = new Flow(FLOW_ID);
ExecutableFlow executableFlow = new ExecutableFlow(project, flow);
ExecutableRamp executableRamp = ExecutableRamp.builder(RAMP_ID, RAMP_POLICY)
.setMetadata(ExecutableRamp.Metadata.builder()
.setMaxFailureToPause(4)
.setMaxFailureToRampDown(3)
.setPercentageScaleForMaxFailure(false)
.build())
.setState(ExecutableRamp.State.builder()
.setStartTime(timeStamp)
.setEndTime(0)
.setLastUpdatedTime(timeStamp)
.setNumOfTrail(6)
.setNumOfSuccess(2)
.setNumOfFailure(0)
.setNumOfIgnored(4)
.setPaused(false)
.setRampStage(4)
.setActive(true)
.build())
.build();
Assert.assertTrue(policy.check(executableFlow, executableRamp));
}
|
Simple Auto Ramp Policy will be divided to 5 stages
stage 1: 5%
stage 2: 20%
stage 3: 50%
stage 4: 75%
stage 5: 100%
|
Test_FullRamp
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
Apache-2.0
|
@Test
public void Test_OverflowStageRamp() throws Exception {
Props sysProps = new Props();
Props privateProps = new Props();
RampPolicy policy = new SimpleAutoRampPolicy(sysProps, privateProps);
Project project = new Project(1, PROJECT_ID);
Flow flow = new Flow(FLOW_ID);
ExecutableFlow executableFlow = new ExecutableFlow(project, flow);
ExecutableRamp executableRamp = ExecutableRamp.builder(RAMP_ID, RAMP_POLICY)
.setMetadata(ExecutableRamp.Metadata.builder()
.setMaxFailureToPause(4)
.setMaxFailureToRampDown(3)
.setPercentageScaleForMaxFailure(false)
.build())
.setState(ExecutableRamp.State.builder()
.setStartTime(timeStamp)
.setEndTime(0)
.setLastUpdatedTime(timeStamp)
.setNumOfTrail(6)
.setNumOfSuccess(2)
.setNumOfFailure(0)
.setNumOfIgnored(4)
.setPaused(false)
.setRampStage(6)
.setActive(true)
.build())
.build();
Assert.assertTrue(policy.check(executableFlow, executableRamp));
}
|
Simple Auto Ramp Policy will be divided to 5 stages
stage 1: 5%
stage 2: 20%
stage 3: 50%
stage 4: 75%
stage 5: 100%
|
Test_OverflowStageRamp
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
Apache-2.0
|
@Test
public void Test_NegativeStageRamp() throws Exception {
Props sysProps = new Props();
Props privateProps = new Props();
RampPolicy policy = new SimpleAutoRampPolicy(sysProps, privateProps);
Project project = new Project(1, PROJECT_ID);
Flow flow = new Flow(FLOW_ID);
ExecutableFlow executableFlow = new ExecutableFlow(project, flow);
ExecutableRamp executableRamp = ExecutableRamp.builder(RAMP_ID, RAMP_POLICY)
.setMetadata(ExecutableRamp.Metadata.builder()
.setMaxFailureToPause(4)
.setMaxFailureToRampDown(3)
.setPercentageScaleForMaxFailure(false)
.build())
.setState(ExecutableRamp.State.builder()
.setStartTime(timeStamp)
.setEndTime(0)
.setLastUpdatedTime(timeStamp)
.setNumOfTrail(6)
.setNumOfSuccess(2)
.setNumOfFailure(0)
.setNumOfIgnored(4)
.setPaused(false)
.setRampStage(-1)
.setActive(true)
.build())
.build();
Assert.assertFalse(policy.check(executableFlow, executableRamp));
}
|
Simple Auto Ramp Policy will be divided to 5 stages
stage 1: 5%
stage 2: 20%
stage 3: 50%
stage 4: 75%
stage 5: 100%
|
Test_NegativeStageRamp
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
Apache-2.0
|
@Test
public void Test_StageRampWithoutRampModification() throws Exception {
Props sysProps = new Props();
Props privateProps = new Props();
RampPolicy policy = new SimpleAutoRampPolicy(sysProps, privateProps);
Map<Integer, String> projects = new HashMap();
projects.put(1, "spark-startkit"); // in 5%
projects.put(2, "spark-start-kit2"); // in 20%
projects.put(3, "spark-start-kit3"); // in 45%
projects.put(4, "spark-start-kit4"); // in 70%
projects.put(5, "spark-start-kit5"); // in 95%
for (int stage = 1; stage <= 5; stage++) {
for(Map.Entry<Integer, String> item : projects.entrySet()) {
Project project = new Project(1, item.getValue());
Flow flow = new Flow(FLOW_ID);
ExecutableFlow executableFlow = new ExecutableFlow(project, flow);
ExecutableRamp executableRamp = ExecutableRamp.builder(RAMP_ID, RAMP_POLICY)
.setMetadata(ExecutableRamp.Metadata.builder()
.setMaxFailureToPause(4)
.setMaxFailureToRampDown(3)
.setPercentageScaleForMaxFailure(false)
.build())
.setState(ExecutableRamp.State.builder()
.setStartTime(timeStamp)
.setEndTime(0)
.setLastUpdatedTime(timeStamp)
.setNumOfTrail(6)
.setNumOfSuccess(2)
.setNumOfFailure(0)
.setNumOfIgnored(4)
.setPaused(false)
.setRampStage(stage)
.setActive(true)
.build())
.build();
Assert.assertEquals(item.getKey() <= stage, policy.check(executableFlow, executableRamp));
}
}
}
|
Simple Auto Ramp Policy will be divided to 5 stages
stage 1: 5%
stage 2: 20%
stage 3: 50%
stage 4: 75%
stage 5: 100%
|
Test_StageRampWithoutRampModification
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
Apache-2.0
|
@Test
public void Test_StageRampWithRampModification() throws Exception {
Props sysProps = new Props();
Props privateProps = new Props();
RampPolicy policy = new SimpleAutoRampPolicy(sysProps, privateProps);
Map<Integer, String> projects = new HashMap();
projects.put(1, "spark-startkit"); // in 5%
projects.put(2, "spark-start-kit2"); // in 20%
projects.put(3, "spark-start-kit3"); // in 45%
projects.put(4, "spark-start-kit4"); // in 70%
projects.put(5, "spark-start-kit5"); // in 95%
for (int stage = 1; stage <= 5; stage++) {
for(Map.Entry<Integer, String> item : projects.entrySet()) {
Project project = new Project(1, item.getValue());
Flow flow = new Flow(FLOW_ID);
ExecutableFlow executableFlow = new ExecutableFlow(project, flow);
ExecutableRamp executableRamp = ExecutableRamp.builder(RAMP_ID, RAMP_POLICY)
.setMetadata(ExecutableRamp.Metadata.builder()
.setMaxFailureToPause(4)
.setMaxFailureToRampDown(3)
.setPercentageScaleForMaxFailure(false)
.build())
.setState(ExecutableRamp.State.builder()
.setStartTime(timeStamp - ESCAPED_TIME)
.setEndTime(0)
.setLastUpdatedTime(timeStamp)
.setNumOfTrail(6)
.setNumOfSuccess(2)
.setNumOfFailure(0)
.setNumOfIgnored(4)
.setPaused(false)
.setRampStage(stage)
.setActive(true)
.build())
.build();
Assert.assertEquals(item.getKey() <= stage + 1, policy.check(executableFlow, executableRamp));
}
}
}
|
Simple Auto Ramp Policy will be divided to 5 stages
stage 1: 5%
stage 2: 20%
stage 3: 50%
stage 4: 75%
stage 5: 100%
|
Test_StageRampWithRampModification
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/ramppolicy/SimpleAutoRampPolicyTest.java
|
Apache-2.0
|
private void compare(SlaOption option1, SlaOption option2) {
assertThat(option1.getType()).isEqualTo(option2.getType());
assertThat(option1.getDuration()).isEqualTo(option2.getDuration());
assertThat(option1.getFlowName()).isEqualTo(option2.getFlowName());
assertThat(option1.getJobName()).isEqualTo(option2.getJobName());
assertThat(option1.hasAlert()).isEqualTo(option2.hasAlert());
assertThat(option1.hasKill()).isEqualTo(option2.hasKill());
assertThat(option1.getEmails()).isEqualTo(option2.getEmails());
}
|
Compare if two {@link SlaOption} are the same
|
compare
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/sla/SlaOptionTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/sla/SlaOptionTest.java
|
Apache-2.0
|
@Test
public void testNoCleanupCase1() throws Exception {
final StorageCleaner storageCleaner = new StorageCleaner(new Props(), this.storage,
this.databaseOperator);
assertFalse(storageCleaner.isCleanupPermitted());
}
|
test default behavior. By default no artifacts should be cleaned up.
|
testNoCleanupCase1
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/storage/StorageCleanerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/storage/StorageCleanerTest.java
|
Apache-2.0
|
@Test
public void testNoCleanupCase2() throws Exception {
final Props props = new Props();
props.put(AZKABAN_STORAGE_ARTIFACT_MAX_RETENTION, 10);
final StorageCleaner storageCleaner = new StorageCleaner(props, this.storage,
this.databaseOperator);
assertTrue(storageCleaner.isCleanupPermitted());
storageCleaner.cleanupProjectArtifacts(TEST_PROJECT_ID, new ArrayList<>());
verify(this.storage, never()).deleteProject(anyString());
}
|
test default behavior. By default no artifacts should be cleaned up.
|
testNoCleanupCase2
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/storage/StorageCleanerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/storage/StorageCleanerTest.java
|
Apache-2.0
|
@Test
public void testCleanup() throws Exception {
final Props props = new Props();
props.put(AZKABAN_STORAGE_ARTIFACT_MAX_RETENTION, 1);
final StorageCleaner storageCleaner = new StorageCleaner(props, this.storage,
this.databaseOperator);
assertTrue(storageCleaner.isCleanupPermitted());
storageCleaner.cleanupProjectArtifacts(TEST_PROJECT_ID, Arrays.asList(3));
// Verify that latest artifact cannot be deleted
verify(this.storage, never()).deleteProject("14/14-8.zip");
// Verify that artifact with project version 3 cannot be deleted
verify(this.storage, never()).deleteProject("14/14-9.zip");
// Verify that remaining artifacts should be deleted
verify(this.storage, times(1)).deleteProject("14/14-10.zip");
verify(this.storage, times(1)).deleteProject("14/14-7.zip");
verify(this.databaseOperator, never()).update(SQL_DELETE_RESOURCE_ID, "14/14-8.zip");
verify(this.databaseOperator, never()).update(SQL_DELETE_RESOURCE_ID, "14/14-9.zip");
verify(this.databaseOperator, times(1)).update(SQL_DELETE_RESOURCE_ID, "14/14-10.zip");
// Verify there was no db update due to previous deletion failure
verify(this.databaseOperator, never()).update(SQL_DELETE_RESOURCE_ID, "14/14-7.zip");
}
|
test default behavior. By default no artifacts should be cleaned up.
|
testCleanup
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/storage/StorageCleanerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/storage/StorageCleanerTest.java
|
Apache-2.0
|
@Test
public void periodTimerTest() {
// get a new timechecker, start from now, repeat every minute. should
// evaluate to false now, and true a minute later.
final long baseTimeInMilliSeconds = 1000;
final ReadablePeriod period = TimeUtils.parsePeriodString("10s");
DateTimeUtils.setCurrentMillisFixed(baseTimeInMilliSeconds);
final BasicTimeChecker timeChecker =
new BasicTimeChecker("BasicTimeChecker_1", baseTimeInMilliSeconds, DateTimeZone.UTC, true, true, period, null);
final Condition cond = getCondition(timeChecker);
assertFalse(cond.isMet());
DateTimeUtils.setCurrentMillisFixed(baseTimeInMilliSeconds + 11 * 1000);
assertTrue(cond.isMet());
cond.resetCheckers();
assertFalse(cond.isMet());
DateTimeUtils.setCurrentMillisFixed(baseTimeInMilliSeconds + 22 * 1000);
assertTrue(cond.isMet());
DateTimeUtils.setCurrentMillisSystem();
}
|
This test manipulates global states (time) in org.joda.time.DateTimeUtils . Thus this test can
run in parallel with tests that do the same.
|
periodTimerTest
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
Apache-2.0
|
@Test
public void testPSTtoPDTunderUTC() {
// Use a Date that is before the date in cron expression (i.e. Before March 8 2020)
final DateTime pastTime = new DateTime(2020, 1, 1, 00, 00, 0, DateTimeZone.UTC);
// Cron expression for 10:30 am UTC on March 8 2020
final String cronExpression = "0 30 10 8 3 ? 2020";
final BasicTimeChecker timeChecker =
new BasicTimeChecker("BasicTimeChecker_1", pastTime.getMillis(), DateTimeZone.UTC, true, true, null,
cronExpression);
System.out.println("getNextCheckTime = " + timeChecker.getNextCheckTime());
final Condition cond = getCondition(timeChecker);
final DateTime spring2020UTC = new DateTime(2020, 3, 8, 10, 30, 0, DateTimeZone.UTC);
final DateTime spring2020PDT = new DateTime(2020, 3, 8, 3, 30, 0, DateTimeZone.forID("America/Los_Angeles"));
assertTrue(cond.getNextCheckTime() == spring2020UTC.getMillis());
assertTrue(cond.getNextCheckTime() == spring2020PDT.getMillis());
}
|
Test when PST-->PDT happens in 2020. -8:00 -> -7:00 See details why confusion happens during
this change: https://en.wikipedia.org/wiki/Pacific_Time_Zone
This test demonstrates that if the cron is under UTC settings, When daylight saving change
occurs, 2:30 will be changed to 3:30 at that day.
|
testPSTtoPDTunderUTC
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
Apache-2.0
|
@Test
public void testPSTtoPDTdst2() {
// Use a Date that is before the date in cron expression (i.e. Before March 8 2020)
final DateTime pastTime = new DateTime(2020, 1, 1, 00, 00, 0, DateTimeZone.UTC);
final String cronExpression = "0 30 2 8,9 3 ? 2020";
final BasicTimeChecker timeChecker =
new BasicTimeChecker("BasicTimeChecker_1", pastTime.getMillis(), DateTimeZone.forID("America/Los_Angeles"),
true, true, null, cronExpression);
System.out.println("getNextCheckTime = " + timeChecker.getNextCheckTime());
final Condition cond = getCondition(timeChecker);
final DateTime aTime = new DateTime(2020, 3, 9, 2, 30, 0, DateTimeZone.forID("America/Los_Angeles"));
assertTrue(cond.getNextCheckTime() == aTime.getMillis());
}
|
Test when PST-->PDT happens in 2020. -8:00 -> -7:00 See details why confusion happens during
this change: https://en.wikipedia.org/wiki/Pacific_Time_Zone
This test demonstrates that 2:30 AM will not happen during the daylight saving day on Cron
settings under PDT/PST. Since we let the cron triggered both at March 8th, and 9th, it will
execute at March 9th.
|
testPSTtoPDTdst2
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
Apache-2.0
|
@Test
public void testPDTtoPSTdst1() {
// Use a Date that is before the date in cron expression (i.e. Before Nov 1 2020)
final DateTime pastTime = new DateTime(2020, 1, 1, 00, 00, 0, DateTimeZone.UTC);
// 9:00 UTC == 1:00 PST (difference is 8 hours)
final String cronExpression = "0 0 1 4,5 11 ? 2029";
final BasicTimeChecker timeChecker =
new BasicTimeChecker("BasicTimeChecker_1", pastTime.getMillis(), DateTimeZone.forID("America/Los_Angeles"),
true, true, null, cronExpression);
System.out.println("getNextCheckTime = " + timeChecker.getNextCheckTime());
final Condition cond = getCondition(timeChecker);
final DateTime winter2020 = new DateTime(2029, 11, 4, 9, 0, 0, DateTimeZone.UTC);
final DateTime winter2020_2 = new DateTime(2029, 11, 4, 1, 0, 0, DateTimeZone.forID("America/Los_Angeles"));
final DateTime winter2020_3 = new DateTime(2029, 11, 4, 2, 0, 0, DateTimeZone.forID("America/Los_Angeles"));
assertTrue(cond.getNextCheckTime() == winter2020.getMillis());
// Both 1 and 2 o'clock can not pass the test. Based on milliseconds we got,
// winter2020_2.getMillis() == 11/1/2020, 1:00:00 AM GMT-7:00 DST
// winter2020_3.getMillis() == 11/1/2020, 2:00:00 AM GMT-8:00
// Both time doesn't match the second 1:00 AM
assertFalse(cond.getNextCheckTime() == winter2020_2.getMillis());
assertFalse(cond.getNextCheckTime() == winter2020_3.getMillis());
}
|
Test when PDT-->PST happens in 2020. -7:00 -> -8:00 See details why confusion happens during
this change: https://en.wikipedia.org/wiki/Pacific_Time_Zone
This test cronDayLightPacificWinter1 is in order to compare against the
cronDayLightPacificWinter2.
In this Test, we let job run at 1:00 at Nov.1st, 2020. We know that we will have two 1:00 at
that day. The test shows that the first 1:00 is skipped at that day. Schedule will still be
executed once on that day.
|
testPDTtoPSTdst1
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
Apache-2.0
|
@Test
public void testPDTtoPSTdst2() {
// Use a Date that is before the date in cron expression (i.e. Before Nov 1 2020)
final DateTime pastTime = new DateTime(2020, 1, 1, 00, 00, 0, DateTimeZone.UTC);
// 7:59 UTC == 0:59 PDT (difference is 7 hours)
final String cronExpression = "0 59 0 4,5 11 ? 2029";
final BasicTimeChecker timeChecker =
new BasicTimeChecker("BasicTimeChecker_1", pastTime.getMillis(), DateTimeZone.forID("America/Los_Angeles"),
true, true, null, cronExpression);
System.out.println("getNextCheckTime = " + timeChecker.getNextCheckTime());
final Condition cond = getCondition(timeChecker);
// 7:59 UTC == 0:59 PDT (difference is 7 hours)
final DateTime winter2020 = new DateTime(2029, 11, 4, 7, 59, 0, DateTimeZone.UTC);
final DateTime winter2020_2 = new DateTime(2029, 11, 4, 0, 59, 0, DateTimeZone.forID("America/Los_Angeles"));
// Local time remains the same.
assertTrue(cond.getNextCheckTime() == winter2020.getMillis());
assertTrue(cond.getNextCheckTime() == winter2020_2.getMillis());
}
|
Test when PDT-->PST happens in 2020. -7:00 -> -8:00 See details why confusion happens during
this change: https://en.wikipedia.org/wiki/Pacific_Time_Zone
This test cronDayLightPacificWinter2 is in order to be compared against the
cronDayLightPacificWinter1.
In this Test, we let job run at 0:59 at Nov.1st, 2020. it shows that it is 7:59 UTC The test
shows 7:59 UTC jump to 9:00 UTC.
|
testPDTtoPSTdst2
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
Apache-2.0
|
@Test
public void testPDTtoPSTdst3() {
// Use a Date that is before the date in cron expression (i.e. Before Nov 1 2020)
final DateTime pastTime = new DateTime(2020, 1, 1, 00, 00, 0, DateTimeZone.UTC);
// 9:30 UTC == 1:30 PST (difference is 8 hours)
final String cronExpression = "0 30 1 4,5 11 ? 2029";
final BasicTimeChecker timeChecker =
new BasicTimeChecker("BasicTimeChecker_1", pastTime.getMillis(), DateTimeZone.forID("America/Los_Angeles"),
true, true, null, cronExpression);
System.out.println("getNextCheckTime = " + timeChecker.getNextCheckTime());
final Condition cond = getCondition(timeChecker);
// 9:30 UTC == 1:30 PST (difference is 8 hours)
final DateTime winter2020 = new DateTime(2029, 11, 4, 9, 30, 0, DateTimeZone.UTC);
final DateTime winter2020_2 = new DateTime(2029, 11, 4, 1, 30, 0, DateTimeZone.forID("America/Los_Angeles"));
final DateTime winter2020_3 = new DateTime(2029, 11, 4, 2, 30, 0, DateTimeZone.forID("America/Los_Angeles"));
assertTrue(cond.getNextCheckTime() == winter2020.getMillis());
// Both 1:30 and 2:30 can not pass the test.
assertFalse(cond.getNextCheckTime() == winter2020_2.getMillis());
assertFalse(cond.getNextCheckTime() == winter2020_3.getMillis());
}
|
Test when PDT-->PST happens in 2020. -7:00 -> -8:00 See details why confusion happens during
this change: https://en.wikipedia.org/wiki/Pacific_Time_Zone
This test is a supplement to cronDayLightPacificWinter1.
Still, we let job run at 1:30 at Nov.1st, 2020. We know that we will have two 1:30 at that day.
The test shows the 1:30 at that day will be based on PST, not PDT. It means that the first 1:30
is skipped at that day.
|
testPDTtoPSTdst3
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
Apache-2.0
|
@Test
public void testMissedScheduleExpiredTrigger() {
// first check date is 2022/01/01 00:00
final DateTime pastTime = new DateTime(2022, 1, 1, 00, 00, 0, DateTimeZone.UTC);
// trigger every 10 minute at first hour(00:00:00 ~ 00:59:59) of 2022/01/01
final String cronExpression = "0 0/10 0 1 JAN ? 2022";
final BasicTimeChecker timeChecker =
new BasicTimeChecker("BasicTimeChecker_1", pastTime.getMillis(), DateTimeZone.UTC, pastTime.getMillis(), true,
true, null, cronExpression);
final List<Long> missed = timeChecker.getMissedCheckTimesBeforeNow();
Assertions.assertThat(missed.size()).isEqualTo(0);
Assertions.assertThat(timeChecker.getNextCheckTime()).isEqualTo(pastTime.getMillis());
}
|
Test when PDT-->PST happens in 2020. -7:00 -> -8:00 See details why confusion happens during
this change: https://en.wikipedia.org/wiki/Pacific_Time_Zone
This test is a supplement to cronDayLightPacificWinter1.
Still, we let job run at 1:30 at Nov.1st, 2020. We know that we will have two 1:30 at that day.
The test shows the 1:30 at that day will be based on PST, not PDT. It means that the first 1:30
is skipped at that day.
|
testMissedScheduleExpiredTrigger
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
Apache-2.0
|
@Test
public void testMissedScheduleRecoverFromDB() {
final DateTime now = DateTime.now();
// first check time was 1s ago
final DateTime firstCheck = now.minusSeconds(1);
// trigger every 30 minute
final String cronExpression = "0 */30 * ? * * *";
final Date nextValidTime = Utils.parseCronExpression(cronExpression, DateTimeZone.forID("America/Los_Angeles"))
.getNextValidTimeAfter(now.toDate());
final BasicTimeChecker timeChecker =
new BasicTimeChecker("BasicTimeChecker_1", firstCheck.getMillis(), DateTimeZone.forID("America/Los_Angeles"),
firstCheck.getMillis(), true, true, null, cronExpression);
timeChecker.updateNextCheckTime();
final List<Long> missed = timeChecker.getMissedCheckTimesBeforeNow();
Assertions.assertThat(missed.size()).isEqualTo(1);
Assertions.assertThat(missed.get(0)).isEqualTo(firstCheck.getMillis());
Assertions.assertThat(timeChecker.getNextCheckTime()).isEqualTo(nextValidTime.getTime());
}
|
Test when PDT-->PST happens in 2020. -7:00 -> -8:00 See details why confusion happens during
this change: https://en.wikipedia.org/wiki/Pacific_Time_Zone
This test is a supplement to cronDayLightPacificWinter1.
Still, we let job run at 1:30 at Nov.1st, 2020. We know that we will have two 1:30 at that day.
The test shows the 1:30 at that day will be based on PST, not PDT. It means that the first 1:30
is skipped at that day.
|
testMissedScheduleRecoverFromDB
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
Apache-2.0
|
@Test
public void testMissedScheduleOnReset() {
final DateTime now = DateTime.now();
// first check time was 1s ago
final DateTime firstCheck = now.minusSeconds(1);
// trigger every 30 minute
final String cronExpression = "0 */30 * ? * * *";
final Date nextValidTime = Utils.parseCronExpression(cronExpression, DateTimeZone.forID("America/Los_Angeles"))
.getNextValidTimeAfter(now.toDate());
final BasicTimeChecker timeChecker =
new BasicTimeChecker("BasicTimeChecker_1", firstCheck.getMillis(), DateTimeZone.forID("America/Los_Angeles"),
firstCheck.getMillis(), true, true, null, cronExpression);
timeChecker.reset();
final List<Long> missed = timeChecker.getMissedCheckTimesBeforeNow();
Assertions.assertThat(missed.size()).isEqualTo(0);
Assertions.assertThat(timeChecker.getNextCheckTime()).isEqualTo(nextValidTime.getTime());
}
|
Test when PDT-->PST happens in 2020. -7:00 -> -8:00 See details why confusion happens during
this change: https://en.wikipedia.org/wiki/Pacific_Time_Zone
This test is a supplement to cronDayLightPacificWinter1.
Still, we let job run at 1:30 at Nov.1st, 2020. We know that we will have two 1:30 at that day.
The test shows the 1:30 at that day will be based on PST, not PDT. It means that the first 1:30
is skipped at that day.
|
testMissedScheduleOnReset
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/trigger/builtin/BasicTimeCheckerTest.java
|
Apache-2.0
|
@Test
public void testUploadProjectFlag() throws Exception {
final Permission permission = new Permission();
permission.addPermission(new Type[]{Type.UPLOADPROJECTS});
final int flags = permission.toFlags();
final Permission permission2 = new Permission(flags);
assertThat(permission2.isPermissionSet(Type.UPLOADPROJECTS)).isTrue();
assertThat(permission.equals(permission2)).isTrue();
permission.removePermissions(new Type[]{Type.UPLOADPROJECTS});
final Type[] allPermissions = new Type[]{
Type.READ, Type.WRITE, Type.EXECUTE, Type.METRICS, Type.SCHEDULE, Type.CREATEPROJECTS
};
permission.addPermission(allPermissions);
assertThat(permission.isPermissionSet(Type.UPLOADPROJECTS)).isFalse();
}
|
Verify that the binary bit for UPLOADPROJECTS is not turned on by setting the other
permissions.
|
testUploadProjectFlag
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/user/PermissionTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/user/PermissionTest.java
|
Apache-2.0
|
@Test
public void testFilePropNotSet() throws Exception {
final Props props = new Props(this.baseProps);
// Should throw
try {
final XmlUserManager manager = new XmlUserManager(props, () -> this.fileWatcher);
} catch (final UndefinedPropertyException e) {
return;
}
fail("XmlUserManager should throw an exception when the file property isn't set");
}
|
Testing for when the xml path isn't set in properties.
|
testFilePropNotSet
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
Apache-2.0
|
@Test
public void testDoNotExist() throws Exception {
final Props props = new Props(this.baseProps);
props.put(XmlUserManager.XML_FILE_PARAM, "unit/test-conf/doNotExist.xml");
try {
final UserManager manager = new XmlUserManager(props, () -> this.fileWatcher);
} catch (final RuntimeException e) {
return;
}
fail("XmlUserManager should throw an exception when the file doesn't exist");
}
|
Testing for when the xml path doesn't exist.
|
testDoNotExist
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
Apache-2.0
|
private Path getFilePath(final String testName) throws IOException {
final URL configURL = Resources.getResource("test-conf/azkaban-users-test1.xml");
final String origPathStr = configURL.getPath();
// Create a new directory and copy the file in it.
final Path workDir = temporaryFolder.newFolder().toPath();
// Copy the file to keep original file unmodified
final String path = workDir.toString() + "/" + testName + ".xml";
final Path filePath = Paths.get(path);
Files.copy(Paths.get(origPathStr), filePath, StandardCopyOption.REPLACE_EXISTING);
return filePath;
}
|
Testing for when the xml path doesn't exist.
|
getFilePath
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
Apache-2.0
|
@Test
public void testAutoReload() throws Exception {
final Props props = new Props(this.baseProps);
final Path filePath = getFilePath("testAutoReload");
props.put(XmlUserManager.XML_FILE_PARAM, filePath.toString());
final CountDownLatch managerLoaded = setupMocks(filePath);
final UserManager manager = new XmlUserManager(props, () -> this.fileWatcher);
// Get the user8 from existing XML with password == password8
User user8 = manager.getUser("user8", "password8");
// Modify the password for user8
// TODO : djaiswal : Find a better way to modify XML
final List<String> lines = new ArrayList<>();
for (final String line : Files.readAllLines(filePath)) {
if (line.contains("password8")) {
lines.add(line.replace("password8", "passwordModified"));
} else {
lines.add(line);
}
}
// Make sure the file gets reverted back.
// Update the file
Files.write(filePath, lines);
managerLoaded.countDown();
// Wait until login fails with the old password
Awaitility.await().atMost(60L, TimeUnit.SECONDS).
pollInterval(100L, TimeUnit.MILLISECONDS).until(
() -> {
User user;
try {
user = manager.getUser("user8", "password8");
} catch (final UserManagerException e) {
user = null;
}
return user == null;
});
// Assert that login succeeds with the modified password
user8 = manager.getUser("user8", "passwordModified");
assertEquals("user8", user8.getUserId());
Mockito.verify(this.fileWatcher, Mockito.timeout(10_000L).atLeast(3)).take();
}
|
Test auto reload of user XML
|
testAutoReload
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
Apache-2.0
|
@Test
public void testAutoReloadFail() throws Exception {
final Props props = new Props(this.baseProps);
final Path filePath = getFilePath("testAutoReloadFail");
props.put(XmlUserManager.XML_FILE_PARAM, filePath.toString());
final CountDownLatch managerLoaded = setupMocks(filePath);
final UserManager manager;
try {
manager = new XmlUserManager(props, () -> this.fileWatcher);
} catch (final RuntimeException e) {
fail("Should have found the xml file");
return;
}
// Get the user8 from existing XML with password == password8
final User user8 = manager.getUser("user8", "password8");
assertEquals("user8", user8.getUserId());
// Update the file to make it empty.
Files.write(filePath, new byte[0], StandardOpenOption.TRUNCATE_EXISTING);
managerLoaded.countDown();
// Make sure the file gets reverted back.
managerLoaded.await(10L, TimeUnit.SECONDS);
assertEquals(0, managerLoaded.getCount());
// assert that watcher.take() was still called after the failed reload
Mockito.verify(this.fileWatcher, Mockito.timeout(20_000L).atLeast(3)).take();
// Nothing should've changed, login should succeed as originally
final User user = manager.getUser("user8", "password8");
assertEquals("user8", user.getUserId());
}
|
Negative test auto reload of user XML
|
testAutoReloadFail
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
Apache-2.0
|
@Ignore
@Test
public void testBasicLoad() throws Exception {
final Props props = new Props(this.baseProps);
props.put(XmlUserManager.XML_FILE_PARAM,
"unit/test-conf/azkaban-users-test1.xml");
UserManager manager = null;
try {
manager = new XmlUserManager(props, () -> this.fileWatcher);
} catch (final RuntimeException e) {
e.printStackTrace();
fail("XmlUserManager should've found file azkaban-users.xml");
}
try {
manager.getUser("user0", null);
} catch (final UserManagerException e) {
System.out.println("Exception handled correctly: " + e.getMessage());
}
try {
manager.getUser(null, "etw");
} catch (final UserManagerException e) {
System.out.println("Exception handled correctly: " + e.getMessage());
}
try {
manager.getUser("user0", "user0");
} catch (final UserManagerException e) {
System.out.println("Exception handled correctly: " + e.getMessage());
}
try {
manager.getUser("user0", "password0");
} catch (final UserManagerException e) {
e.printStackTrace();
fail("XmlUserManager should've returned a user.");
}
final User user0 = manager.getUser("user0", "password0");
checkUser(user0, "role0", "group0");
final User user1 = manager.getUser("user1", "password1");
checkUser(user1, "role0,role1", "group1,group2");
final User user2 = manager.getUser("user2", "password2");
checkUser(user2, "role0,role1,role2", "group1,group2,group3");
final User user3 = manager.getUser("user3", "password3");
checkUser(user3, "role1,role2", "group1,group2");
final User user4 = manager.getUser("user4", "password4");
checkUser(user4, "role1,role2", "group1,group2");
final User user5 = manager.getUser("user5", "password5");
checkUser(user5, "role1,role2", "group1,group2");
final User user6 = manager.getUser("user6", "password6");
checkUser(user6, "role3,role2", "group1,group2");
final User user7 = manager.getUser("user7", "password7");
checkUser(user7, "", "group1");
final User user8 = manager.getUser("user8", "password8");
checkUser(user8, "role3", "");
final User user9 = manager.getUser("user9", "password9");
checkUser(user9, "", "");
}
|
Negative test auto reload of user XML
|
testBasicLoad
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
Apache-2.0
|
private CountDownLatch setupMocks(final Path filePath) throws IOException, InterruptedException {
// mock registering the parent folder, but only if registered with the right args
Mockito.doReturn(this.watchKey).when(this.fileWatcher).register(
Paths.get(filePath.getParent().toString()));
Mockito.doReturn(this.watchKey).when(this.fileWatcher).take();
Mockito.doReturn(filePath).when(this.watchEvent).context();
// thread-safe latch to allow releasing an event
final CountDownLatch managerLoaded = new CountDownLatch(2);
Mockito.doAnswer(invocation -> {
// avoid busy-looping in UserUtils.java
long sleepMillis = managerLoaded.getCount() == 0 ? 5_000L : 10L;
if (managerLoaded.getCount() == 1) {
// go back to returning an empty list
managerLoaded.countDown();
return Collections.singletonList(this.watchEvent);
}
Thread.sleep(sleepMillis);
return Collections.emptyList();
}).when(this.fileWatcher).pollEvents(this.watchKey);
return managerLoaded;
}
|
Negative test auto reload of user XML
|
setupMocks
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
Apache-2.0
|
private void checkUser(final User user, final String rolesStr, final String groupsStr) {
// Validating roles
final HashSet<String> roleSet = new HashSet<>(user.getRoles());
if (rolesStr.isEmpty()) {
if (!roleSet.isEmpty()) {
String outputRoleStr = "";
for (final String role : roleSet) {
outputRoleStr += role + ",";
}
throw new RuntimeException("Roles mismatch for " + user.getUserId()
+ ". Expected roles to be empty but got " + outputRoleStr);
}
} else {
String outputRoleStr = "";
for (final String role : roleSet) {
outputRoleStr += role + ",";
}
final String[] splitRoles = rolesStr.split(",");
final HashSet<String> expectedRoles = new HashSet<>();
for (final String role : splitRoles) {
if (!roleSet.contains(role)) {
throw new RuntimeException("Roles mismatch for user "
+ user.getUserId() + " role " + role + ". Expected roles to "
+ rolesStr + " but got " + outputRoleStr);
}
expectedRoles.add(role);
}
for (final String role : roleSet) {
if (!expectedRoles.contains(role)) {
throw new RuntimeException("Roles mismatch for user "
+ user.getUserId() + " role " + role + ". Expected roles to "
+ rolesStr + " but got " + outputRoleStr);
}
}
}
final HashSet<String> groupSet = new HashSet<>(user.getGroups());
if (groupsStr.isEmpty()) {
if (!groupSet.isEmpty()) {
String outputGroupStr = "";
for (final String role : roleSet) {
outputGroupStr += role + ",";
}
throw new RuntimeException("Roles mismatch for " + user.getUserId()
+ ". Expected roles to be empty but got " + outputGroupStr);
}
} else {
String outputGroupStr = "";
for (final String group : groupSet) {
outputGroupStr += group + ",";
}
final String[] splitGroups = groupsStr.split(",");
final HashSet<String> expectedGroups = new HashSet<>();
for (final String group : splitGroups) {
if (!groupSet.contains(group)) {
throw new RuntimeException("Groups mismatch for user "
+ user.getUserId() + " group " + group + ". Expected groups to "
+ groupsStr + " but got " + outputGroupStr);
}
expectedGroups.add(group);
}
for (final String group : groupSet) {
if (!expectedGroups.contains(group)) {
throw new RuntimeException("Groups mismatch for user "
+ user.getUserId() + " group " + group + ". Expected groups to "
+ groupsStr + " but got " + outputGroupStr);
}
}
}
}
|
Negative test auto reload of user XML
|
checkUser
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/user/XmlUserManagerTest.java
|
Apache-2.0
|
@Test
public void testEncodingToUFT8() {
assertTrue(ExternalLinkUtils.encodeToUTF8(" ").equals("%20"));
assertTrue(ExternalLinkUtils.encodeToUTF8("+").equals("%2B"));
assertTrue(ExternalLinkUtils.encodeToUTF8("/").equals("%2F"));
assertTrue(ExternalLinkUtils.encodeToUTF8(":").equals("%3A"));
assertTrue(ExternalLinkUtils.encodeToUTF8("?").equals("%3F"));
assertTrue(ExternalLinkUtils.encodeToUTF8("=").equals("%3D"));
}
|
Test validates that when we encode URLs to UTF-8, it does not give us incorrect encodings.
|
testEncodingToUFT8
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/ExternalLinkUtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/ExternalLinkUtilsTest.java
|
Apache-2.0
|
@Test
public void testParseExternalLinks() {
final Map<String, Object> params = new HashMap<>();
params.put("level", ExternalLinkScope.FLOW.getName());
params.put("topic", "topic1");
final String flowLevelExternalLinkTopics =
StrSubstitutor.replace(ConfigurationKeys.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPICS, params,
"${", "}");
final String flowLevelExternalLinkTopic1Url =
StrSubstitutor.replace(ConfigurationKeys.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC_URL, params,
"${", "}");
final String flowLevelExternalLinkTopic1Label =
StrSubstitutor.replace(ConfigurationKeys.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC_LABEL, params,
"${", "}");
params.put("level", ExternalLinkScope.JOB.getName());
params.put("topic", "jobTopic1");
final String jobLevelExternalLinkTopics =
StrSubstitutor.replace(ConfigurationKeys.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPICS, params,
"${", "}");
final String jobLevelExternalLinkTopic1Url =
StrSubstitutor.replace(ConfigurationKeys.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC_URL, params,
"${", "}");
final String jobLevelExternalLinkTopic1Label =
StrSubstitutor.replace(ConfigurationKeys.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC_LABEL, params,
"${", "}");
params.put("topic", "jobMisconfiguredTopic");
final String jobLevelExternalLinkMisconfiguredTopicUrl =
StrSubstitutor.replace(ConfigurationKeys.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC_URL, params,
"${", "}");
final ImmutableMap<String,String> confs = ImmutableMap.<String, String>builder()
.put(flowLevelExternalLinkTopics, "topic1,notConfiguredTopic, topic1")
.put(flowLevelExternalLinkTopic1Url,
"http://url.com/${exec_id}/{$job_id}/${webserver_host}?url=${url}")
.put(flowLevelExternalLinkTopic1Label, "Topic1Label")
.put(jobLevelExternalLinkTopics, "jobTopic1, jobMisconfiguredTopic")
.put(jobLevelExternalLinkTopic1Url,
"http://joburl.com/${exec_id}/{$job_id}/${webserver_host}?url=${url}")
.put(jobLevelExternalLinkTopic1Label, "JobTopic1Label")
.put(jobLevelExternalLinkMisconfiguredTopicUrl, "http://joburl.com/u=${url}")
.build();
final Props azkabanProps = new Props(null, confs);
// parse flow level external link configs
final List<ExternalLink> expectedFlowLinks = ImmutableList.of(
new ExternalLink("topic1", "Topic1Label",
"http://url.com/${exec_id}/{$job_id}/${webserver_host}?url=${url}", true)
);
final List<ExternalLink> parsedLinks = ExternalLinkUtils.parseExternalLinks(azkabanProps, ExternalLinkScope.FLOW);
Assert.assertEquals(expectedFlowLinks.size(), 1);
Assert.assertEquals(expectedFlowLinks, parsedLinks);
// parse job level external link configs
final List<ExternalLink> expectedJobLinks = ImmutableList.of(
new ExternalLink("jobTopic1", "JobTopic1Label",
"http://joburl.com/${exec_id}/{$job_id}/${webserver_host}?url=${url}", true)
);
final List<ExternalLink> parsedJobLinks = ExternalLinkUtils.parseExternalLinks(azkabanProps,
ExternalLinkScope.JOB);
Assert.assertEquals(expectedJobLinks.size(), 1);
Assert.assertEquals(expectedJobLinks, parsedJobLinks);
}
|
Test validates that when we encode URLs to UTF-8, it does not give us incorrect encodings.
|
testParseExternalLinks
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/ExternalLinkUtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/ExternalLinkUtilsTest.java
|
Apache-2.0
|
@Test
public void testBuildExternalLinkUrl() {
final HttpServletRequest mockRequest = mock(HttpServletRequest.class);
when(mockRequest.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8081/executor"));
when(mockRequest.getQueryString()).thenReturn("execid=1");
when(mockRequest.getServerName()).thenReturn("localhost");
String templateUrl1 = "http://url.com/params?p=";
for(ExternalLinkParams p : ExternalLinkParams.values()) { // Enum.values() follow declaration order
templateUrl1 += "|${" + p.getName() + "}";
}
final String expectedUrl1 = String.format("http://url.com/params?p=|12345|myJob|localhost|%s",
ExternalLinkUtils.encodeToUTF8("http://localhost:8081/executor?execid=1"));
String url = ExternalLinkUtils.buildExternalLinkUrl(templateUrl1, mockRequest, 12345,
"myJob");
Assert.assertEquals(expectedUrl1, url);
final String templateUrl2 = "http://url.com/params?e=${exec_id}&u=${url}";
final String expectedUrl2 = String.format("http://url.com/params?e=12345&u=%s",
ExternalLinkUtils.encodeToUTF8("http://localhost:8081/executor?execid=1"));
url = ExternalLinkUtils.buildExternalLinkUrl(templateUrl2, mockRequest, 12345,
"myJob");
Assert.assertEquals(expectedUrl2, url);
// empty template url
url = ExternalLinkUtils.buildExternalLinkUrl("", mockRequest, 12345,
"myJob");
Assert.assertEquals("", url);
}
|
Test validates that when we encode URLs to UTF-8, it does not give us incorrect encodings.
|
testBuildExternalLinkUrl
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/ExternalLinkUtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/ExternalLinkUtilsTest.java
|
Apache-2.0
|
@Before
public void beforeTest() {
this.layout.setConversionPattern("%m");
}
|
Test output of PatternLayoutEscapedTest It should be appending stack traces, escaping new lines,
quotes, tabs and backslashes This is necessary when we are logging these messages out as JSON
objects
|
beforeTest
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
Apache-2.0
|
@Test
public void testWithException() {
try {
throw new Exception("This is an exception");
} catch (final Exception e) {
final LoggingEvent event = createEventWithException("There was an exception", e);
// Stack trace might change if the codebase changes, but this prefix should always remain the same
assertTrue(this.layout.format(event)
.startsWith("There was an exception\\njava.lang.Exception: This is an exception"));
}
}
|
Test output of PatternLayoutEscapedTest It should be appending stack traces, escaping new lines,
quotes, tabs and backslashes This is necessary when we are logging these messages out as JSON
objects
|
testWithException
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
Apache-2.0
|
@Test
public void testNewLine() {
final LoggingEvent event = createMessageEvent("This message contains \n new lines");
assertTrue(this.layout.format(event).equals("This message contains \\n new lines"));
}
|
Test output of PatternLayoutEscapedTest It should be appending stack traces, escaping new lines,
quotes, tabs and backslashes This is necessary when we are logging these messages out as JSON
objects
|
testNewLine
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
Apache-2.0
|
@Test
public void testQuote() {
final LoggingEvent event = createMessageEvent("This message contains \" quotes");
assertTrue(this.layout.format(event).equals("This message contains \\\" quotes"));
}
|
Test output of PatternLayoutEscapedTest It should be appending stack traces, escaping new lines,
quotes, tabs and backslashes This is necessary when we are logging these messages out as JSON
objects
|
testQuote
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
Apache-2.0
|
@Test
public void testTab() {
final LoggingEvent event = createMessageEvent("This message contains a tab \t");
assertTrue(this.layout.format(event).equals("This message contains a tab \\t"));
}
|
Test output of PatternLayoutEscapedTest It should be appending stack traces, escaping new lines,
quotes, tabs and backslashes This is necessary when we are logging these messages out as JSON
objects
|
testTab
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
Apache-2.0
|
@Test
public void testBackSlash() {
final LoggingEvent event = createMessageEvent("This message contains a backslash \\");
assertTrue(this.layout.format(event).equals("This message contains a backslash \\\\"));
}
|
Test output of PatternLayoutEscapedTest It should be appending stack traces, escaping new lines,
quotes, tabs and backslashes This is necessary when we are logging these messages out as JSON
objects
|
testBackSlash
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
Apache-2.0
|
private LoggingEvent createMessageEvent(final String message) {
return createEventWithException(message, null);
}
|
Test output of PatternLayoutEscapedTest It should be appending stack traces, escaping new lines,
quotes, tabs and backslashes This is necessary when we are logging these messages out as JSON
objects
|
createMessageEvent
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
Apache-2.0
|
private LoggingEvent createEventWithException(final String message, final Exception e) {
return new LoggingEvent(this.getClass().getCanonicalName(),
this.logger,
0,
Level.toLevel("INFO"),
message,
e);
}
|
Test output of PatternLayoutEscapedTest It should be appending stack traces, escaping new lines,
quotes, tabs and backslashes This is necessary when we are logging these messages out as JSON
objects
|
createEventWithException
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/PatternLayoutEscapedTest.java
|
Apache-2.0
|
public static User getTestUser() {
return new User("testUser");
}
|
Commonly used utils method for unit/integration tests
|
getTestUser
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
Apache-2.0
|
public static ExecutableFlow createTestExecutableFlow(final String projectName,
final String flowName, final DispatchMethod dispatchMethod) throws IOException {
final File jsonFlowFile = ExecutionsTestUtil.getFlowFile(projectName, flowName + ".flow");
final HashMap<String, Object> flowObj =
(HashMap<String, Object>) JSONUtils.parseJSONFromFile(jsonFlowFile);
final Flow flow = Flow.flowFromObject(flowObj);
final Project project = new Project(1, "flow");
final HashMap<String, Flow> flowMap = new HashMap<>();
flowMap.put(flow.getId(), flow);
project.setFlows(flowMap);
final ExecutableFlow execFlow = new ExecutableFlow(project, flow);
execFlow.setDispatchMethod(dispatchMethod);
return execFlow;
}
|
Commonly used utils method for unit/integration tests
|
createTestExecutableFlow
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
Apache-2.0
|
public static ExecutableFlow createTestExecutableFlowFromYaml(final String projectName,
final String flowName) throws IOException {
final Project project = new Project(11, projectName);
final DirectoryYamlFlowLoader loader = new DirectoryYamlFlowLoader(new Props());
loader.loadProjectFlow(project, ExecutionsTestUtil.getFlowDir(projectName));
project.setFlows(loader.getFlowMap());
project.setVersion(123);
final Flow flow = project.getFlow(flowName);
return new ExecutableFlow(project, flow);
}
|
Commonly used utils method for unit/integration tests
|
createTestExecutableFlowFromYaml
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
Apache-2.0
|
public static UserManager createTestXmlUserManager() {
final Props props = new Props();
props.put(XmlUserManager.XML_FILE_PARAM, ExecutionsTestUtil.getDataRootDir()
+ "azkaban-users.xml");
final UserManager manager = new XmlUserManager(props);
return manager;
}
|
Commonly used utils method for unit/integration tests
|
createTestXmlUserManager
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
Apache-2.0
|
public static String readResource(final String name, final Object parent) throws IOException {
try (final InputStream is = parent.getClass().getResourceAsStream(name)) {
return IOUtils.toString(is, Charsets.UTF_8).trim();
}
}
|
Reads a resource into a String
@param name Relative path to the resource (relative to the parent object's package)
@param parent Instance of the class to use in finding the resource. The resource is looked up in the same package
where the class of the parent object is in.
@return Resource content as a String
@throws IOException if an I/O error occurs
|
readResource
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
Apache-2.0
|
public static Project getEmbeddedTestProject(){
final DirectoryFlowLoader loader = new DirectoryFlowLoader(new Props());
final Project project = new Project(11, "myTestProject");
loader.loadProjectFlow(project, ExecutionsTestUtil.getFlowDir("embedded"));
assert loader.getErrors().size() == 0;
project.setFlows(loader.getFlowMap());
project.setVersion(123);
return project;
}
|
Reads a resource into a String
@param name Relative path to the resource (relative to the parent object's package)
@param parent Instance of the class to use in finding the resource. The resource is looked up in the same package
where the class of the parent object is in.
@return Resource content as a String
@throws IOException if an I/O error occurs
|
getEmbeddedTestProject
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
Apache-2.0
|
public static ExecutableFlow getEmbeddedTestExecutionFlow(){
Project project = getEmbeddedTestProject();
Flow flow = FlowUtils.getFlow(project, "jobe");
return new ExecutableFlow(project, flow);
}
|
Reads a resource into a String
@param name Relative path to the resource (relative to the parent object's package)
@param parent Instance of the class to use in finding the resource. The resource is looked up in the same package
where the class of the parent object is in.
@return Resource content as a String
@throws IOException if an I/O error occurs
|
getEmbeddedTestExecutionFlow
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/TestUtils.java
|
Apache-2.0
|
@Test
public void testNegativePort() {
Assert.assertFalse(Utils.isValidPort(-1));
Assert.assertFalse(Utils.isValidPort(-10));
}
|
Test class for azkaban.utils.Utils
|
testNegativePort
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
Apache-2.0
|
@Test
public void testZeroPort() {
Assert.assertFalse(Utils.isValidPort(0));
}
|
Test class for azkaban.utils.Utils
|
testZeroPort
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
Apache-2.0
|
@Test
public void testOverflowPort() {
Assert.assertFalse(Utils.isValidPort(70000));
Assert.assertFalse(Utils.isValidPort(65536));
}
|
Test class for azkaban.utils.Utils
|
testOverflowPort
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
Apache-2.0
|
@Test
public void testValidPort() {
Assert.assertTrue(Utils.isValidPort(1023));
Assert.assertTrue(Utils.isValidPort(10000));
Assert.assertTrue(Utils.isValidPort(3030));
Assert.assertTrue(Utils.isValidPort(1045));
}
|
Test class for azkaban.utils.Utils
|
testValidPort
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
Apache-2.0
|
@Test
public void testValidCronExpressionV() {
final DateTimeZone timezone = DateTimeZone.getDefault();
final int year = Calendar.getInstance().get(Calendar.YEAR);
Assert.assertTrue(Utils.isCronExpressionValid("0 0 3 ? * *", timezone));
Assert.assertTrue(Utils.isCronExpressionValid("0 0 3 ? * * " + year, timezone));
Assert.assertTrue(Utils.isCronExpressionValid("0 0 * ? * *", timezone));
Assert.assertTrue(Utils.isCronExpressionValid("0 0 * ? * FRI", timezone));
// This is a bug from Quartz Cron. It looks like Quartz will parse the preceding 7 fields of a String.
Assert.assertTrue(Utils.isCronExpressionValid("0 0 3 ? * * " + year + " 22", timezone));
}
|
Test class for azkaban.utils.Utils
|
testValidCronExpressionV
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
Apache-2.0
|
@Test
public void testInvalidCronExpression() {
final DateTimeZone timezone = DateTimeZone.getDefault();
Assert.assertFalse(Utils.isCronExpressionValid("0 0 3 * * *", timezone));
Assert.assertFalse(Utils.isCronExpressionValid("0 66 * ? * *", timezone));
Assert.assertFalse(Utils.isCronExpressionValid("0 * * ? * 8", timezone));
Assert.assertFalse(Utils.isCronExpressionValid("0 * 25 ? * FRI", timezone));
}
|
Test class for azkaban.utils.Utils
|
testInvalidCronExpression
|
java
|
azkaban/azkaban
|
azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-common/src/test/java/azkaban/utils/UtilsTest.java
|
Apache-2.0
|
public <T> T query(final String baseQuery, final ResultSetHandler<T> resultHandler,
final Object... params)
throws SQLException {
try {
return this.queryRunner.query(baseQuery, resultHandler, params);
} catch (final SQLException ex) {
// todo kunkun-tang: Retry logics should be implemented here.
logger.error("query failed", ex);
if (this.dbMetrics != null) {
this.dbMetrics.markDBFailQuery();
}
throw ex;
}
}
|
Executes the given Azkaban related SELECT SQL operations. it will call
{@link AzkabanDataSource#getConnection()} inside queryrunner.query.
@param baseQuery The SQL query statement to execute.
@param resultHandler The handler used to create the result object
@param params Initialize the PreparedStatement's IN parameters
@param <T> The type of object that the qeury handler returns
@return The object returned by the handler.
|
query
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseOperator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseOperator.java
|
Apache-2.0
|
public int update(final String updateClause, final Object... params) throws SQLException {
int retryCount = 0;
SQLException exception;
String errorMsg =
"Update failed: Reached maximum number of retries: " + AzDBUtil.MAX_RETRIES_ON_DEADLOCK;
do {
try {
return this.queryRunner.update(updateClause, params);
} catch (final SQLException ex) {
exception = ex;
if (this.queryRunner.getDataSource() instanceof MySQLDataSource &&
ex.getErrorCode() == MySQLDataSource.MYSQL_ER_LOCK_DEADLOCK) {
retryCount++;
logger.warn("Deadlock detected when trying to execute: " + updateClause + " with values: "
+ Arrays.toString(params));
try {
Thread.sleep(AzDBUtil.RETRY_WAIT_TIME);
} catch (final InterruptedException e) {
logger.info("Sleep during DB operation retry interrupted.");
}
} else {
errorMsg = "update failed";
break;
}
}
} while (retryCount < AzDBUtil.MAX_RETRIES_ON_DEADLOCK);
logger.error(errorMsg, exception);
if (this.dbMetrics != null) {
this.dbMetrics.markDBFailUpdate();
}
throw exception;
}
|
Executes the given AZ related INSERT, UPDATE, or DELETE SQL statement.
it will call {@link AzkabanDataSource#getConnection()} inside
queryrunner.update.
@param updateClause sql statements to execute
@param params Initialize the PreparedStatement's IN parameters
@return The number of rows updated.
|
update
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseOperator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseOperator.java
|
Apache-2.0
|
public int[] batch(final String sqlCommand, final Object[]... params) throws SQLException {
try {
return this.queryRunner.batch(sqlCommand, params);
} catch (final SQLException ex) {
logger.error("batch operation failed", ex);
if (this.dbMetrics != null) {
this.dbMetrics.markDBFailUpdate();
}
throw ex;
}
}
|
Execute a batch operation
@param sqlCommand sqlCommand template
@param params parameters
@return result
|
batch
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseOperator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseOperator.java
|
Apache-2.0
|
public AzkabanDataSource getDataSource() {
return (AzkabanDataSource) this.queryRunner.getDataSource();
}
|
@return datasource wrapped in the database operator.
|
getDataSource
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseOperator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseOperator.java
|
Apache-2.0
|
public void updateDatabase()
throws SQLException, IOException {
final Set<String> tables = collectAllTables();
createTables(tables);
}
|
Creates DB tables. The input to this class is a folder path, which includes all create table
sql scripts. The script's name should follow: create.[table_name].sql in order to be
identified. This class is used for unit test only for now.
<p>Todo kunkun-tang: We need to fix some reliability issues if we rely on this class to
create tables when launching AZ in future.
|
updateDatabase
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseSetup.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseSetup.java
|
Apache-2.0
|
private Set<String> collectAllTables() {
final Set<String> tables = new HashSet<>();
final File directory = new File(this.scriptPath);
final File[] createScripts =
directory.listFiles(new PrefixSuffixFileFilter(
CREATE_SCRIPT_PREFIX, SQL_SCRIPT_SUFFIX));
if (createScripts != null) {
for (final File script : createScripts) {
final String name = script.getName();
final String[] nameSplit = name.split("\\.");
final String tableName = nameSplit[1];
tables.add(tableName);
}
}
return tables;
}
|
Creates DB tables. The input to this class is a folder path, which includes all create table
sql scripts. The script's name should follow: create.[table_name].sql in order to be
identified. This class is used for unit test only for now.
<p>Todo kunkun-tang: We need to fix some reliability issues if we rely on this class to
create tables when launching AZ in future.
|
collectAllTables
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseSetup.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseSetup.java
|
Apache-2.0
|
private void createTables(final Set<String> tables) throws SQLException, IOException {
final Connection conn = this.dataSource.getConnection();
conn.setAutoCommit(false);
try {
for (final String table : tables) {
runTableScripts(conn, table);
}
} finally {
conn.close();
}
}
|
Creates DB tables. The input to this class is a folder path, which includes all create table
sql scripts. The script's name should follow: create.[table_name].sql in order to be
identified. This class is used for unit test only for now.
<p>Todo kunkun-tang: We need to fix some reliability issues if we rely on this class to
create tables when launching AZ in future.
|
createTables
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseSetup.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseSetup.java
|
Apache-2.0
|
private void runTableScripts(final Connection conn, final String table)
throws IOException, SQLException {
logger.info("Creating new table " + table);
final String dbSpecificScript = "create." + table + ".sql";
final File script = new File(this.scriptPath, dbSpecificScript);
BufferedInputStream buff = null;
try {
buff = new BufferedInputStream(new FileInputStream(script));
final String queryStr = IOUtils.toString(buff);
final String[] splitQuery = queryStr.split(";\\s*\n");
final QueryRunner runner = new QueryRunner();
for (final String query : splitQuery) {
runner.update(conn, query);
}
conn.commit();
} finally {
IOUtils.closeQuietly(buff);
}
}
|
Creates DB tables. The input to this class is a folder path, which includes all create table
sql scripts. The script's name should follow: create.[table_name].sql in order to be
identified. This class is used for unit test only for now.
<p>Todo kunkun-tang: We need to fix some reliability issues if we rely on this class to
create tables when launching AZ in future.
|
runTableScripts
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseSetup.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseSetup.java
|
Apache-2.0
|
@Override
public boolean accept(final File pathname) {
if (!pathname.isFile() || pathname.isHidden()) {
return false;
}
final String name = pathname.getName();
final int length = name.length();
return this.suffix.length() <= length && this.prefix.length() <= length && name
.startsWith(this.prefix) && name.endsWith(this.suffix);
}
|
Creates DB tables. The input to this class is a folder path, which includes all create table
sql scripts. The script's name should follow: create.[table_name].sql in order to be
identified. This class is used for unit test only for now.
<p>Todo kunkun-tang: We need to fix some reliability issues if we rely on this class to
create tables when launching AZ in future.
|
accept
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseSetup.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseSetup.java
|
Apache-2.0
|
public long getLastInsertId() throws SQLException {
// A default connection: autocommit = true.
long num = -1;
try {
num = ((Number) this.queryRunner
.query(this.conn, "SELECT LAST_INSERT_ID();", new ScalarHandler<>(1)))
.longValue();
} catch (final SQLException ex) {
logger.error("can not get last insertion ID");
throw ex;
}
return num;
}
|
returns the last id from a previous insert statement. Note that last insert and this operation
should use the same connection.
@return the last inserted id in mysql per connection.
|
getLastInsertId
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseTransOperator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseTransOperator.java
|
Apache-2.0
|
public <T> T query(final String querySql, final ResultSetHandler<T> resultHandler,
final Object... params)
throws SQLException {
try {
return this.queryRunner.query(this.conn, querySql, resultHandler, params);
} catch (final SQLException ex) {
//RETRY Logic should be implemented here if needed.
throw ex;
} finally {
// Note: CAN NOT CLOSE CONNECTION HERE.
}
}
|
@param querySql
@param resultHandler
@param params
@param <T>
@return
@throws SQLException
|
query
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseTransOperator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseTransOperator.java
|
Apache-2.0
|
public int update(final String updateClause, final Object... params) throws SQLException {
try {
return this.queryRunner.update(this.conn, updateClause, params);
} catch (final SQLException ex) {
//RETRY Logic should be implemented here if needed.
throw ex;
} finally {
// Note: CAN NOT CLOSE CONNECTION HERE.
}
}
|
@param updateClause
@param params
@return
@throws SQLException
|
update
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseTransOperator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseTransOperator.java
|
Apache-2.0
|
public Connection getConnection() {
return this.conn;
}
|
@return the JDBC connection associated with this operator.
|
getConnection
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DatabaseTransOperator.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DatabaseTransOperator.java
|
Apache-2.0
|
void markDBConnection() {
/*
* This method should be Thread Safe.
* Two reasons that we don't make this function call synchronized:
* 1). drop wizard metrics deals with concurrency internally;
* 2). mark is basically a math addition operation, which should not cause race condition issue.
*/
this.dbConnectionMeter.mark();
}
|
Mark the occurrence of an DB query event.
|
markDBConnection
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/DBMetrics.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/DBMetrics.java
|
Apache-2.0
|
public static EncodingType fromInteger(final int x) {
switch (x) {
case 1:
return PLAIN;
case 2:
return GZIP;
default:
return PLAIN;
}
}
|
Used for when we store text data. Plain uses UTF8 encoding.
|
fromInteger
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/EncodingType.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/EncodingType.java
|
Apache-2.0
|
public int getNumVal() {
return this.numVal;
}
|
Used for when we store text data. Plain uses UTF8 encoding.
|
getNumVal
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/EncodingType.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/EncodingType.java
|
Apache-2.0
|
@Override
public Connection getConnection() throws SQLException {
this.dbMetrics.markDBConnection();
final long startMs = System.currentTimeMillis();
Connection connection = null;
int retryAttempt = 1;
while (retryAttempt < AzDBUtil.MAX_DB_RETRY_COUNT) {
try {
/**
* when DB connection could not be fetched (e.g., network issue), or connection can not be validated,
* {@link BasicDataSource} throws a SQL Exception. {@link BasicDataSource#dataSource} will be reset to null.
* createDataSource() will create a new dataSource.
* Every Attempt generates a thread-hanging-time, about 75 seconds, which is hard coded, and can not be changed.
*/
connection = createDataSource().getConnection();
/**
* If connection is null or connection is read only, retry to find available connection.
* When DB fails over from master to slave, master is set to read-only mode. We must keep
* finding correct data source and sql connection.
*/
if (connection == null || isReadOnly(connection)) {
throw new SQLException("Failed to find DB connection Or connection is read only. ");
} else {
// Evalaute how long it takes to get DB Connection.
this.dbMetrics.setDBConnectionTime(System.currentTimeMillis() - startMs);
return connection;
}
} catch (final SQLException ex) {
/**
* invalidate connection and reconstruct it later. if remote IP address is not reachable,
* it will get hang for a while and throw exception.
*/
this.dbMetrics.markDBFailConnection();
try {
invalidateConnection(connection);
} catch (final Exception e) {
logger.error("can not invalidate connection.", e);
}
logger.error("Failed to find write-enabled DB connection. Wait 15 seconds and retry."
+ " No.Attempt = " + retryAttempt, ex);
/**
* When database is completed down, DB connection fails to be fetched immediately. So we need
* to sleep 15 seconds for retry.
*/
sleep(1000L * 15);
retryAttempt++;
}
}
return connection;
}
|
This method overrides {@link BasicDataSource#getConnection()}, in order to have retry logics.
We don't make the call synchronized in order to guarantee normal cases performance.
|
getConnection
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/MySQLDataSource.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/MySQLDataSource.java
|
Apache-2.0
|
private boolean isReadOnly(final Connection conn) throws SQLException {
final Statement stmt = conn.createStatement();
final ResultSet rs = stmt.executeQuery("SELECT @@global.read_only");
if (rs.next()) {
final int value = rs.getInt(1);
return value != 0;
}
throw new SQLException("can not fetch read only value from DB");
}
|
When database is completed down, DB connection fails to be fetched immediately. So we need
to sleep 15 seconds for retry.
|
isReadOnly
|
java
|
azkaban/azkaban
|
azkaban-db/src/main/java/azkaban/db/MySQLDataSource.java
|
https://github.com/azkaban/azkaban/blob/master/azkaban-db/src/main/java/azkaban/db/MySQLDataSource.java
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.