Merged HEAD-QA to HEAD (4.2) (including moving test classes into separate folders)

51903 to 54309 


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@54310 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Samuel Langlois
2013-08-20 17:17:31 +00:00
parent 0a36e2af67
commit ab4ca7177f
1576 changed files with 36419 additions and 8603 deletions

View File

@@ -1,439 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.columns;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.fk;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.fkeys;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.indexes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.alfresco.util.schemacomp.model.Column;
import org.alfresco.util.schemacomp.model.ForeignKey;
import org.alfresco.util.schemacomp.model.Index;
import org.alfresco.util.schemacomp.model.PrimaryKey;
import org.alfresco.util.schemacomp.model.Schema;
import org.alfresco.util.schemacomp.model.Sequence;
import org.alfresco.util.schemacomp.model.Table;
import org.alfresco.util.schemacomp.validator.DbValidator;
import org.alfresco.util.schemacomp.validator.NameValidator;
import org.junit.Before;
import org.junit.Test;
import com.sun.star.uno.RuntimeException;
/**
* Tests for the {@link DbObjectXMLTransformer} class.
*
* @author Matt Ward
*/
public class DbObjectXMLTransformerTest
{
private DbObjectXMLTransformer transformer;
private TransformerHandler xmlOut;
private Writer writer;
private boolean outputDumpEnabled = true;
@Before
public void setUp()
{
final SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance();
try
{
xmlOut = stf.newTransformerHandler();
}
catch (TransformerConfigurationException error)
{
throw new RuntimeException("Unable to create TransformerHandler.", error);
}
final Transformer t = xmlOut.getTransformer();
try
{
t.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");
}
catch (final IllegalArgumentException e)
{
// It was worth a try
}
t.setOutputProperty(OutputKeys.INDENT, "yes");
writer = new StringWriter();
xmlOut.setResult(new StreamResult(writer));
transformer = new DbObjectXMLTransformer(xmlOut);
}
@Test
public void transformColumn() throws IOException
{
Column column = new Column(null, "last_name", "VARCHAR2(100)", true);
column.setAutoIncrement(true);
column.setOrder(2);
transformer.output(column);
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
dumpOutput();
assertHasPreamble(reader);
assertEquals("<column name=\"last_name\" order=\"2\">", reader.readLine());
assertEquals(" <type>VARCHAR2(100)</type>", reader.readLine());
assertEquals(" <nullable>true</nullable>", reader.readLine());
assertEquals(" <autoincrement>true</autoincrement>", reader.readLine());
assertEquals("</column>", reader.readLine());
}
@Test
public void transformForeignKey() throws IOException
{
ForeignKey fk = new ForeignKey(null, "fk_for_some_table",
"local_column", "target_table", "target_column");
transformer.output(fk);
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
dumpOutput();
assertHasPreamble(reader);
assertEquals("<foreignkey name=\"fk_for_some_table\">", reader.readLine());
assertEquals(" <localcolumn>local_column</localcolumn>", reader.readLine());
assertEquals(" <targettable>target_table</targettable>", reader.readLine());
assertEquals(" <targetcolumn>target_column</targetcolumn>", reader.readLine());
assertEquals("</foreignkey>", reader.readLine());
}
@Test
public void transformIndex() throws IOException
{
Index index = new Index(null, "index_name", Arrays.asList("first", "second"));
transformer.output(index);
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
dumpOutput();
assertHasPreamble(reader);
assertEquals("<index name=\"index_name\" unique=\"false\">", reader.readLine());
assertEquals(" <columnnames>", reader.readLine());
assertEquals(" <columnname>first</columnname>", reader.readLine());
assertEquals(" <columnname>second</columnname>", reader.readLine());
assertEquals(" </columnnames>", reader.readLine());
assertEquals("</index>", reader.readLine());
}
@Test
public void transformPrimaryKey() throws IOException
{
PrimaryKey pk = new PrimaryKey(
null,
"pk_name",
Arrays.asList("a_column", "b_column"),
Arrays.asList(2, 1));
transformer.output(pk);
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
dumpOutput();
assertHasPreamble(reader);
assertEquals("<primarykey name=\"pk_name\">", reader.readLine());
assertEquals(" <columnnames>", reader.readLine());
assertEquals(" <columnname order=\"2\">a_column</columnname>", reader.readLine());
assertEquals(" <columnname order=\"1\">b_column</columnname>", reader.readLine());
assertEquals(" </columnnames>", reader.readLine());
assertEquals("</primarykey>", reader.readLine());
}
@Test
public void transformSchemaNoColumnOrderCheck() throws IOException
{
Collection<Column> columns = columns("one VARCHAR2(100)", "two NUMBER(10)");
PrimaryKey pk = new PrimaryKey(null, "pk_for_my_table", Arrays.asList("id"), Arrays.asList(1));
Collection<ForeignKey> fks = fkeys(fk("fk_one", "lc", "tt", "tc"), fk("fk_two", "lc", "tt", "tc"));
Collection<Index> indexes = indexes("index_one col1 col2", "index_two col3 col4");
Table tableOne = new Table(null, "table_one", columns, pk, fks, indexes);
Table tableTwo = new Table(null, "table_two", columns, pk, fks, indexes);
Schema schema = new Schema("my_schema", "alf_", 132, false);
schema.add(tableOne);
schema.add(tableTwo);
schema.add(new Sequence(null, "sequence_one"));
schema.add(new Sequence(null, "sequence_two"));
schema.add(new Sequence(null, "sequence_three"));
schema.setValidators(new ArrayList<DbValidator>());
transformer.output(schema);
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
dumpOutput();
assertHasPreamble(reader);
assertEquals("<schema " +
"xmlns=\"http://www.alfresco.org/repo/db-schema\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"http://www.alfresco.org/repo/db-schema db-schema.xsd\" " +
"name=\"my_schema\" dbprefix=\"alf_\" version=\"132\" tablecolumnorder=\"false\">", reader.readLine());
assertEquals(" <objects>", reader.readLine());
skipUntilEnd(" {table}", reader);
skipUntilEnd(" {table}", reader);
skipUntilEnd(" {sequence}", reader, true);
skipUntilEnd(" {sequence}", reader, true);
skipUntilEnd(" {sequence}", reader, true);
assertEquals(" </objects>", reader.readLine());
assertEquals("</schema>", reader.readLine());
}
@Test
public void transformSchemaWithColumnOrderCheck() throws IOException
{
Collection<Column> columns = columns("one VARCHAR2(100)", "two NUMBER(10)");
PrimaryKey pk = new PrimaryKey(null, "pk_for_my_table", Arrays.asList("id"), Arrays.asList(1));
Collection<ForeignKey> fks = fkeys(fk("fk_one", "lc", "tt", "tc"), fk("fk_two", "lc", "tt", "tc"));
Collection<Index> indexes = indexes("index_one col1 col2", "index_two col3 col4");
Table tableOne = new Table(null, "table_one", columns, pk, fks, indexes);
Table tableTwo = new Table(null, "table_two", columns, pk, fks, indexes);
Schema schema = new Schema("my_schema", "alf_", 132, true);
schema.add(tableOne);
schema.add(tableTwo);
schema.add(new Sequence(null, "sequence_one"));
schema.add(new Sequence(null, "sequence_two"));
schema.add(new Sequence(null, "sequence_three"));
schema.setValidators(new ArrayList<DbValidator>());
transformer.output(schema);
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
dumpOutput();
assertHasPreamble(reader);
assertEquals("<schema " +
"xmlns=\"http://www.alfresco.org/repo/db-schema\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"http://www.alfresco.org/repo/db-schema db-schema.xsd\" " +
"name=\"my_schema\" dbprefix=\"alf_\" version=\"132\" tablecolumnorder=\"true\">", reader.readLine());
assertEquals(" <objects>", reader.readLine());
skipUntilEnd(" {table}", reader);
skipUntilEnd(" {table}", reader);
skipUntilEnd(" {sequence}", reader, true);
skipUntilEnd(" {sequence}", reader, true);
skipUntilEnd(" {sequence}", reader, true);
assertEquals(" </objects>", reader.readLine());
assertEquals("</schema>", reader.readLine());
}
@Test
public void transformSequence() throws IOException
{
Sequence sequence = new Sequence(null, "my_sequence");
transformer.output(sequence);
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
dumpOutput();
assertHasPreamble(reader);
assertEquals("<sequence name=\"my_sequence\"/>", reader.readLine());
}
@Test
public void transformTable() throws IOException
{
Collection<Column> columns = columns("one VARCHAR2(100)", "two NUMBER(10)");
PrimaryKey pk = new PrimaryKey(null, "pk_for_my_table", Arrays.asList("id"), Arrays.asList(1));
Collection<ForeignKey> fks = fkeys(fk("fk_one", "lc", "tt", "tc"), fk("fk_two", "lc", "tt", "tc"));
Collection<Index> indexes = indexes("index_one col1 col2", "index_two col3 col4");
Table table = new Table(null, "my_table", columns, pk, fks, indexes);
transformer.output(table);
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
dumpOutput();
assertHasPreamble(reader);
assertEquals("<table name=\"my_table\">", reader.readLine());
assertEquals(" <columns>", reader.readLine());
skipUntilEnd(" {column}", reader);
skipUntilEnd(" {column}", reader);
assertEquals(" </columns>", reader.readLine());
skipUntilEnd(" {primarykey}", reader);
assertEquals(" <foreignkeys>", reader.readLine());
skipUntilEnd(" {foreignkey}", reader);
skipUntilEnd(" {foreignkey}", reader);
assertEquals(" </foreignkeys>", reader.readLine());
assertEquals(" <indexes>", reader.readLine());
skipUntilEnd(" {index}", reader);
skipUntilEnd(" {index}", reader);
assertEquals(" </indexes>", reader.readLine());
assertEquals("</table>", reader.readLine());
}
/**
* ALF-13979: empty table causes NPE during schema export.
* @throws IOException
*/
@Test
public void transformTableWithoutPrimaryKey() throws IOException
{
Table table = new Table("my_table");
assertFalse(table.hasPrimaryKey());
transformer.output(table);
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
dumpOutput();
assertHasPreamble(reader);
skipUntilEnd(" {columns}", reader, true);
skipUntilEnd(" {foreignkeys}", reader, true);
skipUntilEnd(" {indexes}", reader, true);
assertEquals("</table>", reader.readLine());
}
@Test
public void transformObjectWithValidators() throws IOException
{
Collection<Column> columns = columns("one VARCHAR2(100)", "two NUMBER(10)");
PrimaryKey pk = new PrimaryKey(null, "pk_for_my_table", Arrays.asList("id"), Arrays.asList(1));
Collection<ForeignKey> fks = fkeys(fk("fk_one", "lc", "tt", "tc"), fk("fk_two", "lc", "tt", "tc"));
Collection<Index> indexes = indexes("index_one col1 col2", "index_two col3 col4");
Table table = new Table(null, "my_table", columns, pk, fks, indexes);
NameValidator nameValidator = new NameValidator();
nameValidator.setPattern(Pattern.compile("match_me_if_you_can"));
List<DbValidator> validators = new ArrayList<DbValidator>();
validators.add(nameValidator);
table.setValidators(validators);
transformer.output(table);
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
dumpOutput();
assertHasPreamble(reader);
assertEquals("<table name=\"my_table\">", reader.readLine());
assertEquals(" <validators>", reader.readLine());
assertEquals(" <validator class=\"org.alfresco.util.schemacomp.validator.NameValidator\">", reader.readLine());
assertEquals(" <properties>", reader.readLine());
assertEquals(" <property name=\"pattern\">match_me_if_you_can</property>", reader.readLine());
assertEquals(" </properties>", reader.readLine());
assertEquals(" </validator>", reader.readLine());
assertEquals(" </validators>", reader.readLine());
assertEquals(" <columns>", reader.readLine());
skipUntilEnd(" {column}", reader);
skipUntilEnd(" {column}", reader);
assertEquals(" </columns>", reader.readLine());
skipUntilEnd(" {primarykey}", reader);
assertEquals(" <foreignkeys>", reader.readLine());
skipUntilEnd(" {foreignkey}", reader);
skipUntilEnd(" {foreignkey}", reader);
assertEquals(" </foreignkeys>", reader.readLine());
assertEquals(" <indexes>", reader.readLine());
skipUntilEnd(" {index}", reader);
skipUntilEnd(" {index}", reader);
assertEquals(" </indexes>", reader.readLine());
assertEquals("</table>", reader.readLine());
}
/**
* Ignore lines that are tested elsewhere, e.g. ignore serialized Column objects
* in the context of a Table since we only need to know that there was text for a
* Column object in the right place - the actual Column text being tested in its own test.
* <p>
* Leading and trailing spaces are ignored in the comparison.
*
* @param textToFind
* @param reader
*/
private void skipUntilEnd(String textToFind, BufferedReader reader, boolean emptyTag)
{
// To aid test code clarity, and distinguish between text we're actually
// testing for and text that needs to be ignored...
// {mytag} becomes </mytag>
// or if an empty tag is expected
// {mytag} becomes <mytag .../>
if (emptyTag)
{
textToFind = textToFind.trim().
replace("{", "<").
replace("}", ".*/>");
}
else
{
textToFind = textToFind.trim().
replace("{", "</").
replace("}", ">");
}
try
{
String line;
while ((line = reader.readLine()) != null)
{
if (line.trim().matches(textToFind))
{
return;
}
}
fail("Unable to find text: " + textToFind);
}
catch (IOException error)
{
throw new RuntimeException("Unable to skip text whilst looking for: " + textToFind, error);
}
}
private void skipUntilEnd(String textToFind, BufferedReader reader)
{
skipUntilEnd(textToFind, reader, false);
}
private void assertHasPreamble(BufferedReader reader) throws IOException
{
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", reader.readLine());
}
private void dumpOutput()
{
if (outputDumpEnabled)
{
System.out.println(writer.toString());
}
}
}

View File

@@ -1,115 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.alfresco.util.schemacomp.model.AbstractDbObject;
import org.alfresco.util.schemacomp.model.DbObject;
import org.junit.Test;
import org.mockito.Mockito;
public class DbPropertyTest
{
@Test(expected = IllegalArgumentException.class)
public void cannotHaveNullDbObject()
{
new DbProperty(null, "theProperty");
}
@Test
public void propertyValueCanBeRetrievedByReflection()
{
DbObjectWithIndexedProp dbo = Mockito.mock(DbObjectWithIndexedProp.class);
Mockito.when(dbo.getTheProperty()).thenReturn("This is the property value");
DbProperty dbProperty = new DbProperty(dbo, "theProperty");
assertEquals("This is the property value", dbProperty.getPropertyValue());
}
@Test
public void indexedPropertyValueCanBeRetrievedByReflection()
{
DbObjectWithIndexedProp dbo = Mockito.mock(DbObjectWithIndexedProp.class);
Mockito.when(dbo.getColours()).thenReturn(Arrays.asList("red", "green", "blue"));
DbProperty greenProperty = new DbProperty(dbo, "colours[1]");
DbProperty blueProperty = new DbProperty(dbo, "colours", 2);
assertEquals("green", greenProperty.getPropertyValue());
assertEquals("blue", blueProperty.getPropertyValue());
}
@Test
public void canGetPath()
{
new MyDbObject("root", 1).
add(new MyDbObject("child", 2)).
add(new MyDbObject("grandchild", 3)).
add(new MyDbObject("greatgrandchild", 4));
DbProperty levelProp = new DbProperty(MyDbObject.lastAdded, "level");
assertEquals("Incorrect path", "root.child.grandchild.greatgrandchild.level", levelProp.getPath());
DbProperty greatGrandChildProp = new DbProperty(MyDbObject.lastAdded);
assertEquals("Incorrect path", "root.child.grandchild.greatgrandchild", greatGrandChildProp.getPath());
}
private interface DbObjectWithIndexedProp extends DbObject
{
String getTheProperty();
List<String> getColours();
}
public static class MyDbObject extends AbstractDbObject
{
public static MyDbObject lastAdded;
private int level;
public MyDbObject(String name, int level)
{
super(null, name);
this.level = level;
}
@Override
public void accept(DbObjectVisitor visitor)
{
}
public MyDbObject add(MyDbObject child)
{
child.setParent(this);
lastAdded = child;
return child;
}
public int getLevel()
{
return this.level;
}
}
}

