Merge branch 'tests' into 'dev'

Added DeviceService tests possibly breaking everything

See merge request sa4-2020/the-sanmarinoes/backend!150
This commit is contained in:
Claudio Maggioni 2020-05-19 14:38:52 +02:00
commit 90ec64469b
5 changed files with 141 additions and 114 deletions

View file

@ -6,28 +6,40 @@ import java.util.HashSet;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import javax.persistence.*; import javax.persistence.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/** A user of the Smarthut application */ /** A user of the Smarthut application */
@Entity(name = "smarthutuser") @Entity(name = "smarthutuser")
@ToString
public class User { public class User {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false, unique = true) @Column(name = "id", updatable = false, nullable = false, unique = true)
@ApiModelProperty(hidden = true) @ApiModelProperty(hidden = true)
@Getter
@Setter
private Long id; private Long id;
/** The full name of the user */ /** The full name of the user */
@Column(nullable = false) @Column(nullable = false)
@Getter
@Setter
private String name; private String name;
/** The full username of the user */ /** The full username of the user */
@Column(nullable = false, unique = true) @Column(nullable = false, unique = true)
@Getter
@Setter
private String username; private String username;
/** A properly salted way to store the password */ /** A properly salted way to store the password */
@Column(nullable = false) @Column(nullable = false)
@GsonExclude @GsonExclude
@Getter
@Setter
private String password; private String password;
/** /**
@ -35,11 +47,15 @@ public class User {
* </code>, technically not RFC 5322 compliant * </code>, technically not RFC 5322 compliant
*/ */
@Column(nullable = false, unique = true) @Column(nullable = false, unique = true)
@Getter
@Setter
private String email; private String email;
/** Guests invited by this user */ /** Guests invited by this user */
@ManyToMany(mappedBy = "hosts", cascade = CascadeType.DETACH) @ManyToMany(mappedBy = "hosts", cascade = CascadeType.DETACH)
@GsonExclude @GsonExclude
@Getter
@ToString.Exclude
private Set<User> guests = new HashSet<>(); private Set<User> guests = new HashSet<>();
@ManyToMany(cascade = CascadeType.DETACH) @ManyToMany(cascade = CascadeType.DETACH)
@ -48,74 +64,34 @@ public class User {
joinColumns = @JoinColumn(name = "guest_id"), joinColumns = @JoinColumn(name = "guest_id"),
inverseJoinColumns = @JoinColumn(name = "host_id")) inverseJoinColumns = @JoinColumn(name = "host_id"))
@GsonExclude @GsonExclude
@Getter
@ToString.Exclude
private Set<User> hosts = new HashSet<>(); private Set<User> hosts = new HashSet<>();
/** Determines whether a guest can access security cameras */ /** Determines whether a guest can access security cameras */
@Column(nullable = false) @Column(nullable = false)
@Getter
@Setter
private boolean cameraEnabled; private boolean cameraEnabled;
@Column(nullable = false) @Column(nullable = false)
@GsonExclude @GsonExclude
@Getter
@Setter
private boolean isEnabled = false; private boolean isEnabled = false;
public Long getId() { @Override
return id; public int hashCode() {
if (id == null) return Integer.MAX_VALUE;
return (int) (id % Integer.MAX_VALUE);
} }
public void setId(Long id) { @Override
this.id = id; public boolean equals(Object o) {
} if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
public String getName() { User user = (User) o;
return name; return Objects.equals(id, user.id);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean getEnabled() {
return isEnabled;
}
public void setEnabled(boolean enabled) {
isEnabled = enabled;
}
public Set<User> getGuests() {
return guests;
}
public Set<User> getHosts() {
return hosts;
}
public boolean isCameraEnabled() {
return cameraEnabled;
} }
public void addGuest(User guest) { public void addGuest(User guest) {
@ -125,54 +101,4 @@ public class User {
public void addHost(User host) { public void addHost(User host) {
this.hosts.add(host); this.hosts.add(host);
} }
public void removeGuest(User guest) {
this.guests.remove(guest);
}
public void setCameraEnabled(boolean cameraEnabled) {
this.cameraEnabled = cameraEnabled;
}
@Override
public String toString() {
return "User{id="
+ id
+ ", name='"
+ name
+ '\''
+ ", username='"
+ username
+ '\''
+ ", password='"
+ password
+ '\''
+ ", email='"
+ email
+ '\''
+ ", cameraEnabled="
+ cameraEnabled
+ ", isEnabled="
+ isEnabled
+ '}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return cameraEnabled == user.cameraEnabled
&& isEnabled == user.isEnabled
&& Objects.equals(id, user.id)
&& Objects.equals(name, user.name)
&& Objects.equals(username, user.username)
&& Objects.equals(password, user.password)
&& Objects.equals(email, user.email);
}
@Override
public int hashCode() {
return Objects.hash(id, name, username, password, email, isEnabled, cameraEnabled);
}
} }

View file

@ -16,7 +16,7 @@ public class JWTUserDetailsService implements UserDetailsService {
@Override @Override
public UserDetails loadUserByUsername(String username) { public UserDetails loadUserByUsername(String username) {
User toReturn = repository.findByUsername(username); User toReturn = repository.findByUsername(username);
if (toReturn != null && toReturn.getEnabled()) { if (toReturn != null && toReturn.isEnabled()) {
return new org.springframework.security.core.userdetails.User( return new org.springframework.security.core.userdetails.User(
toReturn.getUsername(), toReturn.getPassword(), Set.of()); toReturn.getUsername(), toReturn.getPassword(), Set.of());
} else { } else {

View file

@ -56,7 +56,7 @@ public abstract class SmartHutTest {
assertThat(res3).isNotNull(); assertThat(res3).isNotNull();
assertThat(res3.getStatusCode()).isEqualTo(HttpStatus.FOUND); assertThat(res3.getStatusCode()).isEqualTo(HttpStatus.FOUND);
assertThat(userRepository.findByUsername("enabled").getEnabled()).isTrue(); assertThat(userRepository.findByUsername("enabled").isEnabled()).isTrue();
} }
@BeforeEach @BeforeEach

View file

@ -20,7 +20,7 @@ public class UserTests {
@Test @Test
@DisplayName("get and set id") @DisplayName("get and set id")
public void getAndSetId() { public void getAndSetId() {
user.setId(20l); user.setId(20L);
assertEquals(20, user.getId()); assertEquals(20, user.getId());
} }
@ -62,7 +62,7 @@ public class UserTests {
public void getAndSetEnabled() { public void getAndSetEnabled() {
user.setEnabled(true); user.setEnabled(true);
assertTrue(user.getEnabled()); assertTrue(user.isEnabled());
} }
@Test @Test
@ -76,8 +76,8 @@ public class UserTests {
@Test @Test
@DisplayName("equals") @DisplayName("equals")
public void eq() { public void eq() {
assertFalse(user.equals(null)); assertNotEquals(null, user);
assertTrue(user.equals(user)); assertEquals(user, user);
} }
} }

View file

@ -1,8 +1,8 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.service; package ch.usi.inf.sa4.sanmarinoes.smarthut.service;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.doNothing; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
@ -136,4 +137,104 @@ public class DeviceServiceTests {
assertThat(deviceService.saveAsGuest(t, "user", 1L)).isEqualTo(t); assertThat(deviceService.saveAsGuest(t, "user", 1L)).isEqualTo(t);
} }
@Test
public void testDeleteIdAsOwner() {
try {
doNothing().when(devicePropagationService).deleteByIdAsOwner(1L, "user");
deviceService.deleteByIdAsOwner(1L, "user");
} catch (NotFoundException e) {
fail(e.getMessage());
}
}
@Test
public void populateComputedFields() {
doNothing().when(devicePopulationService).populateComputedFields(List.of());
deviceService.populateComputedFields(List.of());
}
@Test
public void testSaveAllAsOwner() {
final DeviceService currentDeviceService = Mockito.spy(deviceService);
List<Device> devices = List.of(new RegularLight(), new ButtonDimmer());
when(devicePropagationService.saveAllAsOwner(
eq(devices), eq("user"), anyBoolean(), eq(false)))
.thenReturn(devices);
final int[] count = new int[1];
doAnswer(i -> count[0]++)
.when(currentDeviceService)
.triggerTriggers(any(Device.class), eq("user"));
currentDeviceService.saveAllAsOwner(devices, "user", true, false);
assertThat(count[0]).isEqualTo(0);
currentDeviceService.saveAllAsOwner(devices, "user", false, false);
assertThat(count[0]).isEqualTo(2);
}
@Test
public void testSaveAsOwner() {
final DeviceService currentDeviceService = Mockito.spy(deviceService);
Device device = new ButtonDimmer();
final boolean[] count = new boolean[1];
doAnswer(i -> count[0] = true).when(currentDeviceService).triggerTriggers(device, "user");
when(devicePropagationService.saveAsOwner(device, "user")).thenReturn(device);
assertThat(currentDeviceService.saveAsOwner(device, "user")).isEqualTo(device);
assertThat(count[0]).isTrue();
}
@Test
public void testFindAll() throws NotFoundException {
final DeviceService currentDeviceService = Mockito.spy(deviceService);
final SecurityCamera gerryScotti = new SecurityCamera();
doNothing().when(currentDeviceService).throwIfRoomNotOwned(1L, "user");
doNothing().when(devicePopulationService).populateComputedFields(any());
when(deviceRepository.findByRoomId(1L)).thenReturn(List.of(gerryScotti));
when(deviceRepository.findAllByUsername("user")).thenReturn(List.of(gerryScotti));
final User user = new User();
user.setUsername("user");
user.setEmail("user@example.com");
user.setName("User");
user.setId(1L);
user.setCameraEnabled(true);
final User guest = new User();
guest.setUsername("guest");
guest.setEmail("guest@example.com");
guest.setName("Guest");
guest.setId(2L);
guest.getHosts().add(user);
user.getGuests().add(guest);
when(userRepository.findByUsername("guest")).thenReturn(guest);
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
when(userRepository.findById(3L)).thenReturn(Optional.empty());
final Room r = new Room();
r.setUserId(1L);
when(roomRepository.findById(1L)).thenReturn(Optional.of(r));
when(roomRepository.findById(3L)).thenReturn(Optional.empty());
assertThat(currentDeviceService.findAll(1L, null, "user")).containsExactly(gerryScotti);
assertThat(currentDeviceService.findAll(null, "user")).containsExactly(gerryScotti);
assertThatThrownBy(() -> currentDeviceService.findAll(1L, 3L, "guest"))
.isInstanceOf(NotFoundException.class);
assertThatThrownBy(() -> currentDeviceService.findAll(3L, 1L, "guest"))
.isInstanceOf(NotFoundException.class);
assertThat(currentDeviceService.findAll(1L, 1L, "guest")).containsExactly(gerryScotti);
user.setCameraEnabled(false);
assertThat(currentDeviceService.findAll(1L, 1L, "guest")).isEmpty();
}
} }