Added Pet´s tests to the project

parent 1da8652a
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 24-02-2017 a las 13:08:34
-- Versión del servidor: 10.1.9-MariaDB
-- Versión de PHP: 5.6.15
CREATE DATABASE `daaexample`;
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `daaexample`
--
CREATE DATABASE IF NOT EXISTS `daaexample` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `daaexample`;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `people`
--
DROP TABLE IF EXISTS `people`;
CREATE TABLE `people` (
`id` int(11) NOT NULL,
CREATE TABLE `daaexample`.`people` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`surname` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- RELACIONES PARA LA TABLA `people`:
--
-- --------------------------------------------------------
`surname` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
--
-- Estructura de tabla para la tabla `pet`
--
DROP TABLE IF EXISTS `pet`;
CREATE TABLE `pet` (
`id` int(11) NOT NULL,
CREATE TABLE `daaexample`.`pet` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`breed` varchar(45) DEFAULT NULL,
`idOwner` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- RELACIONES PARA LA TABLA `pet`:
-- `idOwner`
-- `people` -> `id`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `users`
--
`breed` varchar(45) NOT NULL,
`idOwner` int NOT NULL
PRIMARY KEY (`id`)
);
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
CREATE TABLE `daaexample`.`users` (
`login` varchar(100) NOT NULL,
`password` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- RELACIONES PARA LA TABLA `users`:
--
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `people`
--
ALTER TABLE `people`
ADD PRIMARY KEY (`id`);
`password` varchar(64) NOT NULL,
PRIMARY KEY (`login`)
);
--
-- Indices de la tabla `pet`
--
ALTER TABLE `pet`
ADD PRIMARY KEY (`id`),
ADD KEY `idOwner_idx` (`idOwner`);
ALTER TABLE `pet` ADD CONSTRAINT `idOwner` FOREIGN KEY (`idOwner`) REFERENCES `people` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Indices de la tabla `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`login`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
GRANT ALL ON `daaexample`.* TO 'daa'@'localhost' IDENTIFIED BY 'daa';
--
-- AUTO_INCREMENT de la tabla `people`
--
ALTER TABLE `people`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT de la tabla `pet`
--
ALTER TABLE `pet`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- Restricciones para tablas volcadas
--
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Antón','Pérez');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Manuel','Martínez');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Laura','Reboredo');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Perico','Palotes');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Ana','María');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'María','Nuevo');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Alba','Fernández');
INSERT INTO `daaexample`.`people` (`id`,`name`,`surname`) VALUES (0,'Asunción','Jiménez');
--
-- Filtros para la tabla `pet`
--
ALTER TABLE `pet`
ADD CONSTRAINT `idOwner` FOREIGN KEY (`idOwner`) REFERENCES `people` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
INSERT INTO `daaexample`.`pet` (`id`,`name`,`breed`, `idOwner`) VALUES (0,'Jackye','Pitbull', '1');
INSERT INTO `daaexample`.`pet` (`id`,`name`,`breed`, `idOwner`) VALUES (0,'Robert','Persian cat', '2');
INSERT INTO `daaexample`.`pet` (`id`,`name`,`breed`, `idOwner`) VALUES (0,'Milles','Hot dog', '3');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-- The password for each user is its login suffixed with "pass". For example, user "admin" has the password "adminpass".
INSERT INTO `daaexample`.`users` (`login`,`password`) VALUES ('admin', '43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70');
INSERT INTO `daaexample`.`users` (`login`,`password`) VALUES ('normal', '688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336');
CREATE DATABASE `daaexample`;
CREATE TABLE `daaexample`.`people` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`surname` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `daaexample`.`pets` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`breed` varchar(100) NOT NULL,
`idOwner` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `daaexample`.`users` (
`login` varchar(100) NOT NULL,
`password` varchar(64) NOT NULL,
PRIMARY KEY (`login`)
);
GRANT ALL ON `daaexample`.* TO 'daa'@'localhost' IDENTIFIED BY 'daa';
......@@ -3,6 +3,7 @@
*/
var PetsView = (function() {
var dao;
var peopleDAO;
// Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery.
var self;
......@@ -12,8 +13,9 @@ var PetsView = (function() {
var formQuery = '#' + formId;
var listQuery = '#' + listId;
function PetsView(petsDao, formContainerId, listContainerId) {
function PetsView(petsDao, peopleDao, formContainerId, listContainerId) {
dao = petsDao;
peopleDAO = peopleDao;
self = this;
insertPetsForm($('#' + formContainerId));
......@@ -135,11 +137,17 @@ var PetsView = (function() {
}
var insertPetsForm = function(parent) {
var l = peopleDAO.listPeople();
parent.append(
'<form id="' + formId + '">\
<input name="id" type="hidden" value=""/>\
<input name="name" type="text" value="" />\
<input name="breed" type="text" value=""/>\
<select>\n\
<option name="id" value="' + l[i].$1 + '">' + l[i].$2 + '</option>\n\
</select>\
<input name="idOwner" type="text" value=""/>\
<input id="btnSubmit" type="submit" value="Create"/>\
<input id="btnClear" type="reset" value="Limpiar"/>\
......
......@@ -27,7 +27,7 @@
<script type="text/javascript" src="js/view/pets.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var view = new PetsView(new PetsDAO(), 'pet-container', 'pet-container');
var view = new PetsView(new PetsDAO(), new PeopleDAO, 'pet-container', 'pet-container');
view.init();
});
......
package es.uvigo.esei.daa.dao;
/**
* Created by Alex on 08/03/2017.
*/
import static com.sun.org.apache.xerces.internal.util.PropertyState.is;
import static es.uvigo.esei.daa.dataset.PetDataset.*;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.containsPetsInAnyOrder;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.equalsToPet;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.reset;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.sql.SQLException;
import org.junit.Test;
import com.mysql.jdbc.Statement;
import es.uvigo.esei.daa.entities.Pet;
import es.uvigo.esei.daa.util.DatabaseQueryUnitTest;
public class PetDAOUnitTest extends DatabaseQueryUnitTest {
@Test
public void testList() throws Exception {
final Pet[] pets = pets();
for (Pet pet : pets) {
expectPetRow(pet);
}
expect(result.next()).andReturn(false);
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
assertThat(petDAO.list(), containsPetsInAnyOrder(pets));
}
@Test(expected = DAOException.class)
public void testListUnexpectedException() throws Exception {
expect(result.next()).andThrow(new SQLException());
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.list();
}
@Test
public void testGet() throws Exception {
final Pet existentPet = existentPet();
expectPetRow(existentPet);
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
assertThat(petDAO.get(existentId()), is(equalTo(existentPet)));
}
@Test(expected = IllegalArgumentException.class)
public void testGetMissing() throws Exception {
expect(result.next()).andReturn(false);
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.get(existentId());
}
@Test(expected = DAOException.class)
public void testGetUnexpectedException() throws Exception {
expect(result.next()).andThrow(new SQLException());
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.get(existentId());
}
@Test
public void testAdd() throws Exception {
final Pet pet = newPet();
reset(connection);
expect(connection.prepareStatement(anyString(), eq(Statement.RETURN_GENERATED_KEYS)))
.andReturn(statement);
expect(statement.executeUpdate()).andReturn(1);
expect(statement.getGeneratedKeys()).andReturn(result);
// Key retrieval
expect(result.next()).andReturn(true);
expect(result.getInt(1)).andReturn(pet.getId());
connection.close();
result.close();
replayAll();
final PetDAO petDAO = new PetDAO();
final Pet newPet = petDAO.add(pet.getName(), pet.getBreed(), pet.getIdOwner());
assertThat(newPet, is(equalsToPet(pet)));
}
@Test(expected = IllegalArgumentException.class)
public void testAddNullName() throws Exception {
replayAll();
final PetDAO petDAO = new PetDAO();
resetAll(); // No expectations
petDAO.add(null, newBreed(), newIdOwner());
}
@Test(expected = IllegalArgumentException.class)
public void testAddNullBreed() throws Exception {
replayAll();
final PetDAO petDAO = new PetDAO();
resetAll(); // No expectations
petDAO.add(newName(), null, newIdOwner());
}
@Test(expected = DAOException.class)
public void testAddZeroUpdatedRows() throws Exception {
reset(connection);
expect(connection.prepareStatement(anyString(), eq(1)))
.andReturn(statement);
expect(statement.executeUpdate()).andReturn(0);
connection.close();
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.add(newName(), newBreed(), newIdOwner());
}
@Test(expected = DAOException.class)
public void testAddNoGeneratedKey() throws Exception {
reset(connection);
expect(connection.prepareStatement(anyString(), eq(1)))
.andReturn(statement);
expect(statement.executeUpdate()).andReturn(1);
expect(statement.getGeneratedKeys()).andReturn(result);
expect(result.next()).andReturn(false);
result.close();
connection.close();
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.add(newName(), newBreed(), newIdOwner());
}
@Test(expected = DAOException.class)
public void testAddUnexpectedException() throws Exception {
reset(connection);
expect(connection.prepareStatement(anyString(), eq(1)))
.andReturn(statement);
expect(statement.executeUpdate()).andThrow(new SQLException());
connection.close();
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.add(newName(), newBreed(), newIdOwner());
}
@Test
public void testDelete() throws Exception {
expect(statement.executeUpdate()).andReturn(1);
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.delete(existentId());
}
@Test(expected = IllegalArgumentException.class)
public void testDeleteInvalidId() throws Exception {
expect(statement.executeUpdate()).andReturn(0);
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.delete(existentId());
}
@Test(expected = DAOException.class)
public void testDeleteUnexpectedException() throws Exception {
expect(statement.executeUpdate()).andThrow(new SQLException());
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.delete(existentId());
}
@Test
public void testModify() throws Exception {
expect(statement.executeUpdate()).andReturn(1);
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.modify(existentPet());
}
@Test(expected = IllegalArgumentException.class)
public void testModifyNullPet() throws Exception {
replayAll();
final PetDAO petDAO = new PetDAO();
resetAll(); // No expectations
petDAO.modify(null);
}
@Test(expected = IllegalArgumentException.class)
public void testModifyZeroUpdatedRows() throws Exception {
expect(statement.executeUpdate()).andReturn(0);
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.modify(existentPet());
}
@Test(expected = DAOException.class)
public void testModifyUnexpectedException() throws Exception {
expect(statement.executeUpdate()).andThrow(new SQLException());
replayAll();
final PetDAO petDAO = new PetDAO();
petDAO.modify(existentPet());
}
private void expectPetRow(Pet pet) throws SQLException {
expect(result.next()).andReturn(true);
expect(result.getInt("id")).andReturn(pet.getId());
expect(result.getString("name")).andReturn(pet.getName());
expect(result.getString("breed")).andReturn(pet.getBreed());
expect(result.getInt("idOwner")).andReturn(pet.getIdOwner());
}
}
package es.uvigo.esei.daa.dao;
/**
* Created by Alex on 08/03/2017.
*/
import static com.sun.org.apache.xerces.internal.util.PropertyState.is;
import static es.uvigo.esei.daa.dataset.PetDataset.*;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.containsPetsInAnyOrder;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.equalsToPet;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import es.uvigo.esei.daa.entities.Pet;
import es.uvigo.esei.daa.listeners.ApplicationContextBinding;
import es.uvigo.esei.daa.listeners.ApplicationContextJndiBindingTestExecutionListener;
import es.uvigo.esei.daa.listeners.DbManagement;
import es.uvigo.esei.daa.listeners.DbManagementTestExecutionListener;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:contexts/mem-context.xml")
@TestExecutionListeners({
DbUnitTestExecutionListener.class,
DbManagementTestExecutionListener.class,
ApplicationContextJndiBindingTestExecutionListener.class
})
@ApplicationContextBinding(
jndiUrl = "java:/comp/env/jdbc/daaexample",
type = DataSource.class
)
@DbManagement(
create = "classpath:db/hsqldb.sql",
drop = "classpath:db/hsqldb-drop.sql"
)
@DatabaseSetup("/datasets/dataset.xml")
@ExpectedDatabase("/datasets/dataset.xml")
public class PetsDAOTest {
private PetDAO dao;
@Before
public void setUp() throws Exception {
this.dao = new PetDAO();
}
@Test
public void testList() throws DAOException {
assertThat(this.dao.list(), containsPetsInAnyOrder(pets()));
}
@Test
public void testGet() throws DAOException {
final Pet pet = this.dao.get(existentId());
assertThat(pet, is(equalsToPet(existentPet())));
}
@Test(expected = IllegalArgumentException.class)
public void testGetNonExistentId() throws DAOException {
this.dao.get(nonExistentId());
}
@Test
@ExpectedDatabase("/datasets/dataset-delete.xml")
public void testDelete() throws DAOException {
this.dao.delete(existentId());
assertThat(this.dao.list(), containsPetsInAnyOrder(petsWithout(existentId())));
}
@Test(expected = IllegalArgumentException.class)
public void testDeleteNonExistentId() throws DAOException {
this.dao.delete(nonExistentId());
}
@Test
@ExpectedDatabase("/datasets/dataset-modify.xml")
public void testModify() throws DAOException {
final Pet pet = existentPet();
pet.setName(newName());
pet.setBreed(newBreed());
pet.setIdOwner(newIdOwner());
this.dao.modify(pet);
final Pet persistentPet = this.dao.get(pet.getId());
assertThat(persistentPet, is(equalsToPet(pet)));
}
@Test(expected = IllegalArgumentException.class)
public void testModifyNonExistentId() throws DAOException {
this.dao.modify(nonExistentPet());
}
@Test(expected = IllegalArgumentException.class)
public void testModifyNullPerson() throws DAOException {
this.dao.modify(null);
}
@Test
@ExpectedDatabase("/datasets/dataset-add.xml")
public void testAdd() throws DAOException {
final Pet pet = this.dao.add(newName(), newBreed(), newIdOwner());
assertThat(pet, is(equalsToPet(newPet())));
final Pet persistentPerson = this.dao.get(pet.getId());
assertThat(persistentPerson, is(equalsToPet(newPet())));
}
@Test(expected = IllegalArgumentException.class)
public void testAddNullName() throws DAOException {
this.dao.add(null, newBreed(), newIdOwner());
}
@Test(expected = IllegalArgumentException.class)
public void testAddNullSurname() throws DAOException {
this.dao.add(newName(), null, newIdOwner());
}
}
\ No newline at end of file
package es.uvigo.esei.daa.dataset;
/**
* Created by Alex on 08/03/2017.
*/
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.stream;
import java.util.Arrays;
import java.util.function.Predicate;
import es.uvigo.esei.daa.entities.Pet;
public class PetDataset {
private PetDataset() {}
public static Pet[] pets() {
return new Pet[] {
new Pet(1, "Jackye", "Pitbull", 1),
new Pet(2, "Robert", "Persian cat", 2),
new Pet(3, "Miles", "Hot dog", 3),
};
}
public static Pet[] petsWithout(int ... ids) {
Arrays.sort(ids);
final Predicate<Pet> hasValidId = pets ->
binarySearch(ids, pets.getId()) < 0;
return stream(pets())
.filter(hasValidId)
.toArray(Pet[]::new);
}
public static Pet pet(int id) {
return stream(pets())
.filter(pets -> pets.getId() == id)
.findAny()
.orElseThrow(IllegalArgumentException::new);
}
public static int existentId() {
return 5;
}
public static int nonExistentId() {
return 1234;
}
public static Pet existentPet() {
return pet(existentId());
}
public static Pet nonExistentPet() {
return new Pet(nonExistentId(), "Pico Pato", "Bird", 1);
}
public static String newName() {
return "Jackye";
}
public static String newBreed() {
return "Pitbull";
}
public static int newIdOwner() {
return 1;
}
public static Pet newPet() {
return new Pet(pets().length + 1, newName(), newBreed(), newIdOwner());
}
}
package es.uvigo.esei.daa.entities;
/**
* Created by Alex on 07/03/2017.
*/
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
public class PetUnitTest {
@Test
public void testPetIntStringStringInt() {
final int id = 1;
final String name = "Jackye";
final String breed = "Pitbull";
final int idOwner = 1;
final Pet pet = new Pet(id, name, breed, idOwner);
assertThat(pet.getId(), is(equalTo(id)));
assertThat(pet.getName(), is(equalTo(name)));
assertThat(pet.getBreed(), is(equalTo(breed)));
assertThat(pet.getIdOwner(), is(equalTo(idOwner)));
}
@Test(expected = NullPointerException.class)
public void testPetIntStringStringIntNullName() {
new Pet(1, null, "Pitbull", 1);
}
@Test(expected = NullPointerException.class)
public void testPetIntStringStringIntNullBreed() {
new Pet(1, "Jackye", null, 1);
}
@Test
public void testSetName() {
final int id = 1;
final String breed = "Doe";
final int idOwner = 1;
final Pet pet = new Pet(id, "John", breed, idOwner);
pet.setName("Juan");
assertThat(pet.getId(), is(equalTo(id)));
assertThat(pet.getName(), is(equalTo("Juan")));
assertThat(pet.getBreed(), is(equalTo(breed)));
}
@Test(expected = NullPointerException.class)
public void testSetNullName() {
final Pet pet = new Pet(1, "John", "Doe", 1);
pet.setName(null);
}
@Test
public void testSetBreed() {
final int id = 1;
final String name = "Jackye";
final int idOwner = 1;
final Pet pet = new Pet(id, name, "Chiwaka", 1);
pet.setBreed("Pitbull");
assertThat(pet.getId(), is(equalTo(id)));
assertThat(pet.getName(), is(equalTo(name)));
assertThat(pet.getBreed(), is(equalTo("Pitbull")));
assertThat(pet.getIdOwner(), is(equalTo(idOwner)));
}
@Test(expected = NullPointerException.class)
public void testSetNullBreed() {
final Pet pet = new Pet(1, "John", "Doe", 1);
pet.setBreed(null);
}
@Test
public void testEqualsObject() {
final Pet petA = new Pet(1, "Name A", "Breed A",1);
final Pet petB = new Pet(1, "Name B", "Breed B", 2);
assertTrue(petA.equals(petB));
}
@Test
public void testEqualsHashcode() {
EqualsVerifier.forClass(Pet.class)
.withIgnoredFields("name", "breed", "idOwner")
.suppress(Warning.STRICT_INHERITANCE)
.suppress(Warning.NONFINAL_FIELDS)
.verify();
}
}
\ No newline at end of file
package es.uvigo.esei.daa.matchers;
/**
* Created by Alex on 08/03/2017.
*/
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import es.uvigo.esei.daa.entities.Pet;
public class IsEqualToPet extends IsEqualToEntity<Pet>{
public IsEqualToPet(Pet entity) {
super(entity);
}
@Override
protected boolean matchesSafely(Pet actual) {
this.clearDescribeTo();
if (actual == null) {
this.addTemplatedDescription("actual", expected.toString());
return false;
} else {
return checkAttribute("id", Pet::getId, actual)
&& checkAttribute("name", Pet::getName, actual)
&& checkAttribute("surname", Pet::getBreed, actual)
&& checkAttribute("idOwner", Pet::getIdOwner, actual);
}
}
/**
* Factory method that creates a new {@link IsEqualToEntity} matcher with
* the provided {@link Pet} as the expected value.
*
* @param pet the expected pet.
* @return a new {@link IsEqualToEntity} matcher with the provided
* {@link Pet} as the expected value.
*/
@Factory
public static IsEqualToPet equalsToPet(Pet pet) {
return new IsEqualToPet(pet);
}
/**
* Factory method that returns a new {@link Matcher} that includes several
* {@link IsEqualToPet} matchers, each one using an {@link Pet} of the
* provided ones as the expected value.
*
* @param pets the pets to be used as the expected values.
* @return a new {@link Matcher} that includes several
* {@link IsEqualToPet} matchers, each one using an {@link Pet} of the
* provided ones as the expected value.
* @see IsEqualToEntity#containsEntityInAnyOrder(java.util.function.Function, Object...)
*/
@Factory
public static Matcher<Iterable<? extends Pet>> containsPetsInAnyOrder(Pet ... pets) {
return containsEntityInAnyOrder(IsEqualToPet::equalsToPet, pets);
}
}
package es.uvigo.esei.daa.rest;
/**
* Created by Alex on 08/03/2017.
*/
import static com.sun.org.apache.xerces.internal.util.PropertyState.is;
import static es.uvigo.esei.daa.dataset.PetDataset.*;
import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasBadRequestStatus;
import static es.uvigo.esei.daa.matchers.HasHttpStatus.hasOkStatus;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.containsPetsInAnyOrder;
import static es.uvigo.esei.daa.matchers.IsEqualToPet.equalsToPet;
import static javax.ws.rs.client.Entity.entity;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static sun.plugin.javascript.navig.JSType.Form;
import java.io.IOException;
import java.util.List;
import javax.sql.DataSource;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import es.uvigo.esei.daa.DAAExampleApplication;
import es.uvigo.esei.daa.entities.Pet;
import es.uvigo.esei.daa.listeners.ApplicationContextBinding;
import es.uvigo.esei.daa.listeners.ApplicationContextJndiBindingTestExecutionListener;
import es.uvigo.esei.daa.listeners.DbManagement;
import es.uvigo.esei.daa.listeners.DbManagementTestExecutionListener;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:contexts/mem-context.xml")
@TestExecutionListeners({
DbUnitTestExecutionListener.class,
DbManagementTestExecutionListener.class,
ApplicationContextJndiBindingTestExecutionListener.class
})
@ApplicationContextBinding(
jndiUrl = "java:/comp/env/jdbc/daaexample",
type = DataSource.class
)
@DbManagement(
create = "classpath:db/hsqldb.sql",
drop = "classpath:db/hsqldb-drop.sql"
)
@DatabaseSetup("/datasets/dataset.xml")
@ExpectedDatabase("/datasets/dataset.xml")
public class PetResourceTest extends JerseyTest{
@Override
protected Application configure() {
return new DAAExampleApplication();
}
@Override
protected void configureClient(ClientConfig config) {
super.configureClient(config);
// Enables JSON transformation in client
config.register(JacksonJsonProvider.class);
config.property("com.sun.jersey.api.json.POJOMappingFeature", Boolean.TRUE);
}
@Test
public void testList() throws IOException {
final Response response = target("pets").request().get();
assertThat(response, hasOkStatus());
final List<Pet> pets = response.readEntity(new GenericType<List<Pet>>(){});
assertThat(pets, containsPetsInAnyOrder(pets()));
}
@Test
public void testGet() throws IOException {
final Response response = target("pets/" + existentId()).request().get();
assertThat(response, hasOkStatus());
final Pet pet = response.readEntity(Pet.class);
assertThat(pet, is(equalsToPet(existentPet())));
}
@Test
public void testGetInvalidId() throws IOException {
final Response response = target("pets/" + nonExistentId()).request().get();
assertThat(response, hasBadRequestStatus());
}
@Test
@ExpectedDatabase("/datasets/dataset-add.xml")
public void testAdd() throws IOException {
final Form form = new Form();
form.param("name", newName());
form.param("breed", newBreed());
form.param("idOwner", Integer.toString(newIdOwner()));
final Response response = target("pets")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasOkStatus());
final Pet pet = response.readEntity(Pet.class);
assertThat(pet, is(equalsToPet(newPet())));
}
@Test
public void testAddMissingName() throws IOException {
final Form form = new Form();
form.param("breed", newBreed());
form.param("idOwner", Integer.toString(newIdOwner()));
final Response response = target("pets")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
public void testAddMissingBreed() throws IOException {
final Form form = new Form();
form.param("name", newName());
form.param("idOwner", Integer.toString(newIdOwner()));
final Response response = target("people")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
@ExpectedDatabase("/datasets/dataset-modify.xml")
public void testModify() throws IOException {
final Form form = new Form();
form.param("name", newName());
form.param("breed", newBreed());
form.param("idOwner", Integer.toString(newIdOwner()));
final Response response = target("pets/" + existentId())
.request(MediaType.APPLICATION_JSON_TYPE)
.put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasOkStatus());
final Pet modifiedPerson = response.readEntity(Pet.class);
final Pet pet = existentPet();
pet.setName(newName());
pet.setBreed(newBreed());
pet.setIdOwner(newIdOwner());
assertThat(modifiedPerson, is(equalsToPet(pet)));
}
@Test
public void testModifyName() throws IOException {
final Form form = new Form();
form.param("name", newName());
final Response response = target("pets/" + existentId())
.request(MediaType.APPLICATION_JSON_TYPE)
.put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
public void testModifyBreed() throws IOException {
final Form form = new Form();
form.param("breed", newBreed());
final Response response = target("people/" + existentId())
.request(MediaType.APPLICATION_JSON_TYPE)
.put(entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
public void testModifyInvalidId() throws IOException {
final Form form = new Form();
form.param("name", newName());
form.param("breed", newBreed());
form.param("idOwner", Integer.toString(newIdOwner()));
final Response response = target("pets/" + nonExistentId())
.request(MediaType.APPLICATION_JSON_TYPE)
.put(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
assertThat(response, hasBadRequestStatus());
}
@Test
@ExpectedDatabase("/datasets/dataset-delete.xml")
public void testDelete() throws IOException {
final Response response = target("pets/" + existentId()).request().delete();
assertThat(response, hasOkStatus());
final Integer deletedId = response.readEntity(Integer.class);
assertThat(deletedId, is(equalTo(existentId())));
}
@Test
public void testDeleteInvalidId() throws IOException {
final Response response = target("pets/" + nonExistentId()).request().delete();
assertThat(response, hasBadRequestStatus());
}
}
package es.uvigo.esei.daa.rest;
/**
* Created by Alex on 08/03/2017.
*/
public class PetResourceUnitTest {
}
......@@ -14,6 +14,10 @@
<people id="10" name="Juan" surname="Jiménez" />
<people id="11" name="John" surname="Doe" />
<pet id="1" name="Jackye" breed="Pitbull" idOwner="1" />
<pet id="2" name="Robert" breed="Persian cat" idOwner="2" />
<pet id="3" name="Miles" breed="Hot dog" idOwner="3" />
<users login="admin" password="43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70" />
<users login="normal" password="688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336" />
</dataset>
\ No newline at end of file
......@@ -12,6 +12,10 @@
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<pet id="1" name="Jackye" breed="Pitbull" idOwner="1" />
<pet id="2" name="Robert" breed="Persian cat" idOwner="2" />
<pet id="3" name="Miles" breed="Hot dog" idOwner="3" />
<users login="admin" password="43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70" />
<users login="normal" password="688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336" />
</dataset>
\ No newline at end of file
......@@ -13,6 +13,10 @@
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<pet id="1" name="Jackye" breed="Pitbull" idOwner="1" />
<pet id="2" name="Robert" breed="Persian cat" idOwner="2" />
<pet id="3" name="Miles" breed="Hot dog" idOwner="3" />
<users login="admin" password="43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70" />
<users login="normal" password="688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336" />
</dataset>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT dataset (people*, users*)>
<!ELEMENT dataset (people*, pet*,users*)>
<!ELEMENT people EMPTY>
<!ELEMENT pet EMPTY>
<!ELEMENT users EMPTY>
<!ATTLIST people
id CDATA #IMPLIED
name CDATA #IMPLIED
surname CDATA #IMPLIED
>
<!ATTLIST pet
id CDATA #IMPLIED
name CDATA #IMPLIED
breed CDATA #IMPLIED
idOwner CDATA #IMPLIED
>
<!ATTLIST users
login CDATA #IMPLIED
password CDATA #IMPLIED
......
......@@ -13,6 +13,10 @@
<people id="9" name="Julia" surname="Justa" />
<people id="10" name="Juan" surname="Jiménez" />
<pet id="1" name="Jackye" breed="Pitbull" idOwner="1" />
<pet id="2" name="Robert" breed="Persian cat" idOwner="2" />
<pet id="3" name="Miles" breed="Hot dog" idOwner="3" />
<users login="admin" password="43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70" />
<users login="normal" password="688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336" />
</dataset>
\ No newline at end of file
DROP TABLE People IF EXISTS;
DROP TABLE pet IF EXISTS;
DROP TABLE Users IF EXISTS;
......@@ -5,6 +5,14 @@ CREATE TABLE people (
PRIMARY KEY (id)
);
CREATE TABLE people (
id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL,
name VARCHAR(45) NOT NULL,
breed VARCHAR(45) NOT NULL,
idOwner VARCHAR(45) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE users (
login VARCHAR(100) NOT NULL,
password VARCHAR(64) NOT NULL,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment