src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
BankAccessFactory { public List<BankAccess> createBankAccesses(List<BankAccessBankingModel> bankingModelList) { List<BankAccess> bankAccessesResult = new ArrayList<BankAccess>(); for (BankAccessBankingModel bankingModel : bankingModelList) { bankAccessesResult.add(this.createBankAccess(bankingModel)); } return bankAcce... | @Test public void createListSuccess() { String accessId = "accessID"; String bankName = "bankName"; String bankCode = "bankCode"; String bankLogin = "bankLogin"; BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setBankName(bankName); bankAccessBankingModel.setBankCode... |
SavingsAccountIntoEntityTransformer { public SavingsAccountEntity transformSavingAccountIntoEntity(SavingsAccount savingsAccount, User currentUser) { SavingsAccountEntity savingsAccountEntity = new SavingsAccountEntity( savingsAccount.getName(), savingsAccount.getGoalbalance(), savingsAccount.getCurrentbalance(), savin... | @Test public void transformSavingAccountIntoEntity() { SavingsAccount savingsAccount = new SavingsAccount(savingsAccountId, savingsAccountName, savingsAccountGoal, savingsAccountCurrent, savingsAccountFinalDate, savingsAccountfinalGoalFinishedDate); User currentUser = new User(userEmail, userFirstName, userLastName); S... |
SavingsAccountIntoEntityTransformer { public User transformContactIntoEntity(Contact contact) { return new User(contact.getEmail(), contact.getFirstName(), contact.getLastName()); } SavingsAccountEntity transformSavingAccountIntoEntity(SavingsAccount savingsAccount, User currentUser); User transformContactIntoEntity(C... | @Test public void transformContactIntoEntity() { Contact contact = new Contact(userEmail, userFirstName, userLastName); User result = transformer.transformContactIntoEntity(contact); assertNotNull(result); assertEquals(userEmail, result.getEmail()); assertEquals(userFirstName, result.getFirstName()); assertEquals(userL... |
SavingsAccountIntoEntityTransformer { public List<BankAccountIdentifierEntity> transformBankAccountIdentifierIntoEntity(List<BankAccountIdentifier> assignedBankAccounts) { List<BankAccountIdentifierEntity> bankAccountIdentifierEntities = new ArrayList<>(); if (assignedBankAccounts == null) { return bankAccountIdentifie... | @Test public void transformBankAccountIdentifierListIntoEntity() { List<BankAccountIdentifier> identifiers = new ArrayList<>(); BankAccountIdentifier accountIdentifier = new BankAccountIdentifier(accessId, accountId); identifiers.add(accountIdentifier); List<BankAccountIdentifierEntity> result = transformer.transformBa... |
SavingsAccountIntoEntityTransformer { public Set<SavingsAccountSubGoalEntity> transformSavingsAccountSubGoalIdentifierIntoEntity(List<SavingsAccountSubGoal> subGoals) { Set<SavingsAccountSubGoalEntity> savingsAccountSubGoalEntities = new HashSet<>(); if (subGoals == null) { return savingsAccountSubGoalEntities; } for (... | @Test public void transformSavingsAccountSubGoalListIdentifierIntoEntity() { List<SavingsAccountSubGoal> subGoals = new ArrayList<SavingsAccountSubGoal>(); SavingsAccountSubGoal savingsAccountSubGoal = new SavingsAccountSubGoal(savingsAccountSubGoalTestName, savingsAccountSubGoalTestAmount); subGoals.add(savingsAccount... |
CustomFilter implements Filter<Transaction> { @Override public boolean shouldBeRemoved(Transaction t) { if(this.startDate.after(t.booking().getDate())){ return true; } if(this.endDate.before(t.booking().getDate())){ return true; } return false; } CustomFilter(Date startDate, Date endDate); @Override boolean shouldBeRem... | @Test public void teste_filter_withEndDate_shouldReturnStay() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date start = sdf.parse("11/06/2017"); Date end = sdf.parse("11/07/2017"); Booking booking = new Booking(); booking.setDate(end); Transaction testTransaction = new Transaction("some... |
BankAccessBankingModelFactory { public BankAccessBankingModel createBankAccessBankingModel(String userId, BankAccessCredential bankAccessCredential) { BankAccessBankingModel bankAccessBankingModel = new BankAccessBankingModel(); bankAccessBankingModel.setUserId(userId); bankAccessBankingModel.setBankCode(bankAccessCred... | @Test public void createTest() { BankAccessBankingModelFactory bankAccessBankingModelFactory = new BankAccessBankingModelFactory(); BankAccessCredential credential = new BankAccessCredential("test", "test", "test"); BankAccessBankingModel testModel = bankAccessBankingModelFactory.createBankAccessBankingModel("1", crede... |
SavingsAccountFromEntityTransformer { public List<SavingsAccount> transformSavingAccountFromEntity(List<SavingsAccountEntity> savingsAccountEntityList, User currentUser) { List<SavingsAccount> savingsAccountList = new ArrayList<>(); for (SavingsAccountEntity savingsAccountEntity : savingsAccountEntityList) { savingsAcc... | @Test public void transformSavingAccountsFromEntity() throws Exception { User currentUser = generateUserEntity(0); List<SavingsAccountEntity> savingsAccountEntityList = new ArrayList<>(); final int numberSavingAccounts = 3; for (int i = 0; i < numberSavingAccounts; i++) { SavingsAccountEntity savingsAccountEntity = gen... |
SavingsAccountFromEntityTransformer { public List<Contact> transformContactFromEntity(Set<SavingsAccountUserRelation> savingsAccountUserRelations, User currentUser) { List<Contact> contacts = new ArrayList<>(); if (savingsAccountUserRelations == null) { return contacts; } for (SavingsAccountUserRelation savingsAccountU... | @Test public void transformContactsFromEntity() throws Exception { Set<SavingsAccountUserRelation> relationEntitySet = new HashSet<>(); final int numberOfUsers = 3; User mainUser = generateUserEntity(0); relationEntitySet.add(new SavingsAccountUserRelation(mainUser)); for (int i = 1; i < numberOfUsers; i++) { User user... |
SavingsAccountFromEntityTransformer { public List<BankAccountIdentifier> transformBankAccountIdentifierFromEntity(Set<SavingsAccountUserRelation> userRelations, User currentUser) { List<BankAccountIdentifier> bankAccountIdentifiers = new ArrayList<>(); if (userRelations == null) { return bankAccountIdentifiers; } for (... | @Test public void transformBankAccountIdentifiersFromEntityEvaluateUser() throws Exception { Set<SavingsAccountUserRelation> relationEntityList = new HashSet<>(); List<BankAccountIdentifierEntity> identifierEntityList = new ArrayList<>(); final int numberIdentifiers = 3; User currentUser = generateUserEntity(0); for (i... |
SavingsAccountFromEntityTransformer { public List<SavingsAccountSubGoal> transformSavingsAccountSubGoalIdentifierFromEntity(Set<SavingsAccountSubGoalEntity> subGoalEntities) { List<SavingsAccountSubGoal> savingsAccountSubGoals = new ArrayList<>(); if (subGoalEntities == null) { return savingsAccountSubGoals; } for (Sav... | @Test public void transformSavingsAccountSubGoalIdentifiersFromEntity() throws Exception { Set<SavingsAccountSubGoalEntity> subGoalEntityList = new HashSet<>(); final int numberSubGoals = 3; for (int i = 0; i < numberSubGoals; i++) { SavingsAccountSubGoalEntity subGoalEntity = generateSubGoalEntity(i); subGoalEntityLis... |
BankAccountFactory { public BankAccount createBankAccount(BankAccountBankingModel bankingModel) { double balance = 0; if (bankingModel.getBankAccountBalance() != null) { balance = bankingModel.getBankAccountBalance().getReadyHbciBalance(); } BankAccount bankAccount = new BankAccount(bankingModel.getId(), bankingModel.g... | @Test public void createSuccess() { final double testAmount = 123.22; BankAccountBalanceBankingModel bankAccountBalanceBankingModel = new BankAccountBalanceBankingModel(); bankAccountBalanceBankingModel.setReadyHbciBalance(testAmount); String accessId = "accessID"; String accountId = "accountId"; String type = "type"; ... |
BankAccountFactory { public List<BankAccount> createBankAccounts(List<BankAccountBankingModel> bankingModelList) { List<BankAccount> bankAccountsResult = new ArrayList<BankAccount>(); for (BankAccountBankingModel bankingModel : bankingModelList) { bankAccountsResult.add(this.createBankAccount(bankingModel)); } return b... | @Test public void createListSuccess() { final double testAmount = 123.22; final int bankAccountActualSize = 1; BankAccountBalanceBankingModel bankAccountBalanceBankingModel = new BankAccountBalanceBankingModel(); bankAccountBalanceBankingModel.setReadyHbciBalance(testAmount); String accessId = "accessID"; String accoun... |
AuthMigrator { public Task<Void> migrate(boolean cleanupDigitsSession) { final FirebaseUser currentUser = mFirebaseAuth.getCurrentUser(); final String sessionJson = mStorageHelpers.getDigitsSessionJson(); final Context context = mApp.getApplicationContext(); final RedeemableDigitsSessionBuilder builder; if (currentUser... | @Test public void migrateAndClear_tokenFound() throws JSONException { when(mockStorageHelpers.getDigitsSessionJson()).thenReturn(VALID_DIGITS_SESSION); when(mockStorageHelpers.getUnsignedJWT(mjsonCaptor.capture())).thenReturn(DIGITS_JWT); when(mockFirebaseAuth.signInWithCustomToken(DIGITS_JWT)).thenReturn(authResultTas... |
AuthMigrator { public boolean hasLegacyAuth() { return mStorageHelpers.hasDigitsSession(); } @VisibleForTesting(otherwise = PRIVATE) AuthMigrator(@NonNull FirebaseApp app, @NonNull StorageHelpers storageHelper,
@NonNull FirebaseAuth firebaseAuth); static AuthMigrator getInstance(FirebaseApp app); stat... | @Test public void hasLegacyAuth() throws JSONException { when(mockStorageHelpers.hasDigitsSession()).thenReturn(true); AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); assertTrue(authMigrator.hasLegacyAuth()); } |
AuthMigrator { public void clearLegacyAuth() { mStorageHelpers.clearDigitsSession(); } @VisibleForTesting(otherwise = PRIVATE) AuthMigrator(@NonNull FirebaseApp app, @NonNull StorageHelpers storageHelper,
@NonNull FirebaseAuth firebaseAuth); static AuthMigrator getInstance(FirebaseApp app); static Aut... | @Test public void clearLegacyAuth() throws JSONException { AuthMigrator authMigrator = new AuthMigrator(mockFirebaseApp, mockStorageHelpers, mockFirebaseAuth); authMigrator.clearLegacyAuth(); verify(mockStorageHelpers).clearDigitsSession(); } |
RedeemableDigitsSessionBuilder { @NonNull static RedeemableDigitsSessionBuilder fromSessionJson(@NonNull String json) throws JSONException { RedeemableDigitsSessionBuilder builder = new RedeemableDigitsSessionBuilder(); JSONObject jsonObject = new JSONObject(json); JSONObject emailJsonObject = safeGetJsonObject(EMAIL_K... | @Test(expected=JSONException.class) public void testInvalidFromDigitsSessionJson() throws JSONException { RedeemableDigitsSessionBuilder.fromSessionJson("invalid_json"); } |
StfCommander { private static JCommander createCommander(CommandContainer commandContainer, String[] args) { JCommander.Builder builder = JCommander.newBuilder(); for (String operation : commandContainer.getAllCommands()) { CommandContainer.Command command = commandContainer.getCommand(operation); builder.addCommand(op... | @DisplayName("connect command is parsed with valid -l param") @Test void testConnectCommandWithValidCacheParam() throws IOException { createCommander("connect -l 1 2 3"); }
@DisplayName("connect command will throw the ParameterException if -l param is invalid") @Test void testConnectCommandWithInvalidValidCacheParam() ... |
BlockingStatus { public void changeStatus(Status status) { synchronized (this) { this.status = status; if (Status.isStatusFinished(status)) { unblock(); } } } BlockingStatus(int execId, String jobId, Status initialStatus); Status blockOnFinishedStatus(); Status viewStatus(); void unblock(); void changeStatus(Status sta... | @Ignore @Test public void testUnfinishedBlock() throws InterruptedException { BlockingStatus status = new BlockingStatus(1, "test", Status.QUEUED); WatchingThread thread = new WatchingThread(status); thread.start(); synchronized (this) { wait(3000); } status.changeStatus(Status.SUCCEEDED); thread.join(); System.out.pri... |
FileIOUtils { public static void createDeepHardlink(File sourceDir, File destDir) throws IOException { if (!sourceDir.exists()) { throw new IOException("Source directory " + sourceDir.getPath() + " doesn't exist"); } else if (!destDir.exists()) { throw new IOException("Destination directory " + destDir.getPath() + " do... | @Test public void testHardlinkCopy() throws IOException { FileIOUtils.createDeepHardlink(sourceDir, destDir); assertTrue(areDirsEqual(sourceDir, destDir, true)); FileUtils.deleteDirectory(destDir); assertTrue(areDirsEqual(baseDir, sourceDir, true)); }
@Test public void testHardlinkCopyNonSource() { boolean exception = ... |
FileIOUtils { public static Pair<Integer, Integer> getUtf8Range(byte[] buffer, int offset, int length) { int start = getUtf8ByteStart(buffer, offset); int end = getUtf8ByteEnd(buffer, offset + length - 1); return new Pair<Integer, Integer>(start, end - start + 1); } static String getSourcePathFromClass(Class<?> contai... | @Test public void testAsciiUTF() throws IOException { String foreignText = "abcdefghijklmnopqrstuvwxyz"; byte[] utf8ByteArray = createUTF8ByteArray(foreignText); int length = utf8ByteArray.length; System.out.println("char length:" + foreignText.length() + " utf8BytesLength:" + utf8ByteArray.length + " for:" + foreignTe... |
PatternLayoutEscaped extends PatternLayout { @Override public String format(final LoggingEvent event) { if (event.getMessage() instanceof String) { return super.format(appendStackTraceToEvent(event)); } return super.format(event); } PatternLayoutEscaped(String s); PatternLayoutEscaped(); @Override String format(final ... | @Test public void testWithException() { try { throw new Exception("This is an exception"); } catch (Exception e) { LoggingEvent event = createEventWithException("There was an exception", e); assertTrue(layout.format(event).startsWith("There was an exception\\njava.lang.Exception: This is an exception")); } }
@Test publ... |
ExternalLinkUtils { public static String getExternalAnalyzerOnReq(Props azkProps, HttpServletRequest req) { if (!azkProps.containsKey(ServerProperties.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC)) { return ""; } String topic = azkProps.getString(ServerProperties.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC); return getLinkFromReq... | @Test public void testGetExternalAnalyzerValidFormat() { azkProps.put(ServerProperties.AZKABAN_SERVER_EXTERNAL_ANALYZER_TOPIC, EXTERNAL_ANALYZER_TOPIC); azkProps.put(ServerProperties.AZKABAN_SERVER_EXTERNAL_TOPIC_URL.replace("${topic}", EXTERNAL_ANALYZER_TOPIC), EXTERNAL_ANALYZER_URL_VALID_FORMAT); when(mockRequest.get... |
JobCallbackUtil { public static boolean isThereJobCallbackProperty(Props props, JobCallbackStatusEnum status) { if (props == null || status == null) { throw new NullPointerException("One of the argument is null"); } String jobCallBackUrl = firstJobcallbackPropertyMap.get(status); return props.containsKey(jobCallBackUrl... | @Test public void multipleStatusesWithJobCallbackTest() { Props props = new Props(); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", "def"); Assert.assertTrue(JobCallbackUtil.isThereJobCallbackProperty(props, JobCallbackStatusEnum.STARTED, JobCallbackStatusEnum.COMPLETED, ... |
ExternalLinkUtils { public static String getExternalLogViewer(Props azkProps, String jobId, Props jobProps) { if (!azkProps.containsKey(ServerProperties.AZKABAN_SERVER_EXTERNAL_LOGVIEWER_TOPIC)) { return ""; } String topic = azkProps.getString(ServerProperties.AZKABAN_SERVER_EXTERNAL_LOGVIEWER_TOPIC); return getLinkFro... | @Test public void testGetExternalLogViewerValidFormat() { azkProps.put(ServerProperties.AZKABAN_SERVER_EXTERNAL_LOGVIEWER_TOPIC, EXTERNAL_LOGVIEWER_TOPIC); azkProps.put(ServerProperties.AZKABAN_SERVER_EXTERNAL_TOPIC_URL.replace("${topic}", EXTERNAL_LOGVIEWER_TOPIC), EXTERNAL_LOGVIEWER_URL_VALID_FORMAT); String external... |
ExternalLinkUtils { static String encodeToUTF8(String url) { try { return URLEncoder.encode(url, "UTF-8").replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { logger.error("Specified encoding is not supported", e); } return ""; } static String getExternalAnalyzerOnReq(Props azkProps, HttpServletRequest... | @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(ExternalLinkUtil... |
ExternalLinkUtils { static String getURLForTopic(String topic, Props azkProps) { return azkProps.getString(ServerProperties.AZKABAN_SERVER_EXTERNAL_TOPIC_URL.replace("${topic}", topic), ""); } static String getExternalAnalyzerOnReq(Props azkProps, HttpServletRequest req); static String getExternalLogViewer(Props azkPr... | @Test public void testFetchURL() { azkProps.put(ServerProperties.AZKABAN_SERVER_EXTERNAL_TOPIC_URL.replace("${topic}", "someTopic"), "This is a link"); assertTrue(ExternalLinkUtils.getURLForTopic("someTopic", azkProps).equals("This is a link")); } |
Emailer extends AbstractMailer implements Alerter { public void sendErrorEmail(ExecutableFlow flow, String... extraReasons) { EmailMessage message = new EmailMessage(mailHost, mailPort, mailUser, mailPassword); message.setFromAddress(mailSender); message.setTLS(tls); message.setAuth(super.hasMailAuth()); ExecutionOptio... | @Ignore @Test public void testSendEmail() throws Exception{ Flow flow = project.getFlow("jobe"); flow.addFailureEmails(receiveAddrList); Assert.assertNotNull(flow); ExecutableFlow exFlow = new ExecutableFlow(project, flow); Emailer emailer = new Emailer(props); emailer.sendErrorEmail(exFlow); } |
RestfulApiClient { public T httpGet(URI uri, List<NameValuePair> headerEntries) throws IOException{ if (null == uri){ logger.error(" unable to perform httpGet as the passed uri is null"); return null; } HttpGet get = new HttpGet(uri); return this.sendAndReturn((HttpGet)completeRequest(get, headerEntries)); } T httpGet... | @Test public void testHttpGet() throws Exception { MockRestfulApiClient mockClient = new MockRestfulApiClient(); @SuppressWarnings("unchecked") URI uri = MockRestfulApiClient.buildUri("test.com", 80, "test", true, new Pair <String,String>("Entry1","Value1")); String result = mockClient.httpGet(uri, null); Assert.assert... |
RestfulApiClient { public T httpPost(URI uri, List<NameValuePair> headerEntries, String postingBody) throws UnsupportedEncodingException, IOException{ if (null == uri){ logger.error(" unable to perform httpPost as the passed uri is null."); return null; } HttpPost post = new HttpPost(uri); return this.sendAndReturn(com... | @Test public void testHttpPost() throws Exception { MockRestfulApiClient mockClient = new MockRestfulApiClient(); @SuppressWarnings("unchecked") URI uri = MockRestfulApiClient.buildUri("test.com", 80, "test", true, new Pair <String,String>("Entry1","Value1")); ArrayList<NameValuePair> headerItems = new ArrayList<NameVa... |
RestfulApiClient { public T httpPut(URI uri, List<NameValuePair> headerEntries, String postingBody) throws UnsupportedEncodingException, IOException{ if (null == uri){ logger.error(" unable to perform httpPut as the passed url is null or empty."); return null; } HttpPut put = new HttpPut(uri); return this.sendAndReturn... | @Test public void testHttpPut() throws Exception { MockRestfulApiClient mockClient = new MockRestfulApiClient(); @SuppressWarnings("unchecked") URI uri = MockRestfulApiClient.buildUri("test.com", 80, "test", true, new Pair <String,String>("Entry1","Value1")); ArrayList<NameValuePair> headerItems = new ArrayList<NameVal... |
RestfulApiClient { public T httpDelete(URI uri, List<NameValuePair> headerEntries) throws IOException{ if (null == uri){ logger.error(" unable to perform httpDelete as the passed uri is null."); return null; } HttpDelete delete = new HttpDelete(uri); return this.sendAndReturn((HttpDelete)completeRequest(delete, headerE... | @Test public void testHttpDelete() throws Exception { MockRestfulApiClient mockClient = new MockRestfulApiClient(); @SuppressWarnings("unchecked") URI uri = MockRestfulApiClient.buildUri("test.com", 80, "test", true, new Pair <String,String>("Entry1","Value1")); ArrayList<NameValuePair> headerItems = new ArrayList<Name... |
Utils { public static boolean isValidPort(int port) { if (port >= 1 && port <= 65535) { return true; } return false; } private Utils(); static boolean equals(Object a, Object b); static T nonNull(T t); static File findFilefromDir(File dir, String fn); static void croak(String message, int exitCode); static boolean isV... | @Test public void testNegativePort() { Assert.assertFalse(Utils.isValidPort(-1)); Assert.assertFalse(Utils.isValidPort(-10)); }
@Test public void testZeroPort() { Assert.assertFalse(Utils.isValidPort(0)); }
@Test public void testOverflowPort() { Assert.assertFalse(Utils.isValidPort(70000)); Assert.assertFalse(Utils.isV... |
Utils { public static boolean isCronExpressionValid(String cronExpression, DateTimeZone timezone) { if (!CronExpression.isValidExpression(cronExpression)) { return false; } CronExpression cronExecutionTime = parseCronExpression(cronExpression, timezone); if (cronExecutionTime == null || cronExecutionTime.getNextValidTi... | @Test public void testValidCronExpressionV() { DateTimeZone timezone = DateTimeZone.getDefault(); Assert.assertTrue(Utils.isCronExpressionValid("0 0 3 ? * *", timezone)); Assert.assertTrue(Utils.isCronExpressionValid("0 0 3 ? * * 2017", timezone)); Assert.assertTrue(Utils.isCronExpressionValid("0 0 * ? * *", timezone))... |
AbstractMailer { protected EmailMessage createEmailMessage(String subject, String mimetype, Collection<String> emailList) { EmailMessage message = new EmailMessage(mailHost, mailPort, mailUser, mailPassword); message.setFromAddress(mailSender); message.addAllToAddress(emailList); message.setMimeType(mimetype); message.... | @Test public void testCreateEmailMessage(){ Props props = createMailProperties(); props.put("mail.port","445"); AbstractMailer mailer = new AbstractMailer(props); EmailMessage emailMessage = mailer.createEmailMessage("subject","text/html",senderList); assert emailMessage.getMailPort()==445; } |
HttpRequestUtils { public static void filterAdminOnlyFlowParams(UserManager userManager, ExecutionOptions options, User user) throws ExecutorManagerException { if (options == null || options.getFlowParameters() == null) return; Map<String, String> params = options.getFlowParameters(); if (!hasPermission(userManager, us... | @Test public void TestFilterNonAdminOnlyFlowParams() throws IOException, ExecutorManagerException, UserManagerException { ExecutableFlow flow = createExecutableFlow(); UserManager manager = TestUtils.createTestXmlUserManager(); User user = manager.getUser("testUser", "testUser"); HttpRequestUtils.filterAdminOnlyFlowPar... |
HttpRequestUtils { public static boolean validateIntegerParam(Map<String, String> params, String paramName) throws ExecutorManagerException { if (params != null && params.containsKey(paramName) && !StringUtils.isNumeric(params.get(paramName))) { throw new ExecutorManagerException(paramName + " should be an integer"); }... | @Test public void testvalidIntegerParam() throws ExecutorManagerException { Map<String, String> params = new HashMap<String, String>(); params.put("param1", "123"); HttpRequestUtils.validateIntegerParam(params, "param1"); }
@Test(expected = ExecutorManagerException.class) public void testInvalidIntegerParam() throws Ex... |
JobCallbackUtil { public static String replaceTokens(String value, Map<String, String> contextInfo, boolean withEncoding) { String result = value; String tokenValue = encodeQueryParam(contextInfo.get(CONTEXT_SERVER_TOKEN), withEncoding); result = result.replaceFirst(Pattern.quote(CONTEXT_SERVER_TOKEN), tokenValue); tok... | @Test public void noTokenTest() { String urlWithNoToken = "http: String result = JobCallbackUtil.replaceTokens(urlWithNoToken, contextInfo, true); Assert.assertEquals(urlWithNoToken, result); }
@Test public void oneTokenTest() { String urlWithOneToken = "http: String result = JobCallbackUtil.replaceTokens(urlWithOneTok... |
HttpRequestUtils { public static boolean hasPermission(UserManager userManager, User user, Permission.Type type) { for (String roleName : user.getRoles()) { Role role = userManager.getRole(roleName); if (role.getPermission().isPermissionSet(type) || role.getPermission().isPermissionSet(Permission.Type.ADMIN)) { return ... | @Test public void testHasAdminPermission() throws UserManagerException { UserManager manager = TestUtils.createTestXmlUserManager(); User adminUser = manager.getUser("testAdmin", "testAdmin"); Assert.assertTrue(HttpRequestUtils.hasPermission(manager, adminUser, Type.ADMIN)); }
@Test public void testHasOrdinaryPermissio... |
ValidationReport { public void addWarnLevelInfoMsg(String msg) { if (msg != null) { _infoMsgs.add("WARN" + msg); } } ValidationReport(); void addWarnLevelInfoMsg(String msg); void addErrorLevelInfoMsg(String msg); void addWarningMsgs(Set<String> msgs); void addErrorMsgs(Set<String> msgs); ValidationStatus getStatus(); ... | @Test public void testAddWarnLevelInfoMsg() { ValidationReport report = new ValidationReport(); String msg = "test warn level info message."; report.addWarnLevelInfoMsg(msg); for (String info : report.getInfoMsgs()) { assertEquals("Info message added through addWarnLevelInfoMsg should have level set to WARN", Validatio... |
ValidationReport { public void addErrorLevelInfoMsg(String msg) { if (msg != null) { _infoMsgs.add("ERROR" + msg); } } ValidationReport(); void addWarnLevelInfoMsg(String msg); void addErrorLevelInfoMsg(String msg); void addWarningMsgs(Set<String> msgs); void addErrorMsgs(Set<String> msgs); ValidationStatus getStatus()... | @Test public void testAddErrorLevelInfoMsg() { ValidationReport report = new ValidationReport(); String msg = "test error level error message."; report.addErrorLevelInfoMsg(msg); for (String info : report.getInfoMsgs()) { assertEquals("Info message added through addErrorLevelInfoMsg should have level set to ERROR", Val... |
XmlValidatorManager implements ValidatorManager { @Override public List<String> getValidatorsInfo() { List<String> info = new ArrayList<String>(); for (String key : validators.keySet()) { info.add(key); } return info; } XmlValidatorManager(Props props); @Override void loadValidators(Props props, Logger log); @Override ... | @Test public void testNoValidatorsDir() { Props props = new Props(baseProps); XmlValidatorManager manager = new XmlValidatorManager(props); assertEquals("XmlValidatorManager should contain only the default validator when no xml configuration " + "file is present.", manager.getValidatorsInfo().size(), 1); assertEquals("... |
XmlValidatorManager implements ValidatorManager { @Override public void loadValidators(Props props, Logger log) { validators = new LinkedHashMap<String, ProjectValidator>(); DirectoryFlowLoader flowLoader = new DirectoryFlowLoader(props, log); validators.put(flowLoader.getValidatorName(), flowLoader); if (!props.contai... | @Test public void testLoadValidators() { Props props = new Props(baseProps); URL validatorUrl = Resources.getResource("project/testValidators"); URL configUrl = Resources.getResource("test-conf/azkaban-validators-test2.xml"); props.put(ValidatorConfigs.VALIDATOR_PLUGIN_DIR, validatorUrl.getPath()); props.put(ValidatorC... |
JdbcProjectLoader extends AbstractJdbcLoader implements
ProjectLoader { @Override public Project fetchProjectByName(String name) throws ProjectManagerException { Connection connection = getConnection(); Project project = null; try { project = fetchProjectByName(connection, name); } finally { DbUtils.closeQuietly(co... | @Test public void testInvalidProjectByFetchProjectByName() { if (!isTestSetup()) { return; } ProjectLoader loader = createLoader(); try { loader.fetchProjectByName("NonExistantProject"); } catch (ProjectManagerException ex) { System.out.println("Test true"); } Assert.fail("Expecting exception, but didn't get one"); } |
JdbcProjectLoader extends AbstractJdbcLoader implements
ProjectLoader { @Override public void removeProject(Project project, String user) throws ProjectManagerException { QueryRunner runner = createQueryRunner(); long updateTime = System.currentTimeMillis(); final String UPDATE_INACTIVE_PROJECT = "UPDATE projects S... | @Test public void testRemoveProject() throws ProjectManagerException { if (!isTestSetup()) { return; } ProjectLoader loader = createLoader(); String projectName = "testRemoveProject"; String projectDescription = "This is my new project"; User user = new User("testUser"); Project project = loader.createNewProject(projec... |
ProcessJob extends AbstractProcessJob { @Override public void run() throws Exception { try { resolveProps(); } catch (Exception e) { handleError("Bad property definition! " + e.getMessage(), e); } getLog().info("ProcessJob sysProps:" + sysProps); getLog().info("ProcessJob jobProps:" + jobProps); if (sysProps.getBoolean... | @Test public void testOneUnixCommand() throws Exception { props.put(ProcessJob.COMMAND, "ls -al"); job.run(); }
@Test public void testOneUnixCommandWithProxyUserInsteadOfSubmitUser() throws Exception { props.removeLocal(CommonJobProperties.SUBMIT_USER); props.put("user.to.proxy", "test_user"); props.put(ProcessJob.COMM... |
ProcessJob extends AbstractProcessJob { public static String[] partitionCommandLine(final String command) { ArrayList<String> commands = new ArrayList<String>(); int index = 0; StringBuffer buffer = new StringBuffer(command.length()); boolean isApos = false; boolean isQuote = false; while (index < command.length()) { c... | @Test public void testPartitionCommand() throws Exception { String test1 = "a b c"; Assert.assertArrayEquals(new String[] { "a", "b", "c" }, ProcessJob.partitionCommandLine(test1)); String test2 = "a 'b c'"; Assert.assertArrayEquals(new String[] { "a", "b c" }, ProcessJob.partitionCommandLine(test2)); String test3 = "a... |
PythonJob extends LongArgJob { public PythonJob(String jobid, Props sysProps, Props jobProps, Logger log) { super(jobid, new String[] { jobProps.getString(PYTHON_BINARY_KEY, "python"), jobProps.getString(SCRIPT_KEY) }, sysProps, jobProps, log, ImmutableSet.of(PYTHON_BINARY_KEY, SCRIPT_KEY, JOB_TYPE)); } PythonJob(Strin... | @Ignore("Test appears to hang.") @Test public void testPythonJob() { props = new Props(); props.put(AbstractProcessJob.WORKING_DIR, "."); props.put("type", "python"); props.put("script", scriptFile); props.put("t", "90"); props.put("type", "script"); props.put("fullPath", "."); job = new PythonJob("TestProcess", props,... |
LoginAbstractAzkabanServlet extends
AbstractAzkabanServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Session session = getSessionFromRequest(req); logRequest(req, session); if (hasParam(req, "logout")) { resp.sendRedirect(req.getContext... | @Test public void testWhenGetRequestSessionIsValid() throws Exception, IOException, ServletException { String clientIp = "127.0.0.1:10000"; String sessionId = "111"; HttpServletRequest req = MockLoginAzkabanServlet.getRequestWithNoUpstream(clientIp, sessionId, "GET"); StringWriter writer = new StringWriter(); HttpServl... |
LoginAbstractAzkabanServlet extends
AbstractAzkabanServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Session session = getSessionFromRequest(req); logRequest(req, session); if (ServletFileUpload.isMultipartContent(req)) { Map<String, O... | @Test public void testWhenPostRequestSessionIsValid() throws Exception{ String clientIp = "127.0.0.1:10000"; String sessionId = "111"; HttpServletRequest req = MockLoginAzkabanServlet.getRequestWithNoUpstream(clientIp, sessionId, "POST"); StringWriter writer = new StringWriter(); HttpServletResponse resp = getResponse(... |
JobCallbackUtil { public static List<HttpRequestBase> parseJobCallbackProperties(Props props, JobCallbackStatusEnum status, Map<String, String> contextInfo, int maxNumCallback) { return parseJobCallbackProperties(props, status, contextInfo, maxNumCallback, logger); } static boolean isThereJobCallbackProperty(Props pro... | @Test public void parseJobCallbackOneGetTest() { Props props = new Props(); String url = "http: props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", url); List<HttpRequestBase> result = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatusEnum.STARTED, contextInfo... |
JobCallbackUtil { public static Header[] parseHttpHeaders(String headers) { if (headers == null || headers.length() == 0) { return null; } String[] headerArray = headers.split(HEADER_ELEMENT_DELIMITER); List<Header> headerList = new ArrayList<Header>(headerArray.length); for (int i = 0; i < headerArray.length; i++) { S... | @Test public void noHeaderElementTest() { Header[] headerArr = JobCallbackUtil.parseHttpHeaders("this is an amazing day"); Assert.assertNotNull(headerArr); Assert.assertEquals(0, headerArr.length); }
@Test public void oneHeaderElementTest() { String name = "Content-type"; String value = "application/json"; String heade... |
XmlUserManager implements UserManager { @Override public User getUser(String username, String password) throws UserManagerException { if (username == null || username.trim().isEmpty()) { throw new UserManagerException("Username is empty."); } else if (password == null || password.trim().isEmpty()) { throw new UserManag... | @Ignore @Test public void testBasicLoad() throws Exception { Props props = new Props(baseProps); props.put(XmlUserManager.XML_FILE_PARAM, "unit/test-conf/azkaban-users-test1.xml"); UserManager manager = null; try { manager = new XmlUserManager(props); } catch (RuntimeException e) { e.printStackTrace(); fail("XmlUserMan... |
Permission { public void addPermissionsByName(String... list) { for (String perm : list) { Type type = Type.valueOf(perm); if (type != null) { addPermission(type); } ; } } Permission(); Permission(int flags); Permission(Type... list); void addPermissions(Permission perm); void setPermission(Type type, boolean set); v... | @Test public void testEmptyPermissionCreation() throws Exception { Permission permission = new Permission(); permission.addPermissionsByName(new String[] {}); } |
ExecutorManager extends EventHandler implements
ExecutorManagerAdapter { @Override public Collection<Executor> getAllActiveExecutors() { return Collections.unmodifiableCollection(activeExecutors); } ExecutorManager(Props azkProps, ExecutorLoader loader,
Map<String, Alerter> alerters); @Override void setupExec... | @Test public void testLocalExecutorScenario() throws ExecutorManagerException { Props props = new Props(); props.put("executor.port", 12345); ExecutorLoader loader = new MockExecutorLoader(); ExecutorManager manager = new ExecutorManager(props, loader, new HashMap<String, Alerter>()); Set<Executor> activeExecutors = ne... |
ExecutorManager extends EventHandler implements
ExecutorManagerAdapter { @Override public String submitExecutableFlow(ExecutableFlow exflow, String userId) throws ExecutorManagerException { synchronized (exflow) { String flowId = exflow.getFlowId(); logger.info("Submitting execution flow " + flowId + " by " + userI... | @Test(expected = ExecutorManagerException.class) public void testDuplicateQueuedFlows() throws ExecutorManagerException, IOException { ExecutorManager manager = createMultiExecutorManagerInstance(); ExecutableFlow flow1 = TestUtils.createExecutableFlow("exectest1", "exec1"); flow1.getExecutionOptions().setConcurrentOpt... |
ExecutableFlow extends ExecutableFlowBase { @Override public String getId() { return getFlowId(); } ExecutableFlow(Project project, Flow flow); ExecutableFlow(); @Override int getOid(); @Override void setOid(int oid); @Override String getId(); @Override ExecutableFlow getExecutableFlow(); void addAllProxyUsers(Collect... | @Test public void testExecutorFlowCreation() throws Exception { Flow flow = project.getFlow("jobe"); Assert.assertNotNull(flow); ExecutableFlow exFlow = new ExecutableFlow(project, flow); Assert.assertNotNull(exFlow.getExecutableNode("joba")); Assert.assertNotNull(exFlow.getExecutableNode("jobb")); Assert.assertNotNull... |
QueuedExecutions { public void enqueue(ExecutableFlow exflow, ExecutionReference ref) throws ExecutorManagerException { if (hasExecution(exflow.getExecutionId())) { String errMsg = "Flow already in queue " + exflow.getExecutionId(); throw new ExecutorManagerException(errMsg); } Pair<ExecutionReference, ExecutableFlow> ... | @Test(expected = ExecutorManagerException.class) public void testEnqueueDuplicateExecution() throws IOException, ExecutorManagerException { Pair<ExecutionReference, ExecutableFlow> pair1 = createExecutablePair("exec1", 1); QueuedExecutions queue = new QueuedExecutions(5); queue.enqueue(pair1.getSecond(), pair1.getFirst... |
QueuedExecutions { public void enqueueAll( Collection<Pair<ExecutionReference, ExecutableFlow>> collection) throws ExecutorManagerException { for (Pair<ExecutionReference, ExecutableFlow> pair : collection) { enqueue(pair.getSecond(), pair.getFirst()); } } QueuedExecutions(long capacity); Pair<ExecutionReference, Execu... | @Test public void testEnqueueAll() throws IOException, ExecutorManagerException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); Assert.assertTrue(queue.getAllEntries().containsAll(dataList)); Assert.assertTrue(data... |
QueuedExecutions { public long size() { return queuedFlowList.size(); } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, ExecutableFl... | @Test public void testSize() throws IOException, ExecutorManagerException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); Assert.assertEquals(queue.size(), 2); } |
QueuedExecutions { public void dequeue(int executionId) { if (queuedFlowMap.containsKey(executionId)) { queuedFlowList.remove(queuedFlowMap.get(executionId)); queuedFlowMap.remove(executionId); } } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void... | @Test public void testDequeue() throws IOException, ExecutorManagerException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); queue.dequeue(dataList.get(0).getFirst().getExecId()); Assert.assertEquals(queue.size(), ... |
QueuedExecutions { public void clear() { for (Pair<ExecutionReference, ExecutableFlow> pair : queuedFlowMap.values()) { dequeue(pair.getFirst().getExecId()); } } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, Exec... | @Test public void testClear() throws IOException, ExecutorManagerException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); Assert.assertEquals(queue.size(), 2); queue.clear(); Assert.assertEquals(queue.size(), 0); ... |
QueuedExecutions { public boolean isEmpty() { return queuedFlowList.isEmpty() && queuedFlowMap.isEmpty(); } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<P... | @Test public void testIsEmpty() throws IOException, ExecutorManagerException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); Assert.assertTrue(queue.isEmpty()); queue.enqueueAll(dataList); Assert.assertEquals(queue.size(), 2); queue.clear(); ... |
QueuedExecutions { public Pair<ExecutionReference, ExecutableFlow> fetchHead() throws InterruptedException { Pair<ExecutionReference, ExecutableFlow> pair = queuedFlowList.take(); if (pair != null && pair.getFirst() != null) { queuedFlowMap.remove(pair.getFirst().getExecId()); } return pair; } QueuedExecutions(long cap... | @Test public void testFetchHead() throws IOException, ExecutorManagerException, InterruptedException { QueuedExecutions queue = new QueuedExecutions(5); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); Assert.assertTrue(queue.isEmpty()); queue.enqueueAll(dataList); Assert.assertEquals(queue.fet... |
JobCallbackRequestMaker { public void makeHttpRequest(String jobId, Logger logger, List<HttpRequestBase> httpRequestList) { if (httpRequestList == null || httpRequestList.isEmpty()) { logger.info("No HTTP requests to make"); return; } for (HttpRequestBase httpRequest : httpRequestList) { logger.info("Job callback http ... | @Test(timeout = 4000) public void basicGetTest() { Props props = new Props(); String url = buildUrlForDelay(1); props.put("job.notification." + JobCallbackStatusEnum.STARTED.name().toLowerCase() + ".1.url", url); List<HttpRequestBase> httpRequestList = JobCallbackUtil.parseJobCallbackProperties(props, JobCallbackStatus... |
QueuedExecutions { public boolean isFull() { return size() >= capacity; } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Collection<Pair<ExecutionReference, Executable... | @Test public void testIsFull() throws IOException, ExecutorManagerException, InterruptedException { QueuedExecutions queue = new QueuedExecutions(2); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); Assert.assertTrue(queue.isFull()); } |
QueuedExecutions { public boolean hasExecution(int executionId) { return queuedFlowMap.containsKey(executionId); } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflow, ExecutionReference ref); void enqueueAll(
Colle... | @Test public void testHasExecution() throws IOException, ExecutorManagerException, InterruptedException { QueuedExecutions queue = new QueuedExecutions(2); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); for (Pair<ExecutionReference, ExecutableFlow> pair : dataList)... |
QueuedExecutions { public ExecutableFlow getFlow(int executionId) { if (hasExecution(executionId)) { return queuedFlowMap.get(executionId).getSecond(); } return null; } QueuedExecutions(long capacity); Pair<ExecutionReference, ExecutableFlow> fetchHead(); void dequeue(int executionId); void enqueue(ExecutableFlow exflo... | @Test public void testGetFlow() throws IOException, ExecutorManagerException, InterruptedException { QueuedExecutions queue = new QueuedExecutions(2); List<Pair<ExecutionReference, ExecutableFlow>> dataList = getDummyData(); queue.enqueueAll(dataList); for (Pair<ExecutionReference, ExecutableFlow> pair : dataList) { As... |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public void uploadExecutableNode(ExecutableNode node, Props inputProps) throws ExecutorManagerException { final String INSERT_EXECUTION_NODE = "INSERT INTO execution_jobs " + "(exec_id, project_id, version, flow_id, job_id, start_ti... | @Test public void testUploadExecutableNode() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); ExecutableFlow flow = createExecutableFlow(10, "exec1"); flow.setExecutionId(10); File jobFile = new File(UNIT_BASE_DIR + "/exectest1", "job10.job"); Props props = new Props(null, jobF... |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public void unassignExecutor(int executionId) throws ExecutorManagerException { final String UPDATE = "UPDATE execution_flows SET executor_id=NULL where exec_id=?"; QueryRunner runner = createQueryRunner(); try { int rows = runner.u... | @Test public void testUnassignExecutorException() throws ExecutorManagerException, IOException { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); try { loader.unassignExecutor(2); Assert.fail("Expecting exception, but didn't get one"); } catch (ExecutorManagerException ex) { System.out.println("T... |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public Executor fetchExecutorByExecutionId(int executionId) throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); FetchExecutorHandler executorHandler = new FetchExecutorHandler(); Executor executor = null; try... | @Test public void testFetchMissingExecutorByExecution() throws ExecutorManagerException, IOException { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Assert.assertEquals(loader.fetchExecutorByExecutionId(1), null); } |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public List<Pair<ExecutionReference, ExecutableFlow>> fetchQueuedFlows() throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); FetchQueuedExecutableFlows flowHandler = new FetchQueuedExecutableFlows(); try { Li... | @Test public void testFetchQueuedFlows() throws ExecutorManagerException, IOException { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); List<Pair<ExecutionReference, ExecutableFlow>> queuedFlows = new LinkedList<Pair<ExecutionReference, ExecutableFlow>>(); ExecutableFlow flow = TestUtils.createE... |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public List<Executor> fetchAllExecutors() throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); FetchExecutorHandler executorHandler = new FetchExecutorHandler(); try { List<Executor> executors = runner.query(F... | @Test public void testFetchEmptyExecutors() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); List<Executor> executors = loader.fetchAllExecutors(); Assert.assertEquals(executors.size(), 0); }
@Test public void testFetchAllExecutors() throws Exception { if (!isTestSetup()) { ret... |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public List<Executor> fetchActiveExecutors() throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); FetchExecutorHandler executorHandler = new FetchExecutorHandler(); try { List<Executor> executors = runner.quer... | @Test public void testFetchEmptyActiveExecutors() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); List<Executor> executors = loader.fetchActiveExecutors(); Assert.assertEquals(executors.size(), 0); }
@Test public void testFetchActiveExecutors() throws Exception { if (!isTestSe... |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public Executor fetchExecutor(String host, int port) throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); FetchExecutorHandler executorHandler = new FetchExecutorHandler(); try { List<Executor> executors = run... | @Test public void testFetchMissingExecutorId() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Executor executor = loader.fetchExecutor(0); Assert.assertEquals(executor, null); }
@Test public void testFetchMissingExecutorHostPort() throws Exception { if (!isTestSetup()) { retu... |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public List<ExecutorLogEvent> getExecutorEvents(Executor executor, int num, int offset) throws ExecutorManagerException { QueryRunner runner = createQueryRunner(); ExecutorLogsResultHandler logHandler = new ExecutorLogsResultHandler... | @Test public void testFetchEmptyExecutorEvents() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); Executor executor = new Executor(1, "localhost", 12345, true); List<ExecutorLogEvent> executorEvents = loader.getExecutorEvents(executor, 5, 0); Assert.assertEquals(executorEvents.... |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public Executor addExecutor(String host, int port) throws ExecutorManagerException { Executor executor = fetchExecutor(host, port); if (executor != null) { throw new ExecutorManagerException(String.format( "Executor %s:%d already ex... | @Test public void testDuplicateAddExecutor() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); try { String host = "localhost"; int port = 12345; loader.addExecutor(host, port); loader.addExecutor(host, port); Assert.fail("Expecting exception, but didn't get one"); } catch (Exec... |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public void updateExecutor(Executor executor) throws ExecutorManagerException { final String UPDATE = "UPDATE executors SET host=?, port=?, active=? where id=?"; QueryRunner runner = createQueryRunner(); try { int rows = runner.upda... | @Test public void testMissingExecutorUpdate() throws Exception { if (!isTestSetup()) { return; } ExecutorLoader loader = createLoader(); try { Executor executor = new Executor(1, "localhost", 1234, true); loader.updateExecutor(executor); Assert.fail("Expecting exception, but didn't get one"); } catch (ExecutorManagerEx... |
JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader { @Override public int removeExecutionLogsByTime(long millis) throws ExecutorManagerException { final String DELETE_BY_TIME = "DELETE FROM execution_logs WHERE upload_time < ?"; QueryRunner runner = createQueryRunner(); int updateNum = 0; try {... | @SuppressWarnings("static-access") @Ignore @Test public void testRemoveExecutionLogsByTime() throws ExecutorManagerException, IOException, InterruptedException { ExecutorLoader loader = createLoader(); File logDir = new File(UNIT_BASE_DIR + "logtest"); File[] largelog = { new File(logDir, "largeLog1.log"), new File(log... |
DefaultMailCreator implements MailCreator { @Override public boolean createErrorEmail(ExecutableFlow flow, EmailMessage message, String azkabanName, String scheme, String clientHostname, String clientPortNumber, String... vars) { ExecutionOptions option = flow.getExecutionOptions(); List<String> emailList = option.getF... | @Test public void createErrorEmail() throws Exception { setJobStatus(Status.FAILED); executableFlow.setEndTime(END_TIME_MILLIS); executableFlow.setStatus(Status.FAILED); assertTrue(mailCreator.createErrorEmail( executableFlow, message, azkabanName, scheme, clientHostname, clientPortNumber)); assertEquals("Flow 'mail-cr... |
DefaultMailCreator implements MailCreator { @Override public boolean createFirstErrorMessage(ExecutableFlow flow, EmailMessage message, String azkabanName, String scheme, String clientHostname, String clientPortNumber, String... vars) { ExecutionOptions option = flow.getExecutionOptions(); List<String> emailList = opti... | @Test public void createFirstErrorMessage() throws Exception { setJobStatus(Status.FAILED); executableFlow.setStatus(Status.FAILED_FINISHING); assertTrue(mailCreator.createFirstErrorMessage( executableFlow, message, azkabanName, scheme, clientHostname, clientPortNumber)); assertEquals("Flow 'mail-creator-test' has enco... |
DefaultMailCreator implements MailCreator { @Override public boolean createSuccessEmail(ExecutableFlow flow, EmailMessage message, String azkabanName, String scheme, String clientHostname, String clientPortNumber, String... vars) { ExecutionOptions option = flow.getExecutionOptions(); List<String> emailList = option.ge... | @Test public void createSuccessEmail() throws Exception { setJobStatus(Status.SUCCEEDED); executableFlow.setEndTime(END_TIME_MILLIS); executableFlow.setStatus(Status.SUCCEEDED); assertTrue(mailCreator.createSuccessEmail( executableFlow, message, azkabanName, scheme, clientHostname, clientPortNumber)); assertEquals("Flo... |
AzkabanDatabaseUpdater { public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser(); OptionSpec<String> scriptDirectory = parser .acceptsAll(Arrays.asList("s", "script"), "Directory of update scripts.").withRequiredArg() .describedAs("script").ofType(String.class); OptionSpec<Voi... | @Ignore @Test public void testMySQLAutoCreate() throws Exception { clearMySQLTestDb(); URL resourceUrl = Resources.getResource("conf/dbtestmysql"); assertNotNull(resourceUrl); File resource = new File(resourceUrl.toURI()); String confDir = resource.getParent(); System.out.println("1.***Now testing check"); AzkabanDatab... |
JobCallbackValidator { public static int validate(String jobName, Props serverProps, Props jobProps, Collection<String> errors) { int maxNumCallback = serverProps.getInt( JobCallbackConstants.MAX_CALLBACK_COUNT_PROPERTY_KEY, JobCallbackConstants.DEFAULT_MAX_CALLBACK_COUNT); int maxPostBodyLength = serverProps.getInt(MA... | @Test public void noJobCallbackProps() { Props jobProps = new Props(); Set<String> errors = new HashSet<String>(); Assert.assertEquals(0, JobCallbackValidator.validate("bogusJob", serverProps, jobProps, errors)); Assert.assertEquals(0, errors.size()); }
@Test public void sequenceStartWithZeroProps() { Props jobProps = ... |
Condition { public Condition(Map<String, ConditionChecker> checkers, String expr) { setCheckers(checkers); this.expression = jexl.createExpression(expr); updateNextCheckTime(); } Condition(Map<String, ConditionChecker> checkers, String expr); Condition(Map<String, ConditionChecker> checkers, String expr,
long ne... | @Test public void conditionTest() { Map<String, ConditionChecker> checkers = new HashMap<String, ConditionChecker>(); ThresholdChecker fake1 = new ThresholdChecker("thresholdchecker1", 10); ThresholdChecker fake2 = new ThresholdChecker("thresholdchecker2", 20); ThresholdChecker.setVal(15); checkers.put(fake1.getId(), f... |
JdbcTriggerLoader extends AbstractJdbcLoader implements
TriggerLoader { @Override public void addTrigger(Trigger t) throws TriggerLoaderException { logger.info("Inserting trigger " + t.toString() + " into db."); t.setLastModifyTime(System.currentTimeMillis()); Connection connection = getConnection(); try { addTrigg... | @Ignore @Test public void addTriggerTest() throws TriggerLoaderException { Trigger t1 = createTrigger("testProj1", "testFlow1", "source1"); Trigger t2 = createTrigger("testProj2", "testFlow2", "source2"); loader.addTrigger(t1); List<Trigger> ts = loader.loadTriggers(); assertTrue(ts.size() == 1); Trigger t3 = ts.get(0)... |
JdbcTriggerLoader extends AbstractJdbcLoader implements
TriggerLoader { @Override public void removeTrigger(Trigger t) throws TriggerLoaderException { logger.info("Removing trigger " + t.toString() + " from db."); QueryRunner runner = createQueryRunner(); try { int removes = runner.update(REMOVE_TRIGGER, t.getTrigg... | @Ignore @Test public void removeTriggerTest() throws TriggerLoaderException { Trigger t1 = createTrigger("testProj1", "testFlow1", "source1"); Trigger t2 = createTrigger("testProj2", "testFlow2", "source2"); loader.addTrigger(t1); loader.addTrigger(t2); List<Trigger> ts = loader.loadTriggers(); assertTrue(ts.size() == ... |
JdbcTriggerLoader extends AbstractJdbcLoader implements
TriggerLoader { @Override public void updateTrigger(Trigger t) throws TriggerLoaderException { if (logger.isDebugEnabled()) { logger.debug("Updating trigger " + t.getTriggerId() + " into db."); } t.setLastModifyTime(System.currentTimeMillis()); Connection conn... | @Ignore @Test public void updateTriggerTest() throws TriggerLoaderException { Trigger t1 = createTrigger("testProj1", "testFlow1", "source1"); t1.setResetOnExpire(true); loader.addTrigger(t1); List<Trigger> ts = loader.loadTriggers(); assertTrue(ts.get(0).isResetOnExpire() == true); t1.setResetOnExpire(false); loader.u... |
JobTypeManager { public synchronized JobTypePluginSet getJobTypePluginSet() { return this.pluginSet; } JobTypeManager(String jobtypePluginDir, Props globalProperties,
ClassLoader parentClassLoader); void loadPlugins(); Job buildJobExecutor(String jobId, Props jobProps, Logger logger); synchronized JobTypePluginSe... | @Test public void testCommonPluginProps() throws Exception { JobTypePluginSet pluginSet = manager.getJobTypePluginSet(); Props props = pluginSet.getCommonPluginJobProps(); System.out.println(props.toString()); assertEquals("commonprop1", props.getString("commonprop1")); assertEquals("commonprop2", props.getString("comm... |
JobTypeManager { public Job buildJobExecutor(String jobId, Props jobProps, Logger logger) throws JobTypeManagerException { final JobTypePluginSet pluginSet = getJobTypePluginSet(); Job job = null; try { String jobType = jobProps.getString("type"); if (jobType == null || jobType.length() == 0) { throw new JobExecutionEx... | @Test public void testBuildClass() throws Exception { Props jobProps = new Props(); jobProps.put("type", "anothertestjob"); jobProps.put("test", "test1"); jobProps.put("pluginprops3", "4"); Job job = manager.buildJobExecutor("anothertestjob", jobProps, logger); assertTrue(job instanceof FakeJavaJob); FakeJavaJob fjj = ... |
PropsUtils { public static Props resolveProps(Props props) { if (props == null) return null; Props resolvedProps = new Props(); LinkedHashSet<String> visitedVariables = new LinkedHashSet<String>(); for (String key : props.getKeySet()) { String value = props.get(key); visitedVariables.add(key); String replacedValue = re... | @Test public void testGoodResolveProps() throws IOException { Props propsGrandParent = new Props(); Props propsParent = new Props(propsGrandParent); Props props = new Props(propsParent); props.put("letter", "a"); propsParent.put("letter", "b"); propsGrandParent.put("letter", "c"); Assert.assertEquals("a", props.get("le... |
PropsUtils { public static String getPropertyDiff(Props oldProps, Props newProps) { StringBuilder builder = new StringBuilder(""); MapDifference<String, String> md = Maps.difference(toStringMap(oldProps, false), toStringMap(newProps, false)); Map<String, String> newlyCreatedProperty = md.entriesOnlyOnRight(); if (newly... | @Test public void testGetPropertyDiff() throws IOException { Props oldProps = new Props(); Props newProps1 = new Props(); oldProps.put("a", "a_value1"); oldProps.put("b", "b_value1"); newProps1.put("b", "b_value2"); String message1 = PropsUtils.getPropertyDiff(oldProps, newProps1); Assert.assertEquals(message1, "Delete... |
StringUtils { public static boolean isFromBrowser(String userAgent) { if (userAgent == null) { return false; } if (BROWSWER_PATTERN.matcher(userAgent).matches()) { return true; } else { return false; } } static String shellQuote(String s, char quoteCh); @Deprecated static String join(List<String> list, String delimite... | @Test public void isBrowser() throws Exception { for (String browser : browserVariants) { Assert.assertTrue(browser, StringUtils.isFromBrowser(browser)); } }
@Test public void notBrowserWithLowercase() throws Exception { for (String browser : browserVariants) { Assert.assertFalse(browser.toLowerCase(), StringUtils.isFr... |
WebUtils { public String getRealClientIpAddr(Map<String, String> httpHeaders, String remoteAddr){ String clientIp = httpHeaders.getOrDefault(X_FORWARDED_FOR_HEADER, null); if(clientIp == null){ clientIp = remoteAddr; } else{ String ips[] = clientIp.split(","); clientIp = ips[0]; } String parts[] = clientIp.split(":"); ... | @Test public void testWhenNoXForwardedForHeaderUseClientIp(){ String clientIp = "127.0.0.1:10000"; Map<String, String> headers = new HashMap<>(); WebUtils utils = new WebUtils(); String ip = utils.getRealClientIpAddr(headers, clientIp); assertEquals(ip, "127.0.0.1"); }
@Test public void testWhenClientIpNoPort(){ String... |
EmailMessage { public void sendEmail() throws MessagingException { checkSettings(); Properties props = new Properties(); if (_usesAuth) { props.put("mail." + protocol + ".auth", "true"); props.put("mail.user", _mailUser); props.put("mail.password", _mailPassword); } else { props.put("mail." + protocol + ".auth", "false... | @Ignore @Test public void testSendEmail() throws IOException { em.addToAddress(toAddr); em.setSubject("azkaban test email"); em.setBody("azkaban test email"); try { em.sendEmail(); } catch (MessagingException e) { e.printStackTrace(); } } |
StringUtils { public static boolean isRgbValue(String color){ Pattern pattern = Pattern.compile("^#(([0123456789abcdefABCDEF]{6})|([0123456789abcdefABCDEF]{8}))$"); Matcher matcher = pattern.matcher(color); return matcher.matches(); } static boolean isRgbValue(String color); } | @Test public void testIsRgbValue() throws Exception { System.out.println("#6688 is color " + StringUtils.isRgbValue("#6688")); System.out.println("#070A01 is color " + StringUtils.isRgbValue("#668899")); System.out.println("dd8899 is color " + StringUtils.isRgbValue("dd8899")); System.out.println("#yy8899 is color " + ... |
EncodeUtils { public static String urlDecode(String encode){ try { return URLDecoder.decode(encode,"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } private EncodeUtils(); static String urlEncode(String s); static String urlDecode(String encode); } | @Test public void urlDecode() throws Exception { String s = "%E4%B8%8A%E6%B5%B7%E5%B8%82%E6%99%AE%E9%99%80%E5%8C%BA%E5%85%89%E5%A4%8D%E8%A5%BF%E8%B7%AF%E9%9D%A0%E8%BF%91%E6%B1%87%E9%93%B6%E9%93%AD%E5%B0%8A6%E5%8F%B7%E6%A5%BC"; s = EncodeUtils.urlDecode(s); System.out.println(s); } |
Money implements Serializable { @Override public String toString() { return format.format(amount); } @Override String toString(); static final NumberFormat format; } | @Test public void go() { Money money = new Money(BigDecimal.valueOf(new Random().nextDouble()).multiply(BigDecimal.valueOf(10000))); System.out.println(money.toString()); money = new Money(new BigDecimal("2820.00000000000000000000")); System.out.println(money.toString()); assertThat(true) .isTrue(); } |
ManageTagController { @DeleteMapping("/manage/tagList") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@RequestParam String name) { try { tagService.delete(name); } catch (Throwable ignored) { log.info("删除时错误", ignored); } } @GetMapping("/manageTag") String index(); @GetMapping("/manageTagAdd") String toAdd... | @Test public void testDelete() throws Exception { int randomNum = random.nextInt(10); while (randomNum-- > 0) { toAdd(); } Tag tag = tagRepository.findAll().stream().max(new RandomComparator()).orElse(null); if (tag == null) { return; } MainGood mainGood = mainGoodService.forSale().stream().max(new RandomComparator()).... |
ManageTagController { @PutMapping("/manage/tagList/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void disable(@RequestParam String name) { tagRepository.getOne(name).setDisabled(true); } @GetMapping("/manageTag") String index(); @GetMapping("/manageTagAdd") String toAdd(); @GetMapping("/manage... | @Test public void disable() throws Exception { changeDisable("/disable", true); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.