Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: tests and crud functionality for api #31

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.liatrio.dojo.devopsknowledgeshareapi;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/authors")
public class AuthorController {

@GetMapping
public List<String> getAuthors() {
// Return a sample list of authors
return Arrays.asList("Author1", "Author2", "Author3");
}
}
11 changes: 11 additions & 0 deletions src/main/java/com/liatrio/dojo/devopsknowledgeshareapi/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@ public class Post {
private @NonNull String imageUrl;
private @NonNull Date dateAsDate;

private String dateUpdated;

public void setDateUpdated(Date dateAsDate) {
DateFormat dateFormat = new SimpleDateFormat(dateFormat());
this.dateUpdated = dateFormat.format(dateAsDate);
}

public String getDateUpdated() {
return dateUpdated;
}

public Post() {
this.dateAsDate = Calendar.getInstance().getTime();
setDatePosted(dateAsDate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Collectors;

@CrossOrigin(origins = "*", maxAge = 3600)
Expand All @@ -19,6 +20,24 @@ public PostController(PostRepository repository) {
this.repository = repository;
}

@GetMapping("/posts/title")
public Collection<Post> getPostsByTitle(@RequestParam("title") String title) {
log.info("{}: received a GET request for posts by title", deploymentType);
return repository.findByTitle(title);
}

@GetMapping("/posts/firstname")
public Collection<Post> getPostsByFirstName(@RequestParam("firstName") String firstName) {
log.info("{}: received a GET request for posts by first name", deploymentType);
return repository.findByFirstName(firstName);
}

@GetMapping("/posts/link")
public Collection<Post> getPostsByLink(@RequestParam("link") String link) {
log.info("{}: received a GET request for posts by link", deploymentType);
return repository.findByLink(link);
}

@GetMapping("/posts")
public Collection<Post> posts() {
log.info("{}: recieved a GET request", deploymentType);
Expand All @@ -31,6 +50,27 @@ public Post post(@RequestBody Post post, HttpServletResponse resp) {
return repository.save(post);
}

@PutMapping("/posts/{id}")
public Post putPost(@PathVariable("id") Long id, @RequestBody Post updatedPost) {
log.info("{}: received a PUT request", deploymentType);
Optional<Post> optionalPost = repository.findById(id);
if (optionalPost.isPresent()) {
Post existingPost = optionalPost.get();
existingPost.setFirstName(updatedPost.getFirstName());
existingPost.setTitle(updatedPost.getTitle());
try {
existingPost.setLink(updatedPost.getLink());
} catch (Exception e) {
e.printStackTrace();
}
existingPost.setDatePosted(updatedPost.getDateAsDate());
existingPost.setImageUrl(updatedPost.getImageUrl());
return repository.save(existingPost);
} else {
throw new RuntimeException("Post not found with id " + id);
}
}

@DeleteMapping("/posts/{id}")
public void deletePost(@PathVariable("id") String id) {
log.info("{}: recieved a DELETE request", deploymentType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;
import java.util.List;

@RepositoryRestResource
@Repository
interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findByTitle(String title);
List<Post> findByFirstName(String firstName);
List<Post> findByLink(String link);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.liatrio.dojo.devopsknowledgeshareapi;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import org.springframework.http.MediaType;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

@ExtendWith(MockitoExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class AuthorControllerTest {

@Autowired
private MockMvc mockMvc;

@InjectMocks
private AuthorController authorController;

@BeforeAll
public void setup() {
mockMvc = standaloneSetup(authorController).build();
}

@Test
public void testGetAuthors() throws Exception {
mockMvc.perform(get("/authors")
.with(csrf())
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isArray())
.andDo(print());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,28 @@ public void deletePostsFirstName() throws Exception {
.andDo(print()).andExpect(status().isOk());
this.mockMvc.perform(delete("/posts/1/").with(csrf())).andDo(print()).andExpect(status().isOk());
}

@Test
public void getPostsByTitle() throws Exception {
this.mockMvc.perform(get("/posts/title")
.param("title", "My First Post"))
.andDo(print())
.andExpect(status().isOk());
}

@Test
public void getPostsByFirstName() throws Exception {
this.mockMvc.perform(get("/posts/firstname")
.param("firstName", "John"))
.andDo(print())
.andExpect(status().isOk());
}

@Test
public void getPostsByLink() throws Exception {
this.mockMvc.perform(get("/posts/link")
.param("link", "https://www.example.com/blog/post-1"))
.andDo(print())
.andExpect(status().isOk());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@ExtendWith(SpringExtension.class)
public class PostTest {
Expand Down Expand Up @@ -106,4 +110,24 @@ public void getImageUrlTest() throws Exception {
String test = hc.getImageUrl();
assertEquals(imageUrl, test);
}
}

@Test
public void setDateUpdatedTest() throws Exception {
Post hc = new Post();
Date date = Calendar.getInstance().getTime();
hc.setDateUpdated(date);
DateFormat dateFormat = new SimpleDateFormat(hc.dateFormat());
String expectedDate = dateFormat.format(date);
assertEquals(expectedDate, hc.getDateUpdated());
}

@Test
public void getDateUpdatedTest() throws Exception {
Post hc = new Post();
Date date = Calendar.getInstance().getTime();
hc.setDateUpdated(date);
DateFormat dateFormat = new SimpleDateFormat(hc.dateFormat());
String expectedDate = dateFormat.format(date);
assertEquals(expectedDate, hc.getDateUpdated());
}
}
Loading