diff --git a/README.md b/README.md index 6e4feef..9a561f5 100644 --- a/README.md +++ b/README.md @@ -34,18 +34,18 @@ While this is incredibly useful, understanding the resulting tests is often hard After researching and looking through the DBUnit code -- especially `FlatXmlDataSetBuilder` and the classes it uses -- for a while, I figured it possible but there was no nice, readable way to do it, yet. Therefore, I came up with a class called `DataSetBuilder` which is basically a wrapper around a `CachedDataSet` using a `BufferedConsumer`. Let's take a look at an example: DataSetBuilder builder = new DataSetBuilder(); - + // Using strings as column names, not type-safe builder.newRow("PERSON").with("NAME", "Bob").with("AGE", 18).add(); - + // Using ColumnSpecs to identify columns, type-safe! ColumnSpec name = ColumnSpec.newColumn("NAME") ColumnSpec age = ColumnSpec.newColumn("AGE"); builder.newRow("PERSON").with(name, "Alice").with(age, 23).add(); - + // New columns are added on the fly builder.newRow("PERSON").with(name, "Charlie").with("LAST_NAME", "Brown").add(); - + IDataSet dataSet = builder.build(); The code listed above creates three records in the `PERSON` table. It showcases two different ways of specifying columns, one using plain Strings and one using `ColumnSpec` instances, respectively. @@ -64,3 +64,38 @@ will print I think I found a way to create a data set directly from Java code in a readable way. In addition, creating the data sets programmatically gives to tools like refactoring, search for references, and so on for free. +## Solution - Step 2 +The idea to create a data set directly from Java code is great and give new possibilities, for example use a sequence for ids. +However the code is still boiler plated. SO the second natural step is to create table specific row builder. +With them the code can be more compact. + + DataSetBuilder builder = new DataSetBuilder(); + newPERSON().NAME("Bob").BIRTHPLACE("NEW YORK").addTo(builder); + newPERSON().NAME("Alice").BIRTHPLACE("London").addTo(builder); + + +with this the code is type-safe and compact. And to make it really comfortable +there should be a generator for this builders - `CustomRowBuilderGenerator.java`. +You can use it very easily: + + CustomRowBuilderGenerator rowBuilder = new CustomRowBuilderGenerator( + new File("src/test/java"), "net.sf.sze.dbunit.rowbuilder", "UTF-8"); + rowBuilder.addTypeMapping(BigInteger.class, Long.class); + rowBuilder.addTypeMapping(BigDecimal.class, Double.class); + rowBuilder.generate(getConnection().createDataSet()); + +With this preparation you can dump dataset from the database with + + BuilderDataSetWriter writer = new BuilderDataSetWriter( + new File("src/test/java"), "net.sf.sze.dbunit.dataset", + "ResultDS", "UTF-8", "net.sf.sze.dbunit.rowbuilder", true, importStatements); + writer.addTypeMapping(BigInteger.class, Long.class); + writer.addTypeMapping(BigDecimal.class, Double.class); + writer.write(getConnection().createDataSet()); + +You can combine this with [Validators dbunit-validation](https://github.com/opensource21/dbunit-validation) +to make your test more robust. + +A further improvement is the DataSetRowChanger. This allows you to define +which rows of of a given dataset should change. To use this you must declare +identifier columns which should be a unique key. diff --git a/pom.xml b/pom.xml index 92f5377..fb796e0 100644 --- a/pom.xml +++ b/pom.xml @@ -1,66 +1,156 @@ - - - 4.0.0 - org.dbunit.datasetbuilder - dbunit-datasetbuilder - 1.0-SNAPSHOT - - DbUnit DataSetBuilder - https://github.com/marcphilipp/dbunit-datasetbuilder - DBUnit - Dynamically Creating Data Sets Using Builders - - - - GNU Lesser General Public License, Version 2.1 - http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt - - - - - http://github.com/marcphilipp/dbunit-datasetbuilder - scm:git:git://github.com/marcphilipp/dbunit-datasetbuilder - scm:git:git@github.com:marcphilipp/dbunit-datasetbuilder.git - - - - - marcphilipp - Marc Philipp - mail@marcphilipp.de - - - - - - - maven-compiler-plugin - - UTF-8 - 1.6 - 1.6 - - - - - - - - org.dbunit - dbunit - 2.4.9 - - - org.slf4j - slf4j-simple - 1.5.6 - test - - - junit - junit - 4.11 - test - - - + + + 4.0.0 + de.ppi.dbunit.datasetbuilder + dbunit-datasetbuilder + 1.5.1-SNAPSHOT + + DbUnit DataSetBuilder + https://github.com/marcphilipp/dbunit-datasetbuilder + DBUnit - Dynamically Creating Data Sets Using Builders + + + + GNU Lesser General Public License, Version 2.1 + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + + + + + http://github.com/opensource21/dbunit-datasetbuilder + scm:git:git://github.com/opensource21/dbunit-datasetbuilder + scm:git:git@github.com:opensource21/dbunit-datasetbuilder.git + HEAD + + + PPI AG + http://www.ppi.de + + + + marcphilipp + Marc Philipp + mail@marcphilipp.de + + + niels + Niels + opensource21@gmail.com + + + + + + + maven-compiler-plugin + + UTF-8 + 1.6 + 1.6 + + + + org.apache.maven.plugins + maven-release-plugin + 2.5.2 + + + + + + maven-central + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + + attach-javadocs + + jar + + + + + UTF-8 + false + false + -Xdoclint:none + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.3 + true + + ossrh + https://oss.sonatype.org/ + true + + + + + + + nexus.releases + https://oss.sonatype.org/service/local/staging/deploy/maven2 + + + nexus.snapshots + https://oss.sonatype.org/content/repositories/snapshots + + + + + + + + org.dbunit + dbunit + 2.4.9 + + + org.slf4j + slf4j-simple + 1.5.6 + test + + + junit + junit + 4.11 + test + + + diff --git a/src/main/java/org/dbunit/dataset/builder/BasicDataRowBuilder.java b/src/main/java/org/dbunit/dataset/builder/BasicDataRowBuilder.java new file mode 100644 index 0000000..3cdfebf --- /dev/null +++ b/src/main/java/org/dbunit/dataset/builder/BasicDataRowBuilder.java @@ -0,0 +1,170 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +package org.dbunit.dataset.builder; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.dbunit.dataset.Column; +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.DefaultTableMetaData; +import org.dbunit.dataset.ITableMetaData; +import org.dbunit.dataset.datatype.DataType; + +public class BasicDataRowBuilder { + + + private final String tableName; + private final String[] identifierColumns; + protected final Map columnNameToValue = new LinkedHashMap(); + private String[] allColumnNames = new String[0]; + private final Map defaultValues = new HashMap(); + + public BasicDataRowBuilder(String tableName, String... identifierColumns) { + this.tableName = tableName; + this.identifierColumns = identifierColumns; + } + + /** + * Added the row to the given {@link IDataSetManipulator}. + * @param dataSet the builder of the dataset. + * @return the given dataset. + * @throws DataSetException + */ + public IDataSetManipulator addTo(IDataSetManipulator dataSet) throws DataSetException { + dataSet.add(this); + return dataSet; + } + + /** + * Added the column to the Data. + * @param columnName the name of the column. + * @param value the value the column should have. + * @return the current object. + */ + public BasicDataRowBuilder with(String columnName, Object value) { + columnNameToValue.put(columnName, value); + return this; + } + + /** + * Define a default value for a column, this is necessary for not null + * columns. + * @author niels + * @since 2.4.10 + * @param columnName + * @param value + */ + public void addDefaultValue(String columnName, Object value) { + defaultValues.put(columnName, value); + } + + /** + * Define all values of the table with null or the defaultvalue. + * All columns are defined with {@link #setAllColumnNames(String...)}. + * For not null columns you must define default values via + * {@link #addDefaultValue(String, Object)}. + * @author niels + * @since 2.4.10 + * @return the current object. + */ + public BasicDataRowBuilder fillUndefinedColumns() { + for (String column : allColumnNames) { + if (!columnNameToValue.containsKey(column)) { + columnNameToValue.put(column, defaultValues.get(column)); + } + } + return this; + } + + /** + * @param allColumnNames the allColumnNames to set + */ + public void setAllColumnNames(String... allColumnNames) { + this.allColumnNames = allColumnNames; + } + + + public Object[] values(Column[] columns) { + Object[] values = new Object[columns.length]; + int index = 0; + for (Column column : columns) { + values[index++] = getValue(column); + } + return values; + } + + public ITableMetaData toMetaData() { + Column[] columns = new Column[numberOfColumns()]; + int index = 0; + for (String columnName : columnNameToValue.keySet()) { + columns[index++] = createColumn(columnName); + } + return createMetaData(columns); + } + + protected int numberOfColumns() { + return columnNameToValue.size(); + } + + + protected ITableMetaData createMetaData(Column[] columns) { + return new DefaultTableMetaData(tableName, columns); + } + + protected Column createColumn(String columnName) { + return new Column(columnName, DataType.UNKNOWN); + } + + protected String getTableName() { + return tableName; + } + + protected void put(String columnName, Object value) { + columnNameToValue.put(columnName, value); + } + + protected Object getValue(Column column) { + return getValue(column.getColumnName()); + } + + protected Object getValue(String columnName) { + return columnNameToValue.get(columnName); + } + + + protected boolean existsValue(String columnName) { + return columnNameToValue.containsKey(columnName); + } + + + /** + * Delivers the identifier column names. + * @return the identifierColumns + */ + public String[] getIdentifierColumns() { + return identifierColumns; + } + + + +} diff --git a/src/main/java/org/dbunit/dataset/builder/BuilderDataSetWriter.java b/src/main/java/org/dbunit/dataset/builder/BuilderDataSetWriter.java new file mode 100644 index 0000000..7918e93 --- /dev/null +++ b/src/main/java/org/dbunit/dataset/builder/BuilderDataSetWriter.java @@ -0,0 +1,284 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +package org.dbunit.dataset.builder; + + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.dbunit.dataset.Column; +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITableMetaData; +import org.dbunit.dataset.stream.DataSetProducerAdapter; +import org.dbunit.dataset.stream.IDataSetConsumer; + +/** + * Writes the dataset in the builder definition. + * @author niels + * + */ +public class BuilderDataSetWriter implements IDataSetConsumer { + + /** Constant that show that autoboxing is allowed.*/ + public static final boolean ALLOW_AUTO_BOXING = true; + /** Constant that show that autoboxing is not allowed.*/ + public static final boolean DISALLOW_AUTO_BOXING = false; + + private final File destinationDir; + private final String packageName; + private final String className; + private final String encoding; + private final String rowBuilderPackage; + private final boolean allowAutoBoxing; + + private final String[] importStatements; + + private final RowBuilderNameCreator rowBuilderNameCreator; + + private static final String INDENT = " "; + + private String currentIndent = ""; + + private PrintWriter out; + + private Column[] currentTableColumns; + private String currentTableName; + + private Map, Class> typeMap = new HashMap, Class>(); + + + + + + /** + * Creates a new writer. + * @param destinationDir directory where the new class should be written. + * @param packageName the package name of the class. + * @param className the name of the class. + * @param encoding the file encoding. + * @param rowBuilderPackage package where the rowbuilder exists. + * @param allowAutoBoxing true if auto boxing is allowed. + * @param rowBuilderNameCreator the naming strategy for teh rowbuilder. + * @param importStatements some additional imports. + */ + public BuilderDataSetWriter(File destinationDir, + String packageName, String className, String encoding, String rowBuilderPackage, + boolean allowAutoBoxing, RowBuilderNameCreator rowBuilderNameCreator, String... importStatements) { + this.destinationDir = new File(destinationDir, + packageName.replace('.', '/')); + this.packageName = packageName; + this.className = className; + this.encoding = encoding == null ? System.getProperty("file.encoding") : encoding; + this.importStatements = importStatements; + this.rowBuilderPackage = rowBuilderPackage; + this.allowAutoBoxing = allowAutoBoxing; + this.rowBuilderNameCreator = rowBuilderNameCreator; + } + + /** + * Map the given source-class (given by the meta-data) to the target-type. + * @param source the source-type + * @param target the target-type + */ + public void addTypeMapping(Class source, Class target) { + typeMap.put(source, target); + } + + /** + * Writes the given {@link IDataSet} using this writer. + * @param dataSet The {@link IDataSet} to be written + * @throws DataSetException + * @throws FileNotFoundException + * @throws UnsupportedEncodingException + */ + public void write(IDataSet dataSet) throws DataSetException, FileNotFoundException, UnsupportedEncodingException { + try { + destinationDir.mkdirs(); + out = new PrintWriter(new File(destinationDir, className + ".java"), encoding); + final DataSetProducerAdapter provider = new DataSetProducerAdapter(dataSet); + provider.setConsumer(this); + println("package " + packageName + ";"); + out.println(); + for (String tableName : dataSet.getTableNames()) { + println("import static " + rowBuilderPackage + "." + + rowBuilderNameCreator.createRowBuilderName(tableName) + + "." + rowBuilderNameCreator.createFactoryMethodName(tableName) + ";"); + } + println("import static org.dbunit.dataset.builder.ObjectFactory.*;"); + println("import static java.lang.Boolean.*;"); + out.println(); + + for (Class clazz : getAllUsedTypes(dataSet)) { + println("import " + clazz.getName() +";"); + } + out.println(); + for (String importStatement : importStatements) { + println(importStatement); + } + out.println(); + out.println("import org.dbunit.dataset.DataSetException;"); + out.println("import org.dbunit.dataset.IDataSet;"); + out.println("import org.dbunit.dataset.builder.DataSetBuilder;"); + out.println(); + provider.produce(); + } finally { + if (out != null) { + out.close(); + } + } + } + + + private Set> getAllUsedTypes(IDataSet dataSet) throws DataSetException { + final Set> result = new HashSet>(); + for (String tableName : dataSet.getTableNames()) { + for (Column column : dataSet.getTableMetaData(tableName).getColumns()) { + final Class type = mappedType(column.getDataType().getTypeClass()); + if (!type.getPackage().getName().equals("java.lang")) { + result.add(type); + } + } + } + return result; + } + + + + @Override + public void startDataSet() throws DataSetException { + println("public class " + className + " {"); + increaseIndent(); + out.println(); + if (allowAutoBoxing) { + println("@SuppressWarnings(\"boxing\")"); + } + println("public static IDataSet build" + className + "DataSet() throws DataSetException {"); + increaseIndent(); + println("final DataSetBuilder b = new DataSetBuilder();"); + } + + + + @Override + public void endDataSet() throws DataSetException { + println("return b.build();"); + decreaseIndent(); + println("}"); + decreaseIndent(); + println("}"); + out.println(); + } + + + @Override + public void startTable(ITableMetaData metaData) throws DataSetException { + currentTableName = metaData.getTableName(); + currentTableColumns = metaData.getColumns(); + } + + @Override + public void endTable() throws DataSetException { + currentTableColumns = null; + currentTableName = null; + } + + @Override + public void row(Object[] values) throws DataSetException { + out.print(currentIndent + rowBuilderNameCreator.createFactoryMethodName(currentTableName) + "()"); + for (int i = 0; i < values.length; i++) { + final String columnName = currentTableColumns[i].getColumnName(); + final Object value = values[i]; + if (value != null) { + out.print("." + rowBuilderNameCreator.createSetterName(columnName) + + "(" + getValueRepresentation(value) + ")"); + } + } + out.println(".addTo(b);"); + } + + private String getValueRepresentation(Object value) { + final Class type = mappedType(value.getClass()); + if (type == String.class) { + return "\"" + value.toString().replaceAll("\"", "\\\\\"") + .replaceAll("\\n", "\\\\n").replaceAll("\\r", "\\\\r") + .replaceAll("\\t", "\\\\t") + "\""; + } else if (type == Boolean.class) { + return value.toString().toUpperCase(); + } else if (Integer.class.isAssignableFrom(type)) { + return allowAutoBoxing?value.toString():"i(" + value.toString() + ")"; + } else if (Long.class.isAssignableFrom(type)) { + return allowAutoBoxing?value.toString()+"L":"l(" + value.toString() + ")"; + } else if (Float.class.isAssignableFrom(type)) { + return allowAutoBoxing?value.toString()+"F":"f(" + value.toString() + ")"; + } else if (Double.class.isAssignableFrom(type)) { + return allowAutoBoxing?value.toString()+"D":"d(" + value.toString() + ")"; + } else if (BigInteger.class.isAssignableFrom(type)) { + return "bi(" + value.toString() + ")"; + } else if (BigDecimal.class.isAssignableFrom(type)) { + return "bd(" + value.toString() + ")"; + } else if (Date.class.isAssignableFrom(type)) { + return "d(\"" + value.toString() + "\")"; + } else if (Timestamp.class.isAssignableFrom(type)) { + return "ts(\"" + value.toString() + "\")"; + } else if (Time.class.isAssignableFrom(type)) { + return "t(\"" + value.toString() + "\")"; + } else if (Number.class.isAssignableFrom(type)) { + return type.getSimpleName() + ".valueOf(" + value.toString() +")"; + } else { + return type.getSimpleName() + ".valueOf(\"" + value.toString() +"\")"; + } + } + + private void increaseIndent() { + currentIndent += INDENT; + } + + private void decreaseIndent() { + currentIndent = currentIndent.substring(0, currentIndent.length() - INDENT.length()); + } + + private void println(String text) { + out.print(currentIndent); + out.println(text); + } + + private Class mappedType(Class type) { + if (typeMap.containsKey(type)) { + return typeMap.get(type); + } else { + return type; + } + } + + +} diff --git a/src/main/java/org/dbunit/dataset/builder/CaseInsensitiveStringPolicy.java b/src/main/java/org/dbunit/dataset/builder/CaseInsensitiveStringPolicy.java index d1af088..8129d6b 100644 --- a/src/main/java/org/dbunit/dataset/builder/CaseInsensitiveStringPolicy.java +++ b/src/main/java/org/dbunit/dataset/builder/CaseInsensitiveStringPolicy.java @@ -1,15 +1,35 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ package org.dbunit.dataset.builder; -public class CaseInsensitiveStringPolicy implements StringPolicy { +public class CaseInsensitiveStringPolicy implements IStringPolicy { - @Override - public boolean areEqual(String first, String second) { - return first.equalsIgnoreCase(second); - } + @Override + public boolean areEqual(String first, String second) { + return first.equalsIgnoreCase(second); + } - @Override - public String toKey(String value) { - return value.toUpperCase(); - } + @Override + public String toKey(String value) { + return value.toUpperCase(); + } } diff --git a/src/main/java/org/dbunit/dataset/builder/CaseSensitiveStringPolicy.java b/src/main/java/org/dbunit/dataset/builder/CaseSensitiveStringPolicy.java index 0254cbb..60a85f6 100644 --- a/src/main/java/org/dbunit/dataset/builder/CaseSensitiveStringPolicy.java +++ b/src/main/java/org/dbunit/dataset/builder/CaseSensitiveStringPolicy.java @@ -1,15 +1,35 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ package org.dbunit.dataset.builder; -public class CaseSensitiveStringPolicy implements StringPolicy { +public class CaseSensitiveStringPolicy implements IStringPolicy { - @Override - public boolean areEqual(String first, String second) { - return first.equals(second); - } + @Override + public boolean areEqual(String first, String second) { + return first.equals(second); + } - @Override - public String toKey(String value) { - return value; - } + @Override + public String toKey(String value) { + return value; + } } diff --git a/src/main/java/org/dbunit/dataset/builder/CustomRowBuilderGenerator.java b/src/main/java/org/dbunit/dataset/builder/CustomRowBuilderGenerator.java new file mode 100644 index 0000000..5222d93 --- /dev/null +++ b/src/main/java/org/dbunit/dataset/builder/CustomRowBuilderGenerator.java @@ -0,0 +1,255 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +package org.dbunit.dataset.builder; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; + +import org.dbunit.dataset.Column; +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITableMetaData; + +/** + * Generates an custom row builder. + * Improvements: Better names. + * @author niels + * + */ +public class CustomRowBuilderGenerator { + + private final File destinationDir; + private final String packageName; + private final String encoding; + private final RowBuilderNameCreator rowBuilderNameCreator; + + private String indent = ""; + + private Map, Class> typeMap = new HashMap, Class>(); + + /** + * Intantiate a new instance. + * @param destinationDir the directory where the file should be written. + * @param packageName the packagename of the classes. + * @param encoding the fileEncoding + * @param javaFriendlyNames true if you prefer more java common names then + * the original table and column-names. + */ + public CustomRowBuilderGenerator(File destinationDir, String packageName, + String encoding, RowBuilderNameCreator rowBuilderNameCreator) { + this.destinationDir = new File(destinationDir, + packageName.replace('.', '/')); + this.packageName = packageName; + this.encoding = encoding == null ? System.getProperty("file.encoding") : encoding; + this.rowBuilderNameCreator = rowBuilderNameCreator; + } + + + public void addTypeMapping(Class source, Class Target) { + typeMap.put(source, Target); + } + + public void generate(IDataSet dataSet) throws DataSetException { + final String[] tableNames = dataSet.getTableNames(); + // tables + for (int i = 0; i < tableNames.length; i++) { + // table element + final String tableName = tableNames[i]; + final ITableMetaData metadata = dataSet.getTableMetaData(tableName); + final Column[] pkColumns = metadata.getPrimaryKeys(); + final String[] pkColumnNames = new String[pkColumns.length]; + for (int col = 0; col < pkColumnNames.length; col++) { + pkColumnNames[col] = pkColumns[col].getColumnName(); + } + // Add the columns + final Column[] columns = metadata.getColumns(); + final Set notNullColumns = new HashSet(); + final SortedMap> columnTypes = new TreeMap>(); + for (int j = 0; j < columns.length; j++) { + final Column column = columns[j]; + final String columnName = column.getColumnName(); + final boolean nullable = (column.getNullable() == Column.NULLABLE); + if (!nullable) { + notNullColumns.add(columnName); + } + columnTypes.put(columnName, mappedType(column.getDataType().getTypeClass())); + + } + indent=""; + writeClass(tableName, columnTypes, notNullColumns, pkColumnNames); + } + + } + + + private void writeClass(String tableName, + SortedMap> columnTypes, Set notNullColumns, String[] pkColumnNames) { + final SortedSet importStatements = new TreeSet(); + for (Class clazz : columnTypes.values()) { + if (!clazz.getPackage().getName().equals("java.lang")) { + importStatements.add("import " + clazz.getName() +";"); + } + } + + final String className = rowBuilderNameCreator.createRowBuilderName(tableName); + destinationDir.mkdirs(); + final File outputFile = new File(destinationDir, className + ".java"); + System.out.println("Write " + outputFile.getAbsolutePath()); + PrintWriter out = null; + try { + out = new PrintWriter(outputFile, encoding); + out.println("package " + packageName + ";"); + out.println(); + out.println("import org.dbunit.dataset.builder.BasicDataRowBuilder;"); + for (String importStatement : importStatements) { + out.println(importStatement); + } + out.println(); + out.println("public class " + className + " extends BasicDataRowBuilder {"); + indent = indent + " "; + out.println(); + println(out, "public static final String TABLE_NAME" + + " = \"" + tableName + "\";"); + out.println(); + for (Map.Entry> columns : columnTypes.entrySet()) { + println(out, "public static final String " + + rowBuilderNameCreator.createColumnConstantName(columns.getKey()) + + " = \"" + columns.getKey() + "\";"); + } + out.println(); + final StringBuilder pk = new StringBuilder("public static final String[] PRIMARY_KEY = {"); + for (int i = 0; i < pkColumnNames.length; i++) { + pk.append(rowBuilderNameCreator.createColumnConstantName(pkColumnNames[i])); + if (i < pkColumnNames.length - 1) { + pk.append(", "); + } + } + pk.append("};"); + println(out, pk.toString()); + out.println(); + final StringBuilder all = new StringBuilder("public static final String[] ALL_COLUMNS = {"); + for (String colName : columnTypes.keySet()) { + all.append(rowBuilderNameCreator.createColumnConstantName(colName)).append(", "); + } + all.replace(all.length() - 2, all.length(), "};"); + println(out, all.toString()); + out.println(); + println(out, "public " + className + "(String... identifierColumns) {"); + println(out, " super(TABLE_NAME, identifierColumns);"); + println(out, " setAllColumnNames(ALL_COLUMNS);"); + for (String column : notNullColumns) { + println(out, " addDefaultValue(" + rowBuilderNameCreator. + createColumnConstantName(column) + + ", " + getDefaultValue(columnTypes.get(column)) + ");"); + } + println(out, "}"); + out.println(); + for (Map.Entry> column : columnTypes.entrySet()) { + createSetterForColumnValue(out, className, column); + out.println(); + } + out.println(); + println(out, "public static " + className + " " + + rowBuilderNameCreator.createFactoryMethodName(tableName) +"() {"); + println(out, " return new " + className + "(PRIMARY_KEY);"); + println(out, "}"); + out.println(); + println(out, "public static " + className + " " + + rowBuilderNameCreator.createFactoryMethodName(tableName) + + "(String... identifierColumns) {"); + println(out, " return new " + className + "(identifierColumns);"); + println(out, "}"); + out.println(); + out.println("}"); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e1) { + e1.printStackTrace(); + } finally { + if (out != null) { + out.close(); + } + } + } + + + /** + * @author niels + * @since 2.4.10 + * @param out + * @param className + * @param column + */ + private void createSetterForColumnValue(PrintWriter out, + final String className, Map.Entry> column) { + Class type = column.getValue(); + if (Number.class.isAssignableFrom(type)) { + type = Number.class; + } + + println(out, "public final " + className + " " + + rowBuilderNameCreator.createSetterName(column.getKey()) + + " (" + type.getSimpleName() + " value) {"); + println(out, " with(" + rowBuilderNameCreator. + createColumnConstantName(column.getKey()) +", value);"); + println(out, " return this;"); + println(out, "}"); + } + + private String getDefaultValue(Class clazz) { + if (Number.class.isAssignableFrom(clazz)) { + return "new " + clazz.getSimpleName() + "(\"0\")"; + } else if (Date.class.isAssignableFrom(clazz)) { + return "new " + clazz.getSimpleName() + "(0)"; + } else if (String.class.equals(clazz)) { + return "\"\""; + } else if (Boolean.class.equals(clazz)) { + return "Boolean.FALSE"; + } else { + System.err.println("Unknown class " + clazz); + } + return null; + } + + private void println(PrintWriter out, String text) { + out.println(indent + text); + } + + private Class mappedType(Class type) { + if (typeMap.containsKey(type)) { + return typeMap.get(type); + } else { + return type; + } + } + +} diff --git a/src/main/java/org/dbunit/dataset/builder/DataRowBuilder.java b/src/main/java/org/dbunit/dataset/builder/DataRowBuilder.java index 9274c48..3dc4295 100644 --- a/src/main/java/org/dbunit/dataset/builder/DataRowBuilder.java +++ b/src/main/java/org/dbunit/dataset/builder/DataRowBuilder.java @@ -1,88 +1,29 @@ package org.dbunit.dataset.builder; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -import org.dbunit.dataset.Column; import org.dbunit.dataset.DataSetException; -import org.dbunit.dataset.DefaultTableMetaData; -import org.dbunit.dataset.ITableMetaData; -import org.dbunit.dataset.datatype.DataType; - -public class DataRowBuilder { - - private final DataSetBuilder dataSet; - private final String tableName; - private final Map columnNameToValue = new LinkedHashMap(); - - protected DataRowBuilder(DataSetBuilder dataSet, String tableName) { - this.dataSet = dataSet; - this.tableName = tableName; - } - - public DataRowBuilder with(ColumnSpec column, T value) { - return with(column.name(), value); - } - - public DataRowBuilder with(String columnName, Object value) { - put(columnName, value); - return this; - } - - public DataSetBuilder add() throws DataSetException { - dataSet.add(this); - return dataSet; - } - - public Object[] values(Column[] columns) { - Object[] values = new Object[columns.length]; - int index = 0; - for (Column column : columns) { - values[index++] = getValue(column); - } - return values; - } - - public ITableMetaData toMetaData() { - Column[] columns = new Column[numberOfColumns()]; - int index = 0; - for (String columnName : allColumnNames()) { - columns[index++] = createColumn(columnName); - } - return createMetaData(columns); - } - - protected int numberOfColumns() { - return columnNameToValue.size(); - } - protected Set allColumnNames() { - return columnNameToValue.keySet(); - } +public class DataRowBuilder extends BasicDataRowBuilder { - protected ITableMetaData createMetaData(Column[] columns) { - return new DefaultTableMetaData(tableName, columns); - } + private final DataSetBuilder dataSet; + protected DataRowBuilder(DataSetBuilder dataSet, String tableName) { + super(tableName); + this.dataSet = dataSet; + } - protected Column createColumn(String columnName) { - return new Column(columnName, DataType.UNKNOWN); - } + public DataRowBuilder with(ColumnSpec column, T value) { + return with(column.name(), value); + } - protected String tableName() { - return tableName; - } - protected void put(String columnName, Object value) { - columnNameToValue.put(columnName, value); - } + public DataRowBuilder with(String columnName, Object value) { + put(columnName, value); + return this; + } - protected Object getValue(Column column) { - return getValue(column.getColumnName()); - } - protected Object getValue(String columnName) { - return columnNameToValue.get(columnName); - } + public DataSetBuilder add() throws DataSetException { + dataSet.add(this); + return dataSet; + } } diff --git a/src/main/java/org/dbunit/dataset/builder/DataSetBuilder.java b/src/main/java/org/dbunit/dataset/builder/DataSetBuilder.java index 2459787..5e15e45 100644 --- a/src/main/java/org/dbunit/dataset/builder/DataSetBuilder.java +++ b/src/main/java/org/dbunit/dataset/builder/DataSetBuilder.java @@ -1,3 +1,23 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ package org.dbunit.dataset.builder; import java.util.HashMap; @@ -7,136 +27,145 @@ import org.dbunit.dataset.stream.BufferedConsumer; import org.dbunit.dataset.stream.IDataSetConsumer; -public class DataSetBuilder { - - private CachedDataSet dataSet = new CachedDataSet(); - private IDataSetConsumer consumer = new BufferedConsumer(dataSet); - private final Map tableNameToMetaData = new HashMap(); - private final StringPolicy stringPolicy; - - private String currentTableName; - - private static StringPolicy stringPolicy(boolean ignoreCase) { - return ignoreCase ? new CaseInsensitiveStringPolicy() : new CaseSensitiveStringPolicy(); - } - - public DataSetBuilder() throws DataSetException { - this(true); - } - - public DataSetBuilder(boolean ignoreCase) throws DataSetException { - this(stringPolicy(ignoreCase)); - } - - public DataSetBuilder(StringPolicy stringPolicy) throws DataSetException { - this.stringPolicy = stringPolicy; - consumer.startDataSet(); - } - - public void ensureTableIsPresent(String tableName) throws DataSetException { - if (containsTable(tableName)) { - return; - } - endTableIfNecessary(); - startTable(metaDataBuilderFor(tableName).build()); - } - - public DataRowBuilder newRow(String tableName) { - return new DataRowBuilder(this, tableName); - } - - public IDataSet build() throws DataSetException { - endTableIfNecessary(); - consumer.endDataSet(); - return dataSet; - } - - public void addDataSet(final IDataSet dataSet) throws DataSetException { - IDataSet[] dataSets = { build(), dataSet }; - CompositeDataSet composite = new CompositeDataSet(dataSets); - this.dataSet = new CachedDataSet(composite); - consumer = new BufferedConsumer(this.dataSet); - } - - protected void add(DataRowBuilder row) throws DataSetException { - ITableMetaData metaData = updateTableMetaData(row); - Object[] values = extractValues(row, metaData); - notifyConsumer(values); - } - - private Object[] extractValues(DataRowBuilder row, ITableMetaData metaData) throws DataSetException { - return row.values(metaData.getColumns()); - } - - private void notifyConsumer(Object[] values) throws DataSetException { - consumer.row(values); - } - - private ITableMetaData updateTableMetaData(DataRowBuilder row) throws DataSetException { - TableMetaDataBuilder builder = metaDataBuilderFor(row.tableName()); - int previousNumberOfColumns = builder.numberOfColumns(); - - ITableMetaData metaData = builder.with(row.toMetaData()).build(); - int newNumberOfColumns = metaData.getColumns().length; - - boolean addedNewColumn = newNumberOfColumns > previousNumberOfColumns; - handleTable(metaData, addedNewColumn); - - return metaData; - } - - private void handleTable(ITableMetaData metaData, boolean addedNewColumn) throws DataSetException { - if (isNewTable(metaData.getTableName())) { - endTableIfNecessary(); - startTable(metaData); - } else if (addedNewColumn) { - startTable(metaData); - } - } - - private void startTable(ITableMetaData metaData) throws DataSetException { - currentTableName = metaData.getTableName(); - consumer.startTable(metaData); - } - - private void endTable() throws DataSetException { - consumer.endTable(); - currentTableName = null; - } - - private void endTableIfNecessary() throws DataSetException { - if (hasCurrentTable()) { - endTable(); - } - } - - private boolean hasCurrentTable() { - return currentTableName != null; - } - - private boolean isNewTable(String tableName) { - return currentTableName == null || !stringPolicy.areEqual(currentTableName, tableName); - } - - private TableMetaDataBuilder metaDataBuilderFor(String tableName) { - String key = stringPolicy.toKey(tableName); - if (containsKey(key)) { - return tableNameToMetaData.get(key); - } - TableMetaDataBuilder builder = createNewTableMetaDataBuilder(tableName); - tableNameToMetaData.put(key, builder); - return builder; - } - - protected TableMetaDataBuilder createNewTableMetaDataBuilder(String tableName) { - return new TableMetaDataBuilder(tableName, stringPolicy); - } - - public boolean containsTable(String tableName) { - return containsKey(stringPolicy.toKey(tableName)); - } - - private boolean containsKey(String key) { - return tableNameToMetaData.containsKey(key); - } +public class DataSetBuilder implements IDataSetManipulator { + + private CachedDataSet dataSet = new CachedDataSet(); + private IDataSetConsumer consumer = new BufferedConsumer(dataSet); + private final Map tableNameToMetaData = new HashMap(); + private final IStringPolicy stringPolicy; + + private String currentTableName; + + private static IStringPolicy stringPolicy(boolean ignoreCase) { + return ignoreCase ? new CaseInsensitiveStringPolicy() : new CaseSensitiveStringPolicy(); + } + + public DataSetBuilder() throws DataSetException { + this(true); + } + + public DataSetBuilder(boolean ignoreCase) throws DataSetException { + this(stringPolicy(ignoreCase)); + } + + public DataSetBuilder(IStringPolicy stringPolicy) throws DataSetException { + this.stringPolicy = stringPolicy; + consumer.startDataSet(); + } + + public void ensureTableIsPresent(String tableName) throws DataSetException { + if (containsTable(tableName)) { + return; + } + endTableIfNecessary(); + startTable(metaDataBuilderFor(tableName).build()); + } + + public static BasicDataRowBuilder newBasicRow(String tableName) { + return new BasicDataRowBuilder(tableName); + } + + public DataRowBuilder newRow(String tableName) { + return new DataRowBuilder(this, tableName); + } + + public IDataSet build() throws DataSetException { + endTableIfNecessary(); + consumer.endDataSet(); + return dataSet; + } + + public void addDataSet(final IDataSet newDataSet) throws DataSetException { + IDataSet[] dataSets = { build(), newDataSet }; + CompositeDataSet composite = new CompositeDataSet(dataSets); + this.dataSet = new CachedDataSet(composite); + consumer = new BufferedConsumer(this.dataSet); + } + + /** + * {@inheritDoc} + */ + @Override + public void add(BasicDataRowBuilder row) throws DataSetException { + row.fillUndefinedColumns(); + ITableMetaData metaData = updateTableMetaData(row); + Object[] values = extractValues(row, metaData); + notifyConsumer(values); + } + + private Object[] extractValues(BasicDataRowBuilder row, ITableMetaData metaData) throws DataSetException { + return row.values(metaData.getColumns()); + } + + private void notifyConsumer(Object[] values) throws DataSetException { + consumer.row(values); + } + + private ITableMetaData updateTableMetaData(BasicDataRowBuilder row) throws DataSetException { + TableMetaDataBuilder builder = metaDataBuilderFor(row.getTableName()); + int previousNumberOfColumns = builder.numberOfColumns(); + + ITableMetaData metaData = builder.with(row.toMetaData()).build(); + int newNumberOfColumns = metaData.getColumns().length; + + boolean addedNewColumn = newNumberOfColumns > previousNumberOfColumns; + handleTable(metaData, addedNewColumn); + + return metaData; + } + + private void handleTable(ITableMetaData metaData, boolean addedNewColumn) throws DataSetException { + if (isNewTable(metaData.getTableName())) { + endTableIfNecessary(); + startTable(metaData); + } else if (addedNewColumn) { + startTable(metaData); + } + } + + private void startTable(ITableMetaData metaData) throws DataSetException { + currentTableName = metaData.getTableName(); + consumer.startTable(metaData); + } + + private void endTable() throws DataSetException { + consumer.endTable(); + currentTableName = null; + } + + private void endTableIfNecessary() throws DataSetException { + if (hasCurrentTable()) { + endTable(); + } + } + + private boolean hasCurrentTable() { + return currentTableName != null; + } + + private boolean isNewTable(String tableName) { + return currentTableName == null || !stringPolicy.areEqual(currentTableName, tableName); + } + + private TableMetaDataBuilder metaDataBuilderFor(String tableName) { + String key = stringPolicy.toKey(tableName); + if (containsKey(key)) { + return tableNameToMetaData.get(key); + } + TableMetaDataBuilder builder = createNewTableMetaDataBuilder(tableName); + tableNameToMetaData.put(key, builder); + return builder; + } + + protected TableMetaDataBuilder createNewTableMetaDataBuilder(String tableName) { + return new TableMetaDataBuilder(tableName, stringPolicy); + } + + public boolean containsTable(String tableName) { + return containsKey(stringPolicy.toKey(tableName)); + } + + private boolean containsKey(String key) { + return tableNameToMetaData.containsKey(key); + } } diff --git a/src/main/java/org/dbunit/dataset/builder/DataSetRowChanger.java b/src/main/java/org/dbunit/dataset/builder/DataSetRowChanger.java new file mode 100644 index 0000000..4335fa1 --- /dev/null +++ b/src/main/java/org/dbunit/dataset/builder/DataSetRowChanger.java @@ -0,0 +1,150 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +package org.dbunit.dataset.builder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.dbunit.dataset.CachedDataSet; +import org.dbunit.dataset.Column; +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITableMetaData; +import org.dbunit.dataset.stream.BufferedConsumer; +import org.dbunit.dataset.stream.DataSetProducerAdapter; + +/** + * {@link IDataSetManipulator} which change the rows of an existing {@link IDataSet} + * and creates a new {@link IDataSet}. + * @author niels + * + */ +public class DataSetRowChanger extends BufferedConsumer implements IDataSetManipulator { + + private final CachedDataSet dataSet; + private final IDataSet oldDataSet; + private final Map> tableNameToRow = new HashMap>(); + + private final IStringPolicy stringPolicy; + + private String currentTableName; + private Column[] currentTableColumns; + private Map columnameToColNr = new HashMap(); + + private static IStringPolicy stringPolicy(boolean ignoreCase) { + return ignoreCase ? new CaseInsensitiveStringPolicy() : new CaseSensitiveStringPolicy(); + } + + public DataSetRowChanger(IDataSet oldDataSet) throws DataSetException { + this(true, oldDataSet); + } + + public DataSetRowChanger(boolean ignoreCase, IDataSet oldDataSet) throws DataSetException { + this(stringPolicy(ignoreCase), oldDataSet); + } + + public DataSetRowChanger(IStringPolicy stringPolicy, IDataSet oldDataSet) throws DataSetException { + this(stringPolicy, oldDataSet, new CachedDataSet()); + } + + private DataSetRowChanger(IStringPolicy stringPolicy, IDataSet oldDataSet, CachedDataSet newDataSet) throws DataSetException { + super(newDataSet); + this.dataSet = newDataSet; + this.stringPolicy = stringPolicy; + this.oldDataSet = oldDataSet; + } + + /** + * {@inheritDoc} + */ + @Override + public void add(BasicDataRowBuilder row) throws DataSetException { + final String key = stringPolicy.toKey(row.getTableName()); + if (!tableNameToRow.containsKey(key)) { + tableNameToRow.put(key, new ArrayList()); + } + tableNameToRow.get(key).add(row); + } + + public IDataSet build() throws DataSetException { + final DataSetProducerAdapter provider = new DataSetProducerAdapter(oldDataSet); + provider.setConsumer(this); + provider.produce(); + return dataSet; + } + + + /** + * {@inheritDoc} + */ + @Override + public void row(Object[] values) throws DataSetException { + final List changeRows = tableNameToRow.get(currentTableName); + if (changeRows != null && !changeRows.isEmpty()) { + for (BasicDataRowBuilder dataRowBuilder : changeRows) { + boolean match = true; + final String[] identifierCols = dataRowBuilder.getIdentifierColumns(); + for (int i = 0; i < identifierCols.length; i++) { + final Integer idColNr = columnameToColNr.get(stringPolicy.toKey( + identifierCols[i])); + if (idColNr == null) { + throw new IllegalStateException(identifierCols[i] + " is unknown."); + } + final boolean thisColMatch = values[idColNr.intValue()].equals( + dataRowBuilder.getValue(identifierCols[i])); + match = match && thisColMatch; + } + if (match) { + for (int i = 0; i < currentTableColumns.length; i++) { + if (dataRowBuilder.existsValue(currentTableColumns[i].getColumnName())) { + values[i] = dataRowBuilder.getValue(currentTableColumns[i]); + } + } + } + } + } + super.row(values); + } + + + + /** + * {@inheritDoc} + */ + @Override + public void startTable(ITableMetaData metaData) throws DataSetException { + currentTableName = metaData.getTableName(); + currentTableColumns = metaData.getColumns(); + for (int i = 0; i < currentTableColumns.length; i++) { + columnameToColNr.put(stringPolicy.toKey(currentTableColumns[i].getColumnName()), + Integer.valueOf(i)); + } + super.startTable(metaData); + } + + public static BasicDataRowBuilder changeRow(String tableName, String... identifierColumns) { + final BasicDataRowBuilder row = new BasicDataRowBuilder(tableName, identifierColumns); + return row; + } + +} diff --git a/src/main/java/org/dbunit/dataset/builder/IDataSetManipulator.java b/src/main/java/org/dbunit/dataset/builder/IDataSetManipulator.java new file mode 100644 index 0000000..9a54737 --- /dev/null +++ b/src/main/java/org/dbunit/dataset/builder/IDataSetManipulator.java @@ -0,0 +1,41 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +package org.dbunit.dataset.builder; + +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.IDataSet; + +/** + * Object to manipulate a {@link IDataSet}, you can add {@link BasicDataRowBuilder} + * with the information how the dataset should be manipulated. + * @author niels + * + */ +public interface IDataSetManipulator { + + /** + * Added a row so that a Dataset can be manipulated or created. + * @param row + * @throws DataSetException + */ + public abstract void add(BasicDataRowBuilder row) throws DataSetException; + +} \ No newline at end of file diff --git a/src/main/java/org/dbunit/dataset/builder/IStringPolicy.java b/src/main/java/org/dbunit/dataset/builder/IStringPolicy.java new file mode 100644 index 0000000..f6d77c0 --- /dev/null +++ b/src/main/java/org/dbunit/dataset/builder/IStringPolicy.java @@ -0,0 +1,29 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +package org.dbunit.dataset.builder; + +public interface IStringPolicy { + + boolean areEqual(String first, String second); + + String toKey(String value); + +} diff --git a/src/main/java/org/dbunit/dataset/builder/JavaFriendlyNameCreator.java b/src/main/java/org/dbunit/dataset/builder/JavaFriendlyNameCreator.java new file mode 100644 index 0000000..4c6c532 --- /dev/null +++ b/src/main/java/org/dbunit/dataset/builder/JavaFriendlyNameCreator.java @@ -0,0 +1,84 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +package org.dbunit.dataset.builder; + +/** + * Creates names for the rowbuilder in a javafriendly way. + * @author niels (linux_java AT users.sourceforge.net) + * @author Last changed by: niels + * @version 13.04.2014 + * @since 2.4.10 + * + */ +public class JavaFriendlyNameCreator implements RowBuilderNameCreator { + + /** + * {@inheritDoc} + */ + @Override + public String createRowBuilderName(String tableName) { + StringBuilder sb = new StringBuilder(); + for(String word : tableName.toLowerCase().split("_")) { + sb.append(word.substring(0,1).toUpperCase()); + sb.append(word.substring(1)); + } + sb.append("RowBuilder"); + return sb.toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public String createFactoryMethodName(String tableName) { + StringBuilder sb = new StringBuilder("new"); + for(String word : tableName.toLowerCase().split("_")) { + sb.append(word.substring(0,1).toUpperCase()); + sb.append(word.substring(1)); + } + return sb.toString(); + } + + + /** + * {@inheritDoc} + */ + @Override + public String createSetterName(String columnName) { + StringBuilder sb = new StringBuilder(); + for(String word : columnName.toLowerCase().split("_")) { + sb.append(word.substring(0,1).toUpperCase()); + sb.append(word.substring(1)); + } + return sb.toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public String createColumnConstantName(String columnName) { + StringBuilder sb = new StringBuilder("C_"); + sb.append(columnName.toUpperCase()); + return sb.toString(); + } +} diff --git a/src/main/java/org/dbunit/dataset/builder/ObjectFactory.java b/src/main/java/org/dbunit/dataset/builder/ObjectFactory.java new file mode 100644 index 0000000..dde0635 --- /dev/null +++ b/src/main/java/org/dbunit/dataset/builder/ObjectFactory.java @@ -0,0 +1,123 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +package org.dbunit.dataset.builder; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; + +/** + * Class for creating Objects, so that we get a more compact code. + * @author niels (linux-java AT users.sourceforge.net) + * @author Last changed by: niels + * @version 03.01.2014 + * @since 2.4.10 + * + */ +public class ObjectFactory { + + private ObjectFactory() { + //Hidden Constructor. + } + + /** + * Converts a string in JDBC date escape format to + * a Date value. + * + * @param s a String object representing a date in + * in the format "yyyy-mm-dd" + * @return a java.sql.Date object representing the + * given date + * @throws IllegalArgumentException if the date given is not in the + * JDBC date escape format (yyyy-mm-dd) + */ + public static Date d(String date) { + return Date.valueOf(date); + } + + /** + * Converts a String object in JDBC timestamp escape format to a + * Timestamp value. + * + * @param s timestamp in format yyyy-mm-dd hh:mm:ss[.f...]. The + * fractional seconds may be omitted. + * @return corresponding Timestamp value + * @exception java.lang.IllegalArgumentException if the given argument + * does not have the format yyyy-mm-dd hh:mm:ss[.f...] + */ + public static Timestamp ts(String time) { + return Timestamp.valueOf(time); + } + + /** + * Converts a string in JDBC time escape format to a Time value. + * + * @param s time in format "hh:mm:ss" + * @return a corresponding Time object + */ + public static Time t(String time) { + return Time.valueOf(time); + } + + public static Double d(double d) { + return Double.valueOf(d); + } + + public static Double d(long d) { + return Double.valueOf(d); + } + + public static Float f(float f) { + return Float.valueOf(f); + } + + public static Float f(long f) { + return Float.valueOf(f); + } + + public static Long l(long l) { + return Long.valueOf(l); + } + + public static Integer i(int i) { + return Integer.valueOf(i); + } + + public static BigInteger bi(String bi) { + return new BigInteger(bi); + } + + public static BigDecimal bd(String bd) { + return new BigDecimal(bd); + } + + public static BigInteger bi(long bi) { + return BigInteger.valueOf(bi); + } + + public static BigDecimal bd(double bd) { + return BigDecimal.valueOf(bd); + } + +} diff --git a/src/main/java/org/dbunit/dataset/builder/RowBuilderNameCreator.java b/src/main/java/org/dbunit/dataset/builder/RowBuilderNameCreator.java new file mode 100644 index 0000000..8dc30b9 --- /dev/null +++ b/src/main/java/org/dbunit/dataset/builder/RowBuilderNameCreator.java @@ -0,0 +1,41 @@ +package org.dbunit.dataset.builder; + +public interface RowBuilderNameCreator { + + /** + * Creates the name of the RowBuilder. + * @author niels + * @since 2.4.0 + * @param tableName name of the table. + * @return name of the RowBuilder. + */ + String createRowBuilderName(String tableName); + + /** + * Creates the name of the factory method for the RowBuilder. + * @author niels + * @since 2.4.0 + * @param tableName name of the table. + * @return name of the factory method for the RowBuilder. + */ + String createFactoryMethodName(String tableName); + + /** + * Creates the name of the method to define a value. + * @author niels + * @since 2.4.0 + * @param columnName name of the column. + * @return the name of the method to define a value. + */ + String createSetterName(String columnName); + + /** + * Creates the name of the constant-name for the column. + * @author niels + * @since 2.4.0 + * @param columnName name of the column. + * @return the name of the constant-name for the column. + */ + String createColumnConstantName(String columnName); + +} \ No newline at end of file diff --git a/src/main/java/org/dbunit/dataset/builder/SimpleNameCreator.java b/src/main/java/org/dbunit/dataset/builder/SimpleNameCreator.java new file mode 100644 index 0000000..d22a4cb --- /dev/null +++ b/src/main/java/org/dbunit/dataset/builder/SimpleNameCreator.java @@ -0,0 +1,60 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +package org.dbunit.dataset.builder; + +/** + * Creates names for the rowbuilder with no conversions. + * @author niels (linux_java AT users.sourceforge.net) + * @author Last changed by: niels + * @version 13.04.2014 + * @since 2.4.10 + * + */ +public class SimpleNameCreator implements RowBuilderNameCreator { + + + public String createRowBuilderName(String tableName) { + StringBuilder sb = new StringBuilder(); + sb.append(tableName); + sb.append("RowBuilder"); + return sb.toString(); + } + + public String createFactoryMethodName(String tableName) { + StringBuilder sb = new StringBuilder("new"); + sb.append(tableName); + return sb.toString(); + } + + + public String createSetterName(String columnName) { + StringBuilder sb = new StringBuilder(); + sb.append(columnName); + return sb.toString(); + } + + public String createColumnConstantName(String columnName) { + StringBuilder sb = new StringBuilder("C_"); + sb.append(columnName); + return sb.toString(); + } +} diff --git a/src/main/java/org/dbunit/dataset/builder/StringPolicy.java b/src/main/java/org/dbunit/dataset/builder/StringPolicy.java deleted file mode 100644 index 6c3b955..0000000 --- a/src/main/java/org/dbunit/dataset/builder/StringPolicy.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.dbunit.dataset.builder; - -public interface StringPolicy { - - boolean areEqual(String first, String second); - - String toKey(String value); - -} diff --git a/src/main/java/org/dbunit/dataset/builder/TableMetaDataBuilder.java b/src/main/java/org/dbunit/dataset/builder/TableMetaDataBuilder.java index 5664598..6b4194c 100644 --- a/src/main/java/org/dbunit/dataset/builder/TableMetaDataBuilder.java +++ b/src/main/java/org/dbunit/dataset/builder/TableMetaDataBuilder.java @@ -1,3 +1,23 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ package org.dbunit.dataset.builder; import java.util.LinkedHashMap; @@ -9,59 +29,59 @@ public class TableMetaDataBuilder { - private final String tableName; - private final StringPolicy policy; - private final LinkedHashMap keysToColumns = new LinkedHashMap(); - - public TableMetaDataBuilder(String tableName, StringPolicy policy) { - this.tableName = tableName; - this.policy = policy; - } - - public TableMetaDataBuilder with(ITableMetaData metaData) throws DataSetException { - return with(metaData.getColumns()); - } - - public TableMetaDataBuilder with(Column... columns) { - for (Column column : columns) { - with(column); - } - return this; - } - - public TableMetaDataBuilder with(Column column) { - if (isUnknown(column)) { - add(column); - } - return this; - } - - public int numberOfColumns() { - return keysToColumns.size(); - } - - public ITableMetaData build() { - return new DefaultTableMetaData(tableName, columns()); - } - - private void add(Column column) { - keysToColumns.put(toKey(column), column); - } - - private String toKey(Column column) { - return policy.toKey(column.getColumnName()); - } - - private boolean isUnknown(Column column) { - return !isKnown(column); - } - - private boolean isKnown(Column column) { - return keysToColumns.containsKey(toKey(column)); - } - - private Column[] columns() { - return keysToColumns.values().toArray(new Column[keysToColumns.size()]); - } + private final String tableName; + private final IStringPolicy policy; + private final LinkedHashMap keysToColumns = new LinkedHashMap(); + + public TableMetaDataBuilder(String tableName, IStringPolicy policy) { + this.tableName = tableName; + this.policy = policy; + } + + public TableMetaDataBuilder with(ITableMetaData metaData) throws DataSetException { + return with(metaData.getColumns()); + } + + public TableMetaDataBuilder with(Column... columns) { + for (Column column : columns) { + with(column); + } + return this; + } + + public TableMetaDataBuilder with(Column column) { + if (isUnknown(column)) { + add(column); + } + return this; + } + + public int numberOfColumns() { + return keysToColumns.size(); + } + + public ITableMetaData build() { + return new DefaultTableMetaData(tableName, columns()); + } + + private void add(Column column) { + keysToColumns.put(toKey(column), column); + } + + private String toKey(Column column) { + return policy.toKey(column.getColumnName()); + } + + private boolean isUnknown(Column column) { + return !isKnown(column); + } + + private boolean isKnown(Column column) { + return keysToColumns.containsKey(toKey(column)); + } + + private Column[] columns() { + return keysToColumns.values().toArray(new Column[keysToColumns.size()]); + } } diff --git a/src/test/java/org/dbunit/dataset/builder/DataSetBuilderIntegrationTest.java b/src/test/java/org/dbunit/dataset/builder/DataSetBuilderIntegrationTest.java new file mode 100644 index 0000000..64d9087 --- /dev/null +++ b/src/test/java/org/dbunit/dataset/builder/DataSetBuilderIntegrationTest.java @@ -0,0 +1,155 @@ +/* + * + * The DbUnit Database Testing Framework + * Copyright (C)2002-2008, DbUnit.org + * + * This library 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 2.1 of the License, or (at your option) any later version. + * + * This library 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 this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +package org.dbunit.dataset.builder; + +import static org.dbunit.dataset.builder.DataSetBuilder.newBasicRow; +import static org.dbunit.dataset.builder.DataSetBuilderIntegrationTest.PERSONRowBuilder.newPERSON; +import static org.dbunit.dataset.builder.ObjectFactory.*; + +import java.sql.Date; +import java.util.TimeZone; + +import org.dbunit.Assertion; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ReplacementDataSet; +import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; +import org.junit.Before; +import org.junit.Test; + +/** + * Test the class {@link DataSetBuilder}. + * @author niels (linux-java AT users.sourceforge.net) + * @author Last changed by: niels + * @version 02.01.2014 + * @since 2.4.10 + * + */ +public class DataSetBuilderIntegrationTest { + + + @Before + public void setUp() throws Exception { + } + + /** + * Test method for {@link org.dbunit.dataset.builder.DataSetBuilder#build()}. + */ + @Test + public void testBuild() throws Exception { + TimeZone.setDefault(TimeZone.getTimeZone("GMT-1")); + DataSetBuilder builder = new DataSetBuilder(); + newPERSON().NAME("Bob").BIRTHPLACE("NEW YORK").addTo(builder); + newPERSON().NAME("Alice").BIRTHPLACE("London").addTo(builder); + newBasicRow("ADDRESS").with("STREET", "Main Street").with("NUMBER", 42).addTo(builder); + + final IDataSet actual = builder.build(); + + ReplacementDataSet expected = new ReplacementDataSet(new FlatXmlDataSetBuilder().build( + this.getClass().getResourceAsStream("/reference.xml"))); + expected.addReplacementObject("[NULL]", null); + + Assertion.assertEquals(expected, actual); + } + + static class PERSONRowBuilder extends BasicDataRowBuilder { + + public static final String TABLE_NAME = "PERSON"; + + public static final String C_DATE_OF_BIRTH = "DATE_OF_BIRTH"; + public static final String C_BIRTHPLACE = "BIRTPLACE"; + public static final String C_SEX = "SEX"; + public static final String C_ID = "ID"; + public static final String C_NAME = "NAME"; + public static final String C_VERSION = "VERSION"; + public static final String C_FIRSTNAME = "FIRSTNAME"; + + public static final String[] PRIMARY_KEY = {C_ID}; + + public static final String[] ALL_COLUMNS = {C_DATE_OF_BIRTH, C_BIRTHPLACE, + C_SEX, C_ID, C_VERSION, C_NAME, C_FIRSTNAME}; + + public PERSONRowBuilder(String... identifierColumns) { + super(TABLE_NAME, identifierColumns); + setAllColumnNames(ALL_COLUMNS); + addDefaultValue(C_DATE_OF_BIRTH, d("1970-01-01")); + addDefaultValue(C_NAME, ""); + addDefaultValue(C_VERSION, new Long("0")); + addDefaultValue(C_FIRSTNAME, ""); + addDefaultValue(C_ID, new Long("0")); + addDefaultValue(C_BIRTHPLACE, ""); + } + + public final PERSONRowBuilder DATE_OF_BIRTH (Date value) { + with(C_DATE_OF_BIRTH, value); + return this; + } + + public final PERSONRowBuilder BIRTHPLACE (String value) { + with(C_BIRTHPLACE, value); + return this; + } + + + + public final PERSONRowBuilder SEX (Integer value) { + with(C_SEX, value); + return this; + } + + + public final PERSONRowBuilder ID (Long value) { + with(C_ID, value); + return this; + } + + + + public final PERSONRowBuilder NAME (String value) { + with(C_NAME, value); + return this; + } + + + public final PERSONRowBuilder VERSION (Long value) { + with(C_VERSION, value); + return this; + } + + + public final PERSONRowBuilder FIRSTNAME (String value) { + with(C_FIRSTNAME, value); + return this; + } + + + public static PERSONRowBuilder newPERSON() { + return new PERSONRowBuilder(PRIMARY_KEY); + } + + public static PERSONRowBuilder newPERSON(String... identifierColumns) { + return new PERSONRowBuilder(identifierColumns); + } + + } + + +} diff --git a/src/test/java/org/dbunit/dataset/builder/DataSetBuilderTest.java b/src/test/java/org/dbunit/dataset/builder/DataSetBuilderTest.java index 5893ff8..a4f6edd 100644 --- a/src/test/java/org/dbunit/dataset/builder/DataSetBuilderTest.java +++ b/src/test/java/org/dbunit/dataset/builder/DataSetBuilderTest.java @@ -1,6 +1,10 @@ package org.dbunit.dataset.builder; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.ITable; @@ -8,127 +12,127 @@ public class DataSetBuilderTest { - @Test - public void ignoringCaseByDefault() throws Exception { - DataSetBuilder builder = new DataSetBuilder(); - builder.ensureTableIsPresent("PeRsoN"); - - assertTrue(builder.containsTable("Person")); - } - - @Test - public void notIgnoringCaseWhenSpecified() throws Exception { - DataSetBuilder builder = new DataSetBuilder(false); - builder.ensureTableIsPresent("PeRsoN"); - - assertFalse(builder.containsTable("Person")); - assertTrue(builder.containsTable("PeRsoN")); - } - - @Test - public void ensuringPresenceOfExistingTableMakesNoHarm() throws Exception { - DataSetBuilder builder = new DataSetBuilder(); - builder.newRow("person").add(); - builder.ensureTableIsPresent("PeRsoN"); - - assertTrue(builder.containsTable("Person")); - } - - @Test - public void tablesAreKeptInOrder() throws Exception { - DataSetBuilder builder = new DataSetBuilder(); - builder.newRow("PERSON").add(); - builder.newRow("ADDRESS").add(); - builder.newRow("_TABLE_").add(); - IDataSet dataSet = builder.build(); - - assertArrayEquals(new String[]{"PERSON", "ADDRESS", "_TABLE_"}, dataSet.getTableNames()); - } - - @Test - public void addsDataForSingleRow() throws Exception { - DataSetBuilder builder = new DataSetBuilder(); - builder.newRow("PERSON").with("NAME", "Bob").with("AGE", 18).add(); - - IDataSet dataSet = builder.build(); - ITable table = dataSet.getTable("PERSON"); - assertEquals(1, table.getRowCount()); - assertEquals("Bob", table.getValue(0, "NAME")); - assertEquals(18, table.getValue(0, "AGE")); - } - - @Test - public void addsDataWithColumnSpec() throws Exception { - DataSetBuilder builder = new DataSetBuilder(); - ColumnSpec name = ColumnSpec.newColumn("NAME"); - ColumnSpec age = ColumnSpec.newColumn("AGE"); - builder.newRow("PERSON").with(name, "Bob").with(age, 18).add(); - - IDataSet dataSet = builder.build(); - ITable table = dataSet.getTable("PERSON"); - assertEquals(1, table.getRowCount()); - assertEquals("Bob", table.getValue(0, "NAME")); - assertEquals(18, table.getValue(0, "AGE")); - } - - @Test - public void addsDataForMultipleRowsOfDifferentTables() throws Exception { - DataSetBuilder builder = new DataSetBuilder(); - builder.newRow("PERSON").with("NAME", "Bob").with("AGE", 18).add(); - builder.newRow("ADDRESS").with("STREET", "Main Street").with("NUMBER", 42).add(); - builder.newRow("PERSON").with("NAME", "Alice").with("AGE", 23).add(); - - IDataSet dataSet = builder.build(); - ITable table = dataSet.getTable("PERSON"); - assertEquals(2, table.getRowCount()); - assertEquals("Bob", table.getValue(0, "NAME")); - assertEquals(18, table.getValue(0, "AGE")); - assertEquals("Alice", table.getValue(1, "NAME")); - assertEquals(23, table.getValue(1, "AGE")); - - table = dataSet.getTable("ADDRESS"); - assertEquals(1, table.getRowCount()); - assertEquals("Main Street", table.getValue(0, "STREET")); - assertEquals(42, table.getValue(0, "NUMBER")); - } - - @Test - public void addsNewColumnsOnTheFly() throws Exception { - DataSetBuilder builder = new DataSetBuilder(); - builder.newRow("PERSON").with("NAME", "Bob").add(); - builder.newRow("PERSON").with("AGE", 18).add(); - - IDataSet dataSet = builder.build(); - ITable table = dataSet.getTable("PERSON"); - assertEquals(2, table.getRowCount()); - assertEquals("Bob", table.getValue(0, "NAME")); - assertNull(table.getValue(0, "AGE")); - assertNull(table.getValue(1, "NAME")); - assertEquals(18, table.getValue(1, "AGE")); - } - - @Test - public void addDataSet() throws Exception { - DataSetBuilder builder = new DataSetBuilder(); - builder.newRow("PERSON").with("NAME", "Bob").with("AGE", 18).add(); - - IDataSet dataSet = builder.build(); - ITable table = dataSet.getTable("PERSON"); - - assertEquals(1, table.getRowCount()); - - builder = new DataSetBuilder(); - builder.newRow("PERSON").with("NAME", "John").with("AGE", 19).add(); - builder.addDataSet(dataSet); - - IDataSet dataSet2 = builder.build(); - ITable table2 = dataSet2.getTable("PERSON"); - - assertEquals(2, table2.getRowCount()); - assertEquals("John", table2.getValue(0, "NAME")); - assertEquals(19, table2.getValue(0, "AGE")); - - assertEquals("Bob", table2.getValue(1, "NAME")); - assertEquals(18, table2.getValue(1, "AGE")); - } + @Test + public void ignoringCaseByDefault() throws Exception { + DataSetBuilder builder = new DataSetBuilder(); + builder.ensureTableIsPresent("PeRsoN"); + + assertTrue(builder.containsTable("Person")); + } + + @Test + public void notIgnoringCaseWhenSpecified() throws Exception { + DataSetBuilder builder = new DataSetBuilder(false); + builder.ensureTableIsPresent("PeRsoN"); + + assertFalse(builder.containsTable("Person")); + assertTrue(builder.containsTable("PeRsoN")); + } + + @Test + public void ensuringPresenceOfExistingTableMakesNoHarm() throws Exception { + DataSetBuilder builder = new DataSetBuilder(); + builder.newRow("person").add(); + builder.ensureTableIsPresent("PeRsoN"); + + assertTrue(builder.containsTable("Person")); + } + + @Test + public void tablesAreKeptInOrder() throws Exception { + DataSetBuilder builder = new DataSetBuilder(); + builder.newRow("PERSON").add(); + builder.newRow("ADDRESS").add(); + builder.newRow("_TABLE_").add(); + IDataSet dataSet = builder.build(); + + assertArrayEquals(new String[]{"PERSON", "ADDRESS", "_TABLE_"}, dataSet.getTableNames()); + } + + @Test + public void addsDataForSingleRow() throws Exception { + DataSetBuilder builder = new DataSetBuilder(); + builder.newRow("PERSON").with("NAME", "Bob").with("AGE", 18).add(); + + IDataSet dataSet = builder.build(); + ITable table = dataSet.getTable("PERSON"); + assertEquals(1, table.getRowCount()); + assertEquals("Bob", table.getValue(0, "NAME")); + assertEquals(18, table.getValue(0, "AGE")); + } + + @Test + public void addsDataWithColumnSpec() throws Exception { + DataSetBuilder builder = new DataSetBuilder(); + ColumnSpec name = ColumnSpec.newColumn("NAME"); + ColumnSpec age = ColumnSpec.newColumn("AGE"); + builder.newRow("PERSON").with(name, "Bob").with(age, 18).add(); + + IDataSet dataSet = builder.build(); + ITable table = dataSet.getTable("PERSON"); + assertEquals(1, table.getRowCount()); + assertEquals("Bob", table.getValue(0, "NAME")); + assertEquals(18, table.getValue(0, "AGE")); + } + + @Test + public void addsDataForMultipleRowsOfDifferentTables() throws Exception { + DataSetBuilder builder = new DataSetBuilder(); + builder.newRow("PERSON").with("NAME", "Bob").with("AGE", 18).add(); + builder.newRow("ADDRESS").with("STREET", "Main Street").with("NUMBER", 42).add(); + builder.newRow("PERSON").with("NAME", "Alice").with("AGE", 23).add(); + + IDataSet dataSet = builder.build(); + ITable table = dataSet.getTable("PERSON"); + assertEquals(2, table.getRowCount()); + assertEquals("Bob", table.getValue(0, "NAME")); + assertEquals(18, table.getValue(0, "AGE")); + assertEquals("Alice", table.getValue(1, "NAME")); + assertEquals(23, table.getValue(1, "AGE")); + + table = dataSet.getTable("ADDRESS"); + assertEquals(1, table.getRowCount()); + assertEquals("Main Street", table.getValue(0, "STREET")); + assertEquals(42, table.getValue(0, "NUMBER")); + } + + @Test + public void addsNewColumnsOnTheFly() throws Exception { + DataSetBuilder builder = new DataSetBuilder(); + builder.newRow("PERSON").with("NAME", "Bob").add(); + builder.newRow("PERSON").with("AGE", 18).add(); + + IDataSet dataSet = builder.build(); + ITable table = dataSet.getTable("PERSON"); + assertEquals(2, table.getRowCount()); + assertEquals("Bob", table.getValue(0, "NAME")); + assertNull(table.getValue(0, "AGE")); + assertNull(table.getValue(1, "NAME")); + assertEquals(18, table.getValue(1, "AGE")); + } + + @Test + public void addDataSet() throws Exception { + DataSetBuilder builder = new DataSetBuilder(); + builder.newRow("PERSON").with("NAME", "Bob").with("AGE", 18).add(); + + IDataSet dataSet = builder.build(); + ITable table = dataSet.getTable("PERSON"); + + assertEquals(1, table.getRowCount()); + + builder = new DataSetBuilder(); + builder.newRow("PERSON").with("NAME", "John").with("AGE", 19).add(); + builder.addDataSet(dataSet); + + IDataSet dataSet2 = builder.build(); + ITable table2 = dataSet2.getTable("PERSON"); + + assertEquals(2, table2.getRowCount()); + assertEquals("John", table2.getValue(0, "NAME")); + assertEquals(19, table2.getValue(0, "AGE")); + + assertEquals("Bob", table2.getValue(1, "NAME")); + assertEquals(18, table2.getValue(1, "AGE")); + } } diff --git a/src/test/java/org/dbunit/dataset/builder/DataSetRowChangerTest.java b/src/test/java/org/dbunit/dataset/builder/DataSetRowChangerTest.java new file mode 100644 index 0000000..24d14bf --- /dev/null +++ b/src/test/java/org/dbunit/dataset/builder/DataSetRowChangerTest.java @@ -0,0 +1,103 @@ +package org.dbunit.dataset.builder; + +import static org.junit.Assert.assertEquals; +import static org.dbunit.dataset.builder.DataSetBuilder.newBasicRow; +import static org.dbunit.dataset.builder.DataSetRowChanger.changeRow; + +import org.dbunit.dataset.CachedDataSet; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.ITable; +import org.junit.Test; + +/** + * Test {@link DataSetRowChanger}. + * @author niels (linux-java AT users.sourceforge.net) + * @author Last changed by: niels + * @version 01.01.2014 + * @since 2.4.10 + * + */ +public class DataSetRowChangerTest { + + private static final String T_ADDRESS = "ADDRESS"; + private static final String T_PERSON = "PERSON"; + + private static final String C_FIRSTNAME = "FIRSTNAME"; + private static final String C_LAST_NAME = "LastName"; + private static final String C_AGE = "AGE"; + + private static final String BOB = "Bob"; + private static final String ALICE = "Alice"; + private static final String MILLER = "Miller"; + + private static final String C_ID = "ID"; + private static final String C_STREET = "STREET"; + private static final String C_NUMBER = "NUMBER"; + private static final String MAIN_STREET = "Main Street"; + + + + @Test + public void testBuild() throws Exception { + //Arrange + final DataSetBuilder builder = new DataSetBuilder(false); + + newBasicRow(T_PERSON).with(C_FIRSTNAME, BOB).with(C_LAST_NAME, MILLER).with(C_AGE, 18).addTo(builder); + newBasicRow(T_ADDRESS).with(C_ID, 1).with(C_STREET, MAIN_STREET).with(C_NUMBER, 42).addTo(builder); + newBasicRow(T_PERSON).with(C_FIRSTNAME, ALICE).with(C_LAST_NAME, MILLER).with(C_AGE, 23).addTo(builder); + final CachedDataSet oldDataSet = (CachedDataSet)builder.build(); + + final DataSetRowChanger changer = new DataSetRowChanger(oldDataSet); + changeRow(T_PERSON, C_LAST_NAME, C_FIRSTNAME).with(C_FIRSTNAME, BOB).with(C_LAST_NAME, MILLER).with(C_AGE, 21).addTo(changer); + changeRow("Address", C_ID).with(C_ID, 1).with(C_NUMBER, 21).addTo(changer); + changeRow(T_ADDRESS, C_ID).with(C_ID, 2).with(C_NUMBER, 72).addTo(changer); + //Act + final IDataSet dataSet = changer.build(); + //Assert + ITable table = dataSet.getTable(T_PERSON); + assertEquals(2, table.getRowCount()); + assertEquals(BOB, table.getValue(0, C_FIRSTNAME)); + assertEquals(MILLER, table.getValue(0, "LASTNAME")); + assertEquals(21, table.getValue(0, C_AGE)); + assertEquals(ALICE, table.getValue(1, C_FIRSTNAME)); + assertEquals(MILLER, table.getValue(0, "LASTNAME")); + assertEquals(23, table.getValue(1, C_AGE)); + + table = dataSet.getTable(T_ADDRESS); + assertEquals(1, table.getRowCount()); + assertEquals(MAIN_STREET, table.getValue(0, C_STREET)); + assertEquals(21, table.getValue(0, C_NUMBER)); + } + + @Test + public void testBuildCaseSensitive() throws Exception { + //Arrange + final DataSetBuilder builder = new DataSetBuilder(true); + + newBasicRow(T_PERSON).with(C_FIRSTNAME, BOB).with(C_LAST_NAME, MILLER).with(C_AGE, 18).addTo(builder); + newBasicRow(T_ADDRESS).with(C_ID, 1).with(C_STREET, MAIN_STREET).with(C_NUMBER, 42).addTo(builder); + newBasicRow(T_PERSON).with(C_FIRSTNAME, ALICE).with(C_LAST_NAME, MILLER).with(C_AGE, 23).addTo(builder); + final CachedDataSet oldDataSet = (CachedDataSet)builder.build(); + + final DataSetRowChanger changer = new DataSetRowChanger(false, oldDataSet); + changeRow(T_PERSON, C_LAST_NAME, C_FIRSTNAME).with(C_FIRSTNAME, BOB).with(C_LAST_NAME, MILLER).with(C_AGE, 21).addTo(changer); + changeRow(T_PERSON, C_LAST_NAME, C_FIRSTNAME).with(C_FIRSTNAME, ALICE).with("LASTNAME", MILLER).with(C_AGE, 21).addTo(changer); + changeRow("Address", C_ID).with(C_ID, 1).with(C_NUMBER, 21).addTo(changer); + //Act + final IDataSet dataSet = changer.build(); + //Assert + ITable table = dataSet.getTable(T_PERSON); + assertEquals(2, table.getRowCount()); + assertEquals(BOB, table.getValue(0, C_FIRSTNAME)); + assertEquals(MILLER, table.getValue(0, "LASTNAME")); + assertEquals(21, table.getValue(0, C_AGE)); + assertEquals(ALICE, table.getValue(1, C_FIRSTNAME)); + assertEquals(MILLER, table.getValue(0, "LASTNAME")); + assertEquals(23, table.getValue(1, C_AGE)); + + table = dataSet.getTable(T_ADDRESS); + assertEquals(1, table.getRowCount()); + assertEquals(MAIN_STREET, table.getValue(0, C_STREET)); + assertEquals(42, table.getValue(0, C_NUMBER)); + } +} diff --git a/src/test/java/org/dbunit/dataset/builder/example/DataSetBuilderExample.java b/src/test/java/org/dbunit/dataset/builder/example/DataSetBuilderExample.java index 63daacf..94bfa64 100644 --- a/src/test/java/org/dbunit/dataset/builder/example/DataSetBuilderExample.java +++ b/src/test/java/org/dbunit/dataset/builder/example/DataSetBuilderExample.java @@ -14,22 +14,22 @@ public class DataSetBuilderExample { private static final ColumnSpec NAME = newColumn("NAME"); private static final ColumnSpec AGE = ColumnSpec.newColumn("AGE"); - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { - DataSetBuilder builder = new DataSetBuilder(); + DataSetBuilder builder = new DataSetBuilder(); - // Using strings as column names, not type-safe - builder.newRow("PERSON").with("NAME", "Bob").with("AGE", 18).add(); + // Using strings as column names, not type-safe + builder.newRow("PERSON").with("NAME", "Bob").with("AGE", 18).add(); - // Using ColumnSpecs to identify columns, type-safe! - builder.newRow("PERSON").with(NAME, "Alice").with(AGE, 23).add(); + // Using ColumnSpecs to identify columns, type-safe! + builder.newRow("PERSON").with(NAME, "Alice").with(AGE, 23).add(); - // New columns are added on the fly - builder.newRow("PERSON").with(NAME, "Charlie").with("LAST_NAME", "Brown").add(); + // New columns are added on the fly + builder.newRow("PERSON").with(NAME, "Charlie").with("LAST_NAME", "Brown").add(); - IDataSet dataSet = builder.build(); + IDataSet dataSet = builder.build(); - new XmlDataSetWriter(new PrintWriter(System.out)).write(dataSet); - } + new XmlDataSetWriter(new PrintWriter(System.out)).write(dataSet); + } } diff --git a/src/test/resources/reference.xml b/src/test/resources/reference.xml new file mode 100644 index 0000000..07e3dec --- /dev/null +++ b/src/test/resources/reference.xml @@ -0,0 +1,6 @@ + + + + +
+