Remove o.h.testing.junit5 package

This commit is contained in:
Andrea Boriero 2021-04-09 11:10:36 +02:00
parent 4f2b0778d3
commit 9c27e41184
83 changed files with 633 additions and 2217 deletions

View File

@ -11,7 +11,7 @@ import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.cfg.Configuration;
import org.hibernate.testing.ServiceRegistryBuilder;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.orm.junit.FailureExpected;
import org.junit.jupiter.api.Test;
@ -19,7 +19,8 @@ import org.junit.jupiter.api.Test;
* @author Emmanuel Bernard
*/
@FailureExpected( jiraKey = "HHH-3157" )
public class DeepCollectionElementTest extends BaseUnitTest {
@BaseUnitTest
public class DeepCollectionElementTest {
@Test
public void testInitialization() {

View File

@ -15,7 +15,7 @@ import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.CannotForceNonNullableException;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.orm.junit.ServiceRegistry;
import org.junit.jupiter.api.AfterEach;
@ -32,7 +32,8 @@ import static org.junit.jupiter.api.Assertions.fail;
* @author Steve Ebersole
*/
@ServiceRegistry
public class AndFormulaTest extends BaseUnitTest {
@BaseUnitTest
public class AndFormulaTest {
private static StandardServiceRegistry ssr;
@BeforeEach

View File

@ -16,7 +16,8 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.tool.schema.internal.SchemaCreatorImpl;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.orm.test.annotations.id.entities.Bunny;
import org.hibernate.orm.test.annotations.id.entities.PointyTooth;
import org.hibernate.orm.test.annotations.id.entities.TwinkleToes;
@ -29,8 +30,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
*
* @author Hardy Ferentschik
*/
@SuppressWarnings("unchecked")
public class JoinColumnOverrideTest extends BaseUnitTest {
@BaseUnitTest
public class JoinColumnOverrideTest {
private static final String expectedSqlPointyTooth = "create table PointyTooth (id numeric(128,0) not null, " +
"bunny_id numeric(128,0), primary key (id))";

View File

@ -18,7 +18,8 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.tool.schema.internal.SchemaCreatorImpl;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.orm.test.annotations.id.sequences.entities.Bunny;
import org.hibernate.orm.test.annotations.id.sequences.entities.PointyTooth;
import org.hibernate.orm.test.annotations.id.sequences.entities.TwinkleToes;
@ -32,7 +33,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
*
* @author Hardy Ferentschik
*/
public class JoinColumnOverrideTest extends BaseUnitTest {
@BaseUnitTest
public class JoinColumnOverrideTest {
private static final String expectedSqlPointyTooth = "create table PointyTooth (id numeric(128,0) not null, " +
"bunny_id numeric(128,0), primary key (id))";

View File

@ -13,10 +13,10 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static junit.framework.TestCase.assertFalse;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ -25,7 +25,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
*
* @author Hardy Ferentschik
*/
public class DiscriminatorOptionsTest extends BaseUnitTest {
@BaseUnitTest
public class DiscriminatorOptionsTest {
@Test
public void testNonDefaultOptions() {
final StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().build();
@ -42,7 +43,7 @@ public class DiscriminatorOptionsTest extends BaseUnitTest {
RootClass root = (RootClass) persistentClass;
assertTrue( root.isForceDiscriminator(), "Discriminator should be forced" );
assertFalse( "Discriminator should not be insertable", root.isDiscriminatorInsertable() );
assertFalse( root.isDiscriminatorInsertable(), "Discriminator should not be insertable" );
}
finally {
StandardServiceRegistryBuilder.destroy( ssr );
@ -64,7 +65,7 @@ public class DiscriminatorOptionsTest extends BaseUnitTest {
assertTrue( persistentClass instanceof RootClass );
RootClass root = (RootClass) persistentClass;
assertFalse( "Discriminator should not be forced by default", root.isForceDiscriminator() );
assertFalse( root.isForceDiscriminator(), "Discriminator should not be forced by default" );
}
finally {
StandardServiceRegistryBuilder.destroy( ssr );

View File

@ -21,7 +21,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.internal.SessionFactoryRegistry;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
@ -32,7 +32,8 @@ import static org.junit.jupiter.api.Assertions.fail;
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
@TestForIssue( jiraKey = "HHH-7214" )
public class DuplicatedDiscriminatorValueTest extends BaseUnitTest {
@BaseUnitTest
public class DuplicatedDiscriminatorValueTest {
private static final String DISCRIMINATOR_VALUE = "D";
@Test

View File

@ -6,8 +6,6 @@
*/
package org.hibernate.orm.test.annotations.override.inheritance;
import static org.junit.Assert.assertTrue;
import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.Entity;
@ -20,14 +18,19 @@ import javax.persistence.UniqueConstraint;
import org.hibernate.cfg.AnnotationBinder;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable;
import org.jboss.logging.Logger;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.jboss.logging.Logger;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Vlad Mihalcea
*/
@ -53,7 +56,7 @@ public class EntityInheritanceAttributeOverrideTest extends EntityManagerFactory
EntityManagerFactory entityManagerFactory = super.produceEntityManagerFactory();
assertTrue("A warning should have been logged for this unsupported configuration", warningLogged.wasTriggered());
assertTrue( warningLogged.wasTriggered(), "A warning should have been logged for this unsupported configuration");
return entityManagerFactory;
}

View File

@ -14,9 +14,9 @@ import javax.persistence.MappedSuperclass;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -25,19 +25,18 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Vlad Mihalcea
*/
public class MappedSuperclassAttributeOverrideTest extends EntityManagerFactoryBasedFunctionalTest {
@Override
public Class[] getAnnotatedClasses() {
return new Class[] {
CategoryEntity.class,
TaxonEntity.class
};
@Jpa(
annotatedClasses = {
MappedSuperclassAttributeOverrideTest.CategoryEntity.class,
MappedSuperclassAttributeOverrideTest.TaxonEntity.class
}
)
public class MappedSuperclassAttributeOverrideTest {
@Test
@TestForIssue(jiraKey = "HHH-12609")
public void test() {
inTransaction( entityManager -> {
public void test(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
TaxonEntity taxon1 = new TaxonEntity();
taxon1.setId( 1L );
taxon1.setCode( "Taxon" );
@ -53,7 +52,7 @@ public class MappedSuperclassAttributeOverrideTest extends EntityManagerFactoryB
entityManager.persist( taxon2 );
} );
inTransaction( entityManager -> {
scope.inTransaction( entityManager -> {
assertEquals(
2,
( (Number) entityManager.createQuery(

View File

@ -9,7 +9,7 @@ package org.hibernate.orm.test.id;
import org.hibernate.id.IdentifierGenerationException;
import org.hibernate.id.IntegralDataTypeHolder;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -20,7 +20,8 @@ import static org.junit.jupiter.api.Assertions.fail;
* @author Steve Ebersole
*/
@SuppressWarnings({ "UnusedDeclaration" })
public abstract class AbstractHolderTest extends BaseUnitTest {
@BaseUnitTest
public abstract class AbstractHolderTest {
protected abstract IntegralDataTypeHolder makeHolder();
@Test
@ -119,6 +120,7 @@ public abstract class AbstractHolderTest extends BaseUnitTest {
}
}
@Test
public void testIncrement() {
IntegralDataTypeHolder holder = makeHolder();
holder.initialize( 0 );

View File

@ -25,7 +25,7 @@ import org.hibernate.type.StandardBasicTypes;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.orm.junit.DialectFeatureChecks.SupportsSequences;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.junit.jupiter.api.AfterEach;
@ -42,7 +42,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
*/
@SuppressWarnings({"deprecation"})
@RequiresDialectFeature(feature = SupportsSequences.class)
public class SequenceHiLoGeneratorNoIncrementTest extends BaseUnitTest {
@BaseUnitTest
public class SequenceHiLoGeneratorNoIncrementTest {
private static final String TEST_SEQUENCE = "test_sequence";
private StandardServiceRegistry serviceRegistry;

View File

@ -24,8 +24,7 @@ import org.hibernate.internal.SessionImpl;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.orm.junit.DialectFeatureChecks.SupportsSequences;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.junit.jupiter.api.AfterEach;
@ -42,7 +41,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
*/
@SuppressWarnings({"deprecation"})
@RequiresDialectFeature(feature = SupportsSequences.class)
public class SequenceHiLoGeneratorTest extends BaseUnitTest {
@BaseUnitTest
public class SequenceHiLoGeneratorTest {
private static final String TEST_SEQUENCE = "test_sequence";
private StandardServiceRegistry serviceRegistry;

View File

@ -24,7 +24,7 @@ import org.hibernate.internal.SessionImpl;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.orm.junit.DialectFeatureChecks.SupportsSequences;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.junit.jupiter.api.AfterEach;
@ -37,7 +37,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* @author Andrea Boriero
*/
@RequiresDialectFeature(feature = SupportsSequences.class)
public class SequenceStyleGeneratorBehavesLikeSequeceHiloGeneratorWitZeroIncrementSizeTest extends BaseUnitTest {
@BaseUnitTest
public class SequenceStyleGeneratorBehavesLikeSequeceHiloGeneratorWitZeroIncrementSizeTest {
private static final String TEST_SEQUENCE = "test_sequence";
private StandardServiceRegistry serviceRegistry;

View File

@ -13,7 +13,7 @@ import org.hibernate.id.enhanced.Optimizer;
import org.hibernate.id.enhanced.OptimizerFactory;
import org.hibernate.id.enhanced.StandardOptimizerDescriptor;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -23,7 +23,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
*
* @author Steve Ebersole
*/
public class OptimizerUnitTest extends BaseUnitTest {
@BaseUnitTest
public class OptimizerUnitTest {
@Test
public void testBasicNoOptimizerUsage() {
// test historic sequence behavior, where the initial values start at 1...

View File

@ -32,11 +32,11 @@ import org.hibernate.id.enhanced.TableStructure;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.testing.boot.MetadataBuildingContextTestingImpl;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.hamcrest.Matchers.instanceOf;
import static org.hibernate.testing.junit5.ExtraAssertions.assertClassAssignability;
import static org.hibernate.testing.orm.junit.ExtraAssertions.assertClassAssignability;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@ -47,7 +47,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
*
* @author Steve Ebersole
*/
public class SequenceStyleConfigUnitTest extends BaseUnitTest {
@BaseUnitTest
public class SequenceStyleConfigUnitTest {
/**
* Test all params defaulted with a dialect supporting pooled sequences

View File

@ -29,7 +29,7 @@ import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable;
import org.hibernate.testing.orm.junit.RequiresDialect;
@ -38,7 +38,6 @@ import org.junit.jupiter.api.Test;
import org.jboss.logging.Logger;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ -51,9 +50,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class PostgreSQLSequenceGeneratorWithSerialTest extends EntityManagerFactoryBasedFunctionalTest {
@Rule
public LoggerInspectionRule logInspection = new LoggerInspectionRule( Logger.getMessageLogger( CoreMessageLogger.class,
SequenceStyleGenerator.class
.getName()
public LoggerInspectionRule logInspection = new LoggerInspectionRule(
Logger.getMessageLogger(
CoreMessageLogger.class,
SequenceStyleGenerator.class.getName()
) );
private Triggerable triggerable = logInspection.watchForLogMessages( "HHH000497:" );
@ -119,7 +119,7 @@ public class PostgreSQLSequenceGeneratorWithSerialTest extends EntityManagerFact
final int ITERATIONS = 51;
doInJPA( this::entityManagerFactory, entityManager -> {
inTransaction( entityManager -> {
for ( int i = 1; i <= ITERATIONS; i++ ) {
ApplicationConfiguration model = new ApplicationConfiguration();

View File

@ -25,7 +25,7 @@ import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.util.ExceptionUtil;

View File

@ -27,7 +27,7 @@ import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;

View File

@ -26,7 +26,7 @@ import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;

View File

@ -9,7 +9,7 @@ package org.hibernate.orm.test.id.hhh12973;
import org.hibernate.id.SequenceMismatchStrategy;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -18,7 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* @author Vlad Mihalcea
*/
@TestForIssue(jiraKey = "HHH-12973")
public class SequenceMismatchStrategyLowerCaseStringValueTest extends BaseUnitTest {
@BaseUnitTest
public class SequenceMismatchStrategyLowerCaseStringValueTest {
@Test
public void test() {

View File

@ -9,7 +9,7 @@ package org.hibernate.orm.test.id.hhh12973;
import org.hibernate.id.SequenceMismatchStrategy;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -19,7 +19,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* @author Vlad Mihalcea
*/
@TestForIssue(jiraKey = "HHH-12973")
public class SequenceMismatchStrategyNullValueTest extends BaseUnitTest {
@BaseUnitTest
public class SequenceMismatchStrategyNullValueTest {
@Test
public void test() {

View File

@ -10,7 +10,7 @@ import org.hibernate.HibernateException;
import org.hibernate.id.SequenceMismatchStrategy;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.hibernate.testing.util.ExceptionUtil;
import org.junit.jupiter.api.Test;
@ -22,7 +22,8 @@ import static org.junit.jupiter.api.Assertions.fail;
* @author Vlad Mihalcea
*/
@TestForIssue(jiraKey = "HHH-12973")
public class SequenceMismatchStrategyUnknownEnumValueTest extends BaseUnitTest {
@BaseUnitTest
public class SequenceMismatchStrategyUnknownEnumValueTest {
@Test
public void test() {

View File

@ -9,7 +9,7 @@ package org.hibernate.orm.test.id.hhh12973;
import org.hibernate.id.SequenceMismatchStrategy;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -18,7 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* @author Vlad Mihalcea
*/
@TestForIssue(jiraKey = "HHH-12973")
public class SequenceMismatchStrategyUpperCaseStringValueTest extends BaseUnitTest {
@BaseUnitTest
public class SequenceMismatchStrategyUpperCaseStringValueTest {
@Test
public void test() {

View File

@ -27,7 +27,7 @@ import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;

View File

@ -10,7 +10,7 @@ import java.util.UUID;
import org.hibernate.id.uuid.CustomVersionOneStrategy;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -20,7 +20,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author Steve Ebersole
*/
public class CustomVersionOneStrategyTest extends BaseUnitTest {
@BaseUnitTest
public class CustomVersionOneStrategyTest {
@Test
public void testUniqueCounter() {

View File

@ -26,10 +26,10 @@ import org.hibernate.id.UUIDGenerator;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.RootClass;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.junit5.ExtraAssertions.assertTyping;
import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ -38,7 +38,8 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
*
* @author Steve Ebersole
*/
public class GeneratedValueTest extends BaseUnitTest {
@BaseUnitTest
public class GeneratedValueTest {
@Test
public void testGeneratedUuidId() throws Exception {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()

View File

@ -7,18 +7,27 @@
package org.hibernate.orm.test.jpa.association;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
/**
* @author Emmanuel Bernard
*/
public class AssociationTest extends EntityManagerFactoryBasedFunctionalTest {
@Jpa(
annotatedClasses = {
Incident.class,
IncidentStatus.class,
Kitchen.class,
Oven.class
}
)
public class AssociationTest {
@AfterEach
public void tearDown() {
inTransaction(
public void tearDown(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
entityManager.createQuery( "delete from Incident" ).executeUpdate();
entityManager.createQuery( "delete from IncidentStatus" ).executeUpdate();
@ -29,9 +38,9 @@ public class AssociationTest extends EntityManagerFactoryBasedFunctionalTest {
}
@Test
public void testBidirOneToOne() {
public void testBidirOneToOne(EntityManagerFactoryScope scope) {
final String id = "10";
inTransaction(
scope.inTransaction(
entityManager -> {
Incident i = entityManager.find( Incident.class, id );
if ( i == null ) {
@ -45,8 +54,8 @@ public class AssociationTest extends EntityManagerFactoryBasedFunctionalTest {
}
@Test
public void testMergeAndBidirOneToOne() {
final Oven persistedOven = fromTransaction(
public void testMergeAndBidirOneToOne(EntityManagerFactoryScope scope) {
final Oven persistedOven = scope.fromTransaction(
entityManager -> {
Oven oven = new Oven();
Kitchen kitchen = new Kitchen();
@ -57,20 +66,11 @@ public class AssociationTest extends EntityManagerFactoryBasedFunctionalTest {
return oven;
} );
Oven mergedOven = fromTransaction(
Oven mergedOven = scope.fromTransaction(
entityManager -> {
return entityManager.merge( persistedOven );
}
);
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[] {
Incident.class,
IncidentStatus.class,
Kitchen.class,
Oven.class
};
}
}

View File

@ -8,10 +8,8 @@ import javax.persistence.Table;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.SkipForDialect;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -19,17 +17,16 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CriteriaLiteralWithSingleQuoteTest extends EntityManagerFactoryBasedFunctionalTest {
@Override
public Class[] getAnnotatedClasses() {
return new Class[] { Student.class };
@Jpa(
annotatedClasses = {
CriteriaLiteralWithSingleQuoteTest.Student.class
}
)
public class CriteriaLiteralWithSingleQuoteTest {
@Test
public void literalSingleQuoteTest() {
inTransaction(
public void literalSingleQuoteTest(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> query = cb.createQuery();
@ -41,9 +38,8 @@ public class CriteriaLiteralWithSingleQuoteTest extends EntityManagerFactoryBase
}
@Test
public void literalProjectionTest() {
inTransaction(
public void literalProjectionTest(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> query = cb.createQuery();
@ -55,8 +51,8 @@ public class CriteriaLiteralWithSingleQuoteTest extends EntityManagerFactoryBase
}
@Test
public void testLiteralProjectionAndGroupBy() {
inTransaction(
public void testLiteralProjectionAndGroupBy(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
final String literal = "' || aValue || '";
@ -74,8 +70,8 @@ public class CriteriaLiteralWithSingleQuoteTest extends EntityManagerFactoryBase
}
@BeforeEach
public void setupData() {
inTransaction(
public void setupData(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
Student student = new Student();
student.setAValue( "A Value" );
@ -85,8 +81,8 @@ public class CriteriaLiteralWithSingleQuoteTest extends EntityManagerFactoryBase
}
@AfterEach
public void cleanupData() {
inTransaction(
public void cleanupData(EntityManagerFactoryScope scope) {
scope.inTransaction(
entityManager -> {
entityManager.createQuery( "delete from Student" ).executeUpdate();
}

View File

@ -14,7 +14,7 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.junit.jupiter.api.Test;

View File

@ -17,7 +17,7 @@ import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.RequiresDialect;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

View File

@ -27,7 +27,7 @@ import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
import org.hibernate.tool.schema.spi.CommandAcceptanceException;
import org.hibernate.tool.schema.spi.SchemaManagementException;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

View File

@ -25,7 +25,7 @@ import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
import org.hibernate.tool.schema.spi.CommandAcceptanceException;
import org.hibernate.tool.schema.spi.SchemaManagementException;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

View File

@ -23,7 +23,7 @@ import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryBasedFunctionalTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

View File

@ -15,15 +15,15 @@ import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.entity.AbstractEntityPersister;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.jboss.logging.Logger;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@ -31,7 +31,13 @@ import static org.junit.Assert.assertTrue;
* @author Vlad Mihalcea
*/
@TestForIssue(jiraKey = "HHH-13228")
public class OneToOneMapsIdChangeParentTest extends EntityManagerFactoryBasedFunctionalTest {
@Jpa(
annotatedClasses = {
OneToOneMapsIdChangeParentTest.Parent.class,
OneToOneMapsIdChangeParentTest.Child.class
}
)
public class OneToOneMapsIdChangeParentTest {
@Rule
public LoggerInspectionRule logInspection = new LoggerInspectionRule(
@ -43,17 +49,10 @@ public class OneToOneMapsIdChangeParentTest extends EntityManagerFactoryBasedFun
private Triggerable triggerable = logInspection.watchForLogMessages( "HHH000502:" );
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Parent.class,
Child.class
};
}
@Test
public void test() {
Child _child = doInJPA( this::entityManagerFactory, entityManager -> {
public void test(EntityManagerFactoryScope scope) {
Child _child = scope.fromTransaction( entityManager -> {
Parent firstParent = new Parent();
firstParent.setId( 1L );
entityManager.persist( firstParent );
@ -68,7 +67,7 @@ public class OneToOneMapsIdChangeParentTest extends EntityManagerFactoryBasedFun
triggerable.reset();
assertFalse( triggerable.wasTriggered() );
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
Parent secondParent = new Parent();
secondParent.setId( 2L );
entityManager.persist( secondParent );

View File

@ -6,7 +6,6 @@
*/
package org.hibernate.orm.test.mapping.onetoone;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EntityManagerFactory;
@ -15,42 +14,45 @@ import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.hibernate.testing.jdbc.SQLStatementInspector;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.jpa.NonStringValueSettingProvider;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.jupiter.api.Assertions.assertSame;
/**
* @author Vlad Mihalcea
*/
public class OneToOneMapsIdJoinColumnTest extends EntityManagerFactoryBasedFunctionalTest {
@Jpa(
annotatedClasses = {
OneToOneMapsIdJoinColumnTest.Person.class,
OneToOneMapsIdJoinColumnTest.PersonDetails.class
},
nonStringValueSettingProviders = { OneToOneMapsIdJoinColumnTest.SQLStatementInspectorProvider.class }
)
public class OneToOneMapsIdJoinColumnTest {
public static class SQLStatementInspectorProvider extends NonStringValueSettingProvider {
@Override
protected void applySettings(Map<Object, Object> settings) {
settings.put( AvailableSettings.STATEMENT_INSPECTOR, SQLStatementInspector.class );
public String getKey() {
return AvailableSettings.STATEMENT_INSPECTOR;
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Person.class,
PersonDetails.class
};
public Object getValue() {
return SQLStatementInspector.class;
}
}
@BeforeEach
public void setUp(){
doInJPA( this::entityManagerFactory, entityManager -> {
public void setUp(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
Person person = new Person( "ABC-123" );
@ -60,16 +62,15 @@ public class OneToOneMapsIdJoinColumnTest extends EntityManagerFactoryBasedFunct
person.setDetails( details );
entityManager.persist( person );
return person;
} );
}
@Test
public void testLifecycle() {
SQLStatementInspector statementInspector = getSqlStatementInspector();
public void testLifecycle(EntityManagerFactoryScope scope) {
SQLStatementInspector statementInspector = getSqlStatementInspector( scope );
statementInspector.clear();
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
Person person = entityManager.find( Person.class, "ABC-123" );
statementInspector.assertExecutedCount( 1 );
statementInspector.assertNumberOfOccurrenceInQuery( 0, "join", 1 );
@ -84,8 +85,8 @@ public class OneToOneMapsIdJoinColumnTest extends EntityManagerFactoryBasedFunct
} );
}
private SQLStatementInspector getSqlStatementInspector() {
EntityManagerFactory entityManagerFactory = entityManagerFactory();
private SQLStatementInspector getSqlStatementInspector(EntityManagerFactoryScope scope) {
EntityManagerFactory entityManagerFactory = scope.getEntityManagerFactory();
SessionFactory sessionFactory = entityManagerFactory.unwrap( SessionFactory.class );
return (SQLStatementInspector) sessionFactory.getSessionFactoryOptions().getStatementInspector();
}
@ -99,7 +100,8 @@ public class OneToOneMapsIdJoinColumnTest extends EntityManagerFactoryBasedFunct
@OneToOne(mappedBy = "person", cascade = CascadeType.PERSIST, optional = false)
private PersonDetails details;
public Person() {}
public Person() {
}
public Person(String id) {
this.id = id;

View File

@ -14,35 +14,31 @@ import javax.persistence.OneToOne;
import org.hibernate.annotations.NaturalId;
import org.hibernate.testing.junit5.EntityManagerFactoryBasedFunctionalTest;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
import org.hibernate.testing.orm.junit.Jpa;
import org.junit.jupiter.api.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
/**
* @author Vlad Mihalcea
*/
public class OneToOneMapsIdTest extends EntityManagerFactoryBasedFunctionalTest {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Person.class,
PersonDetails.class
};
@Jpa(
annotatedClasses = {
OneToOneMapsIdTest.Person.class,
OneToOneMapsIdTest.PersonDetails.class
}
)
public class OneToOneMapsIdTest {
@Test
public void testLifecycle() {
Person _person = doInJPA( this::entityManagerFactory, entityManager -> {
public void testLifecycle(EntityManagerFactoryScope scope) {
Person _person = scope.fromTransaction( entityManager -> {
Person person = new Person( "ABC-123" );
entityManager.persist( person );
return person;
} );
doInJPA( this::entityManagerFactory, entityManager -> {
scope.inTransaction( entityManager -> {
Person person = entityManager.find( Person.class, _person.getId() );
PersonDetails personDetails = new PersonDetails();
@ -63,7 +59,8 @@ public class OneToOneMapsIdTest extends EntityManagerFactoryBasedFunctionalTest
@NaturalId
private String registrationNumber;
public Person() {}
public Person() {
}
public Person(String registrationNumber) {
this.registrationNumber = registrationNumber;

View File

@ -21,17 +21,19 @@ import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.schema.internal.SchemaCreatorImpl;
import org.hibernate.testing.ServiceRegistryBuilder;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.junit.Assert;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* Test harness for ANN-742.
*
* @author Hardy Ferentschik
*
*/
public class NullablePrimaryKeyTest extends BaseUnitTest {
@BaseUnitTest
public class NullablePrimaryKeyTest {
@Test
public void testGeneratedSql() {
@ -48,14 +50,17 @@ public class NullablePrimaryKeyTest extends BaseUnitTest {
ms.addAnnotatedClass( Person.class );
final Metadata metadata = ms.buildMetadata();
final List<String> commands = new SchemaCreatorImpl( serviceRegistry ).generateCreationCommands( metadata, false );
final List<String> commands = new SchemaCreatorImpl( serviceRegistry ).generateCreationCommands(
metadata,
false
);
String expectedMappingTableSql = "create table personAddress (address_id bigint, " +
"person_id bigint not null, primary key (person_id))";
Assert.assertEquals( "Wrong SQL", expectedMappingTableSql, commands.get( 2 ) );
assertEquals( "Wrong SQL", expectedMappingTableSql, commands.get( 2 ) );
}
catch (Exception e) {
Assert.fail(e.getMessage());
fail( e.getMessage() );
}
finally {
ServiceRegistryBuilder.destroy( serviceRegistry );

View File

@ -11,13 +11,14 @@ import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.ServiceRegistryBuilder;
import org.hibernate.testing.junit5.BaseUnitTest;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.Test;
/**
* @author Steve Ebersole
*/
public class SubclassProxyInterfaceTest extends BaseUnitTest {
@BaseUnitTest
public class SubclassProxyInterfaceTest {
@Test
public void testSubclassProxyInterfaces() {
final Configuration cfg = new Configuration()

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
package org.hibernate.testing.envers;
import org.hibernate.dialect.Dialect;
@ -16,7 +16,5 @@ import org.junit.jupiter.api.extension.ExtensionContext;
* @author Steve Ebersole
*/
public interface DialectAccess {
ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create( DialectAccess.class.getName() );
Dialect getDialect();
}

View File

@ -4,12 +4,14 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
package org.hibernate.testing.envers;
import javax.persistence.EntityManagerFactory;
import org.hibernate.dialect.Dialect;
import org.hibernate.testing.orm.junit.DialectContext;
/**
* Contract for things that expose an EntityManagerFactory
*

View File

@ -14,7 +14,6 @@ import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.testing.jta.TestingJtaPlatformImpl;
import org.hibernate.testing.junit5.EntityManagerFactoryAccess;
/**
* @author Chris Cranford

View File

@ -1,211 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.envers;
import java.util.function.Consumer;
import java.util.function.Function;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.hibernate.testing.junit5.SessionFactoryAccess;
import org.jboss.logging.Logger;
/**
* A scope or holder for the SessionFactory instance associated with a given test class.
* Used to:
* <ul>
* <li>Provide lifecycle management related to the SessionFactory</li>
* </ul>
*
* @author Chris Cranford
*/
public class EnversSessionFactoryScope implements SessionFactoryAccess {
private static final Logger log = Logger.getLogger( EnversSessionFactoryScope.class );
private final EnversSessionFactoryProducer sessionFactoryProducer;
private final Strategy auditStrategy;
private SessionFactory sessionFactory;
public EnversSessionFactoryScope(EnversSessionFactoryProducer producer, Strategy auditStrategy) {
log.debugf( "#<init> - %s", auditStrategy.getDisplayName() );
this.auditStrategy = auditStrategy;
this.sessionFactoryProducer = producer;
}
public void releaseSessionFactory() {
log.debugf( "#releaseSessionFactory - %s", auditStrategy.getDisplayName() );
if ( sessionFactory != null ) {
log.infof( "Closing SessionFactory %s (%s)", sessionFactory, auditStrategy.getDisplayName() );
sessionFactory.close();
sessionFactory = null;
}
}
@Override
public SessionFactoryImplementor getSessionFactory() {
log.debugf( "#getSessionFactory - %s", auditStrategy.getDisplayName() );
if ( sessionFactory == null || sessionFactory.isClosed() ) {
sessionFactory = sessionFactoryProducer.produceSessionFactory( auditStrategy.getSettingValue() );
}
return (SessionFactoryImplementor) sessionFactory;
}
/**
* Invoke a lambda action inside an open session without a transaction-scope.
*
* The session will be closed after the action completes, regardless of failure.
*
* @param action The lambda action to invoke.
*/
public void inSession(Consumer<SessionImplementor> action) {
inSession( getSessionFactory(), action );
}
/**
* Invoke a lambda action with an open session without a transaction-scope.
*
* The session will be closed after the action completes, regardless of failure.
*
* @param sfi The session factory.
* @param action The lambda action to invoke.
*/
public void inSession(SessionFactoryImplementor sfi, Consumer<SessionImplementor> action) {
try ( SessionImplementor session = (SessionImplementor) sfi.openSession() ) {
action.accept( session );
}
}
public <R> R inSession(Function<SessionImplementor, R> action) {
return inSession( getSessionFactory(), action );
}
public <R> R inSession(SessionFactoryImplementor sfi, Function<SessionImplementor, R> action) {
try ( SessionImplementor session = (SessionImplementor) sfi.openSession() ) {
return action.apply( session );
}
}
/**
* Invoke a lambda action with an open session inside a new transaction.
*
* The session will be closed after the action completes, regardless of failure.
* The transaction will be committed if successful; otherwise it will be rolled back.
*
* @param action The lambda action to invoke.
*/
public void inTransaction(Consumer<SessionImplementor> action) {
inTransaction( getSessionFactory(), action );
}
/**
* Invoke a lambda action with an open session inside a new transaction.
*
* The session will be closed after the action completes, regardless of failure.
* The transaction will be committed if successful; otherwise it will be rolled back.
*
* @param sfi The session factory.
* @param action The lambda action to invoke.
*/
public void inTransaction(SessionFactoryImplementor sfi, Consumer<SessionImplementor> action) {
try ( SessionImplementor session = (SessionImplementor) sfi.openSession() ) {
inTransaction( session, action );
}
}
/**
* Invoke a lambda action inside a new transaction but bound to an existing open session.
*
* The session will not be closed after the action completes, it will be left as-is.
* The transaction will be committed if successful; otherwise it will be rolled back.
*
* @param session The session to bind the transaction against.
* @param action The lambda action to invoke.
*/
public void inTransaction(SessionImplementor session, Consumer<SessionImplementor> action) {
final Transaction trx = session.beginTransaction();
try {
action.accept( session );
trx.commit();
}
catch ( Exception e ) {
try {
trx.rollback();
}
catch ( Exception ignored ) {
}
throw e;
}
}
public <R> R inTransaction(Function<SessionImplementor, R> action) {
return inTransaction( getSessionFactory(), action );
}
public <R> R inTransaction(SessionFactoryImplementor sfi, Function<SessionImplementor, R> action) {
try ( SessionImplementor session = (SessionImplementor) sfi.openSession() ) {
return inTransaction( session, action );
}
}
public <R> R inTransaction(SessionImplementor session, Function<SessionImplementor, R> action) {
final Transaction trx = session.beginTransaction();
try {
R result = action.apply( session );
trx.commit();
return result;
}
catch ( Exception e ) {
try {
trx.rollback();
}
catch ( Exception ignored ) {
}
throw e;
}
}
/**
* Invoke a series of lambda actions bound inside their own transaction-scope but bound to the same session.
*
* The session will be closed after the actions complete, regardless of failure.
* The transaction associated with lambda will be committed if successful; otherwise it will be rolled back.
* Should a lambda action fail, the remaining actions will be skipped.
*
* @param actions The lambda actions to invoke.
*/
@SafeVarargs
public final void inTransactions(Consumer<SessionImplementor>... actions) {
try( SessionImplementor session = (SessionImplementor) getSessionFactory().openSession() ) {
for ( Consumer<SessionImplementor> action : actions ) {
inTransaction( session, action );
}
}
}
/**
* Invoke a lambda action against an {@link AuditReader} bound to a newly allocated session.
*
* The audit reader instance will be automatically allocated and provided to the lambda.
* The underlying session will be automatically opened and closed.
*
* @param action The lambda action to invoke.
*/
public void inAuditReader(Consumer<AuditReader> action) {
try ( SessionImplementor session = (SessionImplementor) getSessionFactory().openSession() ) {
AuditReader auditReader = AuditReaderFactory.get( session );
action.accept( auditReader );
}
}
}

View File

@ -1,28 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import org.hibernate.testing.orm.junit.ExpectedExceptionExtension;
import org.hibernate.testing.orm.junit.FailureExpectedExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Steve Ebersole
*/
@ExtendWith( FailureExpectedExtension.class )
@ExtendWith( ExpectedExceptionExtension.class )
public abstract class BaseUnitTest {
@SuppressWarnings("unchecked")
protected <T> T cast(Object thing, Class<T> type) {
assertThat( thing, instanceOf( type ) );
return type.cast( thing );
}
}

View File

@ -1,28 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Meant to mark tests that should only be run on the default
* testing database. Generally indicates the test does not
* use JDBC at all.
*
* todo (6.0) : add JUnit extension to skip these on database runs other than the default one?
*
* @author Steve Ebersole
*/
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface DatabaseAgnostic {
}

View File

@ -1,151 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import org.hibernate.dialect.Dialect;
import org.hibernate.testing.orm.junit.DialectFeatureCheck;
import org.hibernate.testing.orm.junit.RequiresDialect;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.orm.junit.RequiresDialectFeatureGroup;
import org.hibernate.testing.orm.junit.RequiresDialects;
import org.hibernate.testing.orm.junit.SkipForDialect;
import org.hibernate.testing.orm.junit.SkipForDialectGroup;
import org.hibernate.testing.orm.junit.TestingUtil;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.jboss.logging.Logger;
/**
* JUnit 5 extension used to add {@link RequiresDialect} and {@link SkipForDialect}
* handling
*
* @author Steve Ebersole
*/
public class DialectFilterExtension implements ExecutionCondition {
private static final Logger log = Logger.getLogger( DialectFilterExtension.class );
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
final Dialect dialect = getDialect( context );
if ( dialect == null ) {
throw new RuntimeException( "#getDialect returned null" );
}
log.debugf( "Checking Dialect [%s] - context = %s", dialect, context.getDisplayName() );
final List<RequiresDialect> effectiveRequiresDialects = TestingUtil.findEffectiveRepeatingAnnotation(
context,
RequiresDialect.class,
RequiresDialects.class
);
if ( !effectiveRequiresDialects.isEmpty() ) {
StringBuilder requiredDialects = new StringBuilder( );
for ( RequiresDialect requiresDialect : effectiveRequiresDialects ) {
requiredDialects.append( requiresDialect.value() );
requiredDialects.append( " " );
if ( requiresDialect.value().isInstance( dialect ) ) {
if ( requiresDialect.matchSubTypes() ) {
if ( dialect.getVersion() >= requiresDialect.version() ) {
return ConditionEvaluationResult.enabled( "Matched @RequiresDialect" );
}
}
else {
if ( requiresDialect.version() == dialect.getVersion() ) {
return ConditionEvaluationResult.enabled( "Matched @RequiresDialect" );
}
}
}
}
return ConditionEvaluationResult.disabled(
String.format(
Locale.ROOT,
"Failed @RequiresDialect(dialect=%s) check - found %s]",
requiredDialects.toString(),
dialect.getClass().getName()
)
);
}
final List<SkipForDialect> effectiveSkips = TestingUtil.findEffectiveRepeatingAnnotation(
context,
SkipForDialect.class,
SkipForDialectGroup.class
);
for ( SkipForDialect effectiveSkipForDialect : effectiveSkips ) {
int version = effectiveSkipForDialect.version();
if ( version > -1 ) {
if ( effectiveSkipForDialect.dialectClass().isInstance( dialect ) ) {
if ( effectiveSkipForDialect.matchSubTypes() ) {
if ( dialect.getVersion() <= version ) {
return ConditionEvaluationResult.disabled( "Matched @SkipForDialect(group)" );
}
}
else {
if ( dialect.getVersion() == version ) {
return ConditionEvaluationResult.disabled( "Matched @SkipForDialect" );
}
}
}
}
else {
if ( effectiveSkipForDialect.matchSubTypes() ) {
if ( effectiveSkipForDialect.dialectClass().isInstance( dialect ) ) {
return ConditionEvaluationResult.disabled( "Matched @SkipForDialect(group)" );
}
}
else {
if ( effectiveSkipForDialect.dialectClass().equals( dialect.getClass() ) ) {
return ConditionEvaluationResult.disabled( "Matched @SkipForDialect" );
}
}
}
}
List<RequiresDialectFeature> effectiveRequiresDialectFeatures = TestingUtil.findEffectiveRepeatingAnnotation(
context,
RequiresDialectFeature.class,
RequiresDialectFeatureGroup.class
);
for ( RequiresDialectFeature effectiveRequiresDialectFeature : effectiveRequiresDialectFeatures ) {
try {
final DialectFeatureCheck dialectFeatureCheck = effectiveRequiresDialectFeature.feature()
.newInstance();
final boolean applicable = dialectFeatureCheck.apply( dialect );
final boolean reverse = effectiveRequiresDialectFeature.reverse();
if ( !( applicable ^ reverse ) ) {
return ConditionEvaluationResult.disabled(
String.format(
Locale.ROOT,
"Failed @RequiresDialectFeature [feature: %s, reverse: %s]",
effectiveRequiresDialectFeature.feature(),
effectiveRequiresDialectFeature.reverse()
) );
}
}
catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException( "Unable to instantiate DialectFeatureCheck class", e );
}
}
return ConditionEvaluationResult.enabled( "Passed all @RequiresDialect(s), @SkipForDialect(s) and @RequiresDialectFeature(group)" );
}
private Dialect getDialect(ExtensionContext context) {
return DialectContext.getDialect();
}
}

View File

@ -1,29 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import javax.persistence.EntityManagerFactory;
/**
* Contract for something that can build an EntityManagerFactory.
*
* Used by EntityManagerFactoryScopeExtension to create the EntityManagerFactoryScope.
*
* Generally speaking, a test class would implement EntityManagerFactoryScopeContainer
* and return the EntityManagerFactoryProducer to be used for those tests. The
* EntityManagerFactoryProducer is then used to build the EntityManagerFactoryScope
* which is injected back into the EntityManagerFactoryScopeContainer.
*
* @see EntityManagerFactoryScopeExtension
* @see EntityManagerFactoryScope
* @see EntityManagerFactoryScopeContainer
*
* @author Chris Cranford
*/
public interface EntityManagerFactoryProducer {
EntityManagerFactory produceEntityManagerFactory();
}

View File

@ -1,144 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import org.jboss.logging.Logger;
/**
* A scope or holder for the EntityManagerFactory instance associated with a given test class.
* Used to:
* <p>
* * provide lifecycle management related to the EntityManagerFactory
* * access to functional programming using an EntityManager generated
* from the EntityManagerFactory.
*
* @author Chris Cranford
*/
public class EntityManagerFactoryScope implements EntityManagerFactoryAccess {
private static final Logger log = Logger.getLogger( EntityManagerFactoryScope.class );
private final EntityManagerFactoryProducer producer;
private EntityManagerFactory entityManagerFactory;
public EntityManagerFactoryScope(EntityManagerFactoryProducer producer) {
log.trace( "EntityManagerFactoryScope#<init>" );
this.producer = producer;
}
public void rebuild() {
log.trace( "EntityManagerFactoryScope#rebuild" );
releaseEntityManagerFactory();
entityManagerFactory = producer.produceEntityManagerFactory();
}
public void releaseEntityManagerFactory() {
log.trace( "EntityManagerFactoryScope#releaseEntityManagerFactory" );
if ( entityManagerFactory != null ) {
entityManagerFactory.close();
}
}
@Override
public EntityManagerFactory getEntityManagerFactory() {
log.trace( "EntityManagerFactoryScope#getEntityManagerFactory" );
if ( entityManagerFactory == null || !entityManagerFactory.isOpen() ) {
entityManagerFactory = producer.produceEntityManagerFactory();
}
return entityManagerFactory;
}
public void inTransaction(Consumer<EntityManager> action) {
log.trace( "#inTransaction(action)" );
inTransaction( getEntityManagerFactory(), action );
}
public <T> T fromTransaction(Function<EntityManager, T> action) {
EntityManager entityManager = getEntityManagerFactory().createEntityManager();
try {
T result = fromTransaction( entityManager, action );
return result;
}
finally {
entityManager.close();
}
}
public void inTransaction(EntityManagerFactory factory, Consumer<EntityManager> action) {
log.trace( "#inTransaction(factory, action)" );
final EntityManager entityManager = factory.createEntityManager();
try {
log.trace( "EntityManager opened, calling action" );
inTransaction( entityManager, action );
log.trace( "called action" );
}
finally {
log.trace( "EntityManager close" );
entityManager.close();
}
}
public <T> T fromTransaction(EntityManager entityManager, Function<EntityManager, T> action) {
log.trace( "inTransaction(entityManager, action)" );
final EntityTransaction trx = entityManager.getTransaction();
final T result;
try {
trx.begin();
log.trace( "Calling action in trx" );
result = action.apply( entityManager );
log.trace( "Called trx in action" );
log.trace( "Committing transaction" );
trx.commit();
log.trace( "Committed transaction" );
}
catch (Exception e) {
log.tracef( "Error calling action: %s (%s) - rollingback", e.getClass().getName(), e.getMessage() );
try {
trx.rollback();
}
catch (Exception ignored) {
log.trace( "Was unable to roll back transaction" );
}
throw e;
}
return result;
}
public void inTransaction(EntityManager entityManager, Consumer<EntityManager> action) {
log.trace( "inTransaction(entityManager, action)" );
final EntityTransaction trx = entityManager.getTransaction();
try {
trx.begin();
log.trace( "Calling action in trx" );
action.accept( entityManager );
log.trace( "Called trx in action" );
log.trace( "Committing transaction" );
trx.commit();
log.trace( "Committed transaction" );
}
catch (Exception e) {
log.tracef( "Error calling action: %s (%s) - rollingback", e.getClass().getName(), e.getMessage() );
try {
trx.rollback();
}
catch (Exception ignored) {
log.trace( "Was unable to roll back transaction" );
}
throw e;
}
}
}

View File

@ -1,82 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.testing.junit5;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Steve Ebersole
*/
public final class ExtraAssertions {
private ExtraAssertions() {
}
public static void assertClassAssignability(Class expected, Class actual) {
if ( !expected.isAssignableFrom( actual ) ) {
fail( "Expected class [" + expected.getName() + "] was not assignable from actual [" + actual.getName() + "]" );
}
}
@SuppressWarnings("unchecked")
public static <T> T assertTyping(Class<T> expectedType, Object value) {
if ( !expectedType.isInstance( value ) ) {
fail(
String.format(
"Expecting value of type [%s], but found [%s]",
expectedType.getName(),
value == null ? "<null>" : value
)
);
}
return (T) value;
}
public static void assertJdbcTypeCode(int expected, int actual) {
if ( expected != actual ) {
final String message = String.format(
"JDBC type codes did not match...\n" +
"Expected: %s (%s)\n" +
"Actual : %s (%s)",
jdbcTypeCodeMap().get( expected ),
expected,
jdbcTypeCodeMap().get( actual ),
actual
);
fail( message );
}
}
private static Map<Integer, String> jdbcTypeCodeMap;
private static synchronized Map<Integer, String> jdbcTypeCodeMap() {
if ( jdbcTypeCodeMap == null ) {
jdbcTypeCodeMap = generateJdbcTypeCache();
}
return jdbcTypeCodeMap;
}
private static Map generateJdbcTypeCache() {
final Field[] fields = Types.class.getFields();
Map cache = new HashMap( (int) ( fields.length * .75 ) + 1 );
for ( Field field : fields ) {
if ( Modifier.isStatic( field.getModifiers() ) ) {
try {
cache.put( field.get( null ), field.getName() );
}
catch (Throwable ignore) {
}
}
}
return cache;
}
}

View File

@ -1,24 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionFactoryImplementor;
/**
* Contract for things that expose a SessionFactory
*
* @author Steve Ebersole
*/
public interface SessionFactoryAccess extends DialectAccess {
SessionFactoryImplementor getSessionFactory();
@Override
default Dialect getDialect() {
return DialectContext.getDialect();
}
}

View File

@ -1,285 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.dynamictests;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.hibernate.testing.orm.junit.FailureExpected;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DynamicNode;
import org.junit.jupiter.api.TestFactory;
import org.opentest4j.TestAbortedException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.DynamicContainer.dynamicContainer;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import static org.junit.platform.commons.util.ReflectionUtils.findMethods;
/**
* Abstract base class that can be used to generate dynamic test-lets.
*
* @see DynamicBeforeAll
* @see DynamicAfterAll
* @see DynamicBeforeEach
* @see DynamicAfterEach
* @see DynamicTest
*
* @author Chris Cranford
*/
public abstract class AbstractDynamicTest<T extends DynamicExecutionContext> {
@TestFactory
@SuppressWarnings("unchecked")
public List<DynamicNode> generateDynamicTestNodes() throws Exception {
final Class<? extends AbstractDynamicTest> testClass = getClass();
final List<DynamicNode> dynamicNodes = new ArrayList<>();
final List<Method> beforeAllMethods = findMethods(
testClass,
method -> method.isAnnotationPresent( DynamicBeforeAll.class )
);
final List<Method> beforeEachMethods = findMethods(
testClass,
method -> method.isAnnotationPresent( DynamicBeforeEach.class )
);
final List<Method> afterAllMethods = findMethods(
testClass,
method -> method.isAnnotationPresent( DynamicAfterAll.class )
);
final List<Method> afterEachMethods = findMethods(
testClass,
method -> method.isAnnotationPresent( DynamicAfterEach.class )
);
final List<Method> testMethods = resolveTestMethods( testClass );
for ( final T context : getExecutionContexts() ) {
if ( testClass.isAnnotationPresent( Disabled.class ) || !context.isExecutionAllowed( testClass ) ) {
continue;
}
final AbstractDynamicTest testInstance = testClass.newInstance();
final List<org.junit.jupiter.api.DynamicTest> tests = new ArrayList<>();
// First invoke all @DynamicBeforeAll annotated methods
beforeAllMethods.forEach( method -> {
if ( !method.isAnnotationPresent( Disabled.class ) && context.isExecutionAllowed( method ) ) {
final DynamicBeforeAll dynamicBeforeAllAnn = method.getAnnotation( DynamicBeforeAll.class );
final Class<? extends Throwable> expectedException = dynamicBeforeAllAnn.expected();
tests.add(
dynamicTest(
method.getName(),
() -> {
Throwable exception = null;
try {
method.invoke( testInstance );
assertEquals(
DynamicBeforeAll.None.class,
expectedException,
"Expected: " + expectedException.getName()
);
}
catch( InvocationTargetException t ) {
// only throw if the exception was not expected
if ( !expectedException.isInstance( t.getTargetException() ) ) {
if ( t.getTargetException() != null ) {
exception = t.getTargetException();
throw t.getTargetException();
}
else {
exception = t;
throw t;
}
}
}
finally {
// guarantee that if any resources are allocated by the @DynamicBeforeAll
// that those resources are cleaned up by @DynamicAfterEach.
try {
for ( Method afterEachMethod : afterEachMethods ) {
afterEachMethod.invoke( testInstance );
}
}
catch ( Throwable t ) {
if ( exception == null ) {
throw t;
}
}
}
}
)
);
}
} );
// Iterate @DynamicTest methods and invoke them, if applicable.
//
// The before/after methods aren't tested as they're ran paired with the actual
// @DynamicTest method. So to control whether the test runs, only the @DynamicTest
// method is checked.
testMethods.forEach( method -> {
if ( !method.isAnnotationPresent( Disabled.class ) && context.isExecutionAllowed( method ) ) {
final DynamicTest dynamicTestAnnotation = method.getAnnotation( DynamicTest.class );
final Class<? extends Throwable> expectedException = dynamicTestAnnotation.expected();
tests.add(
dynamicTest(
method.getName(),
() -> {
// invoke @DynamicBeforeEach
for ( Method beforeEachMethod : beforeEachMethods ) {
beforeEachMethod.invoke( testInstance );
}
Throwable exception = null;
try {
method.invoke( testInstance );
// If the @DynamicTest annotation specifies an expected exception
// and it wasn't thrown during the method invocation, we want to
// assert here and fail the test node accordingly.
assertEquals(
DynamicTest.None.class,
expectedException,
"Expected: " + expectedException.getName()
);
}
catch ( InvocationTargetException t ) {
// Check if FailureExpected annotation is present.
if ( method.isAnnotationPresent( FailureExpected.class ) ) {
// We do nothing
}
else {
// only throw if the exception was not expected.
if ( !expectedException.isInstance( t.getTargetException() ) ) {
if ( t.getTargetException() != null ) {
// in this use case, we only really care about the cause
// we can safely ignore the wrapper exception here.
exception = t.getTargetException();
throw t.getTargetException();
}
else {
exception = t;
throw t;
}
}
}
}
catch ( Throwable t ) {
exception = t;
throw t;
}
finally {
try {
for ( Method afterEachMethod : afterEachMethods ) {
afterEachMethod.invoke( testInstance );
}
}
catch( Throwable t ) {
if ( exception == null ) {
throw t;
}
}
}
}
)
);
}
// todo (6.0) - Be able to mark DynamicTest as skipped.
//
// After discussing with smoyer64 with junit5 team, we determined that it would be nice
// to mark DynamicTest instances as skipped. The proposal is to throw a black-listesd
// exception that Junit will catch and handle internally.
//
// See https://github.com/junit-team/junit5/issues/1816
else {
tests.add(
dynamicTest(
method.getName(),
() -> {
final Disabled annotation = method.getAnnotation( Disabled.class );
if ( annotation != null && annotation.value().length() > 0 ) {
throw new TestAbortedException( annotation.value() );
}
}
)
);
}
} );
// Lastly invoke all @DynamicAfterAll annotated methods
afterAllMethods.forEach( method -> {
if ( context.isExecutionAllowed( method ) ) {
tests.add( dynamicTest( method.getName(), () -> method.invoke( testInstance ) ) );
}
} );
// Only if the tests are not empty do we construct a container and inject the scope
if ( !tests.isEmpty() ) {
testInstance.injectExecutionContext( context );
dynamicNodes.add( dynamicContainer( context.getTestContainerName( testClass ), tests ) );
}
}
return dynamicNodes;
}
protected void injectExecutionContext(T context) {
}
@SuppressWarnings("unchecked")
protected Collection<T> getExecutionContexts() {
return Collections.singletonList( (T) new DynamicExecutionContext() {} );
}
private List<Method> resolveTestMethods(Class<?> testClass) {
final List<Method> testMethods = new ArrayList<>(
findMethods(
testClass,
method -> method.isAnnotationPresent( DynamicTest.class )
)
);
testMethods.sort( new DynamicOrderAnnotationComparator() );
return testMethods;
}
private class DynamicOrderAnnotationComparator implements Comparator<Method> {
@Override
public int compare(Method method1, Method method2) {
final DynamicOrder order1 = method1.getAnnotation( DynamicOrder.class );
final DynamicOrder order2 = method2.getAnnotation( DynamicOrder.class );
if ( order1 != null && order2 != null ) {
if ( order1.value() < order2.value() ) {
return -1;
}
else if ( order1.value() > order2.value() ) {
return 1;
}
else {
return 0;
}
}
else if ( order1 != null ) {
return -1;
}
else if ( order2 != null ) {
return 1;
}
return 0;
}
}
}

View File

@ -1,25 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.testing.junit5.dynamictests;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* {@link org.junit.jupiter.api.AfterAll} equilvalent.
*
* @author Chris Cranford
*/
@Target( METHOD )
@Retention( RUNTIME )
@Inherited
public @interface DynamicAfterAll {
}

View File

@ -1,25 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.testing.junit5.dynamictests;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* {@link org.junit.jupiter.api.AfterEach} equivalent.
*
* @author Chris Cranford
*/
@Retention( RUNTIME )
@Target( METHOD )
@Inherited
public @interface DynamicAfterEach {
}

View File

@ -1,38 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.testing.junit5.dynamictests;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* {@link org.junit.jupiter.api.BeforeAll} equivalent.
*
* @author Chris Cranford
*/
@Target( METHOD )
@Retention( RUNTIME )
@Inherited
public @interface DynamicBeforeAll {
/**
* Default empty exception.
*/
class None extends Throwable {
private None() {
}
}
/**
* An expected {@link Throwable} to cause a test method to succeed, but only if an exception
* of the <code>expected</code> type is thrown.
*/
Class<? extends Throwable> expected() default None.class;
}

View File

@ -1,25 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.testing.junit5.dynamictests;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* {@link org.junit.jupiter.api.BeforeEach} equivalent.
*
* @author Chris Cranford
*/
@Retention( RUNTIME )
@Target( METHOD )
@Inherited
public @interface DynamicBeforeEach {
}

View File

@ -1,48 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.testing.junit5.dynamictests;
import java.lang.reflect.Method;
/**
* Simple contract for a sepcific execution group of dynamic test nodes that allows
* the {@link org.junit.jupiter.api.TestFactory} to check whether given test nodes
* should be generated or not.
*
* @author Chris Cranford
*/
public interface DynamicExecutionContext {
/**
* Allows applying filter criteria against the test class.
*
* @param testClass The test class.
* @return boolean true if the test class should generate nodes, false otherwise.
*/
default boolean isExecutionAllowed(Class<? extends AbstractDynamicTest> testClass) {
return true;
}
/**
* Allows applying filter criteria against the dynamic test method.
*
* @param method The test method.
* @return boolean true if the test method should generate a node, false otherwise.
*/
default boolean isExecutionAllowed(Method method) {
return true;
}
/**
* Return the name of the dynamic node container associated with this execution context.
*
* @param testClass The test class.
* @return The name of the dynamic node container.
*/
default String getTestContainerName(Class<? extends AbstractDynamicTest> testClass) {
return testClass.getName();
}
}

View File

@ -1,34 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.testing.junit5.dynamictests;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Specifies the order in which tests will be sorted and executed.
* <p/>
* This is based on Junit 5.4's {@code @Order} annotation.
*
* @author Chris Cranford
*/
@Target(METHOD)
@Retention(RUNTIME)
@Inherited
public @interface DynamicOrder {
/**
* The order value for annotated element.
* <p/>
* The elements are ordered based on priority where a lower value has greater priority than a higher value.
* For example, {@link Integer#MAX_VALUE} has the lowest priority.
*/
int value() default Integer.MAX_VALUE;
}

View File

@ -1,42 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.testing.junit5.dynamictests;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* A {@link org.junit.jupiter.api.Test} equivalent.
*
* A marker annotation that identifies methods that should be collected and executed like a normal test
* but under the control of of our custom test factory implementation.
*
* A test which uses this annotation should extend {@link AbstractDynamicTest} for these marker methods
* to be injected into the Jupiter test framework via a {@link org.junit.jupiter.api.TestFactory}.
*
* @author Chris Cranford
*/
@Target( METHOD )
@Retention( RUNTIME )
public @interface DynamicTest {
/**
* Default empty exception.
*/
class None extends Throwable {
private None() {
}
}
/**
* An expected {@link Throwable} to cause a test method to succeed, but only if an exception
* of the <code>expected</code> type is thrown.
*/
Class<? extends Throwable> expected() default None.class;
}

View File

@ -1,12 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
/**
* Extensions based on the extension mechanism of JUnit 5 to support things like
* `@FailureExcepted`, `@RequiresDialect`, etc. Used in writing tests
*/
package org.hibernate.testing.junit5;

View File

@ -1,24 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.schema;
import org.hibernate.testing.junit5.DialectAccess;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
/**
* @author Andrea Boriero
*/
public class DialectTestInstancePostProcessor implements TestInstancePostProcessor {
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
if ( testInstance instanceof DialectAccess ) {
context.getStore( DialectAccess.NAMESPACE ).put( testInstance, testInstance );
}
}
}

View File

@ -1,31 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.schema;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.hibernate.testing.junit5.DialectFilterExtension;
import org.hibernate.testing.orm.junit.FailureExpectedExtension;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* @author Andrea Boriero
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ExtendWith(DialectFilterExtension.class)
@ExtendWith(FailureExpectedExtension.class)
@ExtendWith(DialectTestInstancePostProcessor.class)
@Inherited
public @interface FunctionalMetaModelTesting {
}

View File

@ -1,38 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.schema;
import java.util.function.Consumer;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.hbm2ddl.SchemaValidator;
import org.hibernate.tool.schema.internal.SchemaCreatorImpl;
import org.hibernate.tool.schema.internal.SchemaDropperImpl;
import org.hibernate.tool.schema.spi.SchemaFilter;
import org.hibernate.tool.schema.spi.SchemaMigrator;
import org.hibernate.testing.junit5.template.TestScope;
/**
* @author Andrea Boriero
*/
public interface SchemaScope extends TestScope {
void withSchemaUpdate(Consumer<SchemaUpdate> counsumer);
void withSchemaValidator(Consumer<SchemaValidator> counsumer);
void withSchemaMigrator(Consumer<SchemaMigrator> counsumer);
void withSchemaExport(Consumer<SchemaExport> counsumer);
void withSchemaCreator(SchemaFilter filter, Consumer<SchemaCreatorImpl> consumer);
void withSchemaDropper(SchemaFilter filter, Consumer<SchemaDropperImpl> consumer);
}

View File

@ -1,19 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.schema;
import org.hibernate.testing.junit5.template.TestParameter;
import org.hibernate.testing.junit5.template.TestScopeProducer;
/**
* @author Andrea Boriero
*/
public interface SchemaScopeProducer extends TestScopeProducer<SchemaScope, String> {
@Override
SchemaScope produceTestScope(TestParameter<String> metadataExtractionStrategy);
}

View File

@ -1,26 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.schema;
/**
* @author Andrea Boriero
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
@Target({ ElementType.ANNOTATION_TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@TestTemplate
@ExtendWith(SchemaTestExtension.class)
public @interface SchemaTest {
}

View File

@ -1,57 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.schema;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.hibernate.tool.schema.JdbcMetadaAccessStrategy;
import org.hibernate.testing.junit5.template.TestParameter;
import org.hibernate.testing.junit5.template.TestTemplateExtension;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestTemplateInvocationContext;
/**
* @author Andrea Boriero
*/
public class SchemaTestExtension
extends TestTemplateExtension {
public static final List<String> METADATA_ACCESS_STRATEGIES = Arrays.asList( JdbcMetadaAccessStrategy.INDIVIDUALLY.toString(), JdbcMetadaAccessStrategy.GROUPED.toString());
@Override
public boolean supportsTestTemplate(ExtensionContext context) {
return true;
}
@Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(
ExtensionContext context) {
return METADATA_ACCESS_STRATEGIES.stream().map( metadataAccessStrategy -> invocationContext( new SchemaTestParameter( (metadataAccessStrategy))) );
}
private TestTemplateInvocationContext invocationContext(SchemaTestParameter parameter) {
return new CustomTestTemplateInvocationContext( parameter, SchemaScope.class );
}
public class SchemaTestParameter
implements TestParameter<String> {
private final String metadataExtractionStartegy;
public SchemaTestParameter(String metadataExtractionStartegy) {
this.metadataExtractionStartegy = metadataExtractionStartegy;
}
@Override
public String getValue() {
return metadataExtractionStartegy;
}
}
}

View File

@ -1,18 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.serviceregistry;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.testing.junit5.DialectAccess;
/**
* @author Andrea Boriero
*/
public interface ServiceRegistryAccess extends DialectAccess {
StandardServiceRegistry getStandardServiceRegistry();
}

View File

@ -1,16 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.serviceregistry;
import org.hibernate.boot.registry.StandardServiceRegistry;
/**
* @author Andrea Boriero
*/
public interface ServiceRegistryContainer {
void setStandardServiceRegistry(StandardServiceRegistry standardServiceRegistry);
}

View File

@ -1,14 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.testing.junit5.template;
/**
* @author Andrea Boriero
*/
public interface TestParameter<T> {
T getValue();
}

View File

@ -1,14 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.testing.junit5.template;
/**
* @author Andrea Boriero
*/
public interface TestScope {
void clearScope();
}

View File

@ -1,14 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.template;
/**
* @author Andrea Boriero
*/
public interface TestScopeProducer<T extends TestScope, U> {
T produceTestScope(TestParameter<U> parameter);
}

View File

@ -1,79 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5.template;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.TestTemplateInvocationContext;
import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider;
/**
* @author Andrea Boriero
*/
public abstract class TestTemplateExtension
implements TestTemplateInvocationContextProvider {
public class CustomTestTemplateInvocationContext
implements TestTemplateInvocationContext {
private final String displayName;
private final ParameterResolver parameterResolver;
public CustomTestTemplateInvocationContext(TestParameter parameter, Class<? extends TestScope> parameterClass) {
this.displayName = parameter.getValue().toString();
this.parameterResolver = new TestScopeParameterResolver( parameter, parameterClass );
}
@Override
public String getDisplayName(int invocationIndex) {
return displayName;
}
@Override
public List<Extension> getAdditionalExtensions() {
return Collections.singletonList( parameterResolver );
}
}
public class TestScopeParameterResolver implements ParameterResolver {
private final Class<?> parameterClass;
private final TestParameter parameter;
private TestScope testScope;
public TestScopeParameterResolver(TestParameter parameter, Class<?> parameterClass) {
this.parameter = parameter;
this.parameterClass = parameterClass;
}
@Override
public boolean supportsParameter(
ParameterContext parameterContext,
ExtensionContext extensionContext)
throws ParameterResolutionException {
return parameterContext.getParameter().getType().equals( parameterClass );
}
@Override
public TestScope resolveParameter(
ParameterContext parameterContext,
ExtensionContext extensionContext) {
final Object testInstance = extensionContext.getRequiredTestInstance();
if ( !TestScopeProducer.class.isInstance( testInstance ) ) {
throw new RuntimeException( "Test instance does not implement TestScopeProducer" );
}
if ( testScope == null ) {
testScope = ( (TestScopeProducer) testInstance ).produceTestScope( parameter );
}
return testScope;
}
}
}

View File

@ -0,0 +1,151 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.orm.junit;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.hibernate.testing.orm.transaction.TransactionUtil;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.jboss.logging.Logger;
abstract class AbstractEntityManagerFactoryScope implements EntityManagerFactoryScope, ExtensionContext.Store.CloseableResource {
private static final org.jboss.logging.Logger log = Logger.getLogger( EntityManagerFactoryScope.class );
protected javax.persistence.EntityManagerFactory emf;
protected boolean active = true;
@Override
public javax.persistence.EntityManagerFactory getEntityManagerFactory() {
if ( emf == null ) {
if ( !active ) {
throw new IllegalStateException( "EntityManagerFactoryScope is no longer active" );
}
log.debug( "Creating EntityManagerFactory" );
emf = createEntityManagerFactory();
}
return emf;
}
protected abstract EntityManagerFactory createEntityManagerFactory();
@Override
public StatementInspector getStatementInspector() {
return getEntityManagerFactory().unwrap( SessionFactoryImplementor.class )
.getSessionFactoryOptions()
.getStatementInspector();
}
@Override
public void close() {
if ( !active ) {
return;
}
log.debug( "Closing SessionFactoryScope" );
active = false;
releaseEntityManagerFactory();
}
public void releaseEntityManagerFactory() {
if ( emf != null ) {
log.debug( "Releasing SessionFactory" );
try {
emf.close();
}
catch (Exception e) {
log.warn( "Error closing EMF", e );
}
finally {
emf = null;
}
}
}
@Override
public void inEntityManager(Consumer<EntityManager> action) {
log.trace( "#inEntityManager(Consumer)" );
try (SessionImplementor session = getEntityManagerFactory().createEntityManager()
.unwrap( SessionImplementor.class )) {
log.trace( "EntityManager opened, calling action" );
action.accept( session );
}
finally {
log.trace( "EntityManager close - auto-close block" );
}
}
@Override
public <T> T fromEntityManager(Function<EntityManager, T> action) {
log.trace( "#fromEntityManager(Function)" );
try (SessionImplementor session = getEntityManagerFactory().createEntityManager()
.unwrap( SessionImplementor.class )) {
log.trace( "EntityManager opened, calling action" );
return action.apply( session );
}
finally {
log.trace( "EntityManager close - auto-close block" );
}
}
@Override
public void inTransaction(Consumer<EntityManager> action) {
log.trace( "#inTransaction(Consumer)" );
try (SessionImplementor session = getEntityManagerFactory().createEntityManager()
.unwrap( SessionImplementor.class )) {
log.trace( "EntityManager opened, calling action" );
inTransaction( session, action );
}
finally {
log.trace( "EntityManager close - auto-close block" );
}
}
@Override
public <T> T fromTransaction(Function<EntityManager, T> action) {
log.trace( "#fromTransaction(Function)" );
try (SessionImplementor session = getEntityManagerFactory().createEntityManager()
.unwrap( SessionImplementor.class )) {
log.trace( "EntityManager opened, calling action" );
return fromTransaction( session, action );
}
finally {
log.trace( "EntityManager close - auto-close block" );
}
}
@Override
public void inTransaction(EntityManager entityManager, Consumer<EntityManager> action) {
log.trace( "inTransaction(EntityManager,Consumer)" );
TransactionUtil.inTransaction( entityManager, action );
}
@Override
public <T> T fromTransaction(EntityManager entityManager, Function<EntityManager, T> action) {
log.trace( "fromTransaction(EntityManager,Function)" );
final SessionImplementor session = entityManager.unwrap( SessionImplementor.class );
return TransactionUtil.fromTransaction( session, action );
}
}

View File

@ -7,6 +7,7 @@
package org.hibernate.testing.orm.junit;
import java.util.function.Consumer;
import java.util.function.Function;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
@ -158,5 +159,8 @@ public abstract class BaseSessionFactoryFunctionalTest
sessionFactoryScope().inTransaction( action );
}
protected <T> T fromTransaction(Function<SessionImplementor, T> action) {
return sessionFactoryScope().fromTransaction( action );
}
}

View File

@ -12,11 +12,13 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
@Inherited
@Target( ElementType.TYPE )
@Retention( RetentionPolicy.RUNTIME )
@TestInstance( TestInstance.Lifecycle.PER_CLASS )
@ExtendWith( FailureExpectedExtension.class )
@ExtendWith( ExpectedExceptionExtension.class )

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
package org.hibernate.testing.orm.junit;
import java.lang.reflect.Constructor;
import java.sql.Connection;

View File

@ -11,7 +11,6 @@ import java.util.Locale;
import org.hibernate.dialect.Dialect;
import org.hibernate.testing.junit5.DialectContext;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
package org.hibernate.testing.orm.junit;
import java.net.URL;
import java.util.ArrayList;
@ -24,6 +24,7 @@ import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
@ -42,7 +43,6 @@ import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
*/
@FunctionalEntityManagerFactoryTesting
public class EntityManagerFactoryBasedFunctionalTest
extends BaseUnitTest
implements EntityManagerFactoryProducer, EntityManagerFactoryScopeContainer {
private static final Logger log = Logger.getLogger( EntityManagerFactoryBasedFunctionalTest.class );
@ -281,7 +281,9 @@ public class EntityManagerFactoryBasedFunctionalTest
protected void cleanupTestData() {
doInJPA( this::entityManagerFactory, entityManager -> {
Arrays.stream( getAnnotatedClasses() ).forEach( annotatedClass ->
Arrays.stream(
getAnnotatedClasses() ).forEach(
annotatedClass ->
entityManager.createQuery( "delete from " + annotatedClass
.getSimpleName() ).executeUpdate()
);
@ -295,4 +297,14 @@ public class EntityManagerFactoryBasedFunctionalTest
protected <T> T fromTransaction(Function<EntityManager, T> action) {
return entityManagerFactoryScope().fromTransaction( action );
}
protected void inEntityManager(Consumer<EntityManager> action) {
entityManagerFactoryScope().inEntityManager( action );
}
protected <T> T fromEntityManager(Function<EntityManager, T> action) {
return entityManagerFactoryScope().fromEntityManager( action );
}
}

View File

@ -12,26 +12,20 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.persistence.EntityManager;
import javax.persistence.spi.PersistenceUnitInfo;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.hibernate.query.sqm.mutation.internal.idtable.GlobalTemporaryTableStrategy;
import org.hibernate.query.sqm.mutation.internal.idtable.LocalTemporaryTableStrategy;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.hibernate.tool.schema.Action;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.ActionGrouping;
@ -39,8 +33,8 @@ import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.ActionGroup
import org.hibernate.testing.jdbc.SharedDriverManagerConnectionProviderImpl;
import org.hibernate.testing.orm.domain.DomainModelDescriptor;
import org.hibernate.testing.orm.domain.StandardDomainModel;
import org.hibernate.testing.orm.jpa.PersistenceUnitInfoImpl;
import org.hibernate.testing.orm.jpa.NonStringValueSettingProvider;
import org.hibernate.testing.orm.jpa.PersistenceUnitInfoImpl;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
@ -53,10 +47,9 @@ import org.jboss.logging.Logger;
* hibernate-testing implementation of a few JUnit5 contracts to support SessionFactory-based testing,
* including argument injection (or see {@link SessionFactoryScopeAware})
*
* @author Steve Ebersole
* @see SessionFactoryScope
* @see DomainModelExtension
*
* @author Steve Ebersole
*/
public class EntityManagerFactoryExtension
implements TestInstancePostProcessor, AfterAllCallback, TestExecutionExceptionHandler {
@ -69,7 +62,9 @@ public class EntityManagerFactoryExtension
}
@SuppressWarnings("WeakerAccess")
public static EntityManagerFactoryScope findEntityManagerFactoryScope(Object testInstance, ExtensionContext context) {
public static EntityManagerFactoryScope findEntityManagerFactoryScope(
Object testInstance,
ExtensionContext context) {
final ExtensionContext.Store store = locateExtensionStore( testInstance, context );
final EntityManagerFactoryScope existing = (EntityManagerFactoryScope) store.get( EMF_KEY );
if ( existing != null ) {
@ -84,7 +79,8 @@ public class EntityManagerFactoryExtension
context.getElement().get(),
Jpa.class
);
final Jpa emfAnn = emfAnnWrapper.orElseThrow( () -> new RuntimeException( "Could not locate @EntityManagerFactory" ) );
final Jpa emfAnn = emfAnnWrapper.orElseThrow( () -> new RuntimeException(
"Could not locate @EntityManagerFactory" ) );
final PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl( emfAnn.persistenceUnitName() );
@ -99,10 +95,16 @@ public class EntityManagerFactoryExtension
pui.getProperties().setProperty( property.name(), property.value() );
}
pui.getProperties().setProperty( AvailableSettings.GENERATE_STATISTICS, Boolean.toString( emfAnn.generateStatistics() ) );
pui.getProperties().setProperty(
AvailableSettings.GENERATE_STATISTICS,
Boolean.toString( emfAnn.generateStatistics() )
);
if ( emfAnn.exportSchema() ) {
pui.getProperties().setProperty( AvailableSettings.HBM2DDL_DATABASE_ACTION, Action.CREATE_DROP.getExternalHbm2ddlName() );
pui.getProperties().setProperty(
AvailableSettings.HBM2DDL_DATABASE_ACTION,
Action.CREATE_DROP.getExternalHbm2ddlName()
);
}
if ( emfAnn.annotatedPackageNames().length > 0 ) {
@ -136,7 +138,8 @@ public class EntityManagerFactoryExtension
if ( emfAnn.modelDescriptorClasses().length > 0 ) {
for ( int i = 0; i < emfAnn.modelDescriptorClasses().length; i++ ) {
final Class<? extends DomainModelDescriptor> modelDescriptorClass = emfAnn.modelDescriptorClasses()[i];
final DomainModelDescriptor domainModelDescriptor = instantiateDomainModelDescriptor( modelDescriptorClass );
final DomainModelDescriptor domainModelDescriptor = instantiateDomainModelDescriptor(
modelDescriptorClass );
for ( int i1 = 0; i1 < domainModelDescriptor.getAnnotatedClasses().length; i1++ ) {
final Class<?> annotatedClass = domainModelDescriptor.getAnnotatedClasses()[i1];
pui.applyManagedClassNames( annotatedClass.getName() );
@ -193,7 +196,10 @@ public class EntityManagerFactoryExtension
}
}
catch (IllegalAccessException e) {
throw new RuntimeException( "Problem accessing DomainModelDescriptor fields : " + modelDescriptorClass.getName(), e );
throw new RuntimeException(
"Problem accessing DomainModelDescriptor fields : " + modelDescriptorClass.getName(),
e
);
}
// no singleton field, try to instantiate it via reflection
@ -201,7 +207,10 @@ public class EntityManagerFactoryExtension
return modelDescriptorClass.getConstructor( null ).newInstance( null );
}
catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException( "Problem instantiation DomainModelDescriptor : " + modelDescriptorClass.getName(), e );
throw new RuntimeException(
"Problem instantiation DomainModelDescriptor : " + modelDescriptorClass.getName(),
e
);
}
}
@ -255,7 +264,10 @@ public class EntityManagerFactoryExtension
( (SessionFactoryScopeAware) testInstance ).injectSessionFactoryScope( null );
}
final EntityManagerFactoryScopeImpl removed = (EntityManagerFactoryScopeImpl) locateExtensionStore( testInstance, context ).remove( EMF_KEY );
final EntityManagerFactoryScopeImpl removed = (EntityManagerFactoryScopeImpl) locateExtensionStore(
testInstance,
context
).remove( EMF_KEY );
if ( removed != null ) {
removed.close();
}
@ -277,13 +289,10 @@ public class EntityManagerFactoryExtension
throw throwable;
}
private static class EntityManagerFactoryScopeImpl implements EntityManagerFactoryScope, ExtensionContext.Store.CloseableResource {
private static class EntityManagerFactoryScopeImpl extends AbstractEntityManagerFactoryScope {
private final PersistenceUnitInfo persistenceUnitInfo;
private final Map<String, Object> integrationSettings;
private javax.persistence.EntityManagerFactory emf;
private boolean active = true;
private EntityManagerFactoryScopeImpl(
PersistenceUnitInfo persistenceUnitInfo,
Map<String, Object> integrationSettings) {
@ -291,54 +300,8 @@ public class EntityManagerFactoryExtension
this.integrationSettings = integrationSettings;
}
@Override
public javax.persistence.EntityManagerFactory getEntityManagerFactory() {
if ( emf == null ) {
emf = createEntityManagerFactory();
}
protected javax.persistence.EntityManagerFactory createEntityManagerFactory() {
return emf;
}
@Override
public StatementInspector getStatementInspector() {
return getEntityManagerFactory().unwrap( SessionFactoryImplementor.class ).getSessionFactoryOptions().getStatementInspector();
}
@Override
public void close() {
if ( ! active ) {
return;
}
log.debug( "Closing SessionFactoryScope" );
active = false;
releaseEntityManagerFactory();
}
public void releaseEntityManagerFactory() {
if ( emf != null ) {
log.debug( "Releasing SessionFactory" );
try {
emf.close();
}
catch (Exception e) {
log.warn( "Error closing EMF", e );
}
finally {
emf = null;
}
}
}
private javax.persistence.EntityManagerFactory createEntityManagerFactory() {
if ( ! active ) {
throw new IllegalStateException( "EntityManagerFactoryScope is no longer active" );
}
log.debug( "Creating EntityManagerFactory" );
final EntityManagerFactoryBuilder emfBuilder = Bootstrap.getEntityManagerFactoryBuilder(
new PersistenceUnitInfoDescriptor( persistenceUnitInfo ),
@ -347,168 +310,5 @@ public class EntityManagerFactoryExtension
return emfBuilder.build();
}
@Override
public void inEntityManager(Consumer<EntityManager> action) {
log.trace( "#inEntityManager(Consumer)" );
try (SessionImplementor session = getEntityManagerFactory().createEntityManager().unwrap( SessionImplementor.class ) ) {
log.trace( "EntityManager opened, calling action" );
action.accept( session );
}
finally {
log.trace( "EntityManager close - auto-close block" );
}
}
@Override
public <T> T fromEntityManager(Function<EntityManager, T> action) {
log.trace( "#fromEntityManager(Function)" );
try (SessionImplementor session = getEntityManagerFactory().createEntityManager().unwrap( SessionImplementor.class ) ) {
log.trace( "EntityManager opened, calling action" );
return action.apply( session );
}
finally {
log.trace( "EntityManager close - auto-close block" );
}
}
@Override
public void inTransaction(Consumer<EntityManager> action) {
log.trace( "#inTransaction(Consumer)" );
try (SessionImplementor session = getEntityManagerFactory().createEntityManager().unwrap( SessionImplementor.class ) ) {
log.trace( "EntityManager opened, calling action" );
inTransaction( session, action );
}
finally {
log.trace( "EntityManager close - auto-close block" );
}
}
@Override
public <T> T fromTransaction(Function<EntityManager, T> action) {
log.trace( "#fromTransaction(Function)" );
try (SessionImplementor session = getEntityManagerFactory().createEntityManager().unwrap( SessionImplementor.class ) ) {
log.trace( "EntityManager opened, calling action" );
return fromTransaction( session, action );
}
finally {
log.trace( "EntityManager close - auto-close block" );
}
}
@Override
public void inTransaction(EntityManager entityManager, Consumer<EntityManager> action) {
log.trace( "inTransaction(EntityManager,Consumer)" );
final SessionImplementor session = entityManager.unwrap( SessionImplementor.class );
final Transaction txn = session.beginTransaction();
log.trace( "Started transaction" );
try {
log.trace( "Calling action in txn" );
action.accept( session );
log.trace( "Called action - in txn" );
if ( !txn.getRollbackOnly() ) {
log.trace( "Committing transaction" );
txn.commit();
log.trace( "Committed transaction" );
}
else {
try {
log.trace( "Rollback transaction marked for rollback only" );
txn.rollback();
}
catch (Exception e) {
log.error( "Rollback failure", e );
}
}
}
catch (Exception e) {
log.tracef(
"Error calling action: %s (%s) - rolling back",
e.getClass().getName(),
e.getMessage()
);
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw e;
}
catch (AssertionError t) {
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw t;
}
}
@Override
public <T> T fromTransaction(EntityManager entityManager, Function<EntityManager,T> action) {
log.trace( "fromTransaction(EntityManager,Function)" );
final SessionImplementor session = entityManager.unwrap( SessionImplementor.class );
final Transaction txn = session.beginTransaction();
log.trace( "Started transaction" );
try {
log.trace( "Calling action in txn" );
final T result = action.apply( session );
log.trace( "Called action - in txn" );
log.trace( "Committing transaction" );
txn.commit();
log.trace( "Committed transaction" );
return result;
}
catch (Exception e) {
log.tracef(
"Error calling action: %s (%s) - rolling back",
e.getClass().getName(),
e.getMessage()
);
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw e;
}
catch (AssertionError t) {
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw t;
}
}
}
}

View File

@ -6,11 +6,8 @@
*/
package org.hibernate.testing.orm.junit;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
/**
* Contract for something that can build a SessionFactory.
*
@ -28,5 +25,5 @@ import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
* @author Steve Ebersole
*/
public interface EntityManagerFactoryProducer {
EntityManagerFactory produceEntityManagerFactory(PersistenceUnitDescriptor persistenceUnitDescriptor, Map<String,String> integrationSettings);
EntityManagerFactory produceEntityManagerFactory();
}

View File

@ -4,7 +4,10 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
package org.hibernate.testing.orm.junit;
import org.hibernate.testing.orm.junit.EntityManagerFactoryProducer;
import org.hibernate.testing.orm.junit.EntityManagerFactoryScope;
/**
* The keystone in EntityManagerFactoryScopeExtension support.

View File

@ -4,9 +4,10 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
package org.hibernate.testing.orm.junit;
import java.util.Optional;
import javax.persistence.EntityManagerFactory;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
@ -59,7 +60,7 @@ public class EntityManagerFactoryScopeExtension
if ( EntityManagerFactoryScopeContainer.class.isInstance( testInstance ) ) {
final EntityManagerFactoryScopeContainer scopeContainer = EntityManagerFactoryScopeContainer.class.cast(
testInstance );
final EntityManagerFactoryScope scope = new EntityManagerFactoryScope(
final EntityManagerFactoryScope scope = new EntityManagerFactoryScopeImpl(
scopeContainer.getEntityManagerFactoryProducer()
);
context.getStore( namespace( testInstance ) ).put( ENTITYMANAGER_FACTORY_KEY, scope );
@ -95,4 +96,20 @@ public class EntityManagerFactoryScopeExtension
throw throwable;
}
private static class EntityManagerFactoryScopeImpl extends AbstractEntityManagerFactoryScope {
private final EntityManagerFactoryProducer producer;
public EntityManagerFactoryScopeImpl(EntityManagerFactoryProducer producer) {
log.trace( "EntityManagerFactoryScope#<init>" );
this.producer = producer;
}
@Override
protected EntityManagerFactory createEntityManagerFactory() {
return producer.produceEntityManagerFactory();
}
}
}

View File

@ -4,7 +4,7 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.junit5;
package org.hibernate.testing.orm.junit;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
@ -12,7 +12,6 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.hibernate.testing.orm.junit.FailureExpectedExtension;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;

View File

@ -1,16 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.orm.junit;
/**
* Support for tests that wish to have the SessionFactory fixture
* injected as an instance variable for use.
*
* @author Steve Ebersole
*/
public abstract class InjectedSessionFactoryFunctionalTest {
}

View File

@ -16,7 +16,6 @@ import java.util.function.Function;
import org.hibernate.Interceptor;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.spi.MetadataImplementor;
@ -29,6 +28,7 @@ import org.hibernate.tool.schema.Action;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.ActionGrouping;
import org.hibernate.testing.orm.transaction.TransactionUtil;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
@ -349,110 +349,13 @@ public class SessionFactoryExtension
@Override
public void inTransaction(SessionImplementor session, Consumer<SessionImplementor> action) {
log.trace( "inTransaction(Session,Consumer)" );
final Transaction txn = session.beginTransaction();
log.trace( "Started transaction" );
try {
log.trace( "Calling action in txn" );
action.accept( session );
log.trace( "Called action - in txn" );
if ( !txn.getRollbackOnly() ) {
log.trace( "Committing transaction" );
txn.commit();
log.trace( "Committed transaction" );
}
else {
try {
log.trace( "Rollback transaction marked for rollback only" );
txn.rollback();
}
catch (Exception e) {
log.error( "Rollback failure", e );
}
}
}
catch (Exception e) {
log.tracef(
"Error calling action: %s (%s) - rolling back",
e.getClass().getName(),
e.getMessage()
);
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw e;
}
catch (AssertionError t) {
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw t;
}
TransactionUtil.inTransaction( session, action );
}
@Override
public <T> T fromTransaction(SessionImplementor session, Function<SessionImplementor, T> action) {
log.trace( "fromTransaction(Session,Function)" );
final Transaction txn = session.beginTransaction();
log.trace( "Started transaction" );
try {
log.trace( "Calling action in txn" );
final T result = action.apply( session );
log.trace( "Called action - in txn" );
log.trace( "Committing transaction" );
txn.commit();
log.trace( "Committed transaction" );
return result;
}
catch (Exception e) {
log.tracef(
"Error calling action: %s (%s) - rolling back",
e.getClass().getName(),
e.getMessage()
);
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw e;
}
catch (AssertionError t) {
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw t;
}
return TransactionUtil.fromTransaction( session, action );
}
@Override
@ -485,47 +388,7 @@ public class SessionFactoryExtension
public void inStatelessTransaction(StatelessSession session, Consumer<StatelessSession> action) {
log.trace( "inStatelessTransaction(StatelessSession,Consumer)" );
final Transaction txn = session.beginTransaction();
log.trace( "Started transaction" );
try {
log.trace( "Calling action in txn" );
action.accept( session );
log.trace( "Called action - in txn" );
if ( !txn.getRollbackOnly() ) {
log.trace( "Committing transaction" );
txn.commit();
log.trace( "Committed transaction" );
}
else {
try {
log.trace( "Rollback transaction marked for rollback only" );
txn.rollback();
}
catch (Exception e) {
log.error( "Rollback failure", e );
}
}
}
catch (Exception e) {
log.tracef(
"Error calling action: %s (%s) - rolling back",
e.getClass().getName(),
e.getMessage()
);
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw e;
}
TransactionUtil.inTransaction( session, action );
}
}
}

View File

@ -0,0 +1,146 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.testing.orm.transaction;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.persistence.EntityManager;
import org.hibernate.SharedSessionContract;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.hibernate.engine.spi.SessionImplementor;
import org.jboss.logging.Logger;
public abstract class TransactionUtil {
private static final org.jboss.logging.Logger log = Logger.getLogger( TransactionUtil.class );
public static void inTransaction(SessionImplementor session, Consumer<SessionImplementor> action) {
wrapInTransaction( session, session, action );
}
public static void inTransaction(EntityManager entityManager, Consumer<EntityManager> action) {
wrapInTransaction( (SharedSessionContract) entityManager, entityManager, action );
}
public static void inTransaction(StatelessSession session, Consumer<StatelessSession> action) {
wrapInTransaction( session, session, action );
}
public static <R> R fromTransaction(SessionImplementor session, Function<SessionImplementor, R> action) {
return wrapInTransaction( session, session, action );
}
public static <R> R fromTransaction(EntityManager entityManager, Function<EntityManager, R> action) {
return wrapInTransaction( (SharedSessionContract) entityManager, entityManager, action );
}
private static <T> void wrapInTransaction(SharedSessionContract session, T actionInput, Consumer<T> action) {
final Transaction txn = session.beginTransaction();
log.trace( "Started transaction" );
try {
log.trace( "Calling action in txn" );
action.accept( actionInput );
log.trace( "Called action - in txn" );
if ( !txn.getRollbackOnly() ) {
log.trace( "Committing transaction" );
txn.commit();
log.trace( "Committed transaction" );
}
else {
try {
log.trace( "Rollback transaction marked for rollback only" );
txn.rollback();
}
catch (Exception e) {
log.error( "Rollback failure", e );
}
}
}
catch (Exception e) {
log.tracef(
"Error calling action: %s (%s) - rolling back",
e.getClass().getName(),
e.getMessage()
);
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw e;
}
catch (AssertionError t) {
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw t;
}
}
private static <T, R> R wrapInTransaction(SharedSessionContract session, T actionInput, Function<T, R> action) {
log.trace( "Started transaction" );
Transaction txn = session.beginTransaction();
try {
log.trace( "Calling action in txn" );
final R result = action.apply( actionInput );
log.trace( "Called action - in txn" );
log.trace( "Committing transaction" );
txn.commit();
log.trace( "Committed transaction" );
return result;
}
catch (Exception e) {
log.tracef(
"Error calling action: %s (%s) - rolling back",
e.getClass().getName(),
e.getMessage()
);
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw e;
}
catch (AssertionError t) {
try {
txn.rollback();
}
catch (Exception ignore) {
log.trace( "Was unable to roll back transaction" );
// really nothing else we can do here - the attempt to
// rollback already failed and there is nothing else
// to clean up.
}
throw t;
}
}
}