Java Code Examples for org.dbunit.dataset.IDataSet

The following examples show how to use org.dbunit.dataset.IDataSet. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jpa-unit   Source File: DataSetLoaderProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCsvLoaderLoadUsingProperResource() throws Exception {
    // WHEN
    final DataSetLoader<IDataSet> loader = LOADER_PROVIDER.csvLoader();

    // THEN
    assertThat(loader, notNullValue());

    // WHEN
    final IDataSet dataSet = loader.load(getFile("test-data"));

    // THEN
    assertThat(dataSet, notNullValue());

    final List<String> tableNames = Arrays.asList(dataSet.getTableNames());
    assertThat(tableNames.size(), equalTo(2));
    assertThat(tableNames, hasItems("CSV_TABLE_1", "CSV_TABLE_2"));

    final ITable table1 = dataSet.getTable("CSV_TABLE_1");
    assertThat(table1.getRowCount(), equalTo(3));

    final ITable table2 = dataSet.getTable("CSV_TABLE_2");
    assertThat(table2.getRowCount(), equalTo(1));
}
 
Example 2
Source Project: kylin-on-parquet-v2   Source File: KylinTestBase.java    License: Apache License 2.0 6 votes vote down vote up
protected void verifyResultContent(String queryFolder) throws Exception {
    logger.info("---------- verify result content in folder: " + queryFolder);

    List<File> sqlFiles = getFilesFromFolder(new File(queryFolder), ".sql");
    for (File sqlFile : sqlFiles) {
        String queryName = StringUtils.split(sqlFile.getName(), '.')[0];
        String sql = getTextFromFile(sqlFile);

        File expectResultFile = new File(sqlFile.getParent(), sqlFile.getName() + ".expected.xml");
        IDataSet expect = new FlatXmlDataSetBuilder().build(expectResultFile);
        // Get expected table named "expect". FIXME Only support default table name
        ITable expectTable = expect.getTable("expect");

        // execute Kylin
        logger.info("Query Result from Kylin - " + queryName + "  (" + queryFolder + ")");
        IDatabaseConnection kylinConn = new DatabaseConnection(cubeConnection);
        ITable kylinTable = executeQuery(kylinConn, queryName, sql, false);

        // compare the result
        assertTableEquals(expectTable, kylinTable);
    }
}
 
Example 3
@Test
public void testView() throws Exception {
    IDataSet db = database(
            support.loadFlatXmlDataStream(getClass(), "user.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_job.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_task.xml")
            );
    support.cleanInsert(support.getConnection(tx), db);
    tx.commit();

    TaskFilter filter = new TaskFilter();
    filter.setJobId(BigDecimal.ONE);
    filter.setJobLabel("Monograph1");
    List<TaskView> tasks = dao.view(filter);
    assertEquals(1, tasks.size());
    TaskView t = tasks.get(0);
    assertEquals(BigDecimal.ONE, t.getId());
    assertEquals(State.STARTED, t.getState());
    assertEquals("Monograph1", t.getJobLabel());
    assertEquals("test", t.getUserName());

    filter = new TaskFilter();
    filter.setProfileName(Arrays.asList("task.id1", "task.id2"));
    tasks = dao.view(filter);
    assertEquals(2, tasks.size());
}
 
Example 4
Source Project: base-framework   Source File: Fixtures.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 对XML文件中的数据在H2数据库中执行Operation.
 * 
 * @param xmlFilePaths 符合Spring Resource路径格式的文件列表.
 */
private static void execute(DatabaseOperation operation, DataSource dataSource, String... xmlFilePaths)
		throws DatabaseUnitException, SQLException {
	//注意这里HardCode了使用H2的Connetion
	IDatabaseConnection connection = new H2Connection(dataSource.getConnection(), null);

	for (String xmlPath : xmlFilePaths) {
		try {
			InputStream input = resourceLoader.getResource(xmlPath).getInputStream();
			IDataSet dataSet = new FlatXmlDataSetBuilder().setColumnSensing(true).build(input);
			operation.execute(connection, dataSet);
		} catch (IOException e) {
			logger.warn(xmlPath + " file not found", e);
		}finally{
			connection.close();
		}
	}
}
 