View File

@@ -1,45 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import java.io.File;
import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.TempFileProvider;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
/**
* Tests for the DbToXML class.
*
* @author Matt Ward
*/
public class DbToXMLTest
{
@Test
public void execute()
{
ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
File outFile = new File(TempFileProvider.getTempDir(), getClass().getSimpleName() + ".xml");
System.out.println("Writing to temp file: " + outFile);
DbToXML dbToXML = new DbToXML(ctx, outFile);
dbToXML.execute();
}
}

View File

@@ -1,508 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.alfresco.util.schemacomp.Difference.Where;
import org.alfresco.util.schemacomp.model.AbstractDbObject;
import org.alfresco.util.schemacomp.model.DbObject;
import org.alfresco.util.schemacomp.validator.DbValidator;
import org.hibernate.dialect.Dialect;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Tests for the SchemaUtils class.
*
* @author Matt Ward
*/
@RunWith(MockitoJUnitRunner.class)
public class DefaultComparisonUtilsTest
{
private @Mock Results differences;
private DefaultComparisonUtils comparisonUtils;
private DiffContext ctx;
private @Mock Dialect dialect;
@Before
public void setUp()
{
comparisonUtils = new DefaultComparisonUtils();
ctx = new DiffContext(dialect, differences, null, null);
}
@Test
public void compareSimple()
{
comparisonUtils.compareSimple(prop(null), prop(null), ctx);
verify(differences).add(Where.IN_BOTH_NO_DIFFERENCE, prop(null), prop(null));
comparisonUtils.compareSimple(prop("not_null_string"), prop("not_null_string"), ctx);
verify(differences).add(Where.IN_BOTH_NO_DIFFERENCE, prop("not_null_string"), prop("not_null_string"));
comparisonUtils.compareSimple(prop("Not_Null_String"), prop("NOT_NULL_STRING"), ctx);
verify(differences).add(Where.IN_BOTH_NO_DIFFERENCE, prop("Not_Null_String"), prop("NOT_NULL_STRING"));
comparisonUtils.compareSimple(prop("left"), prop("right"), ctx);
verify(differences).add(Where.IN_BOTH_BUT_DIFFERENCE, prop("left"), prop("right"));
comparisonUtils.compareSimple(prop("left"), prop(null), ctx);
verify(differences).add(Where.ONLY_IN_REFERENCE, prop("left"), prop(null));
comparisonUtils.compareSimple(prop(null), prop("right"), ctx);
verify(differences).add(Where.ONLY_IN_TARGET, prop(null), prop("right"));
}
public DbProperty prop(String propValue)
{
DbObject dbo = new DbObjectWithCollection("dbo", null);
return dbPropForValue(dbo, "someProperty", propValue);
}
@Test
public void compareCollections()
{
DbObject db1 = new DatabaseObject("db1");
DbObject db2 = new DatabaseObject("db2"); // only in left
DbObject db3 = new DatabaseObject("db3"); // only in right
DbObject db4 = new DatabaseObject("db4");
Collection<DbObject> left = new ArrayList<DbObject>();
Collections.addAll(left, db1, db2, db4);
Collection<DbObject> right = new ArrayList<DbObject>();
Collections.addAll(right, db1, db3, db4);
comparisonUtils.compareCollections(left, right, ctx);
// Differences and ommissions are noticed...
verify(differences).add(Where.IN_BOTH_BUT_DIFFERENCE, new DbProperty(db1), new DbProperty(db1));
verify(differences).add(Where.ONLY_IN_REFERENCE, new DbProperty(db2), null);
verify(differences).add(Where.ONLY_IN_TARGET, null, new DbProperty(db3));
verify(differences).add(Where.IN_BOTH_BUT_DIFFERENCE, new DbProperty(db4), new DbProperty(db4));
}
@Test
public void compareCollectionsWithMultipleMatches()
{
DbObject db2 = new DatabaseObject("db2");
DbObject db3 = new DatabaseObject("db3");
DbObject db4 = new DatabaseObject("db4");
DbObject db1 = new DatabaseObject("db1", db2, db3);
Collection<DbObject> left = new ArrayList<DbObject>();
Collections.addAll(left, db1, db4);
Collection<DbObject> right = new ArrayList<DbObject>();
Collections.addAll(right, db1, db2, db3);
comparisonUtils.compareCollections(left, right, ctx);
// Differences and ommissions are noticed...
verify(differences).add(Where.ONLY_IN_REFERENCE, new DbProperty(db4), null);
verify(differences).add(Where.IN_BOTH_BUT_DIFFERENCE, new DbProperty(db1), new DbProperty(db1));
verify(differences).add(Where.IN_BOTH_BUT_DIFFERENCE, new DbProperty(db1), new DbProperty(db2));
verify(differences).add(Where.IN_BOTH_BUT_DIFFERENCE, new DbProperty(db1), new DbProperty(db3));
}
@Test
public void propertyIsNotComparedWhenValidatorTakesResponsibility()
{
DbObject db1 = new DatabaseObject("db1");
DbProperty db1NameProp = new DbProperty(db1, "name");
DbObject db2 = new DatabaseObject("db2");
DbProperty db2NameProp = new DbProperty(db2, "name");
// Using mock to decouple unit test from actual NameValidator.
DbValidator nameValidator = mock(DbValidator.class);
when(nameValidator.validates("name")).thenReturn(true);
db1.getValidators().add(nameValidator);
comparisonUtils.compareSimple(db1NameProp, db2NameProp, ctx);
verify(differences, never()).add(Where.IN_BOTH_BUT_DIFFERENCE, db1NameProp, db2NameProp);
}
@Test
public void collectionPropertyIsNotComparedWhenValidatorTakesResponsibility()
{
Collection<Object> refCollection = new ArrayList<Object>();
refCollection.add(123);
refCollection.add("both");
DbObject refDbObj = new DbObjectWithCollection("left", refCollection);
DbProperty refCollProp = new DbProperty(refDbObj, "collection");
Collection<Object> targetCollection = new ArrayList<Object>();
targetCollection.add(234);
targetCollection.add("both");
DbObject targetDbObj = new DbObjectWithCollection("right", targetCollection);
DbProperty targetCollProp = new DbProperty(targetDbObj, "collection");
DbValidator validator = mock(DbValidator.class);
when(validator.validates("collection")).thenReturn(true);
refDbObj.getValidators().add(validator);
comparisonUtils.compareSimpleCollections(refCollProp, targetCollProp, ctx);
// No information should be reported...
verify(differences, never()).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(refDbObj, "collection[1]", "both"),
dbPropForValue(targetDbObj, "collection[1]", "both"));
verify(differences, never()).add(
Where.ONLY_IN_REFERENCE,
dbPropForValue(refDbObj, "collection[0]", 123),
dbPropForValue(targetDbObj, "collection", targetCollection));
verify(differences, never()).add(
Where.ONLY_IN_TARGET,
dbPropForValue(refDbObj, "collection", refCollection),
dbPropForValue(targetDbObj, "collection[0]", 234));
}
@Test
public void objectIsNotComparedWhenValidatorTakesResponsibility()
{
DbObject db1 = new DatabaseObject("db1");
DbObject db2 = new DatabaseObject("db2");
DbObject db3 = new DatabaseObject("db3");
DbObject db4 = new DatabaseObject("db4");
Collection<DbObject> reference = new ArrayList<DbObject>();
Collections.addAll(reference, db1, db3);
Collection<DbObject> target = new ArrayList<DbObject>();
Collections.addAll(target, db2, db4);
DbValidator validator = mock(DbValidator.class);
when(validator.validatesFullObject()).thenReturn(true);
db1.getValidators().add(validator);
db2.getValidators().add(validator);
comparisonUtils.compareCollections(reference, target, ctx);
verify(differences, never()).add(Where.ONLY_IN_REFERENCE, new DbProperty(db1), null);
verify(differences, never()).add(Where.ONLY_IN_TARGET, null, new DbProperty(db2));
verify(differences).add(Where.ONLY_IN_REFERENCE, new DbProperty(db3), null);
verify(differences).add(Where.ONLY_IN_TARGET, null, new DbProperty(db4));
}
// Check that two 'simple' collections (i.e. composed of non DbObject objects)
// must have the same items at the same indexes for those items to qualify as being in both
// collections with no difference. This is important for, e.g. column orderings in
// indexes or primary keys.
@Test
public void orderingFaultsWhenCollectionsSameSize()
{
Collection<Object> left = new ArrayList<Object>();
Collections.<Object>addAll(left, 0, "one", 2, "3", "4_this", 5, "6_this", "seven");
DbObject leftDbObj = new DbObjectWithCollection("left", left);
DbProperty leftCollProp = new DbProperty(leftDbObj, "collection");
Collection<Object> right = new ArrayList<Object>();
Collections.<Object>addAll(right, 0, "one", 2, "3", "4_that", 5, "6_that", "seven");
DbObject rightDbObj = new DbObjectWithCollection("right", right);
DbProperty rightCollProp = new DbProperty(rightDbObj, "collection");
comparisonUtils.compareSimpleOrderedLists(leftCollProp, rightCollProp, ctx);
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[0]", 0),
dbPropForValue(rightDbObj, "collection[0]", 0));
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[1]", "one"),
dbPropForValue(rightDbObj, "collection[1]", "one"));
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[2]", 2),
dbPropForValue(rightDbObj, "collection[2]", 2));
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[3]", "3"),
dbPropForValue(rightDbObj, "collection[3]", "3"));
verify(differences).add(
Where.IN_BOTH_BUT_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[4]", "4_this"),
dbPropForValue(rightDbObj, "collection[4]", "4_that"));
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[5]", 5),
dbPropForValue(rightDbObj, "collection[5]", 5));
verify(differences).add(
Where.IN_BOTH_BUT_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[6]", "6_this"),
dbPropForValue(rightDbObj, "collection[6]", "6_that"));
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[7]", "seven"),
dbPropForValue(rightDbObj, "collection[7]", "seven"));
}
@Test
public void orderingFaultsWhenReferenceCollectionLonger()
{
Collection<Object> reference = new ArrayList<Object>();
Collections.<Object>addAll(reference, "a", "z", "x", "1", "2");
DbObject refDbObj = new DbObjectWithCollection("reference", reference);
DbProperty refCollProp = new DbProperty(refDbObj, "collection");
Collection<Object> target = new ArrayList<Object>();
Collections.<Object>addAll(target, "a", "Q", "x");
DbObject targetDbObj = new DbObjectWithCollection("target", target);
DbProperty targetCollProp = new DbProperty(targetDbObj, "collection");
comparisonUtils.compareSimpleOrderedLists(refCollProp, targetCollProp, ctx);
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(refDbObj, "collection[0]", "a"),
dbPropForValue(targetDbObj, "collection[0]", "a"));
verify(differences).add(
Where.IN_BOTH_BUT_DIFFERENCE,
dbPropForValue(refDbObj, "collection[1]", "z"),
dbPropForValue(targetDbObj, "collection[1]", "Q"));
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(refDbObj, "collection[2]", "x"),
dbPropForValue(targetDbObj, "collection[2]", "x"));
verify(differences).add(
Where.ONLY_IN_REFERENCE,
dbPropForValue(refDbObj, "collection[3]", "1"),
null);
verify(differences).add(
Where.ONLY_IN_REFERENCE,
dbPropForValue(refDbObj, "collection[4]", "2"),
null);
}
@Test
public void orderingFaultsWhenTargetCollectionLonger()
{
Collection<Object> reference = new ArrayList<Object>();
Collections.<Object>addAll(reference, "a", "z", "x");
DbObject refDbObj = new DbObjectWithCollection("reference", reference);
DbProperty refCollProp = new DbProperty(refDbObj, "collection");
Collection<Object> target = new ArrayList<Object>();
Collections.<Object>addAll(target, "a", "Q", "x", "1", "2");
DbObject targetDbObj = new DbObjectWithCollection("target", target);
DbProperty targetCollProp = new DbProperty(targetDbObj, "collection");
comparisonUtils.compareSimpleOrderedLists(refCollProp, targetCollProp, ctx);
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(refDbObj, "collection[0]", "a"),
dbPropForValue(targetDbObj, "collection[0]", "a"));
verify(differences).add(
Where.IN_BOTH_BUT_DIFFERENCE,
dbPropForValue(refDbObj, "collection[1]", "z"),
dbPropForValue(targetDbObj, "collection[1]", "Q"));
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(refDbObj, "collection[2]", "x"),
dbPropForValue(targetDbObj, "collection[2]", "x"));
verify(differences).add(
Where.ONLY_IN_TARGET,
null,
dbPropForValue(targetDbObj, "collection[3]", "1"));
verify(differences).add(
Where.ONLY_IN_TARGET,
null,
dbPropForValue(targetDbObj, "collection[4]", "2"));
}
@Test
public void compareSimpleCollections()
{
Collection<Object> leftCollection = new ArrayList<Object>();
leftCollection.add(123);
leftCollection.add("both");
Collection<Object> subCollectionLeft = new ArrayList<Object>();
subCollectionLeft.add(3);
subCollectionLeft.add("my string");
subCollectionLeft.add(10);
subCollectionLeft.add("another");
leftCollection.add(subCollectionLeft);
leftCollection.add(456);
leftCollection.add("left only");
DbObject leftDbObj = new DbObjectWithCollection("left", leftCollection);
DbProperty leftCollProp = new DbProperty(leftDbObj, "collection");
Collection<Object> rightCollection = new ArrayList<Object>();
rightCollection.add(123);
rightCollection.add(789);
Collection<Object> subCollectionRight = new ArrayList<Object>(subCollectionLeft);
rightCollection.add(subCollectionRight);
rightCollection.add("right only");
rightCollection.add("both");
rightCollection.add("one more right only");
DbObject rightDbObj = new DbObjectWithCollection("right", rightCollection);
DbProperty rightCollProp = new DbProperty(rightDbObj, "collection");
comparisonUtils.compareSimpleCollections(leftCollProp, rightCollProp, ctx);
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[0]", 123),
dbPropForValue(rightDbObj, "collection[0]", 123));
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[1]", "both"),
dbPropForValue(rightDbObj, "collection[4]", "both"));
verify(differences).add(
Where.IN_BOTH_NO_DIFFERENCE,
dbPropForValue(leftDbObj, "collection[2]", subCollectionLeft),
dbPropForValue(rightDbObj, "collection[2]", subCollectionRight));
verify(differences).add(
Where.ONLY_IN_REFERENCE,
dbPropForValue(leftDbObj, "collection[3]", 456),
dbPropForValue(rightDbObj, "collection", rightCollection));
verify(differences).add(
Where.ONLY_IN_REFERENCE,
dbPropForValue(leftDbObj, "collection[4]", "left only"),
dbPropForValue(rightDbObj, "collection", rightCollection));
verify(differences).add(
Where.ONLY_IN_TARGET,
dbPropForValue(leftDbObj, "collection", leftCollection),
dbPropForValue(rightDbObj, "collection[1]", 789));
verify(differences).add(
Where.ONLY_IN_TARGET,
dbPropForValue(leftDbObj, "collection", leftCollection),
dbPropForValue(rightDbObj, "collection[3]", "right only"));
verify(differences).add(
Where.ONLY_IN_TARGET,
dbPropForValue(leftDbObj, "collection", leftCollection),
dbPropForValue(rightDbObj, "collection[5]", "one more right only"));
}
private DbProperty dbPropForValue(DbObject obj, String propName, Object propValue)
{
return new DbProperty(obj, propName, -1, true, propValue);
}
private List<DbObject> createMockDbObjects(int size)
{
ArrayList<DbObject> dbObjects = new ArrayList<DbObject>(size);
for (int i = 0; i < size; i++)
{
DbObject dbo = mock(DbObject.class);
when(dbo.toString()).thenReturn("Mock DbObject " + i);
dbObjects.add(dbo);
}
return dbObjects;
}
public static class DbObjectWithCollection extends AbstractDbObject
{
private Collection<Object> collection;
public DbObjectWithCollection(String name, Collection<Object> collection)
{
super(null, name);
this.collection = collection;
}
@Override
public void accept(DbObjectVisitor visitor)
{
}
public Collection<Object> getCollection()
{
return this.collection;
}
}
public static class DatabaseObject extends AbstractDbObject
{
private DbObject[] equivalentObjects = new DbObject[] {};
public DatabaseObject(String name)
{
super(null, name);
}
public DatabaseObject(String name, DbObject... equivalentObjects)
{
this(name);
this.equivalentObjects = equivalentObjects;
}
@Override
public void accept(DbObjectVisitor visitor)
{
visitor.visit(this);
}
@Override
protected void doDiff(DbObject right, DiffContext ctx)
{
DbProperty leftProp = new DbProperty(this);
DbProperty rightProp = new DbProperty(right);
ctx.getComparisonResults().add(Where.IN_BOTH_BUT_DIFFERENCE, leftProp, rightProp);
}
@Override
public boolean sameAs(DbObject other)
{
// We can tell this stub to treat certain other objects as 'the same' as this object
// by supplying them in the constructor. If this object is invoked with t.sameAs(o)
// and o is in the list of equivalent objects supplied in the constructor, then
// sameAs() will return true. Otherwise the default sameAs() implementation is used.
for (DbObject o : equivalentObjects)
{
if (other.equals(o))
{
return true;
}
}
return super.sameAs(other);
}
}
}

