method2testcases
stringlengths 118
6.63k
|
---|
### Question:
IndentUtil { public static String calcXmlIndent(String[] lines, int row, int column) { Preconditions.checkNotNull(lines, "The parameter 'lines' cannot be null"); Preconditions.checkArgument(lines.length > row && row >= 0, "The parameter 'row' overflows."); final String line = lines[row]; Preconditions.checkArgument(line != null, "Encounter null on row: " + row); Preconditions.checkArgument(line.length() >= column && column >= 0, "The parameter 'column' overflows"); final StringBuilder buffer = new StringBuilder(); final int pos = line.lastIndexOf('<', column) - 1; for (int i = 0; i <= pos; i++) { if (line.charAt(i) == '\t') { buffer.append('\t'); } else { buffer.append(' '); } } return buffer.toString(); } private IndentUtil(); static String calcXmlIndent(String[] lines, int row, int column); }### Answer:
@Test public void testXmlIndent() { final String[] lines = TextUtils.splitLines("<foo> \n <bar> \n \t<test></test></bar> \r\n </foo>"); assertEquals(" ", IndentUtil.calcXmlIndent(lines, 1, 2)); assertEquals(" \t", IndentUtil.calcXmlIndent(lines, 2, 12)); }
@Test public void testXmlIndentBadArgument() { final String[] lines = TextUtils.splitLines("<foo> \n <bar> \n \t<test></test></bar> \r\n </foo>"); try { IndentUtil.calcXmlIndent(lines, 100, 1); fail("Should throw IAE"); } catch (IllegalArgumentException ex) { } try { IndentUtil.calcXmlIndent(lines, -1, 1); fail("Should throw IAE"); } catch (IllegalArgumentException ex) { } try { IndentUtil.calcXmlIndent(lines, 0, -1); fail("Should throw IAE"); } catch (IllegalArgumentException ex) { } try { IndentUtil.calcXmlIndent(lines, 0, 1000); fail("Should throw IAE"); } catch (IllegalArgumentException ex) { } try { IndentUtil.calcXmlIndent(null, 1, 1000); fail("Should throw NPE"); } catch (NullPointerException ex) { } try { IndentUtil.calcXmlIndent(new String[] { null }, 0, 1000); fail("Should throw IAE"); } catch (IllegalArgumentException ex) { } } |
### Question:
AnnotationHandlerImpl implements AnnotationHandler { @Override public Set<Method> findFunctions(final List<URL> urls) { return new Reflections( new ConfigurationBuilder() .addUrls(urls) .setScanners(new MethodAnnotationsScanner()) .addClassLoader(getClassLoader(urls))) .getMethodsAnnotatedWith(FunctionName.class); } @Override Set<Method> findFunctions(final List<URL> urls); @Override Map<String, FunctionConfiguration> generateConfigurations(final Set<Method> methods); @Override FunctionConfiguration generateConfiguration(final Method method); }### Answer:
@Test public void findFunctions() throws Exception { final AnnotationHandler handler = getAnnotationHandler(); final Set<Method> functions = handler.findFunctions(Arrays.asList(getClassUrl())); assertEquals(13, functions.size()); final List<String> methodNames = functions.stream().map(f -> f.getName()).collect(Collectors.toList()); assertTrue(methodNames.contains(HTTP_TRIGGER_METHOD)); assertTrue(methodNames.contains(QUEUE_TRIGGER_METHOD)); assertTrue(methodNames.contains(TIMER_TRIGGER_METHOD)); assertTrue(methodNames.contains(MULTI_OUTPUT_METHOD)); assertTrue(methodNames.contains(BLOB_TRIGGER_METHOD)); assertTrue(methodNames.contains(EVENTHUB_TRIGGER_METHOD)); assertTrue(methodNames.contains(SERVICE_BUS_QUEUE_TRIGGER_METHOD)); assertTrue(methodNames.contains(SERVICE_BUS_TOPIC_TRIGGER_METHOD)); assertTrue(methodNames.contains(COSMOSDB_TRIGGER_METHOD)); assertTrue(methodNames.contains(EVENTGRID_TRIGGER_METHOD)); assertTrue(methodNames.contains(CUSTOM_BINDING_METHOD)); assertTrue(methodNames.contains(EXTENDING_CUSTOM_BINDING_METHOD)); assertTrue(methodNames.contains(EXTENDING_CUSTOM_BINDING_WITHOUT_NAME_METHOD)); } |
### Question:
MSDeployArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(final DeployTarget target) throws AzureExecutionException { final File zipPackage = createZipPackage(); final CloudStorageAccount storageAccount = FunctionArtifactHelper.getCloudStorageAccount(target); final String blobName = getBlobName(); final String packageUri = uploadPackageToAzureStorage(zipPackage, storageAccount, blobName); deployWithPackageUri(target, packageUri, () -> deletePackageFromAzureStorage(storageAccount, blobName)); } private MSDeployArtifactHandlerImpl(@Nonnull final Builder builder); @Override void publish(final DeployTarget target); static final String DEPLOYMENT_PACKAGE_CONTAINER; static final String CREATE_ZIP_START; static final String CREATE_ZIP_DONE; static final String UPLOAD_PACKAGE_START; static final String UPLOAD_PACKAGE_DONE; static final String DEPLOY_PACKAGE_START; static final String DEPLOY_PACKAGE_DONE; static final String DELETE_PACKAGE_START; static final String DELETE_PACKAGE_DONE; static final String DELETE_PACKAGE_FAIL; }### Answer:
@Test public void publish() throws Exception { final DeployTarget deployTarget = mock(DeployTarget.class); final Map mapSettings = mock(Map.class); final File file = mock(File.class); final AppSetting storageSetting = mock(AppSetting.class); mapSettings.put(INTERNAL_STORAGE_KEY, storageSetting); doReturn(mapSettings).when(deployTarget).getAppSettings(); doReturn(storageSetting).when(mapSettings).get(anyString()); buildHandler(); PowerMockito.mockStatic(FunctionArtifactHelper.class); when(FunctionArtifactHelper.getCloudStorageAccount(any())).thenReturn(null); doReturn("").when(handlerSpy).uploadPackageToAzureStorage(file, null, ""); doReturn("").when(handlerSpy).getBlobName(); doReturn(mapSettings).when(deployTarget).getAppSettings(); doNothing().when(handlerSpy).deployWithPackageUri(eq(deployTarget), eq(""), any(Runnable.class)); doReturn(file).when(handlerSpy).createZipPackage(); handlerSpy.publish(deployTarget); verify(handlerSpy, times(1)).publish(deployTarget); verify(handlerSpy, times(1)).createZipPackage(); verify(handlerSpy, times(1)).getBlobName(); verify(handlerSpy, times(1)).uploadPackageToAzureStorage(file, null, ""); verify(handlerSpy, times(1)).deployWithPackageUri(eq(deployTarget), eq(""), any(Runnable.class)); verifyNoMoreInteractions(handlerSpy); } |
### Question:
MSDeployArtifactHandlerImpl extends ArtifactHandlerBase { protected File createZipPackage() throws AzureExecutionException { Log.prompt(""); Log.prompt(CREATE_ZIP_START); final File zipPackage = FunctionArtifactHelper.createFunctionArtifact(stagingDirectoryPath); Log.prompt(CREATE_ZIP_DONE + stagingDirectoryPath.concat(Constants.ZIP_EXT)); return zipPackage; } private MSDeployArtifactHandlerImpl(@Nonnull final Builder builder); @Override void publish(final DeployTarget target); static final String DEPLOYMENT_PACKAGE_CONTAINER; static final String CREATE_ZIP_START; static final String CREATE_ZIP_DONE; static final String UPLOAD_PACKAGE_START; static final String UPLOAD_PACKAGE_DONE; static final String DEPLOY_PACKAGE_START; static final String DEPLOY_PACKAGE_DONE; static final String DELETE_PACKAGE_START; static final String DELETE_PACKAGE_DONE; static final String DELETE_PACKAGE_FAIL; }### Answer:
@Test public void createZipPackage() throws Exception { buildHandler(); final File zipPackage = handlerSpy.createZipPackage(); assertTrue(zipPackage.exists()); } |
### Question:
MSDeployArtifactHandlerImpl extends ArtifactHandlerBase { protected String uploadPackageToAzureStorage(final File zipPackage, final CloudStorageAccount storageAccount, final String blobName) throws AzureExecutionException { Log.prompt(UPLOAD_PACKAGE_START); final CloudBlockBlob blob = AzureStorageHelper.uploadFileAsBlob(zipPackage, storageAccount, DEPLOYMENT_PACKAGE_CONTAINER, blobName); final String packageUri = blob.getUri().toString(); Log.prompt(UPLOAD_PACKAGE_DONE + packageUri); return packageUri; } private MSDeployArtifactHandlerImpl(@Nonnull final Builder builder); @Override void publish(final DeployTarget target); static final String DEPLOYMENT_PACKAGE_CONTAINER; static final String CREATE_ZIP_START; static final String CREATE_ZIP_DONE; static final String UPLOAD_PACKAGE_START; static final String UPLOAD_PACKAGE_DONE; static final String DEPLOY_PACKAGE_START; static final String DEPLOY_PACKAGE_DONE; static final String DELETE_PACKAGE_START; static final String DELETE_PACKAGE_DONE; static final String DELETE_PACKAGE_FAIL; }### Answer:
@Test public void uploadPackageToAzureStorage() throws Exception { final CloudStorageAccount storageAccount = mock(CloudStorageAccount.class); final CloudBlobClient blobClient = mock(CloudBlobClient.class); doReturn(blobClient).when(storageAccount).createCloudBlobClient(); final CloudBlobContainer blobContainer = mock(CloudBlobContainer.class); doReturn(blobContainer).when(blobClient).getContainerReference(anyString()); doReturn(true).when(blobContainer) .createIfNotExists(any(BlobContainerPublicAccessType.class), isNull(), isNull()); final CloudBlockBlob blob = mock(CloudBlockBlob.class); doReturn(blob).when(blobContainer).getBlockBlobReference(anyString()); doNothing().when(blob).upload(any(FileInputStream.class), anyLong()); doReturn(new URI("http: final File file = new File("pom.xml"); buildHandler(); final String packageUri = handler.uploadPackageToAzureStorage(file, storageAccount, "blob"); assertSame("http: } |
### Question:
MSDeployArtifactHandlerImpl extends ArtifactHandlerBase { protected void deployWithPackageUri(final DeployTarget target, final String packageUri, Runnable onDeployFinish) { try { Log.prompt(DEPLOY_PACKAGE_START); target.msDeploy(packageUri, false); Log.prompt(DEPLOY_PACKAGE_DONE); } finally { onDeployFinish.run(); } } private MSDeployArtifactHandlerImpl(@Nonnull final Builder builder); @Override void publish(final DeployTarget target); static final String DEPLOYMENT_PACKAGE_CONTAINER; static final String CREATE_ZIP_START; static final String CREATE_ZIP_DONE; static final String UPLOAD_PACKAGE_START; static final String UPLOAD_PACKAGE_DONE; static final String DEPLOY_PACKAGE_START; static final String DEPLOY_PACKAGE_DONE; static final String DELETE_PACKAGE_START; static final String DELETE_PACKAGE_DONE; static final String DELETE_PACKAGE_FAIL; }### Answer:
@Test public void deployWithPackageUri() throws Exception { final FunctionApp app = mock(FunctionApp.class); final DeployTarget deployTarget = mock(DeployTarget.class); final WithPackageUri withPackageUri = mock(WithPackageUri.class); doReturn(withPackageUri).when(app).deploy(); final WithExecute withExecute = mock(WithExecute.class); doReturn(withExecute).when(withPackageUri).withPackageUri(anyString()); doReturn(withExecute).when(withExecute).withExistingDeploymentsDeleted(false); final Runnable runnable = mock(Runnable.class); doNothing().when(deployTarget).msDeploy("uri", false); buildHandler(); handlerSpy.deployWithPackageUri(deployTarget, "uri", runnable); verify(handlerSpy, times(1)).deployWithPackageUri(deployTarget, "uri", runnable); verify(runnable, times(1)).run(); verify(deployTarget, times(1)).msDeploy("uri", false); } |
### Question:
MSDeployArtifactHandlerImpl extends ArtifactHandlerBase { protected void deletePackageFromAzureStorage(final CloudStorageAccount storageAccount, final String blobName) { try { Log.prompt(DELETE_PACKAGE_START); AzureStorageHelper.deleteBlob(storageAccount, DEPLOYMENT_PACKAGE_CONTAINER, blobName); Log.prompt(DELETE_PACKAGE_DONE + blobName); } catch (Exception e) { Log.error(DELETE_PACKAGE_FAIL + blobName); } } private MSDeployArtifactHandlerImpl(@Nonnull final Builder builder); @Override void publish(final DeployTarget target); static final String DEPLOYMENT_PACKAGE_CONTAINER; static final String CREATE_ZIP_START; static final String CREATE_ZIP_DONE; static final String UPLOAD_PACKAGE_START; static final String UPLOAD_PACKAGE_DONE; static final String DEPLOY_PACKAGE_START; static final String DEPLOY_PACKAGE_DONE; static final String DELETE_PACKAGE_START; static final String DELETE_PACKAGE_DONE; static final String DELETE_PACKAGE_FAIL; }### Answer:
@Test public void deletePackageFromAzureStorage() throws Exception { final CloudStorageAccount storageAccount = mock(CloudStorageAccount.class); final CloudBlobClient blobClient = mock(CloudBlobClient.class); doReturn(blobClient).when(storageAccount).createCloudBlobClient(); final CloudBlobContainer blobContainer = mock(CloudBlobContainer.class); doReturn(blobContainer).when(blobClient).getContainerReference(anyString()); doReturn(true).when(blobContainer).exists(); final CloudBlockBlob blob = mock(CloudBlockBlob.class); doReturn(blob).when(blobContainer).getBlockBlobReference(anyString()); doReturn(true).when(blob).deleteIfExists(); buildHandler(); handler.deletePackageFromAzureStorage(storageAccount, "blob"); } |
### Question:
FunctionArtifactHelper { public static CloudStorageAccount getCloudStorageAccount(final DeployTarget target) throws AzureExecutionException { final Map<String, AppSetting> settingsMap = target.getAppSettings(); if (settingsMap != null) { final AppSetting setting = settingsMap.get(INTERNAL_STORAGE_KEY); if (setting != null) { final String value = setting.value(); if (StringUtils.isNotEmpty(value)) { try { return CloudStorageAccount.parse(value); } catch (InvalidKeyException | URISyntaxException e) { throw new AzureExecutionException("Cannot parse storage connection string due to error: " + e.getMessage(), e); } } } } throw new AzureExecutionException(INTERNAL_STORAGE_NOT_FOUND); } static File createFunctionArtifact(final String stagingDirectoryPath); static void updateAppSetting(final DeployTarget deployTarget, final String key, final String value); static CloudStorageAccount getCloudStorageAccount(final DeployTarget target); }### Answer:
@Test public void testGetCloudStorageAccount() throws Exception { final String storageConnection = "DefaultEndpointsProtocol=https;AccountName=123456;AccountKey=12345678;EndpointSuffix=core.windows.net"; final Map mapSettings = mock(Map.class); final DeployTarget deployTarget = mock(DeployTarget.class); final AppSetting storageSetting = mock(AppSetting.class); mapSettings.put(INTERNAL_STORAGE_KEY, storageSetting); doReturn(mapSettings).when(deployTarget).getAppSettings(); doReturn(storageSetting).when(mapSettings).get(anyString()); doReturn(storageConnection).when(storageSetting).value(); final CloudStorageAccount storageAccount = FunctionArtifactHelper.getCloudStorageAccount(deployTarget); assertNotNull(storageAccount); }
@Test public void testGetCloudStorageAccountWithException() { final FunctionApp app = mock(FunctionApp.class); final DeployTarget deployTarget = mock(DeployTarget.class); final Map appSettings = mock(Map.class); doReturn(appSettings).when(app).getAppSettings(); doReturn(null).when(appSettings).get(anyString()); String exceptionMessage = null; try { FunctionArtifactHelper.getCloudStorageAccount(deployTarget); } catch (Exception e) { exceptionMessage = e.getMessage(); } finally { assertEquals("Application setting 'AzureWebJobsStorage' not found.", exceptionMessage); } } |
### Question:
DeployMojo extends AbstractFunctionMojo { protected FunctionApp updateFunctionApp(final FunctionApp app, final FunctionRuntimeHandler runtimeHandler) throws AzureAuthFailureException, AzureExecutionException { Log.info(FUNCTION_APP_UPDATE); runtimeHandler.updateAppServicePlan(app); final Update update = runtimeHandler.updateAppRuntime(app); updateFunctionAppSettings(update); final FunctionApp result = update.apply(); Log.info(String.format(FUNCTION_APP_UPDATE_DONE, getAppName())); return result; } @Override DeploymentType getDeploymentType(); }### Answer:
@Test public void updateFunctionApp() throws Exception { final FunctionApp app = mock(FunctionApp.class); final Update update = mock(Update.class); doNothing().when(mojoSpy).configureAppSettings(any(Consumer.class), anyMap()); final FunctionRuntimeHandler functionRuntimeHandler = mock(WindowsFunctionRuntimeHandler.class); doReturn(update).when(functionRuntimeHandler).updateAppRuntime(app); mojoSpy.updateFunctionApp(app, functionRuntimeHandler); verify(update, times(1)).apply(); } |
### Question:
FunctionArtifactHelper { public static void updateAppSetting(final DeployTarget deployTarget, final String key, final String value) throws AzureExecutionException { final WebAppBase targetApp = deployTarget.getApp(); if (targetApp instanceof FunctionApp) { ((FunctionApp) targetApp).update().withAppSetting(key, value).apply(); } else if (targetApp instanceof FunctionDeploymentSlot) { ((FunctionDeploymentSlot) targetApp).update().withAppSetting(key, value).apply(); } else { throw new AzureExecutionException(UNSUPPORTED_DEPLOYMENT_TARGET); } } static File createFunctionArtifact(final String stagingDirectoryPath); static void updateAppSetting(final DeployTarget deployTarget, final String key, final String value); static CloudStorageAccount getCloudStorageAccount(final DeployTarget target); }### Answer:
@Test public void testUpdateAppSetting() throws Exception { final DeployTarget deployTarget = mock(DeployTarget.class); final FunctionApp functionApp = mock(FunctionApp.class); doReturn(functionApp).when(deployTarget).getApp(); final FunctionApp.Update update = mock(FunctionApp.Update.class); doReturn(update).when(functionApp).update(); doReturn(update).when(update).withAppSetting(any(), any()); doReturn(functionApp).when(update).apply(); final String appSettingKey = "KEY"; final String appSettingValue = "VALUE"; FunctionArtifactHelper.updateAppSetting(deployTarget, appSettingKey, appSettingValue); verify(deployTarget, times(1)).getApp(); verify(functionApp, times(1)).update(); verify(update, times(1)).withAppSetting(appSettingKey, appSettingValue); verify(update, times(1)).apply(); verifyNoMoreInteractions(update); verifyNoMoreInteractions(functionApp); verifyNoMoreInteractions(deployTarget); }
@Test public void testUpdateAppSettingWithException() { final DeployTarget deployTarget = mock(DeployTarget.class); final WebApp webapp = mock(WebApp.class); doReturn(webapp).when(deployTarget).getApp(); final String appSettingKey = "KEY"; final String appSettingValue = "VALUE"; String exceptionMessage = null; try { FunctionArtifactHelper.updateAppSetting(deployTarget, appSettingKey, appSettingValue); } catch (Exception e) { exceptionMessage = e.getMessage(); } finally { assertEquals("Unsupported deployment target, only function is supported", exceptionMessage); } } |
### Question:
FunctionArtifactHelper { public static File createFunctionArtifact(final String stagingDirectoryPath) throws AzureExecutionException { final File stageDirectory = new File(stagingDirectoryPath); final File zipPackage = new File(stagingDirectoryPath.concat(Constants.ZIP_EXT)); if (!stageDirectory.exists() || !stageDirectory.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } ZipUtil.pack(stageDirectory, zipPackage); ZipUtil.removeEntry(zipPackage, LOCAL_SETTINGS_FILE); return zipPackage; } static File createFunctionArtifact(final String stagingDirectoryPath); static void updateAppSetting(final DeployTarget deployTarget, final String key, final String value); static CloudStorageAccount getCloudStorageAccount(final DeployTarget target); }### Answer:
@Test public void testCreateFunctionArtifactWithException() { String exceptionMessage = null; try { FunctionArtifactHelper.createFunctionArtifact(""); } catch (Exception e) { exceptionMessage = e.getMessage(); } finally { assertEquals("Azure Functions stage directory not found. Please run 'mvn clean" + " azure-functions:package' first.", exceptionMessage); } } |
### Question:
FunctionCoreToolsHandlerImpl implements FunctionCoreToolsHandler { @Override public void installExtension(File stagingDirectory, File basedir) throws AzureExecutionException { assureRequirementAddressed(); installFunctionExtension(stagingDirectory, basedir); } FunctionCoreToolsHandlerImpl(final CommandHandler commandHandler); @Override void installExtension(File stagingDirectory, File basedir); static final String FUNC_EXTENSIONS_INSTALL_TEMPLATE; static final String INSTALL_FUNCTION_EXTENSIONS_FAIL; static final String CANNOT_AUTO_INSTALL; static final String NEED_UPDATE_FUNCTION_CORE_TOOLS; static final String GET_LATEST_VERSION_CMD; static final String GET_LATEST_VERSION_FAIL; static final String GET_LOCAL_VERSION_CMD; static final String GET_LOCAL_VERSION_FAIL; static final Version LEAST_SUPPORTED_VERSION; }### Answer:
@Test public void installExtension() throws Exception { final CommandHandler commandHandler = mock(CommandHandler.class); final FunctionCoreToolsHandlerImpl functionCoreToolsHandler = new FunctionCoreToolsHandlerImpl(commandHandler); final FunctionCoreToolsHandlerImpl functionCoreToolsHandlerSpy = spy(functionCoreToolsHandler); doReturn("3.0.0").when(functionCoreToolsHandlerSpy).getLocalFunctionCoreToolsVersion(); doReturn("3.0.0").when(functionCoreToolsHandlerSpy).getLatestFunctionCoreToolsVersion(); doNothing().when(functionCoreToolsHandlerSpy).installFunctionExtension(new File("folder1"), new File("folder2")); functionCoreToolsHandlerSpy.installExtension(new File("folder1"), new File("folder2")); } |
### Question:
FunctionCoreToolsHandlerImpl implements FunctionCoreToolsHandler { protected String getLocalFunctionCoreToolsVersion() { try { final String localVersion = commandHandler.runCommandAndGetOutput( GET_LOCAL_VERSION_CMD, false, null ); Version.valueOf(localVersion); return localVersion; } catch (Exception e) { Log.warn(GET_LOCAL_VERSION_FAIL); return null; } } FunctionCoreToolsHandlerImpl(final CommandHandler commandHandler); @Override void installExtension(File stagingDirectory, File basedir); static final String FUNC_EXTENSIONS_INSTALL_TEMPLATE; static final String INSTALL_FUNCTION_EXTENSIONS_FAIL; static final String CANNOT_AUTO_INSTALL; static final String NEED_UPDATE_FUNCTION_CORE_TOOLS; static final String GET_LATEST_VERSION_CMD; static final String GET_LATEST_VERSION_FAIL; static final String GET_LOCAL_VERSION_CMD; static final String GET_LOCAL_VERSION_FAIL; static final Version LEAST_SUPPORTED_VERSION; }### Answer:
@Test public void getLocalFunctionCoreToolsVersion() throws Exception { final CommandHandler commandHandler = mock(CommandHandler.class); final FunctionCoreToolsHandlerImpl functionCoreToolsHandler = new FunctionCoreToolsHandlerImpl(commandHandler); final FunctionCoreToolsHandlerImpl functionCoreToolsHandlerSpy = spy(functionCoreToolsHandler); doReturn("2.0.1-beta.26") .when(commandHandler).runCommandAndGetOutput(anyString(), anyBoolean(), any()); assertEquals("2.0.1-beta.26", functionCoreToolsHandlerSpy.getLocalFunctionCoreToolsVersion()); }
@Test public void getLocalFunctionCoreToolsVersionFailed() throws Exception { final CommandHandler commandHandler = mock(CommandHandler.class); final FunctionCoreToolsHandlerImpl functionCoreToolsHandler = new FunctionCoreToolsHandlerImpl(commandHandler); final FunctionCoreToolsHandlerImpl functionCoreToolsHandlerSpy = spy(functionCoreToolsHandler); doReturn("unexpected output") .when(commandHandler).runCommandAndGetOutput(anyString(), anyBoolean(), any()); assertNull(functionCoreToolsHandlerSpy.getLocalFunctionCoreToolsVersion()); } |
### Question:
FunctionCoreToolsHandlerImpl implements FunctionCoreToolsHandler { protected void installFunctionExtension(File stagingDirector, File basedir) throws AzureExecutionException { commandHandler.runCommandWithReturnCodeCheck( String.format(FUNC_EXTENSIONS_INSTALL_TEMPLATE, basedir.getAbsolutePath()), true, stagingDirector.getAbsolutePath(), CommandUtils.getDefaultValidReturnCodes(), INSTALL_FUNCTION_EXTENSIONS_FAIL ); } FunctionCoreToolsHandlerImpl(final CommandHandler commandHandler); @Override void installExtension(File stagingDirectory, File basedir); static final String FUNC_EXTENSIONS_INSTALL_TEMPLATE; static final String INSTALL_FUNCTION_EXTENSIONS_FAIL; static final String CANNOT_AUTO_INSTALL; static final String NEED_UPDATE_FUNCTION_CORE_TOOLS; static final String GET_LATEST_VERSION_CMD; static final String GET_LATEST_VERSION_FAIL; static final String GET_LOCAL_VERSION_CMD; static final String GET_LOCAL_VERSION_FAIL; static final Version LEAST_SUPPORTED_VERSION; }### Answer:
@Test public void installFunctionExtension() throws Exception { final CommandHandler commandHandler = mock(CommandHandler.class); final FunctionCoreToolsHandlerImpl functionCoreToolsHandler = new FunctionCoreToolsHandlerImpl(commandHandler); final FunctionCoreToolsHandlerImpl functionCoreToolsHandlerSpy = spy(functionCoreToolsHandler); doNothing().when(commandHandler).runCommandWithReturnCodeCheck(anyString(), anyBoolean(), any(), ArgumentMatchers.anyList(), anyString()); functionCoreToolsHandlerSpy.installFunctionExtension(new File("path1"), new File("path2")); verify(commandHandler, times(1)).runCommandWithReturnCodeCheck( String.format(FUNC_EXTENSIONS_INSTALL_TEMPLATE, new File("path2").getAbsolutePath()), true, new File("path1").getAbsolutePath(), CommandUtils.getDefaultValidReturnCodes(), INSTALL_FUNCTION_EXTENSIONS_FAIL ); } |
### Question:
CommandHandlerImpl implements CommandHandler { protected static String[] buildCommand(final String command) { return CommandUtils.isWindows() ? new String[]{"cmd.exe", "/c", command} : new String[]{"sh", "-c", command}; } @Override void runCommandWithReturnCodeCheck(final String command,
final boolean showStdout,
final String workingDirectory,
final List<Long> validReturnCodes,
final String errorMessage); @Override String runCommandAndGetOutput(final String command,
final boolean showStdout,
final String workingDirectory); }### Answer:
@Test public void buildCommand() { assertEquals(3, CommandHandlerImpl.buildCommand("cmd").length); } |
### Question:
CommandHandlerImpl implements CommandHandler { protected static ProcessBuilder.Redirect getStdoutRedirect(boolean showStdout) { return showStdout ? ProcessBuilder.Redirect.INHERIT : ProcessBuilder.Redirect.PIPE; } @Override void runCommandWithReturnCodeCheck(final String command,
final boolean showStdout,
final String workingDirectory,
final List<Long> validReturnCodes,
final String errorMessage); @Override String runCommandAndGetOutput(final String command,
final boolean showStdout,
final String workingDirectory); }### Answer:
@Test public void getStdoutRedirect() { assertEquals(ProcessBuilder.Redirect.INHERIT, CommandHandlerImpl.getStdoutRedirect(true)); assertEquals(ProcessBuilder.Redirect.PIPE, CommandHandlerImpl.getStdoutRedirect(false)); } |
### Question:
DeployMojo extends AbstractFunctionMojo { protected void configureAppSettings(final Consumer<Map> withAppSettings, final Map appSettings) { if (appSettings != null && !appSettings.isEmpty()) { withAppSettings.accept(appSettings); } } @Override DeploymentType getDeploymentType(); }### Answer:
@Test public void configureAppSettings() throws Exception { final WithCreate withCreate = mock(WithCreate.class); mojo.configureAppSettings(withCreate::withAppSettings, mojo.getAppSettingsWithDefaultValue()); verify(withCreate, times(1)).withAppSettings(anyMap()); } |
### Question:
CommandHandlerImpl implements CommandHandler { protected void handleExitValue(int exitValue, final List<Long> validReturnCodes, final String errorMessage, final InputStream inputStream) throws AzureExecutionException, IOException { Log.debug("Process exit value: " + exitValue); if (!validReturnCodes.contains(Integer.toUnsignedLong(exitValue))) { showErrorIfAny(inputStream); Log.error(errorMessage); throw new AzureExecutionException(errorMessage); } } @Override void runCommandWithReturnCodeCheck(final String command,
final boolean showStdout,
final String workingDirectory,
final List<Long> validReturnCodes,
final String errorMessage); @Override String runCommandAndGetOutput(final String command,
final boolean showStdout,
final String workingDirectory); }### Answer:
@Test(expected = Exception.class) public void handleExitValue() throws Exception { final CommandHandlerImpl handler = new CommandHandlerImpl(); handler.handleExitValue(1, Arrays.asList(0L), "", null); } |
### Question:
CommandUtils { public static boolean isWindows() { return SystemUtils.IS_OS_WINDOWS; } static boolean isWindows(); static List<Long> getDefaultValidReturnCodes(); static List<Long> getValidReturnCodes(); }### Answer:
@Test public void isWindows() { assertEquals(SystemUtils.IS_OS_WINDOWS, CommandUtils.isWindows()); } |
### Question:
CommandUtils { public static List<Long> getDefaultValidReturnCodes() { return Arrays.asList(0L); } static boolean isWindows(); static List<Long> getDefaultValidReturnCodes(); static List<Long> getValidReturnCodes(); }### Answer:
@Test public void getDefaultValidReturnCodes() throws Exception { assertEquals(2, CommandUtils.getValidReturnCodes().size()); assertEquals(true, CommandUtils.getValidReturnCodes().contains(0L)); } |
### Question:
CommandUtils { public static List<Long> getValidReturnCodes() { return isWindows() ? Arrays.asList(0L, 3221225786L) : Arrays.asList(0L, 130L); } static boolean isWindows(); static List<Long> getDefaultValidReturnCodes(); static List<Long> getValidReturnCodes(); }### Answer:
@Test public void getValidReturnCodes() { assertEquals(Arrays.asList(0L), CommandUtils.getDefaultValidReturnCodes()); } |
### Question:
FTPUploader { public void uploadDirectoryWithRetries(final String ftpServer, final String username, final String password, final String sourceDirectory, final String targetDirectory, final int maxRetryCount) throws AzureExecutionException { int retryCount = 0; while (retryCount < maxRetryCount) { retryCount++; Log.prompt(UPLOAD_START + ftpServer); if (uploadDirectory(ftpServer, username, password, sourceDirectory, targetDirectory)) { Log.prompt(UPLOAD_SUCCESS + ftpServer); return; } else { Log.warn(String.format(UPLOAD_FAILURE, retryCount, maxRetryCount)); } } throw new AzureExecutionException(String.format(UPLOAD_RETRY_FAILURE, maxRetryCount)); } void uploadDirectoryWithRetries(final String ftpServer, final String username, final String password,
final String sourceDirectory, final String targetDirectory,
final int maxRetryCount); static final String UPLOAD_START; static final String UPLOAD_SUCCESS; static final String UPLOAD_FAILURE; static final String UPLOAD_RETRY_FAILURE; static final String UPLOAD_DIR_START; static final String UPLOAD_DIR_FINISH; static final String UPLOAD_DIR_FAILURE; static final String UPLOAD_DIR; static final String UPLOAD_FILE; static final String UPLOAD_FILE_REPLY; }### Answer:
@Test public void uploadDirectoryWithRetries() throws Exception { final FTPUploader uploaderSpy = spy(ftpUploader); AzureExecutionException exception = null; doReturn(false).when(uploaderSpy).uploadDirectory(anyString(), anyString(), anyString(), anyString(), anyString()); try { uploaderSpy.uploadDirectoryWithRetries("ftpServer", "username", "password", "sourceDir", "targetDir", 1); } catch (AzureExecutionException e) { exception = e; } finally { assertNotNull(exception); } doReturn(true).when(uploaderSpy).uploadDirectory(anyString(), anyString(), anyString(), anyString(), anyString()); uploaderSpy.uploadDirectoryWithRetries("ftpServer", "username", "password", "sourceDir", "targetDir", 1); } |
### Question:
FTPUploader { protected boolean uploadDirectory(final String ftpServer, final String username, final String password, final String sourceDirectoryPath, final String targetDirectoryPath) { Log.debug("FTP username: " + username); try { final FTPClient ftpClient = getFTPClient(ftpServer, username, password); Log.prompt(String.format(UPLOAD_DIR_START, sourceDirectoryPath, targetDirectoryPath)); uploadDirectory(ftpClient, sourceDirectoryPath, targetDirectoryPath, ""); Log.prompt(String.format(UPLOAD_DIR_FINISH, sourceDirectoryPath, targetDirectoryPath)); ftpClient.disconnect(); return true; } catch (Exception e) { Log.debug(e); Log.error(String.format(UPLOAD_DIR_FAILURE, sourceDirectoryPath, targetDirectoryPath)); } return false; } void uploadDirectoryWithRetries(final String ftpServer, final String username, final String password,
final String sourceDirectory, final String targetDirectory,
final int maxRetryCount); static final String UPLOAD_START; static final String UPLOAD_SUCCESS; static final String UPLOAD_FAILURE; static final String UPLOAD_RETRY_FAILURE; static final String UPLOAD_DIR_START; static final String UPLOAD_DIR_FINISH; static final String UPLOAD_DIR_FAILURE; static final String UPLOAD_DIR; static final String UPLOAD_FILE; static final String UPLOAD_FILE_REPLY; }### Answer:
@Test public void uploadDirectory() throws Exception { final FTPUploader uploaderSpy = spy(ftpUploader); final FTPClient ftpClient = mock(FTPClient.class); doReturn(ftpClient).when(uploaderSpy).getFTPClient(anyString(), anyString(), anyString()); doNothing().when(uploaderSpy).uploadDirectory(any(FTPClient.class), anyString(), anyString(), anyString()); uploaderSpy.uploadDirectory(anyString(), anyString(), anyString(), anyString(), anyString()); verify(ftpClient, times(1)).disconnect(); verifyNoMoreInteractions(ftpClient); verify(uploaderSpy, times(1)).uploadDirectory(any(FTPClient.class), anyString(), anyString(), anyString()); verify(uploaderSpy, times(1)).getFTPClient(anyString(), anyString(), anyString()); verify(uploaderSpy, times(1)).uploadDirectory(anyString(), anyString(), anyString(), anyString(), anyString()); verifyNoMoreInteractions(uploaderSpy); } |
### Question:
FTPUploader { protected FTPClient getFTPClient(final String ftpServer, final String username, final String password) throws IOException { final FTPClient ftpClient = new FTPClient(); ftpClient.connect(ftpServer); ftpClient.login(username, password); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); return ftpClient; } void uploadDirectoryWithRetries(final String ftpServer, final String username, final String password,
final String sourceDirectory, final String targetDirectory,
final int maxRetryCount); static final String UPLOAD_START; static final String UPLOAD_SUCCESS; static final String UPLOAD_FAILURE; static final String UPLOAD_RETRY_FAILURE; static final String UPLOAD_DIR_START; static final String UPLOAD_DIR_FINISH; static final String UPLOAD_DIR_FAILURE; static final String UPLOAD_DIR; static final String UPLOAD_FILE; static final String UPLOAD_FILE_REPLY; }### Answer:
@Test public void getFTPClient() throws Exception { Exception caughtException = null; try { ftpUploader.getFTPClient("fakeFTPServer", "username", "password"); } catch (Exception e) { caughtException = e; } finally { assertNotNull(caughtException); } } |
### Question:
Utils { public static OperatingSystemEnum parseOperationSystem(final String os) throws AzureExecutionException { if (StringUtils.isEmpty(os)) { throw new AzureExecutionException("The value of 'os' is empty, please specify it in 'runtime' configuration."); } switch (os.toLowerCase(Locale.ENGLISH)) { case "windows": return OperatingSystemEnum.Windows; case "linux": return OperatingSystemEnum.Linux; case "docker": return OperatingSystemEnum.Docker; default: throw new AzureExecutionException("The value of <os> is unknown, supported values are: windows, " + "linux and docker."); } } static String getArtifactCompileVersion(File artifact); static OperatingSystemEnum parseOperationSystem(final String os); static boolean isGUID(String input); static String getSegment(String id, String segment); static String getSubscriptionId(String resourceId); static boolean isPomPackagingProject(String packaging); static boolean isJarPackagingProject(String packaging); static boolean isWarPackagingProject(String packaging); }### Answer:
@Test public void testParseOperationSystem() throws Exception { assertEquals(OperatingSystemEnum.Windows, Utils.parseOperationSystem("windows")); assertEquals(OperatingSystemEnum.Linux, Utils.parseOperationSystem("Linux")); assertEquals(OperatingSystemEnum.Docker, Utils.parseOperationSystem("dOcker")); }
@Test public void testParseOperationSystemUnknown() throws Exception { try { Utils.parseOperationSystem("unkown"); fail("expected AzureExecutionException when os is invalid"); } catch (AzureExecutionException ex) { } try { Utils.parseOperationSystem("windows "); fail("expected AzureExecutionException when os has spaces"); } catch (AzureExecutionException ex) { } try { Utils.parseOperationSystem(" "); fail("expected AzureExecutionException when os is empty"); } catch (AzureExecutionException ex) { } try { Utils.parseOperationSystem(null); fail("expected AzureExecutionException when os is null"); } catch (AzureExecutionException ex) { } } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public MavenProject getProject() { return project; } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void getProject() throws Exception { assertEquals(project, mojo.getProject()); } |
### Question:
DeployMojo extends AbstractFunctionMojo { protected ArtifactHandler getArtifactHandler() throws AzureExecutionException { final ArtifactHandlerBase.Builder builder; final DeploymentType deploymentType = getDeploymentType(); getTelemetryProxy().addDefaultProperty(DEPLOYMENT_TYPE_KEY, deploymentType.toString()); switch (deploymentType) { case MSDEPLOY: builder = new MSDeployArtifactHandlerImpl.Builder().functionAppName(this.getAppName()); break; case FTP: builder = new FTPArtifactHandlerImpl.Builder(); break; case ZIP: builder = new ZIPArtifactHandlerImpl.Builder(); break; case RUN_FROM_BLOB: builder = new RunFromBlobArtifactHandlerImpl.Builder(); break; case DOCKER: builder = new DockerArtifactHandler.Builder(); break; case EMPTY: case RUN_FROM_ZIP: builder = new RunFromZipArtifactHandlerImpl.Builder(); break; default: throw new AzureExecutionException(UNKNOWN_DEPLOYMENT_TYPE); } return builder.project(ProjectUtils.convertCommonProject(this.getProject())) .stagingDirectoryPath(this.getDeploymentStagingDirectoryPath()) .buildDirectoryAbsolutePath(this.getBuildDirectoryAbsolutePath()) .build(); } @Override DeploymentType getDeploymentType(); }### Answer:
@Test(expected = AzureExecutionException.class) public void getArtifactHandlerThrowException() throws Exception { getMojoFromPom().getArtifactHandler(); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public MavenSession getSession() { return session; } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void getSession() throws Exception { assertEquals(session, mojo.getSession()); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public MavenResourcesFiltering getMavenResourcesFiltering() { return mavenResourcesFiltering; } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void getMavenResourcesFiltering() throws Exception { assertEquals(filtering, mojo.getMavenResourcesFiltering()); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public String getBuildDirectoryAbsolutePath() { return buildDirectory.getAbsolutePath(); } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void getBuildDirectoryAbsolutePath() throws Exception { assertEquals("target", mojo.getBuildDirectoryAbsolutePath()); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { @Override public AuthenticationSetting getAuthenticationSetting() { return authentication; } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void getAuthenticationSetting() throws Exception { assertEquals(authenticationSetting, mojo.getAuthenticationSetting()); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public Azure getAzureClient() throws AzureAuthFailureException { if (azure == null) { if (this.authentication != null && (this.authentication.getFile() != null || StringUtils.isNotBlank(authentication.getServerId()))) { Log.warn("You are using an old way of authentication which will be deprecated in future versions, please change your configurations."); azure = new AzureAuthHelperLegacy(this).getAzureClient(); } else { initAuth(); azure = getAzureClientByAuthType(); } if (azure == null) { getTelemetryProxy().trackEvent(INIT_FAILURE); throw new AzureAuthFailureException(AZURE_INIT_FAIL); } printCurrentSubscription(azure); getTelemetryProxy().addDefaultProperty(AUTH_TYPE, authType); getTelemetryProxy().addDefaultProperty(AUTH_METHOD, getAuthMethod()); getTelemetryProxy().addDefaultProperty(SUBSCRIPTION_ID_KEY, azure.subscriptionId()); } return azure; } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void getAzureClient() throws Exception { assertEquals(azure, mojo.getAzureClient()); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { @Override public Settings getSettings() { return settings; } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void getMavenSettings() { assertEquals(settings, mojo.getSettings()); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { @Override public String getSubscriptionId() { return subscriptionId; } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void getSubscriptionId() throws Exception { assertEquals(SUBSCRIPTION_ID, mojo.getSubscriptionId()); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public TelemetryProxy getTelemetryProxy() { if (telemetryProxy == null) { initTelemetry(); } return telemetryProxy; } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void getTelemetryProxy() { assertEquals(telemetryProxy, mojo.getTelemetryProxy()); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { public boolean isTelemetryAllowed() { return allowTelemetry; } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void isTelemetryAllowed() throws Exception { assertTrue(!mojo.isTelemetryAllowed()); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { @Override public void execute() throws MojoExecutionException { try { Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); final Properties prop = new Properties(); if (isFirstRun(prop)) { infoWithMultipleLines(PRIVACY_STATEMENT); updateConfigurationFile(prop); } if (isSkipMojo()) { Log.info("Skip execution."); trackMojoSkip(); } else { trackMojoStart(); doExecute(); trackMojoSuccess(); } } catch (Exception e) { handleException(e); } finally { try { Thread.sleep(2 * 1000); } catch (InterruptedException e) { } ApacheSenderFactory.INSTANCE.create().close(); } } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void execute() throws Exception { mojo.execute(); } |
### Question:
DeployMojo extends AbstractFunctionMojo { protected DeploymentType getDeploymentTypeByRuntime() throws AzureExecutionException { final OperatingSystemEnum operatingSystemEnum = getOsEnum(); switch (operatingSystemEnum) { case Docker: return DOCKER; case Linux: return isDedicatedPricingTier() ? RUN_FROM_ZIP : RUN_FROM_BLOB; default: return RUN_FROM_ZIP; } } @Override DeploymentType getDeploymentType(); }### Answer:
@Test public void testGetDeploymentTypeByRuntime() throws AzureExecutionException { doReturn(Windows).when(mojoSpy).getOsEnum(); assertEquals(RUN_FROM_ZIP, mojoSpy.getDeploymentTypeByRuntime()); doReturn(Linux).when(mojoSpy).getOsEnum(); doReturn(true).when(mojoSpy).isDedicatedPricingTier(); assertEquals(RUN_FROM_ZIP, mojoSpy.getDeploymentTypeByRuntime()); doReturn(false).when(mojoSpy).isDedicatedPricingTier(); assertEquals(RUN_FROM_BLOB, mojoSpy.getDeploymentTypeByRuntime()); doReturn(Docker).when(mojoSpy).getOsEnum(); assertEquals(DOCKER, mojoSpy.getDeploymentTypeByRuntime()); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { protected void handleException(final Exception exception) throws MojoExecutionException { String message = exception.getMessage(); if (StringUtils.isEmpty(message)) { message = exception.toString(); } trackMojoFailure(message); if (isFailingOnError()) { throw new MojoExecutionException(message, exception); } else { Log.error(message); } } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void processException() throws Exception { final String message = "test exception message"; String actualMessage = null; try { mojo.handleException(new Exception(message)); } catch (Exception e) { actualMessage = e.getMessage(); } assertEquals(message, actualMessage); } |
### Question:
AbstractAzureMojo extends AbstractMojo implements TelemetryConfiguration, AuthConfiguration { @Override public Map<String, String> getTelemetryProperties() { final Map<String, String> map = new HashMap<>(); map.put(INSTALLATION_ID_KEY, getInstallationId()); map.put(PLUGIN_NAME_KEY, getPluginName()); map.put(PLUGIN_VERSION_KEY, getPluginVersion()); map.put(SUBSCRIPTION_ID_KEY, getSubscriptionId()); map.put(SESSION_ID_KEY, getSessionId()); return map; } MavenProject getProject(); MavenSession getSession(); String getBuildDirectoryAbsolutePath(); MavenResourcesFiltering getMavenResourcesFiltering(); @Override Settings getSettings(); @Override AuthenticationSetting getAuthenticationSetting(); @Override String getSubscriptionId(); boolean isTelemetryAllowed(); boolean isFailingOnError(); String getSessionId(); String getInstallationId(); String getPluginName(); String getPluginVersion(); @Override String getUserAgent(); @Override String getHttpProxyHost(); @Override int getHttpProxyPort(); Azure getAzureClient(); TelemetryProxy getTelemetryProxy(); @Override Map<String, String> getTelemetryProperties(); String getAuthMethod(); @Override void execute(); void infoWithMultipleLines(final String messages); static final String PLUGIN_NAME_KEY; static final String PLUGIN_VERSION_KEY; static final String INSTALLATION_ID_KEY; static final String SESSION_ID_KEY; static final String SUBSCRIPTION_ID_KEY; static final String AUTH_TYPE; static final String AUTH_METHOD; static final String TELEMETRY_NOT_ALLOWED; static final String INIT_FAILURE; static final String AZURE_INIT_FAIL; static final String FAILURE_REASON; }### Answer:
@Test public void getTelemetryProperties() throws Exception { final Map map = mojo.getTelemetryProperties(); assertEquals(5, map.size()); assertTrue(map.containsKey(INSTALLATION_ID_KEY)); assertTrue(map.containsKey(PLUGIN_NAME_KEY)); assertTrue(map.containsKey(PLUGIN_VERSION_KEY)); assertTrue(map.containsKey(SUBSCRIPTION_ID_KEY)); assertTrue(map.containsKey(SESSION_ID_KEY)); } |
### Question:
SettingsHandlerImpl implements SettingsHandler { @Override public void processSettings(WithCreate withCreate) throws AzureExecutionException { final Map appSettings = mojo.getAppSettings(); if (appSettings != null && !appSettings.isEmpty()) { withCreate.withAppSettings(appSettings); } } SettingsHandlerImpl(final AbstractWebAppMojo mojo); @Override void processSettings(WithCreate withCreate); @Override void processSettings(Update update); }### Answer:
@Test public void processSettings() throws Exception { final WithCreate withCreate = mock(WithCreate.class); handler.processSettings(withCreate); verify(withCreate, times(1)).withAppSettings(ArgumentMatchers.<String, String>anyMap()); }
@Test public void processSettings1() throws Exception { final Update update = mock(Update.class); handler.processSettings(update); verify(update, times(1)).withAppSettings(ArgumentMatchers.<String, String>anyMap()); } |
### Question:
DeploymentSlotHandler { public void createDeploymentSlotIfNotExist() throws AzureExecutionException, AzureAuthFailureException { final DeploymentSlotSetting slotSetting = this.mojo.getDeploymentSlotSetting(); assureValidSlotSetting(slotSetting); final WebApp app = this.mojo.getWebApp(); final String slotName = slotSetting.getName(); if (this.mojo.getDeploymentSlot(app, slotName) == null) { createDeploymentSlot(app, slotName, slotSetting.getConfigurationSource()); } } DeploymentSlotHandler(final AbstractWebAppMojo mojo); void createDeploymentSlotIfNotExist(); }### Answer:
@Test public void createDeploymentSlotIfNotExist() throws AzureAuthFailureException, AzureExecutionException { final DeploymentSlotHandler handlerSpy = spy(handler); final DeploymentSlotSetting slotSetting = mock(DeploymentSlotSetting.class); final WebApp app = mock(WebApp.class); doReturn(app).when(mojo).getWebApp(); doReturn(slotSetting).when(mojo).getDeploymentSlotSetting(); doReturn("").when(slotSetting).getConfigurationSource(); doReturn("").when(slotSetting).getName(); doReturn(null).when(mojo).getDeploymentSlot(app, ""); doNothing().when(handlerSpy).createDeploymentSlot(app, "", ""); handlerSpy.createDeploymentSlotIfNotExist(); verify(handlerSpy, times(1)).createDeploymentSlotIfNotExist(); verify(handlerSpy, times(1)).createDeploymentSlot(app, "", ""); } |
### Question:
DeploymentSlotHandler { protected void createDeploymentSlot(final WebApp app, final String slotName, final String configurationSource) throws AzureExecutionException { assureValidSlotName(slotName); final DeploymentSlot.DefinitionStages.Blank definedSlot = app.deploymentSlots().define(slotName); final ConfigurationSourceType type = ConfigurationSourceType.fromString(configurationSource); switch (type) { case NEW: Log.info(EMPTY_CONFIGURATION_SOURCE); definedSlot.withBrandNewConfiguration().create(); break; case PARENT: Log.info(DEFAULT_CONFIGURATION_SOURCE); definedSlot.withConfigurationFromParent().create(); break; case OTHERS: final DeploymentSlot configurationSourceSlot = this.mojo.getDeploymentSlot(app, configurationSource); if (configurationSourceSlot == null) { throw new AzureExecutionException(TARGET_CONFIGURATION_SOURCE_SLOT_NOT_EXIST); } Log.info(String.format(COPY_CONFIGURATION_FROM_SLOT, configurationSource)); definedSlot.withConfigurationFromDeploymentSlot(configurationSourceSlot).create(); break; default: throw new AzureExecutionException(UNKNOWN_CONFIGURATION_SOURCE); } } DeploymentSlotHandler(final AbstractWebAppMojo mojo); void createDeploymentSlotIfNotExist(); }### Answer:
@Test public void createDeploymentSlotFromParent() throws AzureExecutionException { final DeploymentSlotHandler handlerSpy = spy(handler); final WebApp app = mock(WebApp.class); final DeploymentSlots slots = mock(DeploymentSlots.class); final Blank stage1 = mock(Blank.class); final WithCreate withCreate = mock(WithCreate.class); doReturn(slots).when(app).deploymentSlots(); doReturn(stage1).when(slots).define("test"); doReturn(withCreate).when(stage1).withConfigurationFromParent(); handlerSpy.createDeploymentSlot(app, "test", "parent"); verify(withCreate, times(1)).create(); }
@Test(expected = AzureExecutionException.class) public void createDeploymentSlotFromOtherDeploymentSlotThrowException() throws AzureExecutionException { final WebApp app = mock(WebApp.class); handler.createDeploymentSlot(app, "", "otherSlot"); }
@Test public void createBreadNewDeploymentSlot() throws AzureExecutionException { final DeploymentSlotHandler handlerSpy = spy(handler); final WebApp app = mock(WebApp.class); final DeploymentSlots slots = mock(DeploymentSlots.class); final Blank stage1 = mock(Blank.class); final WithCreate withCreate = mock(WithCreate.class); doReturn(slots).when(app).deploymentSlots(); doReturn(stage1).when(slots).define("test"); doReturn(withCreate).when(stage1).withBrandNewConfiguration(); handlerSpy.createDeploymentSlot(app, "test", "new"); verify(withCreate, times(1)).create(); } |
### Question:
DeploymentSlotHandler { protected void assureValidSlotName(final String slotName) throws AzureExecutionException { final Pattern pattern = Pattern.compile(SLOT_NAME_PATTERN, Pattern.CASE_INSENSITIVE); if (StringUtils.isEmpty(slotName) || !pattern.matcher(slotName).matches()) { throw new AzureExecutionException(INVALID_SLOT_NAME); } } DeploymentSlotHandler(final AbstractWebAppMojo mojo); void createDeploymentSlotIfNotExist(); }### Answer:
@Test(expected = AzureExecutionException.class) public void assureValidSlotNameThrowException() throws AzureExecutionException { final DeploymentSlotHandler handlerSpy = spy(handler); handlerSpy.assureValidSlotName("@#123"); }
@Test public void assureValidSlotName() throws AzureExecutionException { final DeploymentSlotHandler handlerSpy = spy(handler); handlerSpy.assureValidSlotName("slot-Name"); verify(handlerSpy, times(1)).assureValidSlotName("slot-Name"); } |
### Question:
DeployMojo extends AbstractFunctionMojo { protected FunctionDeploymentSlot createDeploymentSlot(final FunctionApp functionApp, final FunctionRuntimeHandler runtimeHandler) throws AzureExecutionException, AzureAuthFailureException { Log.info(FUNCTION_SLOT_CREATE_START); final DeploymentSlotSetting slotSetting = getDeploymentSlotSetting(); final FunctionDeploymentSlot.DefinitionStages.WithCreate withCreate = runtimeHandler.createDeploymentSlot(functionApp, slotSetting); final FunctionDeploymentSlot result = withCreate.create(); Log.info(String.format(FUNCTION_SLOT_CREATED, result.name())); return updateDeploymentSlot(withCreate.create(), runtimeHandler); } @Override DeploymentType getDeploymentType(); }### Answer:
@Test public void testCreateDeploymentSlot() throws AzureAuthFailureException, AzureExecutionException { final FunctionDeploymentSlot slot = mock(FunctionDeploymentSlot.class); final DeploymentSlotSetting slotSetting = new DeploymentSlotSetting(); slotSetting.setName("Test"); doReturn(slotSetting).when(mojoSpy).getDeploymentSlotSetting(); final FunctionRuntimeHandler runtimeHandler = mock(FunctionRuntimeHandler.class); final FunctionDeploymentSlot.DefinitionStages.WithCreate mockWithCreate = mock(FunctionDeploymentSlot.DefinitionStages.WithCreate.class); doReturn(slot).when(mockWithCreate).create(); doReturn(mockWithCreate).when(runtimeHandler).createDeploymentSlot(any(), any()); doReturn(runtimeHandler).when(mojoSpy).getFunctionRuntimeHandler(); final ArtifactHandler artifactHandler = mock(ArtifactHandler.class); doNothing().when(artifactHandler).publish(any()); doReturn(artifactHandler).when(mojoSpy).getArtifactHandler(); final FunctionApp app = mock(FunctionApp.class); doReturn(app).when(mojoSpy).getFunctionApp(); doNothing().when(mojoSpy).parseConfiguration(); doNothing().when(mojoSpy).checkArtifactCompileVersion(); doReturn(slot).when(mojoSpy).updateDeploymentSlot(any(), any()); doCallRealMethod().when(mojoSpy).createDeploymentSlot(any(), any()); doReturn(null).when(mojoSpy).getResourcePortalUrl(any()); PowerMockito.mockStatic(FunctionUtils.class); PowerMockito.when(FunctionUtils.getFunctionDeploymentSlotByName(any(), any())).thenReturn(null); mojoSpy.doExecute(); verify(mojoSpy, times(1)).doExecute(); verify(mojoSpy, times(1)).createOrUpdateResource(); verify(mojoSpy, times(1)).createDeploymentSlot(any(), any()); verify(mojoSpy, times(1)).updateDeploymentSlot(any(), any()); verify(artifactHandler, times(1)).publish(any()); verifyNoMoreInteractions(artifactHandler); } |
### Question:
LinuxRuntimeHandlerImpl extends WebAppRuntimeHandler { @Override public Update updateAppRuntime(WebApp app) throws AzureExecutionException { WebAppUtils.assureLinuxWebApp(app); return app.update().withBuiltInImage(runtime); } private LinuxRuntimeHandlerImpl(final Builder builder); @Override WebApp.DefinitionStages.WithCreate defineAppWithRuntime(); @Override Update updateAppRuntime(WebApp app); }### Answer:
@Test public void updateAppRuntimeTestV2() throws Exception { final WebApp app = mock(WebApp.class); final SiteInner siteInner = mock(SiteInner.class); doReturn(siteInner).when(app).inner(); doReturn("app,linux").when(siteInner).kind(); final WebApp.Update update = mock(WebApp.Update.class); doReturn(update).when(app).update(); doReturn(update).when(update).withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8); doReturn(RuntimeStack.TOMCAT_8_5_JRE8).when(config).getRuntimeStack(); initHandlerV2(); assertSame(update, handler.updateAppRuntime(app)); verify(update, times(1)).withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8); }
@Test public void updateAppRuntimeTestV1() throws Exception { final WebApp app = mock(WebApp.class); final SiteInner siteInner = mock(SiteInner.class); doReturn("app,linux").when(siteInner).kind(); doReturn(siteInner).when(app).inner(); final Update update = mock(Update.class); doReturn(update).when(app).update(); doReturn(update).when(update).withBuiltInImage(any(RuntimeStack.class)); doReturn(RuntimeStack.TOMCAT_8_5_JRE8).when(config).getRuntimeStack(); initHandlerV1(); assertSame(update, handler.updateAppRuntime(app)); verify(update, times(1)).withBuiltInImage(any(RuntimeStack.class)); } |
### Question:
PublicDockerHubRuntimeHandlerImpl extends WebAppRuntimeHandler { @Override public WebApp.Update updateAppRuntime(final WebApp app) throws AzureExecutionException { WebAppUtils.assureLinuxWebApp(app); return app.update().withPublicDockerHubImage(image); } private PublicDockerHubRuntimeHandlerImpl(final PublicDockerHubRuntimeHandlerImpl.Builder builder); @Override WebApp.DefinitionStages.WithCreate defineAppWithRuntime(); @Override WebApp.Update updateAppRuntime(final WebApp app); }### Answer:
@Test public void updateAppRuntimeV2() throws Exception { final SiteInner siteInner = mock(SiteInner.class); doReturn("app,linux").when(siteInner).kind(); final WebApp.Update update = mock(WebApp.Update.class); final WebApp app = mock(WebApp.class); doReturn(siteInner).when(app).inner(); doReturn(update).when(app).update(); doReturn("nginx").when(config).getImage(); initHandlerV2(); handler.updateAppRuntime(app); verify(update, times(1)).withPublicDockerHubImage("nginx"); verifyNoMoreInteractions(update); }
@Test public void updateAppRuntimeV1() throws Exception { final SiteInner siteInner = mock(SiteInner.class); doReturn("app,linux").when(siteInner).kind(); final Update update = mock(Update.class); final WebApp app = mock(WebApp.class); doReturn(siteInner).when(app).inner(); doReturn(update).when(app).update(); doReturn("nginx").when(config).getImage(); initHandlerV1(); handler.updateAppRuntime(app); verify(update, times(1)).withPublicDockerHubImage(any(String.class)); verifyNoMoreInteractions(update); } |
### Question:
NullRuntimeHandlerImpl implements RuntimeHandler<WebApp> { @Override public WithCreate defineAppWithRuntime() throws AzureExecutionException { throw new AzureExecutionException(NO_RUNTIME_CONFIG); } @Override WithCreate defineAppWithRuntime(); @Override Update updateAppRuntime(final WebApp app); @Override AppServicePlan updateAppServicePlan(final WebApp app); static final String NO_RUNTIME_CONFIG; }### Answer:
@Test public void defineAppWithRuntime() throws Exception { AzureExecutionException exception = null; try { handler.defineAppWithRuntime(); } catch (AzureExecutionException e) { exception = e; } finally { assertNotNull(exception); } } |
### Question:
NullRuntimeHandlerImpl implements RuntimeHandler<WebApp> { @Override public Update updateAppRuntime(final WebApp app) { return null; } @Override WithCreate defineAppWithRuntime(); @Override Update updateAppRuntime(final WebApp app); @Override AppServicePlan updateAppServicePlan(final WebApp app); static final String NO_RUNTIME_CONFIG; }### Answer:
@Test public void updateAppRuntime() { final WebApp app = mock(WebApp.class); assertNull(handler.updateAppRuntime(app)); } |
### Question:
PrivateRegistryRuntimeHandlerImpl extends WebAppRuntimeHandler { @Override public WebApp.Update updateAppRuntime(final WebApp app) throws AzureExecutionException { WebAppUtils.assureLinuxWebApp(app); return app.update() .withPrivateRegistryImage(image, registryUrl) .withCredentials(dockerCredentialProvider.getUsername(), dockerCredentialProvider.getPassword()); } private PrivateRegistryRuntimeHandlerImpl(final Builder builder); @Override WebApp.DefinitionStages.WithCreate defineAppWithRuntime(); @Override WebApp.Update updateAppRuntime(final WebApp app); }### Answer:
@Test public void updateAppRuntimeV2() throws Exception { final SiteInner siteInner = mock(SiteInner.class); doReturn("app,linux").when(siteInner).kind(); final WebApp.UpdateStages.WithCredentials withCredentials = mock(WebApp.UpdateStages.WithCredentials.class); final WebApp.Update update = mock(WebApp.Update.class); doReturn(withCredentials).when(update).withPrivateRegistryImage("", ""); final WebApp app = mock(WebApp.class); doReturn(siteInner).when(app).inner(); doReturn(update).when(app).update(); final Server server = mock(Server.class); final Settings settings = mock(Settings.class); doReturn(server).when(settings).getServer(anyString()); doReturn(settings).when(config).getMavenSettings(); doReturn("").when(config).getImage(); doReturn("").when(config).getRegistryUrl(); doReturn("serverId").when(config).getServerId(); initHandlerForV2(); handler.updateAppRuntime(app); verify(update, times(1)).withPrivateRegistryImage("", ""); verify(server, times(1)).getUsername(); verify(server, times(1)).getPassword(); }
@Test public void updateAppRuntimeV1() throws Exception { final SiteInner siteInner = mock(SiteInner.class); doReturn("app,linux").when(siteInner).kind(); final WithCredentials withCredentials = mock(WithCredentials.class); final Update update = mock(Update.class); doReturn(withCredentials).when(update).withPrivateRegistryImage(null, null); final WebApp app = mock(WebApp.class); doReturn(siteInner).when(app).inner(); doReturn(update).when(app).update(); doReturn("serverId").when(config).getServerId(); final Server server = mock(Server.class); final Settings settings = mock(Settings.class); doReturn(server).when(settings).getServer(anyString()); doReturn(settings).when(config).getMavenSettings(); initHandlerV1(); handler.updateAppRuntime(app); verify(update, times(1)).withPrivateRegistryImage(null, null); verify(server, times(1)).getUsername(); verify(server, times(1)).getPassword(); } |
### Question:
WindowsRuntimeHandlerImpl extends WebAppRuntimeHandler { @Override public Update updateAppRuntime(final WebApp app) throws AzureExecutionException { WebAppUtils.assureWindowsWebApp(app); final Update update = app.update(); update.withJavaVersion(javaVersion).withWebContainer(webContainer); return update; } private WindowsRuntimeHandlerImpl(final WindowsRuntimeHandlerImpl.Builder builder); @Override WithCreate defineAppWithRuntime(); @Override Update updateAppRuntime(final WebApp app); }### Answer:
@Test public void updateAppRuntimeTestV1() throws Exception { final SiteInner siteInner = mock(SiteInner.class); doReturn("app").when(siteInner).kind(); final WithWebContainer withWebContainer = mock(WithWebContainer.class); final Update update = mock(Update.class); doReturn(withWebContainer).when(update).withJavaVersion(null); final WebApp app = mock(WebApp.class); doReturn(siteInner).when(app).inner(); doReturn(update).when(app).update(); doReturn(WebContainer.TOMCAT_8_5_NEWEST).when(config).getWebContainer(); initHandlerV1(); assertSame(update, handler.updateAppRuntime(app)); verify(withWebContainer, times(1)).withWebContainer(WebContainer.TOMCAT_8_5_NEWEST); verifyNoMoreInteractions(withWebContainer); }
@Test public void updateAppRuntimeTestV2() throws Exception { final WebApp app = mock(WebApp.class); final SiteInner siteInner = mock(SiteInner.class); doReturn(siteInner).when(app).inner(); doReturn("app").when(siteInner).kind(); doReturn(WebContainer.TOMCAT_8_5_NEWEST).when(config).getWebContainer(); doReturn(JavaVersion.JAVA_8_NEWEST).when(config).getJavaVersion(); final WebAppBase.UpdateStages.WithWebContainer withWebContainer = mock(WebAppBase.UpdateStages.WithWebContainer.class); final WebApp.Update update = mock(WebApp.Update.class); doReturn(withWebContainer).when(update).withJavaVersion(JavaVersion.JAVA_8_NEWEST); doReturn(update).when(app).update(); initHandlerV2(); assertSame(update, handler.updateAppRuntime(app)); verify(withWebContainer, times(1)).withWebContainer(WebContainer.TOMCAT_8_5_NEWEST); verifyNoMoreInteractions(withWebContainer); } |
### Question:
PackageMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { promptCompileInfo(); final AnnotationHandler annotationHandler = getAnnotationHandler(); Set<Method> methods = null; try { methods = findAnnotatedMethods(annotationHandler); } catch (MalformedURLException e) { throw new AzureExecutionException("Invalid URL when resolving class path:" + e.getMessage(), e); } if (methods.size() == 0) { Log.info(NO_FUNCTIONS); return; } final Map<String, FunctionConfiguration> configMap = getFunctionConfigurations(annotationHandler, methods); validateFunctionConfigurations(configMap); final ObjectWriter objectWriter = getObjectWriter(); try { copyHostJsonFile(objectWriter); writeFunctionJsonFiles(objectWriter, configMap); copyJarsToStageDirectory(); } catch (IOException e) { throw new AzureExecutionException("Cannot perform IO operations due to error:" + e.getMessage(), e); } final CommandHandler commandHandler = new CommandHandlerImpl(); final FunctionCoreToolsHandler functionCoreToolsHandler = getFunctionCoreToolsHandler(commandHandler); final Set<BindingEnum> bindingClasses = this.getFunctionBindingEnums(configMap); installExtension(functionCoreToolsHandler, bindingClasses); Log.info(BUILD_SUCCESS); } @Override List<Resource> getResources(); static final String SEARCH_FUNCTIONS; static final String FOUND_FUNCTIONS; static final String NO_FUNCTIONS; static final String GENERATE_CONFIG; static final String GENERATE_SKIP; static final String GENERATE_DONE; static final String VALIDATE_CONFIG; static final String VALIDATE_SKIP; static final String VALIDATE_DONE; static final String SAVE_HOST_JSON; static final String SAVE_FUNCTION_JSONS; static final String SAVE_SKIP; static final String SAVE_FUNCTION_JSON; static final String SAVE_SUCCESS; static final String COPY_JARS; static final String COPY_SUCCESS; static final String INSTALL_EXTENSIONS; static final String SKIP_INSTALL_EXTENSIONS_HTTP; static final String INSTALL_EXTENSIONS_FINISH; static final String BUILD_SUCCESS; static final String FUNCTION_JSON; static final String HOST_JSON; static final String EXTENSION_BUNDLE; static final String EXTENSION_BUNDLE_ID; static final String SKIP_INSTALL_EXTENSIONS_BUNDLE; }### Answer:
@Test public void doExecute() throws Exception { final PackageMojo mojo = getMojoFromPom(); final PackageMojo mojoSpy = spy(mojo); final Set<Method> methods = new HashSet<>(Arrays.asList(this.getClass().getMethods())); ReflectionUtils.setVariableValueInObject(mojoSpy, "finalName", "artifact-0.1.0"); doReturn(mock(AnnotationHandler.class)).when(mojoSpy).getAnnotationHandler(); doReturn(methods).when(mojoSpy).findAnnotatedMethods(any()); doReturn("target/azure-functions").when(mojoSpy).getDeploymentStagingDirectoryPath(); doReturn("target").when(mojoSpy).getBuildDirectoryAbsolutePath(); doReturn(mock(MavenProject.class)).when(mojoSpy).getProject(); doReturn(mock(MavenSession.class)).when(mojoSpy).getSession(); doReturn(false).when(mojoSpy).isInstallingExtensionNeeded(any()); doReturn(mock(MavenResourcesFiltering.class)).when(mojoSpy).getMavenResourcesFiltering(); doNothing().when(mojoSpy).copyHostJsonFile(any()); doNothing().when(mojoSpy).promptCompileInfo(); mojoSpy.doExecute(); } |
### Question:
PrivateDockerHubRuntimeHandlerImpl extends WebAppRuntimeHandler { @Override public WebApp.Update updateAppRuntime(final WebApp app) throws AzureExecutionException { WebAppUtils.assureLinuxWebApp(app); return app.update() .withPrivateDockerHubImage(image) .withCredentials(dockerCredentialProvider.getUsername(), dockerCredentialProvider.getPassword()); } private PrivateDockerHubRuntimeHandlerImpl(final Builder builder); @Override WebApp.DefinitionStages.WithCreate defineAppWithRuntime(); @Override WebApp.Update updateAppRuntime(final WebApp app); }### Answer:
@Test public void updateAppRuntimeV2() throws Exception { final WebApp app = mock(WebApp.class); final SiteInner siteInner = mock(SiteInner.class); doReturn(siteInner).when(app).inner(); doReturn("app,linux").when(siteInner).kind(); final WebApp.Update update = mock(WebApp.Update.class); final WebApp.UpdateStages.WithCredentials withCredentials = mock(WebApp.UpdateStages.WithCredentials.class); doReturn(withCredentials).when(update).withPrivateDockerHubImage(""); doReturn(update).when(app).update(); final Server server = mock(Server.class); final Settings settings = mock(Settings.class); doReturn(server).when(settings).getServer(anyString()); doReturn(settings).when(config).getMavenSettings(); doReturn("").when(config).getImage(); doReturn("serverId").when(config).getServerId(); initHandlerV2(); handler.updateAppRuntime(app); verify(update, times(1)).withPrivateDockerHubImage(""); verify(server, times(1)).getUsername(); verify(server, times(1)).getPassword(); }
@Test public void updateAppRuntimeV1() throws Exception { final WebApp app = mock(WebApp.class); final SiteInner siteInner = mock(SiteInner.class); doReturn("app,linux").when(siteInner).kind(); doReturn(siteInner).when(app).inner(); final Update update = mock(Update.class); final WithCredentials withCredentials = mock(WithCredentials.class); doReturn(withCredentials).when(update).withPrivateDockerHubImage(null); doReturn(update).when(app).update(); doReturn("serverId").when(config).getServerId(); final Server server = mock(Server.class); final Settings settings = mock(Settings.class); doReturn(server).when(settings).getServer(anyString()); doReturn(settings).when(config).getMavenSettings(); initHandlerV1(); handler.updateAppRuntime(app); verify(update, times(1)).withPrivateDockerHubImage(null); verify(server, times(1)).getUsername(); verify(server, times(1)).getPassword(); } |
### Question:
ArtifactHandlerImplV2 extends ArtifactHandlerBase { protected void publishArtifactsViaWarDeploy(final DeployTarget target, final String stagingDirectoryPath, final List<File> warArtifacts) throws AzureExecutionException { if (warArtifacts == null || warArtifacts.size() == 0) { throw new AzureExecutionException( String.format("There is no war artifacts to deploy in staging path %s.", stagingDirectoryPath)); } for (final File warArtifact : warArtifacts) { final String contextPath = getContextPathFromFileName(stagingDirectoryPath, warArtifact.getAbsolutePath()); publishWarArtifact(target, warArtifact, contextPath); } } protected ArtifactHandlerImplV2(final ArtifactHandlerImplV2.Builder builder); @Override void publish(final DeployTarget target); void publishWarArtifact(final DeployTarget target, final File warArtifact,
final String contextPath); }### Answer:
@Test(expected = AzureExecutionException.class) public void publishArtifactsViaWarDeployThrowException() throws AzureExecutionException { final DeployTarget target = mock(DeployTarget.class); final String stagingDirectoryPath = ""; final List<File> warArtifacts = null; buildHandler(); handlerSpy.publishArtifactsViaWarDeploy(target, stagingDirectoryPath, warArtifacts); }
@Test public void publishArtifactsViaWarDeploy() throws AzureExecutionException { final WebApp app = mock(WebApp.class); final DeployTarget target = new WebAppDeployTarget(app); final String stagingDirectory = Paths.get(Paths.get("").toAbsolutePath().toString(), "maven-plugin-temp").toString(); final List<File> artifacts = new ArrayList<>(); final File artifact = new File(Paths.get(stagingDirectory, "dummypath", "dummy.war").toString()); artifacts.add(artifact); buildHandler(); doNothing().when(handlerSpy).publishWarArtifact(target, artifact, "dummypath"); handlerSpy.publishArtifactsViaWarDeploy(target, stagingDirectory, artifacts); verify(handlerSpy, times(1)). publishArtifactsViaWarDeploy(target, stagingDirectory, artifacts); verify(handlerSpy, times(1)).publishWarArtifact(target, artifact, "dummypath"); verifyNoMoreInteractions(handlerSpy); } |
### Question:
ArtifactHandlerImplV2 extends ArtifactHandlerBase { protected void publishArtifactsViaZipDeploy(final DeployTarget target, final String stagingDirectoryPath) throws AzureExecutionException { if (isJavaSERuntime()) { prepareJavaSERuntime(getAllArtifacts(stagingDirectoryPath)); } final File stagingDirectory = new File(stagingDirectoryPath); final File zipFile = Utils.createTempFile(stagingDirectory.getName(), ".zip"); ZipUtil.pack(stagingDirectory, zipFile); Log.info(String.format("Deploying the zip package %s...", zipFile.getName())); final boolean deploySuccess = performActionWithRetry(() -> target.zipDeploy(zipFile), MAX_RETRY_TIMES); if (!deploySuccess) { throw new AzureExecutionException( String.format("The zip deploy failed after %d times of retry.", MAX_RETRY_TIMES + 1)); } } protected ArtifactHandlerImplV2(final ArtifactHandlerImplV2.Builder builder); @Override void publish(final DeployTarget target); void publishWarArtifact(final DeployTarget target, final File warArtifact,
final String contextPath); }### Answer:
@Test public void publishArtifactsViaZipDeploy() throws AzureExecutionException { final DeployTarget target = mock(DeployTarget.class); final File zipTestDirectory = new File("src/test/resources/artifacthandlerv2"); final String stagingDirectoryPath = zipTestDirectory.getAbsolutePath(); doNothing().when(target).zipDeploy(any()); buildHandler(); doReturn(false).when(handlerSpy).isJavaSERuntime(); handlerSpy.publishArtifactsViaZipDeploy(target, stagingDirectoryPath); verify(handlerSpy, times(1)).isJavaSERuntime(); verify(handlerSpy, times(1)).publishArtifactsViaZipDeploy(target, stagingDirectoryPath); verifyNoMoreInteractions(handlerSpy); } |
### Question:
ArtifactHandlerImplV2 extends ArtifactHandlerBase { protected boolean isJavaSERuntime() { final boolean isJarProject = project != null && project.isJarProject(); if (runtimeSetting == null || runtimeSetting.isEmpty() || isJarProject) { return isJarProject; } final String webContainer = runtimeSetting.getOsEnum() == OperatingSystemEnum.Windows ? runtimeSetting.getWebContainer().toString() : runtimeSetting.getLinuxRuntime().stack(); return StringUtils.containsIgnoreCase(webContainer, "java"); } protected ArtifactHandlerImplV2(final ArtifactHandlerImplV2.Builder builder); @Override void publish(final DeployTarget target); void publishWarArtifact(final DeployTarget target, final File warArtifact,
final String contextPath); }### Answer:
@Test public void isJavaSERuntime() throws Exception { final MavenProject mavenProject = TestUtils.getSimpleMavenProjectForUnitTest(); final IProject project = ProjectUtils.convertCommonProject(mavenProject); final RuntimeSetting runtimeSetting = mock(RuntimeSetting.class); handler = new ArtifactHandlerImplV2.Builder() .stagingDirectoryPath(mojo.getDeploymentStagingDirectoryPath()) .project(project) .runtime(runtimeSetting) .build(); handlerSpy = spy(handler); doReturn(false).when(runtimeSetting).isEmpty(); doReturn(OperatingSystemEnum.Windows).when(runtimeSetting).getOsEnum(); doReturn(WebContainer.fromString("java 8")).when(runtimeSetting).getWebContainer(); assertTrue(handlerSpy.isJavaSERuntime()); FieldUtils.writeField(project, "artifactFile", Paths.get("artifactFile.war"), true); doReturn(true).when(runtimeSetting).isEmpty(); assertFalse(handlerSpy.isJavaSERuntime()); FieldUtils.writeField(project, "artifactFile", Paths.get("artifactFile.jar"), true); doReturn(true).when(runtimeSetting).isEmpty(); assertTrue(handlerSpy.isJavaSERuntime()); Mockito.reset(runtimeSetting); doReturn(false).when(runtimeSetting).isEmpty(); FieldUtils.writeField(project, "artifactFile", Paths.get("artifactFile.jar"), true); assertTrue(handlerSpy.isJavaSERuntime()); verify(runtimeSetting, times(0)).getOsEnum(); verify(runtimeSetting, times(0)).getWebContainer(); verify(runtimeSetting, times(0)).getLinuxRuntime(); } |
### Question:
ArtifactHandlerImplV2 extends ArtifactHandlerBase { public void publishWarArtifact(final DeployTarget target, final File warArtifact, final String contextPath) throws AzureExecutionException { final Runnable executor = getRealWarDeployExecutor(target, warArtifact, contextPath); Log.info(String.format("Deploying the war file %s...", warArtifact.getName())); final boolean deploySuccess = performActionWithRetry(executor, MAX_RETRY_TIMES); if (!deploySuccess) { throw new AzureExecutionException( String.format("Failed to deploy war file after %d times of retry.", MAX_RETRY_TIMES)); } } protected ArtifactHandlerImplV2(final ArtifactHandlerImplV2.Builder builder); @Override void publish(final DeployTarget target); void publishWarArtifact(final DeployTarget target, final File warArtifact,
final String contextPath); }### Answer:
@Test public void publishWarArtifact() throws AzureExecutionException { final WebAppDeployTarget target = mock(WebAppDeployTarget.class); final File warArtifact = new File("D:\\temp\\dummypath"); final String contextPath = "dummy"; doNothing().when(target).warDeploy(warArtifact, contextPath); buildHandler(); handlerSpy.publishWarArtifact(target, warArtifact, contextPath); verify(handlerSpy, times(1)).publishWarArtifact(target, warArtifact, contextPath); verifyNoMoreInteractions(handlerSpy); }
@Test(expected = AzureExecutionException.class) public void publishWarArtifactThrowException() throws AzureExecutionException { final WebAppDeployTarget target = mock(WebAppDeployTarget.class); final File warArtifact = new File("D:\\temp\\dummypath"); final String contextPath = "dummy"; doThrow(RuntimeException.class).when(target).warDeploy(warArtifact, contextPath); buildHandler(); handlerSpy.publishWarArtifact(target, warArtifact, contextPath); } |
### Question:
WarArtifactHandlerImpl extends ArtifactHandlerBase { @Override public void publish(final DeployTarget target) throws AzureExecutionException { final File war = getWarFile(); assureWarFileExisted(war); final Runnable warDeployExecutor = ArtifactHandlerUtils.getRealWarDeployExecutor(target, war, getContextPath()); Log.info(String.format(DEPLOY_START, target.getName())); int retryCount = 0; Log.info("Deploying the war file..."); while (retryCount < DEFAULT_MAX_RETRY_TIMES) { retryCount++; try { warDeployExecutor.run(); Log.info(String.format(DEPLOY_FINISH, target.getDefaultHostName())); return; } catch (Exception e) { Log.debug(String.format(UPLOAD_FAILURE, e.getMessage(), retryCount, DEFAULT_MAX_RETRY_TIMES)); } } throw new AzureExecutionException(String.format(DEPLOY_FAILURE, DEFAULT_MAX_RETRY_TIMES)); } protected WarArtifactHandlerImpl(final WarArtifactHandlerImpl.Builder builder); @Override void publish(final DeployTarget target); static final String FILE_IS_NOT_WAR; static final String FIND_WAR_FILE_FAIL; static final String UPLOAD_FAILURE; static final String DEPLOY_FAILURE; static final int DEFAULT_MAX_RETRY_TIMES; }### Answer:
@Test public void publish() throws Exception { final File file = new File(""); final String path = ""; final WebApp appMock = mock(WebApp.class); doReturn(appMock).when(mojo).getWebApp(); doNothing().when(appMock).warDeploy(any(File.class), anyString()); buildHandler(); doReturn(file).when(handlerSpy).getWarFile(); doNothing().when(handlerSpy).assureWarFileExisted(any(File.class)); doReturn(path).when(handlerSpy).getContextPath(); handlerSpy.publish(new WebAppDeployTarget(appMock)); verify(appMock, times(1)).warDeploy(file, path); } |
### Question:
WarArtifactHandlerImpl extends ArtifactHandlerBase { protected String getContextPath() { String path = contextPath.trim(); if (path.charAt(0) == '/') { path = path.substring(1); } return path; } protected WarArtifactHandlerImpl(final WarArtifactHandlerImpl.Builder builder); @Override void publish(final DeployTarget target); static final String FILE_IS_NOT_WAR; static final String FIND_WAR_FILE_FAIL; static final String UPLOAD_FAILURE; static final String DEPLOY_FAILURE; static final int DEFAULT_MAX_RETRY_TIMES; }### Answer:
@Test public void getContextPath() { doReturn("/").when(mojo).getPath(); buildHandler(); assertEquals(handlerSpy.getContextPath(), ""); doReturn(" / ").when(mojo).getPath(); buildHandler(); assertEquals(handlerSpy.getContextPath(), ""); doReturn("/test").when(mojo).getPath(); buildHandler(); assertEquals(handlerSpy.getContextPath(), "test"); doReturn("test").when(mojo).getPath(); buildHandler(); assertEquals(handlerSpy.getContextPath(), "test"); doReturn("/test/test").when(mojo).getPath(); buildHandler(); assertEquals(handlerSpy.getContextPath(), "test/test"); doReturn("test/test").when(mojo).getPath(); buildHandler(); assertEquals(handlerSpy.getContextPath(), "test/test"); } |
### Question:
PackageMojo extends AbstractFunctionMojo { protected AnnotationHandler getAnnotationHandler() { return new AnnotationHandlerImpl(); } @Override List<Resource> getResources(); static final String SEARCH_FUNCTIONS; static final String FOUND_FUNCTIONS; static final String NO_FUNCTIONS; static final String GENERATE_CONFIG; static final String GENERATE_SKIP; static final String GENERATE_DONE; static final String VALIDATE_CONFIG; static final String VALIDATE_SKIP; static final String VALIDATE_DONE; static final String SAVE_HOST_JSON; static final String SAVE_FUNCTION_JSONS; static final String SAVE_SKIP; static final String SAVE_FUNCTION_JSON; static final String SAVE_SUCCESS; static final String COPY_JARS; static final String COPY_SUCCESS; static final String INSTALL_EXTENSIONS; static final String SKIP_INSTALL_EXTENSIONS_HTTP; static final String INSTALL_EXTENSIONS_FINISH; static final String BUILD_SUCCESS; static final String FUNCTION_JSON; static final String HOST_JSON; static final String EXTENSION_BUNDLE; static final String EXTENSION_BUNDLE_ID; static final String SKIP_INSTALL_EXTENSIONS_BUNDLE; }### Answer:
@Test public void getAnnotationHandler() throws Exception { final PackageMojo mojo = getMojoFromPom(); final AnnotationHandler handler = mojo.getAnnotationHandler(); assertNotNull(handler); assertTrue(handler instanceof AnnotationHandlerImpl); } |
### Question:
WarArtifactHandlerImpl extends ArtifactHandlerBase { protected File getWarFile() { return StringUtils.isNotEmpty(warFile) ? new File(warFile) : new File(project.getArtifactFile().toString()); } protected WarArtifactHandlerImpl(final WarArtifactHandlerImpl.Builder builder); @Override void publish(final DeployTarget target); static final String FILE_IS_NOT_WAR; static final String FIND_WAR_FILE_FAIL; static final String UPLOAD_FAILURE; static final String DEPLOY_FAILURE; static final int DEFAULT_MAX_RETRY_TIMES; }### Answer:
@Test public void getWarFile() { doReturn(null).when(mojo).getWarFile(); doReturn("buildDirectory").when(mojo).getBuildDirectoryAbsolutePath(); final MavenProject projectMock = mock(MavenProject.class); final Build buildMock = mock(Build.class); doReturn(projectMock).when(mojo).getProject(); doReturn(buildMock).when(projectMock).getBuild(); doReturn("finalName").when(buildMock).getFinalName(); doReturn("buildDirectory/finalName.war").when(mojo).getWarFile(); buildHandler(); final File customWarFile = handlerSpy.getWarFile(); assertNotNull(customWarFile); assertEquals(customWarFile.getPath(), Paths.get("buildDirectory/finalName.war").toString()); doReturn("warFile.war").when(mojo).getWarFile(); buildHandler(); final File defaultWar = handlerSpy.getWarFile(); assertNotNull(defaultWar); assertEquals(defaultWar.getPath(), Paths.get("warFile.war").toString()); } |
### Question:
WarArtifactHandlerImpl extends ArtifactHandlerBase { protected void assureWarFileExisted(final File war) throws AzureExecutionException { if (!Files.getFileExtension(war.getName()).equalsIgnoreCase("war")) { throw new AzureExecutionException(FILE_IS_NOT_WAR); } if (!war.exists() || !war.isFile()) { throw new AzureExecutionException(String.format(FIND_WAR_FILE_FAIL, war.getAbsolutePath())); } } protected WarArtifactHandlerImpl(final WarArtifactHandlerImpl.Builder builder); @Override void publish(final DeployTarget target); static final String FILE_IS_NOT_WAR; static final String FIND_WAR_FILE_FAIL; static final String UPLOAD_FAILURE; static final String DEPLOY_FAILURE; static final int DEFAULT_MAX_RETRY_TIMES; }### Answer:
@Test(expected = AzureExecutionException.class) public void assureWarFileExistedWhenFileExtWrong() throws AzureExecutionException { buildHandler(); handlerSpy.assureWarFileExisted(new File("test.jar")); }
@Test(expected = AzureExecutionException.class) public void assureWarFileExistedWhenFileNotExist() throws AzureExecutionException { final File fileMock = mock(File.class); doReturn("test.war").when(fileMock).getName(); doReturn(false).when(fileMock).exists(); buildHandler(); handlerSpy.assureWarFileExisted(fileMock); }
@Test(expected = AzureExecutionException.class) public void assureWarFileExistedWhenIsNotAFile() throws AzureExecutionException { final File fileMock = mock(File.class); doReturn("test.war").when(fileMock).getName(); doReturn(false).when(fileMock).exists(); doReturn(false).when(fileMock).isFile(); buildHandler(); handlerSpy.assureWarFileExisted(fileMock); }
@Test public void assureWarFileExisted() throws AzureExecutionException { final File file = mock(File.class); doReturn("test.war").when(file).getName(); doReturn(true).when(file).exists(); doReturn(true).when(file).isFile(); buildHandler(); handlerSpy.assureWarFileExisted(file); verify(file).getName(); verify(file).exists(); verify(file).isFile(); } |
### Question:
JarArtifactHandlerImpl extends ZIPArtifactHandlerImpl { @Override public void publish(DeployTarget deployTarget) throws AzureExecutionException { final File jar = getJarFile(); assureJarFileExisted(jar); try { prepareDeploymentFiles(jar); } catch (IOException e) { throw new AzureExecutionException( String.format("Cannot copy jar to staging directory: '%s'", jar), e); } super.publish(deployTarget); } protected JarArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget deployTarget); static final String FILE_IS_NOT_JAR; static final String FIND_JAR_FILE_FAIL; }### Answer:
@Test public void publish() throws Exception { final DeployTarget deployTarget = new WebAppDeployTarget(this.mojo.getWebApp()); buildHandler(); doNothing().when(handlerSpy).publish(deployTarget); handlerSpy.publish(deployTarget); verify(handlerSpy).publish(deployTarget); }
@Test public void publishToDeploymentSlot() throws Exception { final DeploymentSlot slot = mock(DeploymentSlot.class); final DeployTarget deployTarget = new DeploymentSlotDeployTarget(slot); buildHandler(); doNothing().when(handlerSpy).publish(deployTarget); handlerSpy.publish(deployTarget); verify(handlerSpy).publish(deployTarget); } |
### Question:
JarArtifactHandlerImpl extends ZIPArtifactHandlerImpl { protected void prepareDeploymentFiles(File jar) throws IOException { final File parent = new File(stagingDirectoryPath); parent.mkdirs(); Files.copy(jar, new File(parent, DEFAULT_APP_SERVICE_JAR_NAME)); } protected JarArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget deployTarget); static final String FILE_IS_NOT_JAR; static final String FIND_JAR_FILE_FAIL; }### Answer:
@Test public void prepareDeploymentFiles() throws IOException { } |
### Question:
JarArtifactHandlerImpl extends ZIPArtifactHandlerImpl { protected File getJarFile() { final String jarFilePath = StringUtils.isNotEmpty(jarFile) ? jarFile : project.getArtifactFile().toString(); return new File(jarFilePath); } protected JarArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget deployTarget); static final String FILE_IS_NOT_JAR; static final String FIND_JAR_FILE_FAIL; }### Answer:
@Test public void getJarFile() { doReturn("test.jar").when(mojo).getJarFile(); buildHandler(); assertEquals("test.jar", handlerSpy.getJarFile().getName()); final MavenProject project = mock(MavenProject.class); doReturn(project).when(mojo).getProject(); buildHandler(); assertEquals("test.jar", handlerSpy.getJarFile().getName()); assertEquals("test.jar", handlerSpy.getJarFile().getName()); } |
### Question:
JarArtifactHandlerImpl extends ZIPArtifactHandlerImpl { protected void assureJarFileExisted(File jar) throws AzureExecutionException { if (!Files.getFileExtension(jar.getName()).equalsIgnoreCase("jar")) { throw new AzureExecutionException(FILE_IS_NOT_JAR); } if (!jar.exists() || !jar.isFile()) { throw new AzureExecutionException(String.format(FIND_JAR_FILE_FAIL, jar.getAbsolutePath())); } } protected JarArtifactHandlerImpl(final Builder builder); @Override void publish(DeployTarget deployTarget); static final String FILE_IS_NOT_JAR; static final String FIND_JAR_FILE_FAIL; }### Answer:
@Test(expected = AzureExecutionException.class) public void assureJarFileExistedWhenFileExtWrong() throws AzureExecutionException { buildHandler(); handlerSpy.assureJarFileExisted(new File("test.jar")); }
@Test(expected = AzureExecutionException.class) public void assureJarFileExistedWhenFileNotExist() throws AzureExecutionException { buildHandler(); final File fileMock = mock(File.class); doReturn("test.jar").when(fileMock).getName(); doReturn(false).when(fileMock).exists(); handlerSpy.assureJarFileExisted(fileMock); }
@Test(expected = AzureExecutionException.class) public void assureJarFileExistedWhenIsNotAFile() throws AzureExecutionException { final File fileMock = mock(File.class); doReturn("test.jar").when(fileMock).getName(); doReturn(false).when(fileMock).exists(); buildHandler(); handlerSpy.assureJarFileExisted(fileMock); }
@Test public void assureJarFileExisted() throws AzureExecutionException { final File file = mock(File.class); doReturn("test.jar").when(file).getName(); doReturn(true).when(file).exists(); doReturn(true).when(file).isFile(); buildHandler(); handlerSpy.assureJarFileExisted(file); verify(file).getName(); verify(file).exists(); verify(file).isFile(); } |
### Question:
PackageMojo extends AbstractFunctionMojo { protected String getScriptFilePath() { return new StringBuilder() .append("..") .append("/") .append(getFinalName()) .append(".jar") .toString(); } @Override List<Resource> getResources(); static final String SEARCH_FUNCTIONS; static final String FOUND_FUNCTIONS; static final String NO_FUNCTIONS; static final String GENERATE_CONFIG; static final String GENERATE_SKIP; static final String GENERATE_DONE; static final String VALIDATE_CONFIG; static final String VALIDATE_SKIP; static final String VALIDATE_DONE; static final String SAVE_HOST_JSON; static final String SAVE_FUNCTION_JSONS; static final String SAVE_SKIP; static final String SAVE_FUNCTION_JSON; static final String SAVE_SUCCESS; static final String COPY_JARS; static final String COPY_SUCCESS; static final String INSTALL_EXTENSIONS; static final String SKIP_INSTALL_EXTENSIONS_HTTP; static final String INSTALL_EXTENSIONS_FINISH; static final String BUILD_SUCCESS; static final String FUNCTION_JSON; static final String HOST_JSON; static final String EXTENSION_BUNDLE; static final String EXTENSION_BUNDLE_ID; static final String SKIP_INSTALL_EXTENSIONS_BUNDLE; }### Answer:
@Test public void getScriptFilePath() throws Exception { final PackageMojo mojo = getMojoFromPom(); final PackageMojo mojoSpy = spy(mojo); ReflectionUtils.setVariableValueInObject(mojoSpy, "finalName", "artifact-0.1.0"); final String finalName = mojoSpy.getScriptFilePath(); assertEquals("../artifact-0.1.0.jar", finalName); } |
### Question:
HandlerFactoryImpl extends HandlerFactory { @Override public RuntimeHandler getRuntimeHandler(final WebAppConfiguration config, final Azure azureClient) throws AzureExecutionException { if (config.getOs() == null) { return new NullRuntimeHandlerImpl(); } final WebAppRuntimeHandler.Builder builder; switch (config.getOs()) { case Windows: builder = new WindowsRuntimeHandlerImpl.Builder().javaVersion(config.getJavaVersion()) .webContainer(config.getWebContainer()); break; case Linux: builder = new LinuxRuntimeHandlerImpl.Builder().runtime(config.getRuntimeStack()); break; case Docker: builder = getDockerRuntimeHandlerBuilder(config); break; default: throw new AzureExecutionException("Unknown "); } return builder.appName(config.getAppName()) .resourceGroup(config.getResourceGroup()) .region(config.getRegion()) .pricingTier(config.getPricingTier()) .servicePlanName(config.getServicePlanName()) .servicePlanResourceGroup((config.getServicePlanResourceGroup())) .azure(azureClient) .build(); } @Override RuntimeHandler getRuntimeHandler(final WebAppConfiguration config, final Azure azureClient); @Override SettingsHandler getSettingsHandler(final AbstractWebAppMojo mojo); @Override ArtifactHandler getArtifactHandler(final AbstractWebAppMojo mojo); @Override DeploymentSlotHandler getDeploymentSlotHandler(AbstractWebAppMojo mojo); static final String UNKNOWN_DEPLOYMENT_TYPE; }### Answer:
@Test public void getRuntimeHandler() throws AzureExecutionException { final WebAppConfiguration config = mock(WebAppConfiguration.class); final Azure azureClient = mock(Azure.class); final HandlerFactory factory = new HandlerFactoryImpl(); doReturn("").when(config).getAppName(); doReturn("").when(config).getResourceGroup(); doReturn(Region.US_EAST).when(config).getRegion(); doReturn(new PricingTier("Premium", "P1V2")).when(config).getPricingTier(); doReturn("").when(config).getServicePlanName(); doReturn("").when(config).getServicePlanResourceGroup(); doReturn(null).when(config).getOs(); RuntimeHandler handler = factory.getRuntimeHandler(config, azureClient); assertTrue(handler instanceof NullRuntimeHandlerImpl); doReturn(OperatingSystemEnum.Windows).when(config).getOs(); doReturn(JavaVersion.JAVA_8_NEWEST).when(config).getJavaVersion(); doReturn(WebContainer.TOMCAT_8_5_NEWEST).when(config).getWebContainer(); handler = factory.getRuntimeHandler(config, azureClient); assertTrue(handler instanceof WindowsRuntimeHandlerImpl); doReturn(OperatingSystemEnum.Linux).when(config).getOs(); doReturn(RuntimeStack.JAVA_8_JRE8).when(config).getRuntimeStack(); handler = factory.getRuntimeHandler(config, azureClient); assertTrue(handler instanceof LinuxRuntimeHandlerImpl); doReturn(OperatingSystemEnum.Docker).when(config).getOs(); doReturn("imageName").when(config).getImage(); handler = factory.getRuntimeHandler(config, azureClient); assertTrue(handler instanceof PublicDockerHubRuntimeHandlerImpl); doReturn("serverId").when(config).getServerId(); doReturn("registry").when(config).getRegistryUrl(); doReturn(mock(Settings.class)).when(config).getMavenSettings(); handler = factory.getRuntimeHandler(config, azureClient); assertTrue(handler instanceof PrivateRegistryRuntimeHandlerImpl); doReturn("").when(config).getRegistryUrl(); handler = factory.getRuntimeHandler(config, azureClient); assertTrue(handler instanceof PrivateDockerHubRuntimeHandlerImpl); doReturn("").when(config).getImage(); try { factory.getRuntimeHandler(config, azureClient); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Invalid docker runtime configured."); } } |
### Question:
HandlerFactoryImpl extends HandlerFactory { @Override public SettingsHandler getSettingsHandler(final AbstractWebAppMojo mojo) { return new SettingsHandlerImpl(mojo); } @Override RuntimeHandler getRuntimeHandler(final WebAppConfiguration config, final Azure azureClient); @Override SettingsHandler getSettingsHandler(final AbstractWebAppMojo mojo); @Override ArtifactHandler getArtifactHandler(final AbstractWebAppMojo mojo); @Override DeploymentSlotHandler getDeploymentSlotHandler(AbstractWebAppMojo mojo); static final String UNKNOWN_DEPLOYMENT_TYPE; }### Answer:
@Test public void getSettingsHandler() throws Exception { final HandlerFactory factory = new HandlerFactoryImpl(); final SettingsHandler handler = factory.getSettingsHandler(mojo); assertNotNull(handler); assertTrue(handler instanceof SettingsHandlerImpl); } |
### Question:
HandlerFactoryImpl extends HandlerFactory { @Override public ArtifactHandler getArtifactHandler(final AbstractWebAppMojo mojo) throws AzureExecutionException { switch (SchemaVersion.fromString(mojo.getSchemaVersion())) { case V1: return getV1ArtifactHandler(mojo); case V2: return getV2ArtifactHandler(mojo); default: throw new AzureExecutionException(SchemaVersion.UNKNOWN_SCHEMA_VERSION); } } @Override RuntimeHandler getRuntimeHandler(final WebAppConfiguration config, final Azure azureClient); @Override SettingsHandler getSettingsHandler(final AbstractWebAppMojo mojo); @Override ArtifactHandler getArtifactHandler(final AbstractWebAppMojo mojo); @Override DeploymentSlotHandler getDeploymentSlotHandler(AbstractWebAppMojo mojo); static final String UNKNOWN_DEPLOYMENT_TYPE; }### Answer:
@Test public void getDefaultArtifactHandler() throws AzureExecutionException { doReturn(project).when(mojo).getProject(); doReturn(DeploymentType.EMPTY).when(mojo).getDeploymentType(); project.setPackaging("jar"); final HandlerFactory factory = new HandlerFactoryImpl(); final ArtifactHandler handler = factory.getArtifactHandler(mojo); assertTrue(handler instanceof JarArtifactHandlerImpl); }
@Test public void getAutoArtifactHandler() throws AzureExecutionException { doReturn(project).when(mojo).getProject(); doReturn(DeploymentType.AUTO).when(mojo).getDeploymentType(); project.setPackaging("war"); final HandlerFactory factory = new HandlerFactoryImpl(); final ArtifactHandler handler = factory.getArtifactHandler(mojo); assertTrue(handler instanceof WarArtifactHandlerImpl); } |
### Question:
HandlerFactoryImpl extends HandlerFactory { @Override public DeploymentSlotHandler getDeploymentSlotHandler(AbstractWebAppMojo mojo) { return new DeploymentSlotHandler(mojo); } @Override RuntimeHandler getRuntimeHandler(final WebAppConfiguration config, final Azure azureClient); @Override SettingsHandler getSettingsHandler(final AbstractWebAppMojo mojo); @Override ArtifactHandler getArtifactHandler(final AbstractWebAppMojo mojo); @Override DeploymentSlotHandler getDeploymentSlotHandler(AbstractWebAppMojo mojo); static final String UNKNOWN_DEPLOYMENT_TYPE; }### Answer:
@Test public void getDeploymentSlotHandler() throws AzureExecutionException { final HandlerFactory factory = new HandlerFactoryImpl(); final DeploymentSlotHandler handler = factory.getDeploymentSlotHandler(mojo); assertNotNull(handler); assertTrue(handler instanceof DeploymentSlotHandler); } |
### Question:
HandlerFactoryImpl extends HandlerFactory { protected ArtifactHandlerBase.Builder getArtifactHandlerBuilderFromPackaging(final AbstractWebAppMojo mojo) throws AzureExecutionException { String packaging = mojo.getProject().getPackaging(); if (StringUtils.isEmpty(packaging)) { throw new AzureExecutionException(UNKNOWN_DEPLOYMENT_TYPE); } packaging = packaging.toLowerCase(Locale.ENGLISH).trim(); switch (packaging) { case "war": return new WarArtifactHandlerImpl.Builder().warFile(mojo.getWarFile()) .contextPath(mojo.getPath()); case "jar": return new JarArtifactHandlerImpl.Builder().jarFile(mojo.getJarFile()); default: throw new AzureExecutionException(UNKNOWN_DEPLOYMENT_TYPE); } } @Override RuntimeHandler getRuntimeHandler(final WebAppConfiguration config, final Azure azureClient); @Override SettingsHandler getSettingsHandler(final AbstractWebAppMojo mojo); @Override ArtifactHandler getArtifactHandler(final AbstractWebAppMojo mojo); @Override DeploymentSlotHandler getDeploymentSlotHandler(AbstractWebAppMojo mojo); static final String UNKNOWN_DEPLOYMENT_TYPE; }### Answer:
@Test public void getArtifactHandlerFromPackaging() throws Exception { doReturn(project).when(mojo).getProject(); final HandlerFactoryImpl factory = new HandlerFactoryImpl(); assertTrue(factory.getArtifactHandlerBuilderFromPackaging(mojo).build() instanceof JarArtifactHandlerImpl); }
@Test(expected = AzureExecutionException.class) public void getArtifactHandlerFromPackagingThrowException() throws AzureExecutionException { doReturn(project).when(mojo).getProject(); project.setPackaging("ear"); final HandlerFactoryImpl factory = new HandlerFactoryImpl(); factory.getArtifactHandlerBuilderFromPackaging(mojo); } |
### Question:
PackageMojo extends AbstractFunctionMojo { protected void writeFunctionJsonFile(final ObjectWriter objectWriter, final String functionName, final FunctionConfiguration config) throws IOException { Log.info(SAVE_FUNCTION_JSON + functionName); final File functionJsonFile = Paths.get(getDeploymentStagingDirectoryPath(), functionName, FUNCTION_JSON).toFile(); writeObjectToFile(objectWriter, config, functionJsonFile); Log.info(SAVE_SUCCESS + functionJsonFile.getAbsolutePath()); } @Override List<Resource> getResources(); static final String SEARCH_FUNCTIONS; static final String FOUND_FUNCTIONS; static final String NO_FUNCTIONS; static final String GENERATE_CONFIG; static final String GENERATE_SKIP; static final String GENERATE_DONE; static final String VALIDATE_CONFIG; static final String VALIDATE_SKIP; static final String VALIDATE_DONE; static final String SAVE_HOST_JSON; static final String SAVE_FUNCTION_JSONS; static final String SAVE_SKIP; static final String SAVE_FUNCTION_JSON; static final String SAVE_SUCCESS; static final String COPY_JARS; static final String COPY_SUCCESS; static final String INSTALL_EXTENSIONS; static final String SKIP_INSTALL_EXTENSIONS_HTTP; static final String INSTALL_EXTENSIONS_FINISH; static final String BUILD_SUCCESS; static final String FUNCTION_JSON; static final String HOST_JSON; static final String EXTENSION_BUNDLE; static final String EXTENSION_BUNDLE_ID; static final String SKIP_INSTALL_EXTENSIONS_BUNDLE; }### Answer:
@Test public void writeFunctionJsonFile() throws Exception { final PackageMojo mojo = getMojoFromPom(); final PackageMojo mojoSpy = spy(mojo); doReturn("target/azure-functions").when(mojoSpy).getDeploymentStagingDirectoryPath(); doNothing().when(mojoSpy).writeObjectToFile(isNull(), isNull(), isNotNull()); mojoSpy.writeFunctionJsonFile(null, "httpTrigger", null); } |
### Question:
RuntimeStackUtils { public static RuntimeStack getRuntimeStack(String javaVersion) { for (final RuntimeStack runtimeStack : getValidRuntimeStacks()) { if (runtimeStack.stack().equals("JAVA") && getJavaVersionFromRuntimeStack(runtimeStack).equalsIgnoreCase(javaVersion)) { return runtimeStack; } } return null; } static String getJavaVersionFromRuntimeStack(RuntimeStack runtimeStack); static String getWebContainerFromRuntimeStack(RuntimeStack runtimeStack); static RuntimeStack getRuntimeStack(String javaVersion); static RuntimeStack getRuntimeStack(String javaVersion, String webContainer); static List<RuntimeStack> getValidRuntimeStacks(); static List<String> getValidWebContainer(String javaVersion); static BidiMap<String, String> getValidJavaVersions(); }### Answer:
@Test public void getRuntimeStackFromString() { assertEquals(RuntimeStackUtils.getRuntimeStack("jre8", "tomcat 8.5"), RuntimeStack.TOMCAT_8_5_JRE8); assertEquals(RuntimeStackUtils.getRuntimeStack("java11", "TOMCAT 9.0"), RuntimeStack.TOMCAT_9_0_JAVA11); assertEquals(RuntimeStackUtils.getRuntimeStack("java11", null), RuntimeStack.JAVA_11_JAVA11); assertEquals(RuntimeStackUtils.getRuntimeStack("jre8", "jre8"), RuntimeStack.JAVA_8_JRE8); } |
### Question:
RuntimeStackUtils { public static String getWebContainerFromRuntimeStack(RuntimeStack runtimeStack) { final String stack = runtimeStack.stack(); final String version = runtimeStack.version(); return stack.equalsIgnoreCase("JAVA") ? version.split("-")[1] : stack + " " + version.split("-")[0]; } static String getJavaVersionFromRuntimeStack(RuntimeStack runtimeStack); static String getWebContainerFromRuntimeStack(RuntimeStack runtimeStack); static RuntimeStack getRuntimeStack(String javaVersion); static RuntimeStack getRuntimeStack(String javaVersion, String webContainer); static List<RuntimeStack> getValidRuntimeStacks(); static List<String> getValidWebContainer(String javaVersion); static BidiMap<String, String> getValidJavaVersions(); }### Answer:
@Test public void getWebContainerFromRuntimeStack() { assertEquals(RuntimeStackUtils.getWebContainerFromRuntimeStack(RuntimeStack.TOMCAT_8_5_JAVA11), "TOMCAT 8.5"); assertEquals(RuntimeStackUtils.getWebContainerFromRuntimeStack(RuntimeStack.JAVA_8_JRE8), "jre8"); assertEquals(RuntimeStackUtils.getWebContainerFromRuntimeStack(RuntimeStack.JAVA_11_JAVA11), "java11"); } |
### Question:
V2ConfigurationParser extends ConfigurationParser { @Override protected OperatingSystemEnum getOs() throws AzureExecutionException { validate(validator.validateOs()); final RuntimeSetting runtime = mojo.getRuntime(); final String os = runtime.getOs(); if (runtime.isEmpty()) { return null; } switch (os.toLowerCase(Locale.ENGLISH)) { case "windows": return OperatingSystemEnum.Windows; case "linux": return OperatingSystemEnum.Linux; case "docker": return OperatingSystemEnum.Docker; default: return null; } } V2ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); }### Answer:
@Test public void getOs() throws AzureExecutionException { final RuntimeSetting runtime = mock(RuntimeSetting.class); doReturn(runtime).when(mojo).getRuntime(); doReturn(true).when(runtime).isEmpty(); assertEquals(null, parser.getOs()); doReturn(false).when(runtime).isEmpty(); doReturn("windows").when(runtime).getOs(); assertEquals(OperatingSystemEnum.Windows, parser.getOs()); doReturn("linux").when(runtime).getOs(); assertEquals(OperatingSystemEnum.Linux, parser.getOs()); doReturn("docker").when(runtime).getOs(); assertEquals(OperatingSystemEnum.Docker, parser.getOs()); try { doReturn(null).when(runtime).getOs(); parser.getOs(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Pleas configure the <os> of <runtime> in pom.xml."); } try { doReturn("unknown-os").when(runtime).getOs(); parser.getOs(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "The value of <os> is not correct, supported values are: windows, " + "linux and docker."); } } |
### Question:
V2ConfigurationParser extends ConfigurationParser { @Override protected Region getRegion() throws AzureExecutionException { validate(validator.validateRegion()); final String region = mojo.getRegion(); return Region.fromName(region); } V2ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); }### Answer:
@Test public void getRegion() throws AzureExecutionException { doReturn("unknown-region").when(mojo).getRegion(); try { parser.getRegion(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "The value of <region> is not supported, please correct it in pom.xml."); } doReturn(Region.US_WEST.name()).when(mojo).getRegion(); assertEquals(Region.US_WEST, parser.getRegion()); } |
### Question:
V2ConfigurationParser extends ConfigurationParser { @Override protected RuntimeStack getRuntimeStack() throws AzureExecutionException { validate(validator.validateRuntimeStack()); final RuntimeSetting runtime = mojo.getRuntime(); if (runtime == null || runtime.isEmpty()) { return null; } return runtime.getLinuxRuntime(); } V2ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); }### Answer:
@Test public void getRuntimeStack() throws AzureExecutionException { doReturn(null).when(mojo).getRuntime(); assertNull(parser.getRuntimeStack()); final RuntimeSetting runtime = mock(RuntimeSetting.class); doReturn(true).when(runtime).isEmpty(); doReturn(runtime).when(mojo).getRuntime(); assertNull(parser.getRuntimeStack()); doReturn(false).when(runtime).isEmpty(); doReturn(RuntimeStack.TOMCAT_8_5_JRE8).when(runtime).getLinuxRuntime(); assertEquals(RuntimeStack.TOMCAT_8_5_JRE8, parser.getRuntimeStack()); doReturn(RuntimeStack.TOMCAT_9_0_JRE8).when(runtime).getLinuxRuntime(); assertEquals(RuntimeStack.TOMCAT_9_0_JRE8, parser.getRuntimeStack()); doReturn(RuntimeStack.JAVA_8_JRE8).when(runtime).getLinuxRuntime(); assertEquals(RuntimeStack.JAVA_8_JRE8, parser.getRuntimeStack()); } |
### Question:
V2ConfigurationParser extends ConfigurationParser { @Override protected String getImage() throws AzureExecutionException { validate(validator.validateImage()); final RuntimeSetting runtime = mojo.getRuntime(); return runtime.getImage(); } V2ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); }### Answer:
@Test public void getImage() throws AzureExecutionException { doReturn(null).when(mojo).getRuntime(); try { parser.getImage(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Please configure the <runtime> in pom.xml."); } final RuntimeSetting runtime = mock(RuntimeSetting.class); doReturn("").when(runtime).getImage(); doReturn(runtime).when(mojo).getRuntime(); try { parser.getImage(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Please config the <image> of <runtime> in pom.xml."); } doReturn("imageName").when(runtime).getImage(); assertEquals("imageName", parser.getImage()); } |
### Question:
V2ConfigurationParser extends ConfigurationParser { @Override protected String getServerId() { final RuntimeSetting runtime = mojo.getRuntime(); if (runtime == null) { return null; } return runtime.getServerId(); } V2ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); }### Answer:
@Test public void getServerId() { assertNull(parser.getServerId()); final RuntimeSetting runtime = mock(RuntimeSetting.class); doReturn(runtime).when(mojo).getRuntime(); doReturn("serverId").when(runtime).getServerId(); assertEquals("serverId", parser.getServerId()); } |
### Question:
V2ConfigurationParser extends ConfigurationParser { @Override protected String getRegistryUrl() { final RuntimeSetting runtime = mojo.getRuntime(); if (runtime == null) { return null; } return runtime.getRegistryUrl(); } V2ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); }### Answer:
@Test public void getRegistryUrl() { assertNull(parser.getRegistryUrl()); final RuntimeSetting runtime = mock(RuntimeSetting.class); doReturn(runtime).when(mojo).getRuntime(); doReturn("serverId").when(runtime).getRegistryUrl(); assertEquals("serverId", parser.getRegistryUrl()); } |
### Question:
V2ConfigurationParser extends ConfigurationParser { @Override protected WebContainer getWebContainer() throws AzureExecutionException { validate(validator.validateWebContainer()); final RuntimeSetting runtime = mojo.getRuntime(); return runtime.getWebContainer(); } V2ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); }### Answer:
@Test public void getWebContainer() throws AzureExecutionException { doReturn(null).when(mojo).getRuntime(); try { parser.getWebContainer(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Pleas config the <runtime> in pom.xml."); } final RuntimeSetting runtime = mock(RuntimeSetting.class); doReturn(runtime).when(mojo).getRuntime(); doReturn("windows").when(runtime).getOs(); doReturn(null).when(runtime).getWebContainer(); try { parser.getWebContainer(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "The configuration <webContainer> in pom.xml is not correct."); } doReturn(WebContainer.TOMCAT_8_5_NEWEST).when(runtime).getWebContainer(); assertEquals(WebContainer.TOMCAT_8_5_NEWEST, parser.getWebContainer()); } |
### Question:
V2ConfigurationParser extends ConfigurationParser { @Override protected JavaVersion getJavaVersion() throws AzureExecutionException { validate(validator.validateJavaVersion()); final RuntimeSetting runtime = mojo.getRuntime(); return runtime.getJavaVersion(); } V2ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); }### Answer:
@Test public void getJavaVersion() throws AzureExecutionException { doReturn(null).when(mojo).getRuntime(); try { parser.getJavaVersion(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Pleas config the <runtime> in pom.xml."); } final RuntimeSetting runtime = mock(RuntimeSetting.class); doReturn(runtime).when(mojo).getRuntime(); doReturn(null).when(runtime).getJavaVersion(); try { parser.getJavaVersion(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "The configuration <javaVersion> in pom.xml is not correct."); } doReturn(JavaVersion.JAVA_8_NEWEST).when(runtime).getJavaVersion(); assertEquals(JavaVersion.JAVA_8_NEWEST, parser.getJavaVersion()); } |
### Question:
AzureServicePrincipleAuthHelper { static AzureTokenCredentials getAzureServicePrincipleCredentials(AuthConfiguration config) throws InvalidConfigurationException, IOException { if (StringUtils.isBlank(config.getClient())) { throw new IllegalArgumentException("'Client Id' of your service principal is not configured."); } if (StringUtils.isBlank(config.getTenant())) { throw new IllegalArgumentException("'Tenant Id' of your service principal is not configured."); } final AzureEnvironment env = AzureAuthHelper.getAzureEnvironment(config.getEnvironment()); if (StringUtils.isNotBlank(config.getCertificate())) { return new ApplicationTokenCredentials(config.getClient(), config.getTenant(), FileUtils.readFileToByteArray(new File(config.getCertificate())), config.getCertificatePassword(), env); } else if (StringUtils.isNotBlank(config.getKey())) { return new ApplicationTokenCredentials(config.getClient(), config.getTenant(), config.getKey(), env); } throw new InvalidConfigurationException("Invalid auth configuration, either 'key' or 'certificate' is required."); } private AzureServicePrincipleAuthHelper(); }### Answer:
@Test public void testGetSPCredentialsBadParameter() throws Exception { final AuthConfiguration config = new AuthConfiguration(); try { AzureServicePrincipleAuthHelper.getAzureServicePrincipleCredentials(config); fail("Should throw IAE"); } catch (IllegalArgumentException ex) { } try { config.setClient("client_id"); AzureServicePrincipleAuthHelper.getAzureServicePrincipleCredentials(config); fail("Should throw IAE"); } catch (IllegalArgumentException ex) { } try { config.setTenant("tenant_id"); AzureServicePrincipleAuthHelper.getAzureServicePrincipleCredentials(config); fail("Should throw exception when there is no key and no certificate"); } catch (InvalidConfigurationException ex) { } try { config.setKey("key"); assertNotNull(AzureServicePrincipleAuthHelper.getAzureServicePrincipleCredentials(config)); } catch (IllegalArgumentException ex) { fail("Should not throw IAE"); } try { config.setKey(null); config.setCertificate(this.getClass().getResource("/test.pem").getFile()); assertNotNull(AzureServicePrincipleAuthHelper.getAzureServicePrincipleCredentials(config)); config.setCertificatePassword("pass1"); assertNotNull(AzureServicePrincipleAuthHelper.getAzureServicePrincipleCredentials(config)); } catch (IllegalArgumentException ex) { fail("Should not throw IAE"); } } |
### Question:
V2ConfigurationParser extends ConfigurationParser { @Override protected List<Resource> getResources() { final Deployment deployment = mojo.getDeployment(); return deployment == null ? null : deployment.getResources(); } V2ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); }### Answer:
@Test public void getResources() { doReturn(null).when(mojo).getDeployment(); assertNull(parser.getResources()); final List<Resource> resources = new ArrayList<Resource>(); resources.add(new Resource()); final Deployment deployment = mock(Deployment.class); doReturn(deployment).when(mojo).getDeployment(); doReturn(resources).when(deployment).getResources(); assertEquals(resources, parser.getResources()); } |
### Question:
ConfigurationParser { protected String getAppName() throws AzureExecutionException { validate(validator.validateAppName()); return mojo.getAppName(); } protected ConfigurationParser(final AbstractWebAppMojo mojo, final AbstractConfigurationValidator validator); WebAppConfiguration getWebAppConfiguration(); }### Answer:
@Test public void getWebAppName() throws AzureExecutionException { doReturn("appName").when(mojo).getAppName(); assertEquals("appName", parser.getAppName()); doReturn("-invalidAppName").when(mojo).getAppName(); try { parser.getAppName(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "The <appName> only allow alphanumeric characters, " + "hyphens and cannot start or end in a hyphen."); } doReturn(null).when(mojo).getAppName(); try { parser.getAppName(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Please config the <appName> in pom.xml."); } } |
### Question:
ConfigurationParser { protected String getResourceGroup() throws AzureExecutionException { validate(validator.validateResourceGroup()); return mojo.getResourceGroup(); } protected ConfigurationParser(final AbstractWebAppMojo mojo, final AbstractConfigurationValidator validator); WebAppConfiguration getWebAppConfiguration(); }### Answer:
@Test public void getResourceGroup() throws AzureExecutionException { doReturn("resourceGroupName").when(mojo).getResourceGroup(); assertEquals("resourceGroupName", parser.getResourceGroup()); doReturn("invalid**ResourceGroupName").when(mojo).getResourceGroup(); try { parser.getResourceGroup(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "The <resourceGroup> only allow alphanumeric characters, periods, " + "underscores, hyphens and parenthesis and cannot end in a period."); } doReturn(null).when(mojo).getResourceGroup(); try { parser.getResourceGroup(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Please config the <resourceGroup> in pom.xml."); } } |
### Question:
ConfigurationParser { public WebAppConfiguration getWebAppConfiguration() throws AzureExecutionException { WebAppConfiguration.Builder builder = new WebAppConfiguration.Builder(); final OperatingSystemEnum os = getOs(); if (os == null) { Log.debug("No runtime related config is specified. " + "It will cause error if creating a new web app."); } else { switch (os) { case Windows: builder = builder.javaVersion(getJavaVersion()).webContainer(getWebContainer()); break; case Linux: builder = builder.runtimeStack(getRuntimeStack()); break; case Docker: builder = builder.image(getImage()).serverId(getServerId()).registryUrl(getRegistryUrl()); break; default: throw new AzureExecutionException("Invalid operating system from the configuration."); } } return builder.appName(getAppName()) .resourceGroup(getResourceGroup()) .region(getRegion()) .pricingTier(getPricingTier()) .servicePlanName(mojo.getAppServicePlanName()) .servicePlanResourceGroup(mojo.getAppServicePlanResourceGroup()) .deploymentSlotSetting(getDeploymentSlotSetting()) .os(os) .mavenSettings(mojo.getSettings()) .resources(getResources()) .stagingDirectoryPath(mojo.getDeploymentStagingDirectoryPath()) .buildDirectoryAbsolutePath(mojo.getBuildDirectoryAbsolutePath()) .project(mojo.getProject()) .session(mojo.getSession()) .filtering(mojo.getMavenResourcesFiltering()) .schemaVersion(getSchemaVersion()) .build(); } protected ConfigurationParser(final AbstractWebAppMojo mojo, final AbstractConfigurationValidator validator); WebAppConfiguration getWebAppConfiguration(); }### Answer:
@Test public void getWebAppConfiguration() throws AzureExecutionException { final ConfigurationParser parserSpy = spy(parser); doReturn("appName").when(parserSpy).getAppName(); doReturn("resourceGroupName").when(parserSpy).getResourceGroup(); final MavenProject project = mock(MavenProject.class); final MavenResourcesFiltering filtering = mock(MavenResourcesFiltering.class); final MavenSession session = mock(MavenSession.class); doReturn(project).when(mojo).getProject(); doReturn(filtering).when(mojo).getMavenResourcesFiltering(); doReturn(session).when(mojo).getSession(); doReturn("test-staging-path").when(mojo).getDeploymentStagingDirectoryPath(); doReturn("test-build-directory-path").when(mojo).getBuildDirectoryAbsolutePath(); doReturn("p1v2").when(mojo).getPricingTier(); doReturn(OperatingSystemEnum.Windows).when(parserSpy).getOs(); WebAppConfiguration webAppConfiguration = parserSpy.getWebAppConfiguration(); assertEquals("appName", webAppConfiguration.getAppName()); assertEquals("resourceGroupName", webAppConfiguration.getResourceGroup()); assertEquals(Region.EUROPE_WEST, webAppConfiguration.getRegion()); assertEquals(new PricingTier("PremiumV2", "P1v2"), webAppConfiguration.getPricingTier()); assertEquals(null, webAppConfiguration.getServicePlanName()); assertEquals(null, webAppConfiguration.getServicePlanResourceGroup()); assertEquals(OperatingSystemEnum.Windows, webAppConfiguration.getOs()); assertEquals(null, webAppConfiguration.getMavenSettings()); assertEquals(project, webAppConfiguration.getProject()); assertEquals(session, webAppConfiguration.getSession()); assertEquals(filtering, webAppConfiguration.getFiltering()); assertEquals("test-staging-path", webAppConfiguration.getStagingDirectoryPath()); assertEquals("test-build-directory-path", webAppConfiguration.getBuildDirectoryAbsolutePath()); assertEquals(JavaVersion.JAVA_8_NEWEST, webAppConfiguration.getJavaVersion()); assertEquals(WebContainer.TOMCAT_8_5_NEWEST, webAppConfiguration.getWebContainer()); doReturn(OperatingSystemEnum.Linux).when(parserSpy).getOs(); webAppConfiguration = parserSpy.getWebAppConfiguration(); assertEquals(RuntimeStack.TOMCAT_8_5_JRE8, webAppConfiguration.getRuntimeStack()); doReturn(OperatingSystemEnum.Docker).when(parserSpy).getOs(); webAppConfiguration = parserSpy.getWebAppConfiguration(); assertEquals("image", webAppConfiguration.getImage()); assertEquals(null, webAppConfiguration.getServerId()); assertEquals(null, webAppConfiguration.getRegistryUrl()); } |
### Question:
V1ConfigurationParser extends ConfigurationParser { @Override public OperatingSystemEnum getOs() throws AzureExecutionException { validate(validator.validateOs()); final String linuxRuntime = mojo.getLinuxRuntime(); final String javaVersion = mojo.getJavaVersion(); final ContainerSetting containerSetting = mojo.getContainerSettings(); final boolean isContainerSettingEmpty = containerSetting == null || containerSetting.isEmpty(); final List<OperatingSystemEnum> osList = new ArrayList<>(); if (javaVersion != null) { osList.add(OperatingSystemEnum.Windows); } if (linuxRuntime != null) { osList.add(OperatingSystemEnum.Linux); } if (!isContainerSettingEmpty) { osList.add(OperatingSystemEnum.Docker); } return osList.size() > 0 ? osList.get(0) : null; } V1ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); @Override OperatingSystemEnum getOs(); @Override RuntimeStack getRuntimeStack(); @Override String getImage(); @Override String getServerId(); @Override String getRegistryUrl(); @Override WebContainer getWebContainer(); @Override JavaVersion getJavaVersion(); @Override List<Resource> getResources(); }### Answer:
@Test public void getOs() throws AzureExecutionException { assertNull(parser.getOs()); doReturn("1.8").when(mojo).getJavaVersion(); assertEquals(OperatingSystemEnum.Windows, parser.getOs()); doReturn(null).when(mojo).getJavaVersion(); doReturn("linuxRuntime").when(mojo).getLinuxRuntime(); assertEquals(OperatingSystemEnum.Linux, parser.getOs()); doReturn(null).when(mojo).getJavaVersion(); doReturn(null).when(mojo).getLinuxRuntime(); doReturn(mock(ContainerSetting.class)).when(mojo).getContainerSettings(); assertEquals(OperatingSystemEnum.Docker, parser.getOs()); doReturn("linuxRuntime").when(mojo).getLinuxRuntime(); doReturn("1.8").when(mojo).getJavaVersion(); try { parser.getOs(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Conflict settings found. <javaVersion>, <linuxRuntime>" + "and <containerSettings> should not be set at the same time."); } } |
### Question:
V1ConfigurationParser extends ConfigurationParser { @Override protected Region getRegion() throws AzureExecutionException { validate(validator.validateRegion()); if (StringUtils.isEmpty(mojo.getRegion())) { return Region.EUROPE_WEST; } return Region.fromName(mojo.getRegion()); } V1ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); @Override OperatingSystemEnum getOs(); @Override RuntimeStack getRuntimeStack(); @Override String getImage(); @Override String getServerId(); @Override String getRegistryUrl(); @Override WebContainer getWebContainer(); @Override JavaVersion getJavaVersion(); @Override List<Resource> getResources(); }### Answer:
@Test public void getRegion() throws AzureExecutionException { assertEquals(Region.EUROPE_WEST, parser.getRegion()); doReturn("unknown-region").when(mojo).getRegion(); try { parser.getRegion(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "The value of <region> is not correct, please correct it in pom.xml."); } doReturn(Region.US_WEST.name()).when(mojo).getRegion(); assertEquals(Region.US_WEST, parser.getRegion()); } |
### Question:
V1ConfigurationParser extends ConfigurationParser { @Override public RuntimeStack getRuntimeStack() throws AzureExecutionException { validate(validator.validateRuntimeStack()); final String linuxRuntime = mojo.getLinuxRuntime(); final RuntimeStack javaSERuntimeStack = RuntimeStackUtils.getRuntimeStack(linuxRuntime); if (javaSERuntimeStack != null) { return javaSERuntimeStack; } final List<RuntimeStack> runtimeStacks = RuntimeStackUtils.getValidRuntimeStacks(); for (final RuntimeStack runtimeStack : runtimeStacks) { if (runtimeStack.toString().equalsIgnoreCase(mojo.getLinuxRuntime())) { return runtimeStack; } } throw new AzureExecutionException(RUNTIME_NOT_EXIST); } V1ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); @Override OperatingSystemEnum getOs(); @Override RuntimeStack getRuntimeStack(); @Override String getImage(); @Override String getServerId(); @Override String getRegistryUrl(); @Override WebContainer getWebContainer(); @Override JavaVersion getJavaVersion(); @Override List<Resource> getResources(); }### Answer:
@Test public void getRuntimeStack() throws AzureExecutionException { try { parser.getRuntimeStack(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Please configure the <linuxRuntime> in pom.xml."); } doReturn("tomcat 8.5-jre8").when(mojo).getLinuxRuntime(); assertEquals(RuntimeStack.TOMCAT_8_5_JRE8, parser.getRuntimeStack()); doReturn("tomcat 9.0-jre8").when(mojo).getLinuxRuntime(); assertEquals(RuntimeStack.TOMCAT_9_0_JRE8, parser.getRuntimeStack()); doReturn("jre8").when(mojo).getLinuxRuntime(); assertEquals(RuntimeStack.JAVA_8_JRE8, parser.getRuntimeStack()); doReturn("tomcat 8.5-java11").when(mojo).getLinuxRuntime(); assertEquals(RuntimeStack.TOMCAT_8_5_JAVA11, parser.getRuntimeStack()); doReturn("tomcat 9.0-java11").when(mojo).getLinuxRuntime(); assertEquals(RuntimeStack.TOMCAT_9_0_JAVA11, parser.getRuntimeStack()); doReturn("java11").when(mojo).getLinuxRuntime(); assertEquals(RuntimeStack.JAVA_11_JAVA11, parser.getRuntimeStack()); doReturn("unknown-value").when(mojo).getLinuxRuntime(); try { parser.getRuntimeStack(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "The configuration of <linuxRuntime> in pom.xml is not correct. " + "Please refer https: } } |
### Question:
V1ConfigurationParser extends ConfigurationParser { @Override public String getImage() throws AzureExecutionException { validate(validator.validateImage()); final ContainerSetting containerSetting = mojo.getContainerSettings(); return containerSetting.getImageName(); } V1ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); @Override OperatingSystemEnum getOs(); @Override RuntimeStack getRuntimeStack(); @Override String getImage(); @Override String getServerId(); @Override String getRegistryUrl(); @Override WebContainer getWebContainer(); @Override JavaVersion getJavaVersion(); @Override List<Resource> getResources(); }### Answer:
@Test public void getImage() throws AzureExecutionException { try { parser.getImage(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Please config the <containerSettings> in pom.xml."); } final ContainerSetting containerSetting = mock(ContainerSetting.class); doReturn(containerSetting).when(mojo).getContainerSettings(); doReturn("imageName").when(containerSetting).getImageName(); assertEquals("imageName", parser.getImage()); doReturn("").when(containerSetting).getImageName(); try { parser.getImage(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Please config the <imageName> of <containerSettings> in pom.xml."); } } |
### Question:
V1ConfigurationParser extends ConfigurationParser { @Override public String getServerId() { final ContainerSetting containerSetting = mojo.getContainerSettings(); if (containerSetting == null) { return null; } return containerSetting.getServerId(); } V1ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); @Override OperatingSystemEnum getOs(); @Override RuntimeStack getRuntimeStack(); @Override String getImage(); @Override String getServerId(); @Override String getRegistryUrl(); @Override WebContainer getWebContainer(); @Override JavaVersion getJavaVersion(); @Override List<Resource> getResources(); }### Answer:
@Test public void getServerId() { assertNull(parser.getServerId()); final ContainerSetting containerSetting = mock(ContainerSetting.class); doReturn(containerSetting).when(mojo).getContainerSettings(); doReturn("serverId").when(containerSetting).getServerId(); assertEquals("serverId", parser.getServerId()); } |
### Question:
V1ConfigurationParser extends ConfigurationParser { @Override public String getRegistryUrl() { final ContainerSetting containerSetting = mojo.getContainerSettings(); if (containerSetting == null) { return null; } return containerSetting.getRegistryUrl(); } V1ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); @Override OperatingSystemEnum getOs(); @Override RuntimeStack getRuntimeStack(); @Override String getImage(); @Override String getServerId(); @Override String getRegistryUrl(); @Override WebContainer getWebContainer(); @Override JavaVersion getJavaVersion(); @Override List<Resource> getResources(); }### Answer:
@Test public void getRegistryUrl() { assertNull(parser.getRegistryUrl()); final ContainerSetting containerSetting = mock(ContainerSetting.class); doReturn(containerSetting).when(mojo).getContainerSettings(); doReturn("registryUrl").when(containerSetting).getRegistryUrl(); assertEquals("registryUrl", parser.getRegistryUrl()); } |
### Question:
AzureServicePrincipleAuthHelper { static AzureTokenCredentials getCredentialFromAzureCliWithServicePrincipal() throws InvalidConfigurationException, IOException { final JsonObject subscription = getDefaultSubscriptionObject(); final String servicePrincipalName = subscription == null ? null : subscription.get("user").getAsJsonObject().get("name").getAsString(); if (servicePrincipalName == null) { throw new InvalidConfigurationException(AZURE_CLI_GET_SUBSCRIPTION_FAIL); } final JsonArray tokens = getAzureCliTokenList(); if (tokens == null) { throw new InvalidConfigurationException(AZURE_CLI_LOAD_TOKEN_FAIL); } for (final JsonElement token : tokens) { final JsonObject tokenObject = (JsonObject) token; if (servicePrincipalName.equals(getStringFromJsonObject(tokenObject, "servicePrincipalId"))) { final String tenantId = getStringFromJsonObject(tokenObject, "servicePrincipalTenant"); final String key = getStringFromJsonObject(tokenObject, "accessToken"); final String certificateFile = getStringFromJsonObject(tokenObject, "certificateFile"); final String env = getStringFromJsonObject(subscription, "environmentName"); final String subscriptionId = getStringFromJsonObject(subscription, "id"); if (StringUtils.isNotBlank(key)) { return new ApplicationTokenCredentials(servicePrincipalName, tenantId, key, AzureAuthHelper.getAzureEnvironment(env)) .withDefaultSubscriptionId(subscriptionId); } if (StringUtils.isNotBlank(certificateFile) && new File(certificateFile).exists()) { return new ApplicationTokenCredentials(servicePrincipalName, tenantId, FileUtils.readFileToByteArray(new File(certificateFile)), null, AzureAuthHelper.getAzureEnvironment(env)) .withDefaultSubscriptionId(subscriptionId); } } } return null; } private AzureServicePrincipleAuthHelper(); }### Answer:
@Test public void testGetSPCredentials() throws Exception { final File testConfigDir = new File(this.getClass().getResource("/azure-cli/sp/azureProfile.json").getFile()).getParentFile(); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); final AzureTokenCredentials cred = AzureServicePrincipleAuthHelper.getCredentialFromAzureCliWithServicePrincipal(); assertEquals("00000000-0000-0000-0000-000000000002", ((ApplicationTokenCredentials) cred).clientId()); assertEquals("https: assertEquals("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", TestHelper.readField(cred, "clientSecret")); }
@Test public void testGetSPCredentialsNoSubscription() throws Exception { final File testConfigDir = new File(this.getClass().getResource("/azure-cli/no-subscription/azureProfile.json").getFile()).getParentFile(); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); try { AzureServicePrincipleAuthHelper.getCredentialFromAzureCliWithServicePrincipal(); } catch (InvalidConfigurationException ex) { } }
@Test public void testGetSPCredentialsNoTokens() throws Exception { final File testConfigDir = new File(this.getClass().getResource("/azure-cli/no-tokens/azureProfile.json").getFile()).getParentFile(); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); try { AzureServicePrincipleAuthHelper.getCredentialFromAzureCliWithServicePrincipal(); } catch (InvalidConfigurationException ex) { } }
@Test public void testGetCredentialsFromCliNotSP() throws Exception { final File testConfigDir = new File(this.getClass().getResource("/azure-cli/default/azureProfile.json").getFile()).getParentFile(); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); final AzureTokenCredentials cred = AzureServicePrincipleAuthHelper.getCredentialFromAzureCliWithServicePrincipal(); assertNull(cred); } |
### Question:
V1ConfigurationParser extends ConfigurationParser { @Override public WebContainer getWebContainer() throws AzureExecutionException { validate(validator.validateWebContainer()); return mojo.getJavaWebContainer(); } V1ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); @Override OperatingSystemEnum getOs(); @Override RuntimeStack getRuntimeStack(); @Override String getImage(); @Override String getServerId(); @Override String getRegistryUrl(); @Override WebContainer getWebContainer(); @Override JavaVersion getJavaVersion(); @Override List<Resource> getResources(); }### Answer:
@Test public void getWebContainer() throws AzureExecutionException { try { parser.getWebContainer(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "The configuration of <javaWebContainer> in pom.xml is not correct."); } doReturn(WebContainer.TOMCAT_8_5_NEWEST).when(mojo).getJavaWebContainer(); assertEquals(WebContainer.TOMCAT_8_5_NEWEST, parser.getWebContainer()); } |
### Question:
V1ConfigurationParser extends ConfigurationParser { @Override public JavaVersion getJavaVersion() throws AzureExecutionException { validate(validator.validateJavaVersion()); return JavaVersion.fromString(mojo.getJavaVersion()); } V1ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); @Override OperatingSystemEnum getOs(); @Override RuntimeStack getRuntimeStack(); @Override String getImage(); @Override String getServerId(); @Override String getRegistryUrl(); @Override WebContainer getWebContainer(); @Override JavaVersion getJavaVersion(); @Override List<Resource> getResources(); }### Answer:
@Test public void getJavaVersion() throws AzureExecutionException { try { parser.getJavaVersion(); } catch (AzureExecutionException e) { assertEquals(e.getMessage(), "Please config the <javaVersion> in pom.xml."); } doReturn("1.8").when(mojo).getJavaVersion(); assertEquals(JavaVersion.JAVA_8_NEWEST, parser.getJavaVersion()); } |
### Question:
AuthConfiguration { public void setClient(String client) { this.client = client; } String getClient(); void setClient(String client); String getTenant(); void setTenant(String tenant); String getKey(); void setKey(String key); String getCertificate(); void setCertificate(String certificate); String getCertificatePassword(); void setCertificatePassword(String certificatePassword); String getEnvironment(); void setEnvironment(String environment); String getServerId(); void setServerId(String serverId); String getHttpProxyHost(); void setHttpProxyHost(String httpProxyHost); String getHttpProxyPort(); void setHttpProxyPort(String httpProxyPort); List<ConfigurationProblem> validate(); }### Answer:
@Test public void testSetClient() { final AuthConfiguration auth = new AuthConfiguration(); auth.setClient("client1"); assertEquals("client1", auth.getClient()); } |
### Question:
AuthConfiguration { public void setTenant(String tenant) { this.tenant = tenant; } String getClient(); void setClient(String client); String getTenant(); void setTenant(String tenant); String getKey(); void setKey(String key); String getCertificate(); void setCertificate(String certificate); String getCertificatePassword(); void setCertificatePassword(String certificatePassword); String getEnvironment(); void setEnvironment(String environment); String getServerId(); void setServerId(String serverId); String getHttpProxyHost(); void setHttpProxyHost(String httpProxyHost); String getHttpProxyPort(); void setHttpProxyPort(String httpProxyPort); List<ConfigurationProblem> validate(); }### Answer:
@Test public void testSetTenant() { final AuthConfiguration auth = new AuthConfiguration(); auth.setTenant("tenant1"); assertEquals("tenant1", auth.getTenant()); } |
### Question:
AuthConfiguration { public void setKey(String key) { this.key = key; } String getClient(); void setClient(String client); String getTenant(); void setTenant(String tenant); String getKey(); void setKey(String key); String getCertificate(); void setCertificate(String certificate); String getCertificatePassword(); void setCertificatePassword(String certificatePassword); String getEnvironment(); void setEnvironment(String environment); String getServerId(); void setServerId(String serverId); String getHttpProxyHost(); void setHttpProxyHost(String httpProxyHost); String getHttpProxyPort(); void setHttpProxyPort(String httpProxyPort); List<ConfigurationProblem> validate(); }### Answer:
@Test public void testSetKey() { final AuthConfiguration auth = new AuthConfiguration(); auth.setKey("key1"); assertEquals("key1", auth.getKey()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.