@Test public void addTodo() { running( fakeApplication(inMemoryDatabase()), new Runnable() { public void run() { DemoData.loadDemoData(); String authToken = DemoData.user1.createToken(); ObjectNode todoJson = Json.newObject(); todoJson.put("value", "make it work"); FakeRequest fakeRequest = fakeRequest() .withHeader(SecurityController.AUTH_TOKEN_HEADER, authToken) .withJsonBody(todoJson); Result result = callAction(routes.ref.TodoController.createTodo(), fakeRequest); assertThat(status(result)).isEqualTo(OK); Todo todo = Json.fromJson(Json.parse(contentAsString(result)), Todo.class); assertThat(todo.id).isNotNull(); assertThat(todo.value).isEqualTo("make it work"); assertThat(todo.user).isNull(); // this should not be serialized } }); }
/** * Checks that we can build fake request with a json body. In this test we specify the method to * use (DELETE) */ @Test public void withJsonBodyAndSpecifyMethod() { running( fakeApplication(), new Runnable() { @Override public void run() { Map map = new HashMap(); map.put("key1", "val1"); map.put("key2", 2); map.put("key3", true); JsonNode node = Json.toJson(map); Result result = callAction( routes.ref.Application.getIdenticalJson(), fakeRequest().withJsonBody(node, "DELETE")); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("application/json"); JsonNode node2 = Json.parse(contentAsString(result)); assertThat(node2.get("key1").asText()).isEqualTo("val1"); assertThat(node2.get("key2").asInt()).isEqualTo(2); assertThat(node2.get("key3").asBoolean()).isTrue(); } }); }
@Test public void testCommandGetFilteredCollection() { running( fakeApplication(), () -> { try { DbHelper.open("1234567890", TEST_USER, TEST_USER); ObjectNode cmd = MAPPER.createObjectNode(); ObjectNode p = MAPPER.createObjectNode(); ObjectNode q = MAPPER.createObjectNode(); q.put("where", "idx < ?"); ArrayNode params = MAPPER.createArrayNode(); params.add("5"); q.put("params", params); p.put("collection", TEST_COLLECTION); p.put("query", q); cmd.put(ScriptCommand.RESOURCE, "documents"); cmd.put(ScriptCommand.NAME, "list"); cmd.put(ScriptCommand.PARAMS, p); JsonNode node = CommandRegistry.execute(cmd, null); assertNotNull(node); assertTrue(node.isArray()); assertEquals(5, node.size()); } catch (Throwable t) { fail(ExceptionUtils.getFullStackTrace(t)); } finally { DbHelper.close(DbHelper.getConnection()); } }); }
@BeforeClass public static void initTestser() { running( fakeApplication(), () -> { try { DbHelper.open("1234567890", "admin", "admin"); ODocument user = UserService.signUp(TEST_USER, TEST_USER, new Date(), null, null, null, null, false); assertNotNull(user); ODocument alt = UserService.signUp( TEST_ALT_USER, TEST_ALT_USER, new Date(), null, null, null, null, false); assertNotNull(alt); CollectionService.create(TEST_COLLECTION); DbHelper.close(DbHelper.getConnection()); DbHelper.open("1234567890", TEST_USER, TEST_USER); sGenIds = createRandomDocuments(10); DbHelper.close(DbHelper.getConnection()); } catch (Throwable e) { fail(ExceptionUtils.getFullStackTrace(e)); } finally { DbHelper.close(DbHelper.getConnection()); } }); }
@BeforeClass public static void prepareRestaurant() { running( fakeApplication(), () -> { Coordinates coordinates = new Coordinates(); coordinates.setRestaurantId(1601994); coordinates.setLatitude(5.5); coordinates.setLongitude(1.1); coordinates.save(); Address address = new Address(); address.setEmail("*****@*****.**"); address.setCity("Test City"); address.setCountry("Test Country"); address.setStreetName("Test street"); address.setRestaurantId(1601994); address.save(); Restaurant restaurant = new Restaurant(); restaurant.setRestaurantId(1601994); restaurant.setAddress(address); restaurant.setCoordinates(coordinates); restaurant.setName("Test restaurant"); restaurant.setDeals(""); restaurant.setPhone(2252); restaurant.setRating(2); restaurant.setReservationPrice(3); restaurant.setWorkingHours(""); restaurant.save(); }); }
@Test public void testCommandGetSingleDocument() { running( fakeApplication(), () -> { try { DbHelper.open("1234567890", TEST_USER, TEST_USER); ObjectNode cmd = MAPPER.createObjectNode(); ObjectNode p = MAPPER.createObjectNode(); p.put("collection", TEST_COLLECTION); p.put("id", sGenIds.get(0)); cmd.put(ScriptCommand.RESOURCE, "documents"); cmd.put(ScriptCommand.NAME, "get"); cmd.put(ScriptCommand.PARAMS, p); JsonNode node = CommandRegistry.execute(cmd, null); assertNotNull(node); assertTrue(node.isObject()); assertNotNull(node.get("generated")); assertNotNull(node.get("id")); assertEquals(node.get("id").asText(), sGenIds.get(0)); assertEquals(node.get("@class").asText(), TEST_COLLECTION); } catch (Throwable t) { fail(ExceptionUtils.getFullStackTrace(t)); } finally { DbHelper.close(DbHelper.getConnection()); } }); }
@Test public void testCreateDocument() { running( fakeApplication(), () -> { try { DbHelper.open("1234567890", TEST_USER, TEST_USER); ObjectNode params = MAPPER.createObjectNode(); ObjectNode doc = MAPPER.createObjectNode(); doc.put("fresh", "fresh"); params.put("collection", TEST_COLLECTION); params.put("data", doc); ObjectNode cmd = ScriptCommands.createCommand("documents", "post", params); JsonNode exec = CommandRegistry.execute(cmd, null); assertNotNull(exec); assertTrue(exec.isObject()); assertNotNull(exec.get("id")); assertEquals(TEST_COLLECTION, exec.get("@class").asText()); } catch (Throwable t) { fail(ExceptionUtils.getFullStackTrace(t)); } finally { DbHelper.close(DbHelper.getConnection()); } }); }
@Test public void addValidReview() { running( fakeApplication(), () -> { ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put("text", "text of review"); node.put("rating", 4); JsonNode json = null; try { json = (JsonNode) new ObjectMapper().readTree(node.toString()); } catch (IOException e) { e.printStackTrace(); } Http.RequestBuilder rb = new Http.RequestBuilder() .method(POST) .uri("/v1/restaurants/1601994/reviews") .bodyJson(json); Result result = route(rb); assertEquals(Http.Status.OK, result.status()); assertTrue(PersistenceManager.getRestaurantById(1601994).getReviews().size() != 0); assertTrue( PersistenceManager.getRestaurantById(1601994) .getReviews() .get(0) .getText() .equals("text of review")); }); }
@Test public void addToInvalidRestaurant() { running( fakeApplication(), () -> { ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put("text", "text of review"); node.put("rating", 4); JsonNode json = null; try { json = (JsonNode) new ObjectMapper().readTree(node.toString()); } catch (IOException e) { e.printStackTrace(); } Http.RequestBuilder rb = new Http.RequestBuilder() .method(POST) .uri("/v1/restaurants/3213123/reviews") .bodyJson(json); Result result = route(rb); assertEquals(Http.Status.NOT_FOUND, result.status()); }); }
@Test public void test_sessionstatus_new_ok() { running( fakeApplication(), new Runnable() { public void run() { Logger.info("Création d'un nouveau statut de session"); try { TestUtils.updateDatabase("test/data/session_status.js"); Map<String, String> params = new HashMap<String, String>(); params.put("label", "HTTT"); Result result = callAction( routes.ref.SessionStatusController.addSessionStatus(), fakeRequest() .withJsonBody(Json.toJson(params), POST) .withSession("admin", "admin")); assertThat(status(result)).isEqualTo(OK); Logger.info("Vérification que le nouveau statut est bien présent en base de données"); List<BasicDBObject> dbObjects = TestUtils.loadFromDatabase( Constantes.COLLECTION_SESSION_STATUS, new BasicDBObject().append("label", "HTTT")); Assert.assertTrue(null != dbObjects); Assert.assertEquals(1, dbObjects.size()); Assert.assertEquals("HTTT", dbObjects.get(0).get("label")); } catch (IOException e) { Assert.fail(e.getMessage()); } } }); }
@AfterClass public static void removeEverything() { running( fakeApplication(), () -> { Restaurant restaurant = PersistenceManager.getRestaurantById(1601994); if (restaurant != null) { restaurant.delete(); } }); }
/** add your integration test here */ @Test public void test() { databaseConfiguration.put("db.default.url", "jdbc:mysql://localhost:3306/aer"); running( testServer(3333, fakeApplication(databaseConfiguration)), HTMLUNIT, new Callback<TestBrowser>() { public void invoke(TestBrowser browser) throws IOException { long i = Calendar.getInstance().getTimeInMillis(); // Teste que les bons départements sont trouvés par l'application // System.out.println(models.Departement.findDepartementsAER()); // ajouteEspece(); // Credentials.creeHashEtMotDePassePourToutLeMonde(); // listeMembres(); // listeEspecesAvecSousGroupeEtGroupe(); // VerifierMail.envoyerMailDeVerification(Membre.find.all().get(0)); // affichePremieresSystematiques(); // gererBaseDeDonneesInsectes.render(Espece.findAll(), // SousFamille.findSousFamillesExistantes(), Famille.findAll(), // SuperFamille.findSuperFamillesExistantes(), Ordre.findAll(), SousGroupe.findAll(), // Groupe.findAll()); // gererBaseDeDonneesInsectes.render(Espece.findAll(), // SousFamille.findSousFamillesExistantesTriees(), Famille.findAllTriees(), // SuperFamille.findSuperFamillesExistantesTriees(), Ordre.findAllTries(), // SousGroupe.findAll(), Groupe.findAll()); // excelTests(); // System.out.println(StadeSexe.getStadesImagos()); // testDoublonTemoin(); // testDoublonCommune(); // testUTMtoXY(); // metAJourNomAERCommunes(); excelCartes(); long j = Calendar.getInstance().getTimeInMillis(); System.out.println("Calculé en " + (j - i) + " ms"); } }); }
@Test public void tasksRoute() { running( fakeApplication(), new Runnable() { @Override public void run() { Result result = routeAndCall(fakeRequest(GET, "/tasks/json")); assertThat(status(result)).isEqualTo(OK); } }); }
/** * add your integration test here in this example we just check if the welcome page is being shown */ @Test public void test() { running( testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, new Callback<TestBrowser>() { public void invoke(TestBrowser browser) { browser.goTo("http://localhost:3333"); assertThat(browser.pageSource()).contains("Your new application is ready."); } }); }
@Test public void accessAssets() { /* works with play test, but not in eclipse */ running( TEST_SERVER, new Runnable() { @Override public void run() { assertThat(call("assets/javascripts/bootstrap.min.js")).isNotNull(); } }); }
@Test public void indexTemplateShouldContainTheStringThatIsPassedToIt() { running( fakeApplication(), new Runnable() { public void run() { Content html = views.html.index.render("Your new application is ready.", null); assertThat(contentType(html)).isEqualTo("text/html"); assertThat(contentAsString(html)).contains("Your new application is ready."); } }); }
@Test public void testUserChangeRole() { running( fakeApplication(), new Runnable() { public void run() { try { // create a user String userName = "******" + UUID.randomUUID().toString(); String sFakeAdminUserRoute = "/admin/user"; FakeRequest request = new FakeRequest(POST, sFakeAdminUserRoute); request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE); request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC); ObjectMapper mapper = new ObjectMapper(); JsonNode actualObj = mapper.readTree( "{\"username\":\"" + userName + "\"," + "\"password\":\"test\"," + "\"role\":\"registered\"}"); request = request.withJsonBody(actualObj); request = request.withHeader("Content-Type", "application/json"); Result result = route(request); assertRoute(result, "testUserChangeRole.createUser", Status.CREATED, null, true); // change its role FakeRequest request1 = new FakeRequest(PUT, "/admin/user/" + userName); request1 = request1.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE); request1 = request1.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC); mapper = new ObjectMapper(); actualObj = mapper.readTree( "{\"role\":\"backoffice\",\"visibleByAnonymousUsers\":{},\"visibleByTheUser\":{},\"visibleByFriends\":{}," + "\"visibleByRegisteredUsers\":{} }"); request1 = request1.withJsonBody(actualObj, PUT); request1 = request1.withHeader("Content-Type", "application/json"); result = route(request1); assertRoute( result, "testUserChangeRole.changeRole", Status.OK, "\"roles\":[{\"name\":\"backoffice\"", true); } catch (Exception e) { e.printStackTrace(); fail(); } } }); }
@Test public void testSubjectMustNotBePresent_subjectIsPresent_controllerExplicitlyUnrestricted() { running( testServer(PORT, app()), () -> { RestAssured.given() .cookie("user", "greet") .expect() .statusCode(401) .when() .get("/subject/not/present/m/subjectMustNotBePresentInUnrestrictedController"); }); }
/** * add your integration test here in this example we just check if the welcome page is being shown */ @Test @Ignore public void test() { running( testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, new Callback<TestBrowser>() { public void invoke(TestBrowser browser) { browser.goTo("http://localhost:3333"); assertTrue(browser.pageSource().contains("The following are the routes")); } }); }
@Test public void testSubjectNotMustBePresent_subjectIsPresent() { running( testServer(PORT, app()), () -> { RestAssured.given() .cookie("user", "greet") .expect() .statusCode(401) .when() .get("/subject/not/present/m/subjectMustNotBePresent"); }); }
public void testDelete() { running( fakeApplication(), new Runnable() { @Override public void run() { User user = User.find.byId(141); user.delete(); assertThat(User.find.byId(141)).isNull(); } }); }
@Test public void inApp() { running( fakeApplication(), new Runnable() { public void run() { Result result = routeAndCall(fakeRequest(GET, "/key")); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("text/plain"); assertThat(charset(result)).isEqualTo("utf-8"); assertThat(contentAsString(result)).contains("secret"); } }); }
@Test public void getAllTodosNoAuthToken() { running( fakeApplication(inMemoryDatabase()), new Runnable() { public void run() { DemoData.loadDemoData(); Result result = callAction(routes.ref.TodoController.getAllTodos()); assertThat(status(result)).isEqualTo(UNAUTHORIZED); assertThat(contentAsString(result)).doesNotContain(DemoData.todo1.value); } }); }
@Test public void indexShouldContainTheCorrectString() { running( fakeApplication(), new Runnable() { public void run() { Result result = callAction(routes.ref.MainController.index()); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("text/html"); assertThat(charset(result)).isEqualTo("utf-8"); assertThat(contentAsString(result)).contains("Hello from Java"); } }); }
@Test public void sampleRequestResourceById() { running( TEST_SERVER, HTMLUNIT, new Callback<TestBrowser>() { @Override public void invoke(final TestBrowser browser) { browser.goTo(API_PAGE); browser.find("a", withText("hbz ID")).first().click(); assertTypee(browser); } }); }
@Test public void shortModifierSampleRequest() { running( TEST_SERVER, HTMLUNIT, new Callback<TestBrowser>() { @Override public void invoke(final TestBrowser browser) { browser.goTo(API_PAGE); browser.click("a", withId("short.field.sample")); assertThat(browser.pageSource()).contains("edoweb:1637998"); } }); }
@Test public void callIndex() { running( fakeApplication(), new Runnable() { public void run() { Result result = callAction(controllers.routes.ref.Application.index()); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("text/html"); assertThat(charset(result)).isEqualTo("utf-8"); assertThat(contentAsString(result)).contains("Place Crawl App"); } }); }
@Test public void addTodoUnauthorized() { running( fakeApplication(inMemoryDatabase()), new Runnable() { public void run() { DemoData.loadDemoData(); Result result = callAction(routes.ref.TodoController.createTodo(), fakeRequest()); assertThat(status(result)).isEqualTo(UNAUTHORIZED); } }); }
@Test public void inServer() { running( testServer(3333), HTMLUNIT, new Callback<TestBrowser>() { public void invoke(TestBrowser browser) { browser.goTo("http://localhost:3333"); assertThat(browser.$("#title").getTexts().get(0)).isEqualTo("Hello Guest"); browser.$("a").click(); assertThat(browser.url()).isEqualTo("http://localhost:3333/Coco"); assertThat(browser.$("#title", 0).getText()).isEqualTo("Hello Coco"); } }); }
@Test public void insertData() { running( fakeApplication(), new Runnable() { @Override public void run() { // kontak1.save(); // kontak2.save(); } }); }