METAGEN-98 Switching to JUnit, adding a custom test runner and the annotations @WithClasses, @WithMappingFiles, WithProcessorOptions and @IgnoreCompilationErrors

This commit is contained in:
Hardy Ferentschik 2013-10-24 16:07:45 +02:00 committed by Strong Liu
parent b51b230c57
commit bf5b146191
45 changed files with 869 additions and 800 deletions

View File

@ -53,7 +53,7 @@ ext {
pressgangVersion = '3.0.0'
libraries = [
// test libraries
testng: "org.testng:testng:6.1",
junit: "junit:junit:4.10",
hibernate: "org.hibernate:hibernate-core:3.6.0.Beta1",
jpa_api: "org.hibernate.javax.persistence:hibernate-jpa-2.0-api:1.0.0.Final",
slf4j_api: "org.slf4j:slf4j-api:${slf4jVersion}",
@ -84,7 +84,7 @@ configurations.jaxb {
// Prepare the different dependencies per configuration
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
dependencies {
testCompile libraries.testng
testCompile libraries.junit
testCompile libraries.jpa_api
testCompile libraries.hibernate
testCompile libraries.slf4j_api
@ -98,6 +98,8 @@ dependencies {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// The main Java build - jaxb schema class generation, compilation, test
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compileJava.options.define(compilerArgs: ["-proc:none", "-encoding", "UTF-8"])
compileTestJava.options.define(compilerArgs: ["-proc:none", "-encoding", "UTF-8"])
versionInjection {
into( 'org.hibernate.jpamodelgen.Version', 'getVersionString' )
}
@ -153,10 +155,6 @@ task jaxb {
compileJava.dependsOn jaxb
test {
useTestNG()
systemProperty 'sourceBaseDir', 'src/test/java'
systemProperty 'outBaseDir', "${buildDir}/classes/test"
beforeTest { descriptor ->
logger.lifecycle("Running " + descriptor)
}

View File

@ -15,10 +15,10 @@
* limitations under the License.
*/
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -26,16 +26,12 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassG
* @author Hardy Ferentschik
*/
@TestForIssue(jiraKey = "METAGEN-40")
@WithClasses(DefaultPackageEntity.class)
public class DefaultPackageTest extends CompilationTest {
@Test
public void testMetaModelGeneratedForEntitiesInDefaultPackage() {
assertMetamodelClassGeneratedFor( DefaultPackageEntity.class );
}
@Override
protected String getPackageNameOfCurrentTest() {
return null;
}
}

View File

@ -16,13 +16,12 @@
*/
package org.hibernate.jpamodelgen.test;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.util.StringUtil;
import org.junit.Test;
import static org.testng.Assert.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Hardy Ferentschik

View File

@ -16,15 +16,12 @@
*/
package org.hibernate.jpamodelgen.test.accesstype;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithMappingFiles;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAbsenceOfFieldInMetamodelFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAttributeTypeInMetaModelFor;
@ -34,6 +31,31 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfField
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
// TODO - differentiate needed classes per test better. Right now all test classes are processed for each test (HF)
@WithClasses({
Address.class,
Area.class,
Building.class,
Country.class,
Customer.class,
Detail.class,
Hominidae.class,
Hotel.class,
HotelRoom.class,
House.class,
Human.class,
Inhabitant.class,
Item.class,
LivingBeing.class,
Mammals.class,
Order.class,
Pet.class,
Product.class,
Room.class,
Shop.class,
User.class
})
@WithMappingFiles("orm.xml")
public class AccessTypeTest extends CompilationTest {
@Test
@ -71,10 +93,12 @@ public class AccessTypeTest extends CompilationTest {
}
@Test
@TestForIssue( jiraKey = " METAGEN-81")
@TestForIssue(jiraKey = " METAGEN-81")
public void testAccessTypeForEmbeddableDeterminedByIdAnnotationInRootEntity() {
assertPresenceOfFieldInMetamodelFor( Hotel.class, "webmaster",
"Access type should be inherited position of the @Id field annotation in the root entity" );
assertPresenceOfFieldInMetamodelFor(
Hotel.class, "webmaster",
"Access type should be inherited position of the @Id field annotation in the root entity"
);
}
@Test
@ -102,16 +126,4 @@ public class AccessTypeTest extends CompilationTest {
assertPresenceOfFieldInMetamodelFor( Customer.class, "goodPayer", "access type overriding" );
assertAttributeTypeInMetaModelFor( Customer.class, "goodPayer", Boolean.class, "access type overriding" );
}
@Override
protected String getPackageNameOfCurrentTest() {
return AccessTypeTest.class.getPackage().getName();
}
@Override
protected Collection<String> getOrmFiles() {
List<String> ormFiles = new ArrayList<String>();
ormFiles.add( TestUtil.fcnToPath( AccessTypeTest.class.getPackage().getName() ) + "/orm.xml" );
return ormFiles;
}
}

View File

@ -16,10 +16,10 @@
*/
package org.hibernate.jpamodelgen.test.arraytype;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAttributeTypeInMetaModelFor;
@ -30,20 +30,17 @@ public class ArrayTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-2")
@WithClasses(Image.class)
public void testPrimitiveArray() {
assertAttributeTypeInMetaModelFor( Image.class, "data", byte[].class, "Wrong type for field." );
}
@Test
@TestForIssue(jiraKey = "METAGEN-2")
@WithClasses(TemperatureSamples.class)
public void testIntegerArray() {
assertAttributeTypeInMetaModelFor(
TemperatureSamples.class, "samples", Integer[].class, "Wrong type for field."
);
}
@Override
protected String getPackageNameOfCurrentTest() {
return Image.class.getPackage().getName();
}
}

View File

@ -16,10 +16,10 @@
*/
package org.hibernate.jpamodelgen.test.blob;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfFieldInMetamodelFor;
@ -31,13 +31,9 @@ public class BlobTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-38")
@WithClasses(BlobEntity.class)
public void testBlobField() {
assertMetamodelClassGeneratedFor( BlobEntity.class );
assertPresenceOfFieldInMetamodelFor( BlobEntity.class, "blob", "the metamodel should have a member 'blob'" );
}
@Override
protected String getPackageNameOfCurrentTest() {
return BlobTest.class.getPackage().getName();
}
}

View File

@ -16,15 +16,11 @@
*/
package org.hibernate.jpamodelgen.test.elementcollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithMappingFiles;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMapAttributesInMetaModelFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -37,6 +33,7 @@ public class ElementCollectionTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-8")
@WithClasses({ House.class, Room.class })
public void testElementCollectionOnMap() {
assertMetamodelClassGeneratedFor( House.class );
assertMetamodelClassGeneratedFor( Room.class );
@ -46,6 +43,7 @@ public class ElementCollectionTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-19")
@WithClasses({ Hotel.class, Room.class, Cleaner.class })
public void testMapKeyClass() {
assertMetamodelClassGeneratedFor( Hotel.class );
assertMapAttributesInMetaModelFor(
@ -59,6 +57,8 @@ public class ElementCollectionTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-22")
@WithClasses({ Hostel.class, Room.class, Cleaner.class })
@WithMappingFiles("hostel.xml")
public void testMapKeyClassXmlConfigured() {
assertMetamodelClassGeneratedFor( Hostel.class );
assertMapAttributesInMetaModelFor(
@ -69,16 +69,4 @@ public class ElementCollectionTest extends CompilationTest {
Hostel.class, "cleaners", Room.class, Cleaner.class, "Wrong type in map attribute."
);
}
@Override
protected String getPackageNameOfCurrentTest() {
return ElementCollectionTest.class.getPackage().getName();
}
@Override
protected Collection<String> getOrmFiles() {
List<String> ormFiles = new ArrayList<String>();
ormFiles.add( TestUtil.fcnToPath( ElementCollectionTest.class.getPackage().getName() ) + "/hostel.xml" );
return ormFiles;
}
}

View File

@ -16,9 +16,9 @@
*/
package org.hibernate.jpamodelgen.test.embeddable;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAttributeTypeInMetaModelFor;
@ -27,6 +27,7 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAttributeTypeIn
*/
public class EmbeddableAccessTypeTest extends CompilationTest {
@Test
@WithClasses({ Base.class, EmbeddableEntity.class, IStuff.class, MyEntity.class, Stuff.class })
public void testCorrectAccessTypeUsedForEmbeddable() {
assertAttributeTypeInMetaModelFor(
EmbeddableEntity.class,
@ -35,9 +36,4 @@ public class EmbeddableAccessTypeTest extends CompilationTest {
"The target annotation set the type to Stuff"
);
}
@Override
protected String getPackageNameOfCurrentTest() {
return EmbeddableAccessTypeTest.class.getPackage().getName();
}
}

View File

@ -16,13 +16,10 @@
*/
package org.hibernate.jpamodelgen.test.embeddedid.withinheritance;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithMappingFiles;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfFieldInMetamodelFor;
@ -32,23 +29,12 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfField
*/
public class EmbeddedIdWithInheritanceTest extends CompilationTest {
@Test
@WithClasses({ Ref.class, AbstractRef.class, TestEntity.class })
@WithMappingFiles("orm.xml")
public void testEntityContainsEmbeddedIdProperty() {
assertMetamodelClassGeneratedFor( TestEntity.class );
assertPresenceOfFieldInMetamodelFor(
TestEntity.class, "ref", "Property ref should be in metamodel"
);
}
@Override
protected String getPackageNameOfCurrentTest() {
return EmbeddedIdWithInheritanceTest.class.getPackage().getName();
}
@Override
protected Collection<String> getOrmFiles() {
List<String> ormFiles = new ArrayList<String>();
String dir = TestUtil.fcnToPath( EmbeddedIdWithInheritanceTest.class.getPackage().getName() );
ormFiles.add( dir + "/orm.xml" );
return ormFiles;
}
}

View File

@ -16,14 +16,10 @@
*/
package org.hibernate.jpamodelgen.test.embeddedid.withoutinheritance;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithMappingFiles;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfFieldInMetamodelFor;
@ -33,6 +29,8 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfField
*/
public class EmbeddedIdNoInheritanceTest extends CompilationTest {
@Test
@WithClasses({ Person.class, XmlPerson.class, PersonId.class })
@WithMappingFiles("orm.xml")
public void testGeneratedAnnotationNotGenerated() {
assertMetamodelClassGeneratedFor( Person.class );
assertPresenceOfFieldInMetamodelFor(
@ -50,19 +48,5 @@ public class EmbeddedIdNoInheritanceTest extends CompilationTest {
assertPresenceOfFieldInMetamodelFor(
XmlPerson.class, "address", "Property id should be in metamodel"
);
}
@Override
protected String getPackageNameOfCurrentTest() {
return EmbeddedIdNoInheritanceTest.class.getPackage().getName();
}
@Override
protected Collection<String> getOrmFiles() {
List<String> ormFiles = new ArrayList<String>();
String dir = TestUtil.fcnToPath( EmbeddedIdNoInheritanceTest.class.getPackage().getName() );
ormFiles.add( dir + "/orm.xml" );
return ormFiles;
}
}

View File

@ -16,14 +16,14 @@
*/
package org.hibernate.jpamodelgen.test.generatedannotation;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.getMetaModelSourceAsString;
import static org.testng.Assert.assertTrue;
import static org.junit.Assert.assertTrue;
/**
* @author Hardy Ferentschik
@ -32,17 +32,13 @@ public class GeneratedAnnotationTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-79")
@WithClasses(TestEntity.class)
public void testGeneratedAnnotationNotGenerated() {
assertMetamodelClassGeneratedFor( TestEntity.class );
// need to check the source because @Generated is not a runtime annotation
String metaModelSource = getMetaModelSourceAsString( TestEntity.class );
String generatedString = "@Generated(value = \"org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor\")";
assertTrue( metaModelSource.contains( generatedString ), "@Generated should be added to the metamodel." );
}
@Override
protected String getPackageNameOfCurrentTest() {
return GeneratedAnnotationTest.class.getPackage().getName();
assertTrue( "@Generated should be added to the metamodel.", metaModelSource.contains( generatedString ) );
}
}

View File

@ -16,19 +16,17 @@
*/
package org.hibernate.jpamodelgen.test.generatedannotation;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithProcessorOption;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.dumpMetaModelSourceFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.getMetaModelSourceAsString;
import static org.testng.Assert.assertTrue;
import static org.junit.Assert.assertTrue;
/**
* @author Hardy Ferentschik
@ -36,6 +34,8 @@ import static org.testng.Assert.assertTrue;
public class GenerationDateTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-73")
@WithClasses(TestEntity.class)
@WithProcessorOption(key = JPAMetaModelEntityProcessor.ADD_GENERATION_DATE, value = "true")
public void testGeneratedAnnotationGenerated() {
assertMetamodelClassGeneratedFor( TestEntity.class );
@ -45,18 +45,6 @@ public class GenerationDateTest extends CompilationTest {
dumpMetaModelSourceFor( TestEntity.class );
String generatedString = "@Generated(value = \"org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor\", date = \"";
assertTrue( metaModelSource.contains( generatedString ), "@Generated should also contain the date parameter." );
}
@Override
protected Map<String, String> getProcessorOptions() {
Map<String, String> properties = new HashMap<String, String>();
properties.put( JPAMetaModelEntityProcessor.ADD_GENERATION_DATE, "true" );
return properties;
}
@Override
protected String getPackageNameOfCurrentTest() {
return GenerationDateTest.class.getPackage().getName();
assertTrue( "@Generated should also contain the date parameter.", metaModelSource.contains( generatedString ) );
}
}

View File

@ -16,17 +16,16 @@
*/
package org.hibernate.jpamodelgen.test.generatedannotation;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithProcessorOption;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.getMetaModelSourceAsString;
import static org.testng.Assert.assertFalse;
import static org.junit.Assert.assertFalse;
/**
* @author Hardy Ferentschik
@ -34,23 +33,13 @@ import static org.testng.Assert.assertFalse;
public class SkipGeneratedAnnotationTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-79")
@WithClasses(TestEntity.class)
@WithProcessorOption(key = JPAMetaModelEntityProcessor.ADD_GENERATED_ANNOTATION, value = "false")
public void testGeneratedAnnotationGenerated() {
assertMetamodelClassGeneratedFor( TestEntity.class );
// need to check the source because @Generated is not a runtime annotation
String metaModelSource = getMetaModelSourceAsString( TestEntity.class );
assertFalse( metaModelSource.contains( "@Generated" ), "@Generated should not be added to the metamodel." );
}
@Override
protected Map<String, String> getProcessorOptions() {
Map<String, String> properties = new HashMap<String, String>();
properties.put( JPAMetaModelEntityProcessor.ADD_GENERATED_ANNOTATION, "false" );
return properties;
}
@Override
protected String getPackageNameOfCurrentTest() {
return SkipGeneratedAnnotationTest.class.getPackage().getName();
assertFalse( "@Generated should not be added to the metamodel.", metaModelSource.contains( "@Generated" ) );
}
}

View File

@ -16,9 +16,9 @@
*/
package org.hibernate.jpamodelgen.test.generics;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -28,13 +28,9 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassG
public class GenericsTest extends CompilationTest {
@Test
@WithClasses({ Parent.class, Child.class })
public void testGenerics() {
assertMetamodelClassGeneratedFor( Parent.class );
assertMetamodelClassGeneratedFor( Child.class );
}
@Override
protected String getPackageNameOfCurrentTest() {
return GenericsTest.class.getPackage().getName();
}
}

View File

@ -18,7 +18,8 @@ package org.hibernate.jpamodelgen.test.hashcode;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAbsenceOfFieldInMetamodelFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -31,15 +32,11 @@ public class HashCodeTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-76")
@WithClasses(HashEntity.class)
public void testHashCodeDoesNotCreateSingularAttribute() {
assertMetamodelClassGeneratedFor( HashEntity.class );
assertPresenceOfFieldInMetamodelFor( HashEntity.class, "id" );
assertAbsenceOfFieldInMetamodelFor( HashEntity.class, "hashCode", "hashCode is not a persistent property" );
}
@Override
protected String getPackageNameOfCurrentTest() {
return HashCodeTest.class.getPackage().getName();
}
}

View File

@ -16,9 +16,9 @@
*/
package org.hibernate.jpamodelgen.test.inheritance.basic;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAttributeTypeInMetaModelFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfFieldInMetamodelFor;
@ -30,6 +30,15 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertSuperClassRelat
*/
public class InheritanceTest extends CompilationTest {
@Test
@WithClasses({
AbstractEntity.class,
Area.class,
Building.class,
Customer.class,
House.class,
Person.class,
User.class
})
public void testInheritance() throws Exception {
// entity inheritance
@ -53,10 +62,5 @@ public class InheritanceTest extends CompilationTest {
assertPresenceOfFieldInMetamodelFor( Person.class, "name", "Property 'name' should exist" );
}
@Override
protected String getPackageNameOfCurrentTest() {
return InheritanceTest.class.getPackage().getName();
}
}

View File

@ -16,10 +16,10 @@
*/
package org.hibernate.jpamodelgen.test.inheritance.deep;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAttributeTypeInMetaModelFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -34,6 +34,7 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfField
public class DeepInheritanceTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-69")
@WithClasses({ JetPlane.class, PersistenceBase.class, Plane.class })
public void testDeepInheritance() throws Exception {
assertMetamodelClassGeneratedFor( Plane.class );
assertMetamodelClassGeneratedFor( JetPlane.class );
@ -45,9 +46,4 @@ public class DeepInheritanceTest extends CompilationTest {
"jets should be defined in JetPlane_"
);
}
@Override
protected String getPackageNameOfCurrentTest() {
return DeepInheritanceTest.class.getPackage().getName();
}
}

View File

@ -16,9 +16,9 @@
*/
package org.hibernate.jpamodelgen.test.inheritance.unmappedclassinhierarchy;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertSuperClassRelationShipInMetamodel;
@ -28,13 +28,16 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertSuperClassRelat
*/
public class UnmappedClassInHierarchyTest extends CompilationTest {
@Test
@WithClasses({
BaseEntity.class,
MappedBase.class,
NormalExtendsEntity.class,
NormalExtendsMapped.class,
SubA.class,
SubB.class
})
public void testUnmappedClassInHierarchy() throws Exception {
assertSuperClassRelationShipInMetamodel( SubA.class, BaseEntity.class );
assertSuperClassRelationShipInMetamodel( SubB.class, MappedBase.class );
}
@Override
protected String getPackageNameOfCurrentTest() {
return UnmappedClassInHierarchyTest.class.getPackage().getName();
}
}

View File

@ -16,13 +16,12 @@
*/
package org.hibernate.jpamodelgen.test.mappedsuperclass.embeddablemappedsuperclass;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertNoCompilationError;
/**
* @author Hardy Ferentschik
@ -31,13 +30,8 @@ public class EmbeddableMappedSuperClassTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-36")
@WithClasses(EmbeddableAndMappedSuperClass.class)
public void testMetaModelsGenerated() {
assertMetamodelClassGeneratedFor( EmbeddableAndMappedSuperClass.class );
assertNoCompilationError( getCompilationDiagnostics() );
}
@Override
protected String getPackageNameOfCurrentTest() {
return EmbeddableMappedSuperClassTest.class.getPackage().getName();
}
}

View File

@ -16,9 +16,9 @@
*/
package org.hibernate.jpamodelgen.test.mappedsuperclass.mappedsuperclasswithoutid;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfFieldInMetamodelFor;
@ -28,15 +28,11 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfField
*/
public class MappedSuperclassWithoutExplicitIdTest extends CompilationTest {
@Test
@WithClasses({ ConcreteProduct.class, Product.class, Shop.class })
public void testRightAccessTypeForMappedSuperclass() {
assertMetamodelClassGeneratedFor( ConcreteProduct.class );
assertMetamodelClassGeneratedFor( Product.class );
assertMetamodelClassGeneratedFor( Shop.class );
assertPresenceOfFieldInMetamodelFor( Product.class, "shop", "The many to one attribute shop is missing" );
}
@Override
protected String getPackageNameOfCurrentTest() {
return MappedSuperclassWithoutExplicitIdTest.class.getPackage().getName();
}
}

View File

@ -16,10 +16,10 @@
*/
package org.hibernate.jpamodelgen.test.mappedsuperclass.typedmappedsuperclass;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -29,12 +29,15 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassG
@TestForIssue(jiraKey = "METAGEN-37")
public class TypesMappedSuperclassTest extends CompilationTest {
@Test
@WithClasses({
AttachmentGroup.class,
AttachmentGroupInTopic.class,
AttachmentGroupPost.class,
AttachmentGroupPostInTopic.class,
Post.class,
UserRole.class
})
public void testExtractClosestRealType() {
assertMetamodelClassGeneratedFor( AttachmentGroup.class );
}
@Override
protected String getPackageNameOfCurrentTest() {
return TypesMappedSuperclassTest.class.getPackage().getName();
}
}

View File

@ -16,14 +16,10 @@
*/
package org.hibernate.jpamodelgen.test.mixedmode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithMappingFiles;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAbsenceOfFieldInMetamodelFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAttributeTypeInMetaModelFor;
@ -35,6 +31,8 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfField
*/
public class MixedConfigurationTest extends CompilationTest {
@Test
@WithClasses({ Car.class, Vehicle.class })
@WithMappingFiles("car.xml")
public void testDefaultAccessTypeApplied() {
assertMetamodelClassGeneratedFor( Vehicle.class );
assertMetamodelClassGeneratedFor( Car.class );
@ -45,6 +43,8 @@ public class MixedConfigurationTest extends CompilationTest {
}
@Test
@WithClasses({ Truck.class, Vehicle.class })
@WithMappingFiles("truck.xml")
public void testExplicitXmlConfiguredAccessTypeApplied() {
assertMetamodelClassGeneratedFor( Vehicle.class );
assertMetamodelClassGeneratedFor( Truck.class );
@ -56,6 +56,8 @@ public class MixedConfigurationTest extends CompilationTest {
}
@Test
@WithClasses({ Car.class, Vehicle.class, RentalCar.class, RentalCompany.class })
@WithMappingFiles({ "car.xml", "rentalcar.xml" })
public void testMixedConfiguration() {
assertMetamodelClassGeneratedFor( RentalCar.class );
assertMetamodelClassGeneratedFor( RentalCompany.class );
@ -72,6 +74,8 @@ public class MixedConfigurationTest extends CompilationTest {
}
@Test
@WithClasses({ Coordinates.class, ZeroCoordinates.class, Location.class })
@WithMappingFiles("coordinates.xml")
public void testAccessTypeForXmlConfiguredEmbeddables() {
assertMetamodelClassGeneratedFor( Coordinates.class );
assertPresenceOfFieldInMetamodelFor(
@ -91,20 +95,4 @@ public class MixedConfigurationTest extends CompilationTest {
"Field access should be used, but ZeroCoordinates does not define fields"
);
}
@Override
protected String getPackageNameOfCurrentTest() {
return MixedConfigurationTest.class.getPackage().getName();
}
@Override
protected Collection<String> getOrmFiles() {
List<String> ormFiles = new ArrayList<String>();
String dir = TestUtil.fcnToPath( MixedConfigurationTest.class.getPackage().getName() );
ormFiles.add( dir + "/car.xml" );
ormFiles.add( dir + "/rentalcar.xml" );
ormFiles.add( dir + "/truck.xml" );
ormFiles.add( dir + "/coordinates.xml" );
return ormFiles;
}
}

View File

@ -16,14 +16,10 @@
*/
package org.hibernate.jpamodelgen.test.mixedmode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithMappingFiles;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAbsenceOfFieldInMetamodelFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -33,20 +29,10 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassG
*/
public class XmlMetaCompleteTest extends CompilationTest {
@Test
@WithClasses(Person.class)
@WithMappingFiles("orm.xml")
public void testXmlConfiguredEmbeddedClassGenerated() {
assertMetamodelClassGeneratedFor( Person.class );
assertAbsenceOfFieldInMetamodelFor( Person.class, "name" );
}
@Override
protected String getPackageNameOfCurrentTest() {
return XmlMetaCompleteTest.class.getPackage().getName();
}
@Override
protected Collection<String> getOrmFiles() {
List<String> ormFiles = new ArrayList<String>();
ormFiles.add( TestUtil.fcnToPath( XmlMetaCompleteTest.class.getPackage().getName() ) + "/orm.xml" );
return ormFiles;
}
}

View File

@ -16,14 +16,12 @@
*/
package org.hibernate.jpamodelgen.test.persistence21;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithProcessorOption;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -35,23 +33,11 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassG
public class Jpa21DescriptorTest extends CompilationTest {
@Test
@TestForIssue( jiraKey = "METAGEN-92" )
@TestForIssue(jiraKey = "METAGEN-92")
@WithClasses(Snafu.class)
@WithProcessorOption(key = JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION,
value = "org/hibernate/jpamodelgen/test/persistence21/persistence.xml")
public void testMetaModelGeneratedForXmlConfiguredEntity() {
assertMetamodelClassGeneratedFor( Snafu.class );
}
@Override
protected String getPackageNameOfCurrentTest() {
return Jpa21DescriptorTest.class.getPackage().getName();
}
@Override
protected Map<String, String> getProcessorOptions() {
Map<String, String> properties = new HashMap<String, String>();
properties.put(
JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION,
TestUtil.fcnToPath( Jpa21DescriptorTest.class.getPackage().getName() ) + "/persistence.xml"
);
return properties;
}
}

View File

@ -16,9 +16,9 @@
*/
package org.hibernate.jpamodelgen.test.rawtypes;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -28,13 +28,9 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassG
public class RawTypesTest extends CompilationTest {
@Test
@WithClasses({ DeskWithRawType.class, EmployeeWithRawType.class })
public void testGenerics() {
assertMetamodelClassGeneratedFor( DeskWithRawType.class );
assertMetamodelClassGeneratedFor( EmployeeWithRawType.class );
}
@Override
protected String getPackageNameOfCurrentTest() {
return DeskWithRawType.class.getPackage().getName();
}
}

View File

@ -16,17 +16,15 @@
*/
package org.hibernate.jpamodelgen.test.separatecompilationunits;
import java.io.File;
import java.util.List;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.separatecompilationunits.superclass.MappedSuperclass;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.IgnoreCompilationErrors;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.getMetaModelSourceAsString;
import static org.testng.Assert.assertTrue;
import static org.junit.Assert.assertTrue;
/**
* @author Hardy Ferentschik
@ -34,6 +32,8 @@ import static org.testng.Assert.assertTrue;
@TestForIssue(jiraKey = "METAGEN-35")
public class SeparateCompilationUnitsTest extends CompilationTest {
@Test
@WithClasses(value = Entity.class, preCompile = MappedSuperclass.class)
@IgnoreCompilationErrors
public void testInheritance() throws Exception {
// need to work with the source file. Entity_.class won't get generated, because the mapped superclass
// will not be on the classpath
@ -44,23 +44,4 @@ public class SeparateCompilationUnitsTest extends CompilationTest {
)
);
}
@Override
@BeforeClass
// override compileAllTestEntities to compile the mapped super class explicitly
protected void compileAllTestEntities() throws Exception {
String superClassPackageName = getPackageNameOfCurrentTest() + ".superclass";
List<File> sourceFiles = getCompilationUnits(
CompilationTest.getSourceBaseDir(), superClassPackageName
);
compile( sourceFiles );
sourceFiles = getCompilationUnits( getSourceBaseDir(), getPackageNameOfCurrentTest() );
compile( sourceFiles );
}
@Override
protected String getPackageNameOfCurrentTest() {
return SeparateCompilationUnitsTest.class.getPackage().getName();
}
}

View File

@ -16,10 +16,10 @@
*/
package org.hibernate.jpamodelgen.test.sortedcollection;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfFieldInMetamodelFor;
@ -31,15 +31,11 @@ public class SortedCollectionTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-62")
@WithClasses({ Printer.class, PrintJob.class })
public void testGenerics() {
assertMetamodelClassGeneratedFor( Printer.class );
assertMetamodelClassGeneratedFor( PrintJob.class );
assertPresenceOfFieldInMetamodelFor( Printer.class, "printQueue", "There sorted set attribute is missing" );
assertPresenceOfFieldInMetamodelFor( Printer.class, "printedJobs", "There sorted map attribute is missing" );
}
@Override
protected String getPackageNameOfCurrentTest() {
return SortedCollectionTest.class.getPackage().getName();
}
}

View File

@ -16,18 +16,16 @@
*/
package org.hibernate.jpamodelgen.test.supresswarnings;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithProcessorOption;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.getMetaModelSourceAsString;
import static org.testng.Assert.assertTrue;
import static org.junit.Assert.assertTrue;
/**
* @author Hardy Ferentschik
@ -35,29 +33,16 @@ import static org.testng.Assert.assertTrue;
public class SuppressWarningsAnnotationGeneratedTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-50")
@WithClasses(TestEntity.class)
@WithProcessorOption(key = JPAMetaModelEntityProcessor.ADD_SUPPRESS_WARNINGS_ANNOTATION, value = "true")
public void testSuppressedWarningsAnnotationGenerated() {
assertMetamodelClassGeneratedFor( TestEntity.class );
// need to check the source because @SuppressWarnings is not a runtime annotation
String metaModelSource = getMetaModelSourceAsString( TestEntity.class );
assertTrue(
metaModelSource.contains( "@SuppressWarnings(\"all\")" ),
"@SuppressWarnings should be added to the metamodel."
"@SuppressWarnings should be added to the metamodel.",
metaModelSource.contains( "@SuppressWarnings(\"all\")" )
);
}
@Override
protected Map<String, String> getProcessorOptions() {
Map<String, String> properties = new HashMap<String, String>();
properties.put(
JPAMetaModelEntityProcessor.ADD_SUPPRESS_WARNINGS_ANNOTATION,
"true"
);
return properties;
}
@Override
protected String getPackageNameOfCurrentTest() {
return SuppressWarningsAnnotationGeneratedTest.class.getPackage().getName();
}
}

View File

@ -16,14 +16,14 @@
*/
package org.hibernate.jpamodelgen.test.supresswarnings;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.getMetaModelSourceAsString;
import static org.testng.Assert.assertFalse;
import static org.junit.Assert.assertFalse;
/**
* @author Hardy Ferentschik
@ -32,19 +32,15 @@ public class SuppressWarningsAnnotationNotGeneratedTest extends CompilationTest
@Test
@TestForIssue(jiraKey = "METAGEN-50")
@WithClasses(TestEntity.class)
public void testSuppressedWarningsAnnotationNotGenerated() {
assertMetamodelClassGeneratedFor( TestEntity.class );
// need to check the source because @SuppressWarnings is not a runtime annotation
String metaModelSource = getMetaModelSourceAsString( TestEntity.class );
assertFalse(
metaModelSource.contains( "@SuppressWarnings(\"all\")" ),
"@SuppressWarnings should not be added to the metamodel."
"@SuppressWarnings should not be added to the metamodel.",
metaModelSource.contains( "@SuppressWarnings(\"all\")" )
);
}
@Override
protected String getPackageNameOfCurrentTest() {
return SuppressWarningsAnnotationNotGeneratedTest.class.getPackage().getName();
}
}

View File

@ -14,14 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpamodelgen.test.targetannotation;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAttributeTypeInMetaModelFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -34,6 +32,7 @@ public class TargetAnnotationTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-30")
@WithClasses({ Address.class, AddressImpl.class, House.class })
public void testEmbeddableWithTargetAnnotation() {
assertMetamodelClassGeneratedFor( House.class );
assertPresenceOfFieldInMetamodelFor( House.class, "address", "the metamodel should have a member 'address'" );
@ -44,9 +43,4 @@ public class TargetAnnotationTest extends CompilationTest {
"The target annotation set the type to AddressImpl"
);
}
@Override
protected String getPackageNameOfCurrentTest() {
return TargetAnnotationTest.class.getPackage().getName();
}
}

View File

@ -16,10 +16,10 @@
*/
package org.hibernate.jpamodelgen.test.usertype;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfFieldInMetamodelFor;
@ -30,15 +30,11 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfField
@TestForIssue(jiraKey = "METAGEN-28")
public class UserTypeTest extends CompilationTest {
@Test
@WithClasses({ ContactDetails.class, PhoneNumber.class })
public void testCustomUserTypeInMetaModel() {
assertMetamodelClassGeneratedFor( ContactDetails.class );
assertPresenceOfFieldInMetamodelFor(
ContactDetails.class, "phoneNumber", "@Type annotated filed should be in metamodel"
ContactDetails.class, "phoneNumber", "@Type annotated field should be in metamodel"
);
}
@Override
protected String getPackageNameOfCurrentTest() {
return UserTypeTest.class.getPackage().getName();
}
}

View File

@ -0,0 +1,133 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpamodelgen.test.util;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
/**
* Custom JUnit runner which makes sure the annotation processor runs prior to the test method.
*
* @author Hardy Ferentschik
* @see CompilationStatement
*/
public class CompilationRunner extends BlockJUnit4ClassRunner {
private final List<Class<?>> testEntities;
private final List<Class<?>> preCompileEntities;
private final List<String> mappingFiles;
private final Map<String, String> processorOptions;
private final String packageName;
private boolean ignoreCompilationErrors;
public CompilationRunner(Class<?> clazz) throws InitializationError {
super( clazz );
this.testEntities = new ArrayList<Class<?>>();
this.preCompileEntities = new ArrayList<Class<?>>();
this.mappingFiles = new ArrayList<String>();
this.processorOptions = new HashMap<String, String>();
Package pkg = clazz.getPackage();
this.packageName = pkg != null ? pkg.getName() : null;
processWithClasses( clazz.getAnnotation( WithClasses.class ) );
processWithMappingFiles( clazz.getAnnotation( WithMappingFiles.class ) );
processOptions(
clazz.getAnnotation( WithProcessorOption.class ),
clazz.getAnnotation( WithProcessorOption.List.class )
);
ignoreCompilationErrors = clazz.getAnnotation( IgnoreCompilationErrors.class ) != null;
}
@Override
protected Statement methodBlock(FrameworkMethod method) {
Statement statement = super.methodBlock( method );
processAnnotations( method );
if ( !annotationProcessorNeedsToRun() ) {
return statement;
}
return new CompilationStatement(
statement,
testEntities,
preCompileEntities,
mappingFiles,
processorOptions,
ignoreCompilationErrors
);
}
private void processWithClasses(WithClasses withClasses) {
if ( withClasses != null ) {
Collections.addAll( testEntities, withClasses.value() );
Collections.addAll( preCompileEntities, withClasses.preCompile() );
}
}
private void processWithMappingFiles(WithMappingFiles withMappingFiles) {
if ( withMappingFiles != null ) {
String packageNameAsPath = TestUtil.fcnToPath( packageName );
for ( String mappingFile : withMappingFiles.value() ) {
mappingFiles.add( packageNameAsPath + File.separator + mappingFile );
}
}
}
private void processOptions(WithProcessorOption withProcessorOption,
WithProcessorOption.List withProcessorOptionsListAnnotation) {
addOptions( withProcessorOption );
if ( withProcessorOptionsListAnnotation != null ) {
for ( WithProcessorOption option : withProcessorOptionsListAnnotation.value() ) {
addOptions( option );
}
}
}
private void processAnnotations(FrameworkMethod method) {
// configuration will be added to potential class level configuration
processWithClasses( method.getAnnotation( WithClasses.class ) );
processWithMappingFiles( method.getAnnotation( WithMappingFiles.class ) );
processOptions(
method.getAnnotation( WithProcessorOption.class ),
method.getAnnotation( WithProcessorOption.List.class )
);
// overrides potential class level configuration
ignoreCompilationErrors = method.getAnnotation( IgnoreCompilationErrors.class ) != null;
}
private void addOptions(WithProcessorOption withProcessorOptionsAnnotation) {
if ( withProcessorOptionsAnnotation != null ) {
processorOptions.put( withProcessorOptionsAnnotation.key(), withProcessorOptionsAnnotation.value() );
}
}
private boolean annotationProcessorNeedsToRun() {
return !testEntities.isEmpty() || !mappingFiles.isEmpty();
}
}

View File

@ -0,0 +1,181 @@
package org.hibernate.jpamodelgen.test.util;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.fail;
/**
* A custom JUnit statement which will run annotation processor prior to execute the original statement/test.
*
* The classes to process are specified via {@code WithClasses}, {@code WithMappingFiles} and {@code WithProcessorOption}
* on the actual test.
*
* @author Hardy Ferentschik
*/
public class CompilationStatement extends Statement {
private static final Logger log = LoggerFactory.getLogger( CompilationStatement.class );
private static final String PACKAGE_SEPARATOR = ".";
private static final String ANNOTATION_PROCESSOR_OPTION_PREFIX = "-A";
private static final String SOURCE_BASE_DIR_PROPERTY = "sourceBaseDir";
private static final String SOURCE_BASE_DIR;
static {
// first we try to guess the target directory. This will work, if the build is triggered from the
// command line or the output directory used by the id is within the project directory (eg 'out' in Intellij).
File targetDir = TestUtil.getTargetDir();
File potentialSourceDirectory = new File( targetDir.getParent(), "src/test/java" );
if ( potentialSourceDirectory.exists() ) {
SOURCE_BASE_DIR = potentialSourceDirectory.getAbsolutePath();
}
else {
String tmp = System.getProperty( SOURCE_BASE_DIR_PROPERTY );
if ( tmp == null ) {
fail(
"Unable to guess determine the source directory. Specify the system property 'sourceBaseDir'" +
" pointing to the base directory of the test java sources."
);
}
SOURCE_BASE_DIR = tmp;
}
}
private final Statement originalStatement;
private final List<Class<?>> testEntities;
private final List<Class<?>> preCompileEntities;
private final List<String> xmlMappingFiles;
private final Map<String, String> processorOptions;
private final boolean ignoreCompilationErrors;
private final List<Diagnostic<?>> compilationDiagnostics;
public CompilationStatement(Statement originalStatement,
List<Class<?>> testEntities,
List<Class<?>> proCompileEntities,
List<String> xmlMappingFiles,
Map<String, String> processorOptions,
boolean ignoreCompilationErrors) {
this.originalStatement = originalStatement;
this.testEntities = testEntities;
this.preCompileEntities = proCompileEntities;
this.xmlMappingFiles = xmlMappingFiles;
this.processorOptions = processorOptions;
this.ignoreCompilationErrors = ignoreCompilationErrors;
this.compilationDiagnostics = new ArrayList<Diagnostic<?>>();
}
@Override
public void evaluate() throws Throwable {
try {
// some test needs to compile some classes prior to the actual classes under test
if ( !preCompileEntities.isEmpty() ) {
compile( getCompilationUnits( preCompileEntities ) );
}
// now we compile the actual test classes
compile( getCompilationUnits( testEntities ) );
if ( !ignoreCompilationErrors ) {
TestUtil.assertNoCompilationError( compilationDiagnostics );
}
}
catch ( Exception e ) {
StringWriter errors = new StringWriter();
e.printStackTrace( new PrintWriter( errors ) );
log.debug( errors.toString() );
fail( "Unable to process test sources." );
}
originalStatement.evaluate();
}
private List<File> getCompilationUnits(List<Class<?>> classesToCompile) {
List<File> javaFiles = new ArrayList<File>();
for ( Class<?> testClass : classesToCompile ) {
String pathToSource = getPathToSource( testClass );
javaFiles.add( new File( pathToSource ) );
}
return javaFiles;
}
private String getPathToSource(Class<?> testClass) {
return SOURCE_BASE_DIR + File.separator + testClass.getName()
.replace( PACKAGE_SEPARATOR, File.separator ) + ".java";
}
private void compile(List<File> sourceFiles) throws Exception {
List<String> options = createJavaOptions();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager( diagnostics, null, null );
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(
sourceFiles
);
compileSources( options, compiler, diagnostics, fileManager, compilationUnits );
compilationDiagnostics.addAll( diagnostics.getDiagnostics() );
fileManager.close();
}
private List<String> createJavaOptions() {
List<String> options = new ArrayList<String>();
options.add( "-d" );
options.add( TestUtil.getOutBaseDir().getAbsolutePath() );
// pass orm files if specified
if ( !xmlMappingFiles.isEmpty() ) {
StringBuilder builder = new StringBuilder();
builder.append( ANNOTATION_PROCESSOR_OPTION_PREFIX );
builder.append( JPAMetaModelEntityProcessor.ORM_XML_OPTION );
builder.append( "=" );
for ( String ormFile : xmlMappingFiles ) {
builder.append( ormFile );
builder.append( "," );
}
builder.deleteCharAt( builder.length() - 1 );
options.add( builder.toString() );
}
// add any additional options specified by the test
for ( Map.Entry<String, String> entry : processorOptions.entrySet() ) {
StringBuilder builder = new StringBuilder();
builder.append( ANNOTATION_PROCESSOR_OPTION_PREFIX );
builder.append( entry.getKey() );
builder.append( "=" );
builder.append( entry.getValue() );
options.add( builder.toString() );
}
return options;
}
private void compileSources(List<String> options,
JavaCompiler compiler,
DiagnosticCollector<JavaFileObject> diagnostics,
StandardJavaFileManager fileManager,
Iterable<? extends JavaFileObject> compilationUnits) {
JavaCompiler.CompilationTask task = compiler.getTask(
null, fileManager, diagnostics, options, null, compilationUnits
);
task.call();
for ( Diagnostic<?> diagnostic : diagnostics.getDiagnostics() ) {
log.debug( diagnostic.getMessage( null ) );
}
}
}

View File

@ -16,173 +16,23 @@
*/
package org.hibernate.jpamodelgen.test.util;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeClass;
import org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor;
import static org.testng.FileAssert.fail;
import org.junit.After;
import org.junit.runner.RunWith;
/**
* Base class for annotation processor tests.
*
* @author Hardy Ferentschik
*/
@RunWith(CompilationRunner.class)
public abstract class CompilationTest {
private static final Logger log = LoggerFactory.getLogger( CompilationTest.class );
private static final String ANNOTATION_PROCESSOR_OPTION_PREFIX = "-A";
private static final String SOURCE_BASE_DIR_PROPERTY = "sourceBaseDir";
private static final String OUT_BASE_DIR_PROPERTY = "outBaseDir";
private static final String SOURCE_BASE_DIR;
private static final String OUT_BASE_DIR;
public static final String DIRECTORY_SEPARATOR = File.separator;
private List<Diagnostic<?>> compilationDiagnostics;
static {
String tmp = System.getProperty( SOURCE_BASE_DIR_PROPERTY );
if ( tmp == null ) {
fail( "The system property sourceBaseDir has to be set and point to the base directory of the test java sources." );
}
SOURCE_BASE_DIR = tmp;
tmp = System.getProperty( OUT_BASE_DIR_PROPERTY );
if ( tmp == null ) {
fail( "The system property outBaseDir has to be set and point to the base directory of the test output directory." );
}
OUT_BASE_DIR = tmp;
}
public CompilationTest() {
compilationDiagnostics = new ArrayList<Diagnostic<?>>();
}
public final List<Diagnostic<?>> getCompilationDiagnostics() {
return compilationDiagnostics;
}
public static String getSourceBaseDir() {
return SOURCE_BASE_DIR;
}
@BeforeClass
protected void compileAllTestEntities() throws Exception {
List<File> sourceFiles = getCompilationUnits( SOURCE_BASE_DIR, getPackageNameOfCurrentTest() );
// make sure there are no relics from previous runs
TestUtil.deleteGeneratedSourceFiles( new File( OUT_BASE_DIR ) );
compile( sourceFiles );
}
/**
* Compiles the specified Java classes and generated the meta model java files which in turn get also compiled.
*
* @param sourceFiles the files containing the java source files to compile.
*
* @throws Exception in case the compilation fails
*/
protected void compile(List<File> sourceFiles) throws Exception {
List<String> options = createJavaOptions();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager( diagnostics, null, null );
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(
sourceFiles
);
compileSources( options, compiler, diagnostics, fileManager, compilationUnits );
compilationDiagnostics.addAll( diagnostics.getDiagnostics() );
fileManager.close();
}
protected List<File> getCompilationUnits(String baseDir, String packageName) {
List<File> javaFiles = new ArrayList<File>();
String packageDirName = baseDir;
if ( packageName != null ) {
packageDirName = packageDirName + DIRECTORY_SEPARATOR + packageName.replace( ".", DIRECTORY_SEPARATOR );
}
File packageDir = new File( packageDirName );
FilenameFilter javaFileFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith( ".java" ) && !name.endsWith( "Test.java" );
}
};
final File[] files = packageDir.listFiles( javaFileFilter );
if ( files == null ) {
throw new RuntimeException( "Cannot find package directory (is your base dir correct?): " + packageDirName );
}
javaFiles.addAll( Arrays.asList( files ) );
return javaFiles;
}
protected abstract String getPackageNameOfCurrentTest();
protected Map<String, String> getProcessorOptions() {
return Collections.emptyMap();
}
protected Collection<String> getOrmFiles() {
return Collections.emptyList();
}
private void compileSources(List<String> options, JavaCompiler compiler, DiagnosticCollector<JavaFileObject> diagnostics, StandardJavaFileManager fileManager, Iterable<? extends JavaFileObject> compilationUnits) {
JavaCompiler.CompilationTask task = compiler.getTask(
null, fileManager, diagnostics, options, null, compilationUnits
);
task.call();
for ( Diagnostic<?> diagnostic : diagnostics.getDiagnostics() ) {
log.debug( diagnostic.getMessage( null ) );
}
}
private List<String> createJavaOptions() {
List<String> options = new ArrayList<String>();
options.add( "-d" );
options.add( OUT_BASE_DIR );
// pass orm files if specified
if ( !getOrmFiles().isEmpty() ) {
StringBuilder builder = new StringBuilder();
builder.append( ANNOTATION_PROCESSOR_OPTION_PREFIX );
builder.append( JPAMetaModelEntityProcessor.ORM_XML_OPTION );
builder.append( "=" );
for ( String ormFile : getOrmFiles() ) {
builder.append( ormFile );
builder.append( "," );
}
builder.deleteCharAt( builder.length() - 1 );
options.add( builder.toString() );
}
// add any additional options specified by the test
for ( Map.Entry<String, String> entry : getProcessorOptions().entrySet() ) {
StringBuilder builder = new StringBuilder();
builder.append( ANNOTATION_PROCESSOR_OPTION_PREFIX );
builder.append( entry.getKey() );
builder.append( "=" );
builder.append( entry.getValue() );
options.add( builder.toString() );
}
return options;
@After
public void cleanup() throws Exception {
TestUtil.deleteProcessorGeneratedFiles();
}
}

View File

@ -0,0 +1,32 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpamodelgen.test.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to indicate that for this test it is ok to get compilation errors via {@link javax.tools.Diagnostic}.
*
* @author Hardy Ferentschik
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface IgnoreCompilationErrors {
}

View File

@ -25,18 +25,19 @@ import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import javax.tools.Diagnostic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.FileAssert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Hardy Ferentschik
@ -46,48 +47,93 @@ public class TestUtil {
private static final String PATH_SEPARATOR = System.getProperty( "file.separator" );
private static final String PACKAGE_SEPARATOR = ".";
private static final String META_MODEL_CLASS_POSTFIX = "_";
private static final String OUT_BASE_DIR;
private static final File OUT_BASE_DIR;
static {
String tmp = System.getProperty( "outBaseDir" );
if ( tmp == null ) {
fail( "The system property outBaseDir has to be set and point to the base directory of the test output directory." );
File targetDir = getTargetDir();
OUT_BASE_DIR = new File( targetDir, "processor-generated-test-classes" );
if ( !OUT_BASE_DIR.exists() ) {
if ( !OUT_BASE_DIR.mkdirs() ) {
fail( "Unable to create test output directory " + OUT_BASE_DIR.toString() );
}
}
OUT_BASE_DIR = tmp;
}
private TestUtil() {
}
public static void deleteGeneratedSourceFiles(File path) {
if ( path.exists() ) {
File[] files = path.listFiles( new MetaModelFilenameFilter() );
for ( File file : files ) {
if ( file.isDirectory() ) {
deleteGeneratedSourceFiles( file );
}
else {
boolean success = file.delete();
if ( success ) {
log.debug( file.getAbsolutePath() + " deleted successfully" );
}
else {
log.debug( "Failed to delete generated source file" + file.getAbsolutePath() );
}
}
}
}
public static void assertNoSourceFileGeneratedFor(Class<?> clazz) {
assertNotNull( "Class parameter cannot be null", clazz );
File sourceFile = getMetaModelSourceFileFor( clazz );
assertFalse( "There should be no source file: " + sourceFile.getName(), sourceFile.exists() );
}
public static Class<?> getMetamodelClassFor(Class<?> entityClass) {
String entityModelClassName = entityClass.getName() + META_MODEL_CLASS_POSTFIX;
public static void assertAbsenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName) {
assertAbsenceOfFieldInMetamodelFor(
clazz,
fieldName,
"'" + fieldName + "' should not appear in metamodel class"
);
}
try {
return Class.forName( entityModelClassName );
public static void assertAbsenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName, String errorString) {
assertFalse( buildErrorString( errorString, clazz ), hasFieldInMetamodelFor( clazz, fieldName ) );
}
public static void assertPresenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName) {
assertPresenceOfFieldInMetamodelFor(
clazz,
fieldName,
"'" + fieldName + "' should appear in metamodel class"
);
}
public static void assertPresenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName, String errorString) {
assertTrue( buildErrorString( errorString, clazz ), hasFieldInMetamodelFor( clazz, fieldName ) );
}
public static void assertAttributeTypeInMetaModelFor(Class<?> clazz, String fieldName, Class<?> expectedType, String errorString) {
Field field = getFieldFromMetamodelFor( clazz, fieldName );
assertNotNull( "Cannot find field '" + fieldName + "' in " + clazz.getName(), field );
ParameterizedType type = (ParameterizedType) field.getGenericType();
Type actualType = type.getActualTypeArguments()[1];
if ( expectedType.isArray() ) {
expectedType = expectedType.getComponentType();
actualType = getComponentType( actualType );
}
catch ( ClassNotFoundException e ) {
fail( "Unable to load class " + entityModelClassName );
return null;
assertEquals(
"Types do not match: " + buildErrorString( errorString, clazz ),
expectedType,
actualType
);
}
public static void assertMapAttributesInMetaModelFor(Class<?> clazz, String fieldName, Class<?> expectedMapKey, Class<?> expectedMapValue, String errorString) {
Field field = getFieldFromMetamodelFor( clazz, fieldName );
assertNotNull( field );
ParameterizedType type = (ParameterizedType) field.getGenericType();
Type actualMapKeyType = type.getActualTypeArguments()[1];
assertEquals( buildErrorString( errorString, clazz ), expectedMapKey, actualMapKeyType );
Type actualMapKeyValue = type.getActualTypeArguments()[2];
assertEquals( buildErrorString( errorString, clazz ), expectedMapValue, actualMapKeyValue );
}
public static void assertSuperClassRelationShipInMetamodel(Class<?> entityClass, Class<?> superEntityClass) {
Class<?> clazz = getMetamodelClassFor( entityClass );
Class<?> superClazz = getMetamodelClassFor( superEntityClass );
assertEquals(
"Entity " + superClazz.getName() + " should be the superclass of " + clazz.getName(),
superClazz.getName(),
clazz.getSuperclass().getName()
);
}
public static void assertNoCompilationError(List<Diagnostic<?>> diagnostics) {
for ( Diagnostic<?> diagnostic : diagnostics ) {
if ( diagnostic.getKind().equals( Diagnostic.Kind.ERROR ) ) {
fail( "There was a compilation error during annotation processing:\n" + diagnostic.getMessage( null ) );
}
}
}
@ -97,14 +143,47 @@ public class TestUtil {
* @param clazz the class for which a metamodel class should have been generated.
*/
public static void assertMetamodelClassGeneratedFor(Class<?> clazz) {
assertNotNull( clazz, "Class parameter cannot be null" );
String metaModelClassName = clazz.getName() + META_MODEL_CLASS_POSTFIX;
try {
assertNotNull( Class.forName( metaModelClassName ) );
assertNotNull( getMetamodelClassFor( clazz ) );
}
/**
* Deletes recursively all files found in the output directory for the annotation processor.
*/
public static void deleteProcessorGeneratedFiles() {
for ( File file : OUT_BASE_DIR.listFiles() ) {
deleteFilesRecursive( file );
}
catch ( ClassNotFoundException e ) {
}
/**
* @return the output directory for the generated source and class files.
*/
public static File getOutBaseDir() {
return OUT_BASE_DIR;
}
/**
* Returns the static metamodel class for the specified entity.
*
* @param entityClass the entity for which to retrieve the metamodel class. Cannot be {@code null}.
*
* @return the static metamodel class for the specified entity.
*/
public static Class<?> getMetamodelClassFor(Class<?> entityClass) {
assertNotNull( "Class parameter cannot be null", entityClass );
String metaModelClassName = entityClass.getName() + META_MODEL_CLASS_POSTFIX;
try {
URL outDirUrl = OUT_BASE_DIR.toURI().toURL();
URL urls[] = new URL[1];
urls[0] = outDirUrl;
URLClassLoader classLoader = new URLClassLoader( urls, TestUtil.class.getClassLoader() );
return classLoader.loadClass( metaModelClassName );
}
catch ( Exception e ) {
fail( metaModelClassName + " was not generated." );
}
// keep the compiler happy
return null;
}
public static File getMetaModelSourceFileFor(Class<?> clazz) {
@ -122,7 +201,7 @@ public class TestUtil {
try {
BufferedReader input = new BufferedReader( new FileReader( sourceFile ) );
try {
String line = null;
String line;
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
@ -150,81 +229,6 @@ public class TestUtil {
log.info( getMetaModelSourceAsString( clazz ) );
}
public static void assertNoSourceFileGeneratedFor(Class<?> clazz) {
assertNotNull( clazz, "Class parameter cannot be null" );
File sourceFile = getMetaModelSourceFileFor( clazz );
assertFalse( sourceFile.exists(), "There should be no source file: " + sourceFile.getName() );
}
public static void assertAbsenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName) {
assertAbsenceOfFieldInMetamodelFor(
clazz,
fieldName,
"'" + fieldName + "' should not appear in metamodel class"
);
}
public static void assertAbsenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName, String errorString) {
assertFalse( hasFieldInMetamodelFor( clazz, fieldName ), buildErrorString( errorString, clazz ) );
}
public static void assertPresenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName) {
assertPresenceOfFieldInMetamodelFor(
clazz,
fieldName,
"'" + fieldName + "' should appear in metamodel class"
);
}
public static void assertPresenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName, String errorString) {
assertTrue( hasFieldInMetamodelFor( clazz, fieldName ), buildErrorString( errorString, clazz ) );
}
public static void assertAttributeTypeInMetaModelFor(Class<?> clazz, String fieldName, Class<?> expectedType, String errorString) {
Field field = getFieldFromMetamodelFor( clazz, fieldName );
assertNotNull( field, "Cannot find field '" + fieldName + "' in " + clazz.getName() );
ParameterizedType type = (ParameterizedType) field.getGenericType();
Type actualType = type.getActualTypeArguments()[1];
if ( expectedType.isArray() ) {
expectedType = expectedType.getComponentType();
actualType = getComponentType( actualType );
}
assertEquals(
actualType,
expectedType,
"Types do not match: " + buildErrorString( errorString, clazz )
);
}
public static void assertMapAttributesInMetaModelFor(Class<?> clazz, String fieldName, Class<?> expectedMapKey, Class<?> expectedMapValue, String errorString) {
Field field = getFieldFromMetamodelFor( clazz, fieldName );
assertNotNull( field );
ParameterizedType type = (ParameterizedType) field.getGenericType();
Type actualMapKeyType = type.getActualTypeArguments()[1];
assertEquals( actualMapKeyType, expectedMapKey, buildErrorString( errorString, clazz ) );
Type actualMapKeyValue = type.getActualTypeArguments()[2];
assertEquals( actualMapKeyValue, expectedMapValue, buildErrorString( errorString, clazz ) );
}
public static void assertSuperClassRelationShipInMetamodel(Class<?> entityClass, Class<?> superEntityClass) {
String entityModelClassName = entityClass.getName() + META_MODEL_CLASS_POSTFIX;
String superEntityModelClassName = superEntityClass.getName() + META_MODEL_CLASS_POSTFIX;
Class<?> clazz;
Class<?> superClazz;
try {
clazz = Class.forName( entityModelClassName );
superClazz = Class.forName( superEntityModelClassName );
Assert.assertEquals(
clazz.getSuperclass(), superClazz,
"Entity " + superEntityModelClassName + " should be the superclass of " + entityModelClassName
);
}
catch ( ClassNotFoundException e ) {
fail( "Unable to load metamodel class: " + e.getMessage() );
}
}
public static Field getFieldFromMetamodelFor(Class<?> entityClass, String fieldName) {
Class<?> metaModelClass = getMetamodelClassFor( entityClass );
Field field;
@ -241,14 +245,6 @@ public class TestUtil {
return fcn.replace( PACKAGE_SEPARATOR, PATH_SEPARATOR );
}
public static void assertNoCompilationError(List<Diagnostic<?>> diagnostics) {
for ( Diagnostic<?> diagnostic : diagnostics ) {
if ( diagnostic.getKind().equals( Diagnostic.Kind.ERROR ) ) {
fail( "There was a compilation error. " + diagnostic.getMessage( null ) );
}
}
}
private static boolean hasFieldInMetamodelFor(Class<?> clazz, String fieldName) {
return getFieldFromMetamodelFor( clazz, fieldName ) != null;
}
@ -256,7 +252,7 @@ public class TestUtil {
private static String buildErrorString(String baseError, Class<?> clazz) {
StringBuilder builder = new StringBuilder();
builder.append( baseError );
builder.append( "\n" );
builder.append( ".\n\n" );
builder.append( "Source code for " );
builder.append( clazz.getName() );
builder.append( "_.java:" );
@ -297,6 +293,38 @@ public class TestUtil {
}
}
}
private static void deleteFilesRecursive(File file) {
if ( file.isDirectory() ) {
for ( File c : file.listFiles() ) {
deleteFilesRecursive( c );
}
}
if ( !file.delete() ) {
fail( "Unable to delete file: " + file );
}
}
/**
* Returns the target directory of the build.
*
* @return the target directory of the build
*/
public static File getTargetDir() {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
// get a URL reference to something we now is part of the classpath (our own classes)
String currentTestClass = TestUtil.class.getName();
int hopsToCompileDirectory = currentTestClass.split( "\\." ).length;
int hopsToTargetDirectory = hopsToCompileDirectory + 2;
URL classURL = contextClassLoader.getResource( currentTestClass.replace( '.', '/' ) + ".class" );
// navigate back to '/target'
File targetDir = new File( classURL.getFile() );
// navigate back to '/target'
for ( int i = 0; i < hopsToTargetDirectory; i++ ) {
targetDir = targetDir.getParentFile();
}
return targetDir;
}
}

View File

@ -0,0 +1,38 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpamodelgen.test.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation allowing to specify which classes should be passed to the annotation processor for compilation.
*
* @author Hardy Ferentschik
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface WithClasses {
Class<?>[] value();
/**
* @return an array of classes which should be complied prior to compiling the actual test classes
*/
Class<?>[] preCompile() default { };
}

View File

@ -0,0 +1,31 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpamodelgen.test.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Hardy Ferentschik
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface WithMappingFiles {
String[] value();
}

View File

@ -0,0 +1,48 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.jpamodelgen.test.util;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* @author Hardy Ferentschik
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface WithProcessorOption {
String key();
String value();
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@interface List {
WithProcessorOption[] value();
}
}

View File

@ -16,20 +16,16 @@
*/
package org.hibernate.jpamodelgen.test.xmlembeddable;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.IgnoreCompilationErrors;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithMappingFiles;
import org.hibernate.jpamodelgen.test.xmlembeddable.foo.BusinessId;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.getMetaModelSourceAsString;
import static org.testng.Assert.assertTrue;
import static org.junit.Assert.assertTrue;
/**
* @author Hardy Ferentschik
@ -37,37 +33,13 @@ import static org.testng.Assert.assertTrue;
public class EmbeddableConfiguredInXmlTest extends CompilationTest {
@Test
@TestForIssue(jiraKey = "METAGEN-66")
@WithClasses(value = { Foo.class, BusinessEntity.class }, preCompile = BusinessId.class)
@WithMappingFiles("orm.xml")
@IgnoreCompilationErrors
public void testAttributeForEmbeddableConfiguredInXmlExists() {
// need to work with the source file. BusinessEntity_.class won't get generated, because the business id won't
// be on the classpath
String entityMetaModel = getMetaModelSourceAsString( BusinessEntity.class );
assertTrue( entityMetaModel.contains( "SingularAttribute<BusinessEntity, BusinessId<T>> businessId" ) );
}
@Override
@BeforeClass
// override compileAllTestEntities to compile the the business id explicitly
protected void compileAllTestEntities() throws Exception {
String fooPackageName = getPackageNameOfCurrentTest() + ".foo";
List<File> sourceFiles = getCompilationUnits(
CompilationTest.getSourceBaseDir(), fooPackageName
);
compile( sourceFiles );
sourceFiles = getCompilationUnits( getSourceBaseDir(), getPackageNameOfCurrentTest() );
compile( sourceFiles );
}
@Override
protected String getPackageNameOfCurrentTest() {
return EmbeddableConfiguredInXmlTest.class.getPackage().getName();
}
@Override
protected Collection<String> getOrmFiles() {
List<String> ormFiles = new ArrayList<String>();
String packageName = TestUtil.fcnToPath( EmbeddableConfiguredInXmlTest.class.getPackage().getName() );
ormFiles.add( packageName + "/orm.xml" );
return ormFiles;
}
}

View File

@ -16,42 +16,23 @@
*/
package org.hibernate.jpamodelgen.test.xmlmapped;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithMappingFiles;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
/**
* @author Hardy Ferentschik
*/
public class
IgnoreInvalidXmlTest extends CompilationTest {
public class IgnoreInvalidXmlTest extends CompilationTest {
@Test
@WithClasses(Superhero.class)
@WithMappingFiles({ "orm.xml", "jpa1-orm.xml", "malformed-mapping.xml", "non-existend-class.xml" })
public void testInvalidXmlFilesGetIgnored() {
// this is only a indirect test, but if the invalid xml files would cause the processor to abort the
// meta class would not have been generated
assertMetamodelClassGeneratedFor( Superhero.class );
}
@Override
protected String getPackageNameOfCurrentTest() {
return IgnoreInvalidXmlTest.class.getPackage().getName();
}
@Override
protected Collection<String> getOrmFiles() {
List<String> ormFiles = new ArrayList<String>();
String packageName = TestUtil.fcnToPath( IgnoreInvalidXmlTest.class.getPackage().getName() );
ormFiles.add( packageName + "/orm.xml" );
ormFiles.add( packageName + "/jpa1-orm.xml" );
ormFiles.add( packageName + "/malformed-mapping.xml" );
ormFiles.add( packageName + "/non-existend-class.xml" );
return ormFiles;
}
}

View File

@ -16,15 +16,12 @@
*/
package org.hibernate.jpamodelgen.test.xmlmapped;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithProcessorOption;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAttributeTypeInMetaModelFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@ -34,6 +31,18 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertSuperClassRelat
/**
* @author Hardy Ferentschik
*/
// TODO - differentiate needed classes per test better. Right now all test classes are processed for each test (HF)
@WithClasses({
Address.class,
Boy.class,
Building.class,
FakeHero.class,
LivingBeing.class,
Mammal.class,
Superhero.class
})
@WithProcessorOption(key = JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION,
value = "org/hibernate/jpamodelgen/test/xmlmapped/persistence.xml")
public class XmlMappingTest extends CompilationTest {
@Test
public void testXmlConfiguredEmbeddedClassGenerated() {
@ -90,23 +99,8 @@ public class XmlMappingTest extends CompilationTest {
assertSuperClassRelationShipInMetamodel( Mammal.class, LivingBeing.class );
}
@Test(expectedExceptions = ClassNotFoundException.class)
@Test(expected = ClassNotFoundException.class)
public void testNonExistentMappedClassesGetIgnored() throws Exception {
Class.forName( "org.hibernate.jpamodelgen.test.model.Dummy_" );
}
@Override
protected String getPackageNameOfCurrentTest() {
return XmlMappingTest.class.getPackage().getName();
}
@Override
protected Map<String, String> getProcessorOptions() {
Map<String, String> properties = new HashMap<String, String>();
properties.put(
JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION,
TestUtil.fcnToPath( XmlMappingTest.class.getPackage().getName() ) + "/persistence.xml"
);
return properties;
}
}

View File

@ -16,45 +16,29 @@
*/
package org.hibernate.jpamodelgen.test.xmlmetacomplete.multiplepus;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestForIssue;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithProcessorOption;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
/**
* @author Hardy Ferentschik
*/
@TestForIssue( jiraKey = "METAGEN-86" )
@TestForIssue(jiraKey = "METAGEN-86")
public class XmlMetaDataCompleteMultiplePersistenceUnitsTest extends CompilationTest {
@Test
@WithClasses(Dummy.class)
@WithProcessorOption(key = JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION,
value = "org/hibernate/jpamodelgen/test/xmlmetacomplete/multiplepus/persistence.xml")
public void testMetaModelGenerated() {
// only one of the xml files in the example uses 'xml-mapping-metadata-complete', hence annotation processing
// kicks in
assertMetamodelClassGeneratedFor( Dummy.class );
}
@Override
protected String getPackageNameOfCurrentTest() {
return XmlMetaDataCompleteMultiplePersistenceUnitsTest.class.getPackage().getName();
}
@Override
protected Map<String, String> getProcessorOptions() {
Map<String, String> properties = new HashMap<String, String>();
properties.put(
JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION,
TestUtil.fcnToPath(
XmlMetaDataCompleteMultiplePersistenceUnitsTest.class.getPackage().getName()
) + "/persistence.xml"
);
return properties;
}
}

View File

@ -19,11 +19,10 @@ package org.hibernate.jpamodelgen.test.xmlmetacomplete.singlepu;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertNoSourceFileGeneratedFor;
@ -38,18 +37,13 @@ public class XmlMetaDataCompleteSinglePersistenceUnitTest extends CompilationTes
assertNoSourceFileGeneratedFor( Dummy.class );
}
@Override
protected String getPackageNameOfCurrentTest() {
return XmlMetaDataCompleteSinglePersistenceUnitTest.class.getPackage().getName();
}
@Override
protected Map<String, String> getProcessorOptions() {
Map<String, String> properties = new HashMap<String, String>();
properties.put(
JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION,
TestUtil.fcnToPath( XmlMetaDataCompleteSinglePersistenceUnitTest.class.getPackage().getName() ) + "/persistence.xml"
);
return properties;
}
// @Override
// protected Map<String, String> getProcessorOptions() {
// Map<String, String> properties = new HashMap<String, String>();
// properties.put(
// JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION,
// TestUtil.fcnToPath( XmlMetaDataCompleteSinglePersistenceUnitTest.class.getPackage().getName() ) + "/persistence.xml"
// );
// return properties;
// }
}

View File

@ -16,14 +16,11 @@
*/
package org.hibernate.jpamodelgen.test.xmlonly;
import java.util.HashMap;
import java.util.Map;
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
import org.hibernate.jpamodelgen.test.util.TestUtil;
import org.hibernate.jpamodelgen.test.util.WithClasses;
import org.hibernate.jpamodelgen.test.util.WithProcessorOption;
import org.junit.Test;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfFieldInMetamodelFor;
@ -31,6 +28,9 @@ import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfField
/**
* @author Hardy Ferentschik
*/
@WithClasses({ Car.class, Course.class, Option.class, Period.class, Teacher.class, Tire.class, XmlOnly.class })
@WithProcessorOption(key = JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION,
value = "org/hibernate/jpamodelgen/test/xmlonly/persistence.xml")
public class XmlOnlyTest extends CompilationTest {
@Test
public void testMetaModelGeneratedForXmlConfiguredEntity() {
@ -55,19 +55,4 @@ public class XmlOnlyTest extends CompilationTest {
assertPresenceOfFieldInMetamodelFor( Period.class, "start", "Embedded expected" );
assertPresenceOfFieldInMetamodelFor( Period.class, "end", "Embedded expected" );
}
@Override
protected String getPackageNameOfCurrentTest() {
return XmlOnlyTest.class.getPackage().getName();
}
@Override
protected Map<String, String> getProcessorOptions() {
Map<String, String> properties = new HashMap<String, String>();
properties.put(
JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION,
TestUtil.fcnToPath( XmlOnlyTest.class.getPackage().getName() ) + "/persistence.xml"
);
return properties;
}
}