Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
Signed-off-by: Kirill Mokevnin <[email protected]>
  • Loading branch information
mokevnin committed Oct 9, 2023
1 parent f219098 commit 11f5972
Show file tree
Hide file tree
Showing 12 changed files with 50 additions and 54 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
setup:
npm install
./gradlew wrapper --gradle-version 8.3
./gradlew wrapper --gradle-version 8.4
./gradlew build

frontend:
Expand Down
10 changes: 5 additions & 5 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import org.gradle.api.tasks.testing.logging.TestLogEvent
plugins {
application
// "checkstyle"
id("io.freefair.lombok") version "8.3"
id("io.freefair.lombok") version "8.4"
id("org.springframework.boot") version "3.1.4"
id("io.spring.dependency-management") version "1.1.3"
id("com.github.ben-manes.versions") version "0.48.0"
id("com.github.ben-manes.versions") version "0.49.0"
}

group = "io.hexlet.blog"
Expand Down Expand Up @@ -35,12 +35,12 @@ dependencies {

// implementation("io.github.wimdeblauwe:error-handling-spring-boot-starter:4.2.0")

implementation("org.instancio:instancio-junit:3.3.0")
implementation("org.instancio:instancio-junit:3.3.1")
implementation("net.javacrumbs.json-unit:json-unit-assertj:3.2.2")
implementation("net.datafaker:datafaker:2.0.1")
implementation("net.datafaker:datafaker:2.0.2")

// implementation("io.sentry:sentry-spring-boot-starter-jqueryakarta:6.28.0")
runtimeOnly("com.h2database:h2:2.2.222")
runtimeOnly("com.h2database:h2:2.2.224")
testImplementation("org.springframework.security:spring-security-test")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation(platform("org.junit:junit-bom:5.10.0"))
Expand Down
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Expand Down
5 changes: 0 additions & 5 deletions src/main/java/io/hexlet/blog/config/JacksonConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@

@Configuration
public class JacksonConfig {
// TODO: not working
// @Bean
// public JsonNullableModule jsonNullableModule() {
// return new JsonNullableModule();
// }
@Bean
Jackson2ObjectMapperBuilder objectMapperBuilder() {
var builder = new Jackson2ObjectMapperBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ PostDTO update(@RequestBody @Valid PostUpdateDTO postData, @PathVariable Long id

@DeleteMapping("/posts/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
void delete(@PathVariable Long id) {
void destroy(@PathVariable Long id) {
repository.deleteById(id);
}
}
2 changes: 0 additions & 2 deletions src/main/java/io/hexlet/blog/mapper/PostMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
public abstract class PostMapper {
@Mapping(target = "author", source = "authorId")
public abstract Post map(PostCreateDTO dto);
@Mapping(target = "author", source = "authorId")
public abstract Post map(PostUpdateDTO dto);

@Mapping(source = "author.id", target = "authorId")
public abstract PostDTO map(Post model);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/io/hexlet/blog/model/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ public class Post implements BaseEntity {
@EqualsAndHashCode.Include
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@NotNull
@ManyToOne(optional = false)
// @NotNull
private User author;

@Column(unique = true)
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/io/hexlet/blog/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import com.fasterxml.jackson.annotation.JsonIgnore;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
Expand Down Expand Up @@ -41,9 +42,9 @@ public class User implements UserDetails, BaseEntity {
@EqualsAndHashCode.Include
private Long id;

@OneToMany(mappedBy = "author", fetch = FetchType.LAZY)
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
@JsonIgnore
private List<Post> posts;
private List<Post> posts = new ArrayList<>();

// EMAIL
@Column(unique = true)
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/io/hexlet/blog/util/UserUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public User getCurrentUser() {
}

public User getTestUser() {
return userRepository.findByEmail("[email protected]").get();
return userRepository.findByEmail("[email protected]")
.orElseThrow(() -> new RuntimeException("User doesn't exist"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
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;
Expand All @@ -24,6 +25,7 @@

import io.hexlet.blog.dto.PostUpdateDTO;
import io.hexlet.blog.mapper.PostMapper;
import io.hexlet.blog.model.Post;
import io.hexlet.blog.repository.PostRepository;
import io.hexlet.blog.util.ModelGenerator;
import io.hexlet.blog.util.UserUtils;
Expand Down Expand Up @@ -52,17 +54,19 @@ public class PostsControllerTest {

private JwtRequestPostProcessor token;

private Post testPost;

@BeforeEach
public void setUp() {
token = jwt().jwt(builder -> builder.subject("[email protected]"));
var testPost = Instancio.of(modelGenerator.getPostModel())
testPost = Instancio.of(modelGenerator.getPostModel())
.create();
testPost.setAuthor(userUtils.getTestUser());
postRepository.save(testPost);
}

@Test
public void testIndex() throws Exception {
postRepository.save(testPost);
var result = mockMvc.perform(get("/api/posts").with(token))
.andExpect(status().isOk())
.andReturn();
Expand All @@ -72,10 +76,7 @@ public void testIndex() throws Exception {

@Test
public void testCreate() throws Exception {
var data = Instancio.of(modelGenerator.getPostModel())
.create();
data.setAuthor(userUtils.getTestUser());
var dto = postMapper.map(data);
var dto = postMapper.map(testPost);

var request = post("/api/posts")
.with(token)
Expand All @@ -85,49 +86,52 @@ public void testCreate() throws Exception {
mockMvc.perform(request)
.andExpect(status().isCreated());

var post = postRepository.findBySlug(data.getSlug()).get();
var post = postRepository.findBySlug(testPost.getSlug()).get();
assertNotNull(post);
assertThat(post.getName()).isEqualTo(data.getName());
assertThat(post.getName()).isEqualTo(testPost.getName());
}

@Test
public void testUpdate() throws Exception {
var post = Instancio.of(modelGenerator.getPostModel())
.create();
post.setAuthor(userUtils.getTestUser());
postRepository.save(post);
postRepository.save(testPost);

var data = new PostUpdateDTO();
data.setName(JsonNullable.of("new name"));

var request = put("/api/posts/" + post.getId())
var request = put("/api/posts/" + testPost.getId())
.with(token)
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsString(data));

mockMvc.perform(request)
.andExpect(status().isOk());

post = postRepository.findById(post.getId()).get();
assertThat(post.getName()).isEqualTo(data.getName().get());
testPost = postRepository.findById(testPost.getId()).get();
assertThat(testPost.getName()).isEqualTo(data.getName().get());
}

@Test
public void testShow() throws Exception {
var post = Instancio.of(modelGenerator.getPostModel())
.create();
post.setAuthor(userUtils.getTestUser());
postRepository.save(post);
postRepository.save(testPost);

var request = get("/api/posts/" + post.getId()).with(jwt());
var request = get("/api/posts/" + testPost.getId()).with(jwt());
var result = mockMvc.perform(request)
.andExpect(status().isOk())
.andReturn();
var body = result.getResponse().getContentAsString();
assertThatJson(body).and(
v -> v.node("slug").isEqualTo(post.getSlug()),
v -> v.node("name").isEqualTo(post.getName()),
v -> v.node("body").isEqualTo(post.getBody())
);
v -> v.node("slug").isEqualTo(testPost.getSlug()),
v -> v.node("name").isEqualTo(testPost.getName()),
v -> v.node("body").isEqualTo(testPost.getBody()));
}

@Test
public void testDestroy() throws Exception {
postRepository.save(testPost);
var request = delete("/api/posts/" + testPost.getId()).with(jwt());
mockMvc.perform(request)
.andExpect(status().isNoContent());

assertThat(postRepository.existsById(testPost.getId())).isEqualTo(false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import java.util.HashMap;

import org.instancio.Instancio;
import org.instancio.Select;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -47,10 +46,12 @@ public class UsersControllerTest {

private JwtRequestPostProcessor token;

private User testUser;

@BeforeEach
public void setUp() {
token = jwt().jwt(builder -> builder.subject("[email protected]"));
var testUser = Instancio.of(modelGenerator.getUserModel())
testUser = Instancio.of(modelGenerator.getUserModel())
.create();
userRepository.save(testUser);
}
Expand All @@ -63,24 +64,19 @@ public void testIndex() throws Exception {

@Test
public void testUpdate() throws Exception {
var user = Instancio.of(User.class)
.ignore(Select.field(User::getId))
.supply(Select.field(User::getEmail), () -> faker.internet().emailAddress())
.create();
userRepository.save(user);

var data = new HashMap<>();
data.put("firstName", "Mike");

var request = put("/api/users/" + user.getId())
var request = put("/api/users/" + testUser.getId())
.with(token)
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsString(data));

mockMvc.perform(request)
.andExpect(status().isOk());

user = userRepository.findById(user.getId()).get();
var user = userRepository.findById(testUser.getId()).get();
assertThat(user.getFirstName()).isEqualTo(("Mike"));
}
}
3 changes: 2 additions & 1 deletion src/test/java/io/hexlet/blog/util/ModelGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ private void init() {
.toModel();

userModel = Instancio.of(User.class)
.ignore(Select.field(Post::getId))
.ignore(Select.field(User::getId))
.ignore(Select.field(User::getPosts))
.supply(Select.field(User::getEmail), () -> faker.internet().emailAddress())
.toModel();
}
Expand Down

0 comments on commit 11f5972

Please sign in to comment.