Commit 9310fd83 authored by Matija Obreza's avatar Matija Obreza

Unit testing improved

parent 9b573166
......@@ -19,11 +19,15 @@ log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.target=System.out
log4j.appender.stdout.encoding=UTF-8
log4j.appender.stdout.layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %t %5p %c{1.}:%L - %m%n
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %t %5p %c:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=error, stdout
log4j.category.org.genesys.blocks=debug
#log4j.category.org.genesys.blocks.auditlog=trace
\ No newline at end of file
#log4j.category.org.genesys.blocks=debug
#log4j.category.org.genesys.blocks.auditlog=trace
## Shut up hsql
log4j.category.org.hibernate.tool.hbm2ddl.SchemaExport=fatal
log4j.category.org.hibernate.engine.jdbc.spi.SqlExceptionHelper=fatal
......@@ -75,6 +75,67 @@
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>7.0.42</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
......@@ -38,10 +38,11 @@ public abstract class UuidEntity extends AuditedVersionedModel implements IdUUID
protected UUID uuid;
/**
* Prepersist.
* {@inheritDoc}
*/
@PrePersist
private void prepersist() {
protected void prepersist() {
super.prepersist();
if (this.uuid == null) {
this.uuid = UUID.randomUUID();
}
......
......@@ -17,6 +17,7 @@ package org.genesys.blocks.model;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.Version;
import com.fasterxml.jackson.annotation.JsonView;
......@@ -40,6 +41,14 @@ public abstract class VersionedModel extends BasicModel implements Activatable {
@Column(nullable = false)
protected boolean active = true;
/**
* First persisted version is 1
*/
@PrePersist
protected void prepersist() {
version = 1;
}
/**
* Gets the version.
*
......
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.config;
import java.util.Arrays;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
@Configuration
@EnableAspectJAutoProxy
@Import({ DatabaseConfig.class })
@ComponentScan(basePackages = { })
public class ApplicationConfig {
@Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
final PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
propertyPlaceholderConfigurer.setIgnoreResourceNotFound(true);
propertyPlaceholderConfigurer.setFileEncoding("utf-8");
propertyPlaceholderConfigurer.setLocations(new ClassPathResource("application.properties"));
return propertyPlaceholderConfigurer;
}
@Bean
public CacheManager cacheManager() {
final SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("default")));
return cacheManager;
}
}
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author Matija Obreza
* @author Maxym Borodenko
*/
@Configuration
@EnableJpaRepositories(basePackages = { "org.genesys.blocks.persistence" }, repositoryImplementationPostfix = "CustomImpl", entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager")
@EnableTransactionManagement
@EnableJpaAuditing(modifyOnCreate = true)
public class DatabaseConfig {
private static final String[] JPA_PACKAGES = { "org.genesys.blocks.model" };
@Value("${db.url}")
private String dbUrl;
@Value("${db.driverClassName}")
private String dbDriverClassName;
@Value("${db.username}")
private String dbUsername;
@Value("${db.password}")
private String dbPassword;
@Value("${db.showSql}")
private boolean dbShowSql;
@Value("${db.updateSchema}")
private boolean dbGenerateDdl;
@Value("${db.hibernate.dialect}")
private String hibernateDialect;
@Value("${db.pool.maxActive}")
private int dbPoolMaxActive;
@Value("${db.pool.initialSize}")
private int dbPoolInitialSize;
@Bean(name = "dataSource")
public DataSource dataSource() throws Exception {
final DataSource dataSource = new DataSource();
dataSource.setUrl(dbUrl);
dataSource.setDriverClassName(dbDriverClassName);
dataSource.setUsername(dbUsername);
dataSource.setPassword(dbPassword);
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestWhileIdle(true);
dataSource.setTestOnBorrow(true);
dataSource.setMaxActive(dbPoolMaxActive);
dataSource.setMaxIdle(dbPoolInitialSize);
dataSource.setInitialSize(dbPoolInitialSize);
dataSource.setMinIdle(dbPoolInitialSize);
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(final DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception {
final LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(dataSource());
bean.setPersistenceUnitName("spring-jpa");
bean.setPackagesToScan(JPA_PACKAGES);
bean.setPersistenceProvider(new HibernatePersistenceProvider());
final HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setShowSql(dbShowSql);
jpaVendorAdapter.setGenerateDdl(dbGenerateDdl);
final Properties jpaProperties = jpaProperties();
bean.setJpaProperties(jpaProperties);
bean.setJpaVendorAdapter(jpaVendorAdapter);
return bean;
}
@Bean(name = "transactionManager")
public PlatformTransactionManager jpaTransactionManager(final EntityManagerFactory entityManagerFactory) throws Exception {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setDataSource(dataSource());
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
private Properties jpaProperties() throws Exception {
final Properties jpaProp = new Properties();
jpaProp.load(getClass().getResourceAsStream("/hibernate.properties"));
jpaProp.put("hibernate.dialect", hibernateDialect);
return jpaProp;
}
}
\ No newline at end of file
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.model;
import javax.persistence.Column;
import javax.persistence.Entity;
@Entity
public class VersionedEntity extends VersionedModel {
private static final long serialVersionUID = 1L;
@Column(nullable = false)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.persistence;
import org.genesys.blocks.model.VersionedEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface VersionedEntityRepository extends JpaRepository<VersionedEntity, Long> {
}
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.tests;
import org.genesys.blocks.config.ApplicationConfig;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Matija Obreza
* @author Maxym Borodenko
*/
@RunWith(SpringJUnit4ClassRunner.class)
@EnableAspectJAutoProxy
@ContextConfiguration(name = "root", classes = { ApplicationConfig.class })
public abstract class BaseTest {
protected final Logger LOG = LoggerFactory.getLogger(getClass());
@AfterTransaction
@Transactional
public void cleanup() {
LOG.trace("Deleting all from ...");
}
}
\ No newline at end of file
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.security.tests;
package org.genesys.blocks.tests;
import org.junit.After;
import org.junit.Before;
......
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.model;
package org.genesys.blocks.tests.model;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
......@@ -29,6 +29,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.genesys.blocks.model.Copyable;
import org.junit.Test;
public class CopyableTest {
......
/*
* Copyright 2017 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.blocks.tests.model;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import org.genesys.blocks.model.VersionedEntity;
import org.genesys.blocks.tests.ServiceTest;
import org.junit.Test;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class VersionedModelTest extends ServiceTest {
@Test
public void idIsNotNull() {
VersionedEntity entity=new VersionedEntity();
assertThat(entity.getId(), not(nullValue()));
}
@Test
public void versionIsNull() {
VersionedEntity entity=new VersionedEntity();
assertThat(entity.getVersion(), nullValue());
}
}
# Database connection
db.url=jdbc:hsqldb:mem:test;sql.syntax_mys=true;sql.ignore_case=true
db.driverClassName=org.hsqldb.jdbc.JDBCDriver
db.hibernate.dialect=org.genesys.blocks.util.BetterHSQLDialect
db.showSql=false
db.updateSchema=true
# Connection pool
db.username=root
db.password=
# Connection pool
db.pool.initialSize=1
db.pool.maxActive=5
javax.persistence.sharedCache.mode=ENABLE_SELECTIVE
hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
hibernate.hbm2ddl.auto=create-drop
hibernate.connection.charSet=utf8
hibernate.connection.autocommit=false
hibernate.jdbc.fetch_size=25
hibernate.jdbc.batch_size=20
hibernate.order_updates=true
hibernate.order_inserts=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.use_minimal_puts=true
hibernate.cache.region_prefix=hibernate
#MEM:hibernate.cache.region.factory_class=org.hibernate.testing.cache.CachingRegionFactory
#Hazel:hibernate.cache.region.factory_class=com.hazelcast.hibernate.HazelcastCacheRegionFactory
#Hazel:hibernate.cache.region.factory_class=org.genesys2.spring.hazelcast.HazelcastCacheRegionFactoryWrapper
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.use_structured_entries=false
hibernate.generate_statistics=false
#-------------------------------------------------------------------------------
# Copyright 2017 Global Crop Diversity Trust
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#-------------------------------------------------------------------------------
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.target=System.err
log4j.appender.stdout.encoding=UTF-8
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %t %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=error, stdout
log4j.category.org.genesys.blocks=info
......@@ -67,15 +67,30 @@
<build>
<plugins>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>${nexus-staging-maven-plugin.version}</version>
<extensions>true</extensions>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.0.1</version>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
<flattenMode>ossrh</flattenMode>
</configuration>
<executions>
<!-- enable flattening -->
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<!-- ensure proper cleanup -->
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- do not deploy artifacts by default -->
<!-- <plugin>
......@@ -166,7 +181,7 @@
<version>3.3.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
......@@ -187,7 +202,7 @@
<version>${jackson.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
......@@ -216,14 +231,14 @@
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>${tomcat-jdbc.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
......
......@@ -27,14 +27,14 @@ import com.google.common.collect.Lists;
import org.genesys.blocks.security.NotUniqueUserException;
import org.genesys.blocks.security.UserException;
import org.genesys.blocks.security.model.AclEntity;
import org.genesys.blocks.security.model.BasicUser.AccountType;
import org.genesys.blocks.security.model.TestUser;
import org.genesys.blocks.security.model.BasicUser.AccountType;
import org.genesys.blocks.security.persistence.AclEntityPersistence;
import org.genesys.blocks.security.persistence.AclEntryPersistence;
import org.genesys.blocks.security.persistence.AclObjectIdentityPersistence;
import org.genesys.blocks.security.service.CustomAclService;
import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException;
import org.genesys.blocks.security.tests.BaseTest;
import org.genesys.blocks.security.test.BaseTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
......
......@@ -23,9 +23,9 @@ import com.google.common.collect.Sets;
import org.genesys.blocks.oauth.service.OAuthServiceImpl;
import org.genesys.blocks.security.NotUniqueUserException;
import org.genesys.blocks.security.model.BasicUser.AccountType;
import org.genesys.blocks.security.model.TestUser;
import org.genesys.blocks.security.model.UserRole;
import org.genesys.blocks.security.model.BasicUser.AccountType;
import org.genesys.blocks.security.persistence.TestUserPersistence;
import org.genesys.blocks.security.service.BasicUserService;
import org.genesys.blocks.security.service.PasswordPolicy.PasswordPolicyException;
......
......@@ -20,6 +20,7 @@ import javax.persistence.Column;
import javax.persistence.Entity;
import org.genesys.blocks.model.BasicModel;
import org.genesys.blocks.security.model.AclAwareModel;
/**
* Sample entity with ACL support
......
......@@ -18,6 +18,8 @@ package org.genesys.blocks.security.model;
import javax.persistence.Entity;
import org.genesys.blocks.security.model.BasicUser;
@Entity
public class TestUser extends BasicUser<UserRole> {
private static final long serialVersionUID = 1L;
......
......@@ -22,7 +22,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
import org.genesys.blocks.security.tests.ServiceTest;
import org.genesys.blocks.security.test.ServiceTest;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
......