下面列出了怎么用org.springframework.security.authentication.TestingAuthenticationToken的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testGetJobAssertAccessDeniedGivenJobRunningAndUserDoesNotHavePermissions() throws Exception
{
jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_USER_TASK_WITH_CLASSPATH);
Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));
String username = "username";
ApplicationUser applicationUser = new ApplicationUser(getClass());
applicationUser.setUserId(username);
applicationUser.setNamespaceAuthorizations(new HashSet<>());
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
null));
try
{
jobService.getJob(job.getId(), false);
fail();
}
catch (Exception e)
{
assertEquals(AccessDeniedException.class, e.getClass());
assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"%s\"", username, TEST_ACTIVITI_NAMESPACE_CD),
e.getMessage());
}
}
@Test
public void testDeleteJobAssertNoErrorWhenUserHasPermissions() throws Exception
{
// Start a job that will wait in a receive task
jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_RECEIVE_TASK_WITH_CLASSPATH);
Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));
String username = "username";
ApplicationUser applicationUser = new ApplicationUser(getClass());
applicationUser.setUserId(username);
applicationUser.setNamespaceAuthorizations(new HashSet<>());
applicationUser.getNamespaceAuthorizations()
.add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD, Arrays.asList(NamespacePermissionEnum.EXECUTE)));
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
null));
try
{
jobService.deleteJob(job.getId(), new JobDeleteRequest("test delete reason"));
}
catch (AccessDeniedException e)
{
fail();
}
}
@Test
public void spendToNewAccountShouldHaveOneSpendTransaction() throws Exception {
UserProfile parentProfile = new UserProfile("Parent Spender",
new PhoneNumber("+15555555555"),
"[email protected]",
Role.PARENT);
mockMvc.perform(post("/spend")
.with(authentication(
new TestingAuthenticationToken(parentProfile, null, "ROLE_PARENT")))
.param("date", "2018-12-19")
.param("amount", "49.95")
.param("description", "Video game"))
.andExpect(redirectedUrl(AccountController.ACCOUNT_URL));
Collection<TransactionView> transactions = transactionsFromModel();
assertThat(transactions)
.contains(new TransactionView(
"12/19/2018", "Spend", "$49.95", "Video game", "Parent Spender"));
}
@Test
public void shouldGetAccessToken() {
//Given
final OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails = oAuth2ProtectedResourceDetailsBuilder().build();
final TestingAuthenticationToken authentication = new TestingAuthenticationToken(userBuilder().build(), string().next());
//And
final String authenticationId = string().next();
given(keyGenerator.extractKey(oAuth2ProtectedResourceDetails, authentication)).willReturn(authenticationId);
//And
final OAuth2AccessToken expectedToken = oAuth2AccessTokenBuilder().build();
given(mongoOAuth2ClientTokenRepository.findByAuthenticationId(authenticationId)).willReturn(mongoOAuth2ClientTokenBuilder().token(expectedToken).build());
//When
final OAuth2AccessToken accessToken = mongoClientTokenServices.getAccessToken(oAuth2ProtectedResourceDetails, authentication);
//Then
assertThat(accessToken).isEqualTo(expectedToken);
}
@Ignore("Until EasyMock 3.7 upgrade - waiting for release")
@Test
public void testOneExceptionNoOneAuthenticates() {
Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
expect(mockFileProvider.authenticate(authentication)).andReturn(FAILED_AUTHENTICATION);
expect(mockExternalServerProvider.authenticate(authentication)).andThrow(new AuthenticationException("msg1") {});
expect(mockSimpleProvider.authenticate(authentication)).andReturn(FAILED_AUTHENTICATION);
replay(mockFileProvider, mockSimpleProvider, mockExternalServerProvider);
try {
provider.authenticate(authentication);
assertTrue("Should have thrown AuthenticationException", false);
} catch(AuthenticationException e) {
assertEquals(e.getMessage(), "msg1");
}
verify(mockFileProvider, mockSimpleProvider, mockExternalServerProvider);
}
@Ignore("Until EasyMock 3.7 upgrade - waiting for release")
@Test
public void testTwoExceptionNoOneAuthenticates() {
Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
expect(mockFileProvider.authenticate(authentication)).andThrow(new AuthenticationException("msg1") {});
expect(mockExternalServerProvider.authenticate(authentication)).andThrow(new AuthenticationException("msg2") {});
expect(mockSimpleProvider.authenticate(authentication)).andReturn(FAILED_AUTHENTICATION);
replay(mockFileProvider, mockSimpleProvider, mockExternalServerProvider);
try {
provider.authenticate(authentication);
assertTrue("Should have thrown AuthenticationException", false);
} catch(AuthenticationException e) {
assertEquals(e.getMessage(), "msg1");
}
verify(mockFileProvider, mockSimpleProvider, mockExternalServerProvider);
}
@Test
public void testAuthenticationEmptyPassword() {
expect(mockAuthPropsConfig.isAuthFileEnabled()).andReturn(true);
replay(mockAuthPropsConfig);
Authentication authentication = new TestingAuthenticationToken("principal", "");
try {
provider.authenticate(authentication);
fail("Should have thrown BadCredentialsException");
} catch(BadCredentialsException e) {
assertEquals("Password can't be null or empty.", e.getMessage());
}
verify(mockAuthPropsConfig);
}
@Test
public void testAuthenticationNullPassword() {
expect(mockAuthPropsConfig.isAuthFileEnabled()).andReturn(true);
replay(mockAuthPropsConfig);
Authentication authentication = new TestingAuthenticationToken("principal", null);
try {
provider.authenticate(authentication);
fail("Should have thrown BadCredentialsException");
} catch(BadCredentialsException e) {
assertEquals("Password can't be null or empty.", e.getMessage());
}
verify(mockAuthPropsConfig);
}
@Test
public void testAuthenticationUnknownUser() {
expect(mockAuthPropsConfig.isAuthFileEnabled()).andReturn(true);
expect(mockUserDetailsService.loadUserByUsername("principal")).andReturn(null);
replay(mockAuthPropsConfig, mockUserDetailsService);
Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
try {
provider.authenticate(authentication);
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException e) {
assertEquals("User not found.", e.getMessage());
}
verify(mockAuthPropsConfig, mockUserDetailsService);
}
@Test
public void testAuthenticationNoPassword() {
List<GrantedAuthority> grantedAuths = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
User user = new User("principal", null, grantedAuths);
expect(mockAuthPropsConfig.isAuthFileEnabled()).andReturn(true);
expect(mockUserDetailsService.loadUserByUsername("principal")).andReturn(user);
replay(mockAuthPropsConfig, mockUserDetailsService);
Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
try {
provider.authenticate(authentication);
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException e) {
assertEquals("Password can't be null or empty.", e.getMessage());
}
verify(mockAuthPropsConfig, mockUserDetailsService);
}
@Test
public void testGetJobAssertAccessDeniedGivenJobCompletedAndUserDoesNotHavePermissions() throws Exception
{
jobDefinitionServiceTestHelper.createJobDefinition(null);
Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));
String username = "username";
ApplicationUser applicationUser = new ApplicationUser(getClass());
applicationUser.setUserId(username);
applicationUser.setNamespaceAuthorizations(new HashSet<>());
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
null));
try
{
jobService.getJob(job.getId(), false);
fail();
}
catch (Exception e)
{
assertEquals(AccessDeniedException.class, e.getClass());
assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"%s\"", username, TEST_ACTIVITI_NAMESPACE_CD),
e.getMessage());
}
}
@Test
public void testGetJobAssertNoErrorGivenJobCompletedAndUserDoesHasPermissions() throws Exception
{
jobDefinitionServiceTestHelper.createJobDefinition(null);
Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));
String username = "username";
ApplicationUser applicationUser = new ApplicationUser(getClass());
applicationUser.setUserId(username);
applicationUser.setNamespaceAuthorizations(new HashSet<>());
applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD, Arrays.asList(NamespacePermissionEnum.READ)));
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
null));
try
{
jobService.getJob(job.getId(), false);
}
catch (AccessDeniedException e)
{
fail();
}
}
@Test
public void testAuthenticationNullUser() {
expect(mockAuthPropsConfig.isAuthExternalEnabled()).andReturn(true);
replay(mockAuthPropsConfig);
Authentication authentication = new TestingAuthenticationToken(null, "credentials");
try {
provider.authenticate(authentication);
assertTrue("Should have thrown BadCredentialsException", false);
} catch(BadCredentialsException e) {
assertEquals("Username can't be null or empty.", e.getMessage());
}
verify(mockAuthPropsConfig);
}
@Test
public void testAuthenticationUnsuccessful() throws Exception {
expect(mockAuthPropsConfig.isAuthExternalEnabled()).andReturn(true);
expect(mockAuthPropsConfig.getExternalAuthLoginUrl()).andReturn("http://server.com?userName=$USERNAME");
expect(mockAuthPropsConfig.getAllowedRoles()).andReturn(Arrays.asList("AMBARI.ADMINISTRATOR"));
expect(mockExternalServerClient.sendGETRequest("http://server.com?userName=principal", String.class, "principal", "credentials"))
.andReturn("{\"permission_name\": \"NOT.AMBARI.ADMINISTRATOR\" }");
replay(mockAuthPropsConfig, mockExternalServerClient);
Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
try {
provider.authenticate(authentication);
assertTrue("Should have thrown BadCredentialsException", false);
} catch (BadCredentialsException e) {
assertEquals("Bad credentials", e.getMessage());
}
verify(mockAuthPropsConfig, mockExternalServerClient);
}
@Test
public void testAuthenticationPropagation() throws InterruptedException {
final int numThreads = 3;
final Authentication[] authentications = new Authentication[numThreads];
for (int i = 0; i < authentications.length; i++) {
final String principal = "principal" + i;
final String credential = "credential" + i;
authentications[i] = new TestingAuthenticationToken(principal, credential);
}
final CountDownLatch schedulerLatch = new CountDownLatch(numThreads);
final Timer timer = new Timer();
for (Authentication authentication : authentications) {
new Thread(new Runnable() {
@Override
public void run() {
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(authentication);
SecurityContextHolder.setContext(securityContext);
TimerTask timerTask = timerTaskDecoratorFactory.createTimerTaskDecorator().decorate(new TestTimerTask(schedulerLatch, authentication));
timer.schedule(timerTask, DELAY_MS);
}
}).start();
}
Assert.assertTrue("Timed out waiting for timer task completion", schedulerLatch.await(2 * DELAY_MS, TimeUnit.MILLISECONDS));
}
@Test
public void testAuthenticationEmptyUser() {
expect(mockAuthPropsConfig.isAuthSimpleEnabled()).andReturn(true);
replay(mockAuthPropsConfig);
Authentication authentication = new TestingAuthenticationToken("", "credentials");
try {
provider.authenticate(authentication);
assertTrue("Should have thrown BadCredentialsException", false);
} catch(BadCredentialsException e) {
assertEquals("Username can't be null or empty.", e.getMessage());
}
verify(mockAuthPropsConfig);
}
@Test
public void testAuthenticationNullUser() {
expect(mockAuthPropsConfig.isAuthSimpleEnabled()).andReturn(true);
replay(mockAuthPropsConfig);
Authentication authentication = new TestingAuthenticationToken(null, "credentials");
try {
provider.authenticate(authentication);
assertTrue("Should have thrown BadCredentialsException", false);
} catch(BadCredentialsException e) {
assertEquals("Username can't be null or empty.", e.getMessage());
}
verify(mockAuthPropsConfig);
}
@Test
public void testAuthenticationSuccessful() {
expect(mockAuthPropsConfig.isAuthSimpleEnabled()).andReturn(true);
replay(mockAuthPropsConfig);
Authentication authentication = new TestingAuthenticationToken("principal", "credentials");
Authentication authenticationResult = provider.authenticate(authentication);
assertEquals("principal", authenticationResult.getName());
assertEquals("credentials", authenticationResult.getCredentials());
assertEquals(1, authenticationResult.getAuthorities().size());
assertEquals(new SimpleGrantedAuthority("ROLE_USER"), authenticationResult.getAuthorities().iterator().next());
verify(mockAuthPropsConfig);
}
/**
* Provide the mock user information to be used
*
* @param withMockOAuth2Token
* @return
*/
private Authentication getAuthentication(WithMockOAuth2Token withMockOAuth2Token) {
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities());
User userPrincipal = new User(withMockOAuth2Token.userName(), withMockOAuth2Token.password(), true, true, true,
true, authorities);
HashMap<String, String> details = new HashMap<String, String>();
details.put("user_name", withMockOAuth2Token.userName());
details.put("email", "[email protected]");
details.put("name", "Anil Allewar");
TestingAuthenticationToken token = new TestingAuthenticationToken(userPrincipal, null, authorities);
token.setAuthenticated(true);
token.setDetails(details);
return token;
}
@Test
public void shouldRaiseExceptionInvalidJsonPub() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
Authentication auth = new TestingAuthenticationToken("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883", null);
context.setAuthentication(auth);
when(oAuthClientDetailsService.loadClientByIdAsRoot("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883"))
.thenReturn(ServiceResponseBuilder.<OauthClientDetails>ok()
.withResult(OauthClientDetails.builder().parentGateway(gateway).build()).build());
when(jsonParsingService.isValid("[{'a': 10}")).thenReturn(false);
getMockMvc().perform(
post("/gateway/pub")
.flashAttr("principal", gateway)
.contentType(MediaType.APPLICATION_JSON)
.content("[{'a': 10}"))
.andExpect(status().isBadRequest())
.andExpect(content().string(org.hamcrest.Matchers.containsString("{\"code\":\"integration.rest.invalid.body\",\"message\":\"Event content is in invalid format. Expected to be a valid JSON string\"}")));
}
@WithMockUser("jsmith")
@Test
public void submitTalk() throws Exception {
Authentication authentication = new TestingAuthenticationToken(
new User("jsmith", "John Smith"), "secret", "ROLE_USER");
given(this.submissionService.create(any())).willReturn(new Submission());
this.mvc.perform(post("/submit")
.param("title", "Alice in Wonderland")
.param("summary", "my abstract")
.param("track", Track.ALTERNATE_LANGUAGES.getId())
.param("notes", "this rocks")
.with(authentication(authentication))
.with(csrf()))
.andExpect(status().isFound())
.andExpect(header().string(HttpHeaders.LOCATION, "/submit?navSection=submit"));
verify(this.submissionService).create(any());
}
/**
* Asserts that the namespace security advice is enabled. Try calling a secured method with a mock user in the context with invalid permissions. The
* expectation is that the method call fails with AccessDeniedException if the advice is enabled.
*/
@Test
public void assertAdviceEnabled()
{
// put a fake user with no permissions into the security context
// the security context is cleared on the after() method of this test suite
String username = "username";
Class<?> generatedByClass = getClass();
ApplicationUser applicationUser = new ApplicationUser(generatedByClass);
applicationUser.setUserId(username);
applicationUser.setNamespaceAuthorizations(Collections.emptySet());
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
null));
try
{
businessObjectDefinitionServiceImpl
.createBusinessObjectDefinition(new BusinessObjectDefinitionCreateRequest(NAMESPACE, BDEF_NAME, DATA_PROVIDER_NAME, null, null, null));
fail();
}
catch (Exception e)
{
assertEquals(AccessDeniedException.class, e.getClass());
}
}
@Test
public void testGetJobAssertNoErrorGivenJobRunningAndUserDoesHasPermissions() throws Exception
{
jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_USER_TASK_WITH_CLASSPATH);
Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));
String username = "username";
ApplicationUser applicationUser = new ApplicationUser(getClass());
applicationUser.setUserId(username);
applicationUser.setNamespaceAuthorizations(new HashSet<>());
applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD, Arrays.asList(NamespacePermissionEnum.READ)));
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
null));
try
{
jobService.getJob(job.getId(), false);
}
catch (AccessDeniedException e)
{
fail();
}
}
@Test
public void checkPermissionAssertAccessDeniedWhenPrincipalIsNotSecurityUserWrapper() throws Exception
{
// Mock a join point of the method call
// mockMethod("foo");
JoinPoint joinPoint = mock(JoinPoint.class);
MethodSignature methodSignature = mock(MethodSignature.class);
Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
when(methodSignature.getMethod()).thenReturn(method);
when(joinPoint.getSignature()).thenReturn(methodSignature);
when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"});
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("streetcreds", null));
try
{
namespaceSecurityAdvice.checkPermission(joinPoint);
fail();
}
catch (Exception e)
{
assertEquals(AccessDeniedException.class, e.getClass());
assertEquals("Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", e.getMessage());
}
}
@Test
public void checkPermissionAssertAccessDeniedWhenPrincipalIsNull() throws Exception
{
// Mock a join point of the method call
// mockMethod("foo");
JoinPoint joinPoint = mock(JoinPoint.class);
MethodSignature methodSignature = mock(MethodSignature.class);
Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
when(methodSignature.getMethod()).thenReturn(method);
when(joinPoint.getSignature()).thenReturn(methodSignature);
when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"});
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(null, null));
try
{
namespaceSecurityAdvice.checkPermission(joinPoint);
fail();
}
catch (Exception e)
{
assertEquals(AccessDeniedException.class, e.getClass());
assertEquals("Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", e.getMessage());
}
}
@Test
public void testDeleteJobAssertAccessDeniedWhenUserHasNoPermissions() throws Exception
{
// Start a job that will wait in a receive task
jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_RECEIVE_TASK_WITH_CLASSPATH);
Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));
String username = "username";
ApplicationUser applicationUser = new ApplicationUser(getClass());
applicationUser.setUserId(username);
applicationUser.setNamespaceAuthorizations(new HashSet<>());
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser),
null));
try
{
jobService.deleteJob(job.getId(), new JobDeleteRequest("test delete reason"));
fail();
}
catch (Exception e)
{
assertEquals(AccessDeniedException.class, e.getClass());
assertEquals(String.format("User \"%s\" does not have \"[EXECUTE]\" permission(s) to the namespace \"%s\"", username, TEST_ACTIVITI_NAMESPACE_CD),
e.getMessage());
}
}
@Test(expected=AccessDeniedException.class)
public void testPreHandle_UserNotAuthorized() throws Exception {
FilterInvocation filterInvocation = new FilterInvocation("/logs/log-with-oneuser-authorized/list", "GET");
TestingAuthenticationToken authenticatedUser = new TestingAuthenticationToken("not-authorized-user", null);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
logAccessConfigAuthorizedVoter.vote(authenticatedUser, filterInvocation, Arrays.asList(GOOD_ATTRIBUTE));
}
@Before
public void setup() throws Exception {
this.createTestMetadata();
Authentication authentication = new TestingAuthenticationToken("ADMIN", "ADMIN", Constant.ROLE_ADMIN);
SecurityContextHolder.getContext().setAuthentication(authentication);
KylinConfig config = KylinConfig.getInstanceFromEnv();
Broadcaster.getInstance(config).notifyClearAll();
List<String> userGroups = userGroupService.getAllUserGroups();
if (!userGroups.contains(Constant.GROUP_ALL_USERS)) {
userGroupService.addGroup(Constant.GROUP_ALL_USERS);
}
if (!userGroups.contains(Constant.ROLE_ADMIN)) {
userGroupService.addGroup(Constant.ROLE_ADMIN);
}
if (!userGroups.contains(Constant.ROLE_MODELER)) {
userGroupService.addGroup(Constant.ROLE_MODELER);
}
if (!userGroups.contains(Constant.ROLE_ANALYST)) {
userGroupService.addGroup(Constant.ROLE_ANALYST);
}
if (!userService.userExists("ADMIN")) {
userService.createUser(new ManagedUser("ADMIN", "KYLIN", false, Arrays.asList(//
new SimpleGrantedAuthority(Constant.ROLE_ADMIN), new SimpleGrantedAuthority(Constant.ROLE_ANALYST),
new SimpleGrantedAuthority(Constant.ROLE_MODELER))));
}
if (!userService.userExists("MODELER")) {
userService.createUser(new ManagedUser("MODELER", "MODELER", false, Arrays.asList(//
new SimpleGrantedAuthority(Constant.ROLE_ANALYST),
new SimpleGrantedAuthority(Constant.ROLE_MODELER))));
}
if (!userService.userExists("ANALYST")) {
userService.createUser(new ManagedUser("ANALYST", "ANALYST", false, Arrays.asList(//
new SimpleGrantedAuthority(Constant.ROLE_ANALYST))));
}
}
@Test
public void submitSpendShouldReduceAmountInAccount() throws Exception {
mockMvc.perform(post("/spend")
.with(authentication(
new TestingAuthenticationToken(new DummyUserProfile(), null, "ROLE_PARENT")))
.param("amount", "87.34")
.param("date", "2001-11-12")
.param("description", "you spent it on what?"))
.andExpect(redirectedUrl(AccountController.ACCOUNT_URL));
mockMvc.perform(get(AccountController.ACCOUNT_URL))
.andExpect(model().attribute("balance", "-$87.34"));
}
@Before
public void setUp() throws Exception {
reset(ruleEntityService, teamOperationsMock, ruleControllerPropertiesMock);
ruleDTO = new RuleDTO();
ruleDTO.setAccountId("12345");
ruleDTO.setApplicationId("a-1234");
ruleDTO.setApplicationVersion("1.0-SNAPSHOT");
ruleDTO.setExpiryDate(DateTime.now());
ruleDTO.setImageName("amiName");
ruleDTO.setImageOwner("Peter Lustig");
ruleDTO.setReason("BAM!");
ruleDTO.setRegion("eu-west-1");
ruleDTO.setViolationTypeEntityId("APPLICATION_NOT_PRESENT_IN_KIO");
ruleDTO.setMetaInfoJsonPath("$..*");
ruleEntity = new RuleEntity();
ruleEntity.setId(1L);
ruleEntity.setAccountId("1234");
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test-user", null));
when(ruleEntityService.findAll()).thenReturn(newArrayList(ruleEntity));
when(ruleControllerPropertiesMock.getAllowedTeams()).thenReturn(newArrayList("Owner", "OtherTeam"));
when(teamOperationsMock.getAwsAccountsByUser(anyString())).thenReturn(newArrayList(
new Account(
"Team",
"Foo",
"teams_account",
"Description",
"Owner",
false)));
when(teamOperationsMock.getTeamIdsByUser(anyString())).thenReturn(newHashSet("Owner", "OtherTeamID"));
mockMvc = MockMvcBuilders.webAppContextSetup(wac).alwaysDo(print()).build();
}