src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
AzureContextExecutor { public AzureCredential execute() throws MalformedURLException, InterruptedException, ExecutionException, AzureLoginTimeoutException { final ExecutorService executorService = Executors.newSingleThreadExecutor(); try { final AuthenticationContext authenticationContext = new AuthenticationContext(baseUrl, true, executorService); final AuthenticationResult result = this.acquireTokenFunc.acquire(authenticationContext); if (result == null) { return null; } return AzureCredential.fromAuthenticationResult(result); } finally { executorService.shutdown(); } } AzureContextExecutor(String baseUrl, AcquireTokenFunction acquireTokenFunc); AzureCredential execute(); }
@Test public void testExecute() throws Exception { AzureContextExecutor executor = new AzureContextExecutor(AzureLoginHelper.baseURL(AzureEnvironment.AZURE), t -> null); assertNull(executor.execute()); final AuthenticationResult result = TestHelper.createAuthenticationResult(); executor = new AzureContextExecutor(AzureLoginHelper.baseURL(AzureEnvironment.AZURE), t -> result); final AzureCredential cred = executor.execute(); assertNotNull(cred); assertNotNull(cred.getAccessToken()); assertNotNull(cred.getRefreshToken()); assertNull(cred.getEnvironment()); assertNull(cred.getDefaultSubscription()); }
AzureLoginHelper { static AzureCredential oAuthLogin(AzureEnvironment env) throws AzureLoginFailureException, ExecutionException, DesktopNotSupportedException, InterruptedException { if (!Desktop.isDesktopSupported() || !Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { throw new DesktopNotSupportedException("Not able to launch a browser to log you in."); } final LocalAuthServer server = new LocalAuthServer(); try { server.start(); final URI redirectUri = server.getURI(); final String redirectUrl = redirectUri.toString(); final String code; try { final String authorizationUrl = authorizationUrl(env, redirectUrl); Desktop.getDesktop().browse(new URL(authorizationUrl).toURI()); code = server.waitForCode(); } catch (InterruptedException e) { throw new AzureLoginFailureException("The OAuth flow is interrupted."); } finally { server.stop(); } final AzureCredential cred = new AzureContextExecutor(baseURL(env), context -> context .acquireTokenByAuthorizationCode(code, env.managementEndpoint(), Constants.CLIENT_ID, redirectUri, null).get()).execute(); cred.setEnvironment(getShortNameForAzureEnvironment(env)); return cred; } catch (IOException | URISyntaxException e) { throw new AzureLoginFailureException(e.getMessage()); } } private AzureLoginHelper(); }
@Test public void testOauthWithBrowser() throws Exception { PowerMockito.mockStatic(Desktop.class); final URI uri = new URI("http: final Desktop mockDesktop = mock(Desktop.class); PowerMockito.doNothing().when(mockDesktop).browse(uri); PowerMockito.when(mockDesktop.isSupported(Desktop.Action.BROWSE)).thenReturn(true); PowerMockito.when(Desktop.isDesktopSupported()).thenReturn(true); PowerMockito.when(Desktop.getDesktop()).thenReturn(mockDesktop); mockStatic(LocalAuthServer.class); final LocalAuthServer mockServer = mock(LocalAuthServer.class); whenNew(LocalAuthServer.class).withNoArguments().thenReturn(mockServer); PowerMockito.doNothing().when(mockServer).start(); when(mockServer.getURI()).thenReturn(uri); when(mockServer.waitForCode()).thenReturn("test code"); PowerMockito.doNothing().when(mockServer).stop(); final AuthenticationResult authenticationResult = TestHelper.createAuthenticationResult(); final AuthenticationContext ctx = mock(AuthenticationContext.class); final AzureEnvironment env = AzureEnvironment.AZURE; final Future future = mock(Future.class); whenNew(AuthenticationContext.class).withAnyArguments().thenReturn(ctx); when(future.get()).thenReturn(authenticationResult); when(ctx.acquireTokenByAuthorizationCode("test code", env.managementEndpoint(), Constants.CLIENT_ID, uri, null)).thenReturn(future); final AzureCredential credFromOAuth = AzureLoginHelper.oAuthLogin(AzureEnvironment.AZURE); assertEquals("azure", credFromOAuth.getEnvironment()); assertEquals(authenticationResult.getAccessToken(), credFromOAuth.getAccessToken()); assertEquals(authenticationResult.getRefreshToken(), credFromOAuth.getRefreshToken()); } @Test public void testOAuthLoginNoBrowser() throws Exception { PowerMockito.mockStatic(Desktop.class); PowerMockito.when(Desktop.isDesktopSupported()).thenReturn(false); try { AzureLoginHelper.oAuthLogin(AzureEnvironment.AZURE); fail("Should report desktop not supported."); } catch (DesktopNotSupportedException e) { } }
AzureLoginHelper { static AzureCredential deviceLogin(AzureEnvironment env) throws AzureLoginFailureException, MalformedURLException, InterruptedException, ExecutionException { final String currentLogLevelFieldName = "currentLogLevel"; Object logger = null; Object oldLevelValue = null; try { try { logger = LoggerFactory.getLogger(AuthenticationContext.class); if (logger != null) { oldLevelValue = FieldUtils.readField(logger, currentLogLevelFieldName, true); FieldUtils.writeField(logger, currentLogLevelFieldName, LocationAwareLogger.ERROR_INT + 1, true); } } catch (IllegalArgumentException | IllegalAccessException e) { System.out.println("Failed to disable the log of AuthenticationContext, it will continue being noisy."); } final AzureCredential cred = new AzureContextExecutor(baseURL(env), authenticationContext -> { final DeviceCode deviceCode = authenticationContext.acquireDeviceCode(Constants.CLIENT_ID, env.managementEndpoint(), null).get(); System.out.println(TextUtils.yellow(deviceCode.getMessage())); long remaining = deviceCode.getExpiresIn(); final long interval = deviceCode.getInterval(); while (remaining > 0) { try { remaining -= interval; Thread.sleep(Duration.ofSeconds(interval).toMillis()); return authenticationContext.acquireTokenByDeviceCode(deviceCode, null).get(); } catch (ExecutionException e) { if (e.getCause() instanceof AuthenticationException && ((AuthenticationException) e.getCause()).getErrorCode() == AdalErrorCode.AUTHORIZATION_PENDING) { } else { System.out.println(e.getMessage()); break; } } } throw new AzureLoginTimeoutException( String.format("Cannot proceed with device login after waiting for %d minutes.", deviceCode.getExpiresIn() / 60)); }).execute(); cred.setEnvironment(getShortNameForAzureEnvironment(env)); return cred; } finally { try { if (logger != null) { FieldUtils.writeField(logger, currentLogLevelFieldName, oldLevelValue, true); } } catch (IllegalArgumentException | IllegalAccessException e) { System.out.println("Failed to reset the log level of AuthenticationContext."); } } } private AzureLoginHelper(); }
@Test public void testDeviceLogin() throws Exception { final AuthenticationResult authenticationResult = TestHelper.createAuthenticationResult(); final AuthenticationContext ctx = mock(AuthenticationContext.class); final AzureEnvironment env = AzureEnvironment.AZURE; final Future future = mock(Future.class); final DeviceCode deviceCode = mock(DeviceCode.class); when(deviceCode.getMessage()).thenReturn("Mock message"); when(deviceCode.getExpiresIn()).thenReturn(Long.valueOf(3600)); when(deviceCode.getInterval()).thenReturn(Long.valueOf(1)); whenNew(AuthenticationContext.class).withAnyArguments().thenReturn(ctx); when(future.get()).thenReturn(deviceCode); when(ctx.acquireDeviceCode(Constants.CLIENT_ID, env.managementEndpoint(), null)) .thenReturn(future); final Future future2 = mock(Future.class); when(future2.get()).thenReturn(authenticationResult); when(ctx.acquireTokenByDeviceCode(deviceCode, null)).thenReturn(future2); final AzureCredential credFromDeviceLogin = AzureLoginHelper.deviceLogin(AzureEnvironment.AZURE); assertEquals("azure", credFromDeviceLogin.getEnvironment()); assertEquals(authenticationResult.getAccessToken(), credFromDeviceLogin.getAccessToken()); assertEquals(authenticationResult.getRefreshToken(), credFromDeviceLogin.getRefreshToken()); }
AzureLoginHelper { static AzureCredential refreshToken(AzureEnvironment env, String refreshToken) throws MalformedURLException, InterruptedException, ExecutionException { if (env == null) { throw new IllegalArgumentException("Parameter 'env' cannot be null."); } if (StringUtils.isBlank(refreshToken)) { throw new IllegalArgumentException("Parameter 'refreshToken' cannot be empty."); } try { return new AzureContextExecutor(baseURL(env), authenticationContext -> authenticationContext .acquireTokenByRefreshToken(refreshToken, Constants.CLIENT_ID, env.managementEndpoint(), null).get()).execute(); } catch (AzureLoginTimeoutException e) { return null; } } private AzureLoginHelper(); }
@Test public void testRefreshToken() throws Exception { final AuthenticationResult authenticationResult = TestHelper.createAuthenticationResult(); final AuthenticationContext ctx = mock(AuthenticationContext.class); final AzureEnvironment env = AzureEnvironment.AZURE; final Future future = mock(Future.class); whenNew(AuthenticationContext.class).withAnyArguments().thenReturn(ctx); when(future.get()).thenReturn(authenticationResult); when(ctx.acquireTokenByRefreshToken("token for power mock", Constants.CLIENT_ID, env.managementEndpoint(), null)) .thenReturn(future); final Map<String, Object> map = TestHelper.getAuthenticationMap(); final AzureCredential cred = AzureLoginHelper.refreshToken(env, "token for power mock"); assertNotNull(cred); assertEquals(map.get("accessTokenType"), cred.getAccessTokenType()); assertEquals(map.get("accessToken"), cred.getAccessToken()); assertEquals(map.get("refreshToken"), cred.getRefreshToken()); assertEquals(map.get("idToken"), cred.getIdToken()); assertEquals(map.get("isMultipleResourceRefreshToken"), cred.isMultipleResourceRefreshToken()); }
AddMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { try { final List<FunctionTemplate> templates = loadAllFunctionTemplates(); final FunctionTemplate template = getFunctionTemplate(templates); final BindingTemplate bindingTemplate = FunctionUtils.loadBindingTemplate(template.getTriggerType()); final Map params = prepareRequiredParameters(template, bindingTemplate); final String newFunctionClass = substituteParametersInTemplate(template, params); saveNewFunctionToFile(newFunctionClass); } catch (MojoFailureException | IOException e) { throw new AzureExecutionException("Cannot add new java functions.", e); } } String getFunctionPackageName(); String getFunctionName(); String getClassName(); String getFunctionTemplate(); }
@Test public void doExecute() throws Exception { final AddMojo mojo = getMojoFromPom(); final Settings settings = new Settings(); settings.setInteractiveMode(false); ReflectionUtils.setVariableValueInObject(mojo, "basedir", new File("target/test")); ReflectionUtils.setVariableValueInObject(mojo, "settings", settings); mojo.setFunctionTemplate("HttpTrigger"); mojo.setFunctionName("New-Function"); mojo.setFunctionPackageName("com.microsoft.azure"); final File newFunctionFile = new File("target/test/src/main/java/com/microsoft/azure/New_Function.java"); newFunctionFile.delete(); mojo.doExecute(); assertTrue(newFunctionFile.exists()); }
AzureLoginHelper { static String authorizationUrl(AzureEnvironment env, String redirectUrl) throws URISyntaxException, MalformedURLException { if (env == null) { throw new IllegalArgumentException("Parameter 'env' cannot be null."); } if (StringUtils.isBlank(redirectUrl)) { throw new IllegalArgumentException("Parameter 'redirectUrl' cannot be empty."); } final URIBuilder builder = new URIBuilder(baseURL(env)); builder.setPath(String.format("%s/oauth2/authorize", builder.getPath())) .setParameter("client_id", Constants.CLIENT_ID) .setParameter("response_type", "code") .setParameter("redirect_uri", redirectUrl) .setParameter("prompt", "select_account") .setParameter("resource", env.managementEndpoint()); return builder.build().toURL().toString(); } private AzureLoginHelper(); }
@Test public void testAuthorizationUrl() throws Exception { String url = AzureLoginHelper.authorizationUrl(AzureEnvironment.AZURE, "http: Map<String, String> queryMap = splitQuery(url); assertEquals(Constants.CLIENT_ID, queryMap.get("client_id")); assertEquals("http: assertEquals("code", queryMap.get("response_type")); assertEquals("select_account", queryMap.get("prompt")); assertEquals(AzureEnvironment.AZURE.activeDirectoryResourceId(), queryMap.get("resource")); url = AzureLoginHelper.authorizationUrl(AzureEnvironment.AZURE_CHINA, "http: queryMap = splitQuery(url); assertEquals(Constants.CLIENT_ID, queryMap.get("client_id")); assertEquals("http: assertEquals("code", queryMap.get("response_type")); assertEquals("select_account", queryMap.get("prompt")); assertEquals(AzureEnvironment.AZURE_CHINA.activeDirectoryResourceId(), queryMap.get("resource")); } @Test public void tesAuthorizationUrlInvalidParameter() throws Exception { try { AzureLoginHelper.authorizationUrl(null, "http: fail("Should throw IAE when env is null."); } catch (IllegalArgumentException e) { } try { AzureLoginHelper.authorizationUrl(AzureEnvironment.AZURE_CHINA, ""); fail("Should throw IAE when redirectUrl is empty."); } catch (IllegalArgumentException e) { } }
AzureLoginHelper { static String baseURL(AzureEnvironment env) { return env.activeDirectoryEndpoint() + Constants.COMMON_TENANT; } private AzureLoginHelper(); }
@Test public void testBaseURL() { String baseUrl = AzureLoginHelper.baseURL(AzureEnvironment.AZURE); assertEquals("https: baseUrl = AzureLoginHelper.baseURL(AzureEnvironment.AZURE_US_GOVERNMENT); assertEquals("https: }
AzureLoginHelper { static String getShortNameForAzureEnvironment(AzureEnvironment env) { return AZURE_ENVIRONMENT_MAP.get(env); } private AzureLoginHelper(); }
@Test public void testAzureEnvironmentShortName() { assertEquals("azure", AzureLoginHelper.getShortNameForAzureEnvironment(AzureEnvironment.AZURE)); assertEquals("azure_china", AzureLoginHelper.getShortNameForAzureEnvironment(AzureEnvironment.AZURE_CHINA)); assertEquals("azure_us_government", AzureLoginHelper.getShortNameForAzureEnvironment(AzureEnvironment.AZURE_US_GOVERNMENT)); assertNull(AzureLoginHelper.getShortNameForAzureEnvironment(null)); }
AzureAuthHelper { public static AzureCredential oAuthLogin(AzureEnvironment env) throws AzureLoginFailureException, DesktopNotSupportedException, InterruptedException, ExecutionException { return AzureLoginHelper.oAuthLogin(env); } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testOAuthLogin() throws Exception { final AzureEnvironment env = AzureEnvironment.AZURE; final AzureCredential credExpected = AzureCredential.fromAuthenticationResult(TestHelper.createAuthenticationResult()); mockStatic(AzureLoginHelper.class); when(AzureLoginHelper.oAuthLogin(env)).thenReturn(credExpected); final AzureCredential cred = AzureAuthHelper.oAuthLogin(env); assertEquals(credExpected, cred); }
AzureAuthHelper { public static AzureCredential deviceLogin(AzureEnvironment env) throws AzureLoginFailureException, MalformedURLException, InterruptedException, ExecutionException { return AzureLoginHelper.deviceLogin(env); } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testDeviceLogin() throws Exception { final AzureEnvironment env = AzureEnvironment.AZURE; final AzureCredential credExpected = AzureCredential.fromAuthenticationResult(TestHelper.createAuthenticationResult()); mockStatic(AzureLoginHelper.class); when(AzureLoginHelper.deviceLogin(env)).thenReturn(credExpected); final AzureCredential cred = AzureAuthHelper.deviceLogin(env); assertEquals(credExpected, cred); }
AzureAuthHelper { public static AzureCredential refreshToken(AzureEnvironment env, String refreshToken) throws MalformedURLException, InterruptedException, ExecutionException { return AzureLoginHelper.refreshToken(env, refreshToken); } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testRefreshToken() throws Exception { final AzureEnvironment env = AzureEnvironment.AZURE; final AzureCredential credExpected = AzureCredential.fromAuthenticationResult(TestHelper.createAuthenticationResult()); mockStatic(AzureLoginHelper.class); when(AzureLoginHelper.refreshToken(env, "token for power mock")).thenReturn(credExpected); final AzureCredential cred = AzureAuthHelper.refreshToken(env, "token for power mock"); assertEquals(credExpected, cred); } @Test public void testRefreshTokenInvalidToken() throws Exception { try { AzureAuthHelper.refreshToken(AzureEnvironment.AZURE, "invalid"); fail("Should throw AzureLoginFailureException when refreshToken is invalid."); } catch (ExecutionException e) { } } @Test public void testRefreshTokenInvalidParameter() throws Exception { try { AzureAuthHelper.refreshToken(null, "abc"); fail("Should throw IAE when env is null."); } catch (IllegalArgumentException e) { } try { AzureAuthHelper.refreshToken(AzureEnvironment.AZURE_CHINA, ""); fail("Should throw IAE when refreshToken is empty."); } catch (IllegalArgumentException e) { } }
AzureAuthHelper { public static AzureEnvironment getAzureEnvironment(String environment) { if (StringUtils.isEmpty(environment)) { return AzureEnvironment.AZURE; } switch (environment.toUpperCase(Locale.ENGLISH)) { case "AZURE_CHINA": case "AZURECHINACLOUD": return AzureEnvironment.AZURE_CHINA; case "AZURE_GERMANY": case "AZUREGERMANCLOUD": return AzureEnvironment.AZURE_GERMANY; case "AZURE_US_GOVERNMENT": case "AZUREUSGOVERNMENT": return AzureEnvironment.AZURE_US_GOVERNMENT; default: return AzureEnvironment.AZURE; } } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testGetAzureEnvironment() { assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment(null)); assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment(" ")); assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment("azure")); assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment("aZUre")); assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment("AZURE_CLOUD")); assertEquals(AzureEnvironment.AZURE_GERMANY, AzureAuthHelper.getAzureEnvironment("AZURE_GERMANY")); assertEquals(AzureEnvironment.AZURE_GERMANY, AzureAuthHelper.getAzureEnvironment("AzureGermanCloud")); assertEquals(AzureEnvironment.AZURE_GERMANY, AzureAuthHelper.getAzureEnvironment("AZUREGERMANCLOUD")); assertEquals(AzureEnvironment.AZURE_US_GOVERNMENT, AzureAuthHelper.getAzureEnvironment("AZURE_US_GOVERNMENT")); assertEquals(AzureEnvironment.AZURE_US_GOVERNMENT, AzureAuthHelper.getAzureEnvironment("AZUREUSGOVERNMENT")); assertEquals(AzureEnvironment.AZURE_CHINA, AzureAuthHelper.getAzureEnvironment("AzureChinaCloud")); assertEquals(AzureEnvironment.AZURE_CHINA, AzureAuthHelper.getAzureEnvironment("Azure_China")); assertEquals(AzureEnvironment.AZURE, AzureAuthHelper.getAzureEnvironment("AzureChinaCloud ")); }
AddMojo extends AbstractFunctionMojo { protected void assureInputFromUser(final String prompt, final String initValue, final List<String> options, final Consumer<String> setter) { final String option = findElementInOptions(options, initValue); if (option != null) { Log.info(FOUND_VALID_VALUE); setter.accept(option); return; } out.printf("Choose from below options as %s %n", prompt); for (int i = 0; i < options.size(); i++) { out.printf("%d. %s%n", i, options.get(i)); } assureInputFromUser("Enter index to use: ", null, str -> { try { final int index = Integer.parseInt(str); return 0 <= index && index < options.size(); } catch (Exception e) { return false; } }, "Invalid index.", str -> { final int index = Integer.parseInt(str); setter.accept(options.get(index)); } ); } String getFunctionPackageName(); String getFunctionName(); String getClassName(); String getFunctionTemplate(); }
@Test public void assureInputFromUser() throws Exception { final AddMojo mojo = getMojoFromPom(); final AddMojo mojoSpy = spy(mojo); final Scanner scanner = mock(Scanner.class); doReturn("2").when(scanner).nextLine(); doReturn(scanner).when(mojoSpy).getScanner(); final Set<String> set = new HashSet<>(); mojoSpy.assureInputFromUser("property", "", Arrays.asList("a0", "a1", "a2"), set::add); assertTrue(set.contains("a2")); }
AzureAuthHelper { public static boolean validateEnvironment(String environment) { if (StringUtils.isBlank(environment)) { return true; } switch (environment.toUpperCase(Locale.ENGLISH)) { case "AZURE_CHINA": case "AZURECHINACLOUD": case "AZURE_GERMANY": case "AZUREGERMANCLOUD": case "AZURE_US_GOVERNMENT": case "AZUREUSGOVERNMENT": case "AZURE": case "AZURE_CLOUD": return true; default : return false; } } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testEnvironmentValidation() { assertTrue(AzureAuthHelper.validateEnvironment(null)); assertTrue(AzureAuthHelper.validateEnvironment("")); assertTrue(AzureAuthHelper.validateEnvironment(" ")); assertTrue(AzureAuthHelper.validateEnvironment("azure")); assertFalse(AzureAuthHelper.validateEnvironment("azure ")); assertTrue(AzureAuthHelper.validateEnvironment("azure_cloud")); assertTrue(AzureAuthHelper.validateEnvironment("AZURE_CLOUD")); assertTrue(AzureAuthHelper.validateEnvironment("aZURe")); assertFalse(AzureAuthHelper.validateEnvironment("aZURe ")); assertFalse(AzureAuthHelper.validateEnvironment("foo")); }
AzureAuthHelper { public static File getAzureSecretFile() { return new File(getAzureConfigFolder(), Constants.AZURE_SECRET_FILE); } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testGetAzureSecretFile() { TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, null); final File azureSecretFile = AzureAuthHelper.getAzureSecretFile(); assertEquals(Paths.get(System.getProperty("user.home"), ".azure", "azure-secret.json").toString(), azureSecretFile.getAbsolutePath()); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, "test_dir"); assertEquals(Paths.get("test_dir", "azure-secret.json").toFile().getAbsolutePath(), AzureAuthHelper.getAzureSecretFile().getAbsolutePath()); }
AzureAuthHelper { public static File getAzureConfigFolder() { return StringUtils.isNotBlank(System.getenv(Constants.AZURE_CONFIG_DIR)) ? new File(System.getenv(Constants.AZURE_CONFIG_DIR)) : Paths.get(System.getProperty(Constants.USER_HOME), Constants.AZURE_FOLDER).toFile(); } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testGetAzureConfigFolder() { TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, null); final File azureConfigFolder = AzureAuthHelper.getAzureConfigFolder(); assertEquals(Paths.get(System.getProperty("user.home"), ".azure").toString(), azureConfigFolder.getAbsolutePath()); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, "test_dir"); assertEquals(Paths.get("test_dir").toFile().getAbsolutePath(), AzureAuthHelper.getAzureConfigFolder().getAbsolutePath()); }
AzureAuthHelper { public static boolean existsAzureSecretFile() { final File azureSecretFile = getAzureSecretFile(); return azureSecretFile.exists() && azureSecretFile.isFile() && azureSecretFile.length() > 0; } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testExistsAzureSecretFile() { final File testConfigDir = new File(this.getClass().getResource("/azure-login/azure-secret.json").getFile()).getParentFile(); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); assertTrue(AzureAuthHelper.existsAzureSecretFile()); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getParentFile().getAbsolutePath()); assertFalse(AzureAuthHelper.existsAzureSecretFile()); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, ""); }
AzureAuthHelper { public static AzureCredential readAzureCredentials() throws IOException { return readAzureCredentials(getAzureSecretFile()); } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testReadAzureCredentials() throws Exception { final File testConfigDir = new File(this.getClass().getResource("/azure-login/azure-secret.json").getFile()).getParentFile(); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); assertTrue(AzureAuthHelper.existsAzureSecretFile()); assertNotNull(AzureAuthHelper.readAzureCredentials()); try { AzureAuthHelper.readAzureCredentials(null); fail("Should throw IAE"); } catch (IllegalArgumentException ex) { } }
AzureAuthHelper { public static void writeAzureCredentials(AzureCredential cred, File file) throws IOException { if (cred == null) { throw new IllegalArgumentException("Parameter 'cred' cannot be null."); } if (file == null) { throw new IllegalArgumentException("Parameter 'file' cannot be null."); } FileUtils.writeStringToFile(file, JsonUtils.toJson(cred), "utf8"); } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testWriteAzureCredentials() throws Exception { final File testConfigDir = new File(this.getClass().getResource("/azure-login/azure-secret.json").getFile()).getParentFile(); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); assertTrue(AzureAuthHelper.existsAzureSecretFile()); final AzureCredential cred = AzureAuthHelper.readAzureCredentials(); final File tempFile = new File(tempDirectory, "azure-secret.json"); AzureAuthHelper.writeAzureCredentials(cred, tempFile); final AzureCredential cred2 = AzureAuthHelper.readAzureCredentials(tempFile); assertEquals(cred.getAccessToken(), cred2.getAccessToken()); assertEquals(cred.getAccessTokenType(), cred2.getAccessTokenType()); assertEquals(cred.getRefreshToken(), cred2.getRefreshToken()); assertEquals(cred.getDefaultSubscription(), cred2.getDefaultSubscription()); assertEquals(cred.getEnvironment(), cred2.getEnvironment()); assertEquals(cred.getIdToken(), cred2.getIdToken()); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, tempDirectory.getAbsolutePath()); assertTrue(AzureAuthHelper.existsAzureSecretFile()); AzureAuthHelper.deleteAzureSecretFile(); assertFalse(AzureAuthHelper.existsAzureSecretFile()); assertFalse(AzureAuthHelper.deleteAzureSecretFile()); } @Test public void testWriteAzureCredentialsBadParameter() throws Exception { final File tempFile = File.createTempFile("azure-auth-helper-test", ".json"); try { AzureAuthHelper.writeAzureCredentials(null, tempFile); fail("Should throw IAE here."); } catch (IllegalArgumentException ex) { } try { AzureAuthHelper.writeAzureCredentials(AzureCredential.fromAuthenticationResult(TestHelper.createAuthenticationResult()), null); fail("Should throw IAE here."); } catch (IllegalArgumentException ex) { } }
AzureAuthHelper { static boolean isInCloudShell() { return System.getenv(Constants.CLOUD_SHELL_ENV_KEY) != null; } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testIsInCloudShell() { TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, "azure"); assertTrue(AzureAuthHelper.isInCloudShell()); TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, null); assertFalse(AzureAuthHelper.isInCloudShell()); }
AzureAuthHelper { public static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration) throws InvalidConfigurationException, IOException { if (configuration != null) { return new AzureTokenWrapper(AuthMethod.SERVICE_PRINCIPAL, AzureServicePrincipleAuthHelper.getAzureServicePrincipleCredentials(configuration)); } if (existsAzureSecretFile()) { try { return new AzureTokenWrapper(AuthMethod.AZURE_SECRET_FILE, getMavenAzureLoginCredentials(), getAzureSecretFile()); } catch (IOException ex) { } } if (isInCloudShell()) { return new AzureTokenWrapper(AuthMethod.CLOUD_SHELL, new MSICredentials()); } return getAzureCLICredential(AzureEnvironment.AZURE); } private AzureAuthHelper(); static AzureCredential oAuthLogin(AzureEnvironment env); static AzureCredential deviceLogin(AzureEnvironment env); static AzureCredential refreshToken(AzureEnvironment env, String refreshToken); static AzureEnvironment getAzureEnvironment(String environment); static String getAzureEnvironmentDisplayName(AzureEnvironment azureEnvironment); static boolean validateEnvironment(String environment); static File getAzureSecretFile(); static File getAzureConfigFolder(); static boolean existsAzureSecretFile(); static boolean deleteAzureSecretFile(); static void writeAzureCredentials(AzureCredential cred, File file); static AzureCredential readAzureCredentials(); static AzureCredential readAzureCredentials(File file); static AzureTokenCredentials getMavenAzureLoginCredentials(); static AzureTokenCredentials getMavenAzureLoginCredentials(AzureCredential credentials, AzureEnvironment env); static AzureTokenWrapper getAzureCLICredential(AzureEnvironment environment); static AzureTokenWrapper getServicePrincipalCredential(AuthConfiguration configuration); static AzureTokenWrapper getAzureMavenPluginCredential(AzureEnvironment environment); static AzureTokenWrapper getAzureSecretFileCredential(); static AzureTokenWrapper getAzureTokenCredentials(AuthConfiguration configuration); static AzureTokenWrapper getAzureCredentialByOrder(AuthConfiguration authConfiguration, AzureEnvironment azureEnvironment); }
@Test public void testGetAzureTokenCredentials() throws Exception { File testConfigDir = new File(this.getClass().getResource("/azure-login/azure-secret.json").getFile()).getParentFile(); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); AzureTokenCredentials cred = AzureAuthHelper.getAzureTokenCredentials(null); assertNotNull(cred); assertEquals("00000000-0000-0000-0000-000000000001", cred.defaultSubscriptionId()); testConfigDir = new File(this.getClass().getResource("/azure-cli/default/azureProfile.json").getFile()).getParentFile(); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); cred = AzureAuthHelper.getAzureTokenCredentials(null).getAzureTokenCredentials(); assertNotNull(cred); assertTrue(cred instanceof AzureCliCredentials); final AzureCliCredentials cliCred = (AzureCliCredentials) cred; assertEquals("00000000-0000-0000-0000-000000000001", cliCred.defaultSubscriptionId()); assertEquals("00000000-0000-0000-0000-000000000002", cliCred.clientId()); assertEquals("00000000-0000-0000-0000-000000000003", cliCred.domain()); assertEquals(AzureEnvironment.AZURE_CHINA, cliCred.environment()); testConfigDir = new File(this.getClass().getResource("/azure-cli/sp/azureProfile.json").getFile()).getParentFile(); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, testConfigDir.getAbsolutePath()); cred = AzureAuthHelper.getAzureTokenCredentials(null).getAzureTokenCredentials(); assertNotNull(cred); assertTrue(cred instanceof AzureCliCredentials); final AzureCliCredentials azureCliCredential = (AzureCliCredentials) cred; assertEquals("00000000-0000-0000-0000-000000000001", cred.defaultSubscriptionId()); assertEquals("00000000-0000-0000-0000-000000000002", azureCliCredential.clientId()); assertEquals("00000000-0000-0000-0000-000000000003", cred.domain()); assertEquals(AzureEnvironment.AZURE_CHINA, cliCred.environment()); TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, "azure"); assertTrue(AzureAuthHelper.isInCloudShell()); TestHelper.injectEnvironmentVariable(Constants.AZURE_CONFIG_DIR, "non-exist-folder"); cred = AzureAuthHelper.getAzureTokenCredentials(null).getAzureTokenCredentials(); assertNotNull(cred); assertTrue(cred instanceof MSICredentials); TestHelper.injectEnvironmentVariable(Constants.CLOUD_SHELL_ENV_KEY, null); assertNull(AzureAuthHelper.getAzureTokenCredentials(null)); } @Test public void testGetAzureTokenCredentialsFromConfiguration() throws Exception { final AuthConfiguration auth = new AuthConfiguration(); auth.setClient("client_id"); auth.setTenant("tenant_id"); auth.setKey("key"); auth.setEnvironment("azure_germany"); final AzureTokenCredentials cred = AzureAuthHelper.getAzureTokenCredentials(auth).getAzureTokenCredentials(); assertNotNull(cred); assertTrue(cred instanceof ApplicationTokenCredentials); assertNull(cred.defaultSubscriptionId()); assertEquals(AzureEnvironment.AZURE_GERMANY, cred.environment()); assertEquals("tenant_id", cred.domain()); assertEquals("client_id", ((ApplicationTokenCredentials) cred).clientId()); }
AddMojo extends AbstractFunctionMojo { protected void assureInputInBatchMode(final String input, final Function<String, Boolean> validator, final Consumer<String> setter, final boolean required) throws MojoFailureException { if (validator.apply(input)) { Log.info(FOUND_VALID_VALUE); setter.accept(input); return; } if (required) { throw new MojoFailureException(String.format("invalid input: %s", input)); } else { out.printf("The input is invalid. Use empty string.%n"); setter.accept(""); } } String getFunctionPackageName(); String getFunctionName(); String getClassName(); String getFunctionTemplate(); }
@Test(expected = MojoFailureException.class) public void assureInputInBatchModeWhenRequired() throws Exception { final AddMojo mojo = getMojoFromPom(); final AddMojo mojoSpy = spy(mojo); final Set<String> set = new HashSet<>(); mojoSpy.assureInputInBatchMode("", StringUtils::isNotEmpty, set::add, true); } @Test public void assureInputInBatchModeWhenNotRequired() throws Exception { final AddMojo mojo = getMojoFromPom(); final AddMojo mojoSpy = spy(mojo); final Set<String> set = new HashSet<>(); mojoSpy.assureInputInBatchMode("a0", StringUtils::isNotEmpty, set::add, true); assertTrue(set.contains("a0")); }
Volume { public Volume withPath(String path) { this.path = path; return this; } String getPath(); String getSize(); Boolean isPersist(); Volume withPath(String path); Volume withSize(String size); Volume withPersist(Boolean persist); }
@Test public void testWithPath() { final Volume volume = new Volume(); volume.withPath("/home/shared"); assertEquals("/home/shared", volume.getPath()); }
Volume { public Volume withSize(String size) { this.size = size; return this; } String getPath(); String getSize(); Boolean isPersist(); Volume withPath(String path); Volume withSize(String size); Volume withPersist(Boolean persist); }
@Test public void testWithSize() { final Volume volume = new Volume(); volume.withSize("10G"); assertEquals("10G", volume.getSize()); }
Volume { public Volume withPersist(Boolean persist) { this.persist = persist; return this; } String getPath(); String getSize(); Boolean isPersist(); Volume withPath(String path); Volume withSize(String size); Volume withPersist(Boolean persist); }
@Test public void testWithPersist() { final Volume volume = new Volume(); volume.withPersist(true); assertEquals(Boolean.TRUE, volume.isPersist()); }
DeploymentSettings extends BaseSettings { public void setCpu(String cpu) { this.cpu = cpu; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }
@Test public void testSetCpu() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setCpu("1"); assertEquals("1", deploy.getCpu()); }
DeploymentSettings extends BaseSettings { public void setMemoryInGB(String memoryInGB) { this.memoryInGB = memoryInGB; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }
@Test public void testSetMemoryInGB() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setMemoryInGB("2"); assertEquals("2", deploy.getMemoryInGB()); }
DeploymentSettings extends BaseSettings { public void setInstanceCount(String instanceCount) { this.instanceCount = instanceCount; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }
@Test public void testSetInstanceCount() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setInstanceCount("3"); assertEquals("3", deploy.getInstanceCount()); }
DeploymentSettings extends BaseSettings { public void setDeploymentName(String deploymentName) { this.deploymentName = deploymentName; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }
@Test public void testSetDeploymentName() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setDeploymentName("deploymentName1"); assertEquals("deploymentName1", deploy.getDeploymentName()); }
DeploymentSettings extends BaseSettings { public void setJvmOptions(String jvmOptions) { this.jvmOptions = jvmOptions; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }
@Test public void testSetJvmOptions() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setJvmOptions("jvmOptions1"); assertEquals("jvmOptions1", deploy.getJvmOptions()); }
DeploymentSettings extends BaseSettings { public void setRuntimeVersion(String runtimeVersion) { this.runtimeVersion = runtimeVersion; } String getCpu(); String getMemoryInGB(); String getInstanceCount(); String getDeploymentName(); void setCpu(String cpu); void setMemoryInGB(String memoryInGB); void setInstanceCount(String instanceCount); void setJvmOptions(String jvmOptions); void setDeploymentName(String deploymentName); String getJvmOptions(); String getRuntimeVersion(); void setRuntimeVersion(String runtimeVersion); }
@Test public void testSetRuntimeVersion() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setRuntimeVersion("8"); assertEquals("8", deploy.getRuntimeVersion()); }
SpringConfiguration { public SpringConfiguration withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }
@Test public void testWithSubscriptionId() { final SpringConfiguration config = new SpringConfiguration(); config.withSubscriptionId("subscriptionId1"); assertEquals("subscriptionId1", config.getSubscriptionId()); }
SpringConfiguration { public SpringConfiguration withResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }
@Test public void testWithResourceGroup() { final SpringConfiguration config = new SpringConfiguration(); config.withResourceGroup("resourceGroup1"); assertEquals("resourceGroup1", config.getResourceGroup()); }
SpringConfiguration { public SpringConfiguration withClusterName(String clusterName) { this.clusterName = clusterName; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }
@Test public void testWithClusterName() { final SpringConfiguration config = new SpringConfiguration(); config.withClusterName("clusterName1"); assertEquals("clusterName1", config.getClusterName()); }
SpringConfiguration { public SpringConfiguration withAppName(String appName) { this.appName = appName; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }
@Test public void testWithAppName() { final SpringConfiguration config = new SpringConfiguration(); config.withAppName("appName1"); assertEquals("appName1", config.getAppName()); }
SpringConfiguration { public SpringConfiguration withRuntimeVersion(String runtimeVersion) { this.runtimeVersion = runtimeVersion; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }
@Test public void testWithRuntimeVersion() { final SpringConfiguration config = new SpringConfiguration(); config.withRuntimeVersion("runtimeVersion1"); assertEquals("runtimeVersion1", config.getRuntimeVersion()); }
SpringConfiguration { public SpringConfiguration withDeployment(Deployment deployment) { this.deployment = deployment; return this; } Boolean isPublic(); String getSubscriptionId(); String getResourceGroup(); String getClusterName(); String getAppName(); String getRuntimeVersion(); String getActiveDeploymentName(); Deployment getDeployment(); SpringConfiguration withPublic(Boolean isPublic); SpringConfiguration withSubscriptionId(String subscriptionId); SpringConfiguration withResourceGroup(String resourceGroup); SpringConfiguration withClusterName(String clusterName); SpringConfiguration withAppName(String appName); SpringConfiguration withRuntimeVersion(String runtimeVersion); SpringConfiguration withActiveDeploymentName(String deploymentName); SpringConfiguration withDeployment(Deployment deployment); }
@Test public void testWithDeployment() { final SpringConfiguration config = new SpringConfiguration(); final Deployment deploy = Mockito.mock(Deployment.class); config.withDeployment(deploy); assertEquals(deploy, config.getDeployment()); }
Deployment { public Deployment withCpu(Integer cpu) { this.cpu = cpu; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }
@Test public void testWithCpu() { final Deployment deploy = new Deployment(); deploy.withCpu(1); assertEquals(1, (int) deploy.getCpu()); }
Deployment { public Deployment withMemoryInGB(Integer memoryInGB) { this.memoryInGB = memoryInGB; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }
@Test public void testWithMemoryInGB() { final Deployment deploy = new Deployment(); deploy.withMemoryInGB(2); assertEquals(2, (int) deploy.getMemoryInGB()); }
Deployment { public Deployment withInstanceCount(Integer instanceCount) { this.instanceCount = instanceCount; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }
@Test public void testWithInstanceCount() { final Deployment deploy = new Deployment(); deploy.withInstanceCount(3); assertEquals(3, (int) deploy.getInstanceCount()); }
Deployment { public Deployment withDeploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }
@Test public void testWithDeploymentName() { final Deployment deploy = new Deployment(); deploy.withDeploymentName("deploymentName1"); assertEquals("deploymentName1", deploy.getDeploymentName()); }
Deployment { public Deployment withJvmOptions(String jvmOptions) { this.jvmOptions = jvmOptions; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }
@Test public void testWithJvmOptions() { final Deployment deploy = new Deployment(); deploy.withJvmOptions("jvmOptions1"); assertEquals("jvmOptions1", deploy.getJvmOptions()); }
RunMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { final CommandHandler commandHandler = new CommandHandlerImpl(); checkStageDirectoryExistence(); checkRuntimeExistence(commandHandler); checkRuntimeCompatibility(commandHandler); runFunctions(commandHandler); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); }
@Test public void doExecute() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); doNothing().when(mojoSpy).checkStageDirectoryExistence(); doNothing().when(mojoSpy).checkRuntimeExistence(any(CommandHandler.class)); doNothing().when(mojoSpy).runFunctions(any(CommandHandler.class)); mojoSpy.doExecute(); verify(mojoSpy, times(1)).checkStageDirectoryExistence(); verify(mojoSpy, times(1)).checkRuntimeExistence(any(CommandHandler.class)); verify(mojoSpy, times(1)).runFunctions(any(CommandHandler.class)); }
Deployment { public Deployment withEnvironment(Map<String, String> environment) { this.environment = environment; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }
@Test public void testWithEnvironment() { final Deployment deploy = new Deployment(); deploy.withEnvironment(Collections.singletonMap("foo", "bar")); assertEquals("bar", deploy.getEnvironment().get("foo")); }
Deployment { public Deployment withResources(List<Resource> resources) { this.resources = resources; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); }
@Test public void testWithResources() { final Deployment deploy = new Deployment(); deploy.withResources(ResourcesUtils.getDefaultResources()); assertEquals(1, deploy.getResources().size()); assertEquals("*.jar", deploy.getResources().get(0).getIncludes().get(0)); }
AppSettings extends BaseSettings { public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); }
@Test public void testSetSubscriptionId() { final AppSettings app = new AppSettings(); app.setSubscriptionId("subscriptionId1"); assertEquals("subscriptionId1", app.getSubscriptionId()); }
AppSettings extends BaseSettings { public void setClusterName(String clusterName) { this.clusterName = clusterName; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); }
@Test public void testSetClusterName() { final AppSettings app = new AppSettings(); app.setClusterName("clusterName1"); assertEquals("clusterName1", app.getClusterName()); }
AppSettings extends BaseSettings { public void setAppName(String appName) { this.appName = appName; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); }
@Test public void testSetAppName() { final AppSettings app = new AppSettings(); app.setAppName("appName1"); assertEquals("appName1", app.getAppName()); }
PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); }
@Test public void testHandle() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("promote", "Input the {{global_property1}} value(***{{default}}***):"), new DefaultMapEntry<>("resource", "App"), new DefaultMapEntry<>("default", "defaultValueForUnitTest"), new DefaultMapEntry<>("property", "appName"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); wrapper.putCommonVariable("global_property1", "value1"); when(reader.readLine()).thenReturn(""); String result = wrapper.handle("testId1", false); assertEquals("defaultValueForUnitTest", result); when(reader.readLine()).thenReturn("abcd"); result = wrapper.handle("testId1", false); assertEquals("abcd", result); when(reader.readLine()).thenReturn("^^&$").thenReturn("wxyz"); result = wrapper.handle("testId1", false, null); assertEquals("wxyz", result); when(reader.readLine()).thenReturn("${expr}"); when(mockEval.evaluate("${expr}")).thenReturn("evaluated"); result = wrapper.handle("testId1", false); assertEquals("${expr}", result); when(reader.readLine()).thenReturn("${expr1}").thenReturn("${expr").thenReturn("${expr}"); when(mockEval.evaluate("${expr}")).thenReturn("evaluated"); when(mockEval.evaluate("${expr1}")).thenReturn("evaluated~!!"); when(mockEval.evaluate("${expr")).thenThrow(new ExpressionEvaluationException("bad expr")); result = wrapper.handle("testId1", false); assertEquals("${expr}", result); } @Test public void testEvaluateDefault() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("promote", "Input the {{global_property1}} value(***{{default}}***):"), new DefaultMapEntry<>("resource", "App"), new DefaultMapEntry<>("default", "${public}"), new DefaultMapEntry<>("property", "isPublic"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); when(mockEval.evaluate("${public}")).thenReturn("true"); when(reader.readLine()).thenReturn(""); assertEquals("${public}", wrapper.handle("testId1", false)); } @Test public void testBadTemplate() throws Exception { try { wrapper.handle("", true); fail("Should report IAE when template cannot be found."); } catch (IllegalArgumentException e) { } try { wrapper.handle("badId", true); fail("Should report IAE when template cannot be found."); } catch (IllegalArgumentException e) { } final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("resource", "ResourceNotFound"), new DefaultMapEntry<>("property", "cpu"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); try { wrapper.handle("testId1", true); fail("Should report IAE when resource cannot be found."); } catch (IllegalArgumentException e) { } map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("resource", "App"), new DefaultMapEntry<>("property", "cpu2"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); try { wrapper.handle("testId1", true); fail("Should report IAE when property cannot be found."); } catch (IllegalArgumentException e) { } } @Test public void testHandleBadConfiguration() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("promote", "Input the {{global_property1}} value(***{{default}}***):"), new DefaultMapEntry<>("default", "false"), new DefaultMapEntry<>("required", false), }); templates.put("testId1", map); map.put("property", ""); try { wrapper.handle("testId1", true, "foo"); fail("Should throw InvalidConfigurationException"); } catch (InvalidConfigurationException ex) { } map.put("property", "appName"); try { wrapper.handle("testId1", true, "foo"); fail("Should throw InvalidConfigurationException"); } catch (InvalidConfigurationException ex) { } map.put("resource", ""); try { wrapper.handle("testId1", true, "foo"); fail("Should throw InvalidConfigurationException"); } catch (InvalidConfigurationException ex) { } map.put("resource", "App"); wrapper.handle("testId1", true, "foo"); }
RequestParams { public static Builder builder (String resource) { return new Builder(resource); } RequestParams( String resource, String primaryKey, String primaryKeyValue, String column, String columnValue, String query, List<NameValuePair> queryArgs, List<NameValuePair> insert, List<NameValuePair> update, Integer page, Integer limit, Integer offset, String sort, String direction); static Builder builder(String resource); String getPath(final String root, final String alias); NameValuePair[] getParameters(); String getParametersAsQueryParams(); UrlEncodedFormEntity getFormBody(); StringEntity getJSONBody(); String toJSON(final List<NameValuePair> params); String getColumn(); String getColumnValue(); String getResource(); String getPrimaryKey(); String getPrimaryKeyValue(); Integer getPage(); Integer getLimit(); Integer getOffset(); String getSort(); String getDirection(); String getQuery(); List<NameValuePair> getQueryArgs(); List<NameValuePair> getInsert(); List<NameValuePair> getUpdate(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
@Test public void testRead_errors () { assertThrows(IllegalStateException.class, () -> RequestParams.builder(resource).value("x")); } @Test public void testDynamicQuery_errors () { assertThrows(IllegalArgumentException.class, () -> RequestParams.builder(resource).dynamicQuery("invalid")); assertThrows(IllegalArgumentException.class, () -> RequestParams.builder(resource).dynamicQuery("Find")); assertThrows(IllegalStateException.class, () -> RequestParams.builder(resource).addQueryParam("bar")); }
TkFriend implements TkRegex { @Override public Response act(final RqRegex req) throws IOException { final User user = new RqAlias(this.base, req).user(); final String alias = req.matcher().group(1); final Iterable<Friend> opts = user.friends(alias); if (Iterables.isEmpty(opts)) { throw new RsFailure( String.format("alias \"%s\" not found", alias) ); } final Friend friend = opts.iterator().next(); if (!friend.alias().equals(alias)) { throw new RsFailure( String.format("alias \"%s\" is not found", alias) ); } final byte[] img = new JdkRequest(friend.photo()) .through(AutoRedirectingWire.class) .through(RetryWire.class) .through(OneMinuteWire.class) .header(HttpHeaders.ACCEPT, "image/*") .header(HttpHeaders.USER_AGENT, "Netbout.com") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .binary(); BufferedImage image = ImageIO.read(new ByteArrayInputStream(img)); if (image == null) { image = ImageIO.read(new URL("http: } final Image thumb = image.getScaledInstance( Tv.HUNDRED, -1, Image.SCALE_SMOOTH ); final BufferedImage bthumb = new BufferedImage( thumb.getWidth(null), thumb.getHeight(null), BufferedImage.TYPE_INT_RGB ); bthumb.getGraphics().drawImage(thumb, 0, 0, null); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bthumb, "png", baos); return new RsFluent() .withType("image/png") .withHeader( "Cache-Control", String.format( "private, max-age=%d", TimeUnit.DAYS.toSeconds(1L) ) ) .withBody(new ByteArrayInputStream(baos.toByteArray())); } TkFriend(final Base bse); @Override Response act(final RqRegex req); }
@Test public void buildsPngImage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; base.user(new URN(urn)).aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkFriend(base).act( new RqRegex.Fake( new RqWithAuth(urn), "(.*)", alias ) ) ), Matchers.notNullValue() ); }
MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); }
@Test public void formatsTextToHtml() throws Exception { final String meta = new MarkdownTxtmark().html( Joiner.on(MarkdownTxtmarkTest.EOL).join( "**hi**, _dude_!\r", "", " b**o", " ", " ", " o**m", "" ) ); MatcherAssert.assertThat( String.format("<x>%s</x>", meta), Matchers.describedAs( meta, XhtmlMatchers.hasXPaths( "/x/p/strong[.='hi']", "/x/p/em[.='dude']", Joiner.on(MarkdownTxtmarkTest.EOL).join( "/x/pre/code[.=' b**o", "", "", "o**m", "']" ) ) ) ); } @Test public void handlesBrokenFormattingGracefully() throws Exception { final String[] texts = { Joiner.on(MarkdownTxtmarkTest.EOL).join("**", ""), "__", "", "**hi there! {{{", Joiner.on(MarkdownTxtmarkTest.EOL).join( " ", " ", " ", " ", "" ), }; for (final String text : texts) { MatcherAssert.assertThat( String.format("<z>%s</z>", new MarkdownTxtmark().html(text)), XhtmlMatchers.hasXPath("/z") ); } } @Test public void handlesReferenceLinks() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html( "Reference-style: \n![alt text][logo]\n\n[logo]: https: ), Matchers.equalTo( "<p>Reference-style:<br />\n<img src=\"https: ) ); } @Test public void handlesScriptViolation() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html( "<script>alert()</script>" ), Matchers.equalTo( "<p>&lt;script>alert()&lt;/script></p>\n" ) ); } @Test public void formatsTextFragmentsToHtml() throws Exception { final String[][] texts = { new String[] {"hi, *dude*!", "<p>hi, <em>dude</em>!</p>"}, new String[] { "hello, **dude**!", "<p>hello, <strong>dude</strong>!</p>", }, new String[] { "wazzup, ***dude***!", "<p>wazzup, <strong><em>dude</em></strong>!</p>", }, new String[] { "hey, _man_!", "<p>hey, <em>man</em>!</p>", }, new String[] { "x: `oops`", "<p>x: <code>oops</code></p>", }, new String[] { "[a](http: "<p><a href=\"http: }, new String[] {"}}}", "<p>}}}</p>"}, }; for (final String[] pair : texts) { MatcherAssert.assertThat( new MarkdownTxtmark().html(pair[0]).trim(), Matchers.equalTo(pair[1]) ); } } @Test public void formatsCodeFragmentsToHtml() throws Exception { final String[][] texts = { new String[] { "```\ncode\nanother line of code\n```", "<p><pre><code>code\nanother line of code</code></pre></p>", }, new String[] { "``code span not block\nextra line``", "<p><code>code span not block\nextra line</code></p>", }, new String[] { "`single char\nextra line with eol\n`", "<p><code>single char\nextra line with eol\n</code></p>", }, }; for (final String[] pair : texts) { MatcherAssert.assertThat( new MarkdownTxtmark().html(pair[0]).trim(), Matchers.equalTo(pair[1]) ); } } @Test public void formatsBulletsToHtml() throws Exception { final String meta = new MarkdownTxtmark().html( Joiner.on(MarkdownTxtmarkTest.EOL).join( "my list:", "", "* line one", "* line two", "", "normal text now" ) ); MatcherAssert.assertThat( String.format("<r>%s</r>", meta), Matchers.describedAs( meta, XhtmlMatchers.hasXPaths( "/r/p[text()='my list:']", "/r/ul[count(li) = 2]", "/r/ul/li[text()='line one']", "/r/ul/li[text()='line two']", "/r/p[.='normal text now']" ) ) ); } @Test public void breaksSingleLine() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html( Joiner.on(MarkdownTxtmarkTest.EOL) .join("line1 line", "line2", "", "line3").trim() ), Matchers.equalTo( Joiner.on(MarkdownTxtmarkTest.EOL).join( "<p>line1 line<br />", "line2<br /></p>", "<p>line3</p>", "" ) ) ); } @Test public void leavesDivUntouched() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html("<div>hey<svg viewBox='444'/></div>"), XhtmlMatchers.hasXPaths( "/div/svg[@viewBox]" ) ); } @Test public void detectsLinks() throws Exception { final String[][] texts = { new String[] { "<a href=\"http: "<p><a href=\"http: }, new String[] { "http: "<p><a href=\"http: }, new String[]{ "(http: "<p>(<a href=\"http: }, new String[] { "(http: "<p>(<a href=\"http: }, new String[] { "(https: "<p>(<a href=\"https: }, new String[] { "[foo](http: "<p><a href=\"http: }, new String[] { "[http: "<p><a href=\"http: }, new String[] { "[http: "<p>[<a href=\"http: }, new String[] { "[google](http: "<p><a href=\"http: }, new String[] { Joiner.on(MarkdownTxtmarkTest.EOL).join( "http: "http: ), Joiner.on(MarkdownTxtmarkTest.EOL).join( "<p><a href=\"http: "<a href=\"http: ), }, new String[] { "![logo] (http: "<p><img src=\"http: }, new String[] { "![logo](http: "<p><img src=\"http: }, }; for (final String[] pair : texts) { MatcherAssert.assertThat( new MarkdownTxtmark().html(pair[0]).trim(), Matchers.equalTo(pair[1]) ); } } @Test public void escapesReplacement() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html("backslash \\ and group reference $3\n"), Matchers.is("<p>backslash \\ and group reference $3<br /></p>\n") ); } @Test public void handlesWhitespaceAfterLinks() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html( "Hi [google](http: ), Matchers.equalTo( "<p>Hi <a href=\"http: ) ); }
TkIndex implements Take { @Override public Response act(final Request req) throws IOException { return new RsPage( "/xsl/account.xsl", this.base, new RqWithDefaultHeader(req, HttpHeaders.ACCEPT, "text/xml"), new XeLink("save-email", "/acc/save") ); } TkIndex(final Base bse); @Override Response act(final Request req); }
@Test public void rendersPage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; base.user(URN.create(urn)).aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkIndex(base).act(new RqWithAuth(urn)) ).printBody(), XhtmlMatchers.hasXPaths( "/page/alias/email", "/page/links/link[@rel='save-email']/@href" ) ); }
PsTwice implements Pass { @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } PsTwice(final Pass first, final Pass second); @Override Opt<Identity> enter(final Request req); @Override Response exit(final Response response, final Identity identity); }
@Test public void returnsSecondIdentity() throws Exception { MatcherAssert.assertThat( new PsTwice( new PsFake(true), new PsLogout() ).enter(new RqFake()).get(), Matchers.is(Identity.ANONYMOUS) ); } @Test public void returnsEmptyIdentity() throws Exception { MatcherAssert.assertThat( new PsTwice( new PsFake(false), new PsLogout() ).enter(new RqFake()).has(), Matchers.equalTo(false) ); }
PsTwice implements Pass { @Override public Response exit(final Response response, final Identity identity) throws IOException { return this.snd.exit(response, identity); } PsTwice(final Pass first, final Pass second); @Override Opt<Identity> enter(final Request req); @Override Response exit(final Response response, final Identity identity); }
@Test public void returnsCorrectResponseOnExit() throws Exception { MatcherAssert.assertThat( new PsTwice( new PsFake(true), new PsLogout() ).exit(new RsEmpty(), Identity.ANONYMOUS) .head().iterator().next(), Matchers.containsString("HTTP/1.1 200 O") ); }
TkFavicon implements Take { @Override public Response act(final Request req) throws IOException { final long unread = TkFavicon.unread(req); final int width = 64; final int height = 64; final BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB ); final Graphics graph = image.getGraphics(); graph.setColor(new Color(0x4b, 0x42, 0x50)); graph.fillRect(0, 0, width, height); if (unread > 0L) { final String text; if (unread >= (long) Tv.HUNDRED) { text = "99"; } else { text = Long.toString(unread); } graph.setColor(Color.WHITE); graph.setFont(new Font(Font.SANS_SERIF, Font.BOLD, height / 2)); graph.drawString( text, width - width / Tv.TEN - graph.getFontMetrics().stringWidth(text), height - height / Tv.TEN ); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "gif", baos); return new RsWithType( new RsWithBody(baos.toByteArray()), "image/gif" ); } @Override Response act(final Request req); }
@Test public void buildsGifImage() throws Exception { MatcherAssert.assertThat( new RsPrint( new TkFavicon().act(new RqFake("GET", "/?unread=44")) ).printBody(), Matchers.notNullValue() ); }
TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } TkAttach(final Base bse); @Override Response act(final Request req); }
@Test public void sendsMessageToBout() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:1"; final User user = base.user(new URN(urn)); user.aliases().add("jeff1"); final Alias alias = user.aliases().iterate().iterator().next(); final long number = alias.inbox().start(); final Bout bout = alias.inbox().bout(number); bout.friends().invite(alias.name()); final RqWithAuth request = new RqWithAuth( urn, new RqMultipart.Fake( TkAttachTest.fake(number), new RqWithHeaders( TkAttachTest.body("non-zero"), String.format(TkAttachTest.POST_URL, number), "Content-Disposition: form-data; name=\"file\"; filename=\"some.xml\"", "Content-Type: application/xml", "Content-Length: 8" ) ) ); try { new FkBout(".+", new TkAttach(base)).route(request); } catch (final RsForward response) { MatcherAssert.assertThat( response, new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER) ); } MatcherAssert.assertThat( bout.messages().iterate().iterator().next().text(), Matchers.containsString("attachment \"some.xml\"") ); } @Test(expected = RsFailure.class) public void ignoresWrongRequest() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:3"; final User user = base.user(new URN(urn)); user.aliases().add("jeff3"); final Alias alias = user.aliases().iterate().iterator().next(); final long bout = alias.inbox().start(); alias.inbox().bout(bout).friends().invite(alias.name()); new FkBout(".*", new TkAttach(base)).route( new RqWithAuth( urn, new RqMultipart.Fake( TkAttachTest.fake(bout), new RqWithHeaders( new RqLive( new ByteArrayInputStream("content2".getBytes()) ), String.format(TkAttachTest.POST_URL, bout), "Content-Disposition: form-data; name=\"file\"; filenam=\"aBaaPDF.pdf\"", "Content-Type: application/pdf" ) ) ) ); } @Test public void ignoresWrongFile() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:2"; final User user = base.user(new URN(urn)); user.aliases().add("jeff2"); final Alias alias = user.aliases().iterate().iterator().next(); final long bout = alias.inbox().start(); alias.inbox().bout(bout).friends().invite(alias.name()); final String file = "test.bin"; final RqWithAuth request = new RqWithAuth( urn, new RqMultipart.Fake( TkAttachTest.fake(bout), new RqWithHeaders( TkAttachTest.body(""), String.format(TkAttachTest.POST_URL, bout), String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"", file), "Content-Type: application/octet-stream" ) ) ); try { new FkBout(".*$", new TkAttach(base)).route(request); Assert.fail("Expected RsFailure exception but nothing was thrown"); } catch (final RsFailure ex) { MatcherAssert.assertThat( "file unexpectedly exists after attach failure", new Attachments.Search( alias.inbox().bout(bout).attachments() ).exists(file), Matchers.is(false) ); } }
TkIndex implements Take { private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } TkIndex(final Base bse); @Override Response act(final Request req); }
@Test public void rendersBoutPage() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:1"; final User user = base.user(new URN(urn)); user.aliases().add("jeff"); final Alias alias = user.aliases().iterate().iterator().next(); final Bout bout = alias.inbox().bout(alias.inbox().start()); bout.attachments().create("a1"); bout.messages().post("hello, world!"); bout.friends().invite(alias.name()); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( new FkBout(TkIndexTest.REGEX, new TkIndex(base)).route( new RqWithAuth( urn, new RqFake( RqMethod.GET, String.format("/b/%d", bout.number()) ) ) ).get() ).printBody() ), XhtmlMatchers.hasXPaths( "/page/bout[number=1]", "/page/bout[title='untitled']", "/page/bout[unread=0]", "/page/bout/friends/friend[alias='jeff']", "/page/bout/friends/friend/links/link[@rel='photo']", "/page/bout/friends/friend/links/link[@rel='kick']", "/page/bout/attachments/attachment/links/link[@rel='delete']", "/page/bout/messages/message[text='hello, world!']" ) ); } @Test public void searchesMessages() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:99"; final User user = base.user(new URN(urn)); user.aliases().add("test-search-user"); final Alias alias = user.aliases().iterate().iterator().next(); final Bout bout = alias.inbox().bout(alias.inbox().start()); bout.messages().post("test1"); bout.messages().post("test2"); bout.messages().post("fest"); bout.friends().invite(alias.name()); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( new FkBout(TkIndexTest.REGEX, new TkIndex(base)).route( new RqWithAuth( urn, new RqFake( RqMethod.GET, String.format( "/b/%d/search?q=test", bout.number() ) ) ) ).get() ).printBody() ), XhtmlMatchers.hasXPaths( "/page/bout/friends/friend[alias='test-search-user']", "/page/bout/messages/message[text='test2']", "/page/bout/messages/message[text='test1']" ) ); }
TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } TkSaveEmail(final Base bse); TkSaveEmail(final Base bse, final boolean lcl); @Override Response act(final Request req); }
@Test public void savesEmail() throws Exception { final Base base = new CdBase(new MkBase()); final String urn = "urn:test:1"; final User user = base.user(new URN(urn)); user.aliases().add("alias"); final Alias alias = user.aliases().iterate().iterator().next(); alias.email("[email protected]"); new TkAuth( new TkSaveEmail(base, false), new PsFixed(new Identity.Simple(urn)) ).act( new RqForm.Fake( new RqFake(), TkSaveEmailTest.EMAIL, "[email protected]" ) ); MatcherAssert.assertThat( alias.email(), Matchers.equalTo("[email protected][email protected]") ); } @Test public void savesEmailLocal() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:2"; final User user = base.user(new URN(urn)); user.aliases().add("alias2"); final Alias alias = user.aliases().iterate().iterator().next(); alias.email("[email protected]"); final String email = "[email protected]"; new TkAuth( new TkSaveEmail(base), new PsFixed(new Identity.Simple(urn)) ).act(new RqForm.Fake(new RqFake(), TkSaveEmailTest.EMAIL, email)); MatcherAssert.assertThat( alias.email(), Matchers.equalTo(email) ); } @Test(expected = RsForward.class) public void throwsRsForward() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:3"; final User user = base.user(new URN(urn)); user.aliases().add("alias3"); final Alias alias = user.aliases().iterate().iterator().next(); alias.email("[email protected]"); new TkAuth( new TkSaveEmail(base, true), new PsFixed(new Identity.Simple(urn)) ).act( new RqForm.Fake( new RqFake(), TkSaveEmailTest.EMAIL, "invalidemail" ) ); }
TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } TkInvite(final Base bse); @Override Response act(final Request req); String inviteByEmail(@NotNull(message = "Invite can't be NULL") final String invite, final Bout bout); }
@Test (expected = RsForward.class) public void invitesUserByEmail() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:1"; final User user = base.user(new URN(urn)); user.aliases().add("jeff"); final Alias alias = user.aliases().iterate().iterator().next(); final Bout bout = alias.inbox().bout(alias.inbox().start()); bout.messages().post("Before invite by email."); bout.friends().invite(alias.name()); try { new TkInvite(base).act( new RqWithHeader( new RqWithAuth( urn, new RqFake( RqMethod.POST, String.format( TkInviteTest.INVITE_PATH, bout.number() ), "[email protected]" ) ), TkInviteTest.NETBOUT_HEADER, Long.toString(bout.number()) ) ); } catch (final RsForward ex) { MatcherAssert.assertThat( ex.getLocalizedMessage(), Matchers.containsString("foo-bar-airfrc") ); throw ex; } } @Test (expected = RsFailure.class) public void failsWhenInvitingWithTooLongAlias() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:2"; final User user = base.user(new URN(urn)); final String name = StringUtils.join( "12345678901234567890123456789012345678901234", "5678901234567890123456789012345678901234567", "890123456789012345678901234567890" ); user.aliases().add("jack"); final Alias alias = user.aliases().iterate().iterator().next(); final Bout bout = alias.inbox().bout(alias.inbox().start()); try { new TkInvite(base).act( new RqWithHeader( new RqWithAuth( urn, new RqFake( RqMethod.POST, String.format( TkInviteTest.INVITE_PATH, bout.number() ), String.format(TkInviteTest.INVITE_PARAM, name) ) ), TkInviteTest.NETBOUT_HEADER, Long.toString(bout.number()) ) ); } catch (final RsFailure ex) { MatcherAssert.assertThat( ex.getLocalizedMessage(), Matchers.containsString("alias is too long") ); throw ex; } } @Test (expected = RsForward.class) public void invitesValidAlias() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:3"; final User user = base.user(new URN(urn)); final String name = "john"; user.aliases().add(name); final Alias alias = user.aliases().iterate().iterator().next(); try { final Bout bout = alias.inbox().bout(alias.inbox().start()); new TkInvite(base).act( new RqWithHeader( new RqWithAuth( urn, new RqFake( RqMethod.POST, String.format( TkInviteTest.INVITE_PATH, bout.number() ), String.format(TkInviteTest.INVITE_PARAM, name) ) ), TkInviteTest.NETBOUT_HEADER, Long.toString(bout.number()) ) ); } catch (final RsForward ex) { MatcherAssert.assertThat( ex.getLocalizedMessage(), Matchers.containsString( String.format("\"%s\" invited to the bout", name) ) ); throw ex; } }
Ports { public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } private Ports(); static int allocate(); static void release(final int port); }
@Test public void allocatesDifferentNumbersWithDifferentPorts() throws Exception { final int porta = Ports.allocate(); final int portb = Ports.allocate(); final int portc = Ports.allocate(); MatcherAssert.assertThat(porta, Matchers.not(portb)); MatcherAssert.assertThat(porta, Matchers.not(portc)); MatcherAssert.assertThat(portb, Matchers.not(portc)); } @Test public void allocatesDifferentNumbersWithSamePorts() throws Exception { final int porta = Ports.allocate(); final int portb = Ports.allocate(); final int portc = Ports.allocate(); MatcherAssert.assertThat(porta, Matchers.not(portb)); MatcherAssert.assertThat(porta, Matchers.not(portc)); MatcherAssert.assertThat(portb, Matchers.not(portc)); }
EmCatch { public void start() { final Thread monitor = new Thread( new Runnable() { @Override public void run() { EmCatch.this.mainLoop(); } } ); monitor.setDaemon(true); monitor.start(); } EmCatch(final Action act, final String usr, final String pass, final String hst, final int prt, final long prd); void start(); }
@Test public void readsInboxPeriodically() throws Exception { final GreenMail mail = new GreenMail( new ServerSetup(Ports.allocate(), null, "pop3") ); mail.start(); final ServerSetup setup = mail.getPop3().getServerSetup(); final String login = "to"; final String from = "[email protected]"; final String to = "[email protected]"; final String password = "soooosecret"; final String subject = GreenMailUtil.random(); final String body = GreenMailUtil.random(); final GreenMailUser user = mail.setUser(login, password); new EmCatch( new EmCatch.Action() { @Override public void run(final Message msg) { MatcherAssert.assertThat(msg, Matchers.notNullValue()); try { MatcherAssert.assertThat( msg.getSubject(), Matchers.equalTo(subject) ); MatcherAssert.assertThat( msg.getFrom()[0].toString(), Matchers.equalTo(from) ); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.equalTo(to) ); } catch (final MessagingException ex) { throw new IllegalStateException(ex); } } }, login, password, setup.getBindAddress(), setup.getPort(), 500L ).start(); final MimeMessage message = GreenMailUtil.createTextEmail( to, from, subject, body, setup ); user.deliver(message); MatcherAssert.assertThat( mail.getReceivedMessages().length, Matchers.equalTo(1) ); Thread.sleep(1000); Ports.release(setup.getPort()); mail.stop(); }
BoutInviteMail { public void send(final String email, final String urn, final Bout bout) throws IOException { this.postman.send( new Envelope.MIME() .with(new StRecipient(email)) .with( new StSubject( String.format( "#%d: %s", bout.number(), bout.title() ) ) ) .with( new EnHTML( Joiner.on('\n').join( new Markdown.Default().html( BoutInviteMail.MAIL_CONTENT ), "<br/>", String.format( Manifests.read("Netbout-Site") .concat("/b/%d?invite=%s"), bout.number(), encrypt(urn) ), "<p style=\"color:#C8C8C8;font-size:2px;\">", String.format("%d</p>", System.nanoTime()), new GmailViewAction(bout.number()).xml() ) ) ) ); } BoutInviteMail(final Postman pst); void send(final String email, final String urn, final Bout bout); }
@Test public void sendEmailWithInviteKey() throws Exception { final String content = "You are invited into the Netbout click on the link to"; final Postman postman = Mockito.mock(Postman.class); final BoutInviteMail mail = new BoutInviteMail(postman); final MkBase base = new MkBase(); final Alias alias = new EmAlias(base.randomAlias(), postman); final String email = "[email protected]"; final String urn = "urn:[email protected]:mesutozen36-gmail-com"; final Bout bout = alias.inbox().bout(alias.inbox().start()); mail.send(email, urn, bout); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Message msg = captor.getValue().unwrap(); MatcherAssert.assertThat(msg.getAllRecipients().length, Matchers.is(1)); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.equalTo(email) ); MatcherAssert.assertThat(msg.getSubject(), Matchers.startsWith("#1: ")); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); MimeMultipart.class.cast(msg.getContent()).writeTo(baos); MatcherAssert.assertThat( baos.toString(), Matchers.containsString(content) ); }
EmMessages implements Messages { @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } EmMessages(final Messages org, final Postman pst, final Bout bot, final String slf); @Override void post(final String text); @Override long unread(); @Override Pageable<Message> jump(final long num); @Override Iterable<Message> iterate(); @Override Iterable<Message> search(final String term); }
@Test(expected = RsFailure.class) public void throwsUserFriendlyExceptionOnFailure() throws Exception { final Postman postman = Mockito.mock(Postman.class); final MkBase base = new MkBase(); final Alias alias = new EmAlias(base.randomAlias(), postman); final Bout bout = alias.inbox().bout(alias.inbox().start()); bout.friends().invite(base.randomAlias().name()); Mockito.doThrow(new IOException()).when(postman) .send(Mockito.any(Envelope.class)); final EmMessages messages = new EmMessages( bout.messages(), postman, bout, alias.name() ); messages.post("how are you?"); } @Test public void canSendEmailWithReplyTo() throws Exception { final Postman postman = Mockito.mock(Postman.class); final MkBase base = new MkBase(); final Alias alias = new EmAlias(base.randomAlias(), postman); final Bout bout = alias.inbox().bout(alias.inbox().start()); bout.friends().invite(base.randomAlias().name()); bout.messages().post("reply-to header test"); final ArgumentCaptor<Envelope> argument = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman) .send(argument.capture()); final String[] reply = argument.getValue().unwrap().getReplyTo()[0].toString().split("@"); MatcherAssert.assertThat( String.format( "%s@%s", EmCatch.decrypt(reply[0]), reply[1] ), Matchers.equalTo( String.format( "%s|%[email protected]", alias.name(), bout.number() ) ) ); }
EmAlias implements Alias { @Override public String email() throws IOException { return this.origin.email(); } EmAlias(final Alias org, final Postman pst); @Override String name(); @Override URI photo(); @Override Locale locale(); @Override void photo(final URI uri); @Override String email(); @Override void email(final String email); @Override void email(final String email, final String urn, final Bout bout); @Override void email(final String email, final String link); @Override Inbox inbox(); }
@Test public void sendsConfirmationEmail() throws Exception { final Postman postman = Mockito.mock(Postman.class); final Alias alias = new EmAlias(new MkBase().randomAlias(), postman); alias.email("[email protected]", "netbout.com/test/verification/link"); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Message msg = captor.getValue().unwrap(); MatcherAssert.assertThat(msg.getFrom().length, Matchers.is(1)); MatcherAssert.assertThat( msg.getSubject(), Matchers.equalTo("Netbout email verification") ); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.containsString("mihai@test") ); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); MimeMultipart.class.cast(msg.getContent()).writeTo(baos); final String content = new String(baos.toByteArray(), "UTF-8"); MatcherAssert.assertThat( content, Matchers.containsString( "<p>Hi,<br />Your notification e-mail address" ) ); MatcherAssert.assertThat( content, Matchers.containsString( "<a href=\"netbout.com/test/verification/link\">here</a>" ) ); }
MkMessages implements Messages { @Override public void post(final String text) throws IOException { try { new JdbcSession(this.sql.source()) .sql("INSERT INTO message (bout, text, author) VALUES (?, ?, ?)") .set(this.bout) .set(text) .set(this.self) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } new TouchBout(this.sql, this.bout).act(); } MkMessages(final Sql src, final long bot, final String slf); @Override void post(final String text); @Override long unread(); @Override Pageable<Message> jump(final long number); @Override Iterable<Message> iterate(); @Override Iterable<Message> search(final String term); }
@Test public void changesUpdateAttribute() throws Exception { final Bout bout = new MkBase().randomBout(); final Messages messages = bout.messages(); final Long last = bout.updated().getTime(); messages.post("hi"); Thread.sleep(Tv.HUNDRED); MatcherAssert.assertThat( bout.updated().getTime(), Matchers.greaterThan(last) ); }
MkInbox implements Inbox { @Override public long start() throws IOException { try { final Long number = new JdbcSession(this.sql.source()) .sql("INSERT INTO bout (title) VALUES (?)") .set("untitled") .insert(new SingleOutcome<Long>(Long.class)); this.bout(number).friends().invite(this.self); return number; } catch (final SQLException ex) { throw new IOException(ex); } } MkInbox(final Sql src, final String name); @Override long start(); @Override long unread(); @Override Bout bout(final long number); @Override Pageable<Bout> jump(final long number); @Override Iterable<Bout> iterate(); @Override Iterable<Bout> search(final String term); }
@Test public final void testStart() throws IOException { final String name = "current-name"; final Sql sql = new H2Sql(); final Aliases aliases = new MkUser( sql, URN.create( String.format( "urn:test:%d", new SecureRandom().nextInt(Integer.MAX_VALUE) ) ) ).aliases(); aliases.add(name); final Alias alias = aliases.iterate().iterator().next(); alias.email(String.format("%[email protected]", alias.name())); final MkInbox inbox = new MkInbox(sql, name); final Bout bout = inbox.bout(inbox.start()); MatcherAssert.assertThat( bout.friends().iterate(), Matchers.hasItem(new Friend.HasAlias(Matchers.is(name))) ); }
MkAlias implements Alias { @Override public String email() throws IOException { try { return new JdbcSession(this.sql.source()) .sql("SELECT email FROM alias WHERE name = ?") .set(this.label) .select(new SingleOutcome<String>(String.class)); } catch (final SQLException ex) { throw new IOException(ex); } } MkAlias(final Sql src, final String name); @Override String name(); @Override URI photo(); @Override Locale locale(); @Override void photo(final URI uri); @Override String email(); @Override void email(final String email); @Override void email(final String email, final String urn, final Bout bout); @Override void email(final String email, final String link); @Override Inbox inbox(); }
@Test public void savesAndReadsEmail() throws Exception { final Alias alias = new MkBase().randomAlias(); MatcherAssert.assertThat(alias.email(), Matchers.notNullValue()); final String email = "[email protected]"; alias.email(email); MatcherAssert.assertThat(alias.email(), Matchers.equalTo(email)); }
MkBase implements Base { public Bout randomBout() throws IOException { final Inbox inbox = this.randomAlias().inbox(); final Bout bout = inbox.bout(inbox.start()); bout.rename( String.format( "random title %d", MkBase.RANDOM.nextInt(Integer.MAX_VALUE) ) ); return bout; } MkBase(); MkBase(final Sql src); @Override User user(final URN urn); @Override void close(); Alias randomAlias(); Bout randomBout(); }
@Test public void startsBoutAndTalks() throws Exception { final Messages messages = new MkBase().randomBout().messages(); messages.post("How are you doing?"); MatcherAssert.assertThat( messages.iterate(), Matchers.hasItem( new Message.HasText(Matchers.containsString("are you")) ) ); }
TouchBout { public void act() throws IOException { try { new JdbcSession(this.sql.source()) .sql("UPDATE bout SET updated = CURRENT_TIMESTAMP WHERE number = ?") .set(this.bout) .update(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } TouchBout(final Sql src, final long bot); void act(); }
@Test public void changesUpdateAttribute() throws Exception { final Sql sql = new H2Sql(); final Bout bout = new MkBase(sql).randomBout(); final Long last = bout.updated().getTime(); new TouchBout(sql, bout.number()).act(); Thread.sleep(Tv.HUNDRED); MatcherAssert.assertThat( bout.updated().getTime(), Matchers.greaterThan(last) ); }
MkFriends implements Friends { @Override public void invite(final String friend) throws IOException { try { final boolean exists = new JdbcSession(this.sql.source()) .sql("SELECT name FROM alias WHERE name = ?") .set(friend) .select(Outcome.NOT_EMPTY); if (!exists) { throw new Friends.UnknownAliasException( String.format("alias '%s' doesn't exist", friend) ); } new JdbcSession(this.sql.source()) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(true) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } MkFriends(final Sql src, final long bot); @Override void invite(final String friend); @Override void kick(final String friend); @Override Iterable<Friend> iterate(); }
@Test(expected = Friends.UnknownAliasException.class) public void inviteFailsOnUnknownAlias() throws Exception { new MkBase().randomBout().friends().invite("NoSuchFriend"); }
TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); @Override Response act(final Request req); }
@Test public void kicksAnUser() throws Exception { final String alias = "test"; final String urn = "urn:test:1"; final MkBase base = new MkBase(); final Bout bout = base.randomBout(); base.user(new URN(urn)).aliases().add(alias); bout.friends().invite(alias); MatcherAssert.assertThat( new RsPrint( new TkAuth( new TkApp(base), new PsFixed(new Identity.Simple(urn)) ).act( new RqFake( RqMethod.GET, String.format( "/b/%d/kick?name=%s", bout.number(), alias ) ) ) ).printHead(), Matchers.containsString("you+kicked") ); } @Test public void searchesBouts() throws Exception { final String urn = "urn:test:2"; final MkBase base = new MkBase(); final Aliases aliases = base.user(new URN(urn)).aliases(); aliases.add("test2"); final Inbox inbox = aliases.iterate().iterator().next().inbox(); final Bout first = inbox.bout(inbox.start()); final String firsttitle = "bout1 title"; first.rename(firsttitle); first.messages().post("hello"); final Bout second = inbox.bout(inbox.start()); final String secondtitle = "bout2 title"; second.rename(secondtitle); second.messages().post("message with term"); final String thirdtitle = "bout title with term"; inbox.bout(inbox.start()).rename(thirdtitle); final String body = new RsPrint( new TkAuth( new TkInbox(base), new PsFixed(new Identity.Simple(urn)) ).act( new RqFake( RqMethod.GET, String.format( "/search?q=%s", "term" ) ) ) ).printBody(); MatcherAssert.assertThat( body, Matchers.containsString(secondtitle) ); MatcherAssert.assertThat( body, Matchers.containsString(thirdtitle) ); MatcherAssert.assertThat( body, Matchers.not(Matchers.containsString(firsttitle)) ); } @Test public void handleInvalidSince() throws Exception { final String alias = "test3"; final String urn = "urn:test:3"; final MkBase base = new MkBase(); final Bout bout = base.randomBout(); base.user(new URN(urn)).aliases().add(alias); bout.friends().invite(alias); MatcherAssert.assertThat( new RsPrint( new TkAuth( new TkApp(base), new PsFixed(new Identity.Simple(urn)) ).act( new RqFake( RqMethod.GET, "/?since" ) ) ).printHead(), Matchers.containsString( "invalid+%27since%27+value%2C+timestamp+is+expected" ) ); } @Test public void handleValidSince() throws Exception { final String alias = "test4"; final String urn = "urn:test:4"; final MkBase base = new MkBase(); final Bout bout = base.randomBout(); base.user(new URN(urn)).aliases().add(alias); bout.friends().invite(alias); MatcherAssert.assertThat( new RsPrint( new TkAuth( new TkApp(base), new PsFixed(new Identity.Simple(urn)) ).act( new RqFake( RqMethod.GET, "/?since=123456789" ) ) ).printHead(), Matchers.startsWith( "HTTP/1.1 200 OK" ) ); }
Compiler { public void compile() throws IOException { assert this.properties != null; final long start = System.currentTimeMillis(); final Facet[] facets = { new XeFacet.Wrap(new Aggregate(new File(this.input))), new XeFacet.Wrap(new AntlrFacet()), new Transform("cleanup/duplicate-step-numbers.xsl"), new Transform("cleanup/duplicate-step-signatures.xsl"), new Transform("cleanup/duplicate-step-objects.xsl"), new Transform("cleanup/duplicate-step-results.xsl"), new Transform("cleanup/lost-steps.xsl"), new Transform("cleanup/lost-methods.xsl"), new Transform("cleanup/duplicate-signatures.xsl"), new Transform("cleanup/duplicate-method-signatures.xsl"), new Transform("cleanup/duplicate-method-objects.xsl"), new Transform("cleanup/duplicate-method-bindings.xsl"), new Transform("cleanup/incomplete-step-object.xsl"), new Transform("cleanup/incomplete-step-signature.xsl"), new Transform("cleanup/incomplete-step-result.xsl"), new Transform("cleanup/incomplete-binding.xsl"), new Transform("cleanup/bindings-in-exception.xsl"), new Transform("seal-methods.xsl"), new Transform("sanity/signatures-check.xsl"), new Transform("sanity/types-check.xsl"), new Transform("sanity/seals-check.xsl"), new Transform("sanity/exception-rethrow-check.xsl"), new Transform("sanity/misplaced-failure-check.xsl"), new Transform("sanity/broken-order-of-steps.xsl"), new Transform("sanity/missed-step-numbers.xsl"), new Transform("sanity/too-many-steps.xsl"), new Transform("sanity/empty-re-throws.xsl"), new Transform("sanity/orphan-types.xsl"), new Transform("sanity/undeclared-bindings.xsl"), new Transform("sanity/actor-is-singleton.xsl"), new Transform("step-refs.xsl"), new Transform("methods-in-markdown.xsl"), new Transform("pages-in-html.xsl"), new Transform("count-ambiguity.xsl"), new Transform("find-tbds.xsl"), new Transform("uml/sequence-diagrams.xsl"), new Transform("uml/use-case-diagrams.xsl"), new Transform("uml/class-diagrams.xsl"), new XeFacet.Wrap(new Rules()), new XeFacet.Wrap(new XeFacet.Fixed(Compiler.decor())), new Transform("renumber.xsl"), new XeFacet.Wrap( spec -> new Directives().xpath("/*").attr( "msec", Long.toString(System.currentTimeMillis() - start) ) ), }; XML spec = new XMLDocument( "<?xml-stylesheet href='requs.xsl' type='text/xsl'?><spec/>" ); for (final Facet facet : facets) { spec = facet.touch(spec); Logger.info(this, "%s done", facet); } this.copy(); FileUtils.write( new File(this.output, "requs.xml"), new StrictXML(spec, Compiler.SCHEMA).toString(), StandardCharsets.UTF_8 ); Logger.info(this, "compiled and saved to %s", this.output); } Compiler(final File src, final File dest); @SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors") Compiler(@NotNull final File src, @NotNull final File dest, @NotNull final Map<String, String> props); void compile(); static final XSD SCHEMA; }
@Test public void combinesMultipleFiles() throws Exception { final File input = this.temp.newFolder(); final File output = this.temp.newFolder(); FileUtils.write( new File(input, "b.req"), "\n\nUser is a \"good human being\".", StandardCharsets.UTF_8 ); FileUtils.write( new File(input, "a.req"), "\n\nUser is a \"human being\".", StandardCharsets.UTF_8 ); FileUtils.write( new File(input, "c.req"), "\n\n\nUser is a \"very good human being\". bug", StandardCharsets.UTF_8 ); new Compiler(input, output).compile(); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new XMLDocument(new File(output, "requs.xml"))), XhtmlMatchers.hasXPaths( "/spec/files/file[@id='0' and @line='1']", "/spec/files/file[@id='1' and @line='4']", "/spec/files/file[@id='2' and @line='7']", " " " "/spec/errors/error[@file='2' and @line='4']" ) ); }
XeMethod implements Method { @Override public void attribute(final String name, final String seal) { this.dirs.xpath(this.start) .strict(1) .addIf("attributes") .xpath( String.format( "%s/attributes[not(attribute=%s)]", this.start, XeOntology.escapeXPath(name) ) ) .add("attribute").set(name) .xpath( String.format( "%s/attributes/attribute[.=%s]", this.start, XeOntology.escapeXPath(name) ) ) .strict(1) .attr("seal", seal); } XeMethod(final Directives directives, final String xpath); @Override void attribute(final String name, final String seal); @Override Nfr nfr(final String name); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void input(final String name); @Override void explain(final String info); @Override void mention(final int where); }
@Test public void setsAttributes() throws Exception { final Directives dirs = new Directives().add("x"); final Method method = new XeMethod(dirs, "/x"); final String name = "attr-1"; method.attribute(name, ""); method.attribute(name, "ffa7ed"); method.attribute("another", "123456"); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/x/attributes[count(attribute)=2]", "/x/attributes[attribute='attr-1' and attribute='another']", "/x/attributes/attribute[.='attr-1' and @seal='ffa7ed']" ) ); }
XeOntology implements Ontology { @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } @Override Type type(final String name); @Override Method method(final String name); @Override Page page(final String name); @Override Acronym acronym(final String name); @Override Iterator<Directive> iterator(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String escapeXPath(final String text); }
@Test public void manipulatesWithTypesAndUseCases() throws Exception { final XeOntology onto = new XeOntology(); final Type type = onto.type("First"); type.explain("first text"); type.parent("Root"); type.slot("one").assign("Emp"); onto.type("Second").explain("second text"); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(onto).xml()), XhtmlMatchers.hasXPaths( "/spec", "/spec/types/type[name='First']", "/spec/types/type[name='Second']" ) ); } @Test public void avoidsDuplication() throws Exception { final XeOntology onto = new XeOntology(); final String name = "Alpha"; onto.type(name); onto.type(name); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(onto).xml()), XhtmlMatchers.hasXPath("/spec/types[count(type)=1]") ); }
XeOntology implements Ontology { @Override public Method method(final String name) { this.root("methods") .xpath( String.format( "/spec/methods[not(method/id=%s)]", XeOntology.escapeXPath(name) ) ) .add("method").add("id").set(name); return new XeMethod( this.dirs, String.format( "/spec/methods/method[id=%s]", XeOntology.escapeXPath(name) ) ); } @Override Type type(final String name); @Override Method method(final String name); @Override Page page(final String name); @Override Acronym acronym(final String name); @Override Iterator<Directive> iterator(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String escapeXPath(final String text); }
@Test public void avoidsDuplicationOfMethods() throws Exception { final XeOntology onto = new XeOntology(); final String name = "UC3"; onto.method(name); onto.method(name); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(onto).xml()), XhtmlMatchers.hasXPath("/spec/methods[count(method)=1]") ); }
XeFlow implements Flow { @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } XeFlow(final Directives directives, final String xpath); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void explain(final String info); }
@Test public void manipulatesWithBindings() throws Exception { final Directives dirs = new Directives().add("f"); final Flow flow = new XeFlow(dirs, "/f"); flow.binding("emp", "Employee"); flow.binding("one", "One"); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/f/bindings/binding[name='emp' and type='Employee']", "/f/bindings/binding[name='one' and type='One']" ) ); } @Test public void avoidsDuplicateBindings() throws Exception { final Directives dirs = new Directives().add("f1"); final Flow flow = new XeFlow(dirs, "/f1"); for (int idx = 0; idx < Tv.FIVE; ++idx) { flow.binding("a", "alpha"); } MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/f1/bindings[count(binding)=1]", "/f1/bindings/binding[name='a' and type='alpha']" ) ); }
Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } Transform(final String xsl); @Override XML touch(final XML spec); }
@Test public void checksSeals() { MatcherAssert.assertThat( XhtmlMatchers.xhtml( new Transform("sanity/seals-check.xsl").touch( new XMLDocument( StringUtils.join( "<spec><method seal='a12ef4'>", "<id>UC5</id><attributes>", "<attribute seal='b89e4e'>invalid</attribute>", "<attribute seal='a12ef4'>valid</attribute>", "</attributes></method><errors/></spec>" ) ) ) ), XhtmlMatchers.hasXPaths( "/spec/errors[count(error)=1]", "/spec/errors/error[contains(.,'a12ef4')]" ) ); } @Test public void checksTypes() { MatcherAssert.assertThat( XhtmlMatchers.xhtml( new Transform("sanity/types-check.xsl").touch( new XMLDocument( StringUtils.join( "<spec><types><type><name>User</name>", "<slots><slot><type>Alpha</type></slot></slots>", "</type></types><methods><method><bindings>", "<binding><type>Beta</type></binding>", "</bindings></method></methods><errors/></spec>" ) ) ) ), XhtmlMatchers.hasXPaths( "/spec/errors[count(error)=2]", "/spec/errors/error[contains(.,'Alpha')]" ) ); } @Test public void checksSignatures() { MatcherAssert.assertThat( XhtmlMatchers.xhtml( new Transform("sanity/signatures-check.xsl").touch( new XMLDocument( StringUtils.join( "<spec><methods><method><signature>abc</signature>", "</method><method><steps><step><signature>cde", "</signature></step></steps></method></methods>", "<errors/></spec>" ) ) ) ), XhtmlMatchers.hasXPaths( "/spec/errors[count(error)=1 ]", "/spec/errors/error[contains(.,'cde')]" ) ); }
Plant { @SuppressWarnings("PMD.ProhibitPublicStaticMethods") public static String svg(final String src) throws IOException { final String svg; if (SystemUtils.IS_OS_WINDOWS) { svg = "<p>SVG can't be rendered in Windows</p>"; } else { final SourceStringReader reader = new SourceStringReader(src); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); reader.generateImage(baos, new FileFormatOption(FileFormat.SVG)); svg = new XMLDocument( new String(baos.toByteArray()) ).nodes("/*").get(0).toString().replace("xmlns=\"\"", ""); } return svg; } private Plant(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String svg(final String src); }
@Test public void buildsSvg() throws IOException { Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS); MatcherAssert.assertThat( XhtmlMatchers.xhtml( Plant.svg("@startuml\nBob -> Alice : hello\n@enduml\n") ), XhtmlMatchers.hasXPath(" ); }
CascadingRule implements Rule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> enforce(final String text); }
@Test public void checksInput() throws Exception { MatcherAssert.assertThat( new CascadingRule().enforce("hey\n works\n fine\nstart"), Matchers.empty() ); } @Test public void checksInvalidInput() throws Exception { MatcherAssert.assertThat( new CascadingRule().enforce( "\n\n\n hey\n three!" ).iterator().next().line(), Matchers.equalTo(Tv.FIVE) ); }
Main { private Main() { } private Main(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static void main(final String... args); }
@Test public void displaysVersionNumber() throws Exception { Main.main(new String[]{"-v"}); MatcherAssert.assertThat( this.out.toString(), Matchers.containsString("-SNAPSHOT") ); } @Test public void rendersHelpMessage() throws Exception { Main.main(new String[] {"-h"}); MatcherAssert.assertThat( this.out.toString(), Matchers.containsString("Usage:") ); } @Test public void compilesRequsSources() throws Exception { final File input = this.temp.newFolder(); final File output = this.temp.newFolder(); FileUtils.write( new File(input, "employee.req"), "Employee is a \"user of the system\".", StandardCharsets.UTF_8 ); Main.main( new String[] { "-i", input.getAbsolutePath(), "-o", output.getAbsolutePath(), } ); MatcherAssert.assertThat( this.out.toString(), Matchers.containsString("compiled and saved to") ); MatcherAssert.assertThat( XhtmlMatchers.xhtml( FileUtils.readFileToString( new File(output, "requs.xml"), StandardCharsets.UTF_8 ) ), XhtmlMatchers.hasXPaths("/spec/types/type[name='Employee']") ); }
InstantRs extends BaseRs { @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") public String post(@NotNull @FormParam("text") final String text) throws IOException { final File input = Files.createTempDir(); FileUtils.write( new File(input, "in.req"), text, StandardCharsets.UTF_8 ); final File output = Files.createTempDir(); try { new org.requs.Compiler(input, output).compile(); final XML xml = new XMLDocument( FileUtils.readFileToString( new File(output, "requs.xml"), StandardCharsets.UTF_8 ) ); final XSL xsl = new XSLDocument( FileUtils.readFileToString( new File(output, "requs.xsl"), StandardCharsets.UTF_8 ) ); return Json.createObjectBuilder() .add("spec", xml.nodes("/spec").get(0).toString()) .add("html", xsl.applyTo(xml)) .build().toString(); } catch (final RuntimeException ex) { throw new WebApplicationException( Response.status(HttpURLConnection.HTTP_INTERNAL_ERROR) .entity(ExceptionUtils.getStackTrace(ex)) .build() ); } finally { FileUtils.deleteDirectory(input); FileUtils.deleteDirectory(output); } } @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") String post(@NotNull @FormParam("text") final String text); }
@Test public void processesRequsSpec() throws Exception { final InstantRs res = new InstantRs(); res.setUriInfo(new UriInfoMocker().mock()); res.setHttpHeaders(new HttpHeadersMocker().mock()); final SecurityContext sec = Mockito.mock(SecurityContext.class); res.setSecurityContext(sec); final String json = res.post("User is a \"type\"."); MatcherAssert.assertThat( Json.createReader(new StringReader(json)) .readObject().getString("spec"), XhtmlMatchers.hasXPath("/spec/types/type[name='User']") ); }
IndexRs extends BaseRs { @GET @Path("/") public Response index() throws Exception { return new PageBuilder() .stylesheet("/xsl/index.xsl") .build(DemoPage.class) .init(this) .render() .build(); } @GET @Path("/") Response index(); }
@Test public void rendersFrontPage() throws Exception { final IndexRs res = new IndexRs(); res.setUriInfo(new UriInfoMocker().mock()); res.setHttpHeaders(new HttpHeadersMocker().mock()); final SecurityContext sec = Mockito.mock(SecurityContext.class); res.setSecurityContext(sec); final Response response = res.index(); MatcherAssert.assertThat( JaxbConverter.the(response.getEntity()), XhtmlMatchers.hasXPaths( "/page/millis", "/page/version/name" ) ); }
Rules implements XeFacet { @Override public Iterable<Directive> touch(final XML spec) { final Rule[] rules = { new LineRule.Wrap( new RegexRule( "[^ ] +$", "trailing space(s) at the end of line" ) ), new LineRule.Wrap( new RegexRule( "[^ ] {2,}", "avoid two or more consecutive spaces" ) ), new LineRule.Wrap( new RegexRule( ".{81,}", "avoid lines longer than 80 characters" ) ), new LineRule.Wrap( new RegexRule( "\t", "avoid TAB characters, use four spaces instead" ) ), new LineRule.Wrap( new RegexRule( "\r", "don't use Windows line-endings" ) ), new LineRule.Wrap( new RegexRule( ",[^$ \n\r]", "always use space after comma" ) ), new LineRule.Wrap( new RegexRule( ";[^$ ]", "always use space after semicolon" ) ), new LineRule.Wrap(new IndentationRule()), new CascadingRule(), }; final String input; if (spec.nodes("/spec/input[.!='']").isEmpty()) { input = ""; } else { input = spec.xpath("/spec/input/text()").get(0); } final Directives dirs = new Directives().xpath("/spec").addIf("errors"); for (final Rule rule : rules) { for (final Violation violation : rule.enforce(input)) { dirs.add("error") .attr("pos", Integer.toString(violation.position())) .attr("line", Integer.toString(violation.line())) .set(violation.details()).up(); } } return dirs; } @Override Iterable<Directive> touch(final XML spec); }
@Test public void checksInput() throws IOException { MatcherAssert.assertThat( new XeFacet.Wrap(new Rules()).touch( new XMLDocument( StringUtils.join( "<spec><input>", "User is\ta &quot;human being&quot;. ", "</input></spec>" ) ) ), XhtmlMatchers.hasXPaths( "/spec/errors", "/spec/errors[count(error)>2]" ) ); }
IndentationRule implements LineRule { @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } @Override Collection<Violation> check(final String line); }
@Test public void checksInput() throws Exception { MatcherAssert.assertThat( new IndentationRule().check(" works fine"), Matchers.empty() ); } @Test public void checksInvalidInput() throws Exception { MatcherAssert.assertThat( new IndentationRule().check(" works fine"), Matchers.not(Matchers.empty()) ); }
RegexRule implements LineRule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } RegexRule(final String rgx, final String txt); @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> check(final String line); }
@Test public void checksInput() throws Exception { MatcherAssert.assertThat( new RegexRule("[a-z]+", "").check("abjkljeklsf"), Matchers.not(Matchers.empty()) ); } @Test public void checksInvalidInput() throws Exception { MatcherAssert.assertThat( new RegexRule("[0-9]", "").check("broken input"), Matchers.empty() ); }
XeSignature implements Signature { @Override public void sign(final String text) { this.dirs.xpath(this.start).strict(1) .add("signature").set(text); } XeSignature(final Directives directives, final String xpath); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override void input(final String name); @Override void explain(final String info); }
@Test public void signsMethod() throws Exception { final Directives dirs = new Directives().add("s"); final Signature signature = new XeSignature(dirs, "/s"); signature.sign("\"informal one\""); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/s[signature='\"informal one\"']" ) ); }
XeMethod implements Method { @Override public Step step(final int number) { return this.flow.step(number); } XeMethod(final Directives directives, final String xpath); @Override void attribute(final String name, final String seal); @Override Nfr nfr(final String name); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void input(final String name); @Override void explain(final String info); @Override void mention(final int where); }
@Test public void avoidsDuplicateSteps() throws Exception { final Directives dirs = new Directives().add("mtd"); final Method method = new XeMethod(dirs, "/mtd"); method.step(1); method.step(1); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPath("/mtd/steps[count(step)=1]") ); }
ParametricState { public ParametricState(State state) { Position[] stateMemberPositionArray = state.getMemberPositions(); int memberPositionCount = stateMemberPositionArray.length; memberPositionBoundaryOffsetArray = new int[memberPositionCount]; memberPositionEArray = new int[memberPositionCount]; memberPositionTArray = new boolean[memberPositionCount]; for(int i = 0; i < memberPositionCount; i++) { memberPositionBoundaryOffsetArray[i] = stateMemberPositionArray[i].getI() - stateMemberPositionArray[0].getI(); memberPositionEArray[i] = stateMemberPositionArray[i].getE(); memberPositionTArray[i] = stateMemberPositionArray[i].getT(); } } ParametricState(State state); ParametricState(State state, int transitionBoundaryOffset); int getLargestPositionOffset(); int getTransitionBoundaryOffset(); State createActualState(int minimalBoundary); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }
@Test(dataProvider = "parametricStateTestDP") public void parametricStateTest(int originalBase, State s) { ParametricState ts = new ParametricState(s); State s1 = ts.createActualState(originalBase); assert Arrays.equals(s.getMemberPositions(), s1.getMemberPositions()); }
Position implements Comparable<Position> { public State transitionInternal(int maxEditDistance, int relevantSubwordSize, int hitIndex) { Position.EditDistanceRelationType edRelationType = (E < maxEditDistance ? (E == 0 ? Position.EditDistanceRelationType.AT_ZERO_AND_NOT_AT_MAX : Position.EditDistanceRelationType.NOT_AT_ZERO_AND_NOT_AT_MAX) : Position.EditDistanceRelationType.AT_MAX); Position.StateRelevantSubwordSizeType stateRSSizeType = (relevantSubwordSize >= 2 ? Position.StateRelevantSubwordSizeType.ATLEAST_TWO : (relevantSubwordSize == 1 ? Position.StateRelevantSubwordSizeType.ONE : Position.StateRelevantSubwordSizeType.ZERO)); Position.PositionType pType = (T ? Position.PositionType.TRANSPOSITION_POSITION : Position.PositionType.STANDARD_POSITION); Position.RelevantSubwordHitIndexType rsHitIndexType; switch(hitIndex) { case -1: rsHitIndexType = Position.RelevantSubwordHitIndexType.NO_INDEX; break; case 0: rsHitIndexType = Position.RelevantSubwordHitIndexType.FIRST_INDEX; break; case 1: rsHitIndexType = Position.RelevantSubwordHitIndexType.SECOND_INDEX; break; default: rsHitIndexType = Position.RelevantSubwordHitIndexType.TRAILING_INDEX; break; } Position.ElementaryTransitionTerm[] elementaryTransition = procureTransition(edRelationType, stateRSSizeType, pType, rsHitIndexType); HashSet<Position> possibleNewPositionHashSet = new HashSet<Position>(); for(Position.ElementaryTransitionTerm currentTerm : elementaryTransition) { Position transitionPosition = currentTerm.execute(this, hitIndex); if(transitionPosition != null) possibleNewPositionHashSet.add(transitionPosition); } if(!possibleNewPositionHashSet.isEmpty()) { Position[] positionArray = possibleNewPositionHashSet.toArray(new Position[possibleNewPositionHashSet.size()]); Arrays.sort(positionArray); return new State(positionArray); } else return null; } Position(int I, int E, boolean T); int getI(); int getE(); boolean getT(); Position.ElementaryTransitionTerm[] procureTransition(Position.EditDistanceRelationType edRelationType, Position.StateRelevantSubwordSizeType sRSSizeType, Position.PositionType pType, Position.RelevantSubwordHitIndexType rsHitIndexType); State transitionInternal(int maxEditDistance, int relevantSubwordSize, int hitIndex); int[] procurePositionTransitionData(int maxEditDistance, int relevantSubwordStartIndex, AugBitSet parentStateRelevantSubwordCharacteristicVector); State transition(int maxEditDistance, int parentStateRelevantSubwordLocationIndex, AugBitSet parentStateRelevantSubwordCharacteristicVector); boolean subsumes(Position p, int maxEditDistance); @Override int compareTo(Position p2); boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }
@Test(dataProvider = "transitionInternalTestDp") public void transitionInternalTest(Position p) { int mdStartIndex = p.getE() + (!p.getT() ? 2 : 1); for(int mdi = mdStartIndex; mdi >= p.getE(); mdi--) { for(int rsi = 0; rsi <= 2; rsi++) { for(int hii = -1; hii <= 4; hii++) { int currentE = (mdi == p.getE() + 2 ? 0 : p.getE()); boolean currentT = (rsi < 2 ? false : p.getT()); Position currentPosition = new Position(p.getI(),currentE, currentT); State s = currentPosition.transitionInternal(mdi, rsi, hii); if(currentE == 0 && currentE < mdi) { switch(rsi) { case 0: insertionTransitionAssertion(currentPosition, s); break; case 1: { switch(hii) { case 0: matchTransitionAssertion(currentPosition, s); break; default: defaultTransitionAssertion(currentPosition, s); break; } break; } default: { switch(hii) { case -1: defaultTransitionAssertion(currentPosition, s); break; case 0: matchTransitionAssertion(currentPosition, s); break; case 1: preTranspositionTransitionAssertion(currentPosition, s, hii); break; default: deletionTransitionAssertion(currentPosition, s, hii); break; } break; } } } else if(currentE > 0 && currentE < mdi) { switch(rsi) { case 0: insertionTransitionAssertion(currentPosition, s); break; case 1: { switch(hii) { case 0: matchTransitionAssertion(currentPosition, s); break; default: defaultTransitionAssertion(currentPosition, s); break; } break; } default: { if(!currentT) { switch(hii) { case -1: defaultTransitionAssertion(currentPosition, s); break; case 0: matchTransitionAssertion(currentPosition, s); break; case 1: preTranspositionTransitionAssertion(currentPosition, s, hii); break; default: deletionTransitionAssertion(currentPosition, s, hii); break; } break; } else { switch(hii) { case 0: transpositionTransitionAssertion(currentPosition, s); break; default: assert s == null; break; } } } } } else { switch(rsi) { case 0: assert (s == null); break; default: { if(!currentPosition.getT()) { switch(hii) { case 0: matchTransitionAssertion(currentPosition, s); break; default: assert (s == null); break; } break; } else { switch(hii) { case 0: transpositionTransitionAssertion(currentPosition, s); break; default: assert (s == null); break; } break; } } } } } } } }
ADistribution implements IDistribution<SPACE> { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } ADistribution(); @Override List<SPACE> generateSamples(int numberOfSamples); abstract CONFIG createDefaultDistributionConfiguration(); @Override ADistributionConfiguration getDefaultDistributionConfiguration(); @Override @SuppressWarnings("unchecked") void setDistributionConfiguration(ADistributionConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getDistributionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override String toString(); }
@Test @Override public void testWrongParameters() throws JsonParsingFailedException { List<Pair<String, JsonObject>> listOfPairsOfStringAndJsonObjects = getWrongParameters(); for (int i = 0; i < listOfPairsOfStringAndJsonObjects.size(); i++) { IDistribution<SPACE> distribution = getDistribution(); try { distribution.setParameters(listOfPairsOfStringAndJsonObjects.get(i).getSecond()); fail(String.format(ERROR_INCORRECT_PARAMETER_ACCEPTED, listOfPairsOfStringAndJsonObjects.get(i).getSecond())); } catch (ParameterValidationFailedException e) { Assert.assertEquals(ERROR_WRONG_OUTPUT, listOfPairsOfStringAndJsonObjects.get(i).getFirst(), e.getMessage()); } } } @Test @Override public void testCorrectParameters() throws JsonParsingFailedException { List<JsonObject> listOfJsonObjects = getCorrectParameters(); for (int i = 0; i < listOfJsonObjects.size(); i++) { IDistribution<SPACE> distribution = getDistribution(); try { distribution.setParameters(listOfJsonObjects.get(i)); } catch (ParameterValidationFailedException e) { fail(String.format(ERROR_CORRECT_PARAMETER_NOT_ACCEPTED, listOfJsonObjects.get(i))); } } }
AEvaluation implements IEvaluation { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } AEvaluation(ELearningProblem eLearningProblem); @Override void evaluate(); @Override EvaluationResult runEvaluationForOneSetOfEvaluationSettings(Pair<Integer, List<EvaluationSetting>> evaluationSettingsForOneSet); abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting); static EvaluationResult createCombinedEvaluationResultForOneSet(List<EvaluationResult> evaluationResultsForOneSet); List<EvaluationResult> getEvaluationResult(); @Override JsonObject getMetricParameterJsonObject(String metricIdentifier); boolean checkValidtiyOfEvalautionResult(); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms, List<IMetric<?, ?>> metrics); @Override int setupSingleEvaluationDatasetAndAlgorithm(int setNumber, DatasetFile datasetFile, ILearningAlgorithm learningAlgorithm, List<IMetric<?, ?>> metrics); @Override String interpretEvaluationResult(); @SuppressWarnings("unchecked") @Override AEvaluationConfiguration getEvaluationConfiguration(); @Override AEvaluationConfiguration getDefaultEvalutionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override @SuppressWarnings("unchecked") void setEvaluationConfiguration(AEvaluationConfiguration evaluationConfiguration); @Override int hashCode(); @Override boolean equals(Object secondObject); }
@Override @Test public void testCorrectParameters() throws JsonParsingFailedException { List<JsonObject> testPairs = getCorrectParameters(); for (int i = 0; i < testPairs.size(); i++) { IEvaluation evaluation = getEvaluation(); JsonObject object = testPairs.get(i); try { evaluation.setParameters(object); } catch (ParameterValidationFailedException e) { fail(String.format(ERROR_CORRECT_PARAMETER_NOT_ACCEPTED, object.toString())); } } } @Override @Test public void testWrongParameters() throws JsonParsingFailedException { List<Pair<String, JsonObject>> testPairs = getWrongParameters(); for (int i = 0; i < testPairs.size(); i++) { IEvaluation evaluation = getEvaluation(); JsonObject object = testPairs.get(i).getSecond(); try { evaluation.setParameters(object); fail(String.format(ERROR_INCORRECT_PARAMETER_ACCEPTED, testPairs.get(i).getSecond().toString())); } catch (ParameterValidationFailedException exception) { Assert.assertEquals(ERROR_WRONG_OUTPUT, exception.getMessage(), testPairs.get(i).getFirst()); } } }
AEvaluation implements IEvaluation { public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; AEvaluation(ELearningProblem eLearningProblem); @Override void evaluate(); @Override EvaluationResult runEvaluationForOneSetOfEvaluationSettings(Pair<Integer, List<EvaluationSetting>> evaluationSettingsForOneSet); abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting); static EvaluationResult createCombinedEvaluationResultForOneSet(List<EvaluationResult> evaluationResultsForOneSet); List<EvaluationResult> getEvaluationResult(); @Override JsonObject getMetricParameterJsonObject(String metricIdentifier); boolean checkValidtiyOfEvalautionResult(); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms, List<IMetric<?, ?>> metrics); @Override int setupSingleEvaluationDatasetAndAlgorithm(int setNumber, DatasetFile datasetFile, ILearningAlgorithm learningAlgorithm, List<IMetric<?, ?>> metrics); @Override String interpretEvaluationResult(); @SuppressWarnings("unchecked") @Override AEvaluationConfiguration getEvaluationConfiguration(); @Override AEvaluationConfiguration getDefaultEvalutionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override @SuppressWarnings("unchecked") void setEvaluationConfiguration(AEvaluationConfiguration evaluationConfiguration); @Override int hashCode(); @Override boolean equals(Object secondObject); }
@Test public void testCorrectEvaluationSettings() { evaluation = (AEvaluation<?>) getEvaluation(); List<Pair<EvaluationSetting, EvaluationResult>> testPairs = getCorrectListOfEvaluationSettings(); for (int i = 0; i < testPairs.size(); i++) { EvaluationSetting evaluationSetting = testPairs.get(i).getFirst(); try { EvaluationResult evaluatedEvaluationResult = evaluation.evaluateSingleCombination(evaluationSetting); EvaluationResult expectedEvaluationResult = testPairs.get(i).getSecond(); String expectedResult = expectedEvaluationResult.getExtraEvaluationInformation(); String evaluatedResult = evaluatedEvaluationResult.getExtraEvaluationInformation(); Assert.assertEquals(String.format(ASSERT_EVALUATION_RESULT_EQUAL, expectedResult, evaluatedResult), expectedResult, evaluatedResult); for (int k = 0; k < expectedEvaluationResult.getEvaluationMetrics().size(); k++) { IMetric<?, ?> metric = expectedEvaluationResult.getEvaluationMetrics().get(k); Object expectedLoss = expectedEvaluationResult.getLossForMetric(metric); Object evaluatedLoss = evaluatedEvaluationResult.getLossForMetric(metric); if (expectedLoss instanceof Double) { String[] split = evaluationSetting.getDataset().getDatasetFile().toString().split("/"); String fileName = split[split.length - 1]; logger.debug(String.format(DEBUG_MESSAGE_EVALUATION_RESULT, fileName, metric.toString(), expectedLoss, evaluatedLoss)); String assertMessage = String.format(ASSERT_EVALUATION_LOSS_EQUAL, metric.toString(), expectedEvaluationResult.getLearningAlgorithm().toString()); Assert.assertEquals(assertMessage, (Double) expectedLoss, (Double) evaluatedLoss, ERROR_MARGIN); } else { Assert.assertEquals(String.format(ASSERT_EVALUATION_LOSS_EQUAL, metric.toString(), expectedEvaluationResult.getLearningAlgorithm().toString()), expectedLoss, evaluatedLoss); } } } catch (LossException | PredictionFailedException exception) { fail(String.format(ERROR_CORRECT_EVALUATION_RESULT_NOT_ACHIEVED_FOR_CORRECT_SETTING, testPairs.get(i).getSecond().toString(), evaluationSetting.toString())); } } } @Test public void testWrongEvaluationSettings() { List<Pair<EvaluationSetting, EvaluationResult>> testPairs = getWrongListOfEvaluationSettings(); AEvaluation<?> evaluation = (AEvaluation<?>) getEvaluation(); for (int i = 0; i < testPairs.size(); i++) { try { EvaluationSetting evaluationSetting = testPairs.get(i).getFirst(); EvaluationResult evaluatedEvaluationResult = evaluation.evaluateSingleCombination(evaluationSetting); EvaluationResult expectedEvaluationResult = testPairs.get(i).getSecond(); String expectedResult = expectedEvaluationResult.getExtraEvaluationInformation(); String evaluatedResult = evaluatedEvaluationResult.getExtraEvaluationInformation(); Assert.assertNotEquals(String.format(ASSERT_CORRECT_EVALUATION_RESULT_ACHIEVED_FOR_INCORRECT_SETTING, expectedResult, evaluationSetting.toString()), evaluatedResult, expectedResult); for (IMetric<?, ?> evaluationMetric : expectedEvaluationResult.getEvaluationMetrics()) { Object expectedLoss = expectedEvaluationResult.getLossForMetric(evaluationMetric); Object evaluatedLoss = evaluatedEvaluationResult.getLossForMetric(evaluationMetric); if (evaluatedLoss.getClass() == Double.class) { expectedLoss = (double) expectedLoss; evaluatedLoss = (double) evaluatedLoss; boolean compare = TestUtils.areDoublesEqual((double) expectedLoss, (double) evaluatedLoss, ERROR_MARGIN); Assert.assertFalse(String.format(ASSERT_CORRECT_LOSS_ACHIEVED_FOR_INCORRECT_SETTING, expectedLoss, evaluatedLoss), compare); } else { Assert.assertNotEquals(String.format(ASSERT_CORRECT_LOSS_ACHIEVED_FOR_INCORRECT_SETTING, expectedLoss, evaluatedLoss), expectedLoss, evaluatedLoss); } } } catch (LossException | PredictionFailedException exception) { Assert.fail(String.format(ERROR_EXCEPTION_NOT_OCCURR_ERROR_MESSAGE, testPairs.get(i).getFirst().getMetrics())); } } }
EvaluateAlgorithmsCommand extends ACommand { @Override public String getFailureReason() { return failureReason; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); }
@Test public void testEvaluateAlgorithmsCommandWithCommandLineCompleteInput() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String correctResult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_COMMAND_POSITIVE_TEST), EEvaluation.SUPPLIED_TEST_SET_RANK_AGGREGATION.getEvaluationIdentifier(), ELearningProblem.RANK_AGGREGATION.getLearningProblemIdentifier()); runSystemConfigCommandWithFile(getTestRessourcePathFor(SYSTEM_CONFIG_JSON_FILE)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier(), String.format(EVALUATE_ALGORITHM_IDENTIFIER_COMMAND_LINE, EvaluationsKeyValuePairs.EVALUATION_SUPPLIED_TEST_SET_IDENTIFIER), String.format(METRICS_IDENTIFIER_COMMAND_LINE, EMetric.KENDALLS_TAU.getMetricIdentifier(), EMetric.SPEARMANS_RANK_CORRELATION.getMetricIdentifier()) }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(commandResult.isExecutedSuccessfully()); assertTrue(command.getFailureReason().isEmpty()); assertTrue(commandResult.getException() instanceof NullException); assertTrue(commandResult.getResult().toString().equals(correctResult)); } @Test public void testEvaluateAlgorithmsCommandWithSystemConfigCompleteInput() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String correctResult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_COMMAND_POSITIVE_TEST), EEvaluation.SUPPLIED_TEST_SET_RANK_AGGREGATION.getEvaluationIdentifier(), ELearningProblem.RANK_AGGREGATION.getLearningProblemIdentifier()); runSystemConfigCommandWithFile(getTestRessourcePathFor(SYSTEM_CONFIG_JSON_FILE)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(commandResult.isExecutedSuccessfully()); assertTrue(command.getFailureReason().isEmpty()); assertTrue(commandResult.getException() instanceof NullException); assertTrue(commandResult.getResult().toString().equals(correctResult)); }
EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); }
@Test public void testEvaluateAlgorithmsCommandWithSystemConfigNullEvalaution() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String inCorrectresult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_CANNOT_CREATE_EVALUATION_FOR_LEARNING_PROBLEM), EEvaluation.CROSS_VALIDATION_DATASET_RANK_AGGREGATION.getEvaluationIdentifier(), ELearningProblem.RANK_AGGREGATION.getLearningProblemIdentifier()); runSystemConfigCommandWithFileWithoutTrainingModels(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_NULL_EVALUATION)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, CannotCreateEvaluationForLearningProblemException.class); assertTrue(commandResult.getException().getMessage().equals(inCorrectresult)); } @Test public void testEvaluateAlgorithmsCommandWithSystemConfigWrongParameters() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String inCorrectresult = String.format( TestUtils.getStringByReflection(AEvaluationConfiguration.class, REFLECTION_VALIDATION_EVALUATION_METRIC), RANK_AGGREGATION_EVALUATION_WRONG_VALUE); runSystemConfigCommandWithFile(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_WRONG_PARAMETERS)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, ParameterValidationFailedException.class); assertTrue(commandResult.getException().getMessage().contains(inCorrectresult)); } @Test public void testEvaluateAlgorithmsCommandWithSystemConfigWrongParametersForMetrics() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String invalidValue = TestUtils.getStringByReflection(FMeasureConfiguration.class, REFLECTION_TYPE_VALUE_INVALID); runSystemConfigCommandWithFileWithoutTrainingModels(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_WRONG_PARAMETERS_FORMETRICS)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, ParameterValidationFailedException.class); assertTrue(commandResult.getException().getMessage().contains(invalidValue)); } @Test public void testEvaluateAlgorithmsCommandWithSystemConfigWithUnknownEvaluationIdentifier() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String inCorrectresult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_EVALUATION_IDENTIFIER_UNKNOWN_ERROR_MESSAGE), INCORRECT_EVALUATION_IDENTIFIER); runSystemConfigCommandWithFile(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_UNKNOWN_EVALUATION_IDENTIFIER)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, UnknownEvaluationIdentifierException.class); assertTrue(commandResult.getException().getMessage().equals(inCorrectresult)); } @Test public void testEvaluateAlgorithmsCommandWithSystemConfigHaveNoEvaluation() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String inCorrectresult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_EVALUATION_FOR_LEARNINGPROBLEM_NOT_EXIST_ERROR_MESSAGE), EvaluationsKeyValuePairs.EVALUATION_PERCENTAGE_SPLIT_IDENTIFIER, ELearningProblem.RANK_AGGREGATION.getLearningProblemIdentifier()); runSystemConfigCommandWithFileWithoutTrainingModels(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_NO_EVALUATION)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, EvaluationDoesnotExistForLearningProblemException.class); assertTrue(commandResult.getException().getMessage().equals(inCorrectresult)); } @Test public void testEvaluateAlgorithmsCommandWithSystemConfigWithNoAlgorithmsSet() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { runSystemConfigCommandWithFileWithoutLoadingAlgorithms(getTestRessourcePathFor(SYSTEM_CONFIG_JSON_FILE)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, DatasetsOrLearningAlgorithmsNotSetForEvaluationException.class); String inCorrectresult = String.format( StringUtils.LINE_BREAK + TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_LEARNING_ALGORITHMS_ERROR_MESSAGE), EEvaluation.SUPPLIED_TEST_SET_RANK_AGGREGATION.getEvaluationIdentifier()); assertTrue(commandResult.getException().getMessage().equals(inCorrectresult)); } @Test public void testEvaluateAlgorithmsCommandWithSystemConfigWithNoSetupForEvaluation() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { runSystemConfigCommandWithFileWithoutTrainingModels(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_SETUP_PROBLEM_IN_EVALUATION)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, CouldNotSetupEvaluationException.class); String inCorrectresult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_COULDNOT_SETUP_EVALUATION_ERROR_MESSAGE), EvaluationsKeyValuePairs.EVALUATION_USE_TRAINING_DATASET_IDENTIFIER); assertTrue(commandResult.getException().getMessage().equals(inCorrectresult)); }
RunCompleteToolChainCommand extends ACommand { public RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration) { super(ECommand.RUN_COMPLETE_TOOLCHAIN.getCommandIdentifier()); this.commandConfiguration = commandConfiguration; toolChainCommands = new ArrayList<>(); commandExecutionSuccessPairs = new ArrayList<>(); inputControl = InputControl.getInputControl(); systemStatus = SystemStatus.getSystemStatus(); } RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); }
@Test public void testRunCompleteToolChainCommand() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String command[] = { ECommand.RUN_COMPLETE_TOOLCHAIN.getCommandIdentifier(), PARAMETER_CONFIG + getTestRessourcePathFor(CORRECT_SYSTEM_CONFIG_JSON) }; TestUtils.simulateCommandLineInput(command); assertCorrectCommandResultAsLatestInCommandHistory(); }
InputControl implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } private InputControl(); static InputControl getInputControl(); @Override void update(Observable o, Object arg); void printUsage(); void simulateUserInput(String[] userInput); }
@Test(expected = UnsupportedOperationException.class) public void testUpdateFailureWithWrongObservable() { inputControl.update(new DetermineApplicableAlgorithmsCommandHandler(), StringUtils.EMPTY_STRING); } @Test(expected = UnsupportedOperationException.class) public void testUpdateFailureWithWrongArgument() { inputControl.update(CommandLineParserView.getCommandLineParserView(), new Exception()); }
ADatasetParser implements IDatasetParser { @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } @Override IDataset<?, ?, ?> parse(DatasetFile file); @Override IDataset<?, ?, ?> parsePartialOf(DatasetFile file, int amountOfInstances); static Ranking parseRelativeRanking(String ranking); static final String ITEM_MARKER; }
@Test public void testParseInvalidDataset() { List<DatasetFile> datasets = getInvalidDatasets(); for (int i = 0; i < datasets.size(); i++) { try { DatasetFile datasetFile = datasets.get(i); getDatasetParser().parse(datasetFile); fail(PARSING_FAILED_EXCEPTION_EXPECTED_BUT_NOT_FOUND); } catch (ParsingFailedException e) { } } } @Test public void testParseValidDataset() throws ParsingFailedException { List<DatasetFile> datasets = getValidDatasets(); for (int i = 0; i < datasets.size(); i++) { DatasetFile datasetFile = datasets.get(i); IDatasetParser parser = getDatasetParser(); parser.parse(datasetFile); validateDataset(i, parser.getDataset()); } }
CombinedRankingAndRegressionLearningAlgorithm extends ALearningAlgorithm<CombinedRankingAndRegressionConfiguration> { @Override public CombinedRankingAndRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (CombinedRankingAndRegressionLearningModel) super.train(dataset); } CombinedRankingAndRegressionLearningAlgorithm(); @Override IDatasetParser getDatasetParser(); @Override void init(); @Override CombinedRankingAndRegressionLearningModel train(IDataset<?, ?, ?> dataset); @Override boolean equals(Object secondObject); @Override int hashCode(); }
@Override @Test public void testCorrectPredictions() { List<IDataset<double[], List<double[]>, IVector>> correctDatasetList = getCorrectDatasetList(); List<Pair<IDataset<double[], List<double[]>, IVector>, List<IVector>>> predictionDatasetList = getPredictionsForDatasetList(); Assert.assertEquals(ERROR_DIFFERENT_LIST_LENGTHS, correctDatasetList.size(), predictionDatasetList.size()); for (int i = 0; i < correctDatasetList.size(); i++) { IDataset<double[], List<double[]>, IVector> testDataset = correctDatasetList.get(i); IDataset<double[], List<double[]>, IVector> predictDataset = predictionDatasetList.get(i).getFirst(); List<IVector> expectedPredictedValueOfDataset = predictionDatasetList.get(i).getSecond(); try { ITrainableAlgorithm algorithm = getTrainableAlgorithm(); @SuppressWarnings("unchecked") ILearningModel<Double> trainedLearningModel = (ILearningModel<Double>) algorithm.train(testDataset); List<Double> predictedValueOfDataset = trainedLearningModel.predict(predictDataset); if (!areIVectorRatingListsEqual(predictedValueOfDataset, expectedPredictedValueOfDataset)) { fail(String.format(ERROR_WRONG_OUTPUT, expectedPredictedValueOfDataset, predictedValueOfDataset)); } } catch (TrainModelsFailedException e) { fail(String.format(ERROR_INCORRECT_DATASET, e.getMessage())); } catch (PredictionFailedException e) { fail(String.format(ERROR_PREDICTION_FAILED, e.getMessage())); } } }
PairwiseRankingLearningAlgorithm extends AObjectRankingWithBaseLearner<PairwiseRankingConfiguration> { @Override public PairwiseRankingLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (PairwiseRankingLearningModel) super.train(dataset); } PairwiseRankingLearningAlgorithm(); @Override PairwiseRankingLearningModel train(IDataset<?, ?, ?> dataset); }
@Test @Ignore public void pairwiseRankingAlgorithmTestCorrectInput() throws ParsingFailedException, TrainModelsFailedException, PredictionFailedException, LossException { File file = new File(getTestRessourcePathFor(OBJECT_RANKING_DATASET_B)); PairwiseRankingLearningAlgorithm algortihm = new PairwiseRankingLearningAlgorithm(); DatasetFile datasetFile = new DatasetFile(file); ObjectRankingDatasetParser objectRankingParser = (ObjectRankingDatasetParser) algortihm.getDatasetParser(); IDataset<?, ?, ?> objectRankingDataset = objectRankingParser.parse(datasetFile); IInstance<?, ?, ?> instance = objectRankingDataset.getInstance(505); IDataset<?, ?, ?> testSet = objectRankingDataset.getPartOfDataset(515, 518); objectRankingDataset = objectRankingDataset.getPartOfDataset(0, 10); ILearningModel<?> train = algortihm.train(objectRankingDataset); PairwiseRankingLearningModel castedLearningModel = (PairwiseRankingLearningModel) train; Ranking predict = null; List<Ranking> predictedRankingsOnTestSet = new ArrayList<>(); if (castedLearningModel != null) { predict = castedLearningModel.predict(instance); predictedRankingsOnTestSet = castedLearningModel.predict(testSet); } int[] objectList = new int[] { 0, 8, 21, 16, 7, 12, 30, 24, 59, 14 }; Ranking expectedResult = new Ranking(objectList, Ranking.createCompareOperatorArrayForLabels(objectList)); assertNotNull(predict); assertTrue(expectedResult.getObjectList().length == predict.getObjectList().length); assertTrue(expectedResult.getCompareOperators().length == predict.getCompareOperators().length); assertTrue(expectedResult.equals(predict)); List<Ranking> expected = ((ObjectRankingDataset) testSet).getRankings(); SpearmansCorrelation correlation = new SpearmansCorrelation(); double rho = correlation.getAggregatedLossForRatings(expected, predictedRankingsOnTestSet); Assert.assertEquals(0.5191919191919192, rho, 0.0001); }