View File

@@ -1,90 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.alfresco.util.schemacomp.Difference.Where;
import org.alfresco.util.schemacomp.model.Column;
import org.junit.Before;
import org.junit.Test;
import org.springframework.extensions.surf.util.I18NUtil;
/**
* Tests for the {@link Difference} class.
*
* @author Matt Ward
*/
public class DifferenceTest
{
@Before
public void setUp()
{
I18NUtil.registerResourceBundle("alfresco.messages.system-messages");
}
@Test
public void describe()
{
DbProperty refDbProp = mock(DbProperty.class);
when(refDbProp.getPath()).thenReturn("alfresco.some_table.some_column.name");
when(refDbProp.getDbObject()).thenReturn(new Column("some_column"));
when(refDbProp.getPropertyValue()).thenReturn("node_ref");
DbProperty targetDbProp = mock(DbProperty.class);
when(targetDbProp.getPath()).thenReturn("alfresco.some_table.some_column.name");
when(targetDbProp.getDbObject()).thenReturn(new Column("some_column"));
when(targetDbProp.getPropertyValue()).thenReturn("nood_ref");
Difference diff = new Difference(Where.IN_BOTH_BUT_DIFFERENCE, refDbProp, targetDbProp);
assertEquals("Difference: expected column alfresco.some_table.some_column.name=\"node_ref\"" +
", but was alfresco.some_table.some_column.name=\"nood_ref\"",
diff.describe());
}
@Test
public void describeRefOnly()
{
DbProperty refDbProp = mock(DbProperty.class);
when(refDbProp.getPath()).thenReturn("alfresco.some_table.some_column");
when(refDbProp.getDbObject()).thenReturn(new Column("some_column"));
Difference diff = new Difference(Where.ONLY_IN_REFERENCE, refDbProp, null);
assertEquals("Difference: missing column from database, expected at path: alfresco.some_table.some_column",
diff.describe());
}
@Test
public void describeTargetOnly()
{
DbProperty targetDbProp = mock(DbProperty.class);
when(targetDbProp.getPath()).thenReturn("alfresco.some_table.some_column");
when(targetDbProp.getDbObject()).thenReturn(new Column("some_column"));
Difference diff = new Difference(Where.ONLY_IN_TARGET, null, targetDbProp);
assertEquals("Difference: unexpected column found in database with path: alfresco.some_table.some_column",
diff.describe());
}
}

View File

@@ -1,107 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import javax.sql.DataSource;
import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.schemacomp.model.Schema;
import org.alfresco.util.schemacomp.test.exportdb.AbstractExportTester;
import org.alfresco.util.schemacomp.test.exportdb.MySQLDialectExportTester;
import org.alfresco.util.schemacomp.test.exportdb.PostgreSQLDialectExportTester;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.PostgreSQLDialect;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
/**
* Tests for the ExportDb class. Loads the database into an in-memory {@link Schema} representation.
* <p>
* This test is DBMS specific, if the test is run on a system configured against MySQL for example,
* it will run MySQL specific tests. If there is no test available for the configured DBMS then
* the test will pass - this allows addition of new DBMS-specific tests when available.
*
* @see AbstractExportTester
* @author Matt Ward
*/
public class ExportDbTest
{
private ApplicationContext ctx;
private ExportDb exporter;
private Dialect dialect;
private DataSource dataSource;
private SimpleJdbcTemplate jdbcTemplate;
private PlatformTransactionManager tx;
private AbstractExportTester exportTester;
private static final Log logger = LogFactory.getLog(ExportDbTest.class);
@Before
public void setUp() throws Exception
{
ctx = ApplicationContextHelper.getApplicationContext();
dataSource = (DataSource) ctx.getBean("dataSource");
tx = (PlatformTransactionManager) ctx.getBean("transactionManager");
jdbcTemplate = new SimpleJdbcTemplate(dataSource);
exporter = new ExportDb(ctx);
exporter.setNamePrefix("export_test_");
dialect = (Dialect) ctx.getBean("dialect");
}
@Test
public void exportDb() throws Exception
{
Class dialectClass = dialect.getClass();
if (logger.isDebugEnabled())
{
logger.debug("Using dialect class " + dialectClass.getName());
}
if (PostgreSQLDialect.class.isAssignableFrom(dialectClass))
{
exportTester = new PostgreSQLDialectExportTester(exporter, tx, jdbcTemplate);
}
else if (MySQLDialect.class.isAssignableFrom(dialectClass))
{
exportTester = new MySQLDialectExportTester(exporter, tx, jdbcTemplate);
}
if (exportTester != null)
{
// Run the DBMS specific tests.
exportTester.runExportTest();
}
else
{
if (logger.isInfoEnabled())
{
logger.info("Unsupported dialect for this test " + dialectClass.getName());
}
}
}
}

View File

@@ -1,178 +0,0 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.alfresco.util.TempFileProvider;
import org.alfresco.util.schemacomp.MultiFileDumper.DbToXMLFactory;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Tests for the MultiFileDumper class.
*
* @author Matt Ward
*/
@RunWith(MockitoJUnitRunner.class)
public class MultiFileDumperTest
{
private @Mock DbToXMLFactory dbToXMLFactory;
private @Mock DbToXML dbToXMLForA;
private @Mock DbToXML dbToXMLForB;
private @Mock DbToXML dbToXMLForC;
@Test(expected=IllegalArgumentException.class)
public void exceptionThrownWhenZeroPrefixesUsed()
{
// Shouldn't be able to construct a dumper with no prefixes to dump.
new MultiFileDumper(new String[] {}, TempFileProvider.getTempDir(), "", dbToXMLFactory);
}
@Test(expected=IllegalArgumentException.class)
public void exceptionThrownWhenNullPrefixListUsed()
{
// Shouldn't be able to construct a dumper with no prefixes to dump.
new MultiFileDumper(null, TempFileProvider.getTempDir(), "", dbToXMLFactory);
}
@Test
public void canDumpSchemaToFiles()
{
String[] prefixes = new String[] { "a_", "b_", "c_" };
File directory = TempFileProvider.getTempDir();
String fileNamePattern = "SchemaDump-MySQL-{0}-";
MultiFileDumper dumper = new MultiFileDumper(prefixes, directory, fileNamePattern, dbToXMLFactory);
when(dbToXMLFactory.create(argThat(isFileNameStartingWith("SchemaDump-MySQL-a_-")), eq("a_"))).
thenReturn(dbToXMLForA);
when(dbToXMLFactory.create(argThat(isFileNameStartingWith("SchemaDump-MySQL-b_-")), eq("b_"))).
thenReturn(dbToXMLForB);
when(dbToXMLFactory.create(argThat(isFileNameStartingWith("SchemaDump-MySQL-c_-")), eq("c_"))).
thenReturn(dbToXMLForC);
List<File> files = dumper.dumpFiles();
Iterator<File> it = files.iterator();
assertPathCorrect("SchemaDump-MySQL-a_-", directory, it.next());
assertPathCorrect("SchemaDump-MySQL-b_-", directory, it.next());
assertPathCorrect("SchemaDump-MySQL-c_-", directory, it.next());
verify(dbToXMLForA).execute();
verify(dbToXMLForB).execute();
verify(dbToXMLForC).execute();
}
@Test
public void canDumpSchemaToFilesForDefaultDBPrefixes()
{
File directory = TempFileProvider.getTempDir();
String fileNamePattern = "SchemaDump-MySQL-{0}-";
MultiFileDumper dumper = new MultiFileDumper(directory, fileNamePattern, dbToXMLFactory);
Map<String, DbToXML> xmlExporters = new HashMap<String, DbToXML>(MultiFileDumper.DEFAULT_PREFIXES.length);
// Each of the prefixes will be used to call DbToXMLFactory.create(...)
for (String prefix : MultiFileDumper.DEFAULT_PREFIXES)
{
DbToXML dbToXML = mock(DbToXML.class);
xmlExporters.put(prefix, dbToXML);
when(dbToXMLFactory.create(any(File.class), eq(prefix))).thenReturn(dbToXML);
}
dumper.dumpFiles();
// Check that each DEFAULT_PREFIX prefix resulted in its associated DbToXML object being used.
for (DbToXML dbToXML : xmlExporters.values())
{
verify(dbToXML).execute();
}
}
private ArgumentMatcher<File> isFileNameStartingWith(String startOfName)
{
return new FileNameBeginsWith(startOfName);
}
private static class FileNameBeginsWith extends ArgumentMatcher<File>
{
private final String startOfName;
public FileNameBeginsWith(String startOfName)
{
this.startOfName = startOfName;
}
@Override
public boolean matches(Object arg)
{
if (arg != null)
{
File fileArg = (File) arg;
return fileArg.getName().startsWith(startOfName);
}
return false;
}
}
/**
* Check that actualFile has the expected directory and file name prefix, e.g. if the actual file
* is /temp/my_file_123.xml and we call:
* <pre>
* assertPathCorrect("my_file_", new File("/tmp"), actualFile)
* </pre>
* Then the assertion should hold true.
*
* @param expectedFileNamePrefix
* @param expectedDirectory
* @param actualFile
*/
private void assertPathCorrect(String expectedFileNamePrefix, File expectedDirectory, File actualFile)
{
File expectedPath = new File(expectedDirectory, expectedFileNamePrefix);
if (!actualFile.getAbsolutePath().startsWith(expectedPath.getAbsolutePath()))
{
String failureMsg = "File path " + actualFile.getAbsolutePath() +
" does not start as expected: " + expectedPath.getAbsolutePath();
Assert.fail(failureMsg);
}
}
}

View File

@@ -1,98 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.util.schemacomp.model.AbstractDbObject;
import org.alfresco.util.schemacomp.model.DbObject;
import org.junit.Before;
import org.junit.Test;
import org.springframework.extensions.surf.util.I18NUtil;
/**
* Tests for the {@link RedundantDbObject} class.
*
* @author Matt Ward
*/
public class RedundantDbObjectTest
{
@Before
public void setUp()
{
I18NUtil.registerResourceBundle("alfresco.messages.system-messages");
}
@Test
public void describe()
{
DbObject reference = new MyDbObject("reference");
List<DbObject> matches = makeMatches(3);
RedundantDbObject redundantDBO = new RedundantDbObject(reference, matches);
assertEquals("Redundancy: 3 items matching MyDbObject[name=reference], " +
"matches: MyDbObject[name=match1], MyDbObject[name=match2], MyDbObject[name=match3]",
redundantDBO.describe());
}
@Test
public void describeTooManyMatches()
{
DbObject reference = new MyDbObject("reference");
List<DbObject> matches = makeMatches(4);
RedundantDbObject redundantDBO = new RedundantDbObject(reference, matches);
assertEquals("4 redundant items? reference: MyDbObject[name=reference], " +
"matches: MyDbObject[name=match1], MyDbObject[name=match2], MyDbObject[name=match3] and 1 more...",
redundantDBO.describe());
}
/**
* @return
*/
private List<DbObject> makeMatches(int numMatches)
{
List<DbObject> matches = new ArrayList<DbObject>();
for (int i = 0; i < numMatches; i++)
{
matches.add(new MyDbObject("match" + (i+1)));
}
return matches;
}
private static class MyDbObject extends AbstractDbObject
{
public MyDbObject(String name)
{
super(null, name);
}
@Override
public void accept(DbObjectVisitor visitor)
{
}
}
}

View File

@@ -1,39 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import org.alfresco.util.schemacomp.model.ModelTestSuite;
import org.alfresco.util.schemacomp.validator.ValidatorTestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* Test suite running all the tests in the schemacomp package - and subpackages.
* @author Matt Ward
*/
@RunWith(Suite.class)
@Suite.SuiteClasses(
{
ModelTestSuite.class,
ValidatorTestSuite.class,
SchemaCompTestSuite.class
})
public class SchemaCompPackageTestSuite
{
}

View File

@@ -1,48 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* Test suite for tests in the schemacomp package.
*
* @author Matt Ward
*/
@RunWith(Suite.class)
@Suite.SuiteClasses(
{
DbObjectXMLTransformerTest.class,
DbPropertyTest.class,
DbToXMLTest.class,
DefaultComparisonUtilsTest.class,
DifferenceTest.class,
ExportDbTest.class,
MultiFileDumperTest.class,
RedundantDbObjectTest.class,
SchemaComparatorTest.class,
SchemaToXMLTest.class,
ValidationResultTest.class,
ValidatingVisitorTest.class,
XMLToSchemaTest.class
})
public class SchemaCompTestSuite
{
}

View File

@@ -1,155 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.alfresco.util.schemacomp.Difference.Where;
import org.alfresco.util.schemacomp.model.Column;
import org.alfresco.util.schemacomp.model.ForeignKey;
import org.alfresco.util.schemacomp.model.Index;
import org.alfresco.util.schemacomp.model.PrimaryKey;
import org.alfresco.util.schemacomp.model.Sequence;
import org.alfresco.util.schemacomp.model.Table;
import org.apache.commons.lang.ArrayUtils;
public class SchemaCompTestingUtils
{
public static void dumpValidation(Results results)
{
System.out.println("Validation Results (" + results.size() + ")");
for (Result r : results)
{
if (r instanceof ValidationResult)
{
System.out.println(r);
}
}
}
public static void dumpDiffs(Results differences, boolean showNonDifferences)
{
System.out.println("Differences (" + differences.size() + ")");
for (Result d : differences)
{
if (d instanceof Difference)
{
Difference diff = (Difference) d;
if (diff.getWhere() != Where.IN_BOTH_NO_DIFFERENCE || showNonDifferences)
{
System.out.println(d);
}
}
}
}
public static Table table(String name)
{
return new Table(null, name, columns("id NUMBER(10)"), pk("pk_" + name, "id"), fkeys(), indexes());
}
public static Table table(String name, Collection<Column> columns, PrimaryKey primaryKey,
Collection<ForeignKey> foreignKeys, Collection<Index> indexes)
{
return new Table(null, name, columns, primaryKey, foreignKeys, indexes);
}
public static Collection<Column> columns(boolean compareColOrder, String... colDefs)
{
assertTrue("Tables must have columns", colDefs.length > 0);
Column[] columns = new Column[colDefs.length];
for (int i = 0; i < colDefs.length; i++)
{
String[] parts = colDefs[i].split(" ");
columns[i] = new Column(null, parts[0], parts[1], false);
columns[i].setOrder(i+1);
columns[i].setCompareOrder(compareColOrder);
}
return Arrays.asList(columns);
}
public static Collection<Column> columns(String... colDefs)
{
return columns(true, colDefs);
}
public static PrimaryKey pk(String name, String... columnNames)
{
assertTrue("No columns specified", columnNames.length > 0);
// Create a list of column orders, ordered the same as the supplied column names
// i.e. 1, 2, 3... N
List<Integer> columnOrders = new ArrayList<Integer>(columnNames.length);
for (int i = 1; i <= columnNames.length; i++)
{
columnOrders.add(i);
}
PrimaryKey pk = new PrimaryKey(null, name, Arrays.asList(columnNames), columnOrders);
return pk;
}
public static List<ForeignKey> fkeys(ForeignKey... fkeys)
{
return Arrays.asList(fkeys);
}
public static ForeignKey fk(String fkName, String localColumn, String targetTable, String targetColumn)
{
return new ForeignKey(null, fkName, localColumn, targetTable, targetColumn);
}
/**
* Create collection of indexes using strings of format "name column1 [column2 ... columnN]"
*/
public static Collection<Index> indexes(String... indexDefs)
{
Index[] indexes = new Index[indexDefs.length];
for (int i = 0; i < indexDefs.length; i++)
{
String[] parts = indexDefs[i].split(" ");
String name = parts[0];
boolean unique = false;
int columnsStart = 1;
if (parts[1].equals("[unique]"))
{
unique = true;
columnsStart++;
}
String[] columns = (String[]) ArrayUtils.subarray(parts, columnsStart, parts.length);
indexes[i] = new Index(null, name, Arrays.asList(columns));
indexes[i].setUnique(unique);
}
return Arrays.asList(indexes);
}
public static Sequence sequence(String name)
{
return new Sequence(name);
}
}

View File

@@ -1,348 +0,0 @@
/*
* Copytarget (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.columns;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.dumpDiffs;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.dumpValidation;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.fk;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.fkeys;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.indexes;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.pk;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.table;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.Arrays;
import java.util.Iterator;
import org.alfresco.util.schemacomp.Difference.Where;
import org.alfresco.util.schemacomp.model.PrimaryKey;
import org.alfresco.util.schemacomp.model.Schema;
import org.alfresco.util.schemacomp.model.Table;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MySQL5InnoDBDialect;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the SchmeaComparator class.
*
* @author Matt Ward
*/
public class SchemaComparatorTest
{
private SchemaComparator comparator;
private Schema reference;
private Schema target;
private Dialect dialect;
@Before
public void setup()
{
reference = new Schema("schema", "alf_", 590, true);
target = new Schema("schema", "alf_", 590, true);
dialect = new MySQL5InnoDBDialect();
}
@Test
public void canPerformDiff()
{
// Reference schema's database objects.
reference.add(new Table(reference, "tbl_no_diff", columns("id NUMBER(10)", "nodeRef VARCHAR2(200)", "name VARCHAR2(150)"),
pk("pk_tbl_no_diff", "id"), fkeys(fk("fk_tbl_no_diff", "nodeRef", "node", "nodeRef")),
indexes("idx_node id nodeRef")));
reference.add(table("table_in_reference"));
reference.add(new Table(reference, "tbl_has_diff_pk", columns("id NUMBER(10)", "nodeRef VARCHAR2(200)"),
pk("pk_is_diff", "id"), fkeys(), indexes("idx_one id nodeRef", "idx_two id")));
// Target schema's database objects.
target.add(new Table(target, "tbl_no_diff", columns("id NUMBER(10)", "nodeRef VARCHAR2(200)", "name VARCHAR2(150)"),
pk("pk_tbl_no_diff", "id"), fkeys(fk("fk_tbl_no_diff", "nodeRef", "node", "nodeRef")),
indexes("idx_node id nodeRef")));
target.add(new Table(target, "tbl_has_diff_pk", columns("id NUMBER(10)", "nodeRef VARCHAR2(200)"),
pk("pk_is_diff", "nodeRef"), fkeys(), indexes("idx_one id nodeRef", "idx_two [unique] id")));
target.add(table("table_in_target"));
comparator = new SchemaComparator(reference, target, dialect);
comparator.validateAndCompare();
// See stdout for diagnostics dump...
dumpDiffs(comparator.getComparisonResults(), false);
dumpValidation(comparator.getComparisonResults());
Results results = comparator.getComparisonResults();
Iterator<Result> it = results.iterator();
// Table table_in_reference only appears in the reference schema
Difference diff = (Difference) it.next();
assertEquals(Where.ONLY_IN_REFERENCE, diff.getWhere());
assertEquals("schema.table_in_reference", diff.getLeft().getPath());
assertEquals(null, diff.getRight());
assertEquals(null, diff.getLeft().getPropertyName());
assertEquals(null, diff.getLeft().getPropertyValue());
// Table tbl_has_diff_pk has PK of "id" in reference and "nodeRef" in target
diff = (Difference) it.next();
assertEquals(Where.IN_BOTH_BUT_DIFFERENCE, diff.getWhere());
assertEquals("schema.tbl_has_diff_pk.pk_is_diff.columnNames[0]", diff.getLeft().getPath());
assertEquals("schema.tbl_has_diff_pk.pk_is_diff.columnNames[0]", diff.getRight().getPath());
assertEquals("columnNames[0]", diff.getLeft().getPropertyName());
assertEquals("id", diff.getLeft().getPropertyValue());
assertEquals("columnNames[0]", diff.getRight().getPropertyName());
assertEquals("nodeRef", diff.getRight().getPropertyValue());
// idx_two is unique in the righ_schema but not in the reference
diff = (Difference) it.next();
assertEquals("schema.tbl_has_diff_pk.idx_two.unique", diff.getLeft().getPath());
assertEquals("schema.tbl_has_diff_pk.idx_two.unique", diff.getRight().getPath());
assertEquals("unique", diff.getLeft().getPropertyName());
assertEquals(false, diff.getLeft().getPropertyValue());
assertEquals("unique", diff.getRight().getPropertyName());
assertEquals(true, diff.getRight().getPropertyValue());
// Table table_in_target does not exist in the reference schema
diff = (Difference) it.next();
assertEquals(Where.ONLY_IN_TARGET, diff.getWhere());
assertEquals("schema.table_in_target", diff.getRight().getPath());
assertEquals(null, diff.getLeft());
assertEquals(null, diff.getRight().getPropertyName());
assertEquals(null, diff.getRight().getPropertyValue());
assertFalse("There should be no more differences", it.hasNext());
}
@Test
public void pkOrderingComparedCorrectly()
{
reference = new Schema("schema", "alf_", 590, true);
target = new Schema("schema", "alf_", 590, true);
// Reference schema's database objects.
reference.add(new Table(
reference,
"table_name",
columns("id NUMBER(10)", "nodeRef VARCHAR2(200)", "name VARCHAR2(150)"),
new PrimaryKey(null, "my_pk_name", Arrays.asList("id", "nodeRef"), Arrays.asList(1, 2)),
fkeys(),
indexes()));
// Target schema's database objects - note different order of PK columns.
target.add(new Table(
target,
"table_name",
columns("id NUMBER(10)", "nodeRef VARCHAR2(200)", "name VARCHAR2(150)"),
new PrimaryKey(null, "my_pk_name", Arrays.asList("id", "nodeRef"), Arrays.asList(2, 1)),
fkeys(),
indexes()));
comparator = new SchemaComparator(reference, target, dialect);
comparator.validateAndCompare();
// See stdout for diagnostics dump...
dumpDiffs(comparator.getComparisonResults(), false);
dumpValidation(comparator.getComparisonResults());
Results results = comparator.getComparisonResults();
Iterator<Result> it = results.iterator();
Difference diff = (Difference) it.next();
assertEquals(Where.IN_BOTH_BUT_DIFFERENCE, diff.getWhere());
assertEquals("schema.table_name.my_pk_name.columnOrders[0]", diff.getLeft().getPath());
assertEquals("schema.table_name.my_pk_name.columnOrders[0]", diff.getRight().getPath());
assertEquals("columnOrders[0]", diff.getLeft().getPropertyName());
assertEquals(1, diff.getLeft().getPropertyValue());
assertEquals("columnOrders[0]", diff.getRight().getPropertyName());
assertEquals(2, diff.getRight().getPropertyValue());
diff = (Difference) it.next();
assertEquals(Where.IN_BOTH_BUT_DIFFERENCE, diff.getWhere());
assertEquals("schema.table_name.my_pk_name.columnOrders[1]", diff.getLeft().getPath());
assertEquals("schema.table_name.my_pk_name.columnOrders[1]", diff.getRight().getPath());
assertEquals("columnOrders[1]", diff.getLeft().getPropertyName());
assertEquals(2, diff.getLeft().getPropertyValue());
assertEquals("columnOrders[1]", diff.getRight().getPropertyName());
assertEquals(1, diff.getRight().getPropertyValue());
assertFalse("There should be no more differences", it.hasNext());
}
@Test
public void indexColumnOrderingComparedCorrectly()
{
reference = new Schema("schema", "alf_", 590, true);
target = new Schema("schema", "alf_", 590, true);
// Reference schema's database objects.
reference.add(new Table(
reference,
"table_name",
columns("id NUMBER(10)", "nodeRef VARCHAR2(200)", "name VARCHAR2(150)"),
pk("pk", "id"),
fkeys(),
indexes("index_name id nodeRef")));
// Target schema's database objects - note different order of index columns.
target.add(new Table(
target,
"table_name",
columns("id NUMBER(10)", "nodeRef VARCHAR2(200)", "name VARCHAR2(150)"),
pk("pk", "id"),
fkeys(),
indexes("index_name nodeRef id")));
comparator = new SchemaComparator(reference, target, dialect);
comparator.validateAndCompare();
// See stdout for diagnostics dump...
dumpDiffs(comparator.getComparisonResults(), false);
dumpValidation(comparator.getComparisonResults());
Results results = comparator.getComparisonResults();
Iterator<Result> it = results.iterator();
Difference diff = (Difference) it.next();
assertEquals(Where.IN_BOTH_BUT_DIFFERENCE, diff.getWhere());
assertEquals("schema.table_name.index_name.columnNames[0]", diff.getLeft().getPath());
assertEquals("schema.table_name.index_name.columnNames[0]", diff.getRight().getPath());
assertEquals("columnNames[0]", diff.getLeft().getPropertyName());
assertEquals("id", diff.getLeft().getPropertyValue());
assertEquals("columnNames[0]", diff.getRight().getPropertyName());
assertEquals("nodeRef", diff.getRight().getPropertyValue());
diff = (Difference) it.next();
assertEquals(Where.IN_BOTH_BUT_DIFFERENCE, diff.getWhere());
assertEquals("schema.table_name.index_name.columnNames[1]", diff.getLeft().getPath());
assertEquals("schema.table_name.index_name.columnNames[1]", diff.getRight().getPath());
assertEquals("columnNames[1]", diff.getLeft().getPropertyName());
assertEquals("nodeRef", diff.getLeft().getPropertyValue());
assertEquals("columnNames[1]", diff.getRight().getPropertyName());
assertEquals("id", diff.getRight().getPropertyValue());
assertFalse("There should be no more differences", it.hasNext());
}
@Test
public void columnOrderingComparedCorrectlyWhenEnabled()
{
reference = new Schema("schema", "alf_", 590, true);
target = new Schema("schema", "alf_", 590, true);
// Reference schema's database objects.
reference.add(new Table(
reference,
"table_name",
columns("id NUMBER(10)", "nodeRef VARCHAR2(200)", "name VARCHAR2(150)"),
new PrimaryKey(null, "my_pk_name", Arrays.asList("id", "nodeRef"), Arrays.asList(1, 2)),
fkeys(),
indexes()));
// Target schema's database objects - note different column order
target.add(new Table(
target,
"table_name",
columns("id NUMBER(10)", "name VARCHAR2(150)", "nodeRef VARCHAR2(200)"),
new PrimaryKey(null, "my_pk_name", Arrays.asList("id", "nodeRef"), Arrays.asList(1, 2)),
fkeys(),
indexes()));
comparator = new SchemaComparator(reference, target, dialect);
comparator.validateAndCompare();
// See stdout for diagnostics dump...
dumpDiffs(comparator.getComparisonResults(), false);
dumpValidation(comparator.getComparisonResults());
Results results = comparator.getComparisonResults();
Iterator<Result> it = results.iterator();
Difference diff = (Difference) it.next();
assertEquals(Where.IN_BOTH_BUT_DIFFERENCE, diff.getWhere());
assertEquals("schema.table_name.nodeRef.order", diff.getLeft().getPath());
assertEquals("order", diff.getLeft().getPropertyName());
assertEquals(2, diff.getLeft().getPropertyValue());
assertEquals("schema.table_name.nodeRef.order", diff.getRight().getPath());
assertEquals("order", diff.getRight().getPropertyName());
assertEquals(3, diff.getRight().getPropertyValue());
diff = (Difference) it.next();
assertEquals(Where.IN_BOTH_BUT_DIFFERENCE, diff.getWhere());
assertEquals("schema.table_name.name.order", diff.getLeft().getPath());
assertEquals("order", diff.getLeft().getPropertyName());
assertEquals(3, diff.getLeft().getPropertyValue());
assertEquals("schema.table_name.name.order", diff.getRight().getPath());
assertEquals("order", diff.getRight().getPropertyName());
assertEquals(2, diff.getRight().getPropertyValue());
assertFalse("There should be no more differences", it.hasNext());
}
@Test
public void columnOrderingIgnoredWhenDisabled()
{
reference = new Schema("schema", "alf_", 590, false);
target = new Schema("schema", "alf_", 590, false);
// Reference schema's database objects.
reference.add(new Table(
reference,
"table_name",
columns(false, "id NUMBER(10)", "nodeRef VARCHAR2(200)", "name VARCHAR2(150)"),
new PrimaryKey(null, "my_pk_name", Arrays.asList("id", "nodeRef"), Arrays.asList(1, 2)),
fkeys(),
indexes()));
// Target schema's database objects - note different column order
target.add(new Table(
target,
"table_name",
columns(false, "id NUMBER(10)", "name VARCHAR2(150)", "nodeRef VARCHAR2(200)"),
new PrimaryKey(null, "my_pk_name", Arrays.asList("id", "nodeRef"), Arrays.asList(1, 2)),
fkeys(),
indexes()));
comparator = new SchemaComparator(reference, target, dialect);
comparator.validateAndCompare();
// See stdout for diagnostics dump...
dumpDiffs(comparator.getComparisonResults(), false);
dumpValidation(comparator.getComparisonResults());
Results results = comparator.getComparisonResults();
// There are no logical differences
assertEquals(0, results.size());
}
}

View File

@@ -1,81 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.junit.Assert.fail;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.io.Writer;
import org.alfresco.repo.domain.schema.SchemaBootstrap;
import org.alfresco.util.ApplicationContextHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Test intended for use in the continuous integration system that checks whether the
* schema reference file (for whichever database the tests are being run against)
* is in sync with the actual schema. If the test fails (and the schema comparator is
* in working order) then the most likely cause is that a new up-to-date schema reference file
* needs to be created.
* <p>
* Schema reference files are created using the {@link DbToXML} tool.
* <p>
* Note: if no reference file exists then the test will pass, this is to allow piece meal
* introduction of schmea reference files.
*
* @see DbToXML
* @author Matt Ward
*/
public class SchemaReferenceFileTest
{
private ClassPathXmlApplicationContext ctx;
private SchemaBootstrap schemaBootstrap;
@Before
public void setUp() throws Exception
{
ctx = (ClassPathXmlApplicationContext) ApplicationContextHelper.getApplicationContext();
schemaBootstrap = (SchemaBootstrap) ctx.getBean("schemaBootstrap");
}
@After
public void tearDown()
{
ctx.close();
}
@Test
public void checkReferenceFile()
{
Writer buff = new CharArrayWriter(1024);
PrintWriter out = new PrintWriter(buff);
int numProblems = schemaBootstrap.validateSchema(null, out);
out.flush();
if (numProblems > 0)
{
fail(buff.toString());
}
}
}

View File

@@ -1,90 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.columns;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.fk;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.fkeys;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.indexes;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.pk;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.table;
import static org.alfresco.util.schemacomp.SchemaCompTestingUtils.sequence;
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.transform.stream.StreamResult;
import org.alfresco.util.schemacomp.model.Schema;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the SchemaToXML class.
* @author Matt Ward
*/
public class SchemaToXMLTest
{
@Before
public void setUp() throws Exception
{
}
@Test
public void canTransformSchemaToXML() throws IOException
{
Writer writer = new StringWriter();
StreamResult out = new StreamResult(writer);
Schema schema = new Schema("alfresco", "my-prefix", 501, true);
schema.add(
table("node",
columns("id NUMBER(10)",
"nodeRef VARCHAR2(200)",
"name VARCHAR2(150)"),
pk("pk_node", "id"),
fkeys(fk("fk_node_noderef", "nodeRef", "node", "nodeRef")),
indexes("idx_node_by_id id nodeRef")));
schema.add(sequence("node_seq"));
schema.add(sequence("content_seq"));
SchemaToXML transformer = new SchemaToXML(schema, out);
transformer.execute();
System.out.println(writer.toString());
// Check the first couple of lines, details tests of the actual content
// are performed by DbObjectXMLTransformerTest
BufferedReader reader = new BufferedReader(new StringReader(writer.toString()));
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", reader.readLine());
String xsd =
"xmlns=\"http://www.alfresco.org/repo/db-schema\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"http://www.alfresco.org/repo/db-schema db-schema.xsd\"";
assertEquals("<schema " + xsd + " name=\"alfresco\" dbprefix=\"my-prefix\" version=\"501\" tablecolumnorder=\"true\">", reader.readLine());
assertEquals(" <validators>", reader.readLine());
}
}

View File

@@ -1,125 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.alfresco.util.schemacomp.model.DbObject;
import org.alfresco.util.schemacomp.model.Index;
import org.alfresco.util.schemacomp.model.Schema;
import org.alfresco.util.schemacomp.model.Table;
import org.alfresco.util.schemacomp.validator.DbValidator;
import org.hibernate.dialect.MySQL5InnoDBDialect;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.mockito.Mockito;
/**
* Tests for the ValidatingVisitor class.
*
* @author Matt Ward
*/
public class ValidatingVisitorTest
{
private DiffContext ctx;
private ValidatingVisitor visitor;
private Table refTable;
private Table targetTable;
private Schema refSchema;
private Schema targetSchema;
private Index refIndex;
private Index targetIndex1;
private Index targetIndex2;
private Index targetIndex3;
private List<DbValidator> validators;
private ComparisonUtils comparisonUtils;
@Before
public void setUp() throws Exception
{
refTable = new Table("reference_table");
refIndex = new Index(refTable, "index_name", Arrays.asList("a", "b", "c"));
ctx = new DiffContext(new MySQL5InnoDBDialect(), refSchema, targetSchema);
visitor = new ValidatingVisitor(ctx);
validators = new ArrayList<DbValidator>();
validators.add(Mockito.mock(DbValidator.class));
validators.add(Mockito.mock(DbValidator.class));
refIndex.setValidators(validators);
targetTable = new Table("target_table");
targetIndex1 = new Index(targetTable, "index_name", Arrays.asList("a", "b", "c"));
targetIndex2 = new Index(targetTable, "another_index", Arrays.asList("a", "b", "c"));
targetIndex3 = new Index(targetTable, "index_name", Arrays.asList("e", "f"));
comparisonUtils = Mockito.mock(ComparisonUtils.class);
visitor.setComparisonUtils(comparisonUtils);
}
@Test
public void canValidate()
{
Mockito.when(comparisonUtils.findEquivalentObjects(refSchema, refIndex)).
thenReturn(Arrays.asList((DbObject) targetIndex1, targetIndex2, targetIndex3));
// Validate all instances of the target schema's indexes that are equivalent to this index
visitor.visit(refIndex);
Mockito.verify(validators.get(0)).validate(refIndex, targetIndex1, ctx);
Mockito.verify(validators.get(0)).validate(refIndex, targetIndex2, ctx);
Mockito.verify(validators.get(0)).validate(refIndex, targetIndex3, ctx);
Mockito.verify(validators.get(1)).validate(refIndex, targetIndex1, ctx);
Mockito.verify(validators.get(1)).validate(refIndex, targetIndex2, ctx);
Mockito.verify(validators.get(1)).validate(refIndex, targetIndex3, ctx);
}
@Test
public void redundantDbObjectsAreNoticed()
{
Mockito.when(comparisonUtils.findEquivalentObjects(refSchema, refIndex)).
thenReturn(Arrays.asList((DbObject) targetIndex1, targetIndex2, targetIndex3));
// Validate all instances of the target schema's indexes that are equivalent to this index
visitor.visit(refIndex);
assertEquals(1, ctx.getComparisonResults().size());
assertEquals(RedundantDbObject.class, ctx.getComparisonResults().get(0).getClass());
}
@Test
public void nonRedundantDbObjectsAreNoticed()
{
Mockito.when(comparisonUtils.findEquivalentObjects(refSchema, refIndex)).
thenReturn(Arrays.asList((DbObject) targetIndex1));
// Validate all instances of the target schema's indexes that are equivalent to this index
visitor.visit(refIndex);
assertEquals(0, ctx.getComparisonResults().size());
}
}

View File

@@ -1,59 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.alfresco.util.schemacomp.model.Index;
import org.junit.Before;
import org.junit.Test;
import org.springframework.extensions.surf.util.I18NUtil;
/**
* Tests for the {@link ValidationResult} class.
*
* @author Matt Ward
*/
public class ValidationResultTest
{
@Before
public void setUp()
{
I18NUtil.registerResourceBundle("alfresco.messages.system-messages");
}
@Test
public void describe()
{
DbProperty targetDbProp = mock(DbProperty.class);
when(targetDbProp.getPath()).thenReturn("alfresco.some_table.idx_table_id.name");
when(targetDbProp.getPropertyValue()).thenReturn("idx_table_id");
when(targetDbProp.getDbObject()).thenReturn(new Index(""));
ValidationResult validation = new ValidationResult(targetDbProp, "value must be 'xyz'");
assertEquals("Validation: index alfresco.some_table.idx_table_id.name=\"idx_table_id\" fails to " +
"match rule: value must be 'xyz'",
validation.describe());
}
}

View File

@@ -1,143 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertNull;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.Iterator;
import org.alfresco.util.schemacomp.model.DbObject;
import org.alfresco.util.schemacomp.model.Index;
import org.alfresco.util.schemacomp.model.Schema;
import org.alfresco.util.schemacomp.model.Sequence;
import org.alfresco.util.schemacomp.model.Table;
import org.alfresco.util.schemacomp.validator.DbValidator;
import org.alfresco.util.schemacomp.validator.NameValidator;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/**
* Tests for the XMLToSchema class.
*
* @author Matt Ward
*/
public class XMLToSchemaTest
{
private XMLToSchema xmlToSchema;
private InputStream in;
@Before
public void setUp() throws Exception
{
Resource testFileResource = new ClassPathResource("schemacomp/xml_to_schema_test.xml");
in = new BufferedInputStream(testFileResource.getInputStream());
xmlToSchema = new XMLToSchema(in);
}
@Test
public void canReadSchemaXML()
{
xmlToSchema.parse();
Schema schema = xmlToSchema.getSchema();
assertNotNull("A null Schema object was returned", schema);
assertNull("Schema isn't meant to have a parent", schema.getParent());
assertEquals("alfresco", schema.getName());
assertEquals("myprefix_", schema.getDbPrefix());
assertEquals(325, schema.getVersion());
Iterator<DbObject> objects = schema.iterator();
Table table = (Table) objects.next();
assertSame("Wrong or no parent set on table", schema, table.getParent());
assertEquals("node", table.getName());
assertEquals(3, table.getColumns().size());
assertSame("Wrong or no parent set", table, table.getColumns().get(0).getParent());
assertEquals("id", table.getColumns().get(0).getName());
assertEquals("NUMBER(10)", table.getColumns().get(0).getType());
assertEquals(false, table.getColumns().get(0).isNullable());
assertEquals(1, table.getColumns().get(0).getOrder());
assertEquals(true, table.getColumns().get(0).isAutoIncrement());
assertSame("Wrong or no parent set", table, table.getColumns().get(1).getParent());
assertEquals("nodeRef", table.getColumns().get(1).getName());
assertEquals("VARCHAR2(200)", table.getColumns().get(1).getType());
assertEquals(false, table.getColumns().get(1).isNullable());
assertEquals(3, table.getColumns().get(1).getOrder());
assertEquals(false, table.getColumns().get(1).isAutoIncrement());
assertSame("Wrong or no parent set", table, table.getColumns().get(2).getParent());
assertEquals("name", table.getColumns().get(2).getName());
assertEquals("VARCHAR2(150)", table.getColumns().get(2).getType());
assertEquals(true, table.getColumns().get(2).isNullable());
assertEquals(2, table.getColumns().get(2).getOrder());
assertEquals(false, table.getColumns().get(2).isAutoIncrement());
assertSame("Wrong or no parent set", table, table.getPrimaryKey().getParent());
assertEquals("pk_node", table.getPrimaryKey().getName());
assertEquals(1, table.getPrimaryKey().getColumnNames().size());
assertEquals("id", table.getPrimaryKey().getColumnNames().get(0));
assertEquals(1, table.getPrimaryKey().getColumnOrders().get(0).intValue());
assertEquals(1, table.getForeignKeys().size());
assertSame("Wrong or no parent set", table, table.getForeignKeys().get(0).getParent());
assertEquals("fk_node_noderef", table.getForeignKeys().get(0).getName());
assertEquals("nodeRef", table.getForeignKeys().get(0).getLocalColumn());
assertEquals("node", table.getForeignKeys().get(0).getTargetTable());
assertEquals("nodeRef", table.getForeignKeys().get(0).getTargetColumn());
assertEquals(1, table.getIndexes().size());
Index index = table.getIndexes().get(0);
assertSame("Wrong or no parent set on index", table, index.getParent());
assertEquals("idx_node_by_id", index.getName());
assertEquals(true, index.isUnique());
assertEquals(2, index.getColumnNames().size());
assertEquals("id", index.getColumnNames().get(0));
assertEquals("nodeRef", index.getColumnNames().get(1));
assertEquals(1, index.getValidators().size());
DbValidator validator = index.getValidators().get(0);
assertEquals(NameValidator.class, validator.getClass());
assertEquals(1, validator.getPropertyNames().size());
assertEquals("idx_.+", validator.getProperty("pattern"));
Sequence seq = (Sequence) objects.next();
assertSame("Wrong or no parent set", schema, seq.getParent());
assertEquals("node_seq", seq.getName());
seq = (Sequence) objects.next();
assertSame("Wrong or no parent set", schema, seq.getParent());
assertEquals("person_seq", seq.getName());
seq = (Sequence) objects.next();
assertSame("Wrong or no parent set", schema, seq.getParent());
assertEquals("content_seq", seq.getName());
assertFalse("Should be no more DB objects", objects.hasNext());
}
}

View File

@@ -1,192 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.inOrder;
import java.util.Arrays;
import java.util.List;
import org.alfresco.util.schemacomp.DbObjectVisitor;
import org.alfresco.util.schemacomp.DbProperty;
import org.alfresco.util.schemacomp.DiffContext;
import org.alfresco.util.schemacomp.Difference.Where;
import org.alfresco.util.schemacomp.Results;
import org.alfresco.util.schemacomp.validator.AbstractDbValidator;
import org.alfresco.util.schemacomp.validator.DbValidator;
import org.hibernate.dialect.Dialect;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Tests for the AbstractDbObject base class.
*
* @author Matt Ward
*/
@RunWith(MockitoJUnitRunner.class)
public class AbstractDbObjectTest
{
private ConcreteDbObject dbObject;
private @Mock Results differences;
private DiffContext ctx;
private @Mock Dialect dialect;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
dbObject = new ConcreteDbObject("the_object");
ctx = new DiffContext(dialect, differences, null, null);
}
@Test
public void sameAs()
{
dbObject.setName(null);
assertFalse("Not the same.", dbObject.sameAs(null));
assertFalse("Not the same.", dbObject.sameAs(new ConcreteDbObject("other_obj_name")));
assertTrue("The very same", dbObject.sameAs(dbObject));
dbObject.setName("the_name");
assertFalse("Not the same.", dbObject.sameAs(null));
assertFalse("Not the same.", dbObject.sameAs(new ConcreteDbObject("different_name")));
assertFalse("Not the same type", dbObject.sameAs(new AnotherConcreteDbObject("the_name")));
assertTrue("Logically the same object.", dbObject.sameAs(new ConcreteDbObject("the_name")));
assertTrue("The very same object with non-null name", dbObject.sameAs(dbObject));
}
@Test
public void diff()
{
ConcreteDbObject otherObject = new ConcreteDbObject("the_other_object");
dbObject.diff(otherObject, ctx);
InOrder inOrder = inOrder(differences);
// The name of the object should be diffed
inOrder.verify(differences).add(
Where.IN_BOTH_BUT_DIFFERENCE,
new DbProperty(dbObject, "name"),
new DbProperty(otherObject, "name"));
// Then the doDiff() method should be processed
inOrder.verify(differences).add(
Where.IN_BOTH_BUT_DIFFERENCE,
new DbProperty(dbObject, "someProp"),
new DbProperty(otherObject, "someProp"));
}
@Test
public void canGetValidators()
{
List<DbValidator> validators = dbObject.getValidators();
assertEquals(0, validators.size());
dbObject.setValidators(null);
validators = dbObject.getValidators();
assertEquals(0, validators.size());
dbObject.setValidators(validatorList(new TestValidator1(), new TestValidator2()));
validators = dbObject.getValidators();
assertEquals(2, validators.size());
assertEquals(TestValidator1.class, validators.get(0).getClass());
assertEquals(TestValidator2.class, validators.get(1).getClass());
}
/**
* Concrete DbObject for testing the AbstractDbObject base class.
*/
public static class ConcreteDbObject extends AbstractDbObject
{
private String someProp = "property value";
public ConcreteDbObject(String name)
{
super(null, name);
}
@Override
protected void doDiff(DbObject right, DiffContext ctx)
{
Results differences = ctx.getComparisonResults();
differences.add(
Where.IN_BOTH_BUT_DIFFERENCE,
new DbProperty(this, "someProp"),
new DbProperty(right, "someProp"));
}
@Override
public void accept(DbObjectVisitor visitor)
{
}
public String getSomeProp()
{
return this.someProp;
}
}
public static class AnotherConcreteDbObject extends AbstractDbObject
{
public AnotherConcreteDbObject(String name)
{
super(null, name);
}
@Override
public void accept(DbObjectVisitor visitor)
{
}
}
private List<DbValidator> validatorList(DbValidator... validators)
{
return Arrays.asList(validators);
}
private static class TestValidator extends AbstractDbValidator
{
@Override
public void validate(DbObject reference, DbObject target, DiffContext ctx)
{
}
}
private static class TestValidator1 extends TestValidator
{
}
private static class TestValidator2 extends TestValidator
{
}
}

View File

@@ -1,104 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.model;
import org.alfresco.util.schemacomp.DbProperty;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
/**
* Tests for the Column class.
* @author Matt Ward
*/
public class ColumnTest extends DbObjectTestBase<Column>
{
private Column thisColumn;
private Column thatColumn;
@Before
public void setUp() throws Exception
{
thisColumn = new Column(null, "this_column", "VARCHAR2(100)", false);
thatColumn = new Column(null, "that_column", "NUMBER(10)", true);
}
@Override
protected Column getThisObject()
{
return thisColumn;
}
@Override
protected Column getThatObject()
{
return thatColumn;
}
@Override
protected void doDiffTests()
{
DbProperty thisTypeProp = new DbProperty(thisColumn, "type");
DbProperty thatTypeProp = new DbProperty(thatColumn, "type");
inOrder.verify(comparisonUtils).compareSimple(thisTypeProp, thatTypeProp, ctx);
DbProperty thisNullableProp = new DbProperty(thisColumn, "nullable");
DbProperty thatNullableProp = new DbProperty(thatColumn, "nullable");
inOrder.verify(comparisonUtils).compareSimple(thisNullableProp, thatNullableProp, ctx);
DbProperty thisOrderProp = new DbProperty(thisColumn, "order");
DbProperty thatOrderProp = new DbProperty(thatColumn, "order");
inOrder.verify(comparisonUtils).compareSimple(thisOrderProp, thatOrderProp, ctx);
DbProperty thisAutoIncProp = new DbProperty(thisColumn, "autoIncrement");
DbProperty thatAutoIncProp = new DbProperty(thatColumn, "autoIncrement");
inOrder.verify(comparisonUtils).compareSimple(thisAutoIncProp, thatAutoIncProp, ctx);
}
@Test
public void acceptVisitor()
{
thisColumn.accept(visitor);
verify(visitor).visit(thisColumn);
}
@Test
public void sameAs()
{
Table thisTable = new Table("the_table");
thisColumn = new Column(thisTable, "this_column", "VARCHAR2(100)", false);
Table thatTable = new Table("the_table");
thatColumn = new Column(thatTable, "this_column", "VARCHAR2(100)", false);
// This column, whilst having the same name as thisColumn, has a different
// parent table - and so is not considered 'the same'.
Table anotherTable = new Table("another_table");
Column anotherColumn = new Column(anotherTable, "this_column", "VARCHAR2(100)", false);
assertTrue("Column should always be the same as itself", thisColumn.sameAs(thisColumn));
assertTrue("Columns should be the same due to same parent table names", thisColumn.sameAs(thatColumn));
assertFalse("Should NOT be the same due to different parent table names", thisColumn.sameAs(anotherColumn));
}
}

View File

@@ -1,102 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.model;
import static org.mockito.Mockito.inOrder;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.util.schemacomp.ComparisonUtils;
import org.alfresco.util.schemacomp.DbObjectVisitor;
import org.alfresco.util.schemacomp.DbProperty;
import org.alfresco.util.schemacomp.DiffContext;
import org.alfresco.util.schemacomp.Results;
import org.hibernate.dialect.Dialect;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Abstract base class for tests for AbstractDbObject subclasses.
*
* @author Matt Ward
*/
@RunWith(MockitoJUnitRunner.class)
public abstract class DbObjectTestBase<T extends AbstractDbObject>
{
protected @Mock Dialect dialect;
protected @Mock Results differences;
protected DiffContext ctx;
protected @Mock ComparisonUtils comparisonUtils;
protected InOrder inOrder;
protected abstract T getThisObject();
protected abstract T getThatObject();
protected @Mock DbObjectVisitor visitor;
@Before
public final void baseSetUp()
{
// Check that the correct calls happened in the correct order.
List<Object> mocks = getMocksUsedInDiff();
inOrder = inOrder(mocks.toArray());
ctx = new DiffContext(dialect, differences, null, null);
}
/**
* Override to add additional mocks to the InOrder call verification.
*
* @return List<Object>
*/
protected List<Object> getMocksUsedInDiff()
{
List<Object> objects = new ArrayList<Object>();
objects.add(differences);
objects.add(comparisonUtils);
return objects;
}
@Test
public void canDiffObjects()
{
AbstractDbObject thisObject = getThisObject();
thisObject.setComparisonUtils(comparisonUtils);
AbstractDbObject thatObject = getThatObject();
thatObject.setComparisonUtils(comparisonUtils);
// Invoke the method under test
thisObject.diff(thatObject, ctx);
// The name of the object should be diffed
inOrder.verify(comparisonUtils).compareSimple(
new DbProperty(thisObject, "name"),
new DbProperty(thatObject, "name"),
ctx);
// Then the doDiff() method should be processed...
doDiffTests();
}
protected abstract void doDiffTests();
}

View File

@@ -1,127 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.model;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import org.alfresco.util.schemacomp.DbProperty;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the ForeignKey class.
*
* @author Matt Ward
*/
public class ForeignKeyTest extends DbObjectTestBase<ForeignKey>
{
private ForeignKey thisFK, thatFK;
private Table parent;
@Before
public void setUp() throws Exception
{
parent = new Table("parent");
thisFK = new ForeignKey(null, "this_fk", "local_col", "target_table", "target_col");
thatFK = new ForeignKey(null, "that_fk", "local_col", "target_table", "target_col");
}
@Override
protected ForeignKey getThisObject()
{
return thisFK;
}
@Override
protected ForeignKey getThatObject()
{
return thatFK;
}
@Override
protected void doDiffTests()
{
inOrder.verify(comparisonUtils).compareSimple(
new DbProperty(thisFK, "localColumn"),
new DbProperty(thatFK, "localColumn"),
ctx);
inOrder.verify(comparisonUtils).compareSimple(
new DbProperty(thisFK, "targetTable"),
new DbProperty(thatFK, "targetTable"),
ctx);
inOrder.verify(comparisonUtils).compareSimple(
new DbProperty(thisFK, "targetColumn"),
new DbProperty(thatFK, "targetColumn"),
ctx);
}
@Test
public void acceptVisitor()
{
thisFK.accept(visitor);
verify(visitor).visit(thisFK);
}
@Test
public void sameAs()
{
// FKs are the same if they have all the same properties
thisFK = new ForeignKey(parent, "the_fk", "local_col", "target_table", "target_col");
thatFK = new ForeignKey(parent, "the_fk", "local_col", "target_table", "target_col");
assertTrue("FKs should be considered the same", thisFK.sameAs(thatFK));
// FKs are the same even if they have different names (but all other properties are the same)
thisFK = new ForeignKey(parent, "the_fk", "local_col", "target_table", "target_col");
thatFK = new ForeignKey(parent, "different_name", "local_col", "target_table", "target_col");
assertTrue("FKs should be considered the same", thisFK.sameAs(thatFK));
// Two references to the same FK are the same of course
assertTrue("FKs should be considered the same", thisFK.sameAs(thisFK));
// A null is never the same
assertFalse("FKs should be considered the different", thisFK.sameAs(null));
thisFK = new ForeignKey(parent, "the_fk", "local_col", "target_table", "target_col");
thatFK = new ForeignKey(new Table("different_parent"), "the_fk", "local_col", "target_table", "target_col");
assertFalse("FKs should be different: parents are different.", thisFK.sameAs(thatFK));
thisFK = new ForeignKey(parent, "the_fk", "local_col", "target_table", "target_col");
thatFK = new ForeignKey(parent, "the_fk", "local_col2", "target_table", "target_col");
assertFalse("FKs have different local columns.", thisFK.sameAs(thatFK));
thisFK = new ForeignKey(parent, "the_fk", "local_col", "target_table", "target_col");
thatFK = new ForeignKey(parent, "the_fk", "local_col", "target_table2", "target_col");
assertFalse("FKs have different target table.", thisFK.sameAs(thatFK));
thisFK = new ForeignKey(parent, "the_fk", "local_col", "target_table", "target_col");
thatFK = new ForeignKey(parent, "the_fk", "local_col", "target_table", "target_col2");
assertFalse("FKs have different target column.", thisFK.sameAs(thatFK));
// ALF-14129 fix test
thisFK = new ForeignKey(parent, "the_fk", "local_col", "target_table", "target_col");
thatFK = new ForeignKey(parent, "the_fk", "local_col", "TARGET_TABLE", "target_col");
assertTrue("FKs are case sensitive to targetTable's name.", thisFK.sameAs(thatFK));
}
}

View File

@@ -1,109 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.model;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import java.util.Arrays;
import org.alfresco.util.schemacomp.DbProperty;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the Index class.
* @author Matt Ward
*/
public class IndexTest extends DbObjectTestBase<Index>
{
private Table thisTable;
private Index thisIndex;
private Table thatTable;
private Index thatIndex;
@Before
public void setUp()
{
thisTable = new Table("this_table");
thisIndex = new Index(thisTable, "this_index", Arrays.asList("id", "name", "age"));
thatTable = new Table("that_table");
thatIndex = new Index(thatTable, "that_index", Arrays.asList("a", "b"));
}
@Override
protected Index getThisObject()
{
return thisIndex;
}
@Override
protected Index getThatObject()
{
return thatIndex;
}
@Override
protected void doDiffTests()
{
inOrder.verify(comparisonUtils).compareSimpleOrderedLists(
new DbProperty(thisIndex, "columnNames"),
new DbProperty(thatIndex, "columnNames"),
ctx);
inOrder.verify(comparisonUtils).compareSimple(
new DbProperty(thisIndex, "unique"),
new DbProperty(thatIndex, "unique"),
ctx);
}
@Test
public void sameAs()
{
assertTrue("Indexes should be logically the same.",
thisIndex.sameAs(new Index(thisTable, "this_index", Arrays.asList("id", "name", "age"))));
assertFalse("Indexes have logically different parents",
thisIndex.sameAs(new Index(thatTable, "this_index", Arrays.asList("id", "name", "age"))));
assertTrue("Indexes should be logically the same, despite different names (as same column order)",
thisIndex.sameAs(new Index(thisTable, "different_name", Arrays.asList("id", "name", "age"))));
assertTrue("Indexes should be identified as the same despite different column order (as same name).",
thisIndex.sameAs(new Index(thisTable, "this_index", Arrays.asList("name", "id", "age"))));
assertFalse("Indexes should be identified different (different name and column order)",
thisIndex.sameAs(new Index(thisTable, "different_name", Arrays.asList("name", "id", "age"))));
assertFalse("Indexes should be identified different (different name & different columns)",
thisIndex.sameAs(new Index(thisTable, "different_name", Arrays.asList("node_ref", "url"))));
}
@Test
public void acceptVisitor()
{
thisIndex.accept(visitor);
verify(visitor).visit(thisIndex);
}
}

View File

@@ -1,44 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.model;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* Test suite for all the model tests.
*
* @author Matt Ward
*/
@RunWith(Suite.class)
@Suite.SuiteClasses(
{
AbstractDbObjectTest.class,
ColumnTest.class,
ForeignKeyTest.class,
IndexTest.class,
PrimaryKeyTest.class,
SchemaTest.class,
SequenceTest.class,
TableTest.class
})
public class ModelTestSuite
{
// Suite defined by annotation above.
}

View File

@@ -1,149 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.model;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import java.util.Arrays;
import java.util.List;
import org.alfresco.util.schemacomp.DbProperty;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the PrimaryKey class.
*
* @author Matt Ward
*/
public class PrimaryKeyTest extends DbObjectTestBase<PrimaryKey>
{
private PrimaryKey thisPK;
private PrimaryKey thatPK;
private Table parent;
@Before
public void setUp()
{
parent = new Table("parent_table");
thisPK = new PrimaryKey(
parent,
"this_pk",
columns("id", "name", "age"),
columnOrders(2, 1, 3));
thatPK = new PrimaryKey(
parent,
"that_pk",
columns("a", "b"),
columnOrders(1, 2));
}
@Override
protected PrimaryKey getThisObject()
{
return thisPK;
}
@Override
protected PrimaryKey getThatObject()
{
return thatPK;
}
@Override
protected void doDiffTests()
{
inOrder.verify(comparisonUtils).compareSimpleOrderedLists(
new DbProperty(thisPK, "columnNames"),
new DbProperty(thatPK, "columnNames"),
ctx);
inOrder.verify(comparisonUtils).compareSimpleOrderedLists(
new DbProperty(thisPK, "columnOrders"),
new DbProperty(thatPK, "columnOrders"),
ctx);
}
@Test
public void acceptVisitor()
{
thisPK.accept(visitor);
verify(visitor).visit(thisPK);
}
@Test
public void sameAs()
{
// Same parent, same name, same columns and ordering - must be same (intended) PK
assertTrue("Primary keys should be logically equivalent",
thisPK.sameAs(
new PrimaryKey(
parent,
"this_pk",
columns("id", "name", "age"),
columnOrders(2, 1, 3))));
// Different names - still the same PK
assertTrue("Primary keys should be logically equivalent",
thisPK.sameAs(
new PrimaryKey(parent, "different_name",
columns("id", "name", "age"),
columnOrders(2, 1, 3))));
// Same object reference ("physically" same object)
assertTrue("PKs should be the same", thisPK.sameAs(thisPK));
// Same parent, same type, but different everything else!
assertTrue("Primary keys should be logically equivalent",
thisPK.sameAs(
new PrimaryKey(parent, "different_name",
columns("di", "eman", "ega"),
columnOrders(1, 2, 3))));
// Same parent, but different type
assertFalse("PKs are never the same as a non-PK",
thisPK.sameAs(new Index(parent, "wrong_type", columns())));
// Different parents
Table otherParent = new Table("other_parent");
assertFalse("PKs should be considered different (different parents)",
thisPK.sameAs(
new PrimaryKey(otherParent, "this_pk",
columns("id", "name", "age"),
columnOrders(2, 1, 3))));
// Other PK is null
assertFalse("PKs should not be considered the same (other PK is null)",
thisPK.sameAs(null));
}
private List<String> columns(String... columns)
{
return Arrays.asList(columns);
}
private List<Integer> columnOrders(Integer... columnOrders)
{
return Arrays.asList(columnOrders);
}
}

View File

@@ -1,109 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.model;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import org.alfresco.util.schemacomp.DbProperty;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Tests for the Schema class.
*
* @author Matt Ward
*/
@RunWith(MockitoJUnitRunner.class)
public class SchemaTest extends DbObjectTestBase<Schema>
{
private Schema left;
private Schema right;
@Before
public void setUp()
{
left = new Schema("left_schema");
right = new Schema("right_schema");
}
@Override
protected Schema getThisObject()
{
return left;
}
@Override
protected Schema getThatObject()
{
return right;
}
@Override
protected void doDiffTests()
{
// We need to be warned if comparing, for example a version 500 schema with a
// version 501 schema.
inOrder.verify(comparisonUtils).compareSimple(
new DbProperty(left, "version"),
new DbProperty(right, "version"),
ctx);
// In addition to the base class functionality, Schema.diff() compares
// the DbObjects held in the other schema with its own DbObjects.
inOrder.verify(comparisonUtils).compareCollections(left.objects, right.objects, ctx);
}
@Test
public void acceptVisitor()
{
DbObject dbo1 = Mockito.mock(DbObject.class);
left.add(dbo1);
DbObject dbo2 = Mockito.mock(DbObject.class);
left.add(dbo2);
DbObject dbo3 = Mockito.mock(DbObject.class);
left.add(dbo3);
left.accept(visitor);
verify(dbo1).accept(visitor);
verify(dbo2).accept(visitor);
verify(dbo3).accept(visitor);
verify(visitor).visit(left);
}
@Test
public void sameAs()
{
// We have to assume that two schemas are always the same, regardless of name,
// otherwise unless the reference schema has the same name as the target database
// all the comparisons will fail - and users can choose to install databases with any schema
// name they choose.
assertTrue("Schemas should be considered the same", left.sameAs(right));
// Things are always the same as themselves.
assertTrue("Schemas are the same physical object", left.sameAs(left));
assertFalse("A table is not the same as a schema", left.sameAs(new Table("left_schema")));
assertFalse("null is not the same as a schema", left.sameAs(null));
}
}

View File

@@ -1,67 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.model;
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the Sequence class.
* @author Matt Ward
*/
public class SequenceTest extends DbObjectTestBase<Sequence>
{
private Sequence thisSequence;
private Sequence thatSequence;
@Before
public void setUp()
{
thisSequence = new Sequence(null, "this_sequence");
thatSequence = new Sequence(null, "that_sequence");
}
@Test
public void acceptVisitor()
{
thisSequence.accept(visitor);
verify(visitor).visit(thisSequence);
}
@Override
protected Sequence getThisObject()
{
return thisSequence;
}
@Override
protected Sequence getThatObject()
{
return thatSequence;
}
@Override
protected void doDiffTests()
{
// Nothing extra to diff.
}
}

View File

@@ -1,135 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.model;
import static org.mockito.Mockito.verify;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Tests for the Table class.
*
* @author Matt Ward
*/
@RunWith(MockitoJUnitRunner.class)
public class TableTest extends DbObjectTestBase<Table>
{
private Table table;
private Table otherTable;
private List<Column> columns;
private @Mock PrimaryKey primaryKey;
private List<ForeignKey> foreignKeys;
private List<Index> indexes;
@Before
public void setUp() throws Exception
{
columns = listOfMocks(Column.class, 3);
foreignKeys = listOfMocks(ForeignKey.class, 1);
indexes = listOfMocks(Index.class, 1);
table = new Table(null, "the_table", columns, primaryKey, foreignKeys, indexes);
otherTable = new Table(null, "the_other_table", columns, primaryKey, foreignKeys, indexes);
}
private <T> List<T> listOfMocks(Class<T> c, int size)
{
List<T> list = new ArrayList<T>(size);
for (int i = 0; i < size; i++)
{
list.add((T) Mockito.mock(c));
}
return list;
}
@Override
protected List<Object> getMocksUsedInDiff()
{
List<Object> mocks = super.getMocksUsedInDiff();
mocks.add(primaryKey);
return mocks;
}
public void doDiffTests()
{
// Check columns
inOrder.verify(comparisonUtils).compareCollections(table.getColumns(), otherTable.getColumns(), ctx);
// Check primary key
inOrder.verify(primaryKey).diff(otherTable.getPrimaryKey(), ctx);
// Check foreign keys
inOrder.verify(comparisonUtils).compareCollections(
table.getForeignKeys(), otherTable.getForeignKeys(), ctx);
// Check indexes
inOrder.verify(comparisonUtils).compareCollections(
table.getIndexes(), otherTable.getIndexes(), ctx);
}
@Override
protected Table getThisObject()
{
return table;
}
@Override
protected Table getThatObject()
{
return otherTable;
}
@Test
public void acceptVisitor()
{
table.setColumns(columns);
table.setForeignKeys(foreignKeys);
table.setIndexes(indexes);
table.setPrimaryKey(primaryKey);
table.accept(visitor);
// All the children should be visited
List<DbObject> children = new ArrayList<DbObject>();
children.addAll(columns);
children.addAll(foreignKeys);
children.addAll(indexes);
children.add(primaryKey);
for (DbObject child : children)
{
verify(child).accept(visitor);
}
// The parent itself should be visited
verify(visitor).visit(table);
}
}

View File

@@ -1,124 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.test.exportdb;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import org.alfresco.util.schemacomp.ExportDb;
import org.alfresco.util.schemacomp.ExportDbTest;
import org.alfresco.util.schemacomp.model.DbObject;
import org.alfresco.util.schemacomp.model.Schema;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
/**
* Base class for DBMS-specific ExportDb tests.
*
* @see ExportDbTest
* @author Matt Ward
*/
public abstract class AbstractExportTester
{
protected ExportDb exporter;
protected PlatformTransactionManager tx;
protected SimpleJdbcTemplate jdbcTemplate;
private final static Log log = LogFactory.getLog(AbstractExportTester.class);
public AbstractExportTester(ExportDb exporter, PlatformTransactionManager tx, SimpleJdbcTemplate jdbcTemplate)
{
this.exporter = exporter;
this.tx = tx;
this.jdbcTemplate = jdbcTemplate;
}
protected abstract void doExportTest() throws Exception;
protected abstract void doDatabaseSetup();
public void runExportTest() throws Exception
{
doDatabaseSetup();
exporter.execute();
// Log the schema for diagnostics
dumpSchema();
commonPostExportChecks();
doExportTest();
}
/**
* Common checks that do not need to be coded into every test implementation.
* May be overridden if required.
*/
protected void commonPostExportChecks()
{
Schema schema = getSchema();
assertNull("Schema shouldn't have a parent", getSchema().getParent());
checkResultsFiltered(schema, "export_test_");
}
public Schema getSchema()
{
return exporter.getSchema();
}
/**
* Check that all top level database objects are prefixed as expected
* (no other objects should have been retrieved)
*
* @param schema
* @param prefix
*/
protected void checkResultsFiltered(Schema schema, String prefix)
{
for (DbObject dbo : schema)
{
if (!dbo.getName().startsWith(prefix))
{
fail("Database object's name does not start with '" + prefix + "': " + dbo);
}
}
}
private void dumpSchema()
{
if (log.isDebugEnabled())
{
log.debug("Iterating through Schema objects:");
}
int i = 0;
for (DbObject dbo : getSchema())
{
i++;
if (log.isDebugEnabled())
{
// Log the object's toString() - indented for clarity.
log.debug(" " + dbo);
}
}
if (log.isDebugEnabled())
{
log.debug("Schema object contains " + i + " objects.");
}
}
}

View File

@@ -1,304 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.test.exportdb;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.util.Iterator;
import org.alfresco.util.schemacomp.ExportDb;
import org.alfresco.util.schemacomp.ExportDbTest;
import org.alfresco.util.schemacomp.model.Column;
import org.alfresco.util.schemacomp.model.DbObject;
import org.alfresco.util.schemacomp.model.ForeignKey;
import org.alfresco.util.schemacomp.model.Index;
import org.alfresco.util.schemacomp.model.PrimaryKey;
import org.alfresco.util.schemacomp.model.Schema;
import org.alfresco.util.schemacomp.model.Table;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
/**
* MySQL specific test for the ExportDb class.
*
* @see ExportDbTest
* @author Matt Ward
*/
public class MySQLDialectExportTester extends AbstractExportTester
{
/**
* Constructor.
*
* @param exporter
* @param tx
* @param jdbcTemplate
*/
public MySQLDialectExportTester(ExportDb exporter, PlatformTransactionManager tx,
SimpleJdbcTemplate jdbcTemplate)
{
super(exporter, tx, jdbcTemplate);
}
@Override
protected void doExportTest() throws Exception
{
Schema schema = getSchema();
Table exampleTable = null;
Table otherTable = null;
for (DbObject dbo : schema)
{
if (dbo.getName().equals("export_test_example"))
{
exampleTable = (Table) dbo;
}
if (dbo.getName().equals("export_test_other"))
{
otherTable = (Table) dbo;
}
}
checkExampleTable(schema, exampleTable);
checkOtherTable(schema, otherTable);
}
private void checkOtherTable(Schema schema, Table otherTable)
{
assertNotNull("Couldn't find table export_test_other", otherTable);
assertSame("Incorrect parent or no parent set", schema, otherTable.getParent());
Iterator<Column> colIt = otherTable.getColumns().iterator();
Column col = colIt.next();
assertSame("Incorrect parent or no parent set", otherTable, col.getParent());
assertEquals("id", col.getName());
assertEquals("bigint", col.getType());
assertEquals(false, col.isNullable());
assertEquals(1, col.getOrder());
assertEquals(false, col.isAutoIncrement());
col = colIt.next();
assertSame("Incorrect parent or no parent set", otherTable, col.getParent());
assertEquals("version", col.getName());
assertEquals("bigint", col.getType());
assertEquals(false, col.isNullable());
assertEquals(2, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", otherTable, col.getParent());
assertEquals("ex_id", col.getName());
assertEquals("bigint", col.getType());
assertEquals(false, col.isNullable());
assertEquals(3, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", otherTable, col.getParent());
assertSame("Incorrect parent or no parent set", otherTable, col.getParent());
assertEquals("local_name", col.getName());
assertEquals("varchar(200)", col.getType());
assertEquals(false, col.isNullable());
assertEquals(4, col.getOrder());
assertEquals(2, otherTable.getIndexes().size());
Iterator<Index> indexIt = otherTable.getIndexes().iterator();
Index index = indexIt.next();
assertSame("Incorrect parent or no parent set", otherTable, index.getParent());
assertEquals("export_test_idx_other_1", index.getName());
assertEquals(true, index.isUnique());
assertEquals(2, index.getColumnNames().size());
assertEquals("ex_id", index.getColumnNames().get(0));
assertEquals("local_name", index.getColumnNames().get(1));
index = indexIt.next();
assertSame("Incorrect parent or no parent set", otherTable, index.getParent());
assertEquals("export_test_idx_other_2", index.getName());
assertEquals(1, index.getColumnNames().size());
assertEquals("ex_id", index.getColumnNames().get(0));
PrimaryKey pk = otherTable.getPrimaryKey();
assertSame("Incorrect parent or no parent set", otherTable, pk.getParent());
assertEquals("id", pk.getColumnNames().get(0));
assertEquals(1, pk.getColumnOrders().get(0).intValue());
assertEquals(1, otherTable.getForeignKeys().size());
ForeignKey fk = otherTable.getForeignKeys().get(0);
assertSame("Incorrect parent or no parent set", otherTable, fk.getParent());
assertEquals("export_test_fk_example", fk.getName());
assertEquals("ex_id", fk.getLocalColumn());
assertEquals("export_test_example", fk.getTargetTable());
assertEquals("id", fk.getTargetColumn());
}
private void checkExampleTable(Schema schema, Table exampleTable)
{
assertNotNull("Couldn't find export_test_example", exampleTable);
assertSame("Incorrect parent or no parent set", schema, exampleTable.getParent());
assertEquals("export_test_example", exampleTable.getName());
Iterator<Column> colIt = exampleTable.getColumns().iterator();
Column col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("id", col.getName());
assertEquals("bigint", col.getType());
assertEquals(false, col.isNullable());
assertEquals(1, col.getOrder());
assertEquals(true, col.isAutoIncrement());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("description", col.getName());
assertEquals("text", col.getType());
assertEquals(true, col.isNullable());
assertEquals(2, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("fixes_from_schema", col.getName());
assertEquals("int", col.getType());
assertEquals(true, col.isNullable());
assertEquals(3, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("fixes_to_schema", col.getName());
assertEquals("int", col.getType());
assertEquals(true, col.isNullable());
assertEquals(4, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("applied_to_schema", col.getName());
assertEquals("int", col.getType());
assertEquals(true, col.isNullable());
assertEquals(5, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("target_schema", col.getName());
assertEquals("int", col.getType());
assertEquals(true, col.isNullable());
assertEquals(6, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("applied_on_date", col.getName());
assertEquals("datetime", col.getType());
assertEquals(true, col.isNullable());
assertEquals(7, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("applied_to_server", col.getName());
assertEquals("varchar(64)", col.getType());
assertEquals(true, col.isNullable());
assertEquals(8, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("was_executed", col.getName());
assertEquals("bit", col.getType());
assertEquals(true, col.isNullable());
assertEquals(9, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("succeeded", col.getName());
assertEquals("bit", col.getType());
assertEquals(true, col.isNullable());
assertEquals(10, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("report", col.getName());
assertEquals("text", col.getType());
assertEquals(true, col.isNullable());
assertEquals(11, col.getOrder());
PrimaryKey pk = exampleTable.getPrimaryKey();
assertSame("Incorrect parent or no parent set", exampleTable, pk.getParent());
assertEquals("id", pk.getColumnNames().get(0));
assertEquals(1, pk.getColumnOrders().get(0).intValue());
}
@Override
protected void doDatabaseSetup()
{
// Create database objects: this decouples test code from the actual schema which is
// free to change without breaking these tests.
final String[] createStatements = new String[]
{
"DROP TABLE IF EXISTS export_test_other CASCADE",
"DROP TABLE IF EXISTS export_test_example CASCADE",
"CREATE TABLE export_test_example" +
" (" +
" id BIGINT NOT NULL AUTO_INCREMENT," +
" description TEXT," +
" fixes_from_schema INTEGER," +
" fixes_to_schema INTEGER," +
" applied_to_schema INTEGER," +
" target_schema INTEGER," +
" applied_on_date DATETIME," +
" applied_to_server VARCHAR(64)," +
" was_executed BIT," +
" succeeded BIT," +
" report TEXT," +
" PRIMARY KEY (id)" +
" ) ENGINE=InnoDB",
"CREATE TABLE export_test_other" +
" (" +
" id BIGINT NOT NULL," +
" version BIGINT NOT NULL," +
" ex_id BIGINT NOT NULL," +
" local_name VARCHAR(200) NOT NULL," +
" CONSTRAINT export_test_fk_example FOREIGN KEY (ex_id) REFERENCES export_test_example (id)," +
" PRIMARY KEY (id)" +
" ) ENGINE=InnoDB",
"CREATE UNIQUE INDEX export_test_idx_other_1 ON export_test_other (ex_id, local_name)",
"CREATE INDEX export_test_idx_other_2 ON export_test_other (ex_id)"
};
TransactionTemplate tt = new TransactionTemplate(tx);
tt.execute(new TransactionCallbackWithoutResult()
{
@Override
protected void doInTransactionWithoutResult(TransactionStatus status)
{
for (String sql : createStatements)
{
jdbcTemplate.update(sql);
}
}
});
}
}

View File

@@ -1,319 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.test.exportdb;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.util.Iterator;
import org.alfresco.util.schemacomp.ExportDb;
import org.alfresco.util.schemacomp.ExportDbTest;
import org.alfresco.util.schemacomp.model.Column;
import org.alfresco.util.schemacomp.model.DbObject;
import org.alfresco.util.schemacomp.model.ForeignKey;
import org.alfresco.util.schemacomp.model.Index;
import org.alfresco.util.schemacomp.model.PrimaryKey;
import org.alfresco.util.schemacomp.model.Schema;
import org.alfresco.util.schemacomp.model.Sequence;
import org.alfresco.util.schemacomp.model.Table;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
/**
* Test implementation for the PostgreSQL database dialect.
*
* @see ExportDbTest
* @author Matt Ward
*/
public class PostgreSQLDialectExportTester extends AbstractExportTester
{
/**
* Constructor.
*
* @param exporter
* @param jdbcTemplate
* @param tx
*/
public PostgreSQLDialectExportTester(ExportDb exporter, PlatformTransactionManager tx, SimpleJdbcTemplate jdbcTemplate)
{
super(exporter, tx, jdbcTemplate);
}
@Override
protected void doExportTest() throws Exception
{
Schema schema = getSchema();
Table exampleTable = null;
Table otherTable = null;
Sequence exampleSeq = null;
for (DbObject dbo : schema)
{
if (dbo.getName().equals("export_test_example"))
{
exampleTable = (Table) dbo;
}
if (dbo.getName().equals("export_test_other"))
{
otherTable = (Table) dbo;
}
if (dbo.getName().equals("export_test_example_seq"))
{
exampleSeq = (Sequence) dbo;
}
}
checkExampleTable(schema, exampleTable);
checkOtherTable(schema, otherTable);
checkExampleSequence(schema, exampleSeq);
}
private void checkOtherTable(Schema schema, Table otherTable)
{
assertNotNull("Couldn't find table export_test_other", otherTable);
assertSame("Incorrect parent or no parent set", schema, otherTable.getParent());
Iterator<Column> colIt = otherTable.getColumns().iterator();
Column col = colIt.next();
assertSame("Incorrect parent or no parent set", otherTable, col.getParent());
assertEquals("id", col.getName());
assertEquals("int8", col.getType());
assertEquals(false, col.isNullable());
assertEquals(1, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", otherTable, col.getParent());
assertEquals("version", col.getName());
assertEquals("int8", col.getType());
assertEquals(false, col.isNullable());
assertEquals(2, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", otherTable, col.getParent());
assertEquals("ex_id", col.getName());
assertEquals("int8", col.getType());
assertEquals(false, col.isNullable());
assertEquals(3, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", otherTable, col.getParent());
assertSame("Incorrect parent or no parent set", otherTable, col.getParent());
assertEquals("local_name", col.getName());
assertEquals("varchar(200)", col.getType());
assertEquals(false, col.isNullable());
assertEquals(4, col.getOrder());
assertEquals(2, otherTable.getIndexes().size());
Iterator<Index> indexIt = otherTable.getIndexes().iterator();
Index index = indexIt.next();
assertSame("Incorrect parent or no parent set", otherTable, index.getParent());
assertEquals("export_test_idx_other_1", index.getName());
assertEquals(true, index.isUnique());
assertEquals(2, index.getColumnNames().size());
assertEquals("ex_id", index.getColumnNames().get(0));
assertEquals("local_name", index.getColumnNames().get(1));
index = indexIt.next();
assertSame("Incorrect parent or no parent set", otherTable, index.getParent());
assertEquals("export_test_idx_other_2", index.getName());
assertEquals(1, index.getColumnNames().size());
assertEquals("ex_id", index.getColumnNames().get(0));
PrimaryKey pk = otherTable.getPrimaryKey();
assertSame("Incorrect parent or no parent set", otherTable, pk.getParent());
assertEquals("id", pk.getColumnNames().get(0));
assertEquals(1, pk.getColumnOrders().get(0).intValue());
assertEquals(1, otherTable.getForeignKeys().size());
ForeignKey fk = otherTable.getForeignKeys().get(0);
assertSame("Incorrect parent or no parent set", otherTable, fk.getParent());
assertEquals("export_test_fk_example", fk.getName());
assertEquals("ex_id", fk.getLocalColumn());
assertEquals("export_test_example", fk.getTargetTable());
assertEquals("id", fk.getTargetColumn());
}
private void checkExampleTable(Schema schema, Table exampleTable)
{
assertNotNull("Couldn't find export_test_example", exampleTable);
assertSame("Incorrect parent or no parent set", schema, exampleTable.getParent());
assertEquals("export_test_example", exampleTable.getName());
Iterator<Column> colIt = exampleTable.getColumns().iterator();
Column col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("id", col.getName());
assertEquals("int8", col.getType());
assertEquals(false, col.isNullable());
assertEquals(1, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("description", col.getName());
assertEquals("varchar(1024)", col.getType());
assertEquals(true, col.isNullable());
assertEquals(2, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("fixes_from_schema", col.getName());
assertEquals("int4", col.getType());
assertEquals(true, col.isNullable());
assertEquals(3, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("fixes_to_schema", col.getName());
assertEquals("int4", col.getType());
assertEquals(true, col.isNullable());
assertEquals(4, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("applied_to_schema", col.getName());
assertEquals("int4", col.getType());
assertEquals(true, col.isNullable());
assertEquals(5, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("target_schema", col.getName());
assertEquals("int4", col.getType());
assertEquals(true, col.isNullable());
assertEquals(6, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("applied_on_date", col.getName());
assertEquals("timestamp", col.getType());
assertEquals(true, col.isNullable());
assertEquals(7, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("applied_to_server", col.getName());
assertEquals("varchar(64)", col.getType());
assertEquals(true, col.isNullable());
assertEquals(8, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("was_executed", col.getName());
assertEquals("bool", col.getType());
assertEquals(true, col.isNullable());
assertEquals(9, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("succeeded", col.getName());
assertEquals("bool", col.getType());
assertEquals(true, col.isNullable());
assertEquals(10, col.getOrder());
col = colIt.next();
assertSame("Incorrect parent or no parent set", exampleTable, col.getParent());
assertEquals("report", col.getName());
assertEquals("varchar(1024)", col.getType());
assertEquals(true, col.isNullable());
assertEquals(11, col.getOrder());
PrimaryKey pk = exampleTable.getPrimaryKey();
assertSame("Incorrect parent or no parent set", exampleTable, pk.getParent());
assertEquals("id", pk.getColumnNames().get(0));
assertEquals(1, pk.getColumnOrders().get(0).intValue());
}
public void checkExampleSequence(Schema schema, Sequence seq)
{
assertNotNull("Couldn't find sequence", seq);
assertSame("Incorrect parent or no parent set", schema, seq.getParent());
assertEquals("export_test_example_seq", seq.getName());
}
@Override
protected void doDatabaseSetup()
{
// Create database objects: this decouples test code from the actual schema which is
// free to change without breaking these tests.
final String[] createStatements = new String[]
{
"DROP TABLE IF EXISTS export_test_example CASCADE",
"CREATE TABLE export_test_example" +
" (" +
" id INT8 NOT NULL," +
" description VARCHAR(1024)," +
" fixes_from_schema INT4," +
" fixes_to_schema INT4," +
" applied_to_schema INT4," +
" target_schema INT4," +
" applied_on_date TIMESTAMP," +
" applied_to_server VARCHAR(64)," +
" was_executed BOOL," +
" succeeded BOOL," +
" report VARCHAR(1024)," +
" PRIMARY KEY (id)" +
" )",
"DROP TABLE IF EXISTS export_test_other CASCADE",
"CREATE TABLE export_test_other" +
" (" +
" id INT8 NOT NULL," +
" version INT8 NOT NULL," +
" ex_id INT8 NOT NULL," +
" local_name VARCHAR(200) NOT NULL," +
" CONSTRAINT export_test_fk_example FOREIGN KEY (ex_id) REFERENCES export_test_example (id)," +
" PRIMARY KEY (id)" +
" )",
"DROP INDEX IF EXISTS export_test_idx_other_1",
"CREATE UNIQUE INDEX export_test_idx_other_1 ON export_test_other (ex_id, local_name)",
"DROP INDEX IF EXISTS export_test_idx_other_2",
"CREATE INDEX export_test_idx_other_2 ON export_test_other (ex_id)",
"DROP SEQUENCE IF EXISTS export_test_example_seq",
"CREATE SEQUENCE export_test_example_seq START WITH 1 INCREMENT BY 1"
};
TransactionTemplate tt = new TransactionTemplate(tx);
tt.execute(new TransactionCallbackWithoutResult()
{
@Override
protected void doInTransactionWithoutResult(TransactionStatus status)
{
for (String sql : createStatements)
{
jdbcTemplate.update(sql);
}
}
});
}
}

View File

@@ -0,0 +1,85 @@
package org.alfresco.util.schemacomp.validator;
import java.util.List;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.util.ParameterCheck;
import org.alfresco.util.schemacomp.DbProperty;
import org.alfresco.util.schemacomp.DiffContext;
import org.alfresco.util.schemacomp.ValidationResult;
import org.alfresco.util.schemacomp.model.DbObject;
import org.alfresco.util.schemacomp.model.Index;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.surf.util.I18NUtil;
/**
* Validates columns names in a Index using a regular expression pattern.
*
* @author pavel.yurkevich
*/
public class IndexColumnsValidator extends NameValidator
{
private final static Log log = LogFactory.getLog(IndexColumnsValidator.class);
@Override
public void validate(DbObject reference, DbObject target, DiffContext ctx)
{
if (!(target instanceof Index))
{
throw new AlfrescoRuntimeException("IndexColumnsValidator could be used only in context of index object but was: " + target.toString());
}
List<String> referenceColumnNames = ((Index)reference).getColumnNames();
List<String> targetColumnNames = ((Index)target).getColumnNames();
for (int i = 0; i < targetColumnNames.size(); i++)
{
String columnName = targetColumnNames.get(i);
if (getPattern() != null && !getPattern().matcher(columnName).matches())
{
if (log.isDebugEnabled())
{
log.debug("Pattern [" + getPattern() + "] not matched.");
}
String message = I18NUtil.getMessage("system.schema_comp.name_validator", getPattern());
ValidationResult result = new ValidationResult(new DbProperty(target, "columnNames", i), message);
ctx.getComparisonResults().add(result);
}
else
{
if (log.isDebugEnabled())
{
log.debug("Pattern [" + getPattern() + "] matched OK.");
}
}
}
if (targetColumnNames.size() != referenceColumnNames.size())
{
if (log.isDebugEnabled())
{
log.debug("Number of columns in index " + target.getName() + "doesn't match expected result");
}
String message = I18NUtil.getMessage("system.schema_comp.index_columns_validator", targetColumnNames.size(), referenceColumnNames.size());
ValidationResult result = new ValidationResult(new DbProperty(target, "columnNames"), message);
ctx.getComparisonResults().add(result);
}
else
{
if (log.isDebugEnabled())
{
log.debug("Number of columns is equivalent.");
}
}
}
@Override
public boolean validates(String fieldName)
{
ParameterCheck.mandatoryString("fieldName", fieldName);
return (fieldName.equals("columnNames"));
}
}

View File

@@ -1,94 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.validator;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.regex.Pattern;
import org.alfresco.util.schemacomp.DiffContext;
import org.alfresco.util.schemacomp.Results;
import org.alfresco.util.schemacomp.ValidationResult;
import org.alfresco.util.schemacomp.model.DbObject;
import org.alfresco.util.schemacomp.model.Index;
import org.hibernate.dialect.Oracle10gDialect;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the NameValidator class.
*
* @author Matt Ward
*/
public class NameValidatorTest
{
private NameValidator validator;
private DiffContext ctx;
private Results validationResults;
@Before
public void setUp() throws Exception
{
validator = new NameValidator();
validationResults = new Results();
ctx = new DiffContext(new Oracle10gDialect(), validationResults, null, null);
}
@Test
public void canSpecifyDefaultRequiredPattern()
{
validator.setPattern(Pattern.compile("SYS_[A-Z_]+"));
validator.validate(null, indexForName("SYS_MYINDEX"), ctx);
validator.validate(null, indexForName("SYS_"), ctx);
validator.validate(null, indexForName("SYS_MY_INDEX"), ctx);
validator.validate(null, indexForName("MY_INDEX"), ctx);
assertEquals(2, validationResults.size());
assertEquals("SYS_", ((ValidationResult) validationResults.get(0)).getValue());
assertEquals("MY_INDEX", ((ValidationResult) validationResults.get(1)).getValue());
}
@Test
public void canValidateAgainstPatternForDialect()
{
validator.setPattern(Pattern.compile("ORA_[A-Z_]+"));
validator.validate(null, indexForName("ORA_MYINDEX"), ctx);
validator.validate(null, indexForName("SYS_MYINDEX"), ctx);
assertEquals(1, validationResults.size());
assertEquals("SYS_MYINDEX", ((ValidationResult) validationResults.get(0)).getValue());
}
@Test
public void canSetPatternUsingProperties()
{
validator.setProperty("pattern", "ORA_[A-Z_]+");
assertEquals("ORA_[A-Z_]+", validator.getPattern().toString());
}
private DbObject indexForName(String name)
{
return new Index(null, name, new ArrayList<String>());
}
}

View File

@@ -1,112 +0,0 @@
/*
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.validator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import org.alfresco.util.schemacomp.DiffContext;
import org.alfresco.util.schemacomp.Results;
import org.alfresco.util.schemacomp.ValidationResult;
import org.alfresco.util.schemacomp.model.DbObject;
import org.alfresco.util.schemacomp.model.Schema;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the SchemaVersionValidator class.
*
* @author Matt Ward
*/
public class SchemaVersionValidatorTest
{
private SchemaVersionValidator validator;
private DbObject reference;
private DbObject target;
private DiffContext ctx;
private Results results;
@Before
public void setUp()
{
validator = new SchemaVersionValidator();
results = new Results();
ctx = new DiffContext(null, results, null, null);
}
@Test
public void validateWhenTargetVersionPredatesReference()
{
reference = schemaWithVersion(501);
target = schemaWithVersion(500);
validator.validate(reference, target, ctx);
assertEquals(1, results.size());
ValidationResult result = (ValidationResult) results.get(0);
assertEquals(500, result.getValue());
assertEquals("version", result.getDbProperty().getPropertyName());
assertSame(target, result.getDbProperty().getDbObject());
}
@Test
public void validateWhenTargetVersionSameAsReference()
{
reference = schemaWithVersion(501);
target = schemaWithVersion(501);
validator.validate(reference, target, ctx);
assertEquals(0, results.size());
}
@Test
public void validateWhenTargetVersionAfterReference()
{
reference = schemaWithVersion(501);
target = schemaWithVersion(502);
validator.validate(reference, target, ctx);
assertEquals(0, results.size());
}
@Test
public void testValidates()
{
assertEquals(true, validator.validates("version"));
}
@Test
public void testValidatesFullObject()
{
assertEquals(false, validator.validatesFullObject());
}
private DbObject schemaWithVersion(int version)
{
return new Schema("", "", version, true);
}
}

View File

@@ -1,31 +0,0 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.util.schemacomp.validator;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses(
{
NameValidatorTest.class
})
public class ValidatorTestSuite
{
}