231 changes: 116 additions & 115 deletions tests/qt_modeltest/dynamictreemodel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@
#include <QtCore/QTimer>


DynamicTreeModel::DynamicTreeModel(QObject *parent)
: QAbstractItemModel(parent),
nextId(1)
DynamicTreeModel::DynamicTreeModel( QObject *parent )
: QAbstractItemModel( parent ),
nextId( 1 )
{
}

QModelIndex DynamicTreeModel::index(int row, int column, const QModelIndex &parent) const
QModelIndex DynamicTreeModel::index( int row, int column, const QModelIndex &parent ) const
{
// if (column != 0)
// return QModelIndex();
Expand All @@ -61,47 +61,48 @@ QModelIndex DynamicTreeModel::index(int row, int column, const QModelIndex &pare
if ( column < 0 || row < 0 )
return QModelIndex();

QList<QList<qint64> > childIdColumns = m_childItems.value(parent.internalId());
QList<QList<qint64> > childIdColumns = m_childItems.value( parent.internalId() );

const qint64 grandParent = findParentId(parent.internalId());
if (grandParent >= 0) {
QList<QList<qint64> > parentTable = m_childItems.value(grandParent);
Q_ASSERT(parent.column() < parentTable.size());
QList<qint64> parentSiblings = parentTable.at(parent.column());
Q_ASSERT(parent.row() < parentSiblings.size());
const qint64 grandParent = findParentId( parent.internalId() );
if ( grandParent >= 0 )
{
QList<QList<qint64> > parentTable = m_childItems.value( grandParent );
Q_ASSERT( parent.column() < parentTable.size() );
QList<qint64> parentSiblings = parentTable.at( parent.column() );
Q_ASSERT( parent.row() < parentSiblings.size() );
}

if (childIdColumns.size() == 0)
if ( childIdColumns.size() == 0 )
return QModelIndex();

if (column >= childIdColumns.size())
if ( column >= childIdColumns.size() )
return QModelIndex();

QList<qint64> rowIds = childIdColumns.at(column);
QList<qint64> rowIds = childIdColumns.at( column );

if ( row >= rowIds.size())
if ( row >= rowIds.size() )
return QModelIndex();

qint64 id = rowIds.at(row);
qint64 id = rowIds.at( row );

return createIndex(row, column, reinterpret_cast<void *>(id));
return createIndex( row, column, reinterpret_cast<void *>( id ) );

}

qint64 DynamicTreeModel::findParentId(qint64 searchId) const
qint64 DynamicTreeModel::findParentId( qint64 searchId ) const
{
if (searchId <= 0)
if ( searchId <= 0 )
return -1;

QHashIterator<qint64, QList<QList<qint64> > > i(m_childItems);
while (i.hasNext())
QHashIterator<qint64, QList<QList<qint64> > > i( m_childItems );
while ( i.hasNext() )
{
i.next();
QListIterator<QList<qint64> > j(i.value());
while (j.hasNext())
QListIterator<QList<qint64> > j( i.value() );
while ( j.hasNext() )
{
QList<qint64> l = j.next();
if (l.contains(searchId))
if ( l.contains( searchId ) )
{
return i.key();
}
Expand All @@ -110,57 +111,57 @@ qint64 DynamicTreeModel::findParentId(qint64 searchId) const
return -1;
}

QModelIndex DynamicTreeModel::parent(const QModelIndex &index) const
QModelIndex DynamicTreeModel::parent( const QModelIndex &index ) const
{
if (!index.isValid())
if ( !index.isValid() )
return QModelIndex();

qint64 searchId = index.internalId();
qint64 parentId = findParentId(searchId);
qint64 parentId = findParentId( searchId );
// Will never happen for valid index, but what the hey...
if (parentId <= 0)
if ( parentId <= 0 )
return QModelIndex();

qint64 grandParentId = findParentId(parentId);
if (grandParentId < 0)
qint64 grandParentId = findParentId( parentId );
if ( grandParentId < 0 )
grandParentId = 0;

int column = 0;
QList<qint64> childList = m_childItems.value(grandParentId).at(column);
QList<qint64> childList = m_childItems.value( grandParentId ).at( column );

int row = childList.indexOf(parentId);
int row = childList.indexOf( parentId );

return createIndex(row, column, reinterpret_cast<void *>(parentId));
return createIndex( row, column, reinterpret_cast<void *>( parentId ) );

}

int DynamicTreeModel::rowCount(const QModelIndex &index ) const
int DynamicTreeModel::rowCount( const QModelIndex &index ) const
{
QList<QList<qint64> > cols = m_childItems.value(index.internalId());
QList<QList<qint64> > cols = m_childItems.value( index.internalId() );

if (cols.size() == 0 )
if ( cols.size() == 0 )
return 0;

if (index.column() > 0)
if ( index.column() > 0 )
return 0;

return cols.at(0).size();
return cols.at( 0 ).size();
}

int DynamicTreeModel::columnCount(const QModelIndex &index ) const
int DynamicTreeModel::columnCount( const QModelIndex &index ) const
{
// Q_UNUSED(index);
return m_childItems.value(index.internalId()).size();
return m_childItems.value( index.internalId() ).size();
}

QVariant DynamicTreeModel::data(const QModelIndex &index, int role) const
QVariant DynamicTreeModel::data( const QModelIndex &index, int role ) const
{
if (!index.isValid())
if ( !index.isValid() )
return QVariant();

if (Qt::DisplayRole == role)
if ( Qt::DisplayRole == role )
{
return m_items.value(index.internalId());
return m_items.value( index.internalId() );
}
return QVariant();
}
Expand All @@ -176,111 +177,111 @@ void DynamicTreeModel::clear()


ModelChangeCommand::ModelChangeCommand( DynamicTreeModel *model, QObject *parent )
: QObject(parent), m_model(model), m_numCols(1), m_startRow(-1), m_endRow(-1)
: QObject( parent ), m_model( model ), m_numCols( 1 ), m_startRow( -1 ), m_endRow( -1 )
{

}

QModelIndex ModelChangeCommand::findIndex(QList<int> rows)
QModelIndex ModelChangeCommand::findIndex( QList<int> rows )
{
const int col = 0;
QModelIndex parent = QModelIndex();
QListIterator<int> i(rows);
while (i.hasNext())
QListIterator<int> i( rows );
while ( i.hasNext() )
{
parent = m_model->index(i.next(), col, parent);
Q_ASSERT(parent.isValid());
parent = m_model->index( i.next(), col, parent );
Q_ASSERT( parent.isValid() );
}
return parent;
}

ModelInsertCommand::ModelInsertCommand(DynamicTreeModel *model, QObject *parent )
: ModelChangeCommand(model, parent)
ModelInsertCommand::ModelInsertCommand( DynamicTreeModel *model, QObject *parent )
: ModelChangeCommand( model, parent )
{

}

void ModelInsertCommand::doCommand()
{
QModelIndex parent = findIndex(m_rowNumbers);
m_model->beginInsertRows(parent, m_startRow, m_endRow);
QModelIndex parent = findIndex( m_rowNumbers );
m_model->beginInsertRows( parent, m_startRow, m_endRow );
qint64 parentId = parent.internalId();
for (int row = m_startRow; row <= m_endRow; row++)
for ( int row = m_startRow; row <= m_endRow; row++ )
{
for(int col = 0; col < m_numCols; col++ )
for ( int col = 0; col < m_numCols; col++ )
{
if (m_model->m_childItems[parentId].size() <= col)
if ( m_model->m_childItems[parentId].size() <= col )
{
m_model->m_childItems[parentId].append(QList<qint64>());
m_model->m_childItems[parentId].append( QList<qint64>() );
}
// QString name = QUuid::createUuid().toString();
qint64 id = m_model->newId();
QString name = QString::number(id);
QString name = QString::number( id );

m_model->m_items.insert(id, name);
m_model->m_childItems[parentId][col].insert(row, id);
m_model->m_items.insert( id, name );
m_model->m_childItems[parentId][col].insert( row, id );

}
}
m_model->endInsertRows();
}


ModelMoveCommand::ModelMoveCommand(DynamicTreeModel *model, QObject *parent)
: ModelChangeCommand(model, parent)
ModelMoveCommand::ModelMoveCommand( DynamicTreeModel *model, QObject *parent )
: ModelChangeCommand( model, parent )
{

}
bool ModelMoveCommand::emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow)
bool ModelMoveCommand::emitPreSignal( const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow )
{
return m_model->beginMoveRows(srcParent, srcStart, srcEnd, destParent, destRow);
return m_model->beginMoveRows( srcParent, srcStart, srcEnd, destParent, destRow );
}

void ModelMoveCommand::doCommand()
{
QModelIndex srcParent = findIndex(m_rowNumbers);
QModelIndex destParent = findIndex(m_destRowNumbers);
QModelIndex srcParent = findIndex( m_rowNumbers );
QModelIndex destParent = findIndex( m_destRowNumbers );

if (!emitPreSignal(srcParent, m_startRow, m_endRow, destParent, m_destRow))
if ( !emitPreSignal( srcParent, m_startRow, m_endRow, destParent, m_destRow ) )
{
return;
}

for ( int column = 0; column < m_numCols; ++column )
{
QList<qint64> l = m_model->m_childItems.value( srcParent.internalId() )[column].mid( m_startRow, m_endRow - m_startRow + 1 );

for ( int i = m_startRow; i <= m_endRow ; i++ )
{
m_model->m_childItems[srcParent.internalId()][column].removeAt( m_startRow );
}
int d;
if ( m_destRow < m_startRow )
d = m_destRow;
else
{
return;
if ( srcParent == destParent )
d = m_destRow - ( m_endRow - m_startRow + 1 );
else
d = m_destRow - ( m_endRow - m_startRow ) + 1;
}

for (int column = 0; column < m_numCols; ++column)
foreach( const qint64 id, l )
{
QList<qint64> l = m_model->m_childItems.value(srcParent.internalId())[column].mid(m_startRow, m_endRow - m_startRow + 1 );

for (int i = m_startRow; i <= m_endRow ; i++)
{
m_model->m_childItems[srcParent.internalId()][column].removeAt(m_startRow);
}
int d;
if (m_destRow < m_startRow)
d = m_destRow;
else
{
if (srcParent == destParent)
d = m_destRow - (m_endRow - m_startRow + 1);
else
d = m_destRow - (m_endRow - m_startRow) + 1;
}

foreach(const qint64 id, l)
{
m_model->m_childItems[destParent.internalId()][column].insert(d++, id);
}
m_model->m_childItems[destParent.internalId()][column].insert( d++, id );
}
}

emitPostSignal();
emitPostSignal();
}

void ModelMoveCommand::emitPostSignal()
{
m_model->endMoveRows();
m_model->endMoveRows();
}

ModelResetCommand::ModelResetCommand(DynamicTreeModel* model, QObject* parent)
: ModelMoveCommand(model, parent)
ModelResetCommand::ModelResetCommand( DynamicTreeModel* model, QObject* parent )
: ModelMoveCommand( model, parent )
{

}
Expand All @@ -290,24 +291,24 @@ ModelResetCommand::~ModelResetCommand()

}

bool ModelResetCommand::emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow)
bool ModelResetCommand::emitPreSignal( const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow )
{
Q_UNUSED(srcParent);
Q_UNUSED(srcStart);
Q_UNUSED(srcEnd);
Q_UNUSED(destParent);
Q_UNUSED(destRow);
Q_UNUSED( srcParent );
Q_UNUSED( srcStart );
Q_UNUSED( srcEnd );
Q_UNUSED( destParent );
Q_UNUSED( destRow );

return true;
return true;
}

void ModelResetCommand::emitPostSignal()
{
m_model->reset();
m_model->reset();
}

ModelResetCommandFixed::ModelResetCommandFixed(DynamicTreeModel* model, QObject* parent)
: ModelMoveCommand(model, parent)
ModelResetCommandFixed::ModelResetCommandFixed( DynamicTreeModel* model, QObject* parent )
: ModelMoveCommand( model, parent )
{

}
Expand All @@ -317,20 +318,20 @@ ModelResetCommandFixed::~ModelResetCommandFixed()

}

