Advertisement
Guest User

Untitled

a guest
Sep 11th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.25 KB | None | 0 0
  1. package rest;
  2.  
  3. import dto.JokeDTO;
  4. import entities.Joke;
  5. import utils.EMF_Creator;
  6. import io.restassured.RestAssured;
  7. import static io.restassured.RestAssured.get;
  8. import static io.restassured.RestAssured.given;
  9. import io.restassured.parsing.Parser;
  10. import java.io.IOException;
  11. import java.net.URI;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import javax.persistence.EntityManager;
  15. import javax.persistence.EntityManagerFactory;
  16. import javax.persistence.Query;
  17. import javax.ws.rs.core.UriBuilder;
  18. import org.glassfish.grizzly.http.server.HttpServer;
  19. import org.glassfish.grizzly.http.util.HttpStatus;
  20. import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
  21. import org.glassfish.jersey.server.ResourceConfig;
  22. import org.hamcrest.MatcherAssert;
  23. import static org.hamcrest.Matchers.equalTo;
  24. import static org.hamcrest.Matchers.hasKey;
  25. import static org.hamcrest.Matchers.not;
  26. import static org.hamcrest.Matchers.notNullValue;
  27. import org.junit.jupiter.api.AfterAll;
  28. import org.junit.jupiter.api.BeforeAll;
  29. import org.junit.jupiter.api.BeforeEach;
  30. import org.junit.jupiter.api.Test;
  31. import utils.EMF_Creator.DbSelector;
  32. import utils.EMF_Creator.Strategy;
  33.  
  34. //Uncomment the line below, to temporarily disable this test
  35. //@Disabled
  36. /**
  37.  * Joke.java contains more than JokeDTO.java, therefore I test twice, to ensure
  38.  * all information is serialized.
  39.  *
  40.  *
  41.  * @author runin
  42.  */
  43. public class JokeResourceTest {
  44.  
  45.     private static final int SERVER_PORT = 7777;
  46.     private static final String SERVER_URL = "http://localhost/api";
  47.     //Read this line from a settings-file  since used several places
  48.     //private static final String TEST_DB = "jdbc:mysql://localhost:3307/startcode_test";
  49.  
  50.     static final URI BASE_URI = UriBuilder.fromUri(SERVER_URL).port(SERVER_PORT).build();
  51.     private static HttpServer httpServer;
  52.     private static EntityManagerFactory emf;
  53.     List<Joke> jokes;
  54.     List<JokeDTO> jokesDTO;
  55.  
  56.     static HttpServer startServer() {
  57.         ResourceConfig rc = ResourceConfig.forApplication(new ApplicationConfig());
  58.         return GrizzlyHttpServerFactory.createHttpServer(BASE_URI, rc);
  59.     }
  60.  
  61.     @BeforeAll
  62.     public static void setUpClass() {
  63.         emf = EMF_Creator.createEntityManagerFactory(DbSelector.TEST, Strategy.CREATE);
  64.  
  65.         //NOT Required if you use the version of EMF_Creator.createEntityManagerFactory used above        
  66.         //System.setProperty("IS_TEST", TEST_DB);
  67.         //We are using the database on the virtual Vagrant image, so username password are the same for all dev-databases
  68.         httpServer = startServer();
  69.  
  70.         //Setup RestAssured
  71.         RestAssured.baseURI = SERVER_URL;
  72.         RestAssured.port = SERVER_PORT;
  73.  
  74.         RestAssured.defaultParser = Parser.JSON;
  75.     }
  76.  
  77.     @AfterAll
  78.     public static void closeTestServer() {
  79.         //System.in.read();
  80.         httpServer.shutdownNow();
  81.     }
  82.  
  83.     // Setup the DataBase (used by the test-server and this test) in a known state BEFORE EACH TEST
  84.     //TODO -- Make sure to change the script below to use YOUR OWN entity class
  85.     @BeforeEach
  86.     public void setUp() {
  87.         EntityManager em = emf.createEntityManager();
  88.  
  89.         jokes = new ArrayList(); //init
  90.         jokesDTO = new ArrayList(); //init
  91.  
  92.         //add to collection
  93.         jokes.add(new Joke("A programmer puts two glasses on his bedside table before going to sleep. A full one, in case he gets thirsty, and an empty one, in case he doesn’t.", "https://redd.it/1kvhmz", "case-handling", 10));
  94.         jokes.add(new Joke("A programmer is heading out to the grocery store, so his wife tells him \"get a gallon of milk, and if they have eggs, get a dozen.\" He returns with 13 gallons of milk.", "https://redd.it/1kvhmz", "numbers", 9));
  95.         jokes.add(new Joke("What do programmers do before sex? Initialize <pre><code>for</code></pre>-play.", "https://redd.it/1kvhmz", "naughty", 7));
  96.         jokes.add(new Joke("A programmer heads out to the store. His wife says \"while you're out, get some milk.\"", "https://redd.it/1kvhmz", "loops", 5));
  97.  
  98.         try {
  99.             em.getTransaction().begin();
  100.             Query query = em.createNativeQuery("truncate table CA1_test.JOKE;");
  101.             query.executeUpdate();
  102.             em.getTransaction().commit();
  103.             for (Joke j : jokes) {
  104.                 em.getTransaction().begin();
  105.                 em.persist(j);
  106.                 em.getTransaction().commit();
  107.             }
  108.         } finally {
  109.             em.close();
  110.         }
  111.  
  112.         jokes.forEach(e -> jokesDTO.add(new JokeDTO(e)));
  113.     }
  114.  
  115.     @Test
  116.     public void testServerIsUp() {
  117.         System.out.println("Testing is server UP");
  118.         given().when().get("/jokes").then().statusCode(200);
  119.     }
  120.  
  121.     //This test assumes the database contains two rows
  122.     @Test
  123.     public void testDummyMsg() throws Exception {
  124.         given()
  125.                 .contentType("application/json")
  126.                 .get("/jokes").then()
  127.                 .assertThat()
  128.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  129.                 .body("msg", equalTo("ACCESS GRANTED"));
  130.     }
  131.  
  132.     @Test
  133.     public void testGetJokeCount() throws Exception {
  134.         given()
  135.                 .contentType("application/json")
  136.                 .get("/jokes/count").then().log().body()
  137.                 .assertThat()
  138.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  139.                 .body("count", equalTo(jokes.size()));
  140.     }
  141.  
  142.     @Test
  143.     public void testGetAllJokes() throws Exception {
  144.         given()
  145.                 .contentType("application/json")
  146.                 .get("/jokes/all").then().log().body()
  147.                 .assertThat()
  148.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  149.                 .body("[0].reference", equalTo(jokes.get(0).getReference()))
  150.                 .body("[1].reference", equalTo(jokes.get(1).getReference()))
  151.                 .body("[2].type", equalTo(jokes.get(2).getType()))
  152.                 .body("[3].type", equalTo(jokes.get(3).getType()));
  153.     }
  154.  
  155.     @Test
  156.     public void testGetAllJokesAsDTO() throws Exception {
  157.         given()
  158.                 .contentType("application/json")
  159.                 .get("/jokes/all/dto").then().log().body()
  160.                 .assertThat()
  161.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  162.                 .body("[0].joke", equalTo(jokesDTO.get(0).getJoke()))
  163.                 .body("[1].joke", equalTo(jokesDTO.get(1).getJoke()))
  164.                 .body("[2].rating", equalTo(jokesDTO.get(2).getRating()))
  165.                 .body("[3].rating", equalTo(jokesDTO.get(3).getRating()));
  166.     }
  167.  
  168.     @Test
  169.     public void testGetJokeByID_SIMPLE() throws Exception {
  170.         given()
  171.                 .contentType("application/json")
  172.                 .get("/jokes/{id}", jokes.get(1).getId()).then().log().body()
  173.                 .assertThat()
  174.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  175.                 .body("joke", equalTo(jokes.get(1).getJoke()));
  176.     }
  177.  
  178.     @Test
  179.     public void testGetJokeByID_ADVANCED() throws Exception {
  180.         Joke result = get("jokes/{id}", jokes.get(3).getId()).then()
  181.                 .assertThat()
  182.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  183.                 .extract()
  184.                 .as(Joke.class);
  185.  
  186.         MatcherAssert.assertThat((result), equalTo(jokes.get(3)));
  187.     }
  188.  
  189.     @Test
  190.     public void testGetJokeByIDError() throws Exception {
  191.         given()
  192.                 .contentType("application/json")
  193.                 .get("/jokes/{id}", 999).then().log().body()
  194.                 .assertThat()
  195.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  196.                 .body("error", equalTo("Could not get joke by ID -> Database is empty or joke doesn't exist."));
  197.     }
  198.  
  199.     @Test
  200.     public void testGetJokeByIDAsDTO_SIMPLE() throws Exception {
  201.         given()
  202.                 .contentType("application/json")
  203.                 .get("/jokes/{id}/dto", jokesDTO.get(2).getId()).then().log().body()
  204.                 .assertThat()
  205.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  206.                 .body("joke", equalTo(jokesDTO.get(2).getJoke()));
  207.     }
  208.  
  209.     @Test
  210.     public void testGetJokeByIDAsDTO_ADVANCED() throws Exception {
  211.         JokeDTO result = get("jokes/{id}/dto", jokesDTO.get(3).getId()).then()
  212.                 .assertThat()
  213.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  214.                 .extract()
  215.                 .as(JokeDTO.class);
  216.  
  217.         MatcherAssert.assertThat((result), equalTo(jokesDTO.get(3)));
  218.     }
  219.  
  220.     @Test
  221.     public void testGetJokeByIDAsDTOError() throws Exception {
  222.         given()
  223.                 .contentType("application/json")
  224.                 .get("/jokes/{id}/dto", 888).then().log().body()
  225.                 .assertThat()
  226.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  227.                 .body("error", equalTo("Could not get joke (DTO) by ID -> Database is empty or joke doesn't exist."));
  228.     }
  229.  
  230.     @Test
  231.     public void testGetJokeByRandom() throws Exception {
  232.         given()
  233.                 .contentType("application/json")
  234.                 .get("/jokes/random").then().log().body()
  235.                 .assertThat()
  236.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  237.                 .body("id", notNullValue())
  238.                 .body("joke", notNullValue())
  239.                 .body("reference", notNullValue())
  240.                 .body("type", notNullValue())
  241.                 .body("rating", notNullValue());
  242.     }
  243.    
  244.         @Test
  245.     public void testGetJokeDTOByRandom() throws Exception {
  246.         given()
  247.                 .contentType("application/json")
  248.                 .get("/jokes/random/dto").then().log().body()
  249.                 .assertThat()
  250.                 .statusCode(HttpStatus.OK_200.getStatusCode())
  251.                 .body("id", notNullValue())
  252.                 .body("joke", notNullValue())
  253.                 .body("$", not(hasKey("reference")))
  254.                 .body("$", not(hasKey("type")))
  255.                 .body("rating", notNullValue());
  256.     }
  257.  
  258.     public static void main(String[] args) throws IOException {
  259.         HttpServer server = startServer();
  260.         System.in.read();
  261.         server.shutdownNow();
  262.         System.out.println("done");
  263.     }
  264.  
  265. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement