method2testcases
stringlengths 118
6.63k
|
---|
### Question:
AuthConfiguration { public void setCertificate(String certificate) { this.certificate = certificate; } String getClient(); void setClient(String client); String getTenant(); void setTenant(String tenant); String getKey(); void setKey(String key); String getCertificate(); void setCertificate(String certificate); String getCertificatePassword(); void setCertificatePassword(String certificatePassword); String getEnvironment(); void setEnvironment(String environment); String getServerId(); void setServerId(String serverId); String getHttpProxyHost(); void setHttpProxyHost(String httpProxyHost); String getHttpProxyPort(); void setHttpProxyPort(String httpProxyPort); List<ConfigurationProblem> validate(); }### Answer:
@Test public void testSetCertificate() { final AuthConfiguration auth = new AuthConfiguration(); auth.setCertificate("certificate1"); assertEquals("certificate1", auth.getCertificate()); } |
### Question:
AuthConfiguration { public void setCertificatePassword(String certificatePassword) { this.certificatePassword = certificatePassword; } String getClient(); void setClient(String client); String getTenant(); void setTenant(String tenant); String getKey(); void setKey(String key); String getCertificate(); void setCertificate(String certificate); String getCertificatePassword(); void setCertificatePassword(String certificatePassword); String getEnvironment(); void setEnvironment(String environment); String getServerId(); void setServerId(String serverId); String getHttpProxyHost(); void setHttpProxyHost(String httpProxyHost); String getHttpProxyPort(); void setHttpProxyPort(String httpProxyPort); List<ConfigurationProblem> validate(); }### Answer:
@Test public void testSetCertificatePassword() { final AuthConfiguration auth = new AuthConfiguration(); auth.setCertificatePassword("certificatePassword1"); assertEquals("certificatePassword1", auth.getCertificatePassword()); } |
### Question:
AuthConfiguration { public void setEnvironment(String environment) { this.environment = environment; } String getClient(); void setClient(String client); String getTenant(); void setTenant(String tenant); String getKey(); void setKey(String key); String getCertificate(); void setCertificate(String certificate); String getCertificatePassword(); void setCertificatePassword(String certificatePassword); String getEnvironment(); void setEnvironment(String environment); String getServerId(); void setServerId(String serverId); String getHttpProxyHost(); void setHttpProxyHost(String httpProxyHost); String getHttpProxyPort(); void setHttpProxyPort(String httpProxyPort); List<ConfigurationProblem> validate(); }### Answer:
@Test public void testSetEnvironment() { final AuthConfiguration auth = new AuthConfiguration(); auth.setEnvironment("environment1"); assertEquals("environment1", auth.getEnvironment()); } |
### Question:
AuthConfiguration { public void setServerId(String serverId) { this.serverId = serverId; } String getClient(); void setClient(String client); String getTenant(); void setTenant(String tenant); String getKey(); void setKey(String key); String getCertificate(); void setCertificate(String certificate); String getCertificatePassword(); void setCertificatePassword(String certificatePassword); String getEnvironment(); void setEnvironment(String environment); String getServerId(); void setServerId(String serverId); String getHttpProxyHost(); void setHttpProxyHost(String httpProxyHost); String getHttpProxyPort(); void setHttpProxyPort(String httpProxyPort); List<ConfigurationProblem> validate(); }### Answer:
@Test public void testSetServerId() { final AuthConfiguration auth = new AuthConfiguration(); auth.setServerId("serverId1"); assertEquals("serverId1", auth.getServerId()); } |
### Question:
AuthConfiguration { public void setHttpProxyHost(String httpProxyHost) { this.httpProxyHost = httpProxyHost; } String getClient(); void setClient(String client); String getTenant(); void setTenant(String tenant); String getKey(); void setKey(String key); String getCertificate(); void setCertificate(String certificate); String getCertificatePassword(); void setCertificatePassword(String certificatePassword); String getEnvironment(); void setEnvironment(String environment); String getServerId(); void setServerId(String serverId); String getHttpProxyHost(); void setHttpProxyHost(String httpProxyHost); String getHttpProxyPort(); void setHttpProxyPort(String httpProxyPort); List<ConfigurationProblem> validate(); }### Answer:
@Test public void testSetHttpProxyHost() { final AuthConfiguration auth = new AuthConfiguration(); auth.setHttpProxyHost("httpProxyHost1"); assertEquals("httpProxyHost1", auth.getHttpProxyHost()); } |
### Question:
AuthConfiguration { public void setHttpProxyPort(String httpProxyPort) { this.httpProxyPort = httpProxyPort; } String getClient(); void setClient(String client); String getTenant(); void setTenant(String tenant); String getKey(); void setKey(String key); String getCertificate(); void setCertificate(String certificate); String getCertificatePassword(); void setCertificatePassword(String certificatePassword); String getEnvironment(); void setEnvironment(String environment); String getServerId(); void setServerId(String serverId); String getHttpProxyHost(); void setHttpProxyHost(String httpProxyHost); String getHttpProxyPort(); void setHttpProxyPort(String httpProxyPort); List<ConfigurationProblem> validate(); }### Answer:
@Test public void testSetHttpProxyPort() { final AuthConfiguration auth = new AuthConfiguration(); auth.setHttpProxyPort("8080"); assertEquals("8080", auth.getHttpProxyPort()); } |
### Question:
ListMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { try { Log.info(TEMPLATES_START); printToSystemOut(TEMPLATES_FILE); Log.info(TEMPLATES_END); Log.info(BINDINGS_START); printToSystemOut(BINDINGS_FILE); Log.info(BINDINGS_END); Log.info(RESOURCES_START); printToSystemOut(RESOURCES_FILE); Log.info(RESOURCES_END); } catch (IOException e) { throw new AzureExecutionException("IO errror when printing templates:" + e.getMessage(), e); } } }### Answer:
@Test public void doExecute() throws Exception { PowerMockito.doNothing().when(Log.class); Log.info(any(String.class)); final PrintStream out = mock(PrintStream.class); System.setOut(out); final ListMojo mojo = new ListMojo(); mojo.doExecute(); verify(out, atLeastOnce()).write(any(byte[].class), any(int.class), any(int.class)); } |
### Question:
LocalAuthServer { public void start() throws IOException { if (jettyServer.isStarted()) { return; } try { jettyServer.start(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new IOException(e); } } LocalAuthServer(); URI getURI(); void start(); void stop(); String waitForCode(); }### Answer:
@Test public void testStart() throws IOException { localAuthServer.stop(); try { localAuthServer.start(); } catch (Exception ex) { fail("Should not fail on after start."); } } |
### Question:
LocalAuthServer { public void stop() throws IOException { semaphore.release(); try { jettyServer.stop(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new IOException(e); } } LocalAuthServer(); URI getURI(); void start(); void stop(); String waitForCode(); }### Answer:
@Test public void testStop() throws IOException { localAuthServer.stop(); localAuthServer.stop(); } |
### Question:
AzureCredential { public static AzureCredential fromAuthenticationResult(AuthenticationResult result) { if (result == null) { throw new IllegalArgumentException("Parameter \"result\" cannot be null"); } final AzureCredential token = new AzureCredential(); token.setAccessTokenType(result.getAccessTokenType()); token.setAccessToken(result.getAccessToken()); token.setRefreshToken(result.getRefreshToken()); token.setIdToken(result.getIdToken()); token.setUserInfo(result.getUserInfo()); token.setMultipleResourceRefreshToken(result.isMultipleResourceRefreshToken()); return token; } private AzureCredential(); static AzureCredential fromAuthenticationResult(AuthenticationResult result); String getAccessTokenType(); void setAccessTokenType(String accessTokenType); String getIdToken(); void setIdToken(String idToken); UserInfo getUserInfo(); void setUserInfo(UserInfo userInfo); String getAccessToken(); void setAccessToken(String accessToken); String getRefreshToken(); void setRefreshToken(String refreshToken); boolean isMultipleResourceRefreshToken(); void setMultipleResourceRefreshToken(boolean isMultipleResourceRefreshToken); String getDefaultSubscription(); void setDefaultSubscription(String defaultSubscription); String getEnvironment(); void setEnvironment(String environment); }### Answer:
@Test public void testFromNullResult() { try { AzureCredential.fromAuthenticationResult(null); fail("Should throw IAE"); } catch (IllegalArgumentException ex) { } } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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) { } } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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) { } } |
### Question:
AzureLoginHelper { static String baseURL(AzureEnvironment env) { return env.activeDirectoryEndpoint() + Constants.COMMON_TENANT; } private AzureLoginHelper(); }### Answer:
@Test public void testBaseURL() { String baseUrl = AzureLoginHelper.baseURL(AzureEnvironment.AZURE); assertEquals("https: baseUrl = AzureLoginHelper.baseURL(AzureEnvironment.AZURE_US_GOVERNMENT); assertEquals("https: } |
### Question:
AzureLoginHelper { static String getShortNameForAzureEnvironment(AzureEnvironment env) { return AZURE_ENVIRONMENT_MAP.get(env); } private AzureLoginHelper(); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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) { } } |
### Question:
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); }### Answer:
@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 ")); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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, ""); } |
### Question:
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); }### Answer:
@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) { } } |
### Question:
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); }### Answer:
@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) { } } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@Test public void testWithPath() { final Volume volume = new Volume(); volume.withPath("/home/shared"); assertEquals("/home/shared", volume.getPath()); } |
### Question:
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); }### Answer:
@Test public void testWithSize() { final Volume volume = new Volume(); volume.withSize("10G"); assertEquals("10G", volume.getSize()); } |
### Question:
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); }### Answer:
@Test public void testWithPersist() { final Volume volume = new Volume(); volume.withPersist(true); assertEquals(Boolean.TRUE, volume.isPersist()); } |
### Question:
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); }### Answer:
@Test public void testSetCpu() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setCpu("1"); assertEquals("1", deploy.getCpu()); } |
### Question:
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); }### Answer:
@Test public void testSetMemoryInGB() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setMemoryInGB("2"); assertEquals("2", deploy.getMemoryInGB()); } |
### Question:
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); }### Answer:
@Test public void testSetInstanceCount() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setInstanceCount("3"); assertEquals("3", deploy.getInstanceCount()); } |
### Question:
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); }### Answer:
@Test public void testSetDeploymentName() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setDeploymentName("deploymentName1"); assertEquals("deploymentName1", deploy.getDeploymentName()); } |
### Question:
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); }### Answer:
@Test public void testSetJvmOptions() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setJvmOptions("jvmOptions1"); assertEquals("jvmOptions1", deploy.getJvmOptions()); } |
### Question:
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); }### Answer:
@Test public void testSetRuntimeVersion() { final DeploymentSettings deploy = new DeploymentSettings(); deploy.setRuntimeVersion("8"); assertEquals("8", deploy.getRuntimeVersion()); } |
### Question:
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); }### Answer:
@Test public void testWithSubscriptionId() { final SpringConfiguration config = new SpringConfiguration(); config.withSubscriptionId("subscriptionId1"); assertEquals("subscriptionId1", config.getSubscriptionId()); } |
### Question:
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); }### Answer:
@Test public void testWithResourceGroup() { final SpringConfiguration config = new SpringConfiguration(); config.withResourceGroup("resourceGroup1"); assertEquals("resourceGroup1", config.getResourceGroup()); } |
### Question:
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); }### Answer:
@Test public void testWithClusterName() { final SpringConfiguration config = new SpringConfiguration(); config.withClusterName("clusterName1"); assertEquals("clusterName1", config.getClusterName()); } |
### Question:
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); }### Answer:
@Test public void testWithAppName() { final SpringConfiguration config = new SpringConfiguration(); config.withAppName("appName1"); assertEquals("appName1", config.getAppName()); } |
### Question:
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); }### Answer:
@Test public void testWithRuntimeVersion() { final SpringConfiguration config = new SpringConfiguration(); config.withRuntimeVersion("runtimeVersion1"); assertEquals("runtimeVersion1", config.getRuntimeVersion()); } |
### Question:
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); }### Answer:
@Test public void testWithDeployment() { final SpringConfiguration config = new SpringConfiguration(); final Deployment deploy = Mockito.mock(Deployment.class); config.withDeployment(deploy); assertEquals(deploy, config.getDeployment()); } |
### Question:
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); }### Answer:
@Test public void testWithCpu() { final Deployment deploy = new Deployment(); deploy.withCpu(1); assertEquals(1, (int) deploy.getCpu()); } |
### Question:
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); }### Answer:
@Test public void testWithMemoryInGB() { final Deployment deploy = new Deployment(); deploy.withMemoryInGB(2); assertEquals(2, (int) deploy.getMemoryInGB()); } |
### Question:
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); }### Answer:
@Test public void testWithInstanceCount() { final Deployment deploy = new Deployment(); deploy.withInstanceCount(3); assertEquals(3, (int) deploy.getInstanceCount()); } |
### Question:
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); }### Answer:
@Test public void testWithDeploymentName() { final Deployment deploy = new Deployment(); deploy.withDeploymentName("deploymentName1"); assertEquals("deploymentName1", deploy.getDeploymentName()); } |
### Question:
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); }### Answer:
@Test public void testWithJvmOptions() { final Deployment deploy = new Deployment(); deploy.withJvmOptions("jvmOptions1"); assertEquals("jvmOptions1", deploy.getJvmOptions()); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@Test public void testWithEnvironment() { final Deployment deploy = new Deployment(); deploy.withEnvironment(Collections.singletonMap("foo", "bar")); assertEquals("bar", deploy.getEnvironment().get("foo")); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@Test public void testSetSubscriptionId() { final AppSettings app = new AppSettings(); app.setSubscriptionId("subscriptionId1"); assertEquals("subscriptionId1", app.getSubscriptionId()); } |
### Question:
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); }### Answer:
@Test public void testSetClusterName() { final AppSettings app = new AppSettings(); app.setClusterName("clusterName1"); assertEquals("clusterName1", app.getClusterName()); } |
### Question:
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); }### Answer:
@Test public void testSetAppName() { final AppSettings app = new AppSettings(); app.setAppName("appName1"); assertEquals("appName1", app.getAppName()); } |
### Question:
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(); }### Answer:
@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")); } |
### Question:
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); }### Answer:
@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() ); } |
### Question:
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); }### Answer:
@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" ) ); } |
### Question:
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); }### Answer:
@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) ); } |
### Question:
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); }### Answer:
@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") ); } |
### Question:
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); }### Answer:
@Test public void buildsGifImage() throws Exception { MatcherAssert.assertThat( new RsPrint( new TkFavicon().act(new RqFake("GET", "/?unread=44")) ).printBody(), Matchers.notNullValue() ); } |
### Question:
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); }### Answer:
@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']" ) ); } |
### Question:
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); }### Answer:
@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" ) ); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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) ); } |
### Question:
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); }### Answer:
@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() ) ) ); } |
### Question:
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(); }### Answer:
@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>" ) ); } |
### Question:
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); }### Answer:
@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) ); } |
### Question:
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); }### Answer:
@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))) ); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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")) ) ); } |
### Question:
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(); }### Answer:
@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) ); } |
### Question:
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(); }### Answer:
@Test(expected = Friends.UnknownAliasException.class) public void inviteFailsOnUnknownAlias() throws Exception { new MkBase().randomBout().friends().invite("NoSuchFriend"); } |
### Question:
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); }### Answer:
@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" ) ); } |
### Question:
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); }### Answer:
@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']" ) ); } |
### Question:
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); }### Answer:
@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]") ); } |
### Question:
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); }### Answer:
@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]") ); } |
### Question:
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); }### Answer:
@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']" ) ); } |
### Question:
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); }### Answer:
@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')]" ) ); } |
### Question:
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); }### Answer:
@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(" ); } |
### Question:
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); }### Answer:
@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) ); } |
### Question:
Main { private Main() { } private Main(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static void main(final String... args); }### Answer:
@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']") ); } |
### Question:
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); }### Answer:
@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']") ); } |
### Question:
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(); }### Answer:
@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" ) ); } |
### Question:
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); }### Answer:
@Test public void checksInput() throws IOException { MatcherAssert.assertThat( new XeFacet.Wrap(new Rules()).touch( new XMLDocument( StringUtils.join( "<spec><input>", "User is\ta "human being". ", "</input></spec>" ) ) ), XhtmlMatchers.hasXPaths( "/spec/errors", "/spec/errors[count(error)>2]" ) ); } |
### Question:
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); }### Answer:
@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()) ); } |
### Question:
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); }### Answer:
@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() ); } |
### Question:
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); }### Answer:
@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\"']" ) ); } |
### Question:
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); }### Answer:
@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]") ); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@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))); } } } |
### Question:
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); }### Answer:
@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()); } } } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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()); } } |
### Question:
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(); }### Answer:
@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())); } } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.