bool ModelResetCommandFixed::emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow)
bool ModelResetCommandFixed::emitPreSignal( const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow )
{
Q_UNUSED(srcParent);
Q_UNUSED(srcStart);
Q_UNUSED(srcEnd);
Q_UNUSED(destParent);
Q_UNUSED(destRow);

m_model->beginResetModel();
return true;
Q_UNUSED( srcParent );
Q_UNUSED( srcStart );
Q_UNUSED( srcEnd );
Q_UNUSED( destParent );
Q_UNUSED( destRow );

m_model->beginResetModel();
return true;
}

void ModelResetCommandFixed::emitPostSignal()
{
m_model->endResetModel();
m_model->endResetModel();
}

146 changes: 73 additions & 73 deletions tests/qt_modeltest/dynamictreemodel.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,130 +50,130 @@

class DynamicTreeModel : public QAbstractItemModel
{
Q_OBJECT
Q_OBJECT

public:
DynamicTreeModel(QObject *parent = 0);
public:
DynamicTreeModel( QObject *parent = 0 );

QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex &index) const;
int rowCount(const QModelIndex &index = QModelIndex()) const;
int columnCount(const QModelIndex &index = QModelIndex()) const;
QModelIndex index( int row, int column, const QModelIndex &parent = QModelIndex() ) const;
QModelIndex parent( const QModelIndex &index ) const;
int rowCount( const QModelIndex &index = QModelIndex() ) const;
int columnCount( const QModelIndex &index = QModelIndex() ) const;

QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
QVariant data( const QModelIndex &index, int role = Qt::DisplayRole ) const;

void clear();
void clear();

protected slots:
protected slots:

/**
Finds the parent id of the string with id @p searchId.
/**
Finds the parent id of the string with id @p searchId.
Returns -1 if not found.
*/
qint64 findParentId(qint64 searchId) const;
Returns -1 if not found.
*/
qint64 findParentId( qint64 searchId ) const;

private:
QHash<qint64, QString> m_items;
QHash<qint64, QList<QList<qint64> > > m_childItems;
qint64 nextId;
qint64 newId() { return nextId++; };
private:
QHash<qint64, QString> m_items;
QHash<qint64, QList<QList<qint64> > > m_childItems;
qint64 nextId;
qint64 newId() { return nextId++; };

QModelIndex m_nextParentIndex;
int m_nextRow;
QModelIndex m_nextParentIndex;
int m_nextRow;

int m_depth;
int maxDepth;
int m_depth;
int maxDepth;

friend class ModelInsertCommand;
friend class ModelMoveCommand;
friend class ModelResetCommand;
friend class ModelResetCommandFixed;
friend class ModelInsertCommand;
friend class ModelMoveCommand;
friend class ModelResetCommand;
friend class ModelResetCommandFixed;

};


class ModelChangeCommand : public QObject
{
Q_OBJECT
public:
Q_OBJECT
public:

ModelChangeCommand( DynamicTreeModel *model, QObject *parent = 0 );
ModelChangeCommand( DynamicTreeModel *model, QObject *parent = 0 );

virtual ~ModelChangeCommand() {}
virtual ~ModelChangeCommand() {}

void setAncestorRowNumbers(QList<int> rowNumbers) { m_rowNumbers = rowNumbers; }
void setAncestorRowNumbers( QList<int> rowNumbers ) { m_rowNumbers = rowNumbers; }

QModelIndex findIndex(QList<int> rows);
QModelIndex findIndex( QList<int> rows );

void setStartRow(int row) { m_startRow = row; }
void setStartRow( int row ) { m_startRow = row; }

void setEndRow(int row) { m_endRow = row; }
void setEndRow( int row ) { m_endRow = row; }

void setNumCols(int cols) { m_numCols = cols; }
void setNumCols( int cols ) { m_numCols = cols; }

virtual void doCommand() = 0;
virtual void doCommand() = 0;

protected:
DynamicTreeModel* m_model;
QList<int> m_rowNumbers;
int m_numCols;
int m_startRow;
int m_endRow;
protected:
DynamicTreeModel* m_model;
QList<int> m_rowNumbers;
int m_numCols;
int m_startRow;
int m_endRow;

};

typedef QList<ModelChangeCommand*> ModelChangeCommandList;

class ModelInsertCommand : public ModelChangeCommand
{
Q_OBJECT
Q_OBJECT

public:
public:

ModelInsertCommand(DynamicTreeModel *model, QObject *parent = 0 );
virtual ~ModelInsertCommand() {}
ModelInsertCommand( DynamicTreeModel *model, QObject *parent = 0 );
virtual ~ModelInsertCommand() {}

virtual void doCommand();
virtual void doCommand();
};


class ModelMoveCommand : public ModelChangeCommand
{
Q_OBJECT
public:
ModelMoveCommand(DynamicTreeModel *model, QObject *parent);
Q_OBJECT
public:
ModelMoveCommand( DynamicTreeModel *model, QObject *parent );

virtual ~ModelMoveCommand() {}
virtual ~ModelMoveCommand() {}

virtual bool emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow);
virtual bool emitPreSignal( const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow );

virtual void doCommand();
virtual void doCommand();

virtual void emitPostSignal();
virtual void emitPostSignal();

void setDestAncestors( QList<int> rows ) { m_destRowNumbers = rows; }
void setDestAncestors( QList<int> rows ) { m_destRowNumbers = rows; }

void setDestRow(int row) { m_destRow = row; }
void setDestRow( int row ) { m_destRow = row; }

protected:
QList<int> m_destRowNumbers;
int m_destRow;
protected:
QList<int> m_destRowNumbers;
int m_destRow;
};

/**
A command which does a move and emits a reset signal.
*/
class ModelResetCommand : public ModelMoveCommand
{
Q_OBJECT
public:
ModelResetCommand(DynamicTreeModel* model, QObject* parent = 0);
Q_OBJECT
public:
ModelResetCommand( DynamicTreeModel* model, QObject* parent = 0 );

virtual ~ModelResetCommand();
virtual ~ModelResetCommand();

virtual bool emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow);
virtual void emitPostSignal();
virtual bool emitPreSignal( const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow );
virtual void emitPostSignal();

};

Expand All @@ -182,14 +182,14 @@ class ModelResetCommand : public ModelMoveCommand
*/
class ModelResetCommandFixed : public ModelMoveCommand
{
Q_OBJECT
public:
ModelResetCommandFixed(DynamicTreeModel* model, QObject* parent = 0);
Q_OBJECT
public:
ModelResetCommandFixed( DynamicTreeModel* model, QObject* parent = 0 );

virtual ~ModelResetCommandFixed();
virtual ~ModelResetCommandFixed();

virtual bool emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow);
virtual void emitPostSignal();
virtual bool emitPreSignal( const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow );
virtual void emitPostSignal();

};

Expand Down
722 changes: 371 additions & 351 deletions tests/qt_modeltest/modeltest.cpp

Large diffs are not rendered by default.

65 changes: 33 additions & 32 deletions tests/qt_modeltest/modeltest.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,46 +49,47 @@

