From 05f42c288176241d77da76054212fc1035d25876 Mon Sep 17 00:00:00 2001 From: Rhys Evans <EvansRM17@cardiff.ac.uk> Date: Sun, 18 Feb 2024 00:50:44 +0000 Subject: [PATCH] Finsihed webdriver testing, further database query testing completed --- .../SmartTowns/data/TrailsRepositoryJDBC.java | 1 + .../landmarks/LandmarksController.java | 4 +- .../PlacesController.java | 6 +- src/main/resources/application-dev.properties | 9 +- .../resources/application-test.properties | 4 +- .../static/scripts/locationApprovalForm.js | 8 + .../templates/landmarks/LandmarkFormTh.html | 11 +- .../landmarks/locationApprovalFormTh.html | 2 +- .../SmartTowns/ContainerMockMVCTests.java | 20 +- .../SmartTowns/DatabaseRepositoryTests.java | 177 ++++++++++++++++++ .../SmartTowns/FirefoxDriverPagesTests.java | 165 ++++++++++++++-- .../Team5/SmartTowns/JUnitSimpleTests.java | 60 +++--- .../resources/application-test.properties | 2 +- src/test/resources/data-h2.sql | 8 +- 14 files changed, 417 insertions(+), 60 deletions(-) create mode 100644 src/test/java/Team5/SmartTowns/DatabaseRepositoryTests.java diff --git a/src/main/java/Team5/SmartTowns/data/TrailsRepositoryJDBC.java b/src/main/java/Team5/SmartTowns/data/TrailsRepositoryJDBC.java index 68549602..dcf88b5d 100644 --- a/src/main/java/Team5/SmartTowns/data/TrailsRepositoryJDBC.java +++ b/src/main/java/Team5/SmartTowns/data/TrailsRepositoryJDBC.java @@ -28,6 +28,7 @@ public class TrailsRepositoryJDBC implements TrailsRepository { } @Override public String getTrailNameWithID(String trailsID){ + String resultName = jdbc.queryForObject( "SELECT trailName FROM trails WHERE trailID=?", String.class, trailsID); return resultName; diff --git a/src/main/java/Team5/SmartTowns/landmarks/LandmarksController.java b/src/main/java/Team5/SmartTowns/landmarks/LandmarksController.java index a7012ea1..82501c27 100644 --- a/src/main/java/Team5/SmartTowns/landmarks/LandmarksController.java +++ b/src/main/java/Team5/SmartTowns/landmarks/LandmarksController.java @@ -79,7 +79,7 @@ public class LandmarksController { int locationID = locationRepository.nametoLocationID(location.getLocationName()); // converts valid response using Location constructor into a submittable format to the sql table - System.out.println(locCoord.getLocationCoordsLong()); +// System.out.println(locCoord.getLocationCoordsLong()); LocationsCoordinates ALocCoord = new LocationsCoordinates(locationID, locCoord.getLocationCoordsLat(), locCoord.getLocationCoordsLong()); boolean checkIfCoorsWithinBoundaries = placesCoordinatesRepo.checkIfCoordsAreWithinTownBoundary(ALocCoord); if (checkIfCoorsWithinBoundaries==false){ // if coords outside associated town, form is returned to original state @@ -87,7 +87,7 @@ public class LandmarksController { } placesCoordinatesRepo.addLocationCoord(ALocCoord); // adds valid landmark to locations table locationRepository.updateApprovalStatus(locationID); // updates approval status accordingly - System.out.println(placesCoordinatesRepo.getAllLocationCoords()); +// System.out.println(placesCoordinatesRepo.getAllLocationCoords()); ModelAndView modelAndView = new ModelAndView("redirect:/mobile-home"); //redirects back top form in case admin wants to input second location return modelAndView; diff --git a/src/main/java/Team5/SmartTowns/placeswithcoordinates/PlacesController.java b/src/main/java/Team5/SmartTowns/placeswithcoordinates/PlacesController.java index e421f82d..d3845557 100644 --- a/src/main/java/Team5/SmartTowns/placeswithcoordinates/PlacesController.java +++ b/src/main/java/Team5/SmartTowns/placeswithcoordinates/PlacesController.java @@ -69,9 +69,9 @@ public class PlacesController { int townIDFromTable= placeRepo.getTownIDFromName(townNamee); for (int i=0;i<trailslocations.size();i++){ int trailID = trailsRepo.getTrailIDFromTrailName(trailslocations.get(i).getTrailName()); - System.out.println(trailslocations.get(i)); - System.out.println(trailslocations.get(i).getTrailName()); - System.out.println(trailID); +// System.out.println(trailslocations.get(i)); +// System.out.println(trailslocations.get(i).getTrailName()); +// System.out.println(trailID); if ((trailID>100)&&(trailID<200)&&(Objects.equals(townNamee, "Caerphilly"))){ correctTrails.add(trailslocations.get(i)); } diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties index 00134274..4b87cd28 100644 --- a/src/main/resources/application-dev.properties +++ b/src/main/resources/application-dev.properties @@ -1,6 +1,9 @@ -spring.datasource.url=jdbc:mariadb://localhost:3306/towns -spring.datasource.username=root -spring.datasource.password=comsc +#spring.datasource.url=jdbc:mariadb://localhost:3306/towns +#spring.datasource.username=root +#spring.datasource.password=comsc + + + #spring.sql.init.mode=always #spring.sql.init.data-locations=classpath:data.sql, classpath:/static/sql/user-data.sql, classpath:/static/sql/user-progress-data.sql diff --git a/src/main/resources/application-test.properties b/src/main/resources/application-test.properties index dff27f12..bf3cc73a 100644 --- a/src/main/resources/application-test.properties +++ b/src/main/resources/application-test.properties @@ -1,4 +1,6 @@ spring.datasource.url=jdbc:mariadb://localhost:3306/townstest spring.datasource.username=root spring.datasource.password=comsc -spring.sql.init.platform=test \ No newline at end of file +spring.sql.init.platform=test + +spring.sql.init.data-locations=classpath:data-test.sql, classpath:schema-test.sql \ No newline at end of file diff --git a/src/main/resources/static/scripts/locationApprovalForm.js b/src/main/resources/static/scripts/locationApprovalForm.js index 10778be2..263b84f5 100644 --- a/src/main/resources/static/scripts/locationApprovalForm.js +++ b/src/main/resources/static/scripts/locationApprovalForm.js @@ -3,8 +3,15 @@ function acceptanceValidation(){ var pass=true; + + var name = document.forms["adminCheckpointApproval"]["locationName"].value var lat = document.forms["adminCheckpointApproval"]["locationCoordsLat"].value var long = document.forms["adminCheckpointApproval"]["locationCoordsLong"].value + + if (name==""){ + alert('No location selected. \nPlease select an available location.'); + pass = false; + } if (lat=="") { alert('Invalid location inputted. \nPlease input a valid latitude.'); pass = false; @@ -13,4 +20,5 @@ function acceptanceValidation(){ alert('Invalid location inputted. \nPlease input a valid longitude.'); pass = false; } return pass; + } \ No newline at end of file diff --git a/src/main/resources/templates/landmarks/LandmarkFormTh.html b/src/main/resources/templates/landmarks/LandmarkFormTh.html index 3547d0fb..6d890deb 100644 --- a/src/main/resources/templates/landmarks/LandmarkFormTh.html +++ b/src/main/resources/templates/landmarks/LandmarkFormTh.html @@ -10,7 +10,7 @@ </head> <body> -<header th:insert="~{/fragments/banners :: header}"></header> +<header th:replace="~{/fragments/banners :: header}"></header> <main> @@ -43,11 +43,12 @@ <option value=0 hidden="true">Select Trail</option> <option value=0 disabled selected>Select Trail</option> <option value=101>(Caerphilly) Castle Trail</option> - <option value=0102>(Caerphilly) Pub Trail</option> - <option value=0103>(Caerphilly) Heritage Trail</option> - <option value=0201>(Risca) Heritage and Culture Trail</option> - <option value=0301>(Penarth) Esplanade Trail</option> + <option value=102>(Caerphilly) Pub Trail</option> + <option value=103>(Caerphilly) Heritage Trail</option> + <option value=201>(Risca) Heritage and Culture Trail</option> + <option value=301>(Penarth) Esplanade Trail</option> </select> +<!-- values used to be 0103, 0102, intro error becuase the trailnamefromid trailRepoJDBC used string valeus to search DB and not ints--> </label> <button class="button" type="submit">Submit</button> </form> diff --git a/src/main/resources/templates/landmarks/locationApprovalFormTh.html b/src/main/resources/templates/landmarks/locationApprovalFormTh.html index d2ee7b0b..985e4c33 100644 --- a/src/main/resources/templates/landmarks/locationApprovalFormTh.html +++ b/src/main/resources/templates/landmarks/locationApprovalFormTh.html @@ -11,7 +11,7 @@ </head> <body> -<header th:insert="~{/fragments/banners.html :: header}"></header> +<header th:replace="~{/fragments/banners.html :: header}"></header> <hr style="height:20px; visibility:hidden;" /> <main> <H1 id="formHeader">Locations To Be Approved:</H1> diff --git a/src/test/java/Team5/SmartTowns/ContainerMockMVCTests.java b/src/test/java/Team5/SmartTowns/ContainerMockMVCTests.java index e6405061..3a858bcc 100644 --- a/src/test/java/Team5/SmartTowns/ContainerMockMVCTests.java +++ b/src/test/java/Team5/SmartTowns/ContainerMockMVCTests.java @@ -5,6 +5,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import Team5.SmartTowns.data.Location; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -13,9 +14,7 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; - - - +import java.util.List; @SpringBootTest @@ -25,6 +24,16 @@ public class ContainerMockMVCTests { @Autowired private MockMvc mockMvc; + + @Test + public void getAllLocationsTest(){ +// List<Location> allLocations = locationRepository.getAllLocation(); + + } + + + + // todo have to test @Test public void a_testGreeting() throws Exception { @@ -57,6 +66,9 @@ public class ContainerMockMVCTests { - +// addLocation +// locationRepository.getAllUnapprovedLocations() +// checkIfCoordsAreWithinTownBoundary +// getAllLocationCoords } diff --git a/src/test/java/Team5/SmartTowns/DatabaseRepositoryTests.java b/src/test/java/Team5/SmartTowns/DatabaseRepositoryTests.java new file mode 100644 index 00000000..bf5a346b --- /dev/null +++ b/src/test/java/Team5/SmartTowns/DatabaseRepositoryTests.java @@ -0,0 +1,177 @@ +package Team5.SmartTowns; + + +import Team5.SmartTowns.data.*; +import Team5.SmartTowns.placeswithcoordinates.LocationsCoordinates; +import Team5.SmartTowns.placeswithcoordinates.PlacesCoordinatesRepository; +import Team5.SmartTowns.placeswithcoordinates.TownWithTrails; +import jakarta.transaction.Transactional; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.List; +//@RunWith(SpringRunner.class) +//@ContextConfiguration(classes=LocationRepository.class) +//@JdbcTest +//@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE) +//@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +@SpringBootTest +//container? +//@Transactional +//@Import(LocationRepository.class) +public class DatabaseRepositoryTests { + + + @Autowired + private LocationRepository locationRepo; + @Autowired + private PlacesCoordinatesRepository placesRepo; + + @Autowired + private TrailsRepository trailsRepo; + + + @Test + @Tag("locations") + public void allLocationDataCanBeCalledTest(){ + List<Location> allLocations = locationRepo.getAllLocation(); + assertEquals(allLocations.get(0).getLocationName(),"MockBusiness"); + } + + @Test + @Tag("locations") + public void locationsCanBeAdded(){ + assertFalse(locationRepo.getAllLocation().contains("MockLocation")); + Location location = new Location(1,"MockLocation", "Mock@Test.co.uk", + "MockDescription","MockCaerphilly","99",false); + locationRepo.addLocation(location); + assertTrue(locationRepo.getAllLocation().contains("MockLocation")); + } + + @Test + @Tag("locations") + public void authorisedLocationsCanBeCalled(){ + Location loc=locationRepo.getAllLocation().get(0); + assertFalse(loc.isLocationApproved()); + assertFalse(locationRepo.getAllApprovedLocations().contains(loc)); + } + + @Test + @Tag("locations") + public void unauthorisedLocationsCanBeCalled(){ + Location loc=locationRepo.getAllLocation().get(0); + assertFalse(loc.isLocationApproved()); + assertTrue(locationRepo.getAllUnapprovedLocations().contains(loc)); + } + + @Test + @Tag("locations") + public void nameToLocationIDTest(){ + int locID=locationRepo.nametoLocationID(locationRepo.getAllLocation().get(0).getLocationName()); + assertEquals(locID,1); + } + + @Test + @Tag("locations") + public void doesLocationApprovalStatusUpdate(){ + Location loc=locationRepo.getAllLocation().get(0); + assertFalse(loc.isLocationApproved()); + int DbID=locationRepo.nametoLocationID(loc.getLocationName()); + locationRepo.updateApprovalStatus(DbID); + assertTrue(loc.isLocationApproved()); + } + + + @Test + public void ensureApprovedLocationsAndCoordinatesAreTheSameSize(){ + List<Location> approvedLocations = locationRepo.getAllApprovedLocations(); + List<LocationsCoordinates> coordinatesLocations = placesRepo.getAllLocationCoords(); + assertSame(approvedLocations.size(),coordinatesLocations.size() ); + } + + + @Test + @Tag("locationCoordinates")//both + public void allLocationCoordDataCanBeCalled(){ + List<LocationsCoordinates> list = placesRepo.getAllLocationCoords(); + int locID= locationRepo.nametoLocationID("The Castle"); + assertEquals(list.get(0).getLocationID(),locID); + } + + @Test + @Tag("locationCoordinates") + public void locationCoordsCanBeAdded(){//check + LocationsCoordinates locPlc=new LocationsCoordinates(1, 51.576,-3.222); + placesRepo.addLocationCoord(locPlc); + System.out.println(placesRepo.getAllLocationCoords()); + assertEquals((placesRepo.getAllLocationCoords().get(placesRepo.getAllLocationCoords().size()-1).getLocationID()),(locPlc.getLocationID())); + + } + + @Test + @Tag("locationCoordinates") + @Tag("towns") + public void testIfLocationCoordsWithinTownBoundary(){ + List<TownWithTrails> townsList = placesRepo.getAllTownCoords(); + assertTrue(townsList.get(0).getTownName().contains("Caerphilly")); + LocationsCoordinates locPlc=new LocationsCoordinates(2, 99.00,-2.00); + assertFalse(placesRepo.checkIfCoordsAreWithinTownBoundary(locPlc)); + locPlc.setLocationCoordsLat(51.576); + locPlc.setLocationCoordsLong(-3.222); + assertTrue(placesRepo.checkIfCoordsAreWithinTownBoundary(locPlc)); + } + + @Test + @Tag("towns") + public void getTownIdFromNameTest(){ + int townID = placesRepo.getTownIDFromName("Caerphilly"); + assertEquals(townID,1); + } + + + @Test + @Tag("trails") + public void getAllTrails(){ + List<Trail> trailList = trailsRepo.getAllTrails(); + assertEquals(trailList.get(0).getTrailName(),"Caerphilly Castle Trail"); + } + @Test + @Tag("trails") + public void getTrailNameWithIdTest(){ + String trailActualName=trailsRepo.getAllTrails().get(0).getTrailName(); + String trailName = trailsRepo.getTrailNameWithID(Long.toString(trailsRepo.getAllTrails().get(0).getTrailsId())); + assertEquals(trailName,trailActualName); + } + + @Test + @Tag("trails") + public void getTrailIdWithNameTest(){ + Long trailIDActual =trailsRepo.getAllTrails().get(0).getTrailsId(); + int trailID = trailsRepo.getTrailIDFromTrailName(trailsRepo.getAllTrails().get(0).getTrailName()); + assertEquals(trailID,trailIDActual); + } + + + + + + + +} diff --git a/src/test/java/Team5/SmartTowns/FirefoxDriverPagesTests.java b/src/test/java/Team5/SmartTowns/FirefoxDriverPagesTests.java index 2ab21e63..ee839736 100644 --- a/src/test/java/Team5/SmartTowns/FirefoxDriverPagesTests.java +++ b/src/test/java/Team5/SmartTowns/FirefoxDriverPagesTests.java @@ -1,6 +1,6 @@ package Team5.SmartTowns; -import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.*; //import org.junit.jupiter.api.BeforeAll; //import org.junit.jupiter.api.BeforeEach; @@ -10,17 +10,16 @@ import org.junit.Before; //import org.junit.Test; //- using this stops initialisation error, and runs properly, but breaks firefox driver -import org.junit.jupiter.api.Test; //works but initialisation error -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.runner.RunWith; import org.openqa.selenium.By; +import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Profile; @@ -32,7 +31,10 @@ import org.springframework.test.context.junit4.SpringRunner; import io.github.bonigarcia.wdm.WebDriverManager; +import java.time.Duration; + import static javax.swing.text.html.CSS.getAttribute; +import static org.bouncycastle.oer.its.ieee1609dot2.basetypes.Duration.seconds; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -40,6 +42,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; //@RunWith(SpringRunner.class) @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +//system and functional testing. //@ActiveProfiles("test") public class FirefoxDriverPagesTests { @Value("${local.server.port}") @@ -55,7 +58,7 @@ public class FirefoxDriverPagesTests { @BeforeEach void setupTest() { FirefoxOptions options = new FirefoxOptions(); -// options.addArguments("--headless"); + options.addArguments("--headless"); webDriver = new FirefoxDriver(options); // webDriver = new FirefoxDriver(); } @@ -77,11 +80,126 @@ public class FirefoxDriverPagesTests { } -//test false entries, log ina dn log out? +//test false entries, log ina dn log out?, test Risca and Penarth at least once + + @Test + @DirtiesContext + @Order(1) + public void testingLandmarkSubmissionErrorAlertsShow(){ + this.webDriver.get("http://localhost:" + Integer.toString(port) + "/landmarkSubmission"); + //check error messages aren't showing straight away + assertFalse(webDriver.findElement(By.cssSelector("main form")).getText().contains("You must type in a username.")); + assertFalse(webDriver.findElement(By.cssSelector("main form")).getText().contains("You must attach a contact address.")); //css selector? + assertFalse(webDriver.findElement(By.cssSelector("main form")).getText().contains("You must attach a valid contact address.")); //css selector? + + + //check submitting empty form. + assertTrue(webDriver.findElement(By.cssSelector("main form ")).getText().contains("Submit")); + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); +// this.webDriver.wait(200); + //WebDriverWait wait = new WebDriverWait(this.webDriver, Duration.ofSeconds(100) /*timeout in seconds*/); + assertTrue(webDriver.switchTo().alert().getText().contains("Invalid trail selected. \nPlease select the trail you wish to join.")); + this.webDriver.switchTo().alert().accept(); + assertTrue(webDriver.switchTo().alert().getText().contains("Invalid location selected. \nPlease select the location you wish to join.")); + this.webDriver.switchTo().alert().accept(); + //testing location-trail mismatch + new Select(this.webDriver.findElement(By.name("landmarkLocation"))).selectByVisibleText("Risca"); + new Select(this.webDriver.findElement(By.name("trailID"))).selectByVisibleText("(Penarth) Esplanade Trail"); + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); + assertTrue(webDriver.switchTo().alert().getText().contains("Trail unavailable in your current location. \nPlease choose an available trail")); + this.webDriver.switchTo().alert().accept(); + new Select(this.webDriver.findElement(By.name("landmarkLocation"))).selectByVisibleText("Penarth"); //change location to be acceptable + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); //submit to show backend verification. + assertTrue(webDriver.findElement(By.xpath("/html/body/main/form/div[1]")).getText().contains("You must type in a username.")); + assertTrue(webDriver.findElement(By.xpath("/html/body/main/form/div[2]")).getText().contains("You must attach a contact address.")); //css selector? + new Select(this.webDriver.findElement(By.name("landmarkLocation"))).selectByVisibleText("Penarth"); + //testing description word count + this.webDriver.findElement(By.name("landmarkDescription")).sendKeys("This is a text paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit." + + " This is a text paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. This is a text " + + "paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. This is a text paragraph to test this " + + "form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. This is a " + + "text paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. " + + "This is a text paragraph to test this form’s 200-word limit. This is a text paragraph to test this form’s 200-word limit. Three more words."); + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); + assertTrue(webDriver.switchTo().alert().getText().contains("Please keep your description to a maximum of 200 words.")); + this.webDriver.switchTo().alert().accept(); + this.webDriver.findElement(By.name("landmarkDescription")).clear(); + this.webDriver.findElement(By.name("landmarkDescription")).sendKeys("This is a mock description under 200 words"); + + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); + boolean alertPresent; //make sure alert doesnt show for correct trail + try{ + this.webDriver.switchTo().alert(); + alertPresent=true; + + } catch (NoAlertPresentException Ex){ + alertPresent=false; + } + assertFalse(alertPresent); + //testing javascript verification output + this.webDriver.findElement(By.name("landmarkEmail")).sendKeys("MockAddressNotEmail"); + this.webDriver.findElement(By.name("landmarkName")).sendKeys("MockLocationWorksTMP"); + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); + + assertFalse(webDriver.findElement(By.cssSelector("main form")).getText().contains("You must type in a username.")); + assertFalse(webDriver.findElement(By.cssSelector("main form")).getText().contains("You must attach a contact address.")); //css selector? + assertTrue(webDriver.findElement(By.xpath("/html/body/main/form/div")).getText().contains("You must attach a valid contact address.")); //css selector? + this.webDriver.findElement(By.name("landmarkEmail")).clear(); + this.webDriver.findElement(By.name("landmarkEmail")).sendKeys("MockAddress@Works.co.uk"); + //make sure all error messages disappear once fulfilled + this.webDriver.findElement(By.name("landmarkName")).clear(); + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); + assertFalse(webDriver.findElement(By.cssSelector("main form")).getText().contains("You must attach a valid contact address.")); //css selector? + this.webDriver.findElement(By.name("landmarkName")).sendKeys("MockLocationWorks"); + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); + assertTrue(webDriver.getCurrentUrl().contains("http://localhost:" + Integer.toString(port) + "/mobile-home")); + } + + @Test + @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) + @Order(2) + public void testingAdminAcceptanceForm(){ + this.webDriver.get("http://localhost:" + Integer.toString(port) + "/login"); + this.webDriver.findElement(By.xpath("/html/body/main/div/div[2]/form/label[1]/input")).sendKeys("Admin"); + this.webDriver.findElement(By.xpath("/html/body/main/div/div[2]/form/label[2]/input")).sendKeys("admin"); + this.webDriver.findElement(By.xpath("/html/body/main/div/div[2]/form/button")).click(); + assertTrue(webDriver.getCurrentUrl().contains("http://localhost:" + Integer.toString(port) + "/mobile-home")); + this.webDriver.get("http://localhost:" + Integer.toString(port) + "/checkpointApproval"); +// assertTrue(webDriver.findElement(By.cssSelector("main")).getText().contains("MockAddress@Works.co.uk")); + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); + //verify no coord inputs error alert works + assertTrue(webDriver.switchTo().alert().getText().contains("No location selected. \nPlease select an available location.")); + this.webDriver.switchTo().alert().accept(); + assertTrue(webDriver.switchTo().alert().getText().contains("Invalid location inputted. \nPlease input a valid latitude.")); + this.webDriver.switchTo().alert().accept(); + assertTrue(webDriver.switchTo().alert().getText().contains("Invalid location inputted. \nPlease input a valid longitude.")); + this.webDriver.switchTo().alert().accept(); + //test incorrect coords entered(as per town boundaries todo put method relevant here) + new Select(this.webDriver.findElement(By.name("locationName"))).selectByVisibleText("St Cenydd (101)"); + this.webDriver.findElement(By.name("locationCoordsLat")).sendKeys("123"); + this.webDriver.findElement(By.name("locationCoordsLong")).sendKeys("123"); + //check user directed to correct error form + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); + assertTrue(webDriver.getCurrentUrl().contains("http://localhost:" + Integer.toString(port) + "/checkpointApproval?error")); + assertTrue(webDriver.findElement(By.xpath("/html/body/main/form/div")).getText().contains("Invalid Coordinates entered.")); + new Select(this.webDriver.findElement(By.name("locationName"))).selectByVisibleText("St Cenydd (101)"); + this.webDriver.findElement(By.name("locationCoordsLat")).sendKeys("51.57815"); + this.webDriver.findElement(By.name("locationCoordsLong")).sendKeys("-3.22510"); + this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); + //ensure submission submits + assertTrue(webDriver.getCurrentUrl().contains("http://localhost:" + Integer.toString(port) + "/mobile-home")); + + + + } + + @Test @DirtiesContext +@Order(3) public void testingEntireFeature(){ //homePage + //todo error if submitted location same as approved location(*in trail) and submitted on approvalform this.webDriver.get("http://localhost:" + Integer.toString(port) + "/mobile-home"); assertTrue(webDriver.findElement(By.cssSelector("main")).getText().contains("Welcome to VZTA Smart Towns!")); assertTrue(webDriver.findElements(By.xpath("/html/body/main/div[1]/a[1]/button")).size() > 0); @@ -124,25 +242,48 @@ public void testingEntireFeature(){ assertTrue(webDriver.findElement(By.xpath("/html/body/main/section/h2")).getText().contains("To Be Approved")); assertTrue(webDriver.findElement(By.cssSelector("main h1")).getText().contains("Locations To Be Approved:")); //todo FIX THIS!! - assertTrue(webDriver.findElement(By.cssSelector("main table tbody ")).getText().contains("MockLocation (0103)")); + assertTrue(webDriver.findElement(By.cssSelector("main table tbody ")).getText().contains("MockLocation (103)")); assertTrue(webDriver.findElement(By.cssSelector("main section table tbody")).getText().contains("MockAddress@Contact.co.uk")); assertTrue(webDriver.findElement(By.cssSelector("main section table tbody")).getText().contains("This is a mock description of this business.")); //Can't test Caerphilly;ly as others already there todo? look into Risca //todo test verification of this form - new Select(this.webDriver.findElement(By.name("locationName"))).selectByVisibleText("MockLocation (0103)"); + //<!-- values used to be 0103, 0102, intro error becuase the trailnamefromid trailRepoJDBC used string valeus to search DB and not ints + new Select(this.webDriver.findElement(By.name("locationName"))).selectByVisibleText("MockLocation (103)"); this.webDriver.findElement(By.name("locationCoordsLat")).sendKeys("51.57815"); this.webDriver.findElement(By.name("locationCoordsLong")).sendKeys("-3.22510"); assertTrue(webDriver.findElement(By.xpath("/html/body/main/form/button")).getText().contains("Submit")); assertTrue(webDriver.findElements(By.xpath("/html/body/main/form/button")).size() > 0); this.webDriver.findElement(By.xpath("/html/body/main/form/button")).click(); - + //back to home, check approved variable is gone from approval screen assertTrue(webDriver.findElement(By.cssSelector("main")).getText().contains("Welcome to VZTA Smart Towns!")); this.webDriver.findElement(By.xpath("/html/body/main/div[1]/a[2]")).click(); - assertFalse(webDriver.findElement(By.cssSelector("main table")).getText().contains("MockLocation (0103)")); - + assertFalse(webDriver.findElement(By.cssSelector("main table")).getText().contains("MockLocation (103)")); + //go back to hiome following header + assertTrue(webDriver.findElement(By.xpath("/html/body/header/nav/ul/li[1]")).getText().contains("Home")); assertTrue(webDriver.findElements(By.xpath("/html/body/header/nav/ul/li[1]")).size() > 0); //todo fix tghis bit this.webDriver.findElement(By.xpath("/html/body/header/nav/ul/li[1]/a")).click(); - assertTrue(webDriver.findElement(By.cssSelector("main")).getText().contains("Welcome to VZTA Smart Towns!")); + assertTrue(webDriver.findElement(By.cssSelector("main")).getText().contains("Welcome to VZTA Smart Towns!")); // back home here + //check town is there, click to go to trails page + assertTrue(webDriver.findElement(By.xpath("/html/body/main/article/div[1]/h2")).getText().contains("Caerphilly")); + assertTrue(webDriver.findElements(By.xpath("/html/body/main/article/div[1]/a")).size() > 0); + this.webDriver.findElement(By.xpath("/html/body/main/article/div[1]/a")).click(); + // check path is in towns trails page + assertTrue(webDriver.findElement(By.xpath("/html/body/main/section/a[3]/h1")).getText().contains("Caerphilly Heritage Trail")); + assertTrue(webDriver.findElements(By.xpath("/html/body/main/section/a[3]")).size() > 0); + this.webDriver.findElement(By.xpath("/html/body/main/section/a[3]")).click(); + + //Trail-list page test + assertTrue(webDriver.findElement(By.xpath("/html/body/main/article[1]")).getText().contains("Caerphilly Heritage Trail")); + assertTrue(webDriver.findElement(By.xpath("/html/body/main/article[1]/h3")).getText().contains("Checkpoints")); + assertTrue(webDriver.findElement(By.xpath("/html/body/main/article[1]")).getText().contains("MockLocation")); + assertTrue(webDriver.findElements(By.xpath("//a[text()='MockLocation']")).size() > 0); //tests MockLocation html name is there + this.webDriver.findElement(By.xpath("//a[text()='MockLocation']")).click(); + //Trail-location page test + assertTrue(webDriver.findElement(By.xpath("/html/body/main/article/h1")).getText().contains("MockLocation")); + assertTrue(webDriver.findElement(By.xpath("/html/body/main/article/h4")).getText().contains("Caerphilly")); + assertTrue(webDriver.findElement(By.xpath("/html/body/main/article/p")).getText().contains("This is a mock description of this business.")); + assertTrue(webDriver.findElement(By.xpath("/html/body/main/article/iframe")).getAttribute("src").contains("https://maps.google.com/maps?q=51.57815,-3.2251&hl=en&z=20&output=embed")); + diff --git a/src/test/java/Team5/SmartTowns/JUnitSimpleTests.java b/src/test/java/Team5/SmartTowns/JUnitSimpleTests.java index 58949d98..2c889d97 100644 --- a/src/test/java/Team5/SmartTowns/JUnitSimpleTests.java +++ b/src/test/java/Team5/SmartTowns/JUnitSimpleTests.java @@ -34,34 +34,41 @@ import java.util.stream.Stream; public class JUnitSimpleTests { private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); - private Set<ConstraintViolation<Landmarks>> violationsName; @Test -public void landmarkJakartaValidationTest(){ - Landmarks landmark = new Landmarks("99",1,"MockLandmark","Mock@Mock2.com", - "MockLandmarkDesc","MockRisca","MockImage"); - Set<ConstraintViolation<Landmarks>> violations = validator.validate(landmark); - //username blank, email blank, and email not email - assertTrue(violations.isEmpty()); - System.out.println(violations); - landmark.setLandmarkName(""); - Set<ConstraintViolation<Landmarks>> violationsName = validator.validate(landmark); - System.out.println(violationsName); - assertFalse(violationsName.isEmpty()); - List<String> fieldName = violationsName.stream().map((ConstraintViolation::getPropertyPath)).map(Object::toString).toList(); - System.out.println(fieldName.get(0).equals("landmarkName"));//assert - List<String> fieldMessage = violationsName.stream().map((ConstraintViolation::getMessage)).map(Object::toString).toList(); - System.out.println(fieldMessage.get(0).equals("You must type in a username.")); //assert - - landmark.setLandmarkName("Mock"); - landmark.setLandmarkEmail("aaa"); +public void landmarkJakartaValidationTest() { + Landmarks landmark = new Landmarks("99", 1, "MockLandmark", "Mock@Mock2.com", + "MockLandmarkDesc", "MockRisca", "MockImage"); + Set<ConstraintViolation<Landmarks>> violations = validator.validate(landmark); + //nothing wrong with chosen Landmark wrt violations + assertTrue(violations.isEmpty()); + + //test landmarkName @NotEmpty() verification. + landmark.setLandmarkName(""); + Set<ConstraintViolation<Landmarks>> violationsName = validator.validate(landmark); + assertFalse(violationsName.isEmpty()); + //verify violation message matches correct variable and both are correct + List<String> fieldName = violationsName.stream().map((ConstraintViolation::getPropertyPath)).map(Object::toString).toList(); + List<String> fieldNameMessage = violationsName.stream().map((ConstraintViolation::getMessage)).map(Object::toString).toList(); + assertEquals(fieldName.get(0), "landmarkName"); + assertEquals(fieldNameMessage.get(0), "You must type in a username."); //assert + landmark.setLandmarkName("MockName"); + //test @NotEmpty on email variable. + landmark.setLandmarkEmail(""); + Set<ConstraintViolation<Landmarks>> violationsEmailOne = validator.validate(landmark); + List<String> fieldEmailEmpty = violationsEmailOne.stream().map((ConstraintViolation::getPropertyPath)).map(Object::toString).toList(); + List<String> fieldEmailMessageEmpty = violationsEmailOne.stream().map((ConstraintViolation::getMessage)).map(Object::toString).toList(); + assertEquals(fieldEmailEmpty.get(0), "landmarkEmail"); + assertEquals(fieldEmailMessageEmpty.get(0), "You must attach a contact address."); + //Test @Email() verification + landmark.setLandmarkEmail("NotValidEmail"); + Set<ConstraintViolation<Landmarks>> violationsEmailTwo = validator.validate(landmark); + List<String> fieldEmailWrong = violationsEmailTwo.stream().map((ConstraintViolation::getPropertyPath)).map(Object::toString).toList(); + List<String> fieldEmailMessageWrong = violationsEmailTwo.stream().map((ConstraintViolation::getMessage)).map(Object::toString).toList(); + assertEquals(fieldEmailWrong.get(0), "landmarkEmail"); + assertEquals(fieldEmailMessageWrong.get(0), "You must attach a valid contact address."); + } - Set<ConstraintViolation<Landmarks>> violationsEmail = validator.validate(landmark); -// List<String> fieldName = violationsName.stream().map((ConstraintViolation::getPropertyPath)).map(Object::toString).toList(); -// System.out.println(fieldName.get(0).equals("landmarkName"));//assert -// List<String> fieldMessage = violationsName.stream().map((ConstraintViolation::getMessage)).map(Object::toString).toList(); -// System.out.println(fieldMessage.get(0).equals("You must type in a username.")); //assert - // System.out.println(violationsEmail.get(0)); @@ -69,7 +76,6 @@ public void landmarkJakartaValidationTest(){ -} @Test @Order(1) @@ -233,6 +239,6 @@ public void landmarkJakartaValidationTest(){ } - +//todo test town? diff --git a/src/test/resources/application-test.properties b/src/test/resources/application-test.properties index 7534d0fa..04c65fe4 100644 --- a/src/test/resources/application-test.properties +++ b/src/test/resources/application-test.properties @@ -13,4 +13,4 @@ spring.jpa.database-platform=org.hibernate.dialect.H2Dialect #org.springframework.jdbc.datasource.init=debug #org.springframework.test.context.jdbc=debug -#spring.sql.init.data-locations=classpath:schema-h2.sql, classpath:data-h2.sql \ No newline at end of file +spring.sql.init.data-locations=classpath:schema-h2.sql, classpath:data-h2.sql \ No newline at end of file diff --git a/src/test/resources/data-h2.sql b/src/test/resources/data-h2.sql index ee63ca20..0cfd02b8 100644 --- a/src/test/resources/data-h2.sql +++ b/src/test/resources/data-h2.sql @@ -1,3 +1,7 @@ + + + + delete from trails; insert into trails ( trailID, trailName, trailNumber, city) values ( 0101,'Caerphilly Castle Trail','0101', 'Caerphilly'); insert into trails ( trailID, trailName, trailNumber, city) values ( 0102,'Caerphilly Pub Trail','0102', 'Caerphilly'); @@ -6,7 +10,7 @@ insert into trails ( trailID, trailName, trailNumber, city) values ( 0201,'Risca insert into trails ( trailID, trailName, trailNumber, city) values ( 0301,'Penarth Esplanade Trail','0301', 'Penarth'); delete from locations; -insert into locations ( locationName , locationEmail,locationDescription,locationPlace, locationTrailID, locationApproved) values ( 'St Cenydd','','Location description here','Caerphilly',0101, false); +insert into locations ( locationName , locationEmail,locationDescription,locationPlace, locationTrailID, locationApproved) values ( 'MockBusiness','MockEmail@Hello.com','MockDescription','Caerphilly',0101, false); insert into locations ( locationName , locationEmail,locationDescription,locationPlace, locationTrailID, locationApproved) values ( 'The Castle','','Location description here','Caerphilly',0101, true); insert into locations ( locationName , locationEmail,locationDescription,locationPlace, locationTrailID, locationApproved) values ( 'Medieval Trades','','Location description here','Caerphilly',0101, true); insert into locations ( locationName , locationEmail,locationDescription,locationPlace, locationTrailID, locationApproved) values ( 'The Queen''s War','','Location description here','Caerphilly',0101, true); @@ -30,6 +34,8 @@ insert into locations ( locationName , locationEmail,locationDescription,locatio insert into locations ( locationName , locationEmail,locationDescription,locationPlace, locationTrailID, locationApproved) values ( 'The Esplanade','','Location description here','Penarth',0301, true); insert into locations ( locationName , locationEmail,locationDescription,locationPlace, locationTrailID, locationApproved) values ( 'The Old Swimming Baths','','Location description here','Penarth',0301, true); +insert into locations ( locationName , locationEmail,locationDescription,locationPlace, locationTrailID, locationApproved) values ( 'St Cenydd','','Location description here','Caerphilly',0101, false); + -- GitLab