Example 5
Source Project: jpa-unit   Source File: SqlDbFeatureExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected DbFeature<IDatabaseConnection> createVerifyDataAfterFeature(final ExpectedDataSets expectedDataSets) {
    return (final IDatabaseConnection connection) -> {
        try {
            final IDataSet currentDataSet = connection.createDataSet();
            final IDataSet expectedDataSet = mergeDataSets(loadDataSets(Arrays.asList(expectedDataSets.value())));

            final DataSetComparator dataSetComparator = new DataSetComparator(expectedDataSets.orderBy(),
                    expectedDataSets.excludeColumns(), expectedDataSets.strict(), getColumnFilter(expectedDataSets));

            final AssertionErrorCollector errorCollector = new AssertionErrorCollector();
            dataSetComparator.compare(currentDataSet, expectedDataSet, errorCollector);

            errorCollector.report();
        } catch (final SQLException | DatabaseUnitException e) {
            throw new DbFeatureException("Could not execute DB contents verification feature", e);
        }
    };
}
 
Example 6
Source Project: wetech-cms   Source File: UserDaoTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFindSQLByArgsAndAlias() throws DatabaseUnitException, SQLException {
	IDataSet ds = createDateSet("t_user");
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds);
	SystemContext.removeOrder();
	SystemContext.removeSort();
	SystemContext.setPageSize(3);
	SystemContext.setPageOffset(0);
	Map<String,Object> alias = new HashMap<String,Object>();
	alias.put("ids", Arrays.asList(1,2,4,5,6,7,8,10));
	Pager<User> expected = userDao.findUserBySql("select * from t_user where id>=? and id<=? and id in (:ids)", new Object[]{1,10},alias,User.class,true);
	List<User> actuals = Arrays.asList(new User(1,"admin1"),new User(2,"admin2"),new User(4,"admin4"));
	assertNotNull(expected);
	assertTrue(expected.getTotal()==8);
	assertTrue(expected.getOffset()==0);
	assertTrue(expected.getSize()==3);
	EntitiesHelper.assertUsers(expected.getDatas(), actuals);
}
 
Example 7
Source Project: proarc   Source File: EmpireBatchDaoTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testUpdate() throws Exception {
    IDataSet db = database(
            support.loadFlatXmlDataStream(getClass(), "user.xml"),
            support.loadFlatXmlDataStream(getClass(), "batch.xml")
            );
    support.cleanInsert(support.getConnection(tx), db);
    tx.commit();

    Batch batch = dao.find(1);
    State expectedState = State.INGESTING;
    batch.setState(expectedState);
    String expectedLog = "updated log";
    batch.setLog(expectedLog);
    Timestamp timestamp = batch.getTimestamp();
    dao.update(batch);
    tx.commit();

    batch = dao.find(1);
    assertEquals(expectedState, batch.getState());
    assertEquals(expectedLog, batch.getLog());
    assertTrue(timestamp.before(batch.getTimestamp()));
}
 