class ModelTest : public QObject
{
Q_OBJECT
Q_OBJECT

public:
ModelTest( QAbstractItemModel *model, QObject *parent = 0 );
public:
ModelTest( QAbstractItemModel *model, QObject *parent = 0 );

private Q_SLOTS:
void nonDestructiveBasicTest();
void rowCount();
void columnCount();
void hasIndex();
void index();
void parent();
void data();
private Q_SLOTS:
void nonDestructiveBasicTest();
void rowCount();
void columnCount();
void hasIndex();
void index();
void parent();
void data();

protected Q_SLOTS:
void runAllTests();
void layoutAboutToBeChanged();
void layoutChanged();
void rowsAboutToBeInserted( const QModelIndex &parent, int start, int end );
void rowsInserted( const QModelIndex & parent, int start, int end );
void rowsAboutToBeRemoved( const QModelIndex &parent, int start, int end );
void rowsRemoved( const QModelIndex & parent, int start, int end );
protected Q_SLOTS:
void runAllTests();
void layoutAboutToBeChanged();
void layoutChanged();
void rowsAboutToBeInserted( const QModelIndex &parent, int start, int end );
void rowsInserted( const QModelIndex & parent, int start, int end );
void rowsAboutToBeRemoved( const QModelIndex &parent, int start, int end );
void rowsRemoved( const QModelIndex & parent, int start, int end );

private:
void checkChildren( const QModelIndex &parent, int currentDepth = 0 );
private:
void checkChildren( const QModelIndex &parent, int currentDepth = 0 );

QAbstractItemModel *model;
QAbstractItemModel *model;

struct Changing {
QModelIndex parent;
int oldSize;
QVariant last;
QVariant next;
};
QStack<Changing> insert;
QStack<Changing> remove;
struct Changing
{
QModelIndex parent;
int oldSize;
QVariant last;
QVariant next;
};
QStack<Changing> insert;
QStack<Changing> remove;

bool fetchingMore;
bool fetchingMore;

QList<QPersistentModelIndex> changing;
QList<QPersistentModelIndex> changing;
};

#endif
286 changes: 145 additions & 141 deletions tests/qt_modeltest/tst_modeltest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,17 @@ class tst_ModelTest : public QObject
{
Q_OBJECT

public:
public:
tst_ModelTest() {}
virtual ~tst_ModelTest() {}

public slots:
public slots:
void initTestCase();
void cleanupTestCase();
void init();
void cleanup();

private slots:
private slots:
void stringListModel();
void treeWidgetModel();
void standardItemModel();
Expand Down Expand Up @@ -94,91 +94,92 @@ void tst_ModelTest::cleanup()

void tst_ModelTest::stringListModel()
{
QStringListModel model;
QSortFilterProxyModel proxy;
QStringListModel model;
QSortFilterProxyModel proxy;

ModelTest t1(&model);
ModelTest t2(&proxy);
ModelTest t1( &model );
ModelTest t2( &proxy );

proxy.setSourceModel(&model);
proxy.setSourceModel( &model );

model.setStringList(QStringList() << "2" << "3" << "1");
model.setStringList(QStringList() << "a" << "e" << "plop" << "b" << "c" );
model.setStringList( QStringList() << "2" << "3" << "1" );
model.setStringList( QStringList() << "a" << "e" << "plop" << "b" << "c" );

proxy.setDynamicSortFilter(true);
proxy.setFilterRegExp(QRegExp("[^b]"));
proxy.setDynamicSortFilter( true );
proxy.setFilterRegExp( QRegExp( "[^b]" ) );
}

void tst_ModelTest::treeWidgetModel()
{
QTreeWidget widget;

ModelTest t1(widget.model());

QTreeWidgetItem *root = new QTreeWidgetItem(&widget, QStringList("root"));
for (int i = 0; i < 20; ++i) {
new QTreeWidgetItem(root, QStringList(QString::number(i)));
}
QTreeWidgetItem *remove = root->child(2);
root->removeChild(remove);
QTreeWidgetItem *parent = new QTreeWidgetItem(&widget, QStringList("parent"));
new QTreeWidgetItem(parent, QStringList("child"));
widget.setItemHidden(parent, true);

widget.sortByColumn(0);
QTreeWidget widget;

ModelTest t1( widget.model() );

QTreeWidgetItem *root = new QTreeWidgetItem( &widget, QStringList( "root" ) );
for ( int i = 0; i < 20; ++i )
{
new QTreeWidgetItem( root, QStringList( QString::number( i ) ) );
}
QTreeWidgetItem *remove = root->child( 2 );
root->removeChild( remove );
QTreeWidgetItem *parent = new QTreeWidgetItem( &widget, QStringList( "parent" ) );
new QTreeWidgetItem( parent, QStringList( "child" ) );
widget.setItemHidden( parent, true );

widget.sortByColumn( 0 );
}

void tst_ModelTest::standardItemModel()
{
QStandardItemModel model(10,10);
QSortFilterProxyModel proxy;
QStandardItemModel model( 10, 10 );
QSortFilterProxyModel proxy;


ModelTest t1(&model);
ModelTest t2(&proxy);
ModelTest t1( &model );
ModelTest t2( &proxy );

proxy.setSourceModel(&model);
proxy.setSourceModel( &model );

model.insertRows(2, 5);
model.removeRows(4, 5);
model.insertRows( 2, 5 );
model.removeRows( 4, 5 );

model.insertColumns(2, 5);
model.removeColumns(4, 5);
model.insertColumns( 2, 5 );
model.removeColumns( 4, 5 );

model.insertRows(0,5, model.index(1,1));
model.insertColumns(0,5, model.index(1,3));
model.insertRows( 0, 5, model.index( 1, 1 ) );
model.insertColumns( 0, 5, model.index( 1, 3 ) );
}

void tst_ModelTest::testInsertThroughProxy()
{
DynamicTreeModel *model = new DynamicTreeModel(this);

QSortFilterProxyModel *proxy = new QSortFilterProxyModel(this);
proxy->setSourceModel(model);

new ModelTest(proxy, this);

ModelInsertCommand *insertCommand = new ModelInsertCommand(model, this);
insertCommand->setNumCols(4);
insertCommand->setStartRow(0);
insertCommand->setEndRow(9);
// Parent is QModelIndex()
insertCommand->doCommand();

insertCommand = new ModelInsertCommand(model, this);
insertCommand->setNumCols(4);
insertCommand->setAncestorRowNumbers(QList<int>() << 5);
insertCommand->setStartRow(0);
insertCommand->setEndRow(9);
insertCommand->doCommand();

ModelMoveCommand *moveCommand = new ModelMoveCommand(model, this);
moveCommand->setNumCols(4);
moveCommand->setStartRow(0);
moveCommand->setEndRow(0);
moveCommand->setDestRow(9);
moveCommand->setDestAncestors(QList<int>() << 5);
moveCommand->doCommand();
DynamicTreeModel *model = new DynamicTreeModel( this );

QSortFilterProxyModel *proxy = new QSortFilterProxyModel( this );
proxy->setSourceModel( model );

new ModelTest( proxy, this );

ModelInsertCommand *insertCommand = new ModelInsertCommand( model, this );
insertCommand->setNumCols( 4 );
insertCommand->setStartRow( 0 );
insertCommand->setEndRow( 9 );
// Parent is QModelIndex()
insertCommand->doCommand();

insertCommand = new ModelInsertCommand( model, this );
insertCommand->setNumCols( 4 );
insertCommand->setAncestorRowNumbers( QList<int>() << 5 );
insertCommand->setStartRow( 0 );
insertCommand->setEndRow( 9 );
insertCommand->doCommand();

ModelMoveCommand *moveCommand = new ModelMoveCommand( model, this );
moveCommand->setNumCols( 4 );
moveCommand->setStartRow( 0 );
moveCommand->setEndRow( 0 );
moveCommand->setDestRow( 9 );
moveCommand->setDestAncestors( QList<int>() << 5 );
moveCommand->doCommand();
}

/**
Expand All @@ -187,123 +188,126 @@ void tst_ModelTest::testInsertThroughProxy()
class AccessibleProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
AccessibleProxyModel(QObject *parent = 0) : QSortFilterProxyModel(parent) {}
public:
AccessibleProxyModel( QObject *parent = 0 ) : QSortFilterProxyModel( parent ) {}

QModelIndexList persistent()
{
return persistentIndexList();
return persistentIndexList();
}
};

class ObservingObject : public QObject
{
Q_OBJECT
public:
ObservingObject(AccessibleProxyModel *proxy, QObject *parent = 0)
: QObject(parent),
m_proxy(proxy)
public:
ObservingObject( AccessibleProxyModel *proxy, QObject *parent = 0 )
: QObject( parent ),
m_proxy( proxy )
{
connect(m_proxy, SIGNAL(layoutAboutToBeChanged()), SLOT(storePersistent()));
connect(m_proxy, SIGNAL(layoutChanged()), SLOT(checkPersistent()));
connect( m_proxy, SIGNAL( layoutAboutToBeChanged() ), SLOT( storePersistent() ) );
connect( m_proxy, SIGNAL( layoutChanged() ), SLOT( checkPersistent() ) );
}

public slots:
public slots:

void storePersistent(const QModelIndex &parent)
void storePersistent( const QModelIndex &parent )
{
for (int row = 0; row < m_proxy->rowCount(parent); ++row) {
QModelIndex proxyIndex = m_proxy->index(row, 0, parent);
QModelIndex sourceIndex = m_proxy->mapToSource(proxyIndex);
Q_ASSERT(proxyIndex.isValid());
Q_ASSERT(sourceIndex.isValid());
m_persistentSourceIndexes.append(sourceIndex);
m_persistentProxyIndexes.append(proxyIndex);
if (m_proxy->hasChildren(proxyIndex))
storePersistent(proxyIndex);
}
for ( int row = 0; row < m_proxy->rowCount( parent ); ++row )
{
QModelIndex proxyIndex = m_proxy->index( row, 0, parent );
QModelIndex sourceIndex = m_proxy->mapToSource( proxyIndex );
Q_ASSERT( proxyIndex.isValid() );
Q_ASSERT( sourceIndex.isValid() );
m_persistentSourceIndexes.append( sourceIndex );
m_persistentProxyIndexes.append( proxyIndex );
if ( m_proxy->hasChildren( proxyIndex ) )
storePersistent( proxyIndex );
}
}

void storePersistent()
{
foreach(const QModelIndex &idx, m_persistentProxyIndexes)
Q_ASSERT(idx.isValid()); // This is called from layoutAboutToBeChanged. Persistent indexes should be valid
foreach( const QModelIndex &idx, m_persistentProxyIndexes )
Q_ASSERT( idx.isValid() ); // This is called from layoutAboutToBeChanged. Persistent indexes should be valid

Q_ASSERT(m_proxy->persistent().isEmpty());
storePersistent(QModelIndex());
Q_ASSERT(!m_proxy->persistent().isEmpty());
Q_ASSERT( m_proxy->persistent().isEmpty() );
storePersistent( QModelIndex() );
Q_ASSERT( !m_proxy->persistent().isEmpty() );
}

void checkPersistent()
{
for (int row = 0; row < m_persistentProxyIndexes.size(); ++row) {
QModelIndex updatedProxy = m_persistentProxyIndexes.at(row);
QModelIndex updatedSource = m_persistentSourceIndexes.at(row);
}
for (int row = 0; row < m_persistentProxyIndexes.size(); ++row) {
QModelIndex updatedProxy = m_persistentProxyIndexes.at(row);
QModelIndex updatedSource = m_persistentSourceIndexes.at(row);
QCOMPARE(m_proxy->mapToSource(updatedProxy), updatedSource);
}
m_persistentSourceIndexes.clear();
m_persistentProxyIndexes.clear();
for ( int row = 0; row < m_persistentProxyIndexes.size(); ++row )
{
QModelIndex updatedProxy = m_persistentProxyIndexes.at( row );
QModelIndex updatedSource = m_persistentSourceIndexes.at( row );
}
for ( int row = 0; row < m_persistentProxyIndexes.size(); ++row )
{
QModelIndex updatedProxy = m_persistentProxyIndexes.at( row );
QModelIndex updatedSource = m_persistentSourceIndexes.at( row );
QCOMPARE( m_proxy->mapToSource( updatedProxy ), updatedSource );
}
m_persistentSourceIndexes.clear();
m_persistentProxyIndexes.clear();
}

private:
private:
AccessibleProxyModel *m_proxy;
QList<QPersistentModelIndex> m_persistentSourceIndexes;
QList<QPersistentModelIndex> m_persistentProxyIndexes;
};

void tst_ModelTest::moveSourceItems()
{
DynamicTreeModel *model = new DynamicTreeModel(this);
AccessibleProxyModel *proxy = new AccessibleProxyModel(this);
proxy->setSourceModel(model);

ModelInsertCommand *insertCommand = new ModelInsertCommand(model, this);
insertCommand->setStartRow(0);
insertCommand->setEndRow(2);
insertCommand->doCommand();

insertCommand = new ModelInsertCommand(model, this);
insertCommand->setAncestorRowNumbers(QList<int>() << 1);
insertCommand->setStartRow(0);
insertCommand->setEndRow(2);
insertCommand->doCommand();

ObservingObject observer(proxy);

ModelMoveCommand *moveCommand = new ModelMoveCommand(model, this);
moveCommand->setStartRow(0);
moveCommand->setEndRow(0);
moveCommand->setDestAncestors(QList<int>() << 1);
moveCommand->setDestRow(0);
moveCommand->doCommand();
DynamicTreeModel *model = new DynamicTreeModel( this );
AccessibleProxyModel *proxy = new AccessibleProxyModel( this );
proxy->setSourceModel( model );

ModelInsertCommand *insertCommand = new ModelInsertCommand( model, this );
insertCommand->setStartRow( 0 );
insertCommand->setEndRow( 2 );
insertCommand->doCommand();

insertCommand = new ModelInsertCommand( model, this );
insertCommand->setAncestorRowNumbers( QList<int>() << 1 );
insertCommand->setStartRow( 0 );
insertCommand->setEndRow( 2 );
insertCommand->doCommand();

ObservingObject observer( proxy );

ModelMoveCommand *moveCommand = new ModelMoveCommand( model, this );
moveCommand->setStartRow( 0 );
moveCommand->setEndRow( 0 );
moveCommand->setDestAncestors( QList<int>() << 1 );
moveCommand->setDestRow( 0 );
moveCommand->doCommand();
}

void tst_ModelTest::testResetThroughProxy()
{
DynamicTreeModel *model = new DynamicTreeModel(this);
DynamicTreeModel *model = new DynamicTreeModel( this );

ModelInsertCommand *insertCommand = new ModelInsertCommand(model, this);
insertCommand->setStartRow(0);
insertCommand->setEndRow(2);
insertCommand->doCommand();
ModelInsertCommand *insertCommand = new ModelInsertCommand( model, this );
insertCommand->setStartRow( 0 );
insertCommand->setEndRow( 2 );
insertCommand->doCommand();

QPersistentModelIndex persistent = model->index(0, 0);
QPersistentModelIndex persistent = model->index( 0, 0 );

AccessibleProxyModel *proxy = new AccessibleProxyModel(this);
proxy->setSourceModel(model);
AccessibleProxyModel *proxy = new AccessibleProxyModel( this );
proxy->setSourceModel( model );

ObservingObject observer(proxy);
observer.storePersistent();
ObservingObject observer( proxy );
observer.storePersistent();

ModelResetCommand *resetCommand = new ModelResetCommand(model, this);
resetCommand->setNumCols(0);
resetCommand->doCommand();
ModelResetCommand *resetCommand = new ModelResetCommand( model, this );
resetCommand->setNumCols( 0 );
resetCommand->doCommand();
}


QTEST_MAIN(tst_ModelTest)
QTEST_MAIN( tst_ModelTest )
#include "tst_modeltest.moc"
66 changes: 33 additions & 33 deletions tests/src/analysis/testqgsvectoranalyzer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,20 @@ class TestQgsVectorAnalyzer: public QObject
void init() ;// will be called before each testfunction is executed.
void cleanup() ;// will be called after every testfunction.
/** Our tests proper begin here */
void singleToMulti( );
void multiToSingle( );
void extractNodes( );
void polygonsToLines( );
void exportGeometryInfo( );
void simplifyGeometry( );
void polygonCentroids( );
void layerExtent( );
void singleToMulti( );
void multiToSingle( );
void extractNodes( );
void polygonsToLines( );
void exportGeometryInfo( );
void simplifyGeometry( );
void polygonCentroids( );
void layerExtent( );
private:
QgsGeometryAnalyzer mAnalyzer;
QgsVectorLayer * mpLineLayer;
QgsVectorLayer * mpPolyLayer;
QgsVectorLayer * mpPointLayer;

};

void TestQgsVectorAnalyzer::initTestCase()
Expand All @@ -50,85 +50,85 @@ void TestQgsVectorAnalyzer::initTestCase()
// Runs once before any tests are run
//
// init QGIS's paths - true means that all path will be inited from prefix
QString qgisPath = QCoreApplication::applicationDirPath ();
QString qgisPath = QCoreApplication::applicationDirPath();
QgsApplication::init( INSTALL_PREFIX );
QgsApplication::initQgis( );
QgsApplication::showSettings();
// Instantiate the plugin directory so that providers are loaded
QgsProviderRegistry::instance(QgsApplication::pluginPath());
QgsProviderRegistry::instance( QgsApplication::pluginPath() );

//create some objects that will be used in all tests...
//create a map layer that will be used in all tests...
QString myBaseFileName (TEST_DATA_DIR); //defined in CmakeLists.txt
QString myBaseFileName( TEST_DATA_DIR ); //defined in CmakeLists.txt
QString myEndName = "lines.shp";
QString myFileName = myBaseFileName + QDir::separator() + myEndName;
qDebug() << myFileName;
QFileInfo myLineInfo ( myFileName );
mpLineLayer = new QgsVectorLayer ( myLineInfo.filePath(),
myLineInfo.completeBaseName(), "ogr" );
QFileInfo myLineInfo( myFileName );
mpLineLayer = new QgsVectorLayer( myLineInfo.filePath(),
myLineInfo.completeBaseName(), "ogr" );

myEndName = "polys.shp";
myFileName = myBaseFileName + QDir::separator() + myEndName;
QFileInfo myPolyInfo ( myFileName );
mpPolyLayer = new QgsVectorLayer ( myPolyInfo.filePath(),
myPolyInfo.completeBaseName(), "ogr" );
QFileInfo myPolyInfo( myFileName );
mpPolyLayer = new QgsVectorLayer( myPolyInfo.filePath(),
myPolyInfo.completeBaseName(), "ogr" );

myEndName = "points.shp";
myFileName = myBaseFileName + QDir::separator() + myEndName;
QFileInfo myPointInfo ( myFileName );
mpPointLayer = new QgsVectorLayer ( myPointInfo.filePath(),
myPointInfo.completeBaseName(), "ogr" );
QFileInfo myPointInfo( myFileName );
mpPointLayer = new QgsVectorLayer( myPointInfo.filePath(),
myPointInfo.completeBaseName(), "ogr" );
}
void TestQgsVectorAnalyzer::cleanupTestCase()
{

}
void TestQgsVectorAnalyzer::init()
void TestQgsVectorAnalyzer::init()
{

}
void TestQgsVectorAnalyzer::cleanup()
void TestQgsVectorAnalyzer::cleanup()
{

}

void TestQgsVectorAnalyzer::singleToMulti( )
void TestQgsVectorAnalyzer::singleToMulti( )
{

}
void TestQgsVectorAnalyzer::multiToSingle( )
void TestQgsVectorAnalyzer::multiToSingle( )
{

}
void TestQgsVectorAnalyzer::extractNodes( )
void TestQgsVectorAnalyzer::extractNodes( )
{

}
void TestQgsVectorAnalyzer::polygonsToLines( )
void TestQgsVectorAnalyzer::polygonsToLines( )
{

}
void TestQgsVectorAnalyzer::exportGeometryInfo( )
void TestQgsVectorAnalyzer::exportGeometryInfo( )
{
}

void TestQgsVectorAnalyzer::simplifyGeometry( )
void TestQgsVectorAnalyzer::simplifyGeometry( )
{
QString myTmpDir = QDir::tempPath() + QDir::separator() ;
QString myFileName = myTmpDir + "simplify_layer.shp";
QVERIFY( mAnalyzer.simplify( mpLineLayer,
myFileName,
1.0 ) );
myFileName,
1.0 ) );
}

void TestQgsVectorAnalyzer::polygonCentroids( )
void TestQgsVectorAnalyzer::polygonCentroids( )
{
QString myTmpDir = QDir::tempPath() + QDir::separator() ;
QString myFileName = myTmpDir + "centroid_layer.shp";
QVERIFY( mAnalyzer.centroids( mpPolyLayer, myFileName ) );
}

void TestQgsVectorAnalyzer::layerExtent( )
void TestQgsVectorAnalyzer::layerExtent( )
{
QString myTmpDir = QDir::tempPath() + QDir::separator() ;
QString myFileName = myTmpDir + "extent_layer.shp";
Expand Down
86 changes: 43 additions & 43 deletions tests/src/core/qgsrenderchecker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ QString QgsRenderChecker::controlImagePath() const
{
QString myDataDir( TEST_DATA_DIR ); //defined in CmakeLists.txt
QString myControlImageDir = myDataDir + QDir::separator() + "control_images"
+ QDir::separator() ;
+ QDir::separator() ;
return myControlImageDir;
}

void QgsRenderChecker::setControlName(const QString theName)
void QgsRenderChecker::setControlName( const QString theName )
{
mControlName = theName;
mExpectedImageFile = controlImagePath() + theName + QDir::separator()
+ theName + ".png";
+ theName + ".png";
}

QString QgsRenderChecker::imageToHash( QString theImageFile )
Expand All @@ -59,60 +59,60 @@ QString QgsRenderChecker::imageToHash( QString theImageFile )
myImage.load( theImageFile );
QByteArray myByteArray;
QBuffer myBuffer( &myByteArray );
myImage.save(&myBuffer, "PNG");
myImage.save( &myBuffer, "PNG" );
QString myImageString = QString::fromUtf8( myByteArray.toBase64().data() );
QCryptographicHash myHash( QCryptographicHash::Md5 );
myHash.addData(myImageString.toUtf8());
myHash.addData( myImageString.toUtf8() );
return myHash.result().toHex().constData();
}

