src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
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; }
@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 ); }
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); }
@Test public void buildCommand() { assertEquals(3, CommandHandlerImpl.buildCommand("cmd").length); }
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); }
@Test public void getStdoutRedirect() { assertEquals(ProcessBuilder.Redirect.INHERIT, CommandHandlerImpl.getStdoutRedirect(true)); assertEquals(ProcessBuilder.Redirect.PIPE, CommandHandlerImpl.getStdoutRedirect(false)); }
DeployMojo extends AbstractFunctionMojo { protected void configureAppSettings(final Consumer<Map> withAppSettings, final Map appSettings) { if (appSettings != null && !appSettings.isEmpty()) { withAppSettings.accept(appSettings); } } @Override DeploymentType getDeploymentType(); }
@Test public void configureAppSettings() throws Exception { final WithCreate withCreate = mock(WithCreate.class); mojo.configureAppSettings(withCreate::withAppSettings, mojo.getAppSettingsWithDefaultValue()); verify(withCreate, times(1)).withAppSettings(anyMap()); }
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); }
@Test(expected = Exception.class) public void handleExitValue() throws Exception { final CommandHandlerImpl handler = new CommandHandlerImpl(); handler.handleExitValue(1, Arrays.asList(0L), "", null); }
CommandUtils { public static boolean isWindows() { return SystemUtils.IS_OS_WINDOWS; } static boolean isWindows(); static List<Long> getDefaultValidReturnCodes(); static List<Long> getValidReturnCodes(); }
@Test public void isWindows() { assertEquals(SystemUtils.IS_OS_WINDOWS, CommandUtils.isWindows()); }
CommandUtils { public static List<Long> getDefaultValidReturnCodes() { return Arrays.asList(0L); } static boolean isWindows(); static List<Long> getDefaultValidReturnCodes(); static List<Long> getValidReturnCodes(); }
@Test public void getDefaultValidReturnCodes() throws Exception { assertEquals(2, CommandUtils.getValidReturnCodes().size()); assertEquals(true, CommandUtils.getValidReturnCodes().contains(0L)); }
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(); }
@Test public void getValidReturnCodes() { assertEquals(Arrays.asList(0L), CommandUtils.getDefaultValidReturnCodes()); }
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; }
@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); }
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; }
@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); }
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; }
@Test public void getFTPClient() throws Exception { Exception caughtException = null; try { ftpUploader.getFTPClient("fakeFTPServer", "username", "password"); } catch (Exception e) { caughtException = e; } finally { assertNotNull(caughtException); } }
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); }
@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) { } }
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; }
@Test public void getProject() throws Exception { assertEquals(project, mojo.getProject()); }
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(); }
@Test(expected = AzureExecutionException.class) public void getArtifactHandlerThrowException() throws Exception { getMojoFromPom().getArtifactHandler(); }
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; }
@Test public void getSession() throws Exception { assertEquals(session, mojo.getSession()); }
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; }
@Test public void getMavenResourcesFiltering() throws Exception { assertEquals(filtering, mojo.getMavenResourcesFiltering()); }
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; }
@Test public void getBuildDirectoryAbsolutePath() throws Exception { assertEquals("target", mojo.getBuildDirectoryAbsolutePath()); }
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; }
@Test public void getAuthenticationSetting() throws Exception { assertEquals(authenticationSetting, mojo.getAuthenticationSetting()); }
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; }
@Test public void getAzureClient() throws Exception { assertEquals(azure, mojo.getAzureClient()); }
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; }
@Test public void getMavenSettings() { assertEquals(settings, mojo.getSettings()); }
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; }
@Test public void getSubscriptionId() throws Exception { assertEquals(SUBSCRIPTION_ID, mojo.getSubscriptionId()); }
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; }
@Test public void getTelemetryProxy() { assertEquals(telemetryProxy, mojo.getTelemetryProxy()); }
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; }
@Test public void isTelemetryAllowed() throws Exception { assertTrue(!mojo.isTelemetryAllowed()); }
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; }
@Test public void execute() throws Exception { mojo.execute(); }
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(); }
@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()); }
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; }
@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); }
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; }
@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)); }
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); }
@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()); }
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(); }
@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, "", ""); }
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(); }
@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(); }
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(); }
@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"); }
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(); }
@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); }
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); }
@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)); }
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); }
@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); }
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; }
@Test public void defineAppWithRuntime() throws Exception { AzureExecutionException exception = null; try { handler.defineAppWithRuntime(); } catch (AzureExecutionException e) { exception = e; } finally { assertNotNull(exception); } }
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; }
@Test public void updateAppRuntime() { final WebApp app = mock(WebApp.class); assertNull(handler.updateAppRuntime(app)); }
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); }
@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(); }
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); }
@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); }
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; }
@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(); }
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); }
@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(); }
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); }
@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); }
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); }
@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); }
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); }
@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(); }
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); }
@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); }
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; }
@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); }
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; }
@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"); }
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; }
@Test public void getAnnotationHandler() throws Exception { final PackageMojo mojo = getMojoFromPom(); final AnnotationHandler handler = mojo.getAnnotationHandler(); assertNotNull(handler); assertTrue(handler instanceof AnnotationHandlerImpl); }
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; }
@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()); }
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; }
@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(); }
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; }
@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); }
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; }
@Test public void prepareDeploymentFiles() throws IOException { }
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; }
@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()); }
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; }
@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(); }
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; }
@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); }
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; }
@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."); } }
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; }
@Test public void getSettingsHandler() throws Exception { final HandlerFactory factory = new HandlerFactoryImpl(); final SettingsHandler handler = factory.getSettingsHandler(mojo); assertNotNull(handler); assertTrue(handler instanceof SettingsHandlerImpl); }
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; }
@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); }
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; }
@Test public void getDeploymentSlotHandler() throws AzureExecutionException { final HandlerFactory factory = new HandlerFactoryImpl(); final DeploymentSlotHandler handler = factory.getDeploymentSlotHandler(mojo); assertNotNull(handler); assertTrue(handler instanceof DeploymentSlotHandler); }
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; }
@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); }
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; }
@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); }
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(); }
@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); }
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(); }
@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"); }
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); }
@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."); } }
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); }
@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()); }
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); }
@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()); }
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); }
@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()); }
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); }
@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()); }
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); }
@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()); }
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); }
@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()); }
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); }
@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()); }
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(); }
@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"); } }
V2ConfigurationParser extends ConfigurationParser { @Override protected List<Resource> getResources() { final Deployment deployment = mojo.getDeployment(); return deployment == null ? null : deployment.getResources(); } V2ConfigurationParser(AbstractWebAppMojo mojo, AbstractConfigurationValidator validator); }
@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()); }
ConfigurationParser { protected String getAppName() throws AzureExecutionException { validate(validator.validateAppName()); return mojo.getAppName(); } protected ConfigurationParser(final AbstractWebAppMojo mojo, final AbstractConfigurationValidator validator); WebAppConfiguration getWebAppConfiguration(); }
@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."); } }
ConfigurationParser { protected String getResourceGroup() throws AzureExecutionException { validate(validator.validateResourceGroup()); return mojo.getResourceGroup(); } protected ConfigurationParser(final AbstractWebAppMojo mojo, final AbstractConfigurationValidator validator); WebAppConfiguration getWebAppConfiguration(); }
@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."); } }
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(); }
@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()); }
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(); }
@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."); } }
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(); }
@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()); }
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(); }
@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: } }
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(); }
@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."); } }
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(); }
@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()); }
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(); }
@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()); }
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(); }
@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); }
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(); }
@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()); }
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(); }
@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()); }
DeployMojo extends AbstractWebAppMojo { protected void deployArtifacts(WebAppConfiguration webAppConfiguration) throws AzureAuthFailureException, InterruptedException, AzureExecutionException, IOException { try { util.beforeDeployArtifacts(); final WebApp app = getWebApp(); final DeployTarget target; if (this.isDeployToDeploymentSlot()) { final String slotName = getDeploymentSlotSetting().getName(); final DeploymentSlot slot = getDeploymentSlot(app, slotName); if (slot == null) { throw new AzureExecutionException(SLOT_SHOULD_EXIST_NOW); } target = new DeploymentSlotDeployTarget(slot); } else { target = new WebAppDeployTarget(app); } final ArtifactHandler artifactHandler = getFactory().getArtifactHandler(this); final boolean isV1Schema = SchemaVersion.fromString(this.getSchemaVersion()) == SchemaVersion.V1; if (isV1Schema) { handleV1Artifact(target, this.resources, artifactHandler); } else { final List<Resource> v2Resources = this.deployment == null ? null : this.deployment.getResources(); handleV2Artifact(target, v2Resources, artifactHandler); } } finally { util.afterDeployArtifacts(); } } static final String WEBAPP_NOT_EXIST; static final String WEBAPP_CREATED; static final String CREATE_DEPLOYMENT_SLOT; static final String CREATE_DEPLOYMENT_SLOT_DONE; static final String UPDATE_WEBAPP; static final String UPDATE_WEBAPP_SKIP; static final String UPDATE_WEBAPP_DONE; static final String STOP_APP; static final String START_APP; static final String STOP_APP_DONE; static final String START_APP_DONE; static final String WEBAPP_NOT_EXIST_FOR_SLOT; static final String SLOT_SHOULD_EXIST_NOW; }
@Test public void deployArtifactsWithNoResources() throws Exception { final DeployMojo mojo = getMojoFromPom("/pom-linux.xml"); final DeployMojo mojoSpy = spy(mojo); final WebApp app = mock(WebApp.class); doReturn("target/classes").when(mojoSpy).getDeploymentStagingDirectoryPath(); doReturn(app).when(mojoSpy).getWebApp(); doReturn(false).when(mojoSpy).isDeployToDeploymentSlot(); final MavenResourcesFiltering filtering = mock(MavenResourcesFiltering.class); doNothing().when(filtering).filterResources(any()); doReturn(filtering).when(mojoSpy).getMavenResourcesFiltering(); final MavenSession session = mock(MavenSession.class); doReturn(session).when(mojoSpy).getSession(); final MavenProject project = mock(MavenProject.class); doReturn(new File("target/..")).when(project).getBasedir(); doReturn(project).when(mojoSpy).getProject(); mojoSpy.deployArtifacts(mojoSpy.getWebAppConfiguration()); } @Test public void deployArtifactsWithResources() throws Exception { final DeployMojo mojo = getMojoFromPom("/pom-linux.xml"); final DeployMojo mojoSpy = spy(mojo); final WebApp app = mock(WebApp.class); doReturn(app).when(mojoSpy).getWebApp(); doReturn(false).when(mojoSpy).isDeployToDeploymentSlot(); doReturn("target/classes").when(mojoSpy).getDeploymentStagingDirectoryPath(); final MavenResourcesFiltering filtering = mock(MavenResourcesFiltering.class); doNothing().when(filtering).filterResources(any()); doReturn(filtering).when(mojoSpy).getMavenResourcesFiltering(); final MavenSession session = mock(MavenSession.class); doReturn(session).when(mojoSpy).getSession(); final MavenProject project = mock(MavenProject.class); doReturn(new File("target/..")).when(project).getBasedir(); doReturn(project).when(mojoSpy).getProject(); final DeployTarget deployTarget = new WebAppDeployTarget(app); mojoSpy.deployArtifacts(mojoSpy.getWebAppConfiguration()); verify(artifactHandler, times(1)).publish(refEq(deployTarget)); verifyNoMoreInteractions(artifactHandler); } @Test public void deployToDeploymentSlot() throws Exception { final DeployMojo mojo = getMojoFromPom("/pom-slot.xml"); final DeployMojo mojoSpy = spy(mojo); final DeploymentSlot slot = mock(DeploymentSlot.class); final WebApp app = mock(WebApp.class); final DeploymentSlotSetting slotSetting = mock(DeploymentSlotSetting.class); doReturn(app).when(mojoSpy).getWebApp(); doReturn(slotSetting).when(mojoSpy).getDeploymentSlotSetting(); doReturn("test").when(slotSetting).getName(); doReturn(slot).when(mojoSpy).getDeploymentSlot(app, "test"); doReturn("target/classes").when(mojoSpy).getDeploymentStagingDirectoryPath(); doReturn("target").when(mojoSpy).getBuildDirectoryAbsolutePath(); final MavenResourcesFiltering filtering = mock(MavenResourcesFiltering.class); doNothing().when(filtering).filterResources(any()); doReturn(filtering).when(mojoSpy).getMavenResourcesFiltering(); final MavenSession session = mock(MavenSession.class); doReturn(session).when(mojoSpy).getSession(); final MavenProject project = mock(MavenProject.class); doReturn(new File("target/..")).when(project).getBasedir(); doReturn(project).when(mojoSpy).getProject(); final DeployTarget deployTarget = new DeploymentSlotDeployTarget(slot); mojoSpy.deployArtifacts(mojoSpy.getWebAppConfiguration()); verify(artifactHandler, times(1)).publish(refEq(deployTarget)); verifyNoMoreInteractions(artifactHandler); }
AuthConfiguration { public List<ConfigurationProblem> validate() { final List<ConfigurationProblem> results = new ArrayList<>(); final String errorMessagePostfix = StringUtils.isNotBlank(serverId) ? "server: " + serverId + " in settings.xml." : "<auth> configuration."; if (StringUtils.isBlank(tenant)) { results.add(new ConfigurationProblem("tenant", tenant, "Cannot find 'tenant' in " + errorMessagePostfix, ERROR)); } if (StringUtils.isBlank(client)) { results.add(new ConfigurationProblem("client", client, "Cannot find 'client' in " + errorMessagePostfix, ERROR)); } if (StringUtils.isBlank(key) && StringUtils.isBlank(certificate)) { results.add(new ConfigurationProblem("key", null, "Cannot find either 'key' or 'certificate' in " + errorMessagePostfix, ERROR)); } if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(certificate)) { results.add(new ConfigurationProblem(null, null, "It is illegal to specify both 'key' and 'certificate' in " + errorMessagePostfix, WARNING)); } if (StringUtils.isNotBlank(environment) && !AzureAuthHelper.validateEnvironment(environment)) { results.add(new ConfigurationProblem("environment", environment, String.format("Invalid environment string '%s' in " + errorMessagePostfix, environment), ERROR)); } if ((StringUtils.isNotBlank(httpProxyHost) && StringUtils.isBlank(httpProxyPort)) || (StringUtils.isBlank(httpProxyHost) && StringUtils.isNotBlank(httpProxyPort))) { results.add(new ConfigurationProblem(null, null, "'httpProxyHost' and 'httpProxyPort' must both be set if you want to use proxy.", ERROR)); } if (StringUtils.isNotBlank(httpProxyPort)) { if (!StringUtils.isNumeric(httpProxyPort)) { results.add(new ConfigurationProblem("httpProxyPort", httpProxyPort, String.format("Invalid integer number for httpProxyPort: '%s'.", httpProxyPort), ERROR)); } else if (NumberUtils.toInt(httpProxyPort) <= 0 || NumberUtils.toInt(httpProxyPort) > 65535) { results.add(new ConfigurationProblem("httpProxyPort", httpProxyPort, String.format("Invalid range of httpProxyPort: '%s', it should be a number between %d and %d", httpProxyPort, 1, 65535), ERROR)); } } return results; } 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(); }
@Test public void testValidate() { AuthConfiguration auth = new AuthConfiguration(); auth.setClient("client1"); assertTrue(auth.validate().size() == 2); auth.setTenant("tenant1"); assertTrue(auth.validate().size() == 1); auth.setKey("key1"); assertTrue(auth.validate().size() == 0); auth.setCertificate("certificate1"); assertTrue(auth.validate().size() == 1); auth.setKey(""); assertTrue(auth.validate().size() == 0); auth = new AuthConfiguration(); auth.setTenant("tenant1"); assertTrue(auth.validate().size() == 2); auth.setClient("client1"); auth.setKey("key1"); assertTrue(auth.validate().size() == 0); auth.setEnvironment("hello"); assertTrue(auth.validate().size() == 1); auth.setEnvironment("azure"); assertTrue(auth.validate().size() == 0); auth.setHttpProxyPort("port"); assertTrue(auth.validate().size() == 2); auth.setHttpProxyHost("localhost"); assertTrue(auth.validate().size() == 1); auth.setHttpProxyPort("10000000"); assertTrue(auth.validate().size() == 1); auth.setHttpProxyPort("0"); assertTrue(auth.validate().size() == 1); auth.setHttpProxyPort("1000"); assertTrue(auth.validate().size() == 0); }
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(); }
@Test public void testSetClient() { final AuthConfiguration auth = new AuthConfiguration(); auth.setClient("client1"); assertEquals("client1", auth.getClient()); }
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(); }
@Test public void testSetTenant() { final AuthConfiguration auth = new AuthConfiguration(); auth.setTenant("tenant1"); assertEquals("tenant1", auth.getTenant()); }
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(); }
@Test public void testSetKey() { final AuthConfiguration auth = new AuthConfiguration(); auth.setKey("key1"); assertEquals("key1", auth.getKey()); }
AuthConfiguration { public void setCertificate(String certificate) { this.certificate = certificate; } 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(); }
@Test public void testSetCertificate() { final AuthConfiguration auth = new AuthConfiguration(); auth.setCertificate("certificate1"); assertEquals("certificate1", auth.getCertificate()); }
AuthConfiguration { public void setCertificatePassword(String certificatePassword) { this.certificatePassword = certificatePassword; } 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(); }
@Test public void testSetCertificatePassword() { final AuthConfiguration auth = new AuthConfiguration(); auth.setCertificatePassword("certificatePassword1"); assertEquals("certificatePassword1", auth.getCertificatePassword()); }
AuthConfiguration { public void setEnvironment(String environment) { this.environment = environment; } 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(); }
@Test public void testSetEnvironment() { final AuthConfiguration auth = new AuthConfiguration(); auth.setEnvironment("environment1"); assertEquals("environment1", auth.getEnvironment()); }
AuthConfiguration { public void setServerId(String serverId) { this.serverId = serverId; } 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(); }
@Test public void testSetServerId() { final AuthConfiguration auth = new AuthConfiguration(); auth.setServerId("serverId1"); assertEquals("serverId1", auth.getServerId()); }
AuthConfiguration { public void setHttpProxyHost(String httpProxyHost) { this.httpProxyHost = httpProxyHost; } 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(); }
@Test public void testSetHttpProxyHost() { final AuthConfiguration auth = new AuthConfiguration(); auth.setHttpProxyHost("httpProxyHost1"); assertEquals("httpProxyHost1", auth.getHttpProxyHost()); }
AuthConfiguration { public void setHttpProxyPort(String httpProxyPort) { this.httpProxyPort = httpProxyPort; } 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(); }
@Test public void testSetHttpProxyPort() { final AuthConfiguration auth = new AuthConfiguration(); auth.setHttpProxyPort("8080"); assertEquals("8080", auth.getHttpProxyPort()); }
ListMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { try { Log.info(TEMPLATES_START); printToSystemOut(TEMPLATES_FILE); Log.info(TEMPLATES_END); Log.info(BINDINGS_START); printToSystemOut(BINDINGS_FILE); Log.info(BINDINGS_END); Log.info(RESOURCES_START); printToSystemOut(RESOURCES_FILE); Log.info(RESOURCES_END); } catch (IOException e) { throw new AzureExecutionException("IO errror when printing templates:" + e.getMessage(), e); } } }
@Test public void doExecute() throws Exception { PowerMockito.doNothing().when(Log.class); Log.info(any(String.class)); final PrintStream out = mock(PrintStream.class); System.setOut(out); final ListMojo mojo = new ListMojo(); mojo.doExecute(); verify(out, atLeastOnce()).write(any(byte[].class), any(int.class), any(int.class)); }
MavenSettingHelper { public static AuthConfiguration getAuthConfigurationFromServer(MavenSession session, SettingsDecrypter settingsDecrypter, String serverId) throws MavenDecryptException { if (StringUtils.isBlank(serverId)) { throw new IllegalArgumentException("Parameter 'serverId' cannot be null or empty."); } final Server server = session.getSettings().getServer(serverId); if (server == null) { return null; } final AuthConfiguration configurationFromServer = new AuthConfiguration(); final Xpp3Dom configuration = (Xpp3Dom) server.getConfiguration(); if (configuration == null) { return configurationFromServer; } configurationFromServer.setTenant(getConfiguration(configuration, "tenant")); configurationFromServer.setClient(getConfiguration(configuration, "client")); final String rawKey = getConfiguration(configuration, "key"); configurationFromServer.setKey(isValueEncrypted(rawKey) ? decryptMavenProtectedValue(settingsDecrypter, "key", rawKey) : rawKey); configurationFromServer.setCertificate(getConfiguration(configuration, "certificate")); final String rawCertificatePassword = getConfiguration(configuration, "certificatePassword"); configurationFromServer.setCertificatePassword(isValueEncrypted(rawCertificatePassword) ? decryptMavenProtectedValue(settingsDecrypter, "certificatePassword", rawCertificatePassword) : rawCertificatePassword); configurationFromServer.setEnvironment(getConfiguration(configuration, "environment")); configurationFromServer.setHttpProxyHost(getConfiguration(configuration, "httpProxyHost")); configurationFromServer.setHttpProxyPort(getConfiguration(configuration, "httpProxyPort")); configurationFromServer.setServerId(serverId); return configurationFromServer; } private MavenSettingHelper(); static AuthConfiguration getAuthConfigurationFromServer(MavenSession session, SettingsDecrypter settingsDecrypter, String serverId); }
@Test public void testGetAuthConfigurationFromServer() throws Exception { final DefaultPlexusCipher cipher = new DefaultPlexusCipher(); final String encryptedKey = cipher.encryptAndDecorate("hello", "fake_master_key"); final String xml = "<configuration>\n" + " <client>df4d03fa-135b-4b7b-932d-2f2ba6449792</client>\n" + " <tenant>72f988bf-86f1-41af-91ab-2d7cd011db47</tenant>\n" + " <key>%s</key>\n" + " <environment>AZURE</environment>\n" + " </configuration>"; final Xpp3Dom pluginConfiguration = Xpp3DomBuilder.build(new ByteArrayInputStream(String.format(xml, encryptedKey).getBytes()), "UTF-8"); final Server server = Mockito.mock(Server.class); Mockito.when(server.getConfiguration()).thenReturn(pluginConfiguration); final Settings mavenSettings = Mockito.mock(Settings.class); Mockito.when(mavenSettings.getServer("test1")).thenReturn(server); final MavenSession mavenSession = Mockito.mock(MavenSession.class); Mockito.when(mavenSession.getSettings()).thenReturn(mavenSettings); final SettingsDecrypter settingsDecrypter = newSettingsDecrypter(Paths.get("src/test/resources/maven/settings/settings-security.xml")); final AuthConfiguration auth = MavenSettingHelper.getAuthConfigurationFromServer(mavenSession, settingsDecrypter, "test1"); assertEquals("72f988bf-86f1-41af-91ab-2d7cd011db47", auth.getTenant()); assertEquals("df4d03fa-135b-4b7b-932d-2f2ba6449792", auth.getClient()); assertEquals("AZURE", auth.getEnvironment()); assertEquals("hello", auth.getKey()); } @Test public void testBadServerId() throws Exception { final Server server = Mockito.mock(Server.class); final Settings mavenSettings = Mockito.mock(Settings.class); Mockito.when(mavenSettings.getServer("test1")).thenReturn(server); final MavenSession mavenSession = Mockito.mock(MavenSession.class); Mockito.when(mavenSession.getSettings()).thenReturn(mavenSettings); final SettingsDecrypter settingsDecrypter = newSettingsDecrypter(Paths.get("src/test/resources/maven/settings/settings-security.xml")); try { MavenSettingHelper.getAuthConfigurationFromServer(mavenSession, settingsDecrypter, ""); fail("should throw IAE."); } catch (IllegalArgumentException ex) { } try { MavenSettingHelper.getAuthConfigurationFromServer(mavenSession, settingsDecrypter, null); fail("should throw IAE."); } catch (IllegalArgumentException ex) { } assertNull(MavenSettingHelper.getAuthConfigurationFromServer(mavenSession, settingsDecrypter, "test2")); assertNotNull(MavenSettingHelper.getAuthConfigurationFromServer(mavenSession, settingsDecrypter, "test1")); }
LocalAuthServer { public void start() throws IOException { if (jettyServer.isStarted()) { return; } try { jettyServer.start(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new IOException(e); } } LocalAuthServer(); URI getURI(); void start(); void stop(); String waitForCode(); }
@Test public void testStart() throws IOException { localAuthServer.stop(); try { localAuthServer.start(); } catch (Exception ex) { fail("Should not fail on after start."); } }
LocalAuthServer { public void stop() throws IOException { semaphore.release(); try { jettyServer.stop(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new IOException(e); } } LocalAuthServer(); URI getURI(); void start(); void stop(); String waitForCode(); }
@Test public void testStop() throws IOException { localAuthServer.stop(); localAuthServer.stop(); }
AzureCredential { public static AzureCredential fromAuthenticationResult(AuthenticationResult result) { if (result == null) { throw new IllegalArgumentException("Parameter \"result\" cannot be null"); } final AzureCredential token = new AzureCredential(); token.setAccessTokenType(result.getAccessTokenType()); token.setAccessToken(result.getAccessToken()); token.setRefreshToken(result.getRefreshToken()); token.setIdToken(result.getIdToken()); token.setUserInfo(result.getUserInfo()); token.setMultipleResourceRefreshToken(result.isMultipleResourceRefreshToken()); return token; } private AzureCredential(); static AzureCredential fromAuthenticationResult(AuthenticationResult result); String getAccessTokenType(); void setAccessTokenType(String accessTokenType); String getIdToken(); void setIdToken(String idToken); UserInfo getUserInfo(); void setUserInfo(UserInfo userInfo); String getAccessToken(); void setAccessToken(String accessToken); String getRefreshToken(); void setRefreshToken(String refreshToken); boolean isMultipleResourceRefreshToken(); void setMultipleResourceRefreshToken(boolean isMultipleResourceRefreshToken); String getDefaultSubscription(); void setDefaultSubscription(String defaultSubscription); String getEnvironment(); void setEnvironment(String environment); }
@Test public void testFromNullResult() { try { AzureCredential.fromAuthenticationResult(null); fail("Should throw IAE"); } catch (IllegalArgumentException ex) { } }