Example 8
Source Project: development   Source File: DatabaseTaskHandler.java    License: Apache License 2.0 6 votes vote down vote up
public static void dropTables(String filePath) throws DataSetException,
        IOException, SQLException {
    IDataSet tablesToDelete = new FlatXmlDataSetBuilder().build(new File(
            filePath));
    String[] tableNames = tablesToDelete.getTableNames();
    Statement stmt = conn.createStatement();
    String queryString = "DROP TABLE %s CASCADE";
    for (int i = tableNames.length - 1; i >= 0; i--) {
        // first drop constraints to the table
        deleteConstraints(tableNames[i]);

        // now drop the table itself
        String tableName = tableNames[i];
        try {
            String query = String.format(queryString, tableName);
            stmt.executeUpdate(query);
            System.out.println(query);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
    stmt.close();
}
 
Example 9
@Test
public void testFindJob() throws Exception {
    IDataSet db = database(
            support.loadFlatXmlDataStream(getClass(), "user.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_job.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_task.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_material.xml")
            );
    support.cleanInsert(support.getConnection(tx), db);
    tx.commit();

    Material m = new Material();
    m.setId(BigDecimal.ONE);
    Job job = dao.findJob(m);
    assertNotNull(job);
    assertEquals(BigDecimal.ONE, job.getId());
}
 
Example 10
Source Project: wetech-cms   Source File: UserDaoTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testFindByArgs() throws DatabaseUnitException, SQLException {
	IDataSet ds = createDateSet("t_user");
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds);
	SystemContext.setOrder("desc");
	SystemContext.setSort("id");
	SystemContext.setPageSize(3);
	SystemContext.setPageOffset(0);
	Pager<User> expected = userDao.find("from User where id>=? and id<=?", new Object[]{1,10});
	List<User> actuals = Arrays.asList(new User(10,"admin10"),new User(9,"admin9"),new User(8,"admin8"));
	assertNotNull(expected);
	assertTrue(expected.getTotal()==10);
	assertTrue(expected.getOffset()==0);
	assertTrue(expected.getSize()==3);
	EntitiesHelper.assertUsers(expected.getDatas(), actuals);
}
 
Example 11
Source Project: SpringCloud   Source File: TestUserDao.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFindSQLByArgs() throws DatabaseUnitException, SQLException {
    IDataSet ds = createDateSet("t_user");
    DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
    SystemContext.setOrder("desc");
    SystemContext.setSort("id");
    SystemContext.setPageSize(3);
    SystemContext.setPageOffset(0);
    Pager<User> expected = userDao.findUserBySql("select * from t_user where id>=? and id<=?",
            new Object[] { 1, 10 }, User.class, true);
    List<User> actuals = Arrays.asList(new User(10, "admin10"), new User(9, "admin9"), new User(8, "admin8"));
    assertNotNull(expected);
    assertTrue(expected.getTotal() == 10);
    assertTrue(expected.getOffset() == 0);
    assertTrue(expected.getSize() == 3);
    EntitiesHelper.assertUsers(expected.getDatas(), actuals);
}
 
Example 12
@Test
public void testView() throws Exception {
    IDataSet db = database(
            support.loadFlatXmlDataStream(getClass(), "user.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_job.xml")
            );
    support.cleanInsert(support.getConnection(tx), db);
    tx.commit();

    JobFilter filter = new JobFilter();
    filter.setId(BigDecimal.ONE);
    filter.setLabel("Monograph1");
    List<JobView> jobs = dao.view(filter);
    assertEquals(1, jobs.size());
    JobView job0 = jobs.get(0);
    assertEquals(BigDecimal.ONE, job0.getId());
    assertEquals("job.ndk", job0.getProfileName());
    assertEquals("test", job0.getUserName());
}
 
Example 13
@Test
public void testRemove() throws Exception {
    IDataSet db = database(
            support.loadFlatXmlDataStream(getClass(), "user.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_job.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_task.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_param.xml")
            );
    support.cleanInsert(support.getConnection(tx), db);
    tx.commit();

    Task task = new Task().addId(BigDecimal.ONE);
    List<TaskParameter> params = dao.find(task.getId());
    assertEquals(2, params.size());

    dao.remove(task.getId());
    tx.commit();

    params = dao.find(task.getId());
    assertEquals(0, params.size());
}
 
Example 14
Source Project: database-rider   Source File: DataSetBuilderExporterIt.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldExportEmptyTablesUsingColumnValuesSyntax() {
    executor.createDataSet(new DataSetConfig("yml/empty.yml"));
    IDataSet iDataSet = createDataSetFromDatabase();
    File outputDir = Paths.get("target/FromEmptyYamlColumnValuesSyntax.java").toAbsolutePath().toFile();
    new DataSetBuilderExporter().export(iDataSet, new BuilderExportConfig(BuilderType.COLUMNS_VALUES, outputDir));
    assertThat(contentOf(outputDir)).
            contains("DataSetBuilder builder = new DataSetBuilder();" + NEW_LINE +
                    "IDataSet dataSet = builder" + NEW_LINE +
                    "    .table(\"FOLLOWER\")" + NEW_LINE +
                    "    .table(\"SEQUENCE\")" + NEW_LINE +
                    "        .columns(\"SEQ_NAME\", \"SEQ_COUNT\")" + NEW_LINE +
                    "        .values(\"SEQ_GEN\", 0)" + NEW_LINE +
                    "    .table(\"TWEET\")" + NEW_LINE +
                    "    .table(\"USER\").build();");
}
 
Example 15
Source Project: SpringCloud   Source File: TestUserDao.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFindByArgs() throws DatabaseUnitException, SQLException {
    IDataSet ds = createDateSet("t_user");
    DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
    SystemContext.setOrder("desc");
    SystemContext.setSort("id");
    SystemContext.setPageSize(3);
    SystemContext.setPageOffset(0);
    Pager<User> expected = userDao.find("from User where id>=? and id<=?", new Object[] { 1, 10 });
    List<User> actuals = Arrays.asList(new User(10, "admin10"), new User(9, "admin9"), new User(8, "admin8"));
    assertNotNull(expected);
    assertTrue(expected.getTotal() == 10);
    assertTrue(expected.getOffset() == 0);
    assertTrue(expected.getSize() == 3);
    EntitiesHelper.assertUsers(expected.getDatas(), actuals);
}
 
Example 16
@Test
public void testAddTaskReference() throws Exception {
    IDataSet db = database(
            support.loadFlatXmlDataStream(getClass(), "user.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_job.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_task.xml"),
            support.loadFlatXmlDataStream(getClass(), "wf_material.xml")
            );
    support.cleanInsert(support.getConnection(tx), db);
    tx.commit();

    Material m1 = dao.find(BigDecimal.ONE);
    Task t1 = daoTask.find(BigDecimal.ONE);
    dao.addTaskReference(m1, t1, Way.INPUT);
    tx.commit();

    MaterialFilter filter = new MaterialFilter();
    filter.setId(m1.getId());
    filter.setTaskId(t1.getId());
    filter.setSortBy(schema.tableWorkflowMaterialInTask.way.getBeanPropertyName());
    List<MaterialView> result = dao.view(filter);
    assertEquals(2, result.size());
    assertEquals(BigDecimal.ONE, result.get(0).getId());
    assertEquals(Way.INPUT, result.get(0).getWay());
    assertEquals(BigDecimal.ONE, result.get(1).getId());
    assertEquals(Way.OUTPUT, result.get(1).getWay());
}
 
Example 17
/**
 * Charge le jeu de données à partir d'un fichier XML d'import
 * @return 
 * @throws java.lang.Exception 
 */
@Override
protected IDataSet getDataSet() throws Exception {
    FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
    builder.setColumnSensing(true);
    ReplacementDataSet dataSet = new ReplacementDataSet(builder.build(new FileInputStream(
            getInputDataFileName())));
    dataSet.addReplacementObject("[NULL]", null);
    return dataSet;
}
 
Example 18
Source Project: jpa-unit   Source File: DataSetLoaderProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataSetLoader<IDataSet> xlsLoader() {
    return (final File path) -> {
        try (InputStream in = new FileInputStream(path)) {
            return defineReplaceableExpressions(new XlsDataSet(in));
        } catch (final DataSetException e) {
            throw new IOException(e);
        }
    };
}
 
Example 19
Source Project: wetech-cms   Source File: AbstractDbUnitTestCase.java    License: MIT License 5 votes vote down vote up
private void writeBackupFile(IDataSet ds) throws IOException, DataSetException {
	tempFile = File.createTempFile("back", "xml");
	dtdFile = File.createTempFile("back","dtd");
	//写dtd
	FlatDtdDataSet.write(ds, new FileWriter(dtdFile));
	//写数据表中的文件
	FlatXmlDataSet.write(ds, new FileWriter(tempFile));
}
 
Example 20
Source Project: wetech-cms   Source File: ChannelDaoTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp() throws SQLException, IOException, DatabaseUnitException {
	//此时最好不要使用Spring的Transactional来管理,因为dbunit是通过jdbc来处理connection,再使用spring在一些编辑操作中会造成事务shisu
	Session s = sessionFactory.openSession();
	TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));
	this.backupAllTable();
	IDataSet ds = createDateSet("topic");
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds);
}
 
Example 21
Source Project: jpa-unit   Source File: DataSetLoaderProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataSetLoader<IDataSet> csvLoader() {
    return (final File path) -> {
        try {
            return defineReplaceableExpressions(new CsvDataSet(path));
        } catch (final DataSetException e) {
            throw new IOException(e);
        }
    };
}
 
Example 22
Source Project: database-rider   Source File: DBRiderInterceptorIt.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IDataSet provide() throws DataSetException {
	DataSetBuilder builder = new DataSetBuilder();
	builder.table("user")
			.row()
			    .column("id", 1)
			    .column("name", "@dbunit")
			.row()
			     .column("id", 2)
			     .column("name", "@dbrider");
	return builder.build();
}
 
Example 23
Source Project: Zebra   Source File: H2DatabaseTestCase.java    License: Apache License 2.0 5 votes vote down vote up
protected void cleanlyInsert(String driver, String jdbcUrl, String user, String password, IDataSet dataSet)
		throws Exception {
	IDatabaseTester databaseTester = new JdbcDatabaseTester(driver, jdbcUrl, user, password);
	databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
	databaseTester.setDataSet(dataSet);
	databaseTester.onSetup();
}
 
Example 24
Source Project: database-rider   Source File: DataSetProviderIt.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IDataSet provide()  {
    DataSetBuilder builder = new DataSetBuilder();
    builder.table("user")
            .row()
                .column("id", 1)
                .column("name", "@dbunit")
            .row()
                .column("id", 2)
                .column("name", "@dbrider");
    return builder.build();
}
 