bool QgsRenderChecker::isKnownAnomaly( QString theDiffImageFile )
{
QString myControlImageDir = controlImagePath() + mControlName
+ QDir::separator();
QDir myDirectory = QDir(myControlImageDir);
+ QDir::separator();
QDir myDirectory = QDir( myControlImageDir );
QStringList myList;
QString myFilename = "*";
myList = myDirectory.entryList(QStringList(myFilename),
QDir::Files | QDir::NoSymLinks);
myList = myDirectory.entryList( QStringList( myFilename ),
QDir::Files | QDir::NoSymLinks );
//remove the control file from teh list as the anomalies are
//all files except the control file
myList.removeAt(myList.indexOf(mExpectedImageFile));
myList.removeAt( myList.indexOf( mExpectedImageFile ) );

QString myImageHash = imageToHash( theDiffImageFile );


for (int i = 0; i < myList.size(); ++i)
for ( int i = 0; i < myList.size(); ++i )
{
QString myFile = myList.at(i);
QString myFile = myList.at( i );
mReport += "<tr><td colspan=3>"
"Checking if " + myFile + " is a known anomaly.";
"Checking if " + myFile + " is a known anomaly.";
mReport += "</td></tr>";
QString myAnomalyHash = imageToHash( controlImagePath() + mControlName
+ QDir::separator() + myFile );
QString myHashMessage = QString(
"Checking if anomaly %1 (hash %2)")
.arg( myFile )
.arg( myAnomalyHash );
"Checking if anomaly %1 (hash %2)" )
.arg( myFile )
.arg( myAnomalyHash );
myHashMessage += QString( " matches %1 (hash %2)" )
.arg( theDiffImageFile )
.arg( myImageHash );
.arg( theDiffImageFile )
.arg( myImageHash );
//foo CDash
QString myMeasureMessage = "<DartMeasurement name=\"Anomoly check"
"\" type=\"text/text\">" + myHashMessage +
"</DartMeasurement>";
"\" type=\"text/text\">" + myHashMessage +
"</DartMeasurement>";
qDebug() << myMeasureMessage;
mReport += "<tr><td colspan=3>" + myHashMessage + "</td></tr>";
if ( myImageHash == myAnomalyHash )
{
mReport += "<tr><td colspan=3>"
"Anomaly found! " + myFile;
"Anomaly found! " + myFile;
mReport += "</td></tr>";
return true;
}
}
mReport += "<tr><td colspan=3>"
"No anomaly found! ";
"No anomaly found! ";
mReport += "</td></tr>";
return false;
}
Expand Down Expand Up @@ -146,7 +146,7 @@ bool QgsRenderChecker::runTest( QString theTestName,
mpMapRenderer->setOutputSize( QSize(
myExpectedImage.width(),
myExpectedImage.height() ),
myExpectedImage.logicalDpiX());
myExpectedImage.logicalDpiX() );
QTime myTime;
myTime.start();
mpMapRenderer->render( &myPainter );
Expand All @@ -157,7 +157,7 @@ bool QgsRenderChecker::runTest( QString theTestName,
// visual assessment if needed
//
mRenderedImageFile = QDir::tempPath() + QDir::separator() +
theTestName + "_result.png";
theTestName + "_result.png";
myImage.save( mRenderedImageFile, "PNG", 100 );
return compareImages( theTestName, theMismatchCount );

Expand Down Expand Up @@ -194,8 +194,8 @@ bool QgsRenderChecker::compareImages( QString theTestName,
myExpectedImage.height(),
QImage::Format_RGB32 );
QString myDiffImageFile = QDir::tempPath() + QDir::separator() +
QDir::separator() +
theTestName + "_result_diff.png";
QDir::separator() +
theTestName + "_result_diff.png";
myDifferenceImage.fill( qRgb( 152, 219, 249 ) );

//
Expand Down Expand Up @@ -233,12 +233,12 @@ bool QgsRenderChecker::compareImages( QString theTestName,
// To get the images into CDash
//
QString myDashMessage = "<DartMeasurementFile name=\"Rendered Image " + theTestName + "\""
" type=\"image/png\">" + mRenderedImageFile +
"</DartMeasurementFile>"
"<DartMeasurementFile name=\"Expected Image " + theTestName + "\" type=\"image/png\">" +
mExpectedImageFile + "</DartMeasurementFile>"
"<DartMeasurementFile name=\"Difference Image " + theTestName + "\" type=\"image/png\">" +
myDiffImageFile + "</DartMeasurementFile>";
" type=\"image/png\">" + mRenderedImageFile +
"</DartMeasurementFile>"
"<DartMeasurementFile name=\"Expected Image " + theTestName + "\" type=\"image/png\">" +
mExpectedImageFile + "</DartMeasurementFile>"
"<DartMeasurementFile name=\"Difference Image " + theTestName + "\" type=\"image/png\">" +
myDiffImageFile + "</DartMeasurementFile>";
qDebug( ) << myDashMessage;

//
Expand Down Expand Up @@ -301,10 +301,10 @@ bool QgsRenderChecker::compareImages( QString theTestName,
// And send it to CDash
//
myDashMessage = "<DartMeasurement name=\"Mismatch Count "
"\" type=\"numeric/integer\">" +
QString::number( mMismatchCount ) + "/" +
QString::number( mMatchTarget ) +
"</DartMeasurement>";
"\" type=\"numeric/integer\">" +
QString::number( mMismatchCount ) + "/" +
QString::number( mMatchTarget ) +
"</DartMeasurement>";
qDebug( ) << myDashMessage;

bool myAnomalyMatchFlag = isKnownAnomaly( myDiffImageFile );
Expand All @@ -322,16 +322,16 @@ bool QgsRenderChecker::compareImages( QString theTestName,
mReport += "<tr><td colspan=3>"
"</td></tr>";
QString myMeasureMessage = "<DartMeasurement name=\"No Anomalies Match"
"\" type=\"text/text\">" + myMessage +
" If you feel the difference image should be considered an anomaly "
"you can do something like this\n"
"cp " + myDiffImageFile + "../tests/testdata/control_images/" + theTestName +
"/<imagename>.png"
"</DartMeasurement>";
"\" type=\"text/text\">" + myMessage +
" If you feel the difference image should be considered an anomaly "
"you can do something like this\n"
"cp " + myDiffImageFile + "../tests/testdata/control_images/" + theTestName +
"/<imagename>.png"
"</DartMeasurement>";
qDebug() << myMeasureMessage;
}

if ( mMismatchCount <= theMismatchCount)
if ( mMismatchCount <= theMismatchCount )
{
mReport += "<tr><td colspan = 3>\n";
mReport += "Test image and result image for " + theTestName + " are matched<br>";
Expand Down
135 changes: 69 additions & 66 deletions tests/src/core/qgsrenderchecker.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/***************************************************************************
qgsrenderchecker.h - check maprender output against an expected image
qgsrenderchecker.h - check maprender output against an expected image
--------------------------------------
Date : 18 Jan 2008
Copyright : (C) 2008 by Tim Sutton
Expand All @@ -17,86 +17,89 @@
#define QGSRENDERCHECKER_H

#include <QString>
#include <qgsmaprenderer.h>
#include <qgsmaprenderer.h>
class QImage;

/** \ingroup UnitTests
* This is a helper class for unit tests that need to
* This is a helper class for unit tests that need to
* write an image and compare it to an expected result
* or render time.
*/
class QgsRenderChecker
{
public:

QgsRenderChecker();
public:

//! Destructor
~QgsRenderChecker(){};
QgsRenderChecker();

QString controlImagePath() const;
//! Destructor
~QgsRenderChecker() {};

QString report() { return mReport; };
float matchPercent() { return static_cast<float>(mMismatchCount) /
static_cast<float>(mMatchTarget) * 100; };
unsigned int mismatchCount() { return mMismatchCount; };
unsigned int matchTarget() { return mMatchTarget; };
//only records time for actual render part
int elapsedTime() { return mElapsedTime; };
void setElapsedTimeTarget(int theTarget) { mElapsedTimeTarget = theTarget; };
/** Base directory name for the control image (with control image path
* suffixed) the path to the image will be constructed like this:
* controlImagePath + '/' + mControlName + '/' + mControlName + '.png'
*/
void setControlName(const QString theName);
/** Get an md5 hash that uniquely identifies an image */
QString imageToHash( QString theImageFile );
QString controlImagePath() const;

QString report() { return mReport; };
float matchPercent()
{
return static_cast<float>( mMismatchCount ) /
static_cast<float>( mMatchTarget ) * 100;
};
unsigned int mismatchCount() { return mMismatchCount; };
unsigned int matchTarget() { return mMatchTarget; };
//only records time for actual render part
int elapsedTime() { return mElapsedTime; };
void setElapsedTimeTarget( int theTarget ) { mElapsedTimeTarget = theTarget; };
/** Base directory name for the control image (with control image path
* suffixed) the path to the image will be constructed like this:
* controlImagePath + '/' + mControlName + '/' + mControlName + '.png'
*/
void setControlName( const QString theName );
/** Get an md5 hash that uniquely identifies an image */
QString imageToHash( QString theImageFile );

void setRenderedImage (QString theImageFileName) { mRenderedImageFile = theImageFileName; };
void setMapRenderer ( QgsMapRenderer * thepMapRenderer) { mpMapRenderer = thepMapRenderer; };
/**
* Test using renderer to generate the image to be compared.
* @param theTestName - to be used as the basis for writing a file to
* e.g. /tmp/theTestName.png
* @param theMismatchCount - defaults to 0 - the number of pixels that
* are allowed to be different from the control image. In some cases
* rendering may be non-deterministic. This parameter allows you to account
* for that by providing a tolerance.
* @note make sure to call setExpectedImage and setMapRenderer first
*/
bool runTest( QString theTestName, unsigned int theMismatchCount=0 );
void setRenderedImage( QString theImageFileName ) { mRenderedImageFile = theImageFileName; };
void setMapRenderer( QgsMapRenderer * thepMapRenderer ) { mpMapRenderer = thepMapRenderer; };
/**
* Test using renderer to generate the image to be compared.
* @param theTestName - to be used as the basis for writing a file to
* e.g. /tmp/theTestName.png
* @param theMismatchCount - defaults to 0 - the number of pixels that
* are allowed to be different from the control image. In some cases
* rendering may be non-deterministic. This parameter allows you to account
* for that by providing a tolerance.
* @note make sure to call setExpectedImage and setMapRenderer first
*/
bool runTest( QString theTestName, unsigned int theMismatchCount = 0 );

/**
* Test using two arbitary images (map renderer will not be used)
* @param theTestName - to be used as the basis for writing a file to
* e.g. /tmp/theTestName.png
* @param theMismatchCount - defaults to 0 - the number of pixels that
* are allowed to be different from the control image. In some cases
* rendering may be non-deterministic. This parameter allows you to account
* for that by providing a tolerance.
* @note: make sure to call setExpectedImage and setRenderedImage first.
*/
bool compareImages( QString theTestName, unsigned int theMismatchCount=0 );
/** Get a list of all teh anomalies. An anomaly is a rendered difference
* file where there is some red pixel content (indicating a render check
* mismatch), but where the output was still acceptible. If the render
* diff matches one of these anomalies we will still consider it to be
* acceptible.
* @return a bool indicating if the diff matched one of the anomaly files
*/
bool isKnownAnomaly( QString theDiffImageFile );
/**
* Test using two arbitary images (map renderer will not be used)
* @param theTestName - to be used as the basis for writing a file to
* e.g. /tmp/theTestName.png
* @param theMismatchCount - defaults to 0 - the number of pixels that
* are allowed to be different from the control image. In some cases
* rendering may be non-deterministic. This parameter allows you to account
* for that by providing a tolerance.
* @note: make sure to call setExpectedImage and setRenderedImage first.
*/
bool compareImages( QString theTestName, unsigned int theMismatchCount = 0 );
/** Get a list of all teh anomalies. An anomaly is a rendered difference
* file where there is some red pixel content (indicating a render check
* mismatch), but where the output was still acceptible. If the render
* diff matches one of these anomalies we will still consider it to be
* acceptible.
* @return a bool indicating if the diff matched one of the anomaly files
*/
bool isKnownAnomaly( QString theDiffImageFile );

private:
private:

QString mReport;
QString mExpectedImageFile;
QString mControlName;
QString mRenderedImageFile;
unsigned int mMismatchCount;
unsigned int mMatchTarget;
int mElapsedTime;
int mElapsedTimeTarget;
QgsMapRenderer * mpMapRenderer;
QString mReport;
QString mExpectedImageFile;
QString mControlName;
QString mRenderedImageFile;
unsigned int mMismatchCount;
unsigned int mMatchTarget;
int mElapsedTime;
int mElapsedTimeTarget;
QgsMapRenderer * mpMapRenderer;

}; // class QgsRenderChecker

Expand Down
4 changes: 2 additions & 2 deletions tests/src/core/test_template.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@

class Test[testClassCamelCaseName]: public QObject
{
Q_OBJECT;
Q_OBJECT;
private slots:
[TestMethods]
};

QTEST_MAIN(Test[testClassCamelCaseName])
QTEST_MAIN( Test[testClassCamelCaseName] )
#include "test[testClassLowerCaseName].moc.cpp"


Expand Down
2 changes: 1 addition & 1 deletion tests/src/core/testcontrastenhancements.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ void TestContrastEnhancements::initTestCase()
//runs after all tests
void TestContrastEnhancements::cleanupTestCase()
{
QString myReportFile = QDir::tempPath() + QDir::separator() + "qgis_tests.html";
QString myReportFile = QDir::tempPath() + QDir::separator() + "qgistest.html";
QFile myFile( myReportFile );
if ( myFile.open( QIODevice::WriteOnly | QIODevice::Append ) )
{
Expand Down
36 changes: 16 additions & 20 deletions tests/src/core/testqgscoordinatereferencesystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,8 @@ void TestQgsCoordinateReferenceSystem::initTestCase()
// Runs once before any tests are run
//
// init QGIS's paths - true means that all path will be inited from prefix
QgsApplication::setPrefixPath( INSTALL_PREFIX, true );
QgsApplication::initQgis( );
QgsApplication::init();
QgsApplication::showSettings();

}

void TestQgsCoordinateReferenceSystem::wktCtor()
Expand Down Expand Up @@ -100,7 +98,7 @@ void TestQgsCoordinateReferenceSystem::copyCtor()
void TestQgsCoordinateReferenceSystem::assignmentCtor()
{
QgsCoordinateReferenceSystem myCrs( GEOSRID,
QgsCoordinateReferenceSystem::EpsgCrsId );
QgsCoordinateReferenceSystem::EpsgCrsId );
QgsCoordinateReferenceSystem myCrs2 = myCrs;
debugPrint( myCrs2 );
QVERIFY( myCrs2.isValid() );
Expand Down Expand Up @@ -186,8 +184,7 @@ void TestQgsCoordinateReferenceSystem::equals()
debugPrint( myCrs );
//Note: OSRImportFromProj4 (used internally by equals)
//drops the TOWGS from the WKT which causes this test to fail
QString myProj4( GEOPROJ4 );
QVERIFY( myCrs.equals( myProj4 ) );
QVERIFY( myCrs.equals( GEOPROJ4 ) );
}
void TestQgsCoordinateReferenceSystem::readXML()
{
Expand Down Expand Up @@ -239,17 +236,17 @@ void TestQgsCoordinateReferenceSystem::toWkt()
QString myWkt = myCrs.toWkt();
debugPrint( myCrs );
//Note: this is not the same as GEOWKT as OGR strips off the TOWGS clause...
QString myStrippedWkt("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID"
"[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
"AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY"
"[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY"
"[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]");
QString myStrippedWkt( "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID"
"[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
"AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY"
"[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY"
"[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]" );
// for GDAL 1.7
QString myAltStrippedWkt("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID"
"[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
"AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY"
"[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY"
"[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]");
QString myAltStrippedWkt( "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID"
"[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
"AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY"
"[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY"
"[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]" );
qDebug() << "myWkt:\n";
qDebug() << myWkt;
qDebug() << "myStrippedWkt:\n";
Expand All @@ -263,8 +260,7 @@ void TestQgsCoordinateReferenceSystem::toProj4()
debugPrint( myCrs );
//first proj string produced by gdal 1.8-1.9
//second by gdal 1.7
QVERIFY( myCrs.toProj4() == "+proj=longlat +datum=WGS84 +no_defs" ||
myCrs.toProj4() == "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
QVERIFY( myCrs.toProj4() == GEOPROJ4 );
}
void TestQgsCoordinateReferenceSystem::geographicFlag()
{
Expand All @@ -289,11 +285,11 @@ void TestQgsCoordinateReferenceSystem::setValidationHint()
}

void TestQgsCoordinateReferenceSystem::debugPrint(
QgsCoordinateReferenceSystem &theCrs )
QgsCoordinateReferenceSystem &theCrs )
{
QgsDebugMsg( "***SpatialRefSystem***" );
QgsDebugMsg( "* Valid : " + ( theCrs.isValid() ? QString( "true" ) :
QString( "false" ) ) );
QString( "false" ) ) );
QgsDebugMsg( "* SrsId : " + QString::number( theCrs.srsid() ) );
QgsDebugMsg( "* EPSG ID : " + theCrs.authid() );
QgsDebugMsg( "* PGIS ID : " + QString::number( theCrs.postgisSrid() ) );
Expand Down
12 changes: 6 additions & 6 deletions tests/src/core/testqgsexpression.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,16 @@ class TestQgsExpression: public QObject
{
// check that parsing of numbers works correctly even when using some other locale

char* old_locale = setlocale(LC_NUMERIC, NULL);
qDebug("Old locale: %s", old_locale);
setlocale(LC_NUMERIC, "de_DE.UTF8");
char* new_locale = setlocale(LC_NUMERIC, NULL);
qDebug("New locale: %s", new_locale);
char* old_locale = setlocale( LC_NUMERIC, NULL );
qDebug( "Old locale: %s", old_locale );
setlocale( LC_NUMERIC, "de_DE.UTF8" );
char* new_locale = setlocale( LC_NUMERIC, NULL );
qDebug( "New locale: %s", new_locale );

QgsExpression exp( "1.23 + 4.56" );
QVERIFY( !exp.hasParserError() );

setlocale(LC_NUMERIC, "");
setlocale( LC_NUMERIC, "" );

QVariant v = exp.evaluate();
QCOMPARE( v.toDouble(), 5.79 );
Expand Down
30 changes: 14 additions & 16 deletions tests/src/core/testqgsmaplayer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
#include <QDir>

//qgis includes...
#include <qgsmaplayer.h>
#include <qgsvectorlayer.h>
#include <qgsmaplayer.h>
#include <qgsvectorlayer.h>
#include <qgsapplication.h>
#include <qgsproviderregistry.h>

Expand All @@ -33,12 +33,12 @@
*/
class TestQgsMapLayer: public QObject
{
Q_OBJECT;
Q_OBJECT;
private slots:
void initTestCase();// will be called before the first testfunction is executed.
void cleanupTestCase(){};// will be called after the last testfunction was executed.
void init(){};// will be called before each testfunction is executed.
void cleanup(){};// will be called after every testfunction.
void cleanupTestCase() {};// will be called after the last testfunction was executed.
void init() {};// will be called before each testfunction is executed.
void cleanup() {};// will be called after every testfunction.

void isValid();
private:
Expand All @@ -51,26 +51,24 @@ void TestQgsMapLayer::initTestCase()
// Runs once before any tests are run
//
// init QGIS's paths - true means that all path will be inited from prefix
QString qgisPath = QCoreApplication::applicationDirPath ();
QgsApplication::setPrefixPath(INSTALL_PREFIX, true);
QgsApplication::init();
QgsApplication::showSettings();
// Instantiate the plugin directory so that providers are loaded
QgsProviderRegistry::instance(QgsApplication::pluginPath());
QgsProviderRegistry::instance( QgsApplication::pluginPath() );

//create some objects that will be used in all tests...
//create a map layer that will be used in all tests...
QString myFileName (TEST_DATA_DIR); //defined in CmakeLists.txt
QString myFileName( TEST_DATA_DIR ); //defined in CmakeLists.txt
myFileName = myFileName + QDir::separator() + "points.shp";
QFileInfo myMapFileInfo ( myFileName );
mpLayer = new QgsVectorLayer ( myMapFileInfo.filePath(),
myMapFileInfo.completeBaseName(), "ogr" );
QFileInfo myMapFileInfo( myFileName );
mpLayer = new QgsVectorLayer( myMapFileInfo.filePath(),
myMapFileInfo.completeBaseName(), "ogr" );
}

void TestQgsMapLayer::isValid()
{
QVERIFY ( mpLayer->isValid() );
QVERIFY( mpLayer->isValid() );
}

QTEST_MAIN(TestQgsMapLayer)
QTEST_MAIN( TestQgsMapLayer )
#include "moc_testqgsmaplayer.cxx"

6 changes: 1 addition & 5 deletions tests/src/core/testqgsmaprenderer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,10 @@ void TestQgsMapRenderer::initTestCase()
//
// Runs once before any tests are run
//
// init QGIS's paths - true means that all path will be inited from prefix
QString qgisPath = QCoreApplication::applicationDirPath();
QgsApplication::setPrefixPath( INSTALL_PREFIX, true );
QgsApplication::init();
QgsApplication::showSettings();
// Instantiate the plugin directory so that providers are loaded
QgsProviderRegistry::instance( QgsApplication::pluginPath() );


//create some objects that will be used in all tests...
mEncoding = "UTF-8";
QgsField myField1( "Value", QVariant::Int, "int", 10, 0, "Value on lon" );
Expand Down
12 changes: 6 additions & 6 deletions tests/src/core/testqgspoint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,12 @@ void TestQgsPoint::toDegreesMinutesSeconds()
mReport += "<p>" + mPoint3.toDegreesMinutesSeconds( 2 ) + "</p>";
mReport += "<p>" + mPoint4.toDegreesMinutesSeconds( 2 ) + "</p>";
qDebug() << mPoint4.toDegreesMinutesSeconds( 2 );
QString myControlString = QString( "80" ) + QChar( 176 ) +
QString( "0'0.00" ) +
QString( '"' ) +
QString( "E,20" ) + QChar( 176 ) +
QString( "0'0.00" ) + QString( '"' ) +
QString( "N" );
QString myControlString = QString( "80" ) + QChar( 176 ) +
QString( "0'0.00" ) +
QString( '"' ) +
QString( "E,20" ) + QChar( 176 ) +
QString( "0'0.00" ) + QString( '"' ) +
QString( "N" );
qDebug() << myControlString;
QVERIFY( mPoint4.toDegreesMinutesSeconds( 2 ) == myControlString );

Expand Down
4 changes: 1 addition & 3 deletions tests/src/core/testqgsvectorlayer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ class TestQgsVectorLayer: public QObject
void initTestCase()
{
mTestHasError = false;
// init QGIS's paths - true means that all path will be inited from prefix
QString qgisPath = QCoreApplication::applicationDirPath();
QgsApplication::setPrefixPath( INSTALL_PREFIX, true );
QgsApplication::init();
QgsApplication::showSettings();
// Instantiate the plugin directory so that providers are loaded
QgsProviderRegistry::instance( QgsApplication::pluginPath() );
Expand Down
10 changes: 3 additions & 7 deletions tests/src/core/testziplayer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,7 @@ class TestZipLayer: public QObject

void testZipLayer()
{
// init QGIS's paths - true means that all path will be inited from prefix
QString qgisPath = QCoreApplication::applicationDirPath();
QgsApplication::setPrefixPath( INSTALL_PREFIX, true );
// Instantiate the plugin directory so that providers are loaded
QgsApplication::init();
QgsProviderRegistry::instance( QgsApplication::pluginPath() );
//
//create a point layer that will be used in all tests...
Expand All @@ -47,9 +44,8 @@ class TestZipLayer: public QObject
myDataDir += QDir::separator();
QString myPointsFileName = myDataDir + "points.zip";
QFileInfo myPointFileInfo( myPointsFileName );
QgsVectorLayer * mypPointsLayer;
mypPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(),
myPointFileInfo.completeBaseName(), "ogr" );
QgsVectorLayer * mypPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(),
myPointFileInfo.completeBaseName(), "ogr" );
QVERIFY( mypPointsLayer->isValid() );
delete mypPointsLayer;
}
Expand Down
88 changes: 44 additions & 44 deletions tests/src/gui/testqgsquickprint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@

#include <iostream>
//qgis includes...
#include <qgsmaprenderer.h>
#include <qgsmaplayer.h>
#include <qgsvectorlayer.h>
#include <qgsmaprenderer.h>
#include <qgsmaplayer.h>
#include <qgsvectorlayer.h>
#include <qgsapplication.h>
#include <qgsproviderregistry.h>
#include <qgsmaplayerregistry.h>
Expand All @@ -38,16 +38,16 @@
*/
class TestQgsQuickPrint: public QObject
{
Q_OBJECT;
Q_OBJECT;
private slots:
void initTestCase();// will be called before the first testfunction is executed.
void cleanupTestCase();// will be called after the last testfunction was executed.
void init(){};// will be called before each testfunction is executed.
void cleanup(){};// will be called after every testfunction.
void init() {};// will be called before each testfunction is executed.
void cleanup() {};// will be called after every testfunction.

void basicMapTest();
private:
bool imageCheck(QString theType); //as above
bool imageCheck( QString theType ); //as above
QgsMapRenderer * mpMapRenderer;
QgsMapLayer * mpPointsLayer;
QgsMapLayer * mpLinesLayer;
Expand All @@ -62,43 +62,43 @@ void TestQgsQuickPrint::initTestCase()
// Runs once before any tests are run
//
// init QGIS's paths - true means that all path will be inited from prefix
QString qgisPath = QCoreApplication::applicationDirPath ();
QgsApplication::setPrefixPath(INSTALL_PREFIX, true);
QString qgisPath = QCoreApplication::applicationDirPath();
QgsApplication::setPrefixPath( INSTALL_PREFIX, true );
QgsApplication::showSettings();
// Instantiate the plugin directory so that providers are loaded
QgsProviderRegistry::instance(QgsApplication::pluginPath());
QgsProviderRegistry::instance( QgsApplication::pluginPath() );

//
//create a point layer that will be used in all tests...
//
QString myDataDir (TEST_DATA_DIR); //defined in CmakeLists.txt
QString myDataDir( TEST_DATA_DIR ); //defined in CmakeLists.txt
mTestDataDir = myDataDir + QDir::separator();
QString myPointsFileName = mTestDataDir + "points.shp";
QFileInfo myPointFileInfo ( myPointsFileName );
mpPointsLayer = new QgsVectorLayer ( myPointFileInfo.filePath(),
myPointFileInfo.completeBaseName(), "ogr" );
QFileInfo myPointFileInfo( myPointsFileName );
mpPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(),
myPointFileInfo.completeBaseName(), "ogr" );
// Register the layer with the registry
QgsMapLayerRegistry::instance()->addMapLayer(mpPointsLayer);
QgsMapLayerRegistry::instance()->addMapLayer( mpPointsLayer );

//
//create a poly layer that will be used in all tests...
//
QString myPolysFileName = mTestDataDir + "polys.shp";
QFileInfo myPolyFileInfo ( myPolysFileName );
mpPolysLayer = new QgsVectorLayer ( myPolyFileInfo.filePath(),
myPolyFileInfo.completeBaseName(), "ogr" );
QFileInfo myPolyFileInfo( myPolysFileName );
mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(),
myPolyFileInfo.completeBaseName(), "ogr" );
// Register the layer with the registry
QgsMapLayerRegistry::instance()->addMapLayer(mpPolysLayer);
QgsMapLayerRegistry::instance()->addMapLayer( mpPolysLayer );

//
// Create a line layer that will be used in all tests...
//
QString myLinesFileName = mTestDataDir + "lines.shp";
QFileInfo myLineFileInfo ( myLinesFileName );
mpLinesLayer = new QgsVectorLayer ( myLineFileInfo.filePath(),
myLineFileInfo.completeBaseName(), "ogr" );
QFileInfo myLineFileInfo( myLinesFileName );
mpLinesLayer = new QgsVectorLayer( myLineFileInfo.filePath(),
myLineFileInfo.completeBaseName(), "ogr" );
// Register the layer with the registry
QgsMapLayerRegistry::instance()->addMapLayer(mpLinesLayer);
QgsMapLayerRegistry::instance()->addMapLayer( mpLinesLayer );
//
// We only need maprender instead of mapcanvas
// since maprender does not require a qui
Expand All @@ -109,9 +109,9 @@ void TestQgsQuickPrint::initTestCase()
myLayers << mpPointsLayer->getLayerID();
myLayers << mpPolysLayer->getLayerID();
myLayers << mpLinesLayer->getLayerID();
mpMapRenderer->setLayerSet(myLayers);
mpMapRenderer->setExtent(mpPointsLayer->extent());
mReport+= "<h1>QuickPrint Tests</h1>\n";
mpMapRenderer->setLayerSet( myLayers );
mpMapRenderer->setExtent( mpPointsLayer->extent() );
mReport += "<h1>QuickPrint Tests</h1>\n";
}
void TestQgsQuickPrint::cleanupTestCase()
{
Expand All @@ -126,25 +126,25 @@ void TestQgsQuickPrint::cleanupTestCase()
QDesktopServices::openUrl("file://"+myReportFile);
}
*/

}

