Merge pull request #28 from rbkmoney/ft/JD-190

Update swag api for member role and refactoring tests
This commit is contained in:
Gregory 2021-04-02 11:23:46 +03:00 committed by GitHub
commit da6dbbce6d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 324 additions and 291 deletions

View File

@ -26,6 +26,7 @@
<shared.resources.version>0.3.6</shared.resources.version>
<keycloak.version>12.0.3</keycloak.version>
<schedlock.version>4.14.0</schedlock.version>
<swag.organizations.version>1.18-38ef431-server</swag.organizations.version>
</properties>
<dependencies>
@ -53,7 +54,7 @@
<dependency>
<groupId>com.rbkmoney</groupId>
<artifactId>swag-organizations</artifactId>
<version>1.16-8129cc0-server</version>
<version>${swag.organizations.version}</version>
</dependency>
<dependency>
<groupId>com.rbkmoney</groupId>

View File

@ -1,24 +1,8 @@
package com.rbkmoney.orgmanager.controller;
import com.rbkmoney.orgmanager.service.InvitationService;
import com.rbkmoney.orgmanager.service.KeycloakService;
import com.rbkmoney.orgmanager.service.OrganizationRoleService;
import com.rbkmoney.orgmanager.service.OrganizationService;
import com.rbkmoney.orgmanager.service.ResourceAccessService;
import com.rbkmoney.orgmanager.service.*;
import com.rbkmoney.swag.organizations.api.OrgsApi;
import com.rbkmoney.swag.organizations.model.InlineObject;
import com.rbkmoney.swag.organizations.model.InlineObject1;
import com.rbkmoney.swag.organizations.model.Invitation;
import com.rbkmoney.swag.organizations.model.InvitationListResult;
import com.rbkmoney.swag.organizations.model.InvitationRequest;
import com.rbkmoney.swag.organizations.model.InvitationStatusName;
import com.rbkmoney.swag.organizations.model.Member;
import com.rbkmoney.swag.organizations.model.MemberOrgListResult;
import com.rbkmoney.swag.organizations.model.MemberRole;
import com.rbkmoney.swag.organizations.model.Organization;
import com.rbkmoney.swag.organizations.model.Role;
import com.rbkmoney.swag.organizations.model.RoleAvailableListResult;
import com.rbkmoney.swag.organizations.model.RoleId;
import com.rbkmoney.swag.organizations.model.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.keycloak.representations.AccessToken;
@ -99,14 +83,19 @@ public class OrgsController implements OrgsApi {
}
@Override
public ResponseEntity<InvitationListResult> listInvitations(String xRequestID, String orgId, InvitationStatusName status) {
public ResponseEntity<InvitationListResult> listInvitations(String xRequestID,
String orgId,
InvitationStatusName status) {
log.info("List invitations: requestId={}, orgId={}, status={}", xRequestID, orgId, status);
resourceAccessService.checkOrganizationRights(orgId);
return invitationService.list(orgId, status);
}
@Override
public ResponseEntity<Void> revokeInvitation(String xRequestID, String orgId, String invitationId, InlineObject1 inlineObject1) {
public ResponseEntity<Void> revokeInvitation(String xRequestID,
String orgId,
String invitationId,
InlineObject1 inlineObject1) {
log.info("Revoke invitation: requestId={}, orgId={}, invitationId={}, payload={}",
xRequestID, orgId, invitationId, inlineObject1);
resourceAccessService.checkInvitationRights(orgId, invitationId);
@ -139,7 +128,7 @@ public class OrgsController implements OrgsApi {
}
@Override
public ResponseEntity<Void> assignMemberRole(
public ResponseEntity<MemberRole> assignMemberRole(
String xRequestID,
String orgId,
String userId,
@ -164,9 +153,10 @@ public class OrgsController implements OrgsApi {
String xRequestID,
String orgId,
String userId,
MemberRole memberRole) {
log.info("Expel member organization: requestId={}, orgId={}, userId={}", xRequestID, orgId, userId);
resourceAccessService.checkMemberRoleRights(orgId, userId, memberRole);
return organizationService.removeMemberRole(orgId, userId, memberRole);
String memberRoleId) {
log.info("Remove member role: requestId={}, orgId={}, userId={}, memberRoleId={}", xRequestID, orgId,
userId, memberRoleId);
resourceAccessService.checkMemberRoleRights(orgId, userId, memberRoleId);
return organizationService.removeMemberRole(orgId, userId, memberRoleId);
}
}

View File

@ -1,28 +1,21 @@
package com.rbkmoney.orgmanager.converter;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toSet;
import com.rbkmoney.orgmanager.config.properties.InviteTokenProperties;
import com.rbkmoney.orgmanager.entity.InvitationEntity;
import com.rbkmoney.orgmanager.util.JsonMapper;
import com.rbkmoney.swag.organizations.model.Invitation;
import com.rbkmoney.swag.organizations.model.InvitationAccepted;
import com.rbkmoney.swag.organizations.model.InvitationAcceptedAllOfMember;
import com.rbkmoney.swag.organizations.model.InvitationExpired;
import com.rbkmoney.swag.organizations.model.InvitationPending;
import com.rbkmoney.swag.organizations.model.InvitationRequest;
import com.rbkmoney.swag.organizations.model.InvitationRevoked;
import com.rbkmoney.swag.organizations.model.InvitationStatusName;
import com.rbkmoney.swag.organizations.model.Invitee;
import com.rbkmoney.swag.organizations.model.InviteeContact;
import com.rbkmoney.swag.organizations.model.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Optional;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.stream.Collectors;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toSet;
@Service
@RequiredArgsConstructor
@ -51,7 +44,7 @@ public class InvitationConverter {
.orElse(""))
.inviteeRoles(invitee
.map(Invitee::getRoles)
.orElse(emptySet())
.orElse(emptyList())
.stream()
.map(role -> memberRoleConverter.toEntity(role, orgId))
.collect(toSet()))
@ -97,7 +90,7 @@ public class InvitationConverter {
.roles(entity.getInviteeRoles()
.stream()
.map(memberRoleConverter::toDomain)
.collect(toSet())));
.collect(Collectors.toList())));
return invitation;
}

View File

@ -9,7 +9,7 @@ import org.springframework.stereotype.Service;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Collectors.toList;
@Service
@RequiredArgsConstructor
@ -24,7 +24,7 @@ public class MemberConverter {
.userEmail(entity.getEmail())
.roles(entity.getRoles().stream()
.map(memberRoleConverter::toDomain)
.collect(toSet()));
.collect(toList()));
}
public User toThrift(MemberEntity member) {

View File

@ -30,6 +30,7 @@ public class MemberRoleConverter {
.map(ResourceScopeId::fromValue)
.orElse(null);
return new MemberRole()
.id(entity.getId())
.roleId(RoleId.fromValue(entity.getRoleId()))
.scope(new MemberRoleScope()
.id(resourceScopeId)

View File

@ -7,7 +7,7 @@ import com.rbkmoney.swag.organizations.model.RoleId;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import static java.util.stream.Collectors.toSet;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@ -20,6 +20,6 @@ public class OrganizationRoleConverter {
.scopes(entity.getPossibleScopes()
.stream()
.map(s -> ResourceScopeId.fromValue(s.getId()))
.collect(toSet()));
.collect(Collectors.toList()));
}
}

View File

@ -1,20 +1,8 @@
package com.rbkmoney.orgmanager.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
@ -34,7 +22,7 @@ public class InvitationEntity implements Serializable {
@ToString.Exclude
@EqualsAndHashCode.Exclude
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
@JoinTable(
name = "invitation_to_member_role",
joinColumns = @JoinColumn(name = "invitation_id"),

View File

@ -1,20 +1,8 @@
package com.rbkmoney.orgmanager.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;
@ -32,7 +20,7 @@ public class MemberEntity implements Serializable {
@ToString.Exclude
@EqualsAndHashCode.Exclude
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
name = "member_to_member_role",
joinColumns = @JoinColumn(name = "member_id"),
@ -41,7 +29,7 @@ public class MemberEntity implements Serializable {
@ToString.Exclude
@EqualsAndHashCode.Exclude
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
name = "member_to_organization",
joinColumns = @JoinColumn(name = "member_id"),

View File

@ -5,6 +5,7 @@ import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Set;
@ -31,7 +32,7 @@ public class OrganizationEntity implements Serializable {
@ToString.Exclude
@EqualsAndHashCode.Exclude
@OneToMany(cascade = CascadeType.ALL)
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@Fetch(FetchMode.SUBSELECT)
@JoinColumn(name = "organizationId")
private Set<OrganizationRoleEntity> roles;

View File

@ -3,6 +3,7 @@ package com.rbkmoney.orgmanager.entity;
import lombok.*;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;
@ -21,7 +22,7 @@ public class OrganizationRoleEntity implements Serializable {
@ToString.Exclude
@EqualsAndHashCode.Exclude
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
name = "organization_role_to_scope",
joinColumns = @JoinColumn(name = "organization_role_id"),

View File

@ -0,0 +1,11 @@
package com.rbkmoney.orgmanager.service;
import com.rbkmoney.swag.organizations.model.MemberRole;
public interface MemberRoleService {
MemberRole findById(String id);
void delete(String id);
}

View File

@ -0,0 +1,31 @@
package com.rbkmoney.orgmanager.service;
import com.rbkmoney.orgmanager.converter.MemberRoleConverter;
import com.rbkmoney.orgmanager.exception.ResourceNotFoundException;
import com.rbkmoney.orgmanager.repository.MemberRoleRepository;
import com.rbkmoney.swag.organizations.model.MemberRole;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class MemberRoleServiceImpl implements MemberRoleService {
private final MemberRoleRepository repository;
private final MemberRoleConverter converter;
@Override
@Transactional(readOnly = true)
public MemberRole findById(String id) {
return repository.findById(id)
.map(converter::toDomain)
.orElseThrow(ResourceNotFoundException::new);
}
@Override
@Transactional
public void delete(String id) {
repository.deleteById(id);
}
}

View File

@ -12,13 +12,7 @@ import com.rbkmoney.orgmanager.exception.ResourceNotFoundException;
import com.rbkmoney.orgmanager.repository.InvitationRepository;
import com.rbkmoney.orgmanager.repository.MemberRepository;
import com.rbkmoney.orgmanager.repository.OrganizationRepository;
import com.rbkmoney.swag.organizations.model.InvitationStatusName;
import com.rbkmoney.swag.organizations.model.Member;
import com.rbkmoney.swag.organizations.model.MemberOrgListResult;
import com.rbkmoney.swag.organizations.model.MemberRole;
import com.rbkmoney.swag.organizations.model.Organization;
import com.rbkmoney.swag.organizations.model.OrganizationMembership;
import com.rbkmoney.swag.organizations.model.OrganizationSearchResult;
import com.rbkmoney.swag.organizations.model.*;
import lombok.RequiredArgsConstructor;
import org.hibernate.Hibernate;
import org.springframework.http.HttpStatus;
@ -47,6 +41,7 @@ public class OrganizationService {
private final MemberRoleConverter memberRoleConverter;
private final MemberRepository memberRepository;
private final InvitationRepository invitationRepository;
private final MemberRoleService memberRoleService;
@Transactional(readOnly = true)
public Optional<OrganizationEntity> findById(String orgId) {
@ -118,19 +113,19 @@ public class OrganizationService {
}
@Transactional
public ResponseEntity<Void> assignMemberRole(String orgId, String userId, MemberRole memberRole) {
public ResponseEntity<MemberRole> assignMemberRole(String orgId, String userId, MemberRole memberRole) {
Optional<MemberEntity> memberEntityOptional = memberRepository.findById(userId);
if (memberEntityOptional.isEmpty()) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.build();
}
MemberRoleEntity memberRoleEntity = memberRoleConverter.toEntity(memberRole, orgId);
memberEntityOptional.get().getRoles().add(memberRoleEntity);
return ResponseEntity.ok().build();
MemberRole assignedRole = memberRoleConverter.toDomain(memberRoleEntity);
return ResponseEntity
.status(HttpStatus.CREATED)
.body(assignedRole);
}
@Transactional
@ -149,20 +144,20 @@ public class OrganizationService {
}
@Transactional
public ResponseEntity<Void> removeMemberRole(String orgId, String userId, MemberRole memberRole) {
public ResponseEntity<Void> removeMemberRole(String orgId, String userId, String memberRoleId) {
Optional<MemberEntity> memberEntityOptional = memberRepository.findById(userId);
if (memberEntityOptional.isEmpty()) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.build();
}
memberEntityOptional.get().getRoles().removeIf(memberRoleEntity -> {
return memberRoleConverter.toDomain(memberRoleEntity).equals(memberRole);
});
return ResponseEntity.ok().build();
MemberEntity memberEntity = memberEntityOptional.get();
MemberRole memberRoleToDelete = memberRoleService.findById(memberRoleId);
memberEntity.getRoles()
.removeIf(
memberRoleEntity -> memberRoleConverter.toDomain(memberRoleEntity).equals(memberRoleToDelete));
memberRoleService.delete(memberRoleId);
return ResponseEntity.noContent().build();
}
@Transactional

View File

@ -18,6 +18,8 @@ public interface ResourceAccessService {
void checkMemberRoleRights(String orgId, String memberId, MemberRole memberRole);
void checkMemberRoleRights(String orgId, String memberId, String memberRoleId);
void checkInvitationRights(String orgId, InvitationRequest invitationRequest);
void checkInvitationRights(String orgId, String invitationId);

View File

@ -23,6 +23,7 @@ public class ResourceAccessServiceImpl implements ResourceAccessService {
private final AccessProperties accessProperties;
private final BouncerService bouncerService;
private final OrganizationService organizationService;
private final MemberRoleService memberRoleService;
@Override
public void checkRights() {
@ -137,6 +138,16 @@ public class ResourceAccessServiceImpl implements ResourceAccessService {
}
}
@Override
public void checkMemberRoleRights(String orgId, String memberId, String memberRoleId) {
if (isCheckAccessDisabled()) {
return;
}
log.info("Get member role by id {}", memberRoleId);
MemberRole memberRole = memberRoleService.findById(memberRoleId);
checkMemberRoleRights(orgId, memberId, memberRole);
}
@Override
public void checkInvitationRights(String orgId, InvitationRequest invitationRequest) {
if (isCheckAccessDisabled()) {

View File

@ -1,20 +1,65 @@
package com.rbkmoney.orgmanager.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rbkmoney.orgmanager.repository.InvitationRepository;
import com.rbkmoney.orgmanager.repository.MemberRepository;
import com.rbkmoney.orgmanager.repository.MemberRoleRepository;
import com.rbkmoney.orgmanager.repository.OrganizationRepository;
import com.rbkmoney.orgmanager.service.ResourceAccessService;
import org.junit.ClassRule;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.testcontainers.containers.PostgreSQLContainer;
import java.time.Duration;
@DirtiesContext
@Import(KeycloakTestConfig.class)
public abstract class AbstractControllerTest {
@Autowired
protected InvitationRepository invitationRepository;
@Autowired
protected OrganizationRepository organizationRepository;
@Autowired
protected MemberRepository memberRepository;
@Autowired
protected MemberRoleRepository memberRoleRepository;
@SpyBean
protected ResourceAccessService resourceAccessService;
@Autowired
private PlatformTransactionManager transactionManager;
@Autowired
private TransactionTemplate transactionTemplate;
@BeforeEach
public void setUp() throws Exception {
keycloakOpenIdStub.givenStub();
withTransaction(() -> {
invitationRepository.deleteAll();
organizationRepository.deleteAll();
memberRepository.deleteAll();
memberRoleRepository.deleteAll();
});
}
@ClassRule
@SuppressWarnings("rawtypes")
public static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:9.6")
@ -36,7 +81,13 @@ public abstract class AbstractControllerTest {
}
@Autowired
private KeycloakOpenIdStub keycloakOpenIdStub;
protected KeycloakOpenIdStub keycloakOpenIdStub;
@Autowired
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
protected String generateJwt(long iat, long exp, String... roles) {
return keycloakOpenIdStub.generateJwt(iat, exp, roles);
@ -50,4 +101,19 @@ public abstract class AbstractControllerTest {
return keycloakOpenIdStub.getUserId();
}
protected void withTransaction(Runnable runnable){
if (TransactionSynchronizationManager.isActualTransactionActive()) {
runnable.run();
return;
}
transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
runnable.run();
}
});
}
}

View File

@ -1,50 +1,41 @@
package com.rbkmoney.orgmanager.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rbkmoney.orgmanager.OrgManagerApplication;
import com.rbkmoney.orgmanager.TestObjectFactory;
import com.rbkmoney.orgmanager.entity.MemberEntity;
import com.rbkmoney.orgmanager.entity.MemberRoleEntity;
import com.rbkmoney.orgmanager.entity.OrganizationEntity;
import com.rbkmoney.orgmanager.exception.AccessDeniedException;
import com.rbkmoney.orgmanager.repository.InvitationRepositoryTest;
import com.rbkmoney.orgmanager.repository.MemberRepository;
import com.rbkmoney.orgmanager.repository.OrganizationRepository;
import com.rbkmoney.orgmanager.service.OrganizationService;
import com.rbkmoney.orgmanager.service.ResourceAccessService;
import com.rbkmoney.orgmanager.util.TestData;
import com.rbkmoney.swag.organizations.model.InvitationRequest;
import com.rbkmoney.swag.organizations.model.MemberRole;
import com.rbkmoney.swag.organizations.model.OrganizationMembership;
import com.rbkmoney.swag.organizations.model.RoleId;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsAnything.anything;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doThrow;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = {OrgManagerApplication.class, UserController.class})
@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = InvitationRepositoryTest.Initializer.class)
@AutoConfigureMockMvc
@AutoConfigureWireMock(port = 0)
@ -55,38 +46,8 @@ public class OrgsControllerTest extends AbstractControllerTest {
public static final String MEMBER_ID = "L6Mc2la1D9Rg";
public static final String MEMBER_ROLE_ID = "D3KwP29McT";
@Autowired
private MockMvc mockMvc;
@Autowired
private OrganizationRepository organizationRepository;
@Autowired
private MemberRepository memberRepository;
@Autowired
private KeycloakOpenIdStub keycloakOpenIdStub;
@Autowired
private ObjectMapper objectMapper;
@SpyBean
private OrganizationService organizationService;
@SpyBean
private ResourceAccessService resourceAccessService;
@Before
public void setUp() throws Exception {
keycloakOpenIdStub.givenStub();
OrganizationEntity organizationEntity = TestData.buildOrganization(ORGANIZATION_ID, MEMBER_ID);
organizationRepository.save(organizationEntity);
}
@Test
public void expelOrgMemberWithoutAccess() throws Exception {
void expelOrgMemberWithoutAccess() throws Exception {
doThrow(new AccessDeniedException("Access denied")).when(resourceAccessService)
.checkMemberRights(ORGANIZATION_ID, MEMBER_ID);
@ -98,12 +59,12 @@ public class OrgsControllerTest extends AbstractControllerTest {
}
@Test
public void assignMemberRoleWithoutAccess() throws Exception {
void assignMemberRoleWithoutAccess() throws Exception {
MemberRole memberRole = TestData.buildMemberRole();
doThrow(new AccessDeniedException("Access denied")).when(resourceAccessService)
.checkMemberRoleRights(ORGANIZATION_ID, MEMBER_ID, memberRole);
mockMvc.perform(put(String.format("/orgs/%s/members/%s/roles", ORGANIZATION_ID, MEMBER_ID))
mockMvc.perform(post(String.format("/orgs/%s/members/%s/roles", ORGANIZATION_ID, MEMBER_ID))
.contentType("application/json")
.content(objectMapper.writeValueAsString(memberRole))
.header("Authorization", "Bearer " + generateRBKadminJwt())
@ -112,64 +73,76 @@ public class OrgsControllerTest extends AbstractControllerTest {
}
@Test
public void assignMemberRoleTest() throws Exception {
void assignMemberRoleTest() throws Exception {
OrganizationEntity organizationEntity = TestData.buildOrganization(ORGANIZATION_ID, MEMBER_ID);
organizationRepository.save(organizationEntity);
MemberEntity memberEntity = TestObjectFactory.testMemberEntity(TestObjectFactory.randomString());
OrganizationEntity organization = TestObjectFactory.buildOrganization(memberEntity);
MemberRoleEntity savedMemberRole = memberRoleRepository.save(TestObjectFactory.buildMemberRole(RoleId.ACCOUNTANT, organization.getId()));
memberEntity.setRoles(Set.of(savedMemberRole));
MemberEntity savedMember = memberRepository.save(memberEntity);
OrganizationEntity savedOrganization = organizationRepository.save(organization);
MemberRole memberRole = TestData.buildMemberRole();
mockMvc.perform(put(String.format("/orgs/%s/members/%s/roles", ORGANIZATION_ID, MEMBER_ID))
mockMvc.perform(post(String.format("/orgs/%s/members/%s/roles", savedOrganization.getId(), savedMember.getId()))
.contentType("application/json")
.content(objectMapper.writeValueAsString(memberRole))
.header("Authorization", "Bearer " + generateRBKadminJwt())
.header("X-Request-ID", "testRequestId")
).andExpect(status().isOk());
.header("X-Request-ID", "testRequestId"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").isNotEmpty())
.andExpect(jsonPath("$.roleId", equalTo(memberRole.getRoleId().getValue())))
.andExpect(jsonPath("$.scope.id", equalTo(memberRole.getScope().getId().getValue())))
.andExpect(jsonPath("$.scope.resourceId", equalTo(memberRole.getScope().getResourceId())));
OrganizationMembership organizationMembership =
organizationService.getMembership(ORGANIZATION_ID, MEMBER_ID, "email").getBody();
Assert.assertTrue(organizationMembership.getMember().getRoles()
.stream().anyMatch(role -> role.getRoleId() == RoleId.ADMINISTRATOR));
Optional<MemberRole> memberRoleOptional = organizationMembership.getMember().getRoles().stream()
.filter(role -> role.getRoleId() == RoleId.ADMINISTRATOR)
.findFirst();
Assert.assertTrue(memberRoleOptional.isPresent());
Assert.assertEquals(memberRole.getScope().getId(), memberRoleOptional.get().getScope().getId());
Assert.assertEquals(memberRole.getScope().getResourceId(), memberRoleOptional.get().getScope().getResourceId());
assertFalse(memberRoleRepository.findAll().isEmpty());
}
@Test
public void expelOrgMemberTest() throws Exception {
mockMvc.perform(delete(String.format("/orgs/%s/members/%s", ORGANIZATION_ID, MEMBER_ID))
@Transactional
void expelOrgMemberTest() throws Exception {
MemberEntity savedMember = memberRepository.save(TestObjectFactory.testMemberEntity(TestObjectFactory.randomString()));
OrganizationEntity savedOrganization = organizationRepository.save(TestObjectFactory.buildOrganization(savedMember));
mockMvc.perform(delete(String.format("/orgs/%s/members/%s", savedOrganization.getId(), savedMember.getId()))
.contentType("application/json")
.header("Authorization", "Bearer " + generateRBKadminJwt())
.header("X-Request-ID", "testRequestId")
).andExpect(status().isOk());
.header("X-Request-ID", "testRequestId"))
.andExpect(status().isOk());
Optional<OrganizationEntity> organizationEntityOptional = organizationService.findById(ORGANIZATION_ID);
Assert.assertTrue(organizationEntityOptional.isPresent());
Assert.assertFalse(organizationEntityOptional.get().getMembers().stream()
Optional<OrganizationEntity> organizationEntityOptional = organizationRepository.findById(savedOrganization.getId());
assertTrue(organizationEntityOptional.isPresent());
assertFalse(organizationEntityOptional.get().getMembers().stream()
.anyMatch(memberEntity -> memberEntity.getId().equals(MEMBER_ID)));
}
@Test
public void removeMemberRoleTest() throws Exception {
MemberRole memberRole = TestData.buildMemberRole();
mockMvc.perform(delete(String.format("/orgs/%s/members/%s/roles", ORGANIZATION_ID, MEMBER_ID))
.contentType("application/json")
.content(objectMapper.writeValueAsString(memberRole))
.header("Authorization", "Bearer " + generateRBKadminJwt())
.header("X-Request-ID", "testRequestId")
).andExpect(status().isOk());
@Transactional
void removeMemberRoleTest() throws Exception {
MemberEntity memberEntity = TestObjectFactory.testMemberEntity(TestObjectFactory.randomString());
OrganizationEntity organization = TestObjectFactory.buildOrganization(memberEntity);
MemberRoleEntity savedMemberRole = memberRoleRepository.save(TestObjectFactory.buildMemberRole(RoleId.ACCOUNTANT, organization.getId()));
memberEntity.setRoles(Set.of(savedMemberRole));
MemberEntity savedMember = memberRepository.save(memberEntity);
OrganizationEntity savedOrganization = organizationRepository.save(organization);
Optional<OrganizationEntity> organizationEntityOptional = organizationService.findById(ORGANIZATION_ID);
Assert.assertTrue(organizationEntityOptional.isPresent());
Optional<MemberEntity> memberEntityOptional = organizationEntityOptional.get().getMembers().stream()
.filter(memberEntity -> memberEntity.getId().equals(MEMBER_ID))
.findFirst();
Assert.assertTrue(memberEntityOptional.isPresent());
Assert.assertFalse(memberEntityOptional.get().getRoles().stream()
.anyMatch(memberRoleEntity -> memberRoleEntity.getId().equals(MEMBER_ID)));
mockMvc.perform(delete(String.format("/orgs/%s/members/%s/roles/%s", savedOrganization.getId(), savedMember.getId(), savedMemberRole.getId()))
.contentType("application/json")
.header("Authorization", "Bearer " + generateRBKadminJwt())
.header("X-Request-ID", "testRequestId")).
andExpect(status().isNoContent());
assertTrue(memberRoleRepository.findAll().isEmpty());
assertThat(memberRepository.findById(savedMember.getId()).get().getRoles(), not(hasItem(savedMemberRole)));
}
@Test
public void createInvitationWithoutAccess() throws Exception {
void createInvitationWithoutAccess() throws Exception {
OrganizationEntity organizationEntity = TestData.buildOrganization(ORGANIZATION_ID, MEMBER_ID);
organizationRepository.save(organizationEntity);
InvitationRequest invitation = TestData.buildInvitationRequest();
String body = objectMapper.writeValueAsString(invitation);
@ -185,7 +158,9 @@ public class OrgsControllerTest extends AbstractControllerTest {
}
@Test
public void createInvitationTest() throws Exception {
void createInvitationTest() throws Exception {
OrganizationEntity organizationEntity = TestData.buildOrganization(ORGANIZATION_ID, MEMBER_ID);
organizationRepository.save(organizationEntity);
InvitationRequest invitation = TestData.buildInvitationRequest();
String body = objectMapper.writeValueAsString(invitation);
@ -193,17 +168,20 @@ public class OrgsControllerTest extends AbstractControllerTest {
.contentType("application/json")
.content(body)
.header("Authorization", "Bearer " + generateRBKadminJwt())
.header("X-Request-ID", "testRequestId")
).andExpect(jsonPath("$.status", is("Pending")));
.header("X-Request-ID", "testRequestId"))
.andExpect(jsonPath("$.status", is("Pending")));
}
@Test
public void listOrgMembersTest() throws Exception {
mockMvc.perform(get(String.format("/orgs/%s/members", ORGANIZATION_ID))
void listOrgMembersTest() throws Exception {
MemberEntity savedMember = memberRepository.save(TestObjectFactory.testMemberEntity(TestObjectFactory.randomString()));
OrganizationEntity savedOrganization = organizationRepository.save(TestObjectFactory.buildOrganization(savedMember));
mockMvc.perform(get(String.format("/orgs/%s/members", savedOrganization.getId()))
.contentType("application/json")
.header("Authorization", "Bearer " + generateRBKadminJwt())
.header("X-Request-ID", "testRequestId")
).andExpect(status().isOk())
.header("X-Request-ID", "testRequestId"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.result", anything()));
}

View File

@ -1,32 +1,20 @@
package com.rbkmoney.orgmanager.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rbkmoney.orgmanager.OrgManagerApplication;
import com.rbkmoney.orgmanager.entity.InvitationEntity;
import com.rbkmoney.orgmanager.entity.MemberEntity;
import com.rbkmoney.orgmanager.entity.OrganizationEntity;
import com.rbkmoney.orgmanager.exception.AccessDeniedException;
import com.rbkmoney.orgmanager.exception.ResourceNotFoundException;
import com.rbkmoney.orgmanager.repository.InvitationRepository;
import com.rbkmoney.orgmanager.repository.InvitationRepositoryTest;
import com.rbkmoney.orgmanager.repository.MemberRepository;
import com.rbkmoney.orgmanager.repository.OrganizationRepository;
import com.rbkmoney.orgmanager.service.ResourceAccessService;
import com.rbkmoney.swag.organizations.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.transaction.annotation.Transactional;
@ -35,6 +23,7 @@ import java.util.Set;
import static com.rbkmoney.orgmanager.TestObjectFactory.*;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.doThrow;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@ -43,44 +32,14 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = {OrgManagerApplication.class, UserController.class})
@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = InvitationRepositoryTest.Initializer.class)
@AutoConfigureMockMvc
@AutoConfigureWireMock(port = 0)
@TestPropertySource(locations = "classpath:wiremock.properties")
public class UserControllerTest extends AbstractControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private InvitationRepository invitationRepository;
@Autowired
private OrganizationRepository organizationRepository;
@Autowired
private MemberRepository memberRepository;
@Autowired
private KeycloakOpenIdStub keycloakOpenIdStub;
@SpyBean
private ResourceAccessService resourceAccessService;
@Before
public void setUp() throws Exception {
keycloakOpenIdStub.givenStub();
invitationRepository.deleteAll();
organizationRepository.deleteAll();
memberRepository.deleteAll();
}
@Test
public void joinOrgTestWithResourceNotFound() throws Exception {
void joinOrgTestWithResourceNotFound() throws Exception {
OrganizationJoinRequest organizationJoinRequest = new OrganizationJoinRequest();
organizationJoinRequest.setInvitation(randomString());
doThrow(new ResourceNotFoundException()).when(resourceAccessService)
@ -95,7 +54,7 @@ public class UserControllerTest extends AbstractControllerTest {
}
@Test
public void joinOrgTestWithoutAccess() throws Exception {
void joinOrgTestWithoutAccess() throws Exception {
OrganizationJoinRequest organizationJoinRequest = new OrganizationJoinRequest();
organizationJoinRequest.setInvitation(randomString());
doThrow(new AccessDeniedException("Access denied")).when(resourceAccessService)
@ -110,7 +69,7 @@ public class UserControllerTest extends AbstractControllerTest {
}
@Test
public void joinOrgTest() throws Exception {
void joinOrgTest() throws Exception {
String jwtToken = generateRBKadminJwt();
String userId = getUserFromToken();
OrganizationEntity savedOrg = organizationRepository.save(buildOrganization());
@ -122,25 +81,26 @@ public class UserControllerTest extends AbstractControllerTest {
.contentType("application/json")
.content(objectMapper.writeValueAsString(organizationJoinRequest))
.header("Authorization", "Bearer " + jwtToken)
.header("X-Request-ID", "testRequestId")
).andExpect(status().isOk()).andReturn();
.header("X-Request-ID", "testRequestId"))
.andExpect(status().isOk())
.andReturn();
OrganizationMembership organizationMembership = objectMapper.readValue(
mvcResult.getResponse().getContentAsString(), OrganizationMembership.class);
Assert.assertEquals(savedOrg.getId(), organizationMembership.getOrg().getId());
Assert.assertEquals(userId, organizationMembership.getMember().getId());
Assert.assertTrue(organizationMembership.getMember().getRoles().stream()
assertEquals(savedOrg.getId(), organizationMembership.getOrg().getId());
assertEquals(userId, organizationMembership.getMember().getId());
assertTrue(organizationMembership.getMember().getRoles().stream()
.anyMatch(memberRole -> memberRole.getRoleId() == RoleId.ADMINISTRATOR));
Assert.assertTrue(organizationMembership.getMember().getRoles().stream()
assertTrue(organizationMembership.getMember().getRoles().stream()
.anyMatch(memberRole -> memberRole.getRoleId() == RoleId.ACCOUNTANT));
InvitationEntity invitationEntity = invitationRepository.findById(savedInvitation.getId()).get();
Assert.assertEquals(invitationEntity.getStatus(), InvitationStatusName.ACCEPTED.getValue());
assertEquals(invitationEntity.getStatus(), InvitationStatusName.ACCEPTED.getValue());
}
@Test
@Transactional
public void cancelOrgMembershipTest() throws Exception {
void cancelOrgMembershipTest() throws Exception {
String jwtToken = generateRBKadminJwt();
String userId = getUserFromToken();
MemberEntity member = memberRepository.save(testMemberEntity(userId));
@ -149,15 +109,15 @@ public class UserControllerTest extends AbstractControllerTest {
mockMvc.perform(delete("/user/membership/{orgId}", orgWithMember.getId())
.accept(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + jwtToken)
.header("X-Request-ID", "testRequestId")
).andExpect(status().isOk());
.header("X-Request-ID", "testRequestId"))
.andExpect(status().isOk());
OrganizationEntity organizationEntity = organizationRepository.findById(orgWithMember.getId()).get();
Assert.assertFalse(organizationEntity.getMembers().contains(member));
assertFalse(organizationEntity.getMembers().contains(member));
}
@Test
public void inquireOrgMembershipTest() throws Exception {
void inquireOrgMembershipTest() throws Exception {
String jwtToken = generateRBKadminJwt();
String userId = getUserFromToken();
MemberEntity member = memberRepository.save(testMemberEntity(userId));
@ -176,7 +136,7 @@ public class UserControllerTest extends AbstractControllerTest {
}
@Test
public void listOrgMembershipWithoutLimitTest() throws Exception {
void listOrgMembershipWithoutLimitTest() throws Exception {
String jwtToken = generateRBKadminJwt();
String userId = getUserFromToken();
MemberEntity targetMember = memberRepository.save(testMemberEntity(userId));
@ -186,16 +146,17 @@ public class UserControllerTest extends AbstractControllerTest {
MvcResult mvcResultFirst = mockMvc.perform(get("/user/membership")
.accept(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + jwtToken)
.header("X-Request-ID", "testRequestId")
).andExpect(status().isOk()).andReturn();
.header("X-Request-ID", "testRequestId"))
.andExpect(status().isOk())
.andReturn();
OrganizationSearchResult organizationSearchResult = objectMapper.readValue(
mvcResultFirst.getResponse().getContentAsString(), OrganizationSearchResult.class);
Assert.assertEquals(7, organizationSearchResult.getResult().size());
assertEquals(7, organizationSearchResult.getResult().size());
}
@Test
public void listOrgMembershipTest() throws Exception {
void listOrgMembershipTest() throws Exception {
String jwtToken = generateRBKadminJwt();
String userId = getUserFromToken();
MemberEntity targetMember = memberRepository.save(testMemberEntity(userId));
@ -211,37 +172,40 @@ public class UserControllerTest extends AbstractControllerTest {
.queryParam("limit", limit)
.accept(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + jwtToken)
.header("X-Request-ID", "testRequestId")
).andExpect(status().isOk()).andReturn();
.header("X-Request-ID", "testRequestId"))
.andExpect(status().isOk())
.andReturn();
OrganizationSearchResult organizationSearchResultFirst = objectMapper.readValue(
mvcResultFirst.getResponse().getContentAsString(), OrganizationSearchResult.class);
Assert.assertEquals(4, organizationSearchResultFirst.getResult().size());
assertEquals(4, organizationSearchResultFirst.getResult().size());
MvcResult mvcResultSecond = mockMvc.perform(get("/user/membership")
.queryParam("limit", limit)
.queryParam("continuationToken", organizationSearchResultFirst.getContinuationToken())
.accept(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + jwtToken)
.header("X-Request-ID", "testRequestId")
).andExpect(status().isOk()).andReturn();
.header("X-Request-ID", "testRequestId"))
.andExpect(status().isOk())
.andReturn();
OrganizationSearchResult organizationSearchResultSecond = objectMapper.readValue(
mvcResultSecond.getResponse().getContentAsString(), OrganizationSearchResult.class);
Assert.assertEquals(4, organizationSearchResultSecond.getResult().size());
assertEquals(4, organizationSearchResultSecond.getResult().size());
MvcResult mvcResultThird = mockMvc.perform(get("/user/membership")
.queryParam("limit", limit)
.queryParam("continuationToken", organizationSearchResultSecond.getContinuationToken())
.accept(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + jwtToken)
.header("X-Request-ID", "testRequestId")
).andExpect(status().isOk()).andReturn();
.header("X-Request-ID", "testRequestId"))
.andExpect(status().isOk())
.andReturn();
OrganizationSearchResult organizationSearchResultThird = objectMapper.readValue(
mvcResultThird.getResponse().getContentAsString(), OrganizationSearchResult.class);
Assert.assertEquals(2, organizationSearchResultThird.getResult().size());
Assert.assertNull(organizationSearchResultThird.getContinuationToken());
assertEquals(2, organizationSearchResultThird.getResult().size());
assertNull(organizationSearchResultThird.getContinuationToken());
}
}

View File

@ -8,10 +8,10 @@ import com.rbkmoney.orgmanager.util.JsonMapper;
import com.rbkmoney.swag.organizations.model.*;
import org.junit.Before;
import org.junit.Test;
import org.openapitools.jackson.nullable.JsonNullable;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -50,7 +50,7 @@ public class InvitationConverterTest {
.contact(new InviteeContact()
.type(InviteeContact.TypeEnum.EMAIL)
.email("email"))
.roles(Set.of(new MemberRole())))
.roles(List.of(new MemberRole())))
.metadata(Map.of("a", "b"));
// When
@ -100,7 +100,7 @@ public class InvitationConverterTest {
.contact(new InviteeContact()
.type(InviteeContact.TypeEnum.EMAIL)
.email("email"))
.roles(Set.of(new MemberRole())))
.roles(List.of(new MemberRole())))
.acceptToken("token")
.metadata(Map.of("a", "b"));
expected.setStatus(InvitationStatusName.PENDING);

View File

@ -4,11 +4,13 @@ import com.rbkmoney.bouncer.context.v1.User;
import com.rbkmoney.orgmanager.entity.MemberEntity;
import com.rbkmoney.orgmanager.entity.MemberRoleEntity;
import com.rbkmoney.orgmanager.entity.OrganizationEntity;
import com.rbkmoney.swag.organizations.model.*;
import com.rbkmoney.swag.organizations.model.Member;
import com.rbkmoney.swag.organizations.model.MemberRole;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
@ -48,7 +50,7 @@ public class MemberConverterTest {
Member expected = new Member()
.id("id")
.userEmail("email")
.roles(Set.of(new MemberRole()));
.roles(List.of(new MemberRole()));
assertThat(member).isEqualToComparingFieldByField(expected);
}

View File

@ -76,6 +76,7 @@ public class MemberRoleConverterTest {
// Then
MemberRole expected = new MemberRole()
.id(entity.getId())
.roleId(RoleId.ADMINISTRATOR)
.scope(new MemberRoleScope());
@ -98,6 +99,7 @@ public class MemberRoleConverterTest {
// Then
MemberRole expected = new MemberRole()
.id(entity.getId())
.roleId(RoleId.ADMINISTRATOR)
.scope(new MemberRoleScope()
.resourceId("resource")

View File

@ -8,6 +8,7 @@ import com.rbkmoney.swag.organizations.model.RoleId;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
@ -41,7 +42,7 @@ public class OrganizationRoleConverterTest {
Role expected = new Role()
.id(RoleId.ADMINISTRATOR)
.name("name")
.scopes(Set.of(ResourceScopeId.SHOP));
.scopes(List.of(ResourceScopeId.SHOP));
assertThat(role).isEqualToComparingFieldByField(expected);
}

View File

@ -19,9 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.*;
@ExtendWith(SpringExtension.class)
class ResourceAccessServiceImplTest {
@ -31,6 +29,8 @@ class ResourceAccessServiceImplTest {
private BouncerService bouncerService;
@Mock
private OrganizationService organizationService;
@Mock
private MemberRoleService memberRoleService;
private ResourceAccessService resourceAccessService;
@ -38,7 +38,7 @@ class ResourceAccessServiceImplTest {
void setUp() {
accessProperties = new AccessProperties();
accessProperties.setEnabled(true);
resourceAccessService = new ResourceAccessServiceImpl(accessProperties, bouncerService, organizationService);
resourceAccessService = new ResourceAccessServiceImpl(accessProperties, bouncerService, organizationService, memberRoleService);
}
@Test
@ -177,6 +177,18 @@ class ResourceAccessServiceImplTest {
verify(bouncerService, times(0)).havePrivileges(any(BouncerContextDto.class));
}
@Test
void checkMemberRoleRightsWithoutRequestedResource() {
String orgId = TestObjectFactory.randomString();
String memberId = TestObjectFactory.randomString();
String memberRoleId = TestObjectFactory.randomString();
when(memberRoleService.findById(memberRoleId))
.thenThrow(new ResourceNotFoundException());
assertThrows(ResourceNotFoundException.class,
() -> resourceAccessService.checkMemberRoleRights(orgId,memberId, memberRoleId));
}
@Test
void checkMemberRoleRightsWithoutAccess() {
String orgId = TestObjectFactory.randomString();

View File

@ -4,18 +4,13 @@ import com.rbkmoney.orgmanager.entity.InvitationEntity;
import com.rbkmoney.orgmanager.entity.MemberEntity;
import com.rbkmoney.orgmanager.entity.MemberRoleEntity;
import com.rbkmoney.orgmanager.entity.OrganizationEntity;
import com.rbkmoney.swag.organizations.model.InvitationRequest;
import com.rbkmoney.swag.organizations.model.Invitee;
import com.rbkmoney.swag.organizations.model.InviteeContact;
import com.rbkmoney.swag.organizations.model.MemberRole;
import com.rbkmoney.swag.organizations.model.MemberRoleScope;
import com.rbkmoney.swag.organizations.model.ResourceScopeId;
import com.rbkmoney.swag.organizations.model.RoleId;
import com.rbkmoney.swag.organizations.model.*;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -86,7 +81,7 @@ public class TestData {
inviteeContact.setType(InviteeContact.TypeEnum.EMAIL);
invitee.setContact(inviteeContact);
invitee.setRoles(Set.of(buildMemberRole()));
invitee.setRoles(List.of(buildMemberRole()));
invitation.setInvitee(invitee);
Map<String, String> metadata = new HashMap<>();