Example 25
Source Project: wetech-cms   Source File: UserDaoTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testListByArgs() throws DatabaseUnitException, SQLException {
	IDataSet ds = createDateSet("t_user");
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds);
	SystemContext.setOrder("desc");
	SystemContext.setSort("id");
	List<User> expected = userDao.list("from User where id>? and id<?", new Object[]{1,4});
	List<User> actuals = Arrays.asList(new User(3,"admin3"),new User(2,"admin2"));
	assertNotNull(expected);
	assertTrue(expected.size()==2);
	EntitiesHelper.assertUsers(expected, actuals);
}
 
Example 26
Source Project: wetech-cms   Source File: AbstractDbUnitTestCase.java    License: MIT License 5 votes vote down vote up
protected IDataSet createDateSet(String tname) throws DataSetException, FileNotFoundException, IOException {
	InputStream is = AbstractDbUnitTestCase
				.class
				.getClassLoader().getResourceAsStream(tname+".xml");
	Assert.assertNotNull("dbunit的基本数据文件不存在",is);
	//通过dtd和传入的文件创建测试的IDataSet
	return new FlatXmlDataSet(new FlatXmlProducer(new InputSource(is),new FlatDtdDataSet(new FileReader(dtdFile))));
}
 
Example 27
Source Project: tutorials   Source File: DataSourceDBUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenDataSetEmptySchema_whenDataSetCreated_thenTablesAreEqual() throws Exception {
    IDataSet expectedDataSet = getDataSet();
    ITable expectedTable = expectedDataSet.getTable("CLIENTS");
    IDataSet databaseDataSet = getConnection().createDataSet();
    ITable actualTable = databaseDataSet.getTable("CLIENTS");
    Assertion.assertEquals(expectedTable, actualTable);
}
 
Example 28
Source Project: database-rider   Source File: DataSetProviderIt.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IDataSet provide() throws DataSetException {
    DataSetBuilder builder = new DataSetBuilder();
    builder.table("user")
            .row()
                .column("id", 2)
                .column("name", "@dbrider");
    return builder.build();
}
 
Example 29
Source Project: database-rider   Source File: DataSetProviderIt.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IDataSet provide() throws DataSetException {
    DataSetBuilder builder = new DataSetBuilder();
    builder.table("TWEET")
            .row()
                .column("ID", "abcdef12345")
                .column("CONTENT", "dbrider rules!")
                .column("DATE", "[DAY,NOW]");
    return builder.build();
}
 
Example 30
/**
 * Deletes all rows of tables present in the specified dataset. If the
 * dataset does not contains a particular table, but that table exists in
 * the database, the database table is not affected. Table are truncated in
 * reverse sequence.
 *
 * @param dataSet
 * @throws Exception
 */
protected void deleteFromDatabase(IDataSet dataSet) throws Exception {
    IDatabaseConnection connection = null;
    try {
        connection = getConnection();
        DatabaseOperation.DELETE.execute(connection, dataSet);
    } finally {
        closeConnection(connection);
    }
}