void TestQgsQuickPrint::basicMapTest()
{
//make the legends really long so we can test
//word wrapping
mpPointsLayer->setLayerName("This is a very very very long name it should word wrap");
mpPolysLayer->setLayerName("This is a very very very long name it should also word wrap");
mpLinesLayer->setLayerName("This is a very very very very long name it should word wrap");
mpPointsLayer->setLayerName( "This is a very very very long name it should word wrap" );
mpPolysLayer->setLayerName( "This is a very very very long name it should also word wrap" );
mpLinesLayer->setLayerName( "This is a very very very very long name it should word wrap" );

//now print the map
QgsQuickPrint myQuickPrint;
myQuickPrint.setMapBackgroundColor ( Qt::cyan );
myQuickPrint.setOutputPdf (QDir::tempPath() + QDir::separator() + "quickprinttest.pdf");
myQuickPrint.setMapRenderer (mpMapRenderer);
myQuickPrint.setTitle ("Map Title");
myQuickPrint.setName ("Map Name");
myQuickPrint.setCopyright ("Copyright Text");
myQuickPrint.setMapBackgroundColor( Qt::cyan );
myQuickPrint.setOutputPdf( QDir::tempPath() + QDir::separator() + "quickprinttest.pdf" );
myQuickPrint.setMapRenderer( mpMapRenderer );
myQuickPrint.setTitle( "Map Title" );
myQuickPrint.setName( "Map Name" );
myQuickPrint.setCopyright( "Copyright Text" );
//void setNorthArrow(QString theFileName);
//void setLogo1(QString theFileName);
//void setLogo2(QString theFileName);
Expand All @@ -156,20 +156,20 @@ void TestQgsQuickPrint::basicMapTest()
// Helper functions below
//

bool TestQgsQuickPrint::imageCheck(QString theTestType)
bool TestQgsQuickPrint::imageCheck( QString theTestType )
{
//use the QgsRenderChecker test utility class to
//use the QgsRenderChecker test utility class to
//ensure the rendered output matches our control image
mpMapRenderer->setExtent(mpPointsLayer->extent());
mpMapRenderer->setExtent( mpPointsLayer->extent() );
QString myExpectedImage = mTestDataDir + "expected_" + theTestType + ".png";
QgsRenderChecker myChecker;
myChecker.setExpectedImage ( myExpectedImage );
myChecker.setMapRenderer ( mpMapRenderer );
myChecker.setExpectedImage( myExpectedImage );
myChecker.setMapRenderer( mpMapRenderer );
bool myResultFlag = myChecker.runTest( theTestType );
mReport += myChecker.report();
return myResultFlag;
}

QTEST_MAIN(TestQgsQuickPrint)
QTEST_MAIN( TestQgsQuickPrint )
#include "moc_testqgsquickprint.cxx"

30 changes: 15 additions & 15 deletions tests/src/gui/testrendererv2gui.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,50 +11,50 @@
#include <QApplication>
#include <QToolBar>

TestRendererV2GUI::TestRendererV2GUI(QWidget *parent) :
QMainWindow(parent)
TestRendererV2GUI::TestRendererV2GUI( QWidget *parent ) :
QMainWindow( parent )
{
resize(640,480);
resize( 640, 480 );

QToolBar* toolBar = addToolBar("Actions");
toolBar->addAction( "set renderer", this, SLOT(setRenderer()) );
QToolBar* toolBar = addToolBar( "Actions" );
toolBar->addAction( "set renderer", this, SLOT( setRenderer() ) );

mMapCanvas = new QgsMapCanvas(this);
mMapCanvas = new QgsMapCanvas( this );
mMapCanvas->setCanvasColor( Qt::white );
setCentralWidget(mMapCanvas);
setCentralWidget( mMapCanvas );

connect( QgsProject::instance(), SIGNAL(readProject(QDomDocument)), mMapCanvas, SLOT(readProject(QDomDocument)));
connect( QgsProject::instance(), SIGNAL( readProject( QDomDocument ) ), mMapCanvas, SLOT( readProject( QDomDocument ) ) );
}

void TestRendererV2GUI::loadLayers()
{
// load just first vector layer
QList<QgsMapCanvasLayer> canvasLayers;
foreach (QgsMapLayer* layer, QgsMapLayerRegistry::instance()->mapLayers().values())
foreach( QgsMapLayer* layer, QgsMapLayerRegistry::instance()->mapLayers().values() )
{
if ( layer->type() == QgsMapLayer::VectorLayer )
canvasLayers << QgsMapCanvasLayer( layer );
}

mMapCanvas->setLayerSet(canvasLayers);
mMapCanvas->setLayerSet( canvasLayers );
}

void TestRendererV2GUI::setRenderer()
{
QgsMapLayer* layer = mMapCanvas->layer(0);
QgsMapLayer* layer = mMapCanvas->layer( 0 );
Q_ASSERT( layer );
Q_ASSERT( layer->type() == QgsMapLayer::VectorLayer );
QgsVectorLayer* vlayer = static_cast<QgsVectorLayer*>(layer);
QgsVectorLayer* vlayer = static_cast<QgsVectorLayer*>( layer );

QgsRendererV2PropertiesDialog dlg( vlayer, QgsStyleV2::defaultStyle() );
dlg.exec();

mMapCanvas->refresh();
}

int main(int argc, char* argv[])
int main( int argc, char* argv[] )
{
QApplication app(argc, argv);
QApplication app( argc, argv );

if ( argc < 2 )
{
Expand All @@ -72,7 +72,7 @@ int main(int argc, char* argv[])
bool res = QgsProject::instance()->read();
if ( !res )
{
qDebug("Failed to open project!");
qDebug( "Failed to open project!" );
return 1;
}

Expand Down
12 changes: 6 additions & 6 deletions tests/src/gui/testrendererv2gui.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ class QgsMapCanvas;
class TestRendererV2GUI : public QMainWindow
{
Q_OBJECT
public:
explicit TestRendererV2GUI(QWidget *parent = 0);
public:
explicit TestRendererV2GUI( QWidget *parent = 0 );
void loadLayers();

signals:
signals:

public slots:
public slots:
void setRenderer();

protected:
QgsMapCanvas* mMapCanvas;
protected:
QgsMapCanvas* mMapCanvas;
};

#endif // TESTRENDERERV2GUI_H