diff --git a/tests/TestCaseConverter.cpp b/tests/TestCaseConverter.cpp index 5e9ad6c0c7..4b7c8f93b6 100644 --- a/tests/TestCaseConverter.cpp +++ b/tests/TestCaseConverter.cpp @@ -1,59 +1,59 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestCaseConverter.h" #include "CaseConverter.h" #include -QTEST_MAIN( TestCaseConverter ) +QTEST_GUILESS_MAIN( TestCaseConverter ) TestCaseConverter::TestCaseConverter() { } void TestCaseConverter::testToCapitalizedCase() { QCOMPARE( Amarok::CaseConverter::toCapitalizedCase( "" ), QString( "" ) ); QCOMPARE( Amarok::CaseConverter::toCapitalizedCase( "A" ), QString( "A" ) ); QCOMPARE( Amarok::CaseConverter::toCapitalizedCase( "a" ), QString( "A" ) ); QCOMPARE( Amarok::CaseConverter::toCapitalizedCase( "A tale of true love" ), QString( "A Tale Of True Love" ) ); QCOMPARE( Amarok::CaseConverter::toCapitalizedCase( "A horse with no name" ), QString( "A Horse With No Name" ) ); QCOMPARE( Amarok::CaseConverter::toCapitalizedCase( "riding on a dead horse" ), QString( "Riding On A Dead Horse" ) ); // ätest -> Ätest QCOMPARE( Amarok::CaseConverter::toCapitalizedCase( QChar( 0x00E4 ) + QString( "test" ) ), QChar( 0x00C4 ) + QString( "test" ) ); QCOMPARE( Amarok::CaseConverter::toCapitalizedCase( "a an in of on" ), QString( "A An In Of On" ) ); } void TestCaseConverter::testToTitleCase() { QCOMPARE( Amarok::CaseConverter::toTitleCase( "" ), QString( "" ) ); QCOMPARE( Amarok::CaseConverter::toTitleCase( "A" ), QString( "A" ) ); QCOMPARE( Amarok::CaseConverter::toTitleCase( "a" ), QString( "A" ) ); QCOMPARE( Amarok::CaseConverter::toTitleCase( "a tale of true love" ), QString( "A Tale of True Love" ) ); QCOMPARE( Amarok::CaseConverter::toTitleCase( "a horse with no name" ), QString( "A Horse With No Name" ) ); QCOMPARE( Amarok::CaseConverter::toTitleCase( "riding on a dead horse" ), QString( "Riding on a Dead Horse" ) ); // ätest -> Ätest QCOMPARE( Amarok::CaseConverter::toTitleCase( QChar( 0x00E4 ) + QString( "test" ) ), QChar( 0x00C4 ) + QString( "test" ) ); QCOMPARE( Amarok::CaseConverter::toTitleCase( "a a an in of on" ), QString( "A a an in of on" ) ); } diff --git a/tests/TestDebug.cpp b/tests/TestDebug.cpp index 66e9e4bf90..1a82f46595 100644 --- a/tests/TestDebug.cpp +++ b/tests/TestDebug.cpp @@ -1,170 +1,170 @@ /*************************************************************************** * Copyright (c) 2010 Rick W. Chen * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #define DEBUG_PREFIX "TestDebug" #include "core/support/Debug.h" #include "config-amarok-test.h" #include #include class TestDebug : public QObject { Q_OBJECT public: TestDebug() {} private slots: void benchDebugBlock(); void benchDebugBlock_data(); private: void work( bool debugEnabled, bool colorEnabled ); void work2( bool debugEnabled, bool colorEnabled ); enum BeginOrEnd { Begin, End }; void expectMessage( const QString &message, bool debugEnabled ); void expectBeginEnd( BeginOrEnd type, const QString &message, bool debugEnabled, bool colorEnabled ); QString colorize( const QString &string, int colorIndex, bool colorEnabled ); static QString m_indent; }; QString TestDebug::m_indent; void TestDebug::benchDebugBlock_data() { QTest::addColumn("debugEnabled"); QTest::addColumn("colorEnabled"); QTest::newRow("debug with color") << true << true; QTest::newRow("debug nocolor") << true << false; QTest::newRow("nodebug with color") << false << true; QTest::newRow("nodebug nocolor") << false << false; } void TestDebug::benchDebugBlock() { QFETCH(bool, debugEnabled); QFETCH(bool, colorEnabled); Debug::setDebugEnabled( debugEnabled ); Debug::setColoredDebug( colorEnabled ); QVERIFY( Debug::debugEnabled() == debugEnabled ); QVERIFY( Debug::debugColorEnabled() == colorEnabled ); QBENCHMARK_ONCE { work( debugEnabled, colorEnabled ); } } void TestDebug::work( bool debugEnabled, bool colorEnabled ) { expectBeginEnd( Begin, __PRETTY_FUNCTION__, debugEnabled, colorEnabled ); DEBUG_BLOCK expectMessage( "level 1", debugEnabled ); debug() << "level 1"; for( int i = 0; i < 100; ++i ) { expectBeginEnd( Begin, __PRETTY_FUNCTION__, debugEnabled, colorEnabled ); DEBUG_BLOCK expectMessage( "level 2", debugEnabled ); debug() << "level 2"; work2( debugEnabled, colorEnabled ); expectBeginEnd( End, __PRETTY_FUNCTION__, debugEnabled, colorEnabled ); } expectBeginEnd( End, __PRETTY_FUNCTION__, debugEnabled, colorEnabled ); } void TestDebug::work2( bool debugEnabled, bool colorEnabled ) { expectBeginEnd( Begin, __PRETTY_FUNCTION__, debugEnabled, colorEnabled ); DEBUG_BLOCK for( int j = 0; j < 10; ++j ) { expectMessage( "limbo", debugEnabled ); debug() << "limbo"; } expectBeginEnd( End, __PRETTY_FUNCTION__, debugEnabled, colorEnabled ); } void TestDebug::expectMessage( const QString &message, bool debugEnabled ) { if( !debugEnabled ) return; QString exp = QString( "%1:%2 [%3] %4 " ).arg( "amarok", m_indent, DEBUG_PREFIX, message ); QTest::ignoreMessage( QtDebugMsg, exp.toLocal8Bit() ); } void TestDebug::expectBeginEnd( TestDebug::BeginOrEnd type, const QString &message, bool debugEnabled, bool colorEnabled ) { static int colorIndex = 0; static QStack colorStack; if( !debugEnabled ) return; QString beginEnd; QString took; if( type == Begin ) { beginEnd = "BEGIN:"; colorStack.push( colorIndex ); colorIndex = (colorIndex + 1) % 5; } else { beginEnd = "END__:"; double duration = DEBUG_OVERRIDE_ELAPSED_TIME; took = ' ' + colorize( QString( "[Took: %1s]" ).arg( duration, 0, 'g', 2 ), colorStack.top(), colorEnabled ); m_indent.truncate( m_indent.length() - 2 ); } QString exp = QString( "%1:%2 %3 %4%5 " ).arg( "amarok", m_indent, colorize( beginEnd, colorStack.top(), colorEnabled ), message, took ); QTest::ignoreMessage( QtDebugMsg, exp.toLocal8Bit() ); if( type == Begin ) m_indent.append( " " ); else colorStack.pop(); } QString TestDebug::colorize( const QString &string, int colorIndex, bool colorEnabled ) { static int colors[] = { 1, 2, 4, 5, 6 }; // from Debug.cpp if( !colorEnabled ) return string; return QString( "\x1b[00;3%1m%2\x1b[00;39m" ).arg( QString::number(colors[colorIndex]), string ); } -QTEST_MAIN( TestDebug ) +QTEST_GUILESS_MAIN( TestDebug ) #include "TestDebug.moc" diff --git a/tests/TestEngineController.cpp b/tests/TestEngineController.cpp index e760c85099..1d7fd2c480 100644 --- a/tests/TestEngineController.cpp +++ b/tests/TestEngineController.cpp @@ -1,106 +1,106 @@ /**************************************************************************************** * Copyright (c) 2012 Matěj Laitl * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestEngineController.h" #include "EngineController.h" #include "core/support/Components.h" #include #include #include #include -QTEST_MAIN( TestEngineController ) +QTEST_GUILESS_MAIN( TestEngineController ) class CallSupportedMimeTypesJob : public QObject, public ThreadWeaver::Job { Q_OBJECT protected: void run(ThreadWeaver::JobPointer self, ThreadWeaver::Thread *thread) { Q_UNUSED(self); Q_UNUSED(thread); EngineController *ec = Amarok::Components::engineController(); QVERIFY( ec ); QStringList types = ec->supportedMimeTypes(); QVERIFY( !types.isEmpty() ); } void defaultBegin(const ThreadWeaver::JobPointer& self, ThreadWeaver::Thread *thread) { Q_EMIT started(self); ThreadWeaver::Job::defaultBegin(self, thread); } void defaultEnd(const ThreadWeaver::JobPointer& self, ThreadWeaver::Thread *thread) { ThreadWeaver::Job::defaultEnd(self, thread); if (!self->success()) { Q_EMIT failed(self); } Q_EMIT done(self); } Q_SIGNALS: /** This signal is emitted when this job is being processed by a thread. */ void started(ThreadWeaver::JobPointer); /** This signal is emitted when the job has been finished (no matter if it succeeded or not). */ void done(ThreadWeaver::JobPointer); /** This job has failed. * This signal is emitted when success() returns false after the job is executed. */ void failed(ThreadWeaver::JobPointer); }; void TestEngineController::init() { // the test depend on EngineController being used for the first time QVERIFY( Amarok::Components::engineController() == 0 ); Amarok::Components::setEngineController( new EngineController() ); } void TestEngineController::cleanup() { // we cannot simply call WeaverInterface::finish(), it stops event loop QSignalSpy spy( ThreadWeaver::Queue::instance(), &ThreadWeaver::Queue::finished ); if( !ThreadWeaver::Queue::instance()->isIdle() ) QVERIFY2( spy.wait( 5000 ), "threads did not finish in timeout" ); delete Amarok::Components::setEngineController( 0 ); } void TestEngineController::testSupportedMimeTypesInMainThread() { EngineController *ec = Amarok::Components::engineController(); QVERIFY( ec ); QStringList types = ec->supportedMimeTypes(); QVERIFY( !types.isEmpty() ); } void TestEngineController::testSupportedMimeTypesInAnotherThread() { ThreadWeaver::JobPointer job = QSharedPointer(new CallSupportedMimeTypesJob()); ThreadWeaver::Queue::instance()->enqueue( job ); } #include "TestEngineController.moc" diff --git a/tests/TestExpression.cpp b/tests/TestExpression.cpp index 723cd5f16c..a84ee6f7f8 100644 --- a/tests/TestExpression.cpp +++ b/tests/TestExpression.cpp @@ -1,150 +1,150 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestExpression.h" #include "core/support/Debug.h" #include "core-impl/collections/support/Expression.h" #include -QTEST_MAIN( TestExpression ) +QTEST_GUILESS_MAIN( TestExpression ) //required for Debug.h QMutex Debug::mutex; TestExpression::TestExpression() { } void TestExpression::testParse() { ParsedExpression result; expression_element element; result = ExpressionParser::parse( "" ); QCOMPARE( result.isEmpty(), true ); result = ExpressionParser::parse( "love artist:cure album:\"Best of\" year:<1990 playcount:>2 -score:<50" ); int i = 6; QCOMPARE( result.size(), i ); while( !result.isEmpty() ) { element = result.takeFirst().takeFirst(); if( element.text == "love" ) { QCOMPARE( element.field, QString( "" ) ); QCOMPARE( element.negate, false ); QVERIFY( element.match == expression_element::Contains ); } else if( element.text == "cure" ) { QCOMPARE( element.field, QString( "artist" ) ); QCOMPARE( element.negate, false ); QVERIFY( element.match == expression_element::Contains ); } else if( element.text == "Best of" ) { QCOMPARE( element.field, QString( "album" ) ); QCOMPARE( element.negate, false ); QVERIFY( element.match == expression_element::Contains ); } else if( element.text == "1990" ) { QCOMPARE( element.field, QString( "year" ) ); QCOMPARE( element.negate, false ); QVERIFY( element.match == expression_element::Less ); } else if( element.text == "2" ) { QCOMPARE( element.field, QString( "playcount" ) ); QCOMPARE( element.negate, false ); QVERIFY( element.match == expression_element::More ); } else if( element.text == "50" ) { QCOMPARE( element.field, QString( "score" ) ); QCOMPARE( element.negate, true ); QVERIFY( element.match == expression_element::Less ); } i--; QCOMPARE( result.size(), i ); } /* another more complex one */ result = ExpressionParser::parse( "artist:cure OR album:\"Best of\" OR year:2009" ); i = 1; QCOMPARE( result.size(), i ); // only 1 or_list QList elementList; if( !result.isEmpty() ) elementList = result.at(0); QCOMPARE( elementList.size(), 3 ); while( !elementList.isEmpty() ) { element = elementList.takeFirst(); if( element.text == "cure" ) { QCOMPARE( element.field, QString( "artist" ) ); QCOMPARE( element.negate, false ); QVERIFY( element.match == expression_element::Contains ); } else if( element.text == "Best of" ) { QCOMPARE( element.field, QString( "album" ) ); QCOMPARE( element.negate, false ); QVERIFY( element.match == expression_element::Contains ); } else if( element.text == "2009" ) { QCOMPARE( element.field, QString( "year" ) ); QCOMPARE( element.negate, false ); QVERIFY( element.match == expression_element::Contains ); } } } void TestExpression::testIsAdvancedExpression() { QCOMPARE( ExpressionParser::isAdvancedExpression( "" ), false ); QCOMPARE( ExpressionParser::isAdvancedExpression( "test" ), false ); QCOMPARE( ExpressionParser::isAdvancedExpression( "foo bar" ), false ); QCOMPARE( ExpressionParser::isAdvancedExpression( "\"foo bar\"" ), true ); QCOMPARE( ExpressionParser::isAdvancedExpression( "artist:cure" ), true ); QCOMPARE( ExpressionParser::isAdvancedExpression( "year:<1990" ), true ); QCOMPARE( ExpressionParser::isAdvancedExpression( "artist:cure year:<1990" ), true ); QCOMPARE( ExpressionParser::isAdvancedExpression( "artist:cure AND year:<1990" ), true ); QCOMPARE( ExpressionParser::isAdvancedExpression( "artist:cure OR year:<1990" ), true ); QCOMPARE( ExpressionParser::isAdvancedExpression( "-artist:madonna" ), true ); QCOMPARE( ExpressionParser::isAdvancedExpression( "album:\"Best of\"" ), true ); } diff --git a/tests/TestQStringx.cpp b/tests/TestQStringx.cpp index a68893cf6b..382d5320da 100644 --- a/tests/TestQStringx.cpp +++ b/tests/TestQStringx.cpp @@ -1,172 +1,172 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestQStringx.h" #include "core/support/Debug.h" #include #include #include -QTEST_MAIN( TestQStringx ) +QTEST_GUILESS_MAIN( TestQStringx ) //required for Debug.h QMutex Debug::mutex; TestQStringx::TestQStringx() { } void TestQStringx::testArgs() { QStringList testArgs; m_testString = ""; QCOMPARE( m_testString.args( testArgs ) , QString( "" ) ); m_testString = "test"; QCOMPARE( m_testString.args( testArgs ), QString( "test" ) ); m_testString = ""; testArgs.append( "test" ); QCOMPARE( m_testString.args( testArgs ), QString( "" ) ); m_testString = "test%12abc"; QCOMPARE( m_testString.args( testArgs ) , QString( "testtestabc" ) ); m_testString = "%12test abc"; QCOMPARE( m_testString.args( testArgs ) , QString( "testtest abc" ) ); m_testString = "te%st%12abc"; QCOMPARE( m_testString.args( testArgs ) , QString( "te%sttestabc" ) ); testArgs.clear(); testArgs.append( "test" ); testArgs.append( "abc" ); m_testString = "test%12abc%2xyz"; QCOMPARE( m_testString.args( testArgs ) , QString( "testtestabcabcxyz" ) ); m_testString = "%12test%23abc"; QCOMPARE( m_testString.args( testArgs ) , QString( "testtestabcabc" ) ); } void TestQStringx::testNamedArgs() { QMap testArgs; m_testString = ""; QCOMPARE( m_testString.namedArgs( testArgs ) , QString( "" ) ); m_testString = "test"; QCOMPARE( m_testString.namedArgs( testArgs ) , QString( "test" ) ); testArgs[ "artist" ] = "Pornophonique"; m_testString = "test"; QCOMPARE( m_testString.namedArgs( testArgs ) , QString( "test" ) ); m_testString = "artist: %artist%"; QCOMPARE( m_testString.namedArgs( testArgs ) , QString( "artist: Pornophonique" ) ); m_testString = "artist: %artist% - %album%"; QCOMPARE( m_testString.namedArgs( testArgs ) , QString( "artist: Pornophonique - " ) ); testArgs[ "album" ] = "8-Bit Lagerfeuer"; QCOMPARE( m_testString.namedArgs( testArgs ) , QString( "artist: Pornophonique - 8-Bit Lagerfeuer" ) ); m_testString = "%artist%: %artist% - %album%"; QCOMPARE( m_testString.namedArgs( testArgs ) , QString( "Pornophonique: Pornophonique - 8-Bit Lagerfeuer" ) ); testArgs[ "year" ] = "2007"; QCOMPARE( m_testString.namedArgs( testArgs ) , QString( "Pornophonique: Pornophonique - 8-Bit Lagerfeuer" ) ); } void TestQStringx::testNamedOptArgs() { QMap testArgs; m_testString = ""; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "" ) ); m_testString = "test"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "test" ) ); m_testString = "%test%"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "" ) ); m_testString = "{ %test% }"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "" ) ); m_testString = "test{%test%}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "test" ) ); m_testString = "{test{%test%}}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "test" ) ); m_testString = "%test%{%test%}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "" ) ); m_testString = "test%test% "; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "test " ) ); testArgs[ "artist" ] = "All:My:Faults"; m_testString = "%artist%"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "All:My:Faults" ) ); m_testString = "{%test% }{%artist%}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "All:My:Faults" ) ); m_testString = "{%test% {%artist%}}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "" ) ); m_testString = "{%artist% {%test%}}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "All:My:Faults " ) ); testArgs[ "track" ] = "Some track"; m_testString = "{%test% {%artist%}}%track%"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "Some track" ) ); m_testString = "{%artist% {%track%}} %test%"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "All:My:Faults Some track " ) ); testArgs[ "test" ] = ""; m_testString = "{%test%}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "" ) ); m_testString = "before{%test%}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "before" ) ); m_testString = "{%test%}after"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "after" ) ); m_testString = "before{%test%}after"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "beforeafter" ) ); m_testString = "{%test% }{%artist%}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "All:My:Faults" ) ); m_testString = "{%test% {%artist%}}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "" ) ); m_testString = "{%artist% {%test%}}"; QCOMPARE( m_testString.namedOptArgs( testArgs ) , QString( "All:My:Faults " ) ); m_testString = "[%test2%:test {%artist%}%test%{ [%test%]}]"; QCOMPARE( m_testString.namedOptArgs( testArgs ), QString( "test All:My:Faults Unknown test" ) ); } diff --git a/tests/TestSmartPointerList.cpp b/tests/TestSmartPointerList.cpp index 73d77d1bb2..2a27dda698 100644 --- a/tests/TestSmartPointerList.cpp +++ b/tests/TestSmartPointerList.cpp @@ -1,135 +1,135 @@ /*************************************************************************** * Copyright (c) 2009 Max Howell * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestSmartPointerList.h" #include "core/support/SmartPointerList.h" #include #include #include -QTEST_MAIN( TestSmartPointerList ) +QTEST_GUILESS_MAIN( TestSmartPointerList ) // use a macro, as we don't want to test copy ctor early #define THREE_TIMERS( x ) SmartPointerList x; x << new QTimer << new QTimer << new QTimer TestSmartPointerList::TestSmartPointerList() { } void TestSmartPointerList::testCount() { THREE_TIMERS( objects ); QCOMPARE( objects.count(), 3 ); } void TestSmartPointerList::testCopy() { THREE_TIMERS( objects1 ); SmartPointerList objects2 = objects1; for (int x = 0; x < 3; ++x) QVERIFY( objects1[x] == objects2[x] ); QCOMPARE( objects1.count(), 3 ); QCOMPARE( objects2.count(), 3 ); delete objects1.last(); QCOMPARE( objects1.count(), 2 ); QCOMPARE( objects2.count(), 2 ); } void TestSmartPointerList::testCopyAndThenDelete() { THREE_TIMERS( os1 ); SmartPointerList* os2 = new SmartPointerList( os1 ); SmartPointerList os3( *os2 ); delete os2; QCOMPARE( os1.count(), 3 ); QCOMPARE( os3.count(), 3 ); delete os1[1]; QCOMPARE( os1.count(), 2 ); QCOMPARE( os3.count(), 2 ); } void TestSmartPointerList::testRemove() { THREE_TIMERS( objects ); delete objects.last(); QCOMPARE( objects.count(), 2 ); } void TestSmartPointerList::testRemoveAt() { THREE_TIMERS( os ); QTimer* t = os[1]; os.removeAt( 1 ); os << t; QCOMPARE( os.count(), 3 ); delete t; QCOMPARE( os.count(), 2 ); } void TestSmartPointerList::testMultipleOrgasms() { THREE_TIMERS( os ); for (int x = 0; x < 10; ++x) os << os.last(); QCOMPARE( os.count(), 13 ); delete os.last(); QCOMPARE( os.count(), 2 ); } void TestSmartPointerList::testForeach() { THREE_TIMERS( objects ); int x = 0; foreach (QTimer* o, objects) { (void) o; x++; } QCOMPARE( x, 3 ); } void TestSmartPointerList::testOperatorPlus() { THREE_TIMERS( os1 ); SmartPointerList os2 = os1; QCOMPARE( (os1 + os2).count(), 6 ); delete os1.last(); QCOMPARE( (os1 + os2).count(), 4 ); } void TestSmartPointerList::testOperatorPlusEquals() { THREE_TIMERS( os ); os += os; os += os; QCOMPARE( os.count(), 12 ); QTimer* t = os.takeLast(); QCOMPARE( os.count(), 11 ); delete t; QCOMPARE( os.count(), 8 ); } diff --git a/tests/TestTagGuesser.cpp b/tests/TestTagGuesser.cpp index 3b9e08b6a7..1cb59d9e18 100644 --- a/tests/TestTagGuesser.cpp +++ b/tests/TestTagGuesser.cpp @@ -1,70 +1,70 @@ /*************************************************************************** * Copyright (c) 2010 Casey Link * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestTagGuesser.h" #include "dialogs/TagGuesser.h" #include "MetaValues.h" #include #include -QTEST_MAIN( TestTagGuesser ) +QTEST_GUILESS_MAIN( TestTagGuesser ) TestTagGuesser::TestTagGuesser() { } void TestTagGuesser::init() { mTagGuesser = new TagGuesser; } void TestTagGuesser::cleanup() { delete mTagGuesser; } void TestTagGuesser::testStandard() { mTagGuesser->setFilename( "01 - Artist - Title.mp3" ); mTagGuesser->setSchema( "%track% - %artist% - %title%.%ignore%" ); QVERIFY( mTagGuesser->guess() ); QMap tags = mTagGuesser->tags(); QCOMPARE( tags[Meta::valArtist], QString( "Artist" ) ); QCOMPARE( tags[Meta::valTitle], QString( "Title" ) ); QCOMPARE( tags[Meta::valTrackNr], QString( "01" ) ); } void TestTagGuesser::testDotInFilename() { // based off bug 225743 // https://bugs.kde.org/show_bug.cgi?id=225743 mTagGuesser->setFilename( "03.Moloko - Sing It back.mp3" ); mTagGuesser->setSchema( "%track%.%artist% - %title%.%ignore%" ); QVERIFY( mTagGuesser->guess() ); QMap tags = mTagGuesser->tags(); QCOMPARE( tags[Meta::valArtist], QString( "Moloko" ) ); QCOMPARE( tags[Meta::valTitle], QString( "Sing It back" ) ); QCOMPARE( tags[Meta::valTrackNr], QString( "03" ) ); } diff --git a/tests/TestTrackOrganizer.cpp b/tests/TestTrackOrganizer.cpp index 2337e931b6..7be1a780dd 100644 --- a/tests/TestTrackOrganizer.cpp +++ b/tests/TestTrackOrganizer.cpp @@ -1,183 +1,183 @@ /*************************************************************************** * Copyright (c) 2010 Casey Link * * Copyright (c) 2010 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestTrackOrganizer.h" #include "dialogs/TrackOrganizer.h" #include "core/support/Debug.h" #include "CollectionTestImpl.h" #include "mocks/MockTrack.h" #include "mocks/MockAlbum.h" #include "mocks/MockArtist.h" #include #include #include using ::testing::Return; using ::testing::AnyNumber; -QTEST_MAIN( TestTrackOrganizer ) +QTEST_GUILESS_MAIN( TestTrackOrganizer ) namespace Collections { class MyCollectionTestImpl : public CollectionTestImpl { public: MyCollectionTestImpl( const QString &id ) : CollectionTestImpl( id ) {} }; } //namespace Collections TestTrackOrganizer::TestTrackOrganizer() { } void TestTrackOrganizer::init() { mColl = new Collections::MyCollectionTestImpl("A"); } void TestTrackOrganizer::cleanup() { delete mColl; delete mTrackOrganizer; } void TestTrackOrganizer::testBasic() { mTracks = makeTracks( 10 ); mTrackOrganizer = new TrackOrganizer( mTracks, this ); QString folder = "/home/user/Music" ; mTrackOrganizer->setFormatString( "%collectionroot%/%artist%/%album%/%track%-%title%.%filetype%" ); mTrackOrganizer->setFolderPrefix( folder ); QMap dests = mTrackOrganizer->getDestinations(); QVERIFY( dests.size() == 10 ); foreach( Meta::TrackPtr track, mTracks ) { QVERIFY( dests.contains( track ) ); QString format = "%1/%2/%3/%4-%5.%6"; QString trackNum = QString("%1").arg( track->trackNumber(), 2, 10, QChar('0') ); QString result = format.arg( folder, track->artist()->prettyName(), track->album()->prettyName(), trackNum, track->prettyName(), "mp3"); QCOMPARE( dests.value( track ), result ); } } Meta::TrackPtr TestTrackOrganizer::makeMockTrack( const QString &trackName, const QString &artistName, const QString &albumName, int trackNumber ) { Meta::MockTrack *track = new Meta::MockTrack(); ::testing::Mock::AllowLeak( track ); Meta::TrackPtr trackPtr( track ); EXPECT_CALL( *track, name() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName ) ); EXPECT_CALL( *track, prettyName() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName ) ); EXPECT_CALL( *track, uidUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName + '_' + artistName + '_' + albumName ) ); EXPECT_CALL( *track, playableUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( QUrl( '/' + track->uidUrl() ) ) ); EXPECT_CALL( *track, trackNumber() ).Times( AnyNumber() ).WillRepeatedly( Return( trackNumber ) ); EXPECT_CALL( *track, type() ).Times( AnyNumber() ).WillRepeatedly( Return( "mp3" ) ); EXPECT_CALL( *track, composer() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::ComposerPtr() ) ); EXPECT_CALL( *track, year() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::YearPtr() ) ); EXPECT_CALL( *track, genre() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::GenrePtr() ) ); EXPECT_CALL( *track, discNumber() ).Times( AnyNumber() ).WillRepeatedly( Return( 0 ) ); EXPECT_CALL( *track, rating() ).Times( AnyNumber() ).WillRepeatedly( Return( 0 ) ); EXPECT_CALL( *track, filesize() ).Times( AnyNumber() ).WillRepeatedly( Return( 0 ) ); EXPECT_CALL( *track, length() ).Times( AnyNumber() ).WillRepeatedly( Return( 0 ) ); EXPECT_CALL( *track, comment() ).Times( AnyNumber() ).WillRepeatedly( Return( "" ) ); mColl->mc->addTrack( trackPtr ); Meta::AlbumPtr albumPtr = mColl->mc->albumMap().value( albumName, QString() /* no album artist */ ); Meta::MockAlbum *album; Meta::TrackList albumTracks; if( albumPtr ) { album = dynamic_cast( albumPtr.data() ); if( !album ) { qFatal("expected a Meta::MockAlbum"); // QFAIL( "expected a Meta::MockAlbum" ); return trackPtr; } albumTracks = albumPtr->tracks(); } else { album = new Meta::MockAlbum(); ::testing::Mock::AllowLeak( album ); albumPtr = Meta::AlbumPtr( album ); EXPECT_CALL( *album, name() ).Times( AnyNumber() ).WillRepeatedly( Return( albumName ) ); EXPECT_CALL( *album, prettyName() ).Times( AnyNumber() ).WillRepeatedly( Return( albumName ) ); EXPECT_CALL( *album, hasAlbumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( false ) ); EXPECT_CALL( *album, albumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::ArtistPtr() ) ); EXPECT_CALL( *album, isCompilation() ).Times( AnyNumber() ).WillRepeatedly( Return( false ) ); mColl->mc->addAlbum( albumPtr ); } albumTracks << trackPtr; EXPECT_CALL( *album, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( albumTracks ) ); EXPECT_CALL( *track, album() ).Times( AnyNumber() ).WillRepeatedly( Return( albumPtr ) ); Meta::ArtistPtr artistPtr = mColl->mc->artistMap().value( artistName ); Meta::MockArtist *artist; Meta::TrackList artistTracks; if( artistPtr ) { artist = dynamic_cast( artistPtr.data() ); if( !artist ) { qFatal("expected a Meta::MockArtist"); // QFAIL( "expected a Meta::MockArtist" ); return trackPtr; } artistTracks = artistPtr->tracks(); } else { artist = new Meta::MockArtist(); ::testing::Mock::AllowLeak( artist ); artistPtr = Meta::ArtistPtr( artist ); EXPECT_CALL( *artist, name() ).Times( AnyNumber() ).WillRepeatedly( Return( artistName ) ); EXPECT_CALL( *artist, prettyName() ).Times( AnyNumber() ).WillRepeatedly( Return( artistName ) ); mColl->mc->addArtist( artistPtr ); } artistTracks << trackPtr; EXPECT_CALL( *artist, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( artistTracks ) ); EXPECT_CALL( *track, artist() ).Times( AnyNumber() ).WillRepeatedly( Return( artistPtr ) ); return trackPtr; } Meta::TrackList TestTrackOrganizer::makeTracks( int numTracks ) { Meta::TrackList tracks; for( int i = 1; i <= numTracks; ++i ) { QString title = "Title" + QString::number(i); Meta::TrackPtr t = makeMockTrack( title, "Artist1", "Album1", i ); if( t ) tracks << t; } return tracks; } diff --git a/tests/amarokurls/TestAmarokUrls.cpp b/tests/amarokurls/TestAmarokUrls.cpp index 6e00568217..bb409b751d 100644 --- a/tests/amarokurls/TestAmarokUrls.cpp +++ b/tests/amarokurls/TestAmarokUrls.cpp @@ -1,97 +1,97 @@ /**************************************************************************************** * Copyright (c) 2010 Nikolaj Hald Nielsen * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Pulic License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestAmarokUrls.h" #include "core/support/Components.h" #include "EngineController.h" #include "config-amarok-test.h" #include "amarokurls/AmarokUrl.h" #include "amarokurls/AmarokUrlHandler.h" #include -QTEST_MAIN( TestAmarokUrls ) +QTEST_GUILESS_MAIN( TestAmarokUrls ) TestAmarokUrls::TestAmarokUrls() : QObject() { //apparently the engine controller is needed somewhere, or we will get a crash... EngineController *controller = new EngineController(); Amarok::Components::setEngineController( controller ); } void TestAmarokUrls::testConstructUrl() { AmarokUrl url; url.setCommand( "navigate" ); url.setPath( "collections" ); url.setArg( "filter", "artist:\"Code Monkeys\"" ); url.setArg( "levels", "artist-album" ); QCOMPARE( url.command(), QString( "navigate" ) ); QCOMPARE( url.path(), QString( "collections" ) ); QCOMPARE( url.args().size(), 2 ); QVERIFY( url.args().keys().contains( "filter" ) ); QVERIFY( url.args().keys().contains( "levels" ) ); QCOMPARE( url.args().value( "filter" ), QString( "artist:\"Code Monkeys\"" ) ); QCOMPARE( url.args().value( "levels" ), QString( "artist-album") ); QCOMPARE( url.prettyCommand(), The::amarokUrlHandler()->prettyCommand( "navigate" ) ); } void TestAmarokUrls::testUrlFromString() { AmarokUrl url( "amarok://navigate/collections?filter=artist:\"Code Monkeys\"&levels=artist-album" ); QCOMPARE( url.command(), QString( "navigate" ) ); QCOMPARE( url.path(), QString( "collections" ) ); QCOMPARE( url.args().size(), 2 ); QVERIFY( url.args().keys().contains( "filter" ) ); QVERIFY( url.args().keys().contains( "levels" ) ); QCOMPARE( url.args().value( "filter" ), QString( "artist:\"Code Monkeys\"" ) ); QCOMPARE( url.args().value( "levels" ), QString( "artist-album") ); QCOMPARE( url.prettyCommand(), The::amarokUrlHandler()->prettyCommand( "navigate" ) ); } void TestAmarokUrls::testEncoding() { QString urlString( "amarok://navigate/collections?filter=artist:\"Code Monkeys\"&levels=artist-album" ); AmarokUrl url( urlString ); QUrl qUrl( urlString ); QCOMPARE( url.url(), QString( qUrl.toEncoded() ) ); //check that we do not "double encode" anything AmarokUrl url2( "amarok://navigate/collections?filter=artist:%22Code%20Monkeys%22&levels=artist-album" ); QCOMPARE( url2.url(), QString( qUrl.toEncoded() ) ); } diff --git a/tests/core-impl/collections/aggregate/TestAggregateMeta.cpp b/tests/core-impl/collections/aggregate/TestAggregateMeta.cpp index 044aabddfe..5677802f60 100644 --- a/tests/core-impl/collections/aggregate/TestAggregateMeta.cpp +++ b/tests/core-impl/collections/aggregate/TestAggregateMeta.cpp @@ -1,513 +1,513 @@ /**************************************************************************************** * Copyright (c) 2010 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestAggregateMeta.h" #include "core/capabilities/OrganiseCapability.h" #include "core/meta/Meta.h" #include "core/meta/TrackEditor.h" #include "core/support/Debug.h" #include "core-impl/collections/aggregate/AggregateCollection.h" #include "core-impl/collections/aggregate/AggregateMeta.h" #include "mocks/MetaMock.h" #include "mocks/MockTrack.h" #include #include #include -QTEST_MAIN( TestAggregateMeta ) +QTEST_GUILESS_MAIN( TestAggregateMeta ) TestAggregateMeta::TestAggregateMeta() { int argc = 1; char **argv = (char **) malloc(sizeof(char *)); argv[0] = strdup( QCoreApplication::applicationName().toLocal8Bit().data() ); ::testing::InitGoogleMock( &argc, argv ); } class MyTrackMock : public MetaMock { public: MyTrackMock() : MetaMock( QVariantMap() ) {} bool hasCapabilityInterface( Capabilities::Capability::Type type ) const { bool result = results.value( type ); results.remove( type ); return result; } Capabilities::Capability* createCapabilityInterface(Capabilities::Capability::Type type) { Capabilities::Capability* cap = capabilities.value( type ); capabilities.remove( type ); return cap; } Meta::TrackEditorPtr editor() { return trackEditors.isEmpty() ? Meta::TrackEditorPtr() : trackEditors.takeFirst(); } mutable QMap results; mutable QMap capabilities; QList trackEditors; }; class MyAlbumMock : public MockAlbum { public: MyAlbumMock() : MockAlbum( "testAlbum" ) {} bool hasCapabilityInterface( Capabilities::Capability::Type type ) const { bool result = results.value( type ); results.remove( type ); return result; } Capabilities::Capability* createCapabilityInterface(Capabilities::Capability::Type type) { Capabilities::Capability* cap = capabilities.value( type ); capabilities.remove( type ); return cap; } mutable QMap results; mutable QMap capabilities; }; class MyArtistMock : public MockArtist { public: MyArtistMock() : MockArtist( "testArtist" ) {} bool hasCapabilityInterface( Capabilities::Capability::Type type ) const { bool result = results.value( type ); results.remove( type ); return result; } Capabilities::Capability* createCapabilityInterface(Capabilities::Capability::Type type) { Capabilities::Capability* cap = capabilities.value( type ); capabilities.remove( type ); return cap; } mutable QMap results; mutable QMap capabilities; }; class MyGenreMock : public MockGenre { public: MyGenreMock() : MockGenre( "testGenre" ) {} bool hasCapabilityInterface( Capabilities::Capability::Type type ) const { bool result = results.value( type ); results.remove( type ); return result; } Capabilities::Capability* createCapabilityInterface(Capabilities::Capability::Type type) { Capabilities::Capability* cap = capabilities.value( type ); capabilities.remove( type ); return cap; } mutable QMap results; mutable QMap capabilities; }; class MyComposerMock : public MockComposer { public: MyComposerMock() : MockComposer( "testComposer" ) {} bool hasCapabilityInterface( Capabilities::Capability::Type type ) const { bool result = results.value( type ); results.remove( type ); return result; } Capabilities::Capability* createCapabilityInterface(Capabilities::Capability::Type type) { Capabilities::Capability* cap = capabilities.value( type ); capabilities.remove( type ); return cap; } mutable QMap results; mutable QMap capabilities; }; class MyYearMock : public MockYear { public: MyYearMock() : MockYear( "testYear" ) {} bool hasCapabilityInterface( Capabilities::Capability::Type type ) const { bool result = results.value( type ); results.remove( type ); return result; } Capabilities::Capability* createCapabilityInterface(Capabilities::Capability::Type type) { Capabilities::Capability* cap = capabilities.value( type ); capabilities.remove( type ); return cap; } mutable QMap results; mutable QMap capabilities; }; class MyOrganiseCapability : public Capabilities::OrganiseCapability { public: void deleteTrack() {} }; void TestAggregateMeta::testHasCapabilityOnSingleTrack() { MyTrackMock *mock = new MyTrackMock(); QMap results; results.insert( Capabilities::Capability::Buyable, false ); results.insert( Capabilities::Capability::BookmarkThis, true ); mock->results = results; Meta::TrackPtr ptr( mock ); Meta::AggregateTrack cut( 0, ptr ); QVERIFY( cut.hasCapabilityInterface( Capabilities::Capability::BookmarkThis ) ); QVERIFY( !cut.hasCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( mock->results.count(), 0 ); } void TestAggregateMeta::testCreateCapabilityOnSingleTrack() { MyTrackMock *mock = new MyTrackMock(); QMap capabilities; capabilities.insert( Capabilities::Capability::Buyable, 0 ); Capabilities::Capability *cap = new MyOrganiseCapability(); capabilities.insert( Capabilities::Capability::Organisable, cap ); mock->capabilities = capabilities; Meta::TrackPtr ptr( mock ); Meta::AggregateTrack cut( 0, ptr ); QVERIFY( ! cut.createCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( cut.createCapabilityInterface( Capabilities::Capability::Organisable ), cap ); QCOMPARE( mock->capabilities.count(), 0 ); delete cap; } void TestAggregateMeta::testHasCapabilityOnSingleAlbum() { MyAlbumMock *mock = new MyAlbumMock(); QMap results; results.insert( Capabilities::Capability::Buyable, false ); results.insert( Capabilities::Capability::BookmarkThis, true ); mock->results = results; Meta::AlbumPtr ptr( mock ); Meta::AggregateAlbum album( 0, ptr ); QVERIFY( album.hasCapabilityInterface( Capabilities::Capability::BookmarkThis ) ); QVERIFY( !album.hasCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( mock->results.count(), 0 ); } void TestAggregateMeta::testCreateCapabilityOnSingleAlbum() { MyAlbumMock *mock = new MyAlbumMock(); QMap capabilities; capabilities.insert( Capabilities::Capability::Buyable, 0 ); Capabilities::Capability *cap = new MyOrganiseCapability(); capabilities.insert( Capabilities::Capability::Organisable, cap ); mock->capabilities = capabilities; Meta::AlbumPtr ptr( mock ); Meta::AggregateAlbum album( 0, ptr ); QVERIFY( ! album.createCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( album.createCapabilityInterface( Capabilities::Capability::Organisable ), cap ); QCOMPARE( mock->capabilities.count(), 0 ); delete cap; } void TestAggregateMeta::testHasCapabilityOnSingleArtist() { MyArtistMock *mock = new MyArtistMock(); QMap results; results.insert( Capabilities::Capability::Buyable, false ); results.insert( Capabilities::Capability::BookmarkThis, true ); mock->results = results; Meta::ArtistPtr ptr( mock ); Meta::AggregateArtist artist( 0, ptr ); QVERIFY( artist.hasCapabilityInterface( Capabilities::Capability::BookmarkThis ) ); QVERIFY( !artist.hasCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( mock->results.count(), 0 ); } void TestAggregateMeta::testCreateCapabilityOnSingleArtist() { MyArtistMock *mock = new MyArtistMock(); QMap capabilities; capabilities.insert( Capabilities::Capability::Buyable, 0 ); Capabilities::Capability *cap = new MyOrganiseCapability(); capabilities.insert( Capabilities::Capability::Organisable, cap ); mock->capabilities = capabilities; Meta::ArtistPtr ptr( mock ); Meta::AggregateArtist artist( 0, ptr ); QVERIFY( ! artist.createCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( artist.createCapabilityInterface( Capabilities::Capability::Organisable ), cap ); QCOMPARE( mock->capabilities.count(), 0 ); delete cap; } void TestAggregateMeta::testHasCapabilityOnSingleComposer() { MyComposerMock *mock = new MyComposerMock(); QMap results; results.insert( Capabilities::Capability::Buyable, false ); results.insert( Capabilities::Capability::BookmarkThis, true ); mock->results = results; Meta::ComposerPtr ptr( mock ); Meta::AggregateComposer cut( 0, ptr ); QVERIFY( cut.hasCapabilityInterface( Capabilities::Capability::BookmarkThis ) ); QVERIFY( !cut.hasCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( mock->results.count(), 0 ); } void TestAggregateMeta::testCreateCapabilityOnSingleComposer() { MyComposerMock *mock = new MyComposerMock(); QMap capabilities; capabilities.insert( Capabilities::Capability::Buyable, 0 ); Capabilities::Capability *cap = new MyOrganiseCapability(); capabilities.insert( Capabilities::Capability::Organisable, cap ); mock->capabilities = capabilities; Meta::ComposerPtr ptr( mock ); Meta::AggregateComposer cut( 0, ptr ); QVERIFY( ! cut.createCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( cut.createCapabilityInterface( Capabilities::Capability::Organisable ), cap ); QCOMPARE( mock->capabilities.count(), 0 ); delete cap; } void TestAggregateMeta::testHasCapabilityOnSingleGenre() { MyGenreMock *mock = new MyGenreMock(); QMap results; results.insert( Capabilities::Capability::Buyable, false ); results.insert( Capabilities::Capability::BookmarkThis, true ); mock->results = results; Meta::GenrePtr ptr( mock ); Meta::AggregateGenre cut( 0, ptr ); QVERIFY( cut.hasCapabilityInterface( Capabilities::Capability::BookmarkThis ) ); QVERIFY( !cut.hasCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( mock->results.count(), 0 ); } void TestAggregateMeta::testCreateCapabilityOnSingleGenre() { MyGenreMock *mock = new MyGenreMock(); QMap capabilities; capabilities.insert( Capabilities::Capability::Buyable, 0 ); Capabilities::Capability *cap = new MyOrganiseCapability(); capabilities.insert( Capabilities::Capability::Organisable, cap ); mock->capabilities = capabilities; Meta::GenrePtr ptr( mock ); Meta::AggregateGenre cut( 0, ptr ); QVERIFY( ! cut.createCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( cut.createCapabilityInterface( Capabilities::Capability::Organisable ), cap ); QCOMPARE( mock->capabilities.count(), 0 ); delete cap; } void TestAggregateMeta::testHasCapabilityOnSingleYear() { MyYearMock *mock = new MyYearMock(); QMap results; results.insert( Capabilities::Capability::Buyable, false ); results.insert( Capabilities::Capability::BookmarkThis, true ); mock->results = results; Meta::YearPtr ptr( mock ); Meta::AggreagateYear cut( 0, ptr ); QVERIFY( cut.hasCapabilityInterface( Capabilities::Capability::BookmarkThis ) ); QVERIFY( !cut.hasCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( mock->results.count(), 0 ); } void TestAggregateMeta::testCreateCapabilityOnSingleYear() { MyYearMock *mock = new MyYearMock(); QMap capabilities; capabilities.insert( Capabilities::Capability::Buyable, 0 ); Capabilities::Capability *cap = new MyOrganiseCapability(); capabilities.insert( Capabilities::Capability::Organisable, cap ); mock->capabilities = capabilities; Meta::YearPtr ptr( mock ); Meta::AggreagateYear cut( 0, ptr ); QVERIFY( ! cut.createCapabilityInterface( Capabilities::Capability::Buyable ) ); QCOMPARE( cut.createCapabilityInterface( Capabilities::Capability::Organisable ), cap ); QCOMPARE( mock->capabilities.count(), 0 ); delete cap; } class MyTrackEditor : public Meta::TrackEditor { public: MyTrackEditor() : Meta::TrackEditor() , beginCallCount(0) , endCallcount(0) {} virtual void setAlbum( const QString &newAlbum ) { Q_UNUSED( newAlbum ) } virtual void setAlbumArtist( const QString &newAlbumArtist ) { Q_UNUSED( newAlbumArtist ) } virtual void setArtist( const QString &newArtist ) { Q_UNUSED( newArtist ) } virtual void setComposer( const QString &newComposer ) { Q_UNUSED( newComposer ) }; virtual void setGenre( const QString &newGenre ) { Q_UNUSED( newGenre ) }; virtual void setYear( int newYear ) { Q_UNUSED( newYear ) }; virtual void setTitle( const QString &newTitle ) { Q_UNUSED( newTitle ) }; virtual void setComment( const QString &newComment ) { Q_UNUSED( newComment ) }; virtual void setTrackNumber( int newTrackNumber ) { Q_UNUSED( newTrackNumber ) }; virtual void setDiscNumber( int newDiscNumber ) { Q_UNUSED( newDiscNumber ) }; virtual void setBpm( const qreal newBpm ) { Q_UNUSED( newBpm ) }; virtual void beginUpdate() { beginCallCount++; }; virtual void endUpdate() { endCallcount++; }; int beginCallCount; int endCallcount; }; void TestAggregateMeta::testEditableCapabilityOnMultipleTracks() { MyTrackMock *mock1 = new MyTrackMock(); MyTrackMock *mock2 = new MyTrackMock(); AmarokSharedPointer cap1 ( new MyTrackEditor() ); AmarokSharedPointer cap2 ( new MyTrackEditor() ); mock1->trackEditors << Meta::TrackEditorPtr( cap1.data() ); mock2->trackEditors << Meta::TrackEditorPtr( cap2.data() ); Meta::TrackPtr ptr1( mock1 ); Meta::TrackPtr ptr2( mock2 ); Collections::AggregateCollection *collection = new Collections::AggregateCollection(); QSignalSpy spy( collection, &Collections::AggregateCollection::updated); QVERIFY( spy.isValid() ); Meta::AggregateTrack cut( collection, ptr1 ); cut.add( ptr2 ); Meta::TrackEditorPtr editCap = cut.editor(); QVERIFY( editCap ); QCOMPARE( cap1->beginCallCount, 0 ); QCOMPARE( cap2->beginCallCount, 0 ); editCap->beginUpdate(); QCOMPARE( cap1->beginCallCount, 1 ); QCOMPARE( cap2->beginCallCount, 1 ); QCOMPARE( cap1->endCallcount, 0 ); QCOMPARE( cap2->endCallcount, 0 ); editCap->endUpdate(); QCOMPARE( cap1->endCallcount, 1 ); QCOMPARE( cap2->endCallcount, 1 ); //the signal is delayed a bit, but that is ok QTest::qWait( 50 ); //required so that the colleection browser refreshes itself QCOMPARE( spy.count(), 1 ); } using ::testing::Return; using ::testing::AnyNumber; void TestAggregateMeta::testPrettyUrl() { Meta::MockTrack *mock = new ::testing::NiceMock(); EXPECT_CALL( *mock, prettyUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( "foo" ) ); Meta::TrackPtr trackPtr( mock ); Meta::AggregateTrack track( 0, trackPtr ); QCOMPARE( track.prettyUrl(), QString( "foo" ) ); } diff --git a/tests/core-impl/collections/db/sql/TestSqlArtist.cpp b/tests/core-impl/collections/db/sql/TestSqlArtist.cpp index f32a571e3e..0e4e32d5b6 100644 --- a/tests/core-impl/collections/db/sql/TestSqlArtist.cpp +++ b/tests/core-impl/collections/db/sql/TestSqlArtist.cpp @@ -1,94 +1,94 @@ /**************************************************************************************** * Copyright (c) 2009 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestSqlArtist.h" #include "DefaultSqlQueryMakerFactory.h" #include "core/meta/Meta.h" #include "core-impl/storage/sql/mysqlestorage/MySqlEmbeddedStorage.h" #include "SqlCollection.h" #include "SqlMountPointManagerMock.h" -QTEST_MAIN( TestSqlArtist ) +QTEST_GUILESS_MAIN( TestSqlArtist ) TestSqlArtist::TestSqlArtist() : QObject() , m_collection( 0 ) , m_storage( 0 ) , m_tmpDir( 0 ) { } void TestSqlArtist::initTestCase() { m_tmpDir = new QTemporaryDir(); m_storage = QSharedPointer( new MySqlEmbeddedStorage() ); QVERIFY( m_storage->init( m_tmpDir->path() ) ); m_collection = new Collections::SqlCollection( m_storage ); m_collection->setMountPointManager( new SqlMountPointManagerMock( this, m_storage ) ); } void TestSqlArtist::cleanupTestCase() { delete m_collection; delete m_tmpDir; } void TestSqlArtist::init() { //setup base data m_storage->query( "INSERT INTO artists(id, name) VALUES (1, 'The Foo');" ); m_storage->query( "INSERT INTO artists(id, name) VALUES (2, 'No The Foo');" ); m_storage->query( "INSERT INTO artists(id, name) VALUES (3, 'artist3');" ); m_storage->query( "INSERT INTO composers(id, name) VALUES (1, 'composer1');" ); m_storage->query( "INSERT INTO genres(id, name) VALUES (1, 'genre1');" ); m_storage->query( "INSERT INTO years(id, name) VALUES (1, '1');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, uniqueid ) VALUES (1, -1, './IDoNotExist.mp3', 'uid://1');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, uniqueid ) VALUES (2, -1, './IDoNotExistAsWell.mp3', 'uid://2');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, uniqueid ) VALUES (3, -1, './MeNeither.mp3', 'uid:/3');" ); } void TestSqlArtist::cleanup() { m_storage->query( "TRUNCATE TABLE years;" ); m_storage->query( "TRUNCATE TABLE genres;" ); m_storage->query( "TRUNCATE TABLE composers;" ); m_storage->query( "TRUNCATE TABLE albums;" ); m_storage->query( "TRUNCATE TABLE artists;" ); m_storage->query( "TRUNCATE TABLE tracks;" ); m_storage->query( "TRUNCATE TABLE urls;" ); m_storage->query( "TRUNCATE TABLE labels;" ); m_storage->query( "TRUNCATE TABLE urls_labels;" ); } void TestSqlArtist::testSortableName() { Meta::ArtistPtr artistWithThe = m_collection->registry()->getArtist( 1 ); QCOMPARE( artistWithThe->sortableName(), QString( "Foo, The" ) ); Meta::ArtistPtr artistWithoutThe = m_collection->registry()->getArtist( 2 ); QCOMPARE( artistWithoutThe->sortableName(), QString( "No The Foo" ) ); } diff --git a/tests/core-impl/collections/db/sql/TestSqlCollection.cpp b/tests/core-impl/collections/db/sql/TestSqlCollection.cpp index ca3ab3fa82..79fddeb977 100644 --- a/tests/core-impl/collections/db/sql/TestSqlCollection.cpp +++ b/tests/core-impl/collections/db/sql/TestSqlCollection.cpp @@ -1,91 +1,91 @@ /**************************************************************************************** * Copyright (c) 2009 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestSqlCollection.h" #include #include #include #include #include "SqlMountPointManagerMock.h" #include -QTEST_MAIN( TestSqlCollection ) +QTEST_GUILESS_MAIN( TestSqlCollection ) TestSqlCollection::TestSqlCollection() { } void TestSqlCollection::initTestCase() { m_tmpDir = new QTemporaryDir(); m_storage = QSharedPointer( new MySqlEmbeddedStorage() ); QVERIFY( m_storage->init( m_tmpDir->path() ) ); m_collection = new Collections::SqlCollection( m_storage ); m_mpmMock = new SqlMountPointManagerMock( this, m_storage ); m_collection->setMountPointManager( m_mpmMock ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath) VALUES (1, 1, './IDoNotExist.mp3');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath) VALUES (2, 2, './IDoNotExistAsWell.mp3');" ); m_storage->query( "INSERT INTO tracks(id, url,title) VALUES ( 1,1,'test1');" ); } void TestSqlCollection::cleanupTestCase() { delete m_collection; //m_mpMock is deleted by SqlCollection delete m_tmpDir; } void TestSqlCollection::testDeviceAddedWithTracks() { QSignalSpy spy( m_collection, &Collections::SqlCollection::updated); m_mpmMock->emitDeviceAdded( 1 ); QCOMPARE( spy.count(), 1 ); } void TestSqlCollection::testDeviceAddedWithoutTracks() { QSignalSpy spy( m_collection, &Collections::SqlCollection::updated); m_mpmMock->emitDeviceAdded( 2 ); QCOMPARE( spy.count(), 0 ); } void TestSqlCollection::testDeviceRemovedWithTracks() { QSignalSpy spy( m_collection, &Collections::SqlCollection::updated); m_mpmMock->emitDeviceRemoved( 1 ); QCOMPARE( spy.count(), 1 ); } void TestSqlCollection::testDeviceRemovedWithoutTracks() { QSignalSpy spy( m_collection, &Collections::SqlCollection::updated); m_mpmMock->emitDeviceRemoved( 0 ); QCOMPARE( spy.count(), 0 ); } diff --git a/tests/core-impl/collections/db/sql/TestSqlCollectionLocation.cpp b/tests/core-impl/collections/db/sql/TestSqlCollectionLocation.cpp index 9531efcea0..1e04262b68 100644 --- a/tests/core-impl/collections/db/sql/TestSqlCollectionLocation.cpp +++ b/tests/core-impl/collections/db/sql/TestSqlCollectionLocation.cpp @@ -1,280 +1,280 @@ /**************************************************************************************** * Copyright (c) 2009 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestSqlCollectionLocation.h" #include "DatabaseUpdater.h" #include "core/support/Debug.h" #include "core/support/Components.h" #include "core-impl/logger/ProxyLogger.h" #include "DefaultSqlQueryMakerFactory.h" #include "core/meta/Meta.h" #include "core-impl/storage/sql/mysqlestorage/MySqlEmbeddedStorage.h" #include "SqlCollection.h" #include "SqlCollectionLocation.h" #include "SqlRegistry.h" #include "SqlMountPointManagerMock.h" #include "core/collections/MockCollectionLocationDelegate.h" #include "config-amarok-test.h" #include #include #include #include #include using ::testing::AnyNumber; using ::testing::Return; using ::testing::_; /** A SqlCollectionLocation that claims writing is possible even though it doesn't have * a valid directory. */ class MySqlCollectionLocation : public Collections::SqlCollectionLocation { public: MySqlCollectionLocation( Collections::SqlCollection *coll ) : Collections::SqlCollectionLocation( coll ) {} virtual ~MySqlCollectionLocation() {} bool isWritable() const { return true; } }; class MyOrganizeCollectionDelegate : public OrganizeCollectionDelegate { public: MyOrganizeCollectionDelegate() : OrganizeCollectionDelegate(), overwrite( false ), migrate( false ) {} virtual ~ MyOrganizeCollectionDelegate() {} void setTracks( const Meta::TrackList &tracks ) { Q_UNUSED( tracks ) } void setFolders( const QStringList &folders ) { Q_UNUSED( folders ) } void setIsOrganizing( bool organizing ) { Q_UNUSED( organizing ) } void setTranscodingConfiguration(const Transcoding::Configuration &configuration) { Q_UNUSED( configuration ) } void setCaption( const QString& ) {} void show() { emit accepted(); } bool overwriteDestinations() const { return overwrite; } QMap destinations() const { return dests; } bool migrateLabels() const { return migrate; } bool overwrite; bool migrate; QMap dests; }; class MyOrganizeCollectionDelegateFactory : public OrganizeCollectionDelegateFactory { public: MyOrganizeCollectionDelegateFactory( OrganizeCollectionDelegate *d ) : OrganizeCollectionDelegateFactory() , delegate( d ) {} virtual ~ MyOrganizeCollectionDelegateFactory() {} //warning: SqlCollectionLocation will delete the delegate OrganizeCollectionDelegate* createDelegate() { return delegate; } OrganizeCollectionDelegate *delegate; }; -QTEST_MAIN( TestSqlCollectionLocation ) +QTEST_GUILESS_MAIN( TestSqlCollectionLocation ) TestSqlCollectionLocation::TestSqlCollectionLocation() : QObject() , m_collection( 0 ) , m_storage( 0 ) , m_tmpDir( 0 ) { int argc = 1; char **argv = (char **) malloc(sizeof(char *)); argv[0] = strdup( QCoreApplication::applicationName().toLocal8Bit().data() ); ::testing::InitGoogleMock( &argc, argv ); } void TestSqlCollectionLocation::initTestCase() { Amarok::Components::setLogger( new ProxyLogger() ); m_tmpDir = new QTemporaryDir(); m_storage = QSharedPointer( new MySqlEmbeddedStorage() ); QVERIFY( m_storage->init( m_tmpDir->path() ) ); m_collection = new Collections::SqlCollection( m_storage ); SqlMountPointManagerMock *mock = new SqlMountPointManagerMock( this, m_storage ); mock->setCollectionFolders( QStringList() << m_tmpDir->path() ); // the target folder needs to have enough space and be writable m_collection->setMountPointManager( mock ); // I just need the table and not the whole playlist manager m_storage->query( QString( "CREATE TABLE playlist_tracks (" " id " + m_storage->idType() + ", playlist_id INTEGER " ", track_num INTEGER " ", url " + m_storage->exactTextColumnType() + ", title " + m_storage->textColumnType() + ", album " + m_storage->textColumnType() + ", artist " + m_storage->textColumnType() + ", length INTEGER " ", uniqueid " + m_storage->textColumnType(128) + ") ENGINE = MyISAM;" ) ); } void TestSqlCollectionLocation::cleanupTestCase() { delete m_collection; delete Amarok::Components::setLogger( 0 ); //m_storage is deleted by SqlCollection delete m_tmpDir; } void TestSqlCollectionLocation::init() { //setup base data m_storage->query( "INSERT INTO artists(id, name) VALUES (1, 'artist1');" ); m_storage->query( "INSERT INTO artists(id, name) VALUES (2, 'artist2');" ); m_storage->query( "INSERT INTO artists(id, name) VALUES (3, 'artist3');" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(1,'album1',1);" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(2,'album2',1);" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(3,'album3',2);" ); m_storage->query( "INSERT INTO composers(id, name) VALUES (1, 'composer1');" ); m_storage->query( "INSERT INTO genres(id, name) VALUES (1, 'genre1');" ); m_storage->query( "INSERT INTO years(id, name) VALUES (1, '1');" ); m_storage->query( "INSERT INTO directories(id,deviceid,dir) VALUES (1, -1, '." + m_tmpDir->path() + "/ab/')"); m_storage->query( "INSERT INTO directories(id,deviceid,dir) VALUES (2, -1, '." + m_tmpDir->path() + "/b/')"); m_storage->query( "INSERT INTO directories(id,deviceid,dir) VALUES (3, -1, '." + m_tmpDir->path() + "/c/')"); m_storage->query( QString( "INSERT INTO urls(id, deviceid, rpath, uniqueid, directory ) VALUES (1, -1, '%1', 'uid://1', 1);" ).arg( setupFileInTempDir( "ab/IDoNotExist.mp3" ) ) ); m_storage->query( QString( "INSERT INTO urls(id, deviceid, rpath, uniqueid, directory ) VALUES (2, -1, '%1', 'uid://2', 2);" ).arg( setupFileInTempDir( "b/IDoNotExistAsWell.mp3") ) ); m_storage->query( QString( "INSERT INTO urls(id, deviceid, rpath, uniqueid, directory ) VALUES (3, -1, '%1', 'uid:/3', 3);" ).arg( setupFileInTempDir( "c/MeNeither.mp3" ) ) ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(1,1,'track1','comment1',1,1,1,1,1);" ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(2,2,'track2','comment2',1,2,1,1,1);" ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(3,3,'track3','comment3',2,3,1,1,1);" ); m_collection->registry()->emptyCache(); } void TestSqlCollectionLocation::cleanup() { delete Amarok::Components::setCollectionLocationDelegate( 0 ); m_storage->query( "TRUNCATE TABLE years;" ); m_storage->query( "TRUNCATE TABLE genres;" ); m_storage->query( "TRUNCATE TABLE composers;" ); m_storage->query( "TRUNCATE TABLE albums;" ); m_storage->query( "TRUNCATE TABLE artists;" ); m_storage->query( "TRUNCATE TABLE tracks;" ); m_storage->query( "TRUNCATE TABLE urls;" ); m_storage->query( "TRUNCATE TABLE labels;" ); m_storage->query( "TRUNCATE TABLE urls_labels;" ); m_storage->query( "TRUNCATE TABLE directories;" ); } void TestSqlCollectionLocation::testOrganizingCopiesLabels() { { Collections::MockCollectionLocationDelegate *d = new Collections::MockCollectionLocationDelegate(); EXPECT_CALL( *d, reallyMove( _, _ ) ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); EXPECT_CALL( *d, transcode( _, _, _, _, _ ) ).WillOnce( Return( Transcoding::Configuration( Transcoding::INVALID ) ) ); Amarok::Components::setCollectionLocationDelegate( d ); } { Meta::TrackPtr track = m_collection->registry()->getTrackFromUid( "uid://1" ); QVERIFY( track ); QVERIFY( track->playableUrl().path().endsWith( "ab/IDoNotExist.mp3" ) ); track->addLabel( "test" ); QCOMPARE( track->labels().count(), 1 ); Collections::SqlCollectionLocation *source = new MySqlCollectionLocation( m_collection ); Collections::SqlCollectionLocation *dest = new MySqlCollectionLocation( m_collection ); QSignalSpy spy( source, &Collections::SqlCollectionLocation::destroyed ); { MyOrganizeCollectionDelegate *delegate = new MyOrganizeCollectionDelegate(); delegate->overwrite = true; delegate->migrate = true; delegate->dests.insert( track, m_tmpDir->path() + "b/IDoNotExist.mp3" ); dest->setOrganizeCollectionDelegateFactory( new MyOrganizeCollectionDelegateFactory( delegate ) ); } source->prepareMove( track, dest ); spy.wait( 1000 ); QCOMPARE( track->labels().count(), 1 ); QVERIFY( track->playableUrl().path().endsWith( "b/IDoNotExist.mp3" ) ); } //force a reload from the database m_collection->registry()->emptyCache(); { // Meta::TrackPtr track = m_collection->registry()->getTrack( m_tmpDir->path() + "/b/IDoNotExist.mp3" ); Meta::TrackPtr track = m_collection->registry()->getTrack(1); QVERIFY( track ); QVERIFY( track->playableUrl().path().endsWith( "b/IDoNotExist.mp3" ) ); // TODO: check that the db urls entry really specifies the exiting directories entry QCOMPARE( track->labels().count(), 1 ); } } void TestSqlCollectionLocation::testCopiesLabelFromExternalTracks() { } void TestSqlCollectionLocation::testCopyTrackToDirectoryWithExistingTracks() { } QString TestSqlCollectionLocation::setupFileInTempDir( const QString &relativeName ) { QString absoluteName = m_tmpDir->path() + '/' + relativeName; //TODO: unix specific //create directory where necessary int index = absoluteName.lastIndexOf( '/' ); if(index > 0 ) { QString dir = absoluteName.left( index ); QProcess::execute( "mkdir", QStringList() << "-p" << dir ); } else { qDebug() << "huh? index was " << index << " relative name was " << relativeName << " tmpDir " << m_tmpDir->path(); } QProcess::execute( "touch", QStringList() << absoluteName ); return '.' + absoluteName; } diff --git a/tests/core-impl/collections/db/sql/TestSqlQueryMaker.cpp b/tests/core-impl/collections/db/sql/TestSqlQueryMaker.cpp index 6e79b2c5f9..ef600e0323 100644 --- a/tests/core-impl/collections/db/sql/TestSqlQueryMaker.cpp +++ b/tests/core-impl/collections/db/sql/TestSqlQueryMaker.cpp @@ -1,1025 +1,1025 @@ /**************************************************************************************** * Copyright (c) 2009 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestSqlQueryMaker.h" #include "core/support/Debug.h" #include "DatabaseUpdater.h" #include "SqlCollection.h" #include "SqlQueryMaker.h" #include "SqlRegistry.h" #include "core-impl/storage/sql/mysqlestorage/MySqlEmbeddedStorage.h" #include "SqlMountPointManagerMock.h" #include using namespace Collections; -QTEST_MAIN( TestSqlQueryMaker ) +QTEST_GUILESS_MAIN( TestSqlQueryMaker ) //required for QTest, this is not done in Querymaker.h Q_DECLARE_METATYPE( Collections::QueryMaker::QueryType ) Q_DECLARE_METATYPE( Collections::QueryMaker::NumberComparison ) Q_DECLARE_METATYPE( Collections::QueryMaker::ReturnFunction ) Q_DECLARE_METATYPE( Collections::QueryMaker::AlbumQueryMode ) Q_DECLARE_METATYPE( Collections::QueryMaker::LabelQueryMode ) TestSqlQueryMaker::TestSqlQueryMaker() { qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); } void TestSqlQueryMaker::initTestCase() { m_tmpDir = new QTemporaryDir(); m_storage = QSharedPointer( new MySqlEmbeddedStorage() ); QVERIFY( m_storage->init( m_tmpDir->path() ) ); m_collection = new Collections::SqlCollection( m_storage ); QMap mountPoints; mountPoints.insert( 1, "/foo" ); mountPoints.insert( 2, "/bar" ); m_mpm = new SqlMountPointManagerMock( this, m_storage ); m_mpm->m_mountPoints = mountPoints; m_collection->setMountPointManager( m_mpm ); //setup test data m_storage->query( "INSERT INTO artists(id, name) VALUES (1, 'artist1');" ); m_storage->query( "INSERT INTO artists(id, name) VALUES (2, 'artist2');" ); m_storage->query( "INSERT INTO artists(id, name) VALUES (3, 'artist3');" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(1,'album1',1);" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(2,'album2',1);" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(3,'album3',2);" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(4,'album4',NULL);" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(5,'album4',3);" ); m_storage->query( "INSERT INTO composers(id, name) VALUES (1, 'composer1');" ); m_storage->query( "INSERT INTO composers(id, name) VALUES (2, 'composer2');" ); m_storage->query( "INSERT INTO composers(id, name) VALUES (3, 'composer3');" ); m_storage->query( "INSERT INTO genres(id, name) VALUES (1, 'genre1');" ); m_storage->query( "INSERT INTO genres(id, name) VALUES (2, 'genre2');" ); m_storage->query( "INSERT INTO genres(id, name) VALUES (3, 'genre3');" ); m_storage->query( "INSERT INTO years(id, name) VALUES (1, '1');" ); m_storage->query( "INSERT INTO years(id, name) VALUES (2, '2');" ); m_storage->query( "INSERT INTO years(id, name) VALUES (3, '3');" ); m_storage->query( "INSERT INTO directories(id, deviceid, dir) VALUES (1, -1, './');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES (1, -1, './IDoNotExist.mp3', 1, '1');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES (2, -1, './IDoNotExistAsWell.mp3', 1, '2');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES (3, -1, './MeNeither.mp3', 1, '3');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES (4, 2, './NothingHere.mp3', 1, '4');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES (5, 1, './GuessWhat.mp3', 1, '5');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES (6, 2, './LookItsA.flac', 1, '6');" ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(1,1,'track1','comment1',1,1,1,1,1);" ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(2,2,'track2','comment2',1,2,1,1,1);" ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(3,3,'track3','comment3',3,4,1,1,1);" ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(4,4,'track4','comment4',2,3,3,3,3);" ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(5,5,'track5','',3,5,2,2,2);" ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(6,6,'track6','',1,4,2,2,2);" ); m_storage->query( "INSERT INTO statistics(url,createdate,accessdate,score,rating,playcount) " "VALUES(1,1000,10000, 50.0,2,100);" ); m_storage->query( "INSERT INTO statistics(url,createdate,accessdate,score,rating,playcount) " "VALUES(2,2000,30000, 70.0,9,50);" ); m_storage->query( "INSERT INTO statistics(url,createdate,accessdate,score,rating,playcount) " "VALUES(3,4000,20000, 60.0,4,10);" ); m_storage->query( "INSERT INTO labels(id,label) VALUES (1,'labelA'), (2,'labelB'),(3,'test');" ); m_storage->query( "INSERT INTO urls_labels(url,label) VALUES (1,1),(1,2),(2,2),(3,3),(4,3),(4,2);" ); } void TestSqlQueryMaker::cleanupTestCase() { delete m_collection; //m_storage is deleted by SqlCollection delete m_tmpDir; } void TestSqlQueryMaker::cleanup() { m_collection->setMountPointManager( m_mpm ); } void TestSqlQueryMaker::testQueryAlbums() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setAlbumQueryMode( Collections::QueryMaker::AllAlbums ); qm.setQueryType( Collections::QueryMaker::Album ); qm.run(); QCOMPARE( qm.albums().count(), 5 ); } void TestSqlQueryMaker::testQueryArtists() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Artist ); qm.run(); QCOMPARE( qm.artists().count(), 3 ); } void TestSqlQueryMaker::testQueryComposers() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Composer ); qm.run(); QCOMPARE( qm.composers().count(), 3 ); } void TestSqlQueryMaker::testQueryGenres() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Genre ); qm.run(); QCOMPARE( qm.genres().count(), 3 ); } void TestSqlQueryMaker::testQueryYears() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Year ); qm.run(); QCOMPARE( qm.years().count(), 3 ); } void TestSqlQueryMaker::testQueryTracks() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Track ); qm.run(); QCOMPARE( qm.tracks().count(), 6 ); } void TestSqlQueryMaker::testAlbumQueryMode() { { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setAlbumQueryMode( Collections::QueryMaker::OnlyCompilations ); qm.setQueryType( Collections::QueryMaker::Album ); qm.run(); QCOMPARE( qm.albums().count(), 1 ); } { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setAlbumQueryMode( Collections::QueryMaker::OnlyNormalAlbums ); qm.setQueryType( Collections::QueryMaker::Album ); qm.run(); QCOMPARE( qm.albums().count(), 4 ); } { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Track ); qm.setAlbumQueryMode( Collections::QueryMaker::OnlyCompilations ); qm.run(); QCOMPARE( qm.tracks().count(), 2 ); } { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Track ); qm.setAlbumQueryMode( Collections::QueryMaker::OnlyNormalAlbums ); qm.run(); QCOMPARE( qm.tracks().count(), 4 ); } { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Artist ); qm.setAlbumQueryMode( Collections::QueryMaker::OnlyCompilations ); qm.run(); QCOMPARE( qm.artists().count() , 2 ); } { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Artist ); qm.setAlbumQueryMode( Collections::QueryMaker::OnlyNormalAlbums ); qm.run(); QCOMPARE( qm.artists().count(), 3 ); } { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setAlbumQueryMode( Collections::QueryMaker::OnlyCompilations ); qm.setQueryType( Collections::QueryMaker::Genre ); qm.run(); QCOMPARE( qm.genres().count(), 2 ); } { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setAlbumQueryMode( Collections::QueryMaker::OnlyNormalAlbums ); qm.setQueryType( Collections::QueryMaker::Genre ); qm.run(); QCOMPARE( qm.genres().count(), 3 ); } } void TestSqlQueryMaker::testDeleteQueryMakerWithRunningQuery() { int iteration = 0; bool queryNotDoneYet = true; //wait one second per query in total, that should be enough for it to complete do { Collections::SqlQueryMaker *qm = new Collections::SqlQueryMaker( m_collection ); QSignalSpy spy( qm, &Collections::QueryMaker::queryDone ); qm->setQueryType( Collections::QueryMaker::Track ); qm->addFilter( Meta::valTitle, QString::number( iteration), false, false ); qm->run(); //wait 10 msec more per iteration, might have to be tweaked if( iteration > 0 ) { QTest::qWait( 10 * iteration ); } delete qm; queryNotDoneYet = ( spy.count() == 0 ); if( iteration > 50 ) { break; } iteration++; } while ( queryNotDoneYet ); qDebug() << "Iterations: " << iteration; } void TestSqlQueryMaker::testAsyncAlbumQuery() { Collections::QueryMaker *qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Album ); QSignalSpy doneSpy1( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy1( qm, &Collections::QueryMaker::newAlbumsReady ); qm->run(); doneSpy1.wait( 1000 ); QCOMPARE( resultSpy1.count(), 1 ); QList args1 = resultSpy1.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value().count(), 5 ); QCOMPARE( doneSpy1.count(), 1); delete qm; qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Album ); QSignalSpy doneSpy2( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy2( qm, &Collections::QueryMaker::newAlbumsReady ); qm->addFilter( Meta::valAlbum, "foo" ); //should result in no match qm->run(); doneSpy2.wait( 1000 ); QCOMPARE( resultSpy2.count(), 1 ); QList args2 = resultSpy2.takeFirst(); QVERIFY( args2.value(0).canConvert() ); QCOMPARE( args2.value(0).value().count(), 0 ); QCOMPARE( doneSpy2.count(), 1); } void TestSqlQueryMaker::testAsyncArtistQuery() { Collections::QueryMaker *qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Artist ); QSignalSpy doneSpy1( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy1( qm, &Collections::QueryMaker::newArtistsReady ); qm->run(); doneSpy1.wait( 1000 ); QCOMPARE( resultSpy1.count(), 1 ); QList args1 = resultSpy1.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value().count(), 3 ); QCOMPARE( doneSpy1.count(), 1); delete qm; qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Artist ); QSignalSpy doneSpy2( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy2( qm, &Collections::QueryMaker::newArtistsReady ); qm->addFilter( Meta::valArtist, "foo" ); //should result in no match qm->run(); doneSpy2.wait( 1000 ); QCOMPARE( resultSpy2.count(), 1 ); QList args2 = resultSpy2.takeFirst(); QVERIFY( args2.value(0).canConvert() ); QCOMPARE( args2.value(0).value().count(), 0 ); QCOMPARE( doneSpy2.count(), 1); } void TestSqlQueryMaker::testAsyncComposerQuery() { Collections::QueryMaker *qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Composer ); QSignalSpy doneSpy1( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy1( qm, &Collections::QueryMaker::newComposersReady ); qm->run(); doneSpy1.wait( 1000 ); QCOMPARE( resultSpy1.count(), 1 ); QList args1 = resultSpy1.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value().count(), 3 ); QCOMPARE( doneSpy1.count(), 1); delete qm; qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Composer ); QSignalSpy doneSpy2( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy2( qm, &Collections::QueryMaker::newComposersReady ); qm->addFilter( Meta::valComposer, "foo" ); //should result in no match qm->run(); doneSpy2.wait( 1000 ); QCOMPARE( resultSpy2.count(), 1 ); QList args2 = resultSpy2.takeFirst(); QVERIFY( args2.value(0).canConvert() ); QCOMPARE( args2.value(0).value().count(), 0 ); QCOMPARE( doneSpy2.count(), 1); } void TestSqlQueryMaker::testAsyncTrackQuery() { Collections::QueryMaker *qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Track ); QSignalSpy doneSpy1( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy1( qm, &Collections::QueryMaker::newTracksReady ); qm->run(); doneSpy1.wait( 1000 ); QCOMPARE( resultSpy1.count(), 1 ); QList args1 = resultSpy1.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value().count(), 6 ); QCOMPARE( doneSpy1.count(), 1); delete qm; qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Track ); QSignalSpy doneSpy2( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy2( qm, &Collections::QueryMaker::newTracksReady ); qm->addFilter( Meta::valTitle, "foo" ); //should result in no match qm->run(); doneSpy2.wait( 1000 ); QCOMPARE( resultSpy2.count(), 1 ); QList args2 = resultSpy2.takeFirst(); QVERIFY( args2.value(0).canConvert() ); QCOMPARE( args2.value(0).value().count(), 0 ); QCOMPARE( doneSpy2.count(), 1); } void TestSqlQueryMaker::testAsyncGenreQuery() { Collections::QueryMaker *qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Genre ); QSignalSpy doneSpy1( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy1( qm, &Collections::QueryMaker::newGenresReady ); qm->run(); doneSpy1.wait( 1000 ); QCOMPARE( resultSpy1.count(), 1 ); QList args1 = resultSpy1.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value().count(), 3 ); QCOMPARE( doneSpy1.count(), 1); delete qm; qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Genre ); QSignalSpy doneSpy2( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy2( qm, &Collections::QueryMaker::newGenresReady ); qm->addFilter( Meta::valGenre, "foo" ); //should result in no match qm->run(); doneSpy2.wait( 1000 ); QCOMPARE( resultSpy2.count(), 1 ); QList args2 = resultSpy2.takeFirst(); QVERIFY( args2.value(0).canConvert() ); QCOMPARE( args2.value(0).value().count(), 0 ); QCOMPARE( doneSpy2.count(), 1); } void TestSqlQueryMaker::testAsyncYearQuery() { Collections::QueryMaker *qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Year ); QSignalSpy doneSpy1( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy1( qm, &Collections::QueryMaker::newYearsReady ); qm->run(); doneSpy1.wait( 1000 ); QCOMPARE( resultSpy1.count(), 1 ); QList args1 = resultSpy1.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value().count(), 3 ); QCOMPARE( doneSpy1.count(), 1); delete qm; qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Year ); QSignalSpy doneSpy2( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy2( qm, &Collections::QueryMaker::newYearsReady ); qm->addFilter( Meta::valYear, "foo" ); //should result in no match qm->run(); doneSpy2.wait( 1000 ); QCOMPARE( resultSpy2.count(), 1 ); QList args2 = resultSpy2.takeFirst(); QVERIFY( args2.value(0).canConvert() ); QCOMPARE( args2.value(0).value().count(), 0 ); QCOMPARE( doneSpy2.count(), 1); } void TestSqlQueryMaker::testAsyncCustomQuery() { Collections::QueryMaker *qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Custom ); qm->addReturnFunction( Collections::QueryMaker::Count, Meta::valTitle ); QSignalSpy doneSpy1( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy1( qm, &Collections::QueryMaker::newResultReady ); qm->run(); doneSpy1.wait( 1000 ); QCOMPARE( resultSpy1.count(), 1 ); QList args1 = resultSpy1.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value().count(), 1 ); QCOMPARE( args1.value(0).value().first(), QString( "6" ) ); QCOMPARE( doneSpy1.count(), 1); delete qm; qm = new Collections::SqlQueryMaker( m_collection ); qm->setQueryType( Collections::QueryMaker::Custom ); qm->addReturnFunction( Collections::QueryMaker::Count, Meta::valTitle ); QSignalSpy doneSpy2( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy2( qm, &Collections::QueryMaker::newResultReady ); qm->addFilter( Meta::valTitle, "foo" ); //should result in no match qm->run(); doneSpy2.wait( 1000 ); QCOMPARE( resultSpy2.count(), 1 ); QList args2 = resultSpy2.takeFirst(); QVERIFY( args2.value(0).canConvert() ); QCOMPARE( args2.value(0).value().count(), 1 ); QCOMPARE( args2.value(0).value().first(), QString( "0" ) ); QCOMPARE( doneSpy2.count(), 1); } void TestSqlQueryMaker::testFilter_data() { QTest::addColumn( "type" ); QTest::addColumn( "value" ); QTest::addColumn( "filter" ); QTest::addColumn( "matchBeginning" ); QTest::addColumn( "matchEnd" ); QTest::addColumn( "count" ); QTest::newRow( "track match all titles" ) << Collections::QueryMaker::Track << Meta::valTitle << "track" << false << false << 6; QTest::newRow( "track match all title beginnings" ) << Collections::QueryMaker::Track << Meta::valTitle << "track" << true << false << 6; QTest::newRow( "track match one title beginning" ) << Collections::QueryMaker::Track << Meta::valTitle << "track1" << true << false << 1; QTest::newRow( "track match one title end" ) << Collections::QueryMaker::Track << Meta::valTitle << "rack2" << false << true << 1; QTest::newRow( "track match title on both ends" ) << Collections::QueryMaker::Track << Meta::valTitle << "track3" << true << true << 1; QTest::newRow( "track match artist" ) << Collections::QueryMaker::Track << Meta::valArtist << "artist1" << false << false << 3; QTest::newRow( "artist match artist" ) << Collections::QueryMaker::Artist << Meta::valArtist << "artist1" << true << true << 1; QTest::newRow( "album match artist" ) << Collections::QueryMaker::Album << Meta::valArtist << "artist3" << false << false << 2; QTest::newRow( "track match genre" ) << Collections::QueryMaker::Track << Meta::valGenre << "genre1" << false << false << 3; QTest::newRow( "genre match genre" ) << Collections::QueryMaker::Genre << Meta::valGenre << "genre1" << false << false << 1; QTest::newRow( "track match composer" ) << Collections::QueryMaker::Track << Meta::valComposer << "composer2" << false << false << 2; QTest::newRow( "composer match composer" ) << Collections::QueryMaker::Composer << Meta::valComposer << "composer2" << false << false << 1; QTest::newRow( "track match year" ) << Collections::QueryMaker::Track << Meta::valYear << "2" << true << true << 2; QTest::newRow( "year match year" ) << Collections::QueryMaker::Year << Meta::valYear << "1" << false << false << 1; QTest::newRow( "album match album" ) << Collections::QueryMaker::Album << Meta::valAlbum << "album1" << false << false << 1; QTest::newRow( "track match album" ) << Collections::QueryMaker::Track << Meta::valAlbum << "album1" << false << false << 1; QTest::newRow( "track match albumartit" ) << Collections::QueryMaker::Track << Meta::valAlbumArtist << "artist1" << false << false << 2; QTest::newRow( "album match albumartist" ) << Collections::QueryMaker::Album << Meta::valAlbumArtist << "artist2" << false << false << 1; QTest::newRow( "album match all albumartists" ) << Collections::QueryMaker::Album << Meta::valAlbumArtist << "artist" << true << false << 4; QTest::newRow( "genre match albumartist" ) << Collections::QueryMaker::Genre << Meta::valAlbumArtist << "artist1" << false << false << 1; QTest::newRow( "year match albumartist" ) << Collections::QueryMaker::Year << Meta::valAlbumArtist << "artist1" << false << false << 1; QTest::newRow( "composer match albumartist" ) << Collections::QueryMaker::Composer << Meta::valAlbumArtist << "artist1" << false << false << 1; QTest::newRow( "genre match title" ) << Collections::QueryMaker::Genre << Meta::valTitle << "track1" << false << false << 1; QTest::newRow( "composer match title" ) << Collections::QueryMaker::Composer << Meta::valTitle << "track1" << false << false << 1; QTest::newRow( "year match title" ) << Collections::QueryMaker::Year << Meta::valTitle << "track1" << false << false << 1; QTest::newRow( "album match title" ) << Collections::QueryMaker::Album << Meta::valTitle << "track1" << false << false << 1; QTest::newRow( "artist match title" ) << Collections::QueryMaker::Artist << Meta::valTitle << "track1" << false << false << 1; QTest::newRow( "track match comment" ) << Collections::QueryMaker::Track << Meta::valComment << "comment" << true << false << 4; QTest::newRow( "track match url" ) << Collections::QueryMaker::Track << Meta::valUrl << "Exist" << false << false << 2; QTest::newRow( "album match comment" ) << Collections::QueryMaker::Track << Meta::valComment << "comment1" << true << true << 1; } void TestSqlQueryMaker::checkResultCount( Collections::SqlQueryMaker* qm, Collections::QueryMaker::QueryType type, int count ) { switch( type ) { case QueryMaker::Track: QCOMPARE( qm->tracks().count(), count ); break; case QueryMaker::Artist: QCOMPARE( qm->artists().count(), count ); break; case QueryMaker::Album: QCOMPARE( qm->albums().count(), count ); break; case QueryMaker::Genre: QCOMPARE( qm->genres().count(), count ); break; case QueryMaker::Composer: QCOMPARE( qm->composers().count(), count ); break; case QueryMaker::Year: QCOMPARE( qm->years().count(), count ); break; case QueryMaker::Label: QCOMPARE( qm->labels().count(), count ); break; default: ; // do nothing } } void TestSqlQueryMaker::testFilter() { QFETCH( Collections::QueryMaker::QueryType, type ); QFETCH( qint64, value ); QFETCH( QString, filter ); QFETCH( bool, matchBeginning ); QFETCH( bool, matchEnd ); QFETCH( int, count ); Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( type ); qm.addFilter( value, filter, matchBeginning, matchEnd ); qm.run(); checkResultCount( &qm, type, count ); } void TestSqlQueryMaker::testDynamicCollection() { //this will not crash as we reset the correct mock in cleanup() SqlMountPointManagerMock mpm( this, m_storage ); QMap mountPoints; mpm.m_mountPoints = mountPoints; m_collection->setMountPointManager( &mpm ); Collections::SqlQueryMaker trackQm( m_collection ); trackQm.setQueryType( Collections::QueryMaker::Track ); trackQm.setBlocking( true ); trackQm.run(); QCOMPARE( trackQm.tracks().count(), 3 ); mpm.m_mountPoints.insert( 1, "/foo" ); Collections::SqlQueryMaker trackQm2( m_collection ); trackQm2.setQueryType( Collections::QueryMaker::Track ); trackQm2.setBlocking( true ); trackQm2.run(); QCOMPARE( trackQm2.tracks().count(), 4 ); Collections::SqlQueryMaker artistQm( m_collection ); artistQm.setQueryType( Collections::QueryMaker::Artist ); artistQm.setBlocking( true ); artistQm.run(); QCOMPARE( artistQm.artists().count(), 2 ); Collections::SqlQueryMaker albumQm( m_collection ); albumQm.setQueryType( Collections::QueryMaker::Album ); albumQm.setBlocking( true ); albumQm.run(); QCOMPARE( albumQm.albums().count(), 4 ); Collections::SqlQueryMaker genreQm( m_collection ); genreQm.setQueryType( Collections::QueryMaker::Genre ); genreQm.setBlocking( true ); genreQm.run(); QCOMPARE( genreQm.genres().count(), 2 ); Collections::SqlQueryMaker composerQm( m_collection ); composerQm.setQueryType( Collections::QueryMaker::Composer ); composerQm.setBlocking( true ); composerQm.run(); QCOMPARE( composerQm.composers().count(), 2 ); Collections::SqlQueryMaker yearQm( m_collection ); yearQm.setQueryType( Collections::QueryMaker::Year ); yearQm.setBlocking( true ); yearQm.run(); QCOMPARE( yearQm.years().count(), 2 ); } void TestSqlQueryMaker::testSpecialCharacters_data() { QTest::addColumn( "filter" ); QTest::addColumn( "like" ); QTest::newRow( "slash in filter w/o like" ) << "AC/DC" << false; QTest::newRow( "slash in filter w/ like" ) << "AC/DC" << true; QTest::newRow( "backslash in filter w/o like" ) << "AC\\DC" << false; QTest::newRow( "backslash in filter w like" ) << "AC\\DC" << true; QTest::newRow( "quote in filter w/o like" ) << "Foo'Bar" << false; QTest::newRow( "quote in filter w like" ) << "Foo'Bar" << true; QTest::newRow( "% in filter w/o like" ) << "Foo%Bar" << false; QTest::newRow( "% in filter w/ like" ) << "Foo%Bar" << true; QTest::newRow( "filter ending with % w/o like" ) << "Foo%" << false; QTest::newRow( "filter ending with % w like" ) << "Foo%" << true; QTest::newRow( "filter beginning with % w/o like" ) << "%Foo" << false; QTest::newRow( "filter beginning with % w/o like" ) << "%Foo" << true; QTest::newRow( "\" in filter w/o like" ) << "Foo\"Bar" << false; QTest::newRow( "\" in filter w like" ) << "Foo\"Bar" << true; QTest::newRow( "_ in filter w/o like" ) << "track_" << false; QTest::newRow( "_ in filter w/ like" ) << "track_" << true; QTest::newRow( "filter with two consecutive backslashes w/o like" ) << "Foo\\\\Bar" << false; QTest::newRow( "filter with two consecutive backslashes w like" ) << "Foo\\\\Bar" << true; QTest::newRow( "filter with backslash% w/o like" ) << "FooBar\\%" << false; QTest::newRow( "filter with backslash% w like" ) << "FooBar\\%" << true; } void TestSqlQueryMaker::testSpecialCharacters() { QFETCH( QString, filter ); QFETCH( bool, like ); QString insertTrack = QString( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(999,999,'%1','',1,1,1,1,1);").arg( m_storage->escape( filter ) ); //there is a unique index on TRACKS.URL m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES(999, -1, './foobar.mp3', 1, '999');"); m_storage->query( insertTrack ); QCOMPARE( m_storage->query( "select count(*) from urls where id = 999" ).first(), QString("1") ); QCOMPARE( m_storage->query( "select count(*) from tracks where id = 999" ).first(), QString("1") ); Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Track ); qm.addFilter( Meta::valTitle, filter, !like, !like ); qm.run(); m_storage->query( "DELETE FROM urls WHERE id = 999;" ); m_storage->query( "DELETE FROM tracks WHERE id = 999;" ); QCOMPARE( qm.tracks().count(), 1 ); } void TestSqlQueryMaker::testNumberFilter_data() { QTest::addColumn( "type" ); QTest::addColumn( "value" ); QTest::addColumn( "filter" ); QTest::addColumn( "comparison" ); QTest::addColumn( "exclude" ); QTest::addColumn( "count" ); QTest::newRow( "include rating greater 4" ) << Collections::QueryMaker::Track << Meta::valRating << 4 << Collections::QueryMaker::GreaterThan << false << 1; QTest::newRow( "exclude rating smaller 4" ) << Collections::QueryMaker::Album << Meta::valRating << 4 << Collections::QueryMaker::LessThan << true << 4; QTest::newRow( "exclude tracks first played later than 2000" ) << Collections::QueryMaker::Track << Meta::valFirstPlayed << 2000 << Collections::QueryMaker::GreaterThan << true << 5; //having never been played does not mean played before 20000 QTest::newRow( "include last played before 20000" ) << Collections::QueryMaker::Track << Meta::valLastPlayed << 20000 << Collections::QueryMaker::LessThan << false << 1; QTest::newRow( "playcount equals 100" ) << Collections::QueryMaker::Album << Meta::valPlaycount << 100 << Collections::QueryMaker::Equals << false << 1; //should include unplayed songs QTest::newRow( "playcount != 50" ) << Collections::QueryMaker::Track << Meta::valPlaycount << 50 << Collections::QueryMaker::Equals << true << 5; QTest::newRow( "score greater 60" ) << Collections::QueryMaker::Genre << Meta::valScore << 60 << Collections::QueryMaker::GreaterThan << false << 1; } void TestSqlQueryMaker::testNumberFilter() { QFETCH( Collections::QueryMaker::QueryType, type ); QFETCH( qint64, value ); QFETCH( int, filter ); QFETCH( bool, exclude ); QFETCH( Collections::QueryMaker::NumberComparison, comparison ); QFETCH( int, count ); Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( type ); if( exclude ) qm.excludeNumberFilter( value, filter, comparison ); else qm.addNumberFilter( value, filter, comparison ); qm.run(); checkResultCount( &qm, type, count ); } void TestSqlQueryMaker::testReturnFunctions_data() { QTest::addColumn( "function" ); QTest::addColumn( "value" ); QTest::addColumn( "result" ); QTest::newRow( "count tracks" ) << Collections::QueryMaker::Count << Meta::valTitle << QString( "6" ); QTest::newRow( "sum of playcount" ) << Collections::QueryMaker::Sum << Meta::valPlaycount << QString( "160" ); QTest::newRow( "min score" ) << Collections::QueryMaker::Min << Meta::valScore << QString( "50" ); QTest::newRow( "max rating" ) << Collections::QueryMaker::Max << Meta::valRating << QString( "9" ); } void TestSqlQueryMaker::testReturnFunctions() { QFETCH( Collections::QueryMaker::ReturnFunction, function ); QFETCH( qint64, value ); QFETCH( QString, result ); Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Custom ); qm.addReturnFunction( function, value ); qm.run(); QCOMPARE( qm.customData().first(), result ); } void TestSqlQueryMaker::testLabelMatch() { Meta::LabelPtr label = m_collection->registry()->getLabel( "labelB" ); Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( QueryMaker::Track ); qm.addMatch( label ); qm.run(); QCOMPARE( qm.tracks().count(), 3 ); } void TestSqlQueryMaker::testMultipleLabelMatches() { Meta::LabelPtr labelB = m_collection->registry()->getLabel( "labelB" ); Meta::LabelPtr labelA = m_collection->registry()->getLabel( "labelA" ); Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( QueryMaker::Track ); qm.addMatch( labelB ); qm.addMatch( labelA ); qm.run(); QCOMPARE( qm.tracks().count(), 1 ); } void TestSqlQueryMaker::testQueryTypesWithLabelMatching_data() { QTest::addColumn( "type" ); QTest::addColumn( "result" ); QTest::newRow( "query tracks" ) << Collections::QueryMaker::Track << 1; QTest::newRow( "query albums" ) << Collections::QueryMaker::Album << 1; QTest::newRow( "query artists" ) << Collections::QueryMaker::Artist << 1; QTest::newRow( "query genre" ) << Collections::QueryMaker::Genre << 1; QTest::newRow( "query composers" ) << Collections::QueryMaker::Composer << 1; QTest::newRow( "query years" ) << Collections::QueryMaker::Year << 1; QTest::newRow( "query labels" ) << Collections::QueryMaker::Label << 2; } void TestSqlQueryMaker::testQueryTypesWithLabelMatching() { QFETCH( Collections::QueryMaker::QueryType, type ); QFETCH( int, result ); Meta::LabelPtr labelB = m_collection->registry()->getLabel( "labelB" ); Meta::LabelPtr labelA = m_collection->registry()->getLabel( "labelA" ); Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( type ); qm.addMatch( labelB ); qm.addMatch( labelA ); qm.run(); checkResultCount( &qm, type, result ); } void TestSqlQueryMaker::testFilterOnLabelsAndCombination() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Track ); qm.beginAnd(); qm.addFilter( Meta::valLabel, "labelB", true, true ); qm.addFilter( Meta::valLabel, "labelA", false, false ); qm.endAndOr(); qm.run(); QCOMPARE( qm.tracks().count(), 1 ); } void TestSqlQueryMaker::testFilterOnLabelsOrCombination() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Track ); qm.beginOr(); qm.addFilter( Meta::valLabel, "labelB", true, true ); qm.addFilter( Meta::valLabel, "labelA", false, false ); qm.endAndOr(); qm.run(); QCOMPARE( qm.tracks().count(), 3 ); } void TestSqlQueryMaker::testFilterOnLabelsNegationAndCombination() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Track ); qm.beginAnd(); qm.excludeFilter( Meta::valLabel, "labelB", true, true ); qm.excludeFilter( Meta::valLabel, "labelA", false, false ); qm.endAndOr(); qm.run(); QCOMPARE( qm.tracks().count(), 3 ); } void TestSqlQueryMaker::testFilterOnLabelsNegationOrCombination() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Track ); qm.beginOr(); qm.excludeFilter( Meta::valLabel, "labelB", true, true ); qm.excludeFilter( Meta::valLabel, "labelA", false, false ); qm.endAndOr(); qm.run(); QCOMPARE( qm.tracks().count(), 5 ); } void TestSqlQueryMaker::testComplexLabelsFilter() { Collections::SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( Collections::QueryMaker::Track ); qm.beginOr(); qm.addFilter( Meta::valLabel, "test", true, true ); qm.beginAnd(); qm.addFilter( Meta::valLabel, "labelB", false, false ); qm.excludeFilter( Meta::valLabel, "labelA", false, true ); qm.endAndOr(); qm.endAndOr(); qm.run(); QCOMPARE( qm.tracks().count(), 3 ); } void TestSqlQueryMaker::testLabelQueryMode_data() { QTest::addColumn( "type" ); QTest::addColumn( "labelMode" ); QTest::addColumn( "albumMode" ); QTest::addColumn( "result" ); QTest::newRow( "labels with querymode WithoutLabels" ) << QueryMaker::Label << QueryMaker::OnlyWithoutLabels << QueryMaker::AllAlbums << 0; QTest::newRow( "tracks with labels" ) << QueryMaker::Track << QueryMaker::OnlyWithLabels << QueryMaker::AllAlbums << 4; QTest::newRow( "Compilations with labels" ) << QueryMaker::Album << QueryMaker::OnlyWithLabels << QueryMaker::OnlyCompilations << 1; QTest::newRow( "Compilations without labels" ) << QueryMaker::Album << QueryMaker::OnlyWithoutLabels << QueryMaker::OnlyCompilations << 1; } void TestSqlQueryMaker::testLabelQueryMode() { QFETCH( QueryMaker::QueryType, type ); QFETCH( QueryMaker::LabelQueryMode, labelMode ); QFETCH( QueryMaker::AlbumQueryMode, albumMode ); QFETCH( int, result ); SqlQueryMaker qm( m_collection ); qm.setBlocking( true ); qm.setQueryType( type ); qm.setAlbumQueryMode( albumMode ); qm.setLabelQueryMode( labelMode ); qm.run(); checkResultCount( &qm, type, result ); } diff --git a/tests/core-impl/collections/db/sql/TestSqlScanManager.cpp b/tests/core-impl/collections/db/sql/TestSqlScanManager.cpp index 299625183b..884c2538b4 100644 --- a/tests/core-impl/collections/db/sql/TestSqlScanManager.cpp +++ b/tests/core-impl/collections/db/sql/TestSqlScanManager.cpp @@ -1,1635 +1,1635 @@ /**************************************************************************************** * Copyright (c) 2009 Maximilian Kossick * * Copyright (c) 2010 Ralf Engels * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestSqlScanManager.h" #include "amarokconfig.h" #include "MetaTagLib.h" #include "scanner/GenericScanManager.h" #include "core-impl/collections/db/sql/SqlCollection.h" #include "core-impl/collections/db/sql/SqlQueryMaker.h" #include "core-impl/collections/db/sql/SqlRegistry.h" #include "core-impl/storage/sql/mysqlestorage/MySqlEmbeddedStorage.h" #include "config-amarok-test.h" #include "SqlMountPointManagerMock.h" #include #include #include #include #include #include -QTEST_MAIN( TestSqlScanManager ) +QTEST_GUILESS_MAIN( TestSqlScanManager ) TestSqlScanManager::TestSqlScanManager() : QObject() { QString help = i18n("Amarok"); // prevent a bug when the scanner is the first thread creating a translator } void TestSqlScanManager::initTestCase() { AmarokConfig::instance("amarokrc"); m_autoGetCoverArt = AmarokConfig::autoGetCoverArt(); AmarokConfig::setAutoGetCoverArt( false ); // setenv( "LC_ALL", "", 1 ); // this breakes the test // Amarok does not force LC_ALL=C but obviously the test does it which // will prevent scanning of files with umlauts. //Tell GenericScanManager that we want to use the recently built scanner, not an installed version. const QString overridePath = QString( AMAROK_OVERRIDE_UTILITIES_PATH ); qApp->setProperty( "overrideUtilitiesPath", overridePath ); // that is the original mp3 file that we use to generate the "real" tracks m_sourcePath = QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + "/data/audio/Platz 01.mp3" ); QVERIFY( QFile::exists( m_sourcePath ) ); m_tmpDatabaseDir = new QTemporaryDir(); QVERIFY( m_tmpDatabaseDir->isValid() ); m_storage = QSharedPointer( new MySqlEmbeddedStorage() ); QVERIFY( m_storage->init( m_tmpDatabaseDir->path() ) ); m_collection = new Collections::SqlCollection( m_storage ); connect( m_collection, &Collections::SqlCollection::updated, this, &TestSqlScanManager::slotCollectionUpdated ); // TODO: change the mock mount point manager so that it doesn't pull // in all the devices. Not much of a mock like this. SqlMountPointManagerMock *mock = new SqlMountPointManagerMock( this, m_storage ); m_collection->setMountPointManager( mock ); m_scanManager = m_collection->scanManager(); AmarokConfig::setScanRecursively( true ); AmarokConfig::setMonitorChanges( false ); // switch on writing back so that we can create the test files with all the information AmarokConfig::setWriteBack( true ); AmarokConfig::setWriteBackStatistics( true ); AmarokConfig::setWriteBackCover( true ); // I just need the table and not the whole playlist manager /* m_storage->query( QString( "CREATE TABLE playlist_tracks (" " id " + m_storage->idType() + ", playlist_id INTEGER " ", track_num INTEGER " ", url " + m_storage->exactTextColumnType() + ", title " + m_storage->textColumnType() + ", album " + m_storage->textColumnType() + ", artist " + m_storage->textColumnType() + ", length INTEGER " ", uniqueid " + m_storage->textColumnType(128) + ") ENGINE = MyISAM;" ) ); */ } void TestSqlScanManager::cleanupTestCase() { // aborts a ThreadWeaver job that would otherwise cause next statement to stall delete m_collection; // we cannot simply call WeaverInterface::finish(), it stops event loop // QSignalSpy spy( ThreadWeaver::Queue::instance(), &ThreadWeaver::Queue::finished ); // if( !ThreadWeaver::Queue::instance()->isIdle() ) // QVERIFY2( spy.wait( 5000 ), "threads did not finish in timeout" ); delete m_tmpDatabaseDir; AmarokConfig::setAutoGetCoverArt( m_autoGetCoverArt ); } void TestSqlScanManager::init() { m_tmpCollectionDir = new QTemporaryDir(); QVERIFY( m_tmpCollectionDir->isValid() ); QStringList collectionFolders; collectionFolders << m_tmpCollectionDir->path(); m_collection->mountPointManager()->setCollectionFolders( collectionFolders ); } void TestSqlScanManager::cleanup() { m_scanManager->abort(); m_storage->query( "BEGIN" ); m_storage->query( "TRUNCATE TABLE tracks;" ); m_storage->query( "TRUNCATE TABLE albums;" ); m_storage->query( "TRUNCATE TABLE artists;" ); m_storage->query( "TRUNCATE TABLE composers;" ); m_storage->query( "TRUNCATE TABLE genres;" ); m_storage->query( "TRUNCATE TABLE years;" ); m_storage->query( "TRUNCATE TABLE urls;" ); m_storage->query( "TRUNCATE TABLE statistics;" ); m_storage->query( "TRUNCATE TABLE directories;" ); m_storage->query( "COMMIT" ); m_collection->registry()->emptyCache(); delete m_tmpCollectionDir; } void TestSqlScanManager::testScanSingle() { m_collectionUpdatedCount = 0; createSingleTrack(); fullScanAndWait(); QVERIFY( m_collectionUpdatedCount > 0 ); // -- check the commit Meta::TrackPtr track = m_collection->registry()->getTrack( 1 ); QVERIFY( track ); QCOMPARE( track->name(), QString("Theme From Armageddon") ); QVERIFY( track->artist() ); QCOMPARE( track->artist()->name(), QString("Soundtrack & Theme Orchestra") ); QVERIFY( track->album() ); QCOMPARE( track->album()->name(), QString("Big Screen Adventures") ); QVERIFY( track->album()->albumArtist() ); QCOMPARE( track->album()->albumArtist()->name(), QString("Theme Orchestra") ); QVERIFY( !track->album()->isCompilation() ); // One single track is not compilation QCOMPARE( track->composer()->name(), QString("Unknown Composer") ); QCOMPARE( track->comment(), QString("Amazon.com Song ID: 210541237") ); QCOMPARE( track->year()->year(), 2009 ); QCOMPARE( track->type(), QString("mp3") ); QCOMPARE( track->trackNumber(), 28 ); QCOMPARE( track->bitrate(), 257 ); // TagLib reports 257 kbit/s QCOMPARE( track->length(), qint64(12000) ); QCOMPARE( track->sampleRate(), 44100 ); QCOMPARE( track->filesize(), 389679 ); QDateTime aDate = QDateTime::currentDateTime(); QVERIFY( track->createDate().secsTo( aDate ) < 5 ); // I just imported the file QVERIFY( track->createDate().secsTo( aDate ) >= 0 ); QVERIFY( track->modifyDate().secsTo( aDate ) < 5 ); // I just wrote the file QVERIFY( track->modifyDate().secsTo( aDate ) >= 0 ); Meta::StatisticsPtr statistics = track->statistics(); qFuzzyCompare( statistics->score(), 0.875 ); QCOMPARE( statistics->playCount(), 5 ); QVERIFY( !statistics->firstPlayed().isValid() ); QVERIFY( !statistics->lastPlayed().isValid() ); QVERIFY( track->createDate().isValid() ); // -- check that a further scan doesn't change anything m_collectionUpdatedCount = 0; fullScanAndWait(); QCOMPARE( m_collectionUpdatedCount, 0 ); } void TestSqlScanManager::testScanDirectory() { createAlbum(); fullScanAndWait(); // -- check the commit Meta::AlbumPtr album; album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QCOMPARE( album->name(), QString("Thriller") ); QCOMPARE( album->tracks().count(), 9 ); QVERIFY( !album->isCompilation() ); QVERIFY( !album->hasImage() ); } void TestSqlScanManager::testDuplicateUid() { Meta::FieldHash values; // create two tracks with same uid values.clear(); values.insert( Meta::valUniqueId, QVariant("c6c29f50279ab9523a0f44928bc1e96b") ); values.insert( Meta::valUrl, QVariant("track1.mp3") ); values.insert( Meta::valTitle, QVariant("Track 1") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("c6c29f50279ab9523a0f44928bc1e96b") ); values.insert( Meta::valUrl, QVariant("track2.mp3") ); values.insert( Meta::valTitle, QVariant("Track 2") ); createTrack( values ); fullScanAndWait(); // -- check the commit (the database needs to have been updated correctly) m_collection->registry()->emptyCache(); // -- both tracks should be present Meta::AlbumPtr album; album = m_collection->registry()->getAlbum( 1 ); QVERIFY( album ); QVERIFY( album->tracks().count() >= 1 ); } void TestSqlScanManager::testLongUid() { Meta::FieldHash values; // create two tracks with different very long values.clear(); values.insert( Meta::valUniqueId, QVariant("c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96bbbbbbbbbbbbbbc6c29f50279ab9523a0f44928bc1e96b1") ); values.insert( Meta::valUrl, QVariant("track1.mp3") ); values.insert( Meta::valTitle, QVariant("Track 1") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96c6c29f50279ab9523a0f44928bc1e96bbbbbbbbbbbbbbc6c29f50279ab9523a0f44928bc1e96b2") ); values.insert( Meta::valUrl, QVariant("track2.mp3") ); values.insert( Meta::valTitle, QVariant("Track 2") ); createTrack( values ); fullScanAndWait(); // -- check the commit (the database needs to have been updated correctly) m_collection->registry()->emptyCache(); // both tracks should be present Meta::AlbumPtr album; album = m_collection->registry()->getAlbum( 1 ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 2 ); } void TestSqlScanManager::testCompilation() { createAlbum(); createCompilation(); createCompilationLookAlikeAlbum(); Meta::FieldHash values; // create one compilation track values.clear(); values.insert( Meta::valUniqueId, QVariant("c6c29f50279ab9523a0f44928bc1e96b") ); values.insert( Meta::valUrl, QVariant("Amazon MP3/The Sum Of All Fears (O.S.T.)/The Sum of All Fears/01 - If We Could Remember (O.S.T. LP Version).mp3") ); values.insert( Meta::valTitle, QVariant("If We Could Remember (O.S.T. LP Version)") ); values.insert( Meta::valArtist, QVariant("The Sum Of All Fears (O.S.T.)/Yolanda Adams") ); values.insert( Meta::valAlbum, QVariant("The Sum of All Fears") ); values.insert( Meta::valCompilation, QVariant(true) ); createTrack( values ); // create one various artists track values.clear(); values.insert( Meta::valUniqueId, QVariant("6ae759476c34256ff1d06f0b5c964d75") ); values.insert( Meta::valUrl, QVariant("The Cross Of Changes/06 - The Dream Of The Dolphin.mp3") ); values.insert( Meta::valTitle, QVariant("The Dream Of The Dolphin") ); values.insert( Meta::valArtist, QVariant("Various Artists") ); values.insert( Meta::valAlbum, QVariant("The Cross Of Changes") ); values.insert( Meta::valCompilation, QVariant(false) ); createTrack( values ); // create two tracks in the same directory with different albums values.clear(); values.insert( Meta::valUniqueId, QVariant("7957bc25521c1dc91351d497321c27a6") ); values.insert( Meta::valUrl, QVariant("01 - Solid.mp3") ); values.insert( Meta::valTitle, QVariant("Solid") ); values.insert( Meta::valArtist, QVariant("Ashford & Simpson") ); values.insert( Meta::valAlbum, QVariant("Solid") ); createTrack( values ); // create one none compilation track values.clear(); values.insert( Meta::valUniqueId, QVariant("b88c3405cfee64c50768b75eb6e3feea") ); values.insert( Meta::valUrl, QVariant("In-Mood feat. Juliette - The Last Unicorn (Elemental Radio Mix).mp3") ); values.insert( Meta::valTitle, QVariant("The Last Unicorn (Elemental Radio Mix)") ); values.insert( Meta::valArtist, QVariant("In-Mood") ); values.insert( Meta::valAlbum, QVariant("The Last Unicorn") ); createTrack( values ); fullScanAndWait(); // -- check the commit Meta::AlbumPtr album; album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QCOMPARE( album->tracks().count(), 9 ); QVERIFY( !album->isCompilation() ); album = m_collection->registry()->getAlbum( "Top Gun", QString() ); QCOMPARE( album->name(), QString("Top Gun") ); QCOMPARE( album->tracks().count(), 10 ); QVERIFY( album->isCompilation() ); album = m_collection->registry()->getAlbum( "The Sum of All Fears", QString() ); QCOMPARE( album->tracks().count(), 1 ); QVERIFY( album->isCompilation() ); album = m_collection->registry()->getAlbum( "The Cross Of Changes", QString() ); QCOMPARE( album->tracks().count(), 1 ); QVERIFY( album->isCompilation() ); // the album is by various artists album = m_collection->registry()->getAlbum( "Solid", "Ashford & Simpson" ); QCOMPARE( album->tracks().count(), 1 ); QVERIFY( !album->isCompilation() ); album = m_collection->registry()->getAlbum( "The Last Unicorn", "In-Mood" ); QCOMPARE( album->tracks().count(), 1 ); QVERIFY( !album->isCompilation() ); // this album is a little tricky because it has some nasty special characters in it. Meta::TrackPtr track = m_collection->registry()->getTrackFromUid( m_collection->uidUrlProtocol() + "://" + "0969ea6128444e128cfcac95207bd525" ); QVERIFY( track ); album = track->album(); QCOMPARE( album->tracks().count(), 13 ); QVERIFY( !album->isCompilation() ); } void TestSqlScanManager::testBlock() { /** TODO: do we need blocking at all? createSingleTrack(); Meta::TrackPtr track; m_scanManager->blockScan(); // block the incremental scanning m_scanManager->requestFullScan(); QTest::qWait( 100 ); track = m_collection->registry()->getTrack( 1 ); QVERIFY( !track ); QVERIFY( !m_scanManager->isRunning() ); m_scanManager->unblockScan(); // block the incremental scanning // now the actual behaviour is not defined. // it might or might not continue with the old scan waitScannerFinished(); // in case it does continue after all */ } void TestSqlScanManager::testAddDirectory() { createAlbum(); fullScanAndWait(); createCompilation(); fullScanAndWait(); // -- check the commit Meta::AlbumPtr album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QCOMPARE( album->tracks().count(), 9 ); QVERIFY( !album->isCompilation() ); album = m_collection->registry()->getAlbum( "Top Gun", QString() ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 10 ); QVERIFY( album->isCompilation() ); } void TestSqlScanManager::testRemoveDir() { Meta::AlbumPtr album; createAlbum(); createCompilation(); fullScanAndWait(); // -- check the commit album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 9 ); QVERIFY( !album->isCompilation() ); album = m_collection->registry()->getAlbum( "Top Gun", QString() ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 10 ); QVERIFY( album->isCompilation() ); // -- remove one album album = m_collection->registry()->getAlbum( "Top Gun", QString() ); QVERIFY( album ); foreach( Meta::TrackPtr t, album->tracks() ) QVERIFY( QFile::remove( t->playableUrl().path() ) ); QVERIFY( QDir( m_tmpCollectionDir->path() ).rmdir( QFileInfo( album->tracks().first()->playableUrl().path() ).path() ) ); fullScanAndWait(); // this one is still here album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 9 ); QVERIFY( !album->isCompilation() ); // this one is gone album = m_collection->registry()->getAlbum( "Top Gun", QString() ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 0 ); // -- remove the second album // this time it's a directory inside a directory album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 9 ); foreach( Meta::TrackPtr t, album->tracks() ) QVERIFY( QFile::remove( t->playableUrl().path() ) ); QVERIFY( QDir( m_tmpCollectionDir->path() ).rmdir( QFileInfo( album->tracks().first()->playableUrl().path() ).path() ) ); incrementalScanAndWait(); // this time both are gone album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 0 ); album = m_collection->registry()->getAlbum( "Top Gun", QString() ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 0 ); } void TestSqlScanManager::testUidChangeMoveDirectoryIncrementalScan() { createAlbum(); fullScanAndWait(); Meta::AlbumPtr album; Meta::TrackList tracks; // -- check the commit album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); tracks = album->tracks(); QCOMPARE( tracks.count(), 9 ); QCOMPARE( tracks.first()->uidUrl(), QString("amarok-sqltrackuid://1dc7022c52a3e4c51b46577da9b3c8ff") ); QVERIFY( !album->isCompilation() ); // change all the track uids in a silly way QHash uidChanges; // uid hashed with track number foreach( const Meta::TrackPtr &track, tracks ) { Meta::FieldHash uidChange; QString uid = track->uidUrl().remove( QString("amarok-sqltrackuid://") ); QStringRef left = uid.leftRef( 10 ); QStringRef right = uid.rightRef( uid.size() - left.size() ); QString newUid = QString("%1%2").arg( right.toString(), left.toString() ); uidChange.insert( Meta::valUniqueId, newUid ); uidChanges.insert( track->trackNumber(), newUid ); QUrl url = track->playableUrl(); QVERIFY( url.isLocalFile() ); Meta::Tag::writeTags( url.path(), uidChange, true ); } // move album directory const QUrl oldUrl = tracks.first()->playableUrl(); const QString base = m_tmpCollectionDir->path() + "/Pop"; QVERIFY( QFile::rename( base, base + "Albums" ) ); // do an incremental scan incrementalScanAndWait(); // recheck album album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); tracks = album->tracks(); QCOMPARE( tracks.count(), 9 ); // check changed uids foreach( const Meta::TrackPtr &track, tracks ) { QString uid = track->uidUrl().remove( QString("amarok-sqltrackuid://") ); QCOMPARE( uid, uidChanges.value( track->trackNumber() ) ); } } void TestSqlScanManager::testRemoveTrack() { Meta::AlbumPtr album; Meta::TrackPtr track; QDateTime aDate = QDateTime::currentDateTime(); createAlbum(); fullScanAndWait(); // -- check the commit album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 9 ); QVERIFY( !album->isCompilation() ); track = album->tracks().first(); // the tracks are sorted, so this is always the same track QCOMPARE( track->trackNumber(), 1 ); QVERIFY( !track->statistics()->firstPlayed().isValid() ); static_cast(track.data())->setFirstPlayed( aDate ); // -- remove one track QVERIFY( QFile::remove( track->playableUrl().path() ) ); fullScanAndWait(); // -- check that the track is really gone QCOMPARE( album->tracks().count(), 8 ); } void TestSqlScanManager::testMove() { createAlbum(); createCompilation(); // we use the created and first played attributes for identifying the moved tracks. // currently those are not written back to the track Meta::AlbumPtr album; Meta::TrackPtr track; QDateTime aDate = QDateTime::currentDateTime(); fullScanAndWait(); if( qgetenv("AMAROK_RUN_LONG_TESTS").isNull() ) QSKIP( "takes too long to be run by default;\nDefine AMAROK_RUN_LONG_TESTS " "environment variable to run all tests.", SkipAll ); // -- check the commit album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 9 ); QVERIFY( !album->isCompilation() ); track = album->tracks().first(); QCOMPARE( track->trackNumber(), 1 ); QDateTime createDate = track->createDate(); QDateTime modifyDate = track->modifyDate(); // --- move one track static_cast(track.data())->setFirstPlayed( aDate ); const QString targetPath = m_tmpCollectionDir->path() + "/moved.mp3"; QVERIFY( QFile::rename( track->playableUrl().path(), targetPath ) ); fullScanAndWait(); // -- check that the track is moved QVERIFY( createDate == track->createDate() ); // create date should not have changed QVERIFY( modifyDate == track->modifyDate() ); // we just changed the track. it should have changed QCOMPARE( track->statistics()->firstPlayed(), aDate ); QCOMPARE( track->playableUrl().path(), targetPath ); // --- move a directory album = m_collection->registry()->getAlbum( "Top Gun", QString() ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 10 ); track = album->tracks().first(); QUrl oldUrl = track->playableUrl(); QVERIFY( QFile::rename( m_tmpCollectionDir->path() + "/Top Gun", m_tmpCollectionDir->path() + "/Top Gun - Soundtrack" ) ); // do an incremental scan incrementalScanAndWait(); // check that the track is now moved (but still the old object) QCOMPARE( album->tracks().count(), 10 ); // no doublicate tracks QVERIFY( oldUrl != track->playableUrl() ); } void TestSqlScanManager::testFeat() { Meta::FieldHash values; // create one compilation track values.clear(); values.insert( Meta::valUniqueId, QVariant("b88c3405cfee64c50768b75eb6e3feea") ); values.insert( Meta::valUrl, QVariant("In-Mood feat. Juliette - The Last Unicorn (Elemental Radio Mix).mp3") ); values.insert( Meta::valTitle, QVariant("The Last Unicorn (Elemental Radio Mix)") ); values.insert( Meta::valArtist, QVariant("In-Mood feat. Juliette") ); values.insert( Meta::valAlbum, QVariant("The Last Unicorn") ); createTrack( values ); fullScanAndWait(); // -- check the commit Meta::AlbumPtr album; album = m_collection->registry()->getAlbum( "The Last Unicorn", "In-Mood" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 1 ); } void TestSqlScanManager::testAlbumImage() { createSingleTrack(); createAlbum(); createCompilation(); // put an image into the album directory QString imageSourcePath = QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + "/data/playlists/no-playlist.png" ); QVERIFY( QFile::exists( imageSourcePath ) ); QString targetPath; targetPath = m_tmpCollectionDir->path() + "/Pop/Thriller/cover.png"; QVERIFY( QFile::copy( m_sourcePath, targetPath ) ); // put an image into the compilation directory targetPath = m_tmpCollectionDir->path() + "/Top Gun/front.png"; QVERIFY( QFile::copy( m_sourcePath, targetPath ) ); // set an embedded image targetPath = m_tmpCollectionDir->path() + "/Various Artists/Big Screen Adventures/28 - Theme From Armageddon.mp3"; Meta::Tag::setEmbeddedCover( targetPath, QImage( 200, 200, QImage::Format_RGB32 ) ); fullScanAndWait(); // -- check the commit Meta::AlbumPtr album; album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QVERIFY( album->hasImage() ); album = m_collection->registry()->getAlbum( "Top Gun", QString() ); QVERIFY( album ); QVERIFY( album->hasImage() ); album = m_collection->registry()->getAlbum( "Big Screen Adventures", "Theme Orchestra" ); QVERIFY( album ); QVERIFY( album->hasImage() ); } void TestSqlScanManager::testMerges() { // songs from same album but different directory // check that images are merged // check that old image is not overwritten Meta::FieldHash values; values.clear(); values.insert( Meta::valUniqueId, QVariant("123456d040d5dd9b5b45c1494d84cc82") ); values.insert( Meta::valUrl, QVariant("Various Artists/Big Screen Adventures/28 - Theme From Armageddon.mp3") ); values.insert( Meta::valFormat, QVariant("1") ); values.insert( Meta::valTitle, QVariant("Unnamed track") ); values.insert( Meta::valArtist, QVariant("Unknown artist") ); createTrack( values ); // -- check the commit fullScanAndWait(); Meta::TrackPtr track = m_collection->registry()->getTrack( 1 ); QVERIFY( track ); QCOMPARE( track->name(), QString("Unnamed track") ); // -- now overwrite the track with changed information and a new uid // - remove one track QVERIFY( QFile::remove( track->playableUrl().path() ) ); values.clear(); values.insert( Meta::valUniqueId, QVariant("794b1bd040d5dd9b5b45c1494d84cc82") ); values.insert( Meta::valUrl, QVariant("Various Artists/Big Screen Adventures/28 - Theme From Armageddon.mp3") ); values.insert( Meta::valFormat, QVariant("1") ); values.insert( Meta::valTitle, QVariant("Theme From Armageddon") ); values.insert( Meta::valArtist, QVariant("Soundtrack & Theme Orchestra") ); values.insert( Meta::valAlbum, QVariant("Big Screen Adventures") ); values.insert( Meta::valComposer, QVariant("Unknown Composer") ); values.insert( Meta::valComment, QVariant("Amazon.com Song ID: 210541237") ); values.insert( Meta::valGenre, QVariant("Broadway & Vocalists") ); values.insert( Meta::valYear, QVariant(2009) ); values.insert( Meta::valTrackNr, QVariant(28) ); values.insert( Meta::valScore, QVariant(0.875) ); values.insert( Meta::valPlaycount, QVariant(5) ); createTrack( values ); fullScanAndWait(); // -- check the commit QCOMPARE( track->name(), QString("Theme From Armageddon") ); QVERIFY( track->artist() ); QCOMPARE( track->artist()->name(), QString("Soundtrack & Theme Orchestra") ); QVERIFY( track->album() ); QCOMPARE( track->album()->name(), QString("Big Screen Adventures") );if( qgetenv("AMAROK_RUN_LONG_TESTS").isNull() ) QSKIP( "takes too long to be run by default;\nDefine AMAROK_RUN_LONG_TESTS " "environment variable to run all tests.", SkipAll ); QCOMPARE( track->composer()->name(), QString("Unknown Composer") ); QCOMPARE( track->comment(), QString("Amazon.com Song ID: 210541237") ); QCOMPARE( track->year()->year(), 2009 ); QCOMPARE( track->type(), QString("mp3") ); QCOMPARE( track->trackNumber(), 28 ); QCOMPARE( track->bitrate(), 257 ); QCOMPARE( track->length(), qint64(12000) ); QCOMPARE( track->sampleRate(), 44100 ); QCOMPARE( track->filesize(), 389679 ); Meta::StatisticsPtr statistics = track->statistics(); qFuzzyCompare( statistics->score(), 0.875 ); QCOMPARE( statistics->playCount(), 5 ); QVERIFY( !statistics->firstPlayed().isValid() ); QVERIFY( !statistics->lastPlayed().isValid() ); QVERIFY( track->createDate().isValid() ); // -- now do an incremental scan createAlbum(); // add a new album incrementalScanAndWait(); // -- check the commit Meta::AlbumPtr album; // the old track is still there album = m_collection->registry()->getAlbum( "Big Screen Adventures", "Soundtrack & Theme Orchestra" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 1 ); // the new album is now here album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 9 ); QVERIFY( !album->isCompilation() ); } void TestSqlScanManager::testLargeInsert() { if( qgetenv("AMAROK_RUN_LONG_TESTS").isNull() ) QSKIP( "takes too long to be run by default;\nDefine AMAROK_RUN_LONG_TESTS " "environment variable to run all tests.", SkipAll ); // the old large insert test was misleading as the problems with // the insertion started upwards of 20000 tracks. // // For now here are the "ok" numbers on a sensible fast computer: // Scanning 10000 files <3 min // Committing 10000 files <30 sec // Scanning 50000 files <13 min // Committing 50000 files <1 min QDateTime aDate = QDateTime::currentDateTime(); // -- create the input data QByteArray byteArray; QBuffer *buffer = new QBuffer(&byteArray); buffer->open(QIODevice::ReadWrite); QXmlStreamWriter writer( buffer ); writer.writeStartElement( "scanner" ); int trackCount = 0; // some simulated normal albums for( int dirId = 0; dirId < 2000; dirId++ ) { writer.writeStartElement( "directory" ); writer.writeTextElement( "path", QString::number(dirId) ); writer.writeTextElement( "rpath", '/' + QString::number(dirId) ); writer.writeTextElement( "mtime", QString::number(aDate.toTime_t()) ); for( int trackId = 0; trackId < 20; trackId++ ) { writer.writeStartElement( "track" ); writer.writeTextElement( "uniqueid", "uid" + QString::number(trackCount) ); writer.writeTextElement( "path", "/path" + QString::number(trackCount) ); writer.writeTextElement( "rpath", "path" + QString::number(trackCount) ); trackCount++; writer.writeTextElement( "title", "track" + QString::number(trackCount) ); writer.writeTextElement( "artist", "artist" + QString::number(dirId) ); writer.writeTextElement( "album", QString::number(dirId) ); writer.writeEndElement(); } writer.writeEndElement(); } // a simulated genre folders for( int dirId = 0; dirId < 7; dirId++ ) { writer.writeStartElement( "directory" ); writer.writeTextElement( "path", "genre" + QString::number(dirId) ); writer.writeTextElement( "rpath", "/genre" + QString::number(dirId) ); writer.writeTextElement( "mtime", QString::number(aDate.toTime_t()) ); for( int albumId = 0; albumId < 1000; albumId++ ) { writer.writeStartElement( "track" ); writer.writeTextElement( "uniqueid", "uid" + QString::number(trackCount) ); writer.writeTextElement( "path", "/path" + QString::number(trackCount) ); writer.writeTextElement( "rpath", "path" + QString::number(trackCount) ); trackCount++; writer.writeTextElement( "title", "track" + QString::number(trackCount) ); writer.writeTextElement( "artist", "artist" + QString::number(dirId) + "xx" + QString::number(albumId) ); writer.writeTextElement( "album", "genre album" + QString::number(dirId) + "xx" + QString::number(albumId) ); writer.writeEndElement(); } writer.writeEndElement(); } // A simulated amarok 1.4 collection folder for( int dirId = 0; dirId < 3000; dirId++ ) { writer.writeStartElement( "directory" ); writer.writeTextElement( "path", "collection" + QString::number(dirId) ); writer.writeTextElement( "rpath", "/collection" + QString::number(dirId) ); writer.writeTextElement( "mtime", QString::number(aDate.toTime_t()) ); writer.writeStartElement( "track" ); writer.writeTextElement( "uniqueid", "uid" + QString::number(trackCount) ); writer.writeTextElement( "path", "/path" + QString::number(trackCount) ); writer.writeTextElement( "rpath", "path" + QString::number(trackCount) ); trackCount++; writer.writeTextElement( "title", "track" + QString::number(trackCount) ); writer.writeTextElement( "artist", "album artist" + QString::number(dirId % 200) ); writer.writeTextElement( "album", "album" + QString::number(dirId % 300) ); writer.writeEndElement(); writer.writeEndElement(); } writer.writeEndElement(); aDate = QDateTime::currentDateTime(); // -- feed the scanner in batch mode buffer->seek( 0 ); importAndWait( buffer ); qDebug() << "performance test secs:"<< aDate.secsTo( QDateTime::currentDateTime() ); QVERIFY( aDate.secsTo( QDateTime::currentDateTime() ) < 120 ); // -- get all tracks Collections::SqlQueryMaker *qm = static_cast< Collections::SqlQueryMaker* >( m_collection->queryMaker() ); qm->setQueryType( Collections::QueryMaker::Track ); qm->setBlocking( true ); qm->run(); Meta::TrackList tracks = qm->tracks(); delete qm; for( int i = 0; i < trackCount; i++ ) { Meta::TrackPtr track = m_collection->registry()->getTrackFromUid( m_collection->uidUrlProtocol() + "://uid" + QString::number(i) ); QVERIFY( track ); } qDebug() << "performance test secs:"<< aDate.secsTo( QDateTime::currentDateTime() ) << "tracks:" << trackCount; QCOMPARE( tracks.count(), trackCount ); // -- scan the input a second time. that should be a lot faster (but currently isn't) aDate = QDateTime::currentDateTime(); // -- feed the scanner in batch mode buffer = new QBuffer(&byteArray); // the old scanner deleted the old buffer. buffer->open(QIODevice::ReadWrite); importAndWait( buffer ); qDebug() << "performance test secs:"<< aDate.secsTo( QDateTime::currentDateTime() ); QVERIFY( aDate.secsTo( QDateTime::currentDateTime() ) < 80 ); } void TestSqlScanManager::testIdentifyCompilationInMultipleDirectories() { // Compilations where each is track is from a different artist // are often stored as one track per directory, e.g. // /artistA/compilation/track1 // /artistB/compilation/track2 // // this is how Amarok 1 (after using Organize Collection) and iTunes are storing // these albums on disc // the bad thing is that Amarok 1 (as far as I know) didn't set the id3 tags Meta::FieldHash values; values.insert( Meta::valUniqueId, QVariant("5ef9fede5b3f98deb088b33428b0398e") ); values.insert( Meta::valUrl, QVariant("Kenny Loggins/Top Gun/Top Gun - 01 - Kenny Loggins - Danger Zone.mp3") ); values.insert( Meta::valFormat, QVariant("1") ); values.insert( Meta::valTitle, QVariant("Danger Zone") ); values.insert( Meta::valArtist, QVariant("Kenny Loggins") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); values.insert( Meta::valTrackNr, QVariant("1") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("3e3970f52b0eda3f2a8c1b3a8c8d39ea") ); values.insert( Meta::valUrl, QVariant("Cheap Trick/Top Gun/Top Gun - 02 - Cheap Trick - Mighty Wings.mp3") ); values.insert( Meta::valTitle, QVariant("Mighty Wings") ); values.insert( Meta::valArtist, QVariant("Cheap Trick") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("6ea0bbd97ad8068df58ad75a81f271f7") ); values.insert( Meta::valUrl, QVariant("Kenny Loggins/Top Gun/Top Gun - 03 - Kenny Loggins - Playing With The Boys.mp3") ); values.insert( Meta::valTitle, QVariant("Playing With The Boys") ); values.insert( Meta::valArtist, QVariant("Kenny Loggins") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("f3ac2e15288361d779a0ae813a2018ba") ); values.insert( Meta::valUrl, QVariant("Teena Marie/Top Gun/Top Gun - 04 - Teena Marie - Lead Me On.mp3") ); values.insert( Meta::valTitle, QVariant("Lead Me On") ); values.insert( Meta::valArtist, QVariant("Teena Marie") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); fullScanAndWait(); // -- check the commit Meta::AlbumPtr album = m_collection->registry()->getAlbum( "Top Gun", QString() ); QVERIFY( album ); QCOMPARE( album->name(), QString("Top Gun") ); QCOMPARE( album->tracks().count(), 4 ); QVERIFY( album->isCompilation() ); } void TestSqlScanManager::testAlbumArtistMerges() { // three tracks with the same artist but different album artist. // (one is unset) // Those should end up in different albums. Meta::FieldHash values; values.insert( Meta::valUniqueId, QVariant("1ef9fede5b3f98deb088b33428b0398e") ); values.insert( Meta::valUrl, QVariant("test1/song1.mp3") ); values.insert( Meta::valTitle, QVariant("title1") ); values.insert( Meta::valArtist, QVariant("artist") ); values.insert( Meta::valAlbumArtist, QVariant("albumArtist1") ); values.insert( Meta::valAlbum, QVariant("test1") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("2ef9fede5b3f98deb088b33428b0398b") ); values.insert( Meta::valUrl, QVariant("test1/song2.mp3") ); values.insert( Meta::valTitle, QVariant("title2") ); values.insert( Meta::valArtist, QVariant("artist") ); values.insert( Meta::valAlbumArtist, QVariant("albumArtist2") ); values.insert( Meta::valAlbum, QVariant("test1") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("3ef9fede5b3f98deb088b33428b0398c") ); values.insert( Meta::valUrl, QVariant("test1/song3.mp3") ); values.insert( Meta::valTitle, QVariant("title3") ); values.insert( Meta::valArtist, QVariant("artist") ); values.insert( Meta::valAlbum, QVariant("test1") ); createTrack( values ); fullScanAndWait(); // -- check the commit Meta::AlbumPtr album; album = m_collection->registry()->getAlbum( "test1", QString() ); QVERIFY( album ); QCOMPARE( album->name(), QString("test1") ); QCOMPARE( album->tracks().count(), 1 ); QVERIFY( album->isCompilation() ); album = m_collection->registry()->getAlbum( "test1", QString("albumArtist1") ); QVERIFY( album ); QCOMPARE( album->name(), QString("test1") ); QCOMPARE( album->tracks().count(), 1 ); QVERIFY( !album->isCompilation() ); album = m_collection->registry()->getAlbum( "test1", QString("albumArtist2") ); QVERIFY( album ); QCOMPARE( album->name(), QString("test1") ); QCOMPARE( album->tracks().count(), 1 ); QVERIFY( !album->isCompilation() ); } void TestSqlScanManager::testCrossRenaming() { createAlbum(); // we use the created and first played attributes for identifying the moved tracks. // currently those are not written back to the track Meta::AlbumPtr album; Meta::TrackPtr track; fullScanAndWait(); // -- check the commit album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 9 ); QVERIFY( !album->isCompilation() ); // --- cross-rename two track track = album->tracks().at( 0 ); static_cast(track.data())->setRating( 1 ); QString path1 = track->playableUrl().path(); track = album->tracks().at( 1 ); static_cast(track.data())->setRating( 2 ); QString path2 = track->playableUrl().path(); QString targetPath = m_tmpCollectionDir->path() + "moved.mp3"; QVERIFY( QFile::rename( path2, targetPath ) ); QVERIFY( QFile::rename( path1, path2 ) ); QVERIFY( QFile::rename( targetPath, path1 ) ); fullScanAndWait(); // -- check that the tracks are moved correctly album = m_collection->registry()->getAlbum( "Thriller", "Michael Jackson" ); QVERIFY( album ); QCOMPARE( album->tracks().count(), 9 ); track = album->tracks().at( 0 ); QCOMPARE( track->statistics()->rating(), 1 ); QCOMPARE( track->playableUrl().path(), path2 ); track = album->tracks().at( 1 ); QCOMPARE( track->statistics()->rating(), 2 ); QCOMPARE( track->playableUrl().path(), path1 ); } void TestSqlScanManager::slotCollectionUpdated() { m_collectionUpdatedCount++; } void TestSqlScanManager::fullScanAndWait() { QScopedPointer csc( m_collection->create()); if( csc ) { csc->startFullScan(); waitScannerFinished(); } } void TestSqlScanManager::incrementalScanAndWait() { // incremental scans use the modification time of the file system. // this time is only in seconds, so to be sure that the incremental scan // works we need to wait at least one second. QTest::qWait( 1000 ); QScopedPointer csc( m_collection->create()); if( csc ) csc->startIncrementalScan(); waitScannerFinished(); } void TestSqlScanManager::importAndWait( QIODevice* input ) { QScopedPointer csc( m_collection->create()); if( csc ) csc->import( input, 0 ); waitScannerFinished(); } void TestSqlScanManager::waitScannerFinished() { QVERIFY( m_scanManager->isRunning() ); QSignalSpy succeedSpy( m_scanManager, &GenericScanManager::succeeded ); QSignalSpy failSpy( m_scanManager, &GenericScanManager::failed ); QSignalSpy resultSpy( this, &TestSqlScanManager::scanManagerResult ); // connect the result signal *after* the spies to ensure they are updated first connect( m_scanManager, &GenericScanManager::succeeded, this, &TestSqlScanManager::scanManagerResult ); connect( m_scanManager, &GenericScanManager::failed, this, &TestSqlScanManager::scanManagerResult); const bool ok = resultSpy.wait( 5000 ); disconnect( m_scanManager, &GenericScanManager::succeeded, this, &TestSqlScanManager::scanManagerResult ); disconnect( m_scanManager, &GenericScanManager::failed, this, &TestSqlScanManager::scanManagerResult ); QVERIFY2( ok, "Scan Manager timed out without a result" ); if( failSpy.count() > 0 ) { QStringList errors; foreach( const QList &arguments, static_cast > >( failSpy ) ) errors << arguments.value( 0 ).toString(); // this will fire each time: qWarning() << "ScanManager failed with an error:" << errors.join( ", " ); } QCOMPARE( qMakePair( succeedSpy.count(), failSpy.count() ), qMakePair( 1, 0 ) ); QVERIFY( !m_scanManager->isRunning() ); } void TestSqlScanManager::createTrack( const Meta::FieldHash &values ) { // -- copy the file from our original QVERIFY( values.contains( Meta::valUrl ) ); const QString targetPath = m_tmpCollectionDir->path() + "/" + values.value( Meta::valUrl ).toString(); QVERIFY( QDir( m_tmpCollectionDir->path() ).mkpath( QFileInfo( values.value( Meta::valUrl ).toString() ).path() ) ); QVERIFY( QFile::copy( m_sourcePath, targetPath ) ); // -- set all the values that we need Meta::Tag::writeTags( targetPath, values, true ); } void TestSqlScanManager::createSingleTrack() { Meta::FieldHash values; values.insert( Meta::valUniqueId, QVariant("794b1bd040d5dd9b5b45c1494d84cc82") ); values.insert( Meta::valUrl, QVariant("Various Artists/Big Screen Adventures/28 - Theme From Armageddon.mp3") ); values.insert( Meta::valFormat, QVariant("1") ); values.insert( Meta::valTitle, QVariant("Theme From Armageddon") ); values.insert( Meta::valArtist, QVariant("Soundtrack & Theme Orchestra") ); values.insert( Meta::valAlbumArtist, QVariant("Theme Orchestra") ); values.insert( Meta::valAlbum, QVariant("Big Screen Adventures") ); values.insert( Meta::valComposer, QVariant("Unknown Composer") ); values.insert( Meta::valComment, QVariant("Amazon.com Song ID: 210541237") ); values.insert( Meta::valGenre, QVariant("Broadway & Vocalists") ); values.insert( Meta::valYear, QVariant(2009) ); values.insert( Meta::valTrackNr, QVariant(28) ); // values.insert( Meta::valBitrate, QVariant(216) ); // the bitrate can not be set. it's computed // values.insert( Meta::valLength, QVariant(184000) ); // also can't be set // values.insert( Meta::valSamplerate, QVariant(44100) ); // again // values.insert( Meta::valFilesize, QVariant(5094892) ); // again values.insert( Meta::valScore, QVariant(0.875) ); values.insert( Meta::valPlaycount, QVariant(5) ); // TODO: set an embedded cover createTrack( values ); } void TestSqlScanManager::createAlbum() { Meta::FieldHash values; values.insert( Meta::valUniqueId, QVariant("1dc7022c52a3e4c51b46577da9b3c8ff") ); values.insert( Meta::valUrl, QVariant("Pop/Thriller/Thriller - 01 - Michael Jackson - Track01.mp3") ); values.insert( Meta::valTitle, QVariant("Wanna Be Startin' Somethin'") ); values.insert( Meta::valArtist, QVariant("Michael Jackson") ); values.insert( Meta::valAlbum, QVariant("Thriller") ); values.insert( Meta::valYear, QVariant(1982) ); values.insert( Meta::valTrackNr, QVariant(1) ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("1dc708934a3e4c51b46577da9b3ab11") ); values.insert( Meta::valUrl, QVariant("Pop/Thriller/Thriller - 02 - Michael Jackson - Track02.mp3") ); values.insert( Meta::valTitle, QVariant("Baby Be Mine") ); values.insert( Meta::valArtist, QVariant("Michael Jackson") ); values.insert( Meta::valAlbum, QVariant("Thriller") ); values.insert( Meta::valYear, QVariant(1982) ); values.insert( Meta::valTrackNr, QVariant(2) ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("15a6b1bf79747fdc8e9c6b6f06203017") ); values.insert( Meta::valUrl, QVariant("Pop/Thriller/Thriller - 03 - Michael Jackson - Track03.mp3") ); values.insert( Meta::valTitle, QVariant("The Girl Is Mine") ); values.insert( Meta::valArtist, QVariant("Michael Jackson") ); values.insert( Meta::valAlbum, QVariant("Thriller") ); values.insert( Meta::valYear, QVariant(1982) ); values.insert( Meta::valTrackNr, QVariant(3) ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("4aba4c8b1d1893c03c112cc3c01221e9") ); values.insert( Meta::valUrl, QVariant("Pop/Thriller/Thriller - 04 - Michael Jackson - Track04.mp3") ); values.insert( Meta::valTitle, QVariant("Thriller") ); values.insert( Meta::valArtist, QVariant("Michael Jackson") ); values.insert( Meta::valAlbum, QVariant("Thriller") ); values.insert( Meta::valYear, QVariant(1982) ); values.insert( Meta::valTrackNr, QVariant(4) ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("cb44d2a3d8053829b04672723bf0bd6e") ); values.insert( Meta::valUrl, QVariant("Pop/Thriller/Thriller - 05 - Michael Jackson - Track05.mp3") ); values.insert( Meta::valTitle, QVariant("Beat It") ); values.insert( Meta::valArtist, QVariant("Michael Jackson") ); values.insert( Meta::valAlbum, QVariant("Thriller") ); values.insert( Meta::valYear, QVariant(1982) ); values.insert( Meta::valTrackNr, QVariant(5) ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("eba1858eeeb3c6d97fe3385200114d86") ); values.insert( Meta::valUrl, QVariant("Pop/Thriller/Thriller - 06 - Michael Jackson - Track06.mp3") ); values.insert( Meta::valTitle, QVariant("Billy Jean") ); values.insert( Meta::valArtist, QVariant("Michael Jackson") ); values.insert( Meta::valAlbum, QVariant("Thriller") ); values.insert( Meta::valYear, QVariant(1982) ); values.insert( Meta::valTrackNr, QVariant(6) ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("4623850290998486b0f7b39a2719904e") ); values.insert( Meta::valUrl, QVariant("Pop/Thriller/Thriller - 07 - Michael Jackson - Track07.mp3") ); values.insert( Meta::valTitle, QVariant("Human Nature") ); values.insert( Meta::valArtist, QVariant("Michael Jackson") ); values.insert( Meta::valAlbum, QVariant("Thriller") ); values.insert( Meta::valYear, QVariant(1982) ); values.insert( Meta::valTrackNr, QVariant(7) ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("6d9a7de13af1e16bb13a6208e44b046d") ); values.insert( Meta::valUrl, QVariant("Pop/Thriller/Thriller - 08 - Michael Jackson - Track08.mp3") ); values.insert( Meta::valTitle, QVariant("P.Y.T. (Pretty Young Thing)") ); values.insert( Meta::valArtist, QVariant("Michael Jackson") ); values.insert( Meta::valAlbum, QVariant("Thriller") ); values.insert( Meta::valYear, QVariant(1982) ); values.insert( Meta::valTrackNr, QVariant(8) ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("91cf9a7c0d255399f9f6babfacae432b") ); values.insert( Meta::valUrl, QVariant("Pop/Thriller/Thriller - 09 - Michael Jackson - Track09.mp3") ); values.insert( Meta::valTitle, QVariant("The Lady In My Life") ); values.insert( Meta::valArtist, QVariant("Michael Jackson") ); values.insert( Meta::valAlbum, QVariant("Thriller") ); values.insert( Meta::valYear, QVariant(1982) ); values.insert( Meta::valTrackNr, QVariant(9) ); createTrack( values ); } void TestSqlScanManager::createCompilation() { // a compilation without the compilation flags values.insert( Meta::valCompilation, QVariant(true) ); Meta::FieldHash values; values.insert( Meta::valUniqueId, QVariant("5ef9fede5b3f98deb088b33428b0398e") ); values.insert( Meta::valUrl, QVariant("Top Gun/Top Gun - 01 - Kenny Loggins - Danger Zone.mp3") ); values.insert( Meta::valFormat, QVariant("1") ); values.insert( Meta::valTitle, QVariant("Danger Zone") ); values.insert( Meta::valArtist, QVariant("Kenny Loggins") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("3e3970f52b0eda3f2a8c1b3a8c8d39ea") ); values.insert( Meta::valUrl, QVariant("Top Gun/Top Gun - 02 - Cheap Trick - Mighty Wings.mp3") ); values.insert( Meta::valTitle, QVariant("Mighty Wings") ); values.insert( Meta::valArtist, QVariant("Cheap Trick") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("6ea0bbd97ad8068df58ad75a81f271f7") ); values.insert( Meta::valUrl, QVariant("Top Gun/Top Gun - 03 - Kenny Loggins - Playing With The Boys.mp3") ); values.insert( Meta::valTitle, QVariant("Playing With The Boys") ); values.insert( Meta::valArtist, QVariant("Kenny Loggins") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("f3ac2e15288361d779a0ae813a2018ba") ); values.insert( Meta::valUrl, QVariant("Top Gun/Top Gun - 04 - Teena Marie - Lead Me On.mp3") ); values.insert( Meta::valTitle, QVariant("Lead Me On") ); values.insert( Meta::valArtist, QVariant("Teena Marie") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("ffe2bb3e6e2f698983c95e40937545ff") ); values.insert( Meta::valUrl, QVariant("Top Gun/Top Gun - 05 - Berlin - Take My Breath Away (Love Theme From _Top Gun_).mp3") ); values.insert( Meta::valTitle, QVariant("Take My Breath Away (Love Theme From "Top Gun")") ); values.insert( Meta::valArtist, QVariant("Berlin") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("c871dba16f92483898bcd6a1ed1bc14f") ); values.insert( Meta::valUrl, QVariant("Top Gun/Top Gun - 06 - Miami Sound Machine - Hot Summer Nights.mp3") ); values.insert( Meta::valTitle, QVariant("Hot Summer Nights") ); values.insert( Meta::valArtist, QVariant("Miami Sound Machine") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("80d157c36ed334192ed8df4c01bf0d4e") ); values.insert( Meta::valUrl, QVariant("Top Gun/Top Gun - 07 - Loverboy - Heaven In Your Eyes.mp3") ); values.insert( Meta::valTitle, QVariant("Heaven In Your Eyes") ); values.insert( Meta::valArtist, QVariant("Loverboy") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("1fe5897cdea860348c3a5eb40d47c382") ); values.insert( Meta::valUrl, QVariant("Top Gun/Top Gun - 08 - Larry Greene - Through The Fire.mp3") ); values.insert( Meta::valTitle, QVariant("Through The Fire") ); values.insert( Meta::valArtist, QVariant("Larry Greene") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("e0eacff604bfe38b5c275b45aa4f5323") ); values.insert( Meta::valUrl, QVariant("Top Gun/Top Gun - 09 - Marietta - Destination Unknown.mp3") ); values.insert( Meta::valTitle, QVariant("Destination Unknown") ); values.insert( Meta::valArtist, QVariant("Marietta") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("9f1b00dab2df7537b6c5b2be9f08b220") ); values.insert( Meta::valUrl, QVariant("Top Gun/Top Gun - 10 - Harold Faltermeyer & Steve Stevens - Top Gun Anthem.mp3") ); values.insert( Meta::valTitle, QVariant("Top Gun Anthem") ); values.insert( Meta::valArtist, QVariant("Harold Faltermeyer & Steve Stevens") ); values.insert( Meta::valAlbum, QVariant("Top Gun") ); createTrack( values ); } void TestSqlScanManager::createCompilationLookAlikeAlbum() { Meta::FieldHash values; // Some systems have problems with the umlauts in the file names. // That is the case where the system encoding when compiling does not // match the one of the file system. // the following is the original filename // values.insert( Meta::valUrl, QVariant( "Glen Hansard & Markéta Irglová/Once/01 Glen Hansard & Markéta Irglová - Falling Slowly.mp3" ) ); values.insert( Meta::valUniqueId, QVariant( "8375aa24e0e0434ca0c36e382b6f188c" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/01 Glen Hansard & Marketa Irglova - Falling Slowly.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "Falling Slowly" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "1" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "ff3f82b1c2e1434d9d1a7b6aec67ac9c" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/02 Glen Hansard & Marketa Irglova - If You Want Me.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "If You Want Me" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "2" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "8fb2396f8d974f6196d2b2ef93ba2551" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/03 Glen Hansard - Broken Hearted Hoover Fixer Sucker Guy.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "Broken Hearted Hoover Fixer Sucker Guy" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "3" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "3a211546b91c4bf7a4ec9d41325e5a01" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/04 Glen Hansard & Marketa Irglova - When Your Mind's Made Up.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "When Your Mind's Made Up" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "4" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "e7a1ed52777c437582a217cd29cc35f7" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/05 Glen Hansard - Lies.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "Lies" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "5" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "e0c88a85884d40c899522cd733718d9e" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/06 Interference - Gold.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "Gold" ) ); values.insert( Meta::valArtist, QVariant( "Interference" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "6" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "0969ea6128444e128cfcac95207bd525" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/07 Marketa Irglova - The Hill.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "The Hill" ) ); values.insert( Meta::valArtist, QVariant( "Markéta Irglová" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "7" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "c1d6eff3cb6c42eaa0d63e186ef1b749" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/08 Glen Hansard - Fallen From the Sky.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "Fallen From the Sky" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "8" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "b6611dbccd0e49bca8db5dc598b7bf4f" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/09 Glen Hansard - Leave.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "Leave" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "9" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "46873076087f48dda553fc5ebd3c0fb6" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/10 Glen Hansard - Trying to Pull Myself Away.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "Trying to Pull Myself Away" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "10" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "ea29de7b131c4cf28df177a8cda990ee" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/11 Glen Hansard - All the Way Down.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "All the Way Down" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "11" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "66259801d8ba4d50a2dfdf0129bc8792" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/12 Glen Hansard & Marketa Irglova - Once.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "Once" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "12" ) ); createTrack( values ); values.insert( Meta::valUniqueId, QVariant( "a654e8c5afb14de7b55b6548ac02f724" ) ); values.insert( Meta::valUrl, QVariant( "Glen Hansard & Marketa Irglova/Once/13 Glen Hansard - Say It to Me Now.mp3" ) ); values.insert( Meta::valFormat, QVariant( "1" ) ); values.insert( Meta::valTitle, QVariant( "Say It to Me Now" ) ); values.insert( Meta::valArtist, QVariant( "Glen Hansard" ) ); values.insert( Meta::valAlbum, QVariant( "Once" ) ); values.insert( Meta::valAlbumArtist, QVariant( "Glen Hansard & Markéta Irglová" ) ); values.insert( Meta::valTrackNr, QVariant( "13" ) ); createTrack( values ); } void TestSqlScanManager::createCompilationTrack() { Meta::FieldHash values; values.insert( Meta::valUniqueId, QVariant("c6c29f50279ab9523a0f44928bc1e96b") ); values.insert( Meta::valUrl, QVariant("Amazon MP3/The Sum Of All Fears (O.S.T.)/The Sum of All Fears/01 - If We Could Remember (O.S.T. LP Version).mp3") ); values.insert( Meta::valFormat, QVariant("1") ); values.insert( Meta::valTitle, QVariant("If We Could Remember (O.S.T. LP Version)") ); values.insert( Meta::valArtist, QVariant("The Sum Of All Fears (O.S.T.)/Yolanda Adams") ); values.insert( Meta::valAlbumArtist, QVariant("The Sum Of All Fears (O.S.T.)") ); values.insert( Meta::valAlbum, QVariant("The Sum of All Fears") ); values.insert( Meta::valComment, QVariant("Amazon.com Song ID: 203452096") ); values.insert( Meta::valGenre, QVariant("Soundtracks") ); values.insert( Meta::valYear, QVariant("2002") ); values.insert( Meta::valTrackNr, QVariant("1") ); values.insert( Meta::valComposer, QVariant("Jerry Goldsmith") ); values.insert( Meta::valScore, QVariant("0.875") ); values.insert( Meta::valPlaycount, QVariant("6") ); createTrack( values ); values.clear(); values.insert( Meta::valUniqueId, QVariant("2188afd457cd75a363905f411966b9a0") ); values.insert( Meta::valUrl, QVariant("The Cross Of Changes/01 - Second Chapter.mp3") ); values.insert( Meta::valFormat, QVariant(1) ); values.insert( Meta::valTitle, QVariant("Second Chapter") ); values.insert( Meta::valArtist, QVariant("Enigma") ); values.insert( Meta::valAlbumArtist, QVariant("Enigma") ); values.insert( Meta::valAlbum, QVariant("The Cross Of Changes") ); values.insert( Meta::valComment, QVariant("Amazon.com Song ID: 201985325") ); values.insert( Meta::valGenre, QVariant("Pop") ); values.insert( Meta::valYear, QVariant(2004) ); values.insert( Meta::valTrackNr, QVariant(1) ); values.insert( Meta::valComposer, QVariant("Curly M.C.") ); values.insert( Meta::valScore, QVariant("0.54") ); values.insert( Meta::valPlaycount, QVariant("2") ); values.insert( Meta::valUniqueId, QVariant("637bee4fd456d2ff9eafe65c71ba192e") ); values.insert( Meta::valUrl, QVariant("The Cross Of Changes/02 - The Eyes Of Truth.mp3") ); values.insert( Meta::valFormat, QVariant("1") ); values.insert( Meta::valTitle, QVariant("The Eyes Of Truth") ); values.insert( Meta::valArtist, QVariant("Enigma") ); values.insert( Meta::valAlbumArtist, QVariant("Enigma") ); values.insert( Meta::valAlbum, QVariant("The Cross Of Changes") ); values.insert( Meta::valComment, QVariant("Amazon.com Song ID: 201985326") ); values.insert( Meta::valGenre, QVariant("Pop") ); values.insert( Meta::valYear, QVariant("2004") ); values.insert( Meta::valTrackNr, QVariant("2") ); values.insert( Meta::valComposer, QVariant("Curly M.C.") ); values.insert( Meta::valScore, QVariant("0.928572") ); values.insert( Meta::valPlaycount, QVariant("1286469632") ); values.insert( Meta::valUniqueId, QVariant("b4206da4bc0335d76c2bbc5d4c1b164c") ); values.insert( Meta::valUrl, QVariant("The Cross Of Changes/03 - Return To Innocence.mp3") ); values.insert( Meta::valFormat, QVariant("1") ); values.insert( Meta::valTitle, QVariant("Return To Innocence") ); values.insert( Meta::valArtist, QVariant("Enigma") ); values.insert( Meta::valAlbumArtist, QVariant("Enigma") ); values.insert( Meta::valAlbum, QVariant("The Cross Of Changes") ); values.insert( Meta::valComment, QVariant("Amazon.com Song ID: 201985327") ); values.insert( Meta::valGenre, QVariant("Pop") ); values.insert( Meta::valYear, QVariant("2004") ); values.insert( Meta::valTrackNr, QVariant("3") ); values.insert( Meta::valComposer, QVariant("Curly M.C.") ); values.insert( Meta::valScore, QVariant("0.75") ); values.insert( Meta::valPlaycount, QVariant("1286469888") ); values.insert( Meta::valUniqueId, QVariant("eb0061602f52d67140fd465dc275fbf2") ); values.insert( Meta::valUrl, QVariant("The Cross Of Changes/04 - I Love You...I'Ll Kill You.mp3") ); values.insert( Meta::valFormat, 1 ); values.insert( Meta::valTitle, QVariant("I Love You...I'Ll Kill You") ); values.insert( Meta::valArtist, QVariant("Enigma") ); values.insert( Meta::valAlbumArtist, QVariant("Enigma") ); values.insert( Meta::valAlbum, QVariant("The Cross Of Changes") ); values.insert( Meta::valComment, QVariant("Amazon.com Song ID: 201985328") ); values.insert( Meta::valGenre, QVariant("Pop") ); values.insert( Meta::valYear, QVariant(2004) ); values.insert( Meta::valTrackNr, QVariant(4) ); values.insert( Meta::valComposer, QVariant("Curly M.C.") ); values.insert( Meta::valScore, QVariant(0.5) ); values.insert( Meta::valPlaycount, QVariant(1286470656) ); values.insert( Meta::valUniqueId, QVariant("94dabc09509379646458f62bee7e41ed") ); values.insert( Meta::valUrl, QVariant("The Cross Of Changes/05 - Silent Warrior.mp3") ); values.insert( Meta::valFormat, 1 ); values.insert( Meta::valTitle, QVariant("Silent Warrior") ); values.insert( Meta::valArtist, QVariant("Enigma") ); values.insert( Meta::valAlbumArtist, QVariant("Enigma") ); values.insert( Meta::valAlbum, QVariant("The Cross Of Changes") ); values.insert( Meta::valComment, QVariant("Amazon.com Song ID: 201985329") ); values.insert( Meta::valGenre, QVariant("Pop") ); values.insert( Meta::valYear, QVariant(2004) ); values.insert( Meta::valTrackNr, QVariant(5) ); values.insert( Meta::valComposer, QVariant("Curly M.C.") ); values.insert( Meta::valScore, QVariant(0.96875) ); values.insert( Meta::valPlaycount, QVariant(6) ); values.insert( Meta::valUniqueId, QVariant("6ae759476c34256ff1d06f0b5c964d75") ); values.insert( Meta::valUrl, QVariant("The Cross Of Changes/06 - The Dream Of The Dolphin.mp3") ); values.insert( Meta::valTitle, QVariant("The Dream Of The Dolphin") ); values.insert( Meta::valArtist, QVariant("Enigma") ); values.insert( Meta::valAlbumArtist, QVariant("Enigma") ); values.insert( Meta::valAlbum, QVariant("The Cross Of Changes") ); values.insert( Meta::valComment, QVariant("Amazon.com Song ID: 201985330") ); values.insert( Meta::valGenre, QVariant("Pop") ); values.insert( Meta::valYear, QVariant("2004") ); values.insert( Meta::valTrackNr, QVariant(6) ); values.insert( Meta::valComposer, QVariant("Curly M.C.") ); values.insert( Meta::valScore, QVariant(0.5) ); values.insert( Meta::valPlaycount, QVariant(2) ); values.insert( Meta::valUniqueId, QVariant("7957bc25521c1dc91351d497321c27a6") ); values.insert( Meta::valUrl, QVariant("Amazon MP3/Ashford & Simpson/Solid/01 - Solid.mp3") ); values.insert( Meta::valTitle, QVariant("Solid") ); values.insert( Meta::valArtist, QVariant("Ashford & Simpson") ); values.insert( Meta::valAlbumArtist, QVariant("Ashford & Simpson") ); values.insert( Meta::valAlbum, QVariant("Solid") ); values.insert( Meta::valComment, QVariant("Amazon.com Song ID: 202265871") ); values.insert( Meta::valGenre, QVariant("Pop") ); values.insert( Meta::valYear, QVariant(2007) ); values.insert( Meta::valTrackNr, QVariant(1) ); values.insert( Meta::valComposer, QVariant("Valerie Simpson") ); values.insert( Meta::valRating, QVariant(0.898438) ); values.insert( Meta::valScore, QVariant(0.875) ); values.insert( Meta::valPlaycount, QVariant(12) ); } diff --git a/tests/core-impl/collections/db/sql/TestSqlTrack.cpp b/tests/core-impl/collections/db/sql/TestSqlTrack.cpp index c11abb1850..752171930f 100644 --- a/tests/core-impl/collections/db/sql/TestSqlTrack.cpp +++ b/tests/core-impl/collections/db/sql/TestSqlTrack.cpp @@ -1,561 +1,561 @@ /**************************************************************************************** * Copyright (c) 2010 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestSqlTrack.h" #include "amarokconfig.h" #include "DefaultSqlQueryMakerFactory.h" #include "core/meta/Meta.h" #include "core-impl/storage/sql/mysqlestorage/MySqlEmbeddedStorage.h" #include "SqlCollection.h" #include "SqlMeta.h" #include "SqlRegistry.h" #include "SqlMountPointManagerMock.h" #include "MetaNotificationSpy.h" #include #include -QTEST_MAIN( TestSqlTrack ) +QTEST_GUILESS_MAIN( TestSqlTrack ) TestSqlTrack::TestSqlTrack() : QObject() , m_collection( 0 ) , m_storage( 0 ) , m_tmpDir( 0 ) { } void TestSqlTrack::initTestCase() { AmarokConfig::instance("amarokrc"); m_tmpDir = new QTemporaryDir(); m_storage = QSharedPointer( new MySqlEmbeddedStorage() ); QVERIFY( m_storage->init( m_tmpDir->path() ) ); m_collection = new Collections::SqlCollection( m_storage ); m_collection->setMountPointManager( new SqlMountPointManagerMock( this, m_storage ) ); // I just need the table and not the whole playlist manager m_storage->query( QString( "CREATE TABLE playlist_tracks (" " id " + m_storage->idType() + ", playlist_id INTEGER " ", track_num INTEGER " ", url " + m_storage->exactTextColumnType() + ", title " + m_storage->textColumnType() + ", album " + m_storage->textColumnType() + ", artist " + m_storage->textColumnType() + ", length INTEGER " ", uniqueid " + m_storage->textColumnType(128) + ") ENGINE = MyISAM;" ) ); } void TestSqlTrack::cleanupTestCase() { delete m_collection; //m_storage is deleted by SqlCollection delete m_tmpDir; } void TestSqlTrack::init() { //setup base data m_storage->query( "INSERT INTO artists(id, name) VALUES (1, 'artist1');" ); m_storage->query( "INSERT INTO artists(id, name) VALUES (2, 'artist2');" ); m_storage->query( "INSERT INTO artists(id, name) VALUES (3, 'artist3');" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(1,'album1',1);" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(2,'album2',1);" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(3,'album3',2);" ); m_storage->query( "INSERT INTO albums(id,name,artist) VALUES(4,'album-compilation',0);" ); m_storage->query( "INSERT INTO composers(id, name) VALUES (1, 'composer1');" ); m_storage->query( "INSERT INTO composers(id, name) VALUES (2, 'composer2');" ); m_storage->query( "INSERT INTO composers(id, name) VALUES (3, 'composer3');" ); m_storage->query( "INSERT INTO genres(id, name) VALUES (1, 'genre1');" ); m_storage->query( "INSERT INTO genres(id, name) VALUES (2, 'genre2');" ); m_storage->query( "INSERT INTO genres(id, name) VALUES (3, 'genre3');" ); m_storage->query( "INSERT INTO years(id, name) VALUES (1, '1');" ); m_storage->query( "INSERT INTO years(id, name) VALUES (2, '2');" ); m_storage->query( "INSERT INTO years(id, name) VALUES (3, '3');" ); m_storage->query( "INSERT INTO directories(id, deviceid, dir) VALUES (1, -1, './');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES (1, -1, './IDoNotExist.mp3', 1, '1');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES (2, -1, './IDoNotExistAsWell.mp3', 1, '2');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES (3, -1, './MeNeither.mp3', 1, '3');" ); m_storage->query( "INSERT INTO urls(id, deviceid, rpath, directory, uniqueid) VALUES (4, -1, './NothingHere.mp3', 1, '4');" ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(1,1,'track1','comment1',1,1,1,1,1);" ); m_storage->query( "INSERT INTO tracks(id,url,title,comment,artist,album,genre,year,composer) " "VALUES(2,2,'track2','comment2',1,2,1,1,1);" ); m_collection->registry()->emptyCache(); } void TestSqlTrack::cleanup() { m_storage->query( "TRUNCATE TABLE years;" ); m_storage->query( "TRUNCATE TABLE genres;" ); m_storage->query( "TRUNCATE TABLE composers;" ); m_storage->query( "TRUNCATE TABLE albums;" ); m_storage->query( "TRUNCATE TABLE artists;" ); m_storage->query( "TRUNCATE TABLE tracks;" ); m_storage->query( "TRUNCATE TABLE urls;" ); m_storage->query( "TRUNCATE TABLE directories;" ); m_storage->query( "TRUNCATE TABLE statistics;" ); m_storage->query( "TRUNCATE TABLE labels;" ); m_storage->query( "TRUNCATE TABLE urls_labels;" ); } void TestSqlTrack::setAllValues( Meta::SqlTrack *track ) { track->setTitle( "New Title" ); track->setAlbum( "New Album" ); track->setArtist( "New Artist" ); track->setComposer( "New Composer" ); track->setYear( 1999 ); track->setGenre( "New Genre" ); track->setUrl( -1, "./new_url", 2 ); track->setBpm( 32.0 ); track->setComment( "New Comment" ); track->setScore( 64.0 ); track->setRating( 5 ); track->setLength( 5000 ); track->setSampleRate( 4400 ); track->setBitrate( 128 ); track->setTrackNumber( 4 ); track->setDiscNumber( 1 ); track->setFirstPlayed( QDateTime::fromTime_t(100) ); track->setLastPlayed( QDateTime::fromTime_t(200) ); track->setPlayCount( 20 ); Meta::ReplayGainTag modes[] = { Meta::ReplayGain_Track_Gain, Meta::ReplayGain_Track_Peak, Meta::ReplayGain_Album_Gain, Meta::ReplayGain_Album_Peak }; for( int i=0; i<4; i++ ) track->setReplayGain( modes[i], qreal(i) ); track->addLabel( "New Label" ); } void TestSqlTrack::getAllValues( Meta::SqlTrack *track ) { QCOMPARE( track->name(), QString( "New Title" ) ); QCOMPARE( track->album()->name(), QString( "New Album" ) ); QCOMPARE( track->artist()->name(), QString( "New Artist" ) ); QCOMPARE( track->composer()->name(), QString( "New Composer" ) ); QCOMPARE( track->year()->name(), QString( "1999" ) ); QCOMPARE( track->genre()->name(), QString( "New Genre" ) ); QCOMPARE( track->playableUrl().path(), QString( "/new_url" ) ); QCOMPARE( track->bpm(), 32.0 ); QCOMPARE( track->comment(), QString( "New Comment" ) ); QCOMPARE( track->score(), 64.0 ); QCOMPARE( track->rating(), 5 ); QCOMPARE( track->length(), qint64(5000) ); QCOMPARE( track->sampleRate(), 4400 ); QCOMPARE( track->bitrate(), 128 ); QCOMPARE( track->trackNumber(), 4 ); QCOMPARE( track->discNumber(), 1 ); QCOMPARE( track->firstPlayed(), QDateTime::fromTime_t(100) ); QCOMPARE( track->lastPlayed(), QDateTime::fromTime_t(200) ); QCOMPARE( track->playCount(), 20 ); Meta::ReplayGainTag modes[] = { Meta::ReplayGain_Track_Gain, Meta::ReplayGain_Track_Peak, Meta::ReplayGain_Album_Gain, Meta::ReplayGain_Album_Peak }; for( int i=0; i<4; i++ ) QCOMPARE( track->replayGain( modes[i] ), qreal(i) ); QVERIFY( track->labels().count() > 0 ); QVERIFY( track->labels().contains( m_collection->registry()->getLabel("New Label") ) ); } /** Check that the registry always returns the same track pointer */ void TestSqlTrack::testGetTrack() { { Meta::TrackPtr track1 = m_collection->registry()->getTrack( 1 ); Meta::TrackPtr track2 = m_collection->registry()->getTrack( "/IDoNotExist.mp3" ); Meta::TrackPtr track3 = m_collection->registry()->getTrackFromUid( "1" ); QVERIFY( track1 ); QVERIFY( track1 == track2 ); QVERIFY( track1 == track3 ); } // and also after empty cache m_collection->registry()->emptyCache(); // changed order... { Meta::TrackPtr track2 = m_collection->registry()->getTrack( "/IDoNotExist.mp3" ); Meta::TrackPtr track3 = m_collection->registry()->getTrackFromUid( "1" ); Meta::TrackPtr track1 = m_collection->registry()->getTrack( 1 ); QVERIFY( track1 ); QVERIFY( track1 == track2 ); QVERIFY( track1 == track3 ); } // do again creating a new track cleanup(); m_collection->registry()->emptyCache(); // changed order... { Meta::TrackPtr track1 = m_collection->registry()->getTrack( -1, "./newTrack.mp3", 2, "amarok-sqltrackuid://newuid" ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); sqlTrack1->setBpm( 100 ); // have to commit the new track QVERIFY( track1 ); QCOMPARE( track1->playableUrl().path(), QString("/newTrack.mp3" )); QCOMPARE( track1->uidUrl(), QString("amarok-sqltrackuid://newuid" )); } m_collection->registry()->emptyCache(); // changed order... { Meta::TrackPtr track1 = m_collection->registry()->getTrackFromUid("amarok-sqltrackuid://newuid"); QVERIFY( track1 ); QCOMPARE( track1->playableUrl().path(), QString("/newTrack.mp3" )); QCOMPARE( track1->uidUrl(), QString("amarok-sqltrackuid://newuid" )); QCOMPARE( track1->bpm(), 100.0 ); } } void TestSqlTrack::testSetAllValuesSingleNotExisting() { { // get a new track Meta::TrackPtr track1 = m_collection->registry()->getTrack( -1, "./IamANewTrack.mp3", 1, "1e34fb213489" ); QSignalSpy spy( m_collection, &Collections::SqlCollection::updated); MetaNotificationSpy metaSpy; metaSpy.subscribeTo( track1 ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); setAllValues( sqlTrack1 ); getAllValues( sqlTrack1 ); // new track should have an up-to-date create time (not more than 3 seconds old) QVERIFY( track1->createDate().secsTo(QDateTime::currentDateTime()) < 3 ); QVERIFY( metaSpy.notificationsFromTracks().count() > 1 ); // we should be notified about the changes } // and also after empty cache m_collection->registry()->emptyCache(); { Meta::TrackPtr track1 = m_collection->registry()->getTrack( "/new_url" ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); QVERIFY( track1 ); getAllValues( sqlTrack1 ); } } /** Set all track values but before that create them in the registry. */ void TestSqlTrack::testSetAllValuesSingleExisting() { { Meta::GenrePtr genre = m_collection->registry()->getGenre( "New Genre" ); Meta::ComposerPtr composer = m_collection->registry()->getComposer( "New Composer" ); Meta::YearPtr year = m_collection->registry()->getYear( 1999 ); Meta::AlbumPtr album = m_collection->registry()->getAlbum( "New Album", "New Artist" ); m_collection->registry()->getLabel( "New Label" ); Meta::TrackPtr track1 = m_collection->registry()->getTrack( "/IDoNotExist.mp3" ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); setAllValues( sqlTrack1 ); getAllValues( sqlTrack1 ); // check that the existing object are really updated with the new tracklist QCOMPARE( genre->tracks().count(), 1 ); QCOMPARE( genre->tracks().first().data(), track1.data() ); QCOMPARE( composer->tracks().count(), 1 ); QCOMPARE( composer->tracks().first().data(), track1.data() ); QCOMPARE( year->tracks().count(), 1 ); QCOMPARE( year->tracks().first().data(), track1.data() ); // the logic, how renaming the track artist influences its album is still // unfinished. For sure the track must be in an album with the defined // name QCOMPARE( sqlTrack1->album()->name(), QString("New Album") ); QCOMPARE( sqlTrack1->album()->tracks().count(), 1 ); QCOMPARE( sqlTrack1->album()->tracks().first().data(), track1.data() ); } // and also after empty cache m_collection->registry()->emptyCache(); { Meta::TrackPtr track1 = m_collection->registry()->getTrack( "/new_url" ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); QVERIFY( track1 ); getAllValues( sqlTrack1 ); Meta::GenrePtr genre = m_collection->registry()->getGenre( "New Genre" ); Meta::ComposerPtr composer = m_collection->registry()->getComposer( "New Composer" ); Meta::YearPtr year = m_collection->registry()->getYear( 1999 ); Meta::AlbumPtr album = m_collection->registry()->getAlbum( "New Album", "New Artist" ); // check that the existing object are really updated with the new tracklist QCOMPARE( genre->tracks().count(), 1 ); QCOMPARE( genre->tracks().first().data(), track1.data() ); QCOMPARE( composer->tracks().count(), 1 ); QCOMPARE( composer->tracks().first().data(), track1.data() ); QCOMPARE( year->tracks().count(), 1 ); QCOMPARE( year->tracks().first().data(), track1.data() ); // the logic, how renaming the track artist influences its album is still // unfinished. For sure the track must be in an album with the defined // name QCOMPARE( sqlTrack1->album()->name(), QString("New Album") ); QCOMPARE( sqlTrack1->album()->tracks().count(), 1 ); QCOMPARE( sqlTrack1->album()->tracks().first().data(), track1.data() ); } } void TestSqlTrack::testSetAllValuesBatch() { { Meta::TrackPtr track1 = m_collection->registry()->getTrack( "/IDoNotExist.mp3" ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); QSignalSpy spy( m_collection, &Collections::SqlCollection::updated); MetaNotificationSpy metaSpy; metaSpy.subscribeTo( track1 ); sqlTrack1->beginUpdate(); setAllValues( sqlTrack1 ); QCOMPARE( metaSpy.notificationsFromTracks().count(), 1 ); // add label does one notify sqlTrack1->endUpdate(); QCOMPARE( metaSpy.notificationsFromTracks().count(), 2 ); // only one notificate for all the changes getAllValues( sqlTrack1 ); } // and also after empty cache m_collection->registry()->emptyCache(); { Meta::TrackPtr track1 = m_collection->registry()->getTrack( "/new_url" ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); QVERIFY( track1 ); getAllValues( sqlTrack1 ); } } void TestSqlTrack::testUnsetValues() { { Meta::TrackPtr track1 = m_collection->registry()->getTrack( "/IDoNotExist.mp3" ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); setAllValues( sqlTrack1 ); // now unset the values again sqlTrack1->setAlbum( "" ); sqlTrack1->setArtist( "" ); sqlTrack1->setComposer( "" ); sqlTrack1->setYear( 0 ); // it is not clear what an empty year exactly is sqlTrack1->setGenre( "" ); // note: Amarok is still not clear if an empty artist means track->artist() == 0 QVERIFY( !track1->album() || track1->album()->name().isEmpty() ); QVERIFY( !track1->artist() || track1->artist()->name().isEmpty() ); QVERIFY( !track1->composer() || track1->composer()->name().isEmpty() ); QVERIFY( !track1->year() || track1->year()->year() == 0 ); QVERIFY( !track1->genre() || track1->genre()->name().isEmpty() ); } // and also after empty cache m_collection->registry()->emptyCache(); { Meta::TrackPtr track1 = m_collection->registry()->getTrack( "/new_url" ); QVERIFY( track1 ); QVERIFY( !track1->album() || track1->album()->name().isEmpty() ); QVERIFY( !track1->artist() || track1->artist()->name().isEmpty() ); QVERIFY( !track1->composer() || track1->composer()->name().isEmpty() ); QVERIFY( !track1->year() || track1->year()->year() == 0 ); QVERIFY( !track1->genre() || track1->genre()->name().isEmpty() ); } } void TestSqlTrack::testFinishedPlaying() { Meta::TrackPtr track1 = m_collection->registry()->getTrack( "/IDoNotExist.mp3" ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); sqlTrack1->setLength( 5000 ); QCOMPARE( sqlTrack1->score(), 0.0 ); QCOMPARE( sqlTrack1->playCount(), 0 ); QVERIFY( !sqlTrack1->firstPlayed().isValid() ); QVERIFY( !sqlTrack1->lastPlayed().isValid() ); // now play the track not really sqlTrack1->finishedPlaying( 0.1 ); // can't do a statement about the score here QCOMPARE( sqlTrack1->playCount(), 0 ); QVERIFY( !sqlTrack1->firstPlayed().isValid() ); QVERIFY( !sqlTrack1->lastPlayed().isValid() ); // and now really play it sqlTrack1->finishedPlaying( 1.0 ); QVERIFY( sqlTrack1->score() > 0.0 ); QCOMPARE( sqlTrack1->playCount(), 1 ); QVERIFY( sqlTrack1->firstPlayed().secsTo( QDateTime::currentDateTime() ) < 2 ); QVERIFY( sqlTrack1->lastPlayed().secsTo( QDateTime::currentDateTime() ) < 2 ); } void TestSqlTrack::testAlbumRemaingsNonCompilationAfterChangingAlbumName() { m_storage->query( "INSERT INTO tracks(id,url,title,artist,album,genre,year,composer) " "VALUES (3,3,'track1',1,1,1,1,1 );" ); m_storage->query( "INSERT INTO tracks(id,url,title,artist,album,genre,year,composer) " "VALUES (4,4,'track2',1,1,1,1,1 );" ); Meta::TrackPtr track1 = m_collection->registry()->getTrack( 3 ); Meta::TrackPtr track2 = m_collection->registry()->getTrack( 4 ); QCOMPARE( track1->album()->name(), QString( "album1" ) ); QVERIFY( track1->album()->hasAlbumArtist() ); QCOMPARE( track1->album().data(), track2->album().data() ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); sqlTrack1->setAlbum( "album2" ); Meta::SqlTrack *sqlTrack2 = static_cast( track2.data() ); sqlTrack2->beginUpdate(); sqlTrack2->setAlbum( "album2" ); sqlTrack2->endUpdate(); QCOMPARE( track1->album()->name(), QString( "album2" ) ); QVERIFY( track1->album()->hasAlbumArtist() ); QVERIFY( track1->album() == track2->album() ); } void TestSqlTrack::testAlbumRemainsCompilationAfterChangingAlbumName() { m_storage->query( "INSERT INTO tracks(id,url,title,artist,album,genre,year,composer) " "VALUES (3,3,'track1',1,4,1,1,1 );" ); m_storage->query( "INSERT INTO tracks(id,url,title,artist,album,genre,year,composer) " "VALUES (4,4,'track2',1,4,1,1,1 );" ); Meta::TrackPtr track1 = m_collection->registry()->getTrack( 3 ); Meta::TrackPtr track2 = m_collection->registry()->getTrack( 4 ); QVERIFY( track1 ); QVERIFY( track1->album() ); QVERIFY( track2 ); QVERIFY( track2->album() ); QCOMPARE( track1->album()->name(), QString( "album-compilation" ) ); QVERIFY( track1->album()->isCompilation() ); QVERIFY( track1->album().data() == track2->album().data() ); Meta::SqlTrack *sqlTrack1 = static_cast( track1.data() ); Meta::SqlTrack *sqlTrack2 = static_cast( track2.data() ); sqlTrack1->setAlbum( "album2" ); sqlTrack2->beginUpdate(); sqlTrack2->setAlbum( "album2" ); sqlTrack2->endUpdate(); QCOMPARE( track1->album()->name(), QString( "album2" ) ); QVERIFY( track1->album()->isCompilation() ); QVERIFY( track1->album() == track2->album() ); } void TestSqlTrack::testRemoveLabelFromTrack() { Meta::TrackPtr track = m_collection->registry()->getTrack( "/IDoNotExist.mp3" ); Meta::LabelPtr label = m_collection->registry()->getLabel( "A" ); track->addLabel( label ); QCOMPARE( track->labels().count(), 1 ); track->removeLabel( label ); QCOMPARE( track->labels().count(), 0 ); QStringList urlsLabelsCount = m_storage->query( "SELECT COUNT(*) FROM urls_labels;" ); QCOMPARE( urlsLabelsCount.first().toInt(), 0 ); } void TestSqlTrack::testRemoveLabelFromTrackWhenNotInCache() { m_storage->query( "INSERT INTO labels(id,label) VALUES (1,'A');" ); m_storage->query( "INSERT INTO urls_labels(url,label) VALUES (1,1);" ); Meta::TrackPtr track = m_collection->registry()->getTrack( "/IDoNotExist.mp3" ); Meta::LabelPtr label = m_collection->registry()->getLabel( "A" ); track->removeLabel( label ); QCOMPARE( track->labels().count(), 0 ); QStringList urlsLabelsCount = m_storage->query( "SELECT COUNT(*) FROM urls_labels;" ); QCOMPARE( urlsLabelsCount.first().toInt(), 0 ); } diff --git a/tests/core-impl/collections/support/TestArtistHelper.cpp b/tests/core-impl/collections/support/TestArtistHelper.cpp index e2bbb8c1e1..e5626aa8ba 100644 --- a/tests/core-impl/collections/support/TestArtistHelper.cpp +++ b/tests/core-impl/collections/support/TestArtistHelper.cpp @@ -1,54 +1,54 @@ /**************************************************************************************** * Copyright (c) 2010 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestArtistHelper.h" #include -QTEST_MAIN( TestArtistHelper ) +QTEST_GUILESS_MAIN( TestArtistHelper ) TestArtistHelper::TestArtistHelper() : QObject() { } void TestArtistHelper::testRealTrackArtist_data() { QTest::addColumn( "artistTag" ); QTest::addColumn( "realArtist" ); QTest::newRow( "no ft." ) << "Artist A" << "Artist A"; QTest::newRow( "A ft. B") << "A ft. B" << "A"; QTest::newRow( "A feat. B" ) << "A feat. B" << "A"; QTest::newRow( "A featuring B" ) << "A featuring B" << "A"; QTest::newRow( "A f. B" ) << "A f. B" << "A"; //QTest::newRow( "artist including ft. string" ) << "Aft.B" << "Aft.B"; //not possible according to ML discussion QTest::newRow( "empty A, return original string" ) << " featuring B" << " featuring B"; QTest::newRow( "A (feat. B)" ) << "A (feat. B )" << "A"; QTest::newRow( "A [feat. B]" ) << "A [feat. B]" << "A"; } void TestArtistHelper::testRealTrackArtist() { QFETCH( QString, artistTag ); QFETCH( QString, realArtist ); QCOMPARE( ArtistHelper::realTrackArtist( artistTag ), realArtist ); } diff --git a/tests/core-impl/collections/support/TestMemoryQueryMaker.cpp b/tests/core-impl/collections/support/TestMemoryQueryMaker.cpp index f47da9a9d9..7bab300564 100644 --- a/tests/core-impl/collections/support/TestMemoryQueryMaker.cpp +++ b/tests/core-impl/collections/support/TestMemoryQueryMaker.cpp @@ -1,296 +1,296 @@ /**************************************************************************************** * Copyright (c) 2010 Maximilian Kossick * * Copyright (c) 2011 Ralf Engels * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestMemoryQueryMaker.h" #include "mocks/MetaMock.h" #include "mocks/MockTrack.h" #include "FileType.h" #include #include #include #include using ::testing::AnyNumber; using ::testing::Return; -QTEST_MAIN( TestMemoryQueryMaker ) +QTEST_GUILESS_MAIN( TestMemoryQueryMaker ) TestMemoryQueryMaker::TestMemoryQueryMaker() { int argc = 1; char **argv = (char **) malloc(sizeof(char *)); argv[0] = strdup( QCoreApplication::applicationName().toLocal8Bit().data() ); ::testing::InitGoogleMock( &argc, argv ); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); } void TestMemoryQueryMaker::initTestCase() { // prepare a memory collection with some test data m_mc = QSharedPointer( new Collections::MemoryCollection() ); MetaMock *track; QVariantMap map; map.insert( Meta::Field::UNIQUEID, "1" ); map.insert( Meta::Field::TITLE, "Skater Boy" ); map.insert( Meta::Field::RATING, 3 ); // map.insert( Meta::Field::TYPE, int(Amarok::Mp3) ); map.insert( Meta::Field::TRACKNUMBER, 3 ); track = new MetaMock( map ); track->m_artist = new MockArtist("Avril Lavigne"); track->m_album = new MockAlbum("Let Go"); m_mc->addTrack( Meta::TrackPtr( track ) ); map.insert( Meta::Field::UNIQUEID, "2" ); map.insert( Meta::Field::TITLE, "Substitute" ); map.insert( Meta::Field::RATING, 4 ); // map.insert( Meta::Field::TYPE, int(Amarok::Ogg) ); map.insert( Meta::Field::TRACKNUMBER, 1 ); track = new MetaMock( map ); track->m_artist = new MockArtist("Clout" ); track->m_album = new MockAlbum("Substitute" ); m_mc->addTrack( Meta::TrackPtr( track ) ); map.insert( Meta::Field::UNIQUEID, "3" ); map.insert( Meta::Field::TITLE, "I Say A Little Prayer" ); map.insert( Meta::Field::RATING, 2 ); // map.insert( Meta::Field::TYPE, int(Amarok::Wma) ); map.insert( Meta::Field::TRACKNUMBER, 1 ); map.insert( Meta::Field::DISCNUMBER, 2 ); track = new MetaMock( map ); track->m_artist = new MockArtist("The Bosshoss" ); track->m_album = new MockAlbum("Rodeo Radio" ); m_mc->addTrack( Meta::TrackPtr( track ) ); } void TestMemoryQueryMaker::cleanupTestCase() { } void TestMemoryQueryMaker::testDeleteQueryMakerWhileQueryIsRunning() { QSharedPointer mc( new Collections::MemoryCollection() ); mc->addTrack( Meta::TrackPtr( new MetaMock( QVariantMap() ))); mc->addTrack( Meta::TrackPtr( new MetaMock( QVariantMap() ))); Meta::MockTrack *mock = new Meta::MockTrack(); EXPECT_CALL( *mock, uidUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( "track3" ) ); Meta::TrackPtr trackPtr( mock ); mc->addTrack( trackPtr ); Collections::MemoryQueryMaker *qm = new Collections::MemoryQueryMaker( mc.toWeakRef(), "test" ); qm->setQueryType( Collections::QueryMaker::Track ); qm->run(); delete qm; //we cannot wait for a signal here.... //QTest::qWait( 500 ); } void TestMemoryQueryMaker::testDeleteCollectionWhileQueryIsRunning() { QSharedPointer mc( new Collections::MemoryCollection() ); mc->addTrack( Meta::TrackPtr( new MetaMock( QVariantMap() ))); mc->addTrack( Meta::TrackPtr( new MetaMock( QVariantMap() ))); Collections::MemoryQueryMaker *qm = new Collections::MemoryQueryMaker( mc, "test" ); qm->setQueryType( Collections::QueryMaker::Track ); QSignalSpy spy( qm, &Collections::QueryMaker::queryDone); qm->run(); mc.clear(); QTest::qWait( 500 ); QCOMPARE( spy.count(), 1 ); delete qm; } class TestStringMemoryFilter : public StringMemoryFilter { public: TestStringMemoryFilter() : StringMemoryFilter() {} protected: QString value( Meta::TrackPtr track ) const { Q_UNUSED(track); return "abcdef"; } }; void TestMemoryQueryMaker::testStringMemoryFilterSpeedFullMatch() { //Test 1: match complete string TestStringMemoryFilter filter1; filter1.setFilter( QString( "abcdef" ), true, true ); QBENCHMARK { filter1.filterMatches( Meta::TrackPtr() ); } } void TestMemoryQueryMaker::testStringMemoryFilterSpeedMatchBegin() { //Test 2: match beginning of string TestStringMemoryFilter filter2; filter2.setFilter( QString( "abcd" ), true, false ); QBENCHMARK { filter2.filterMatches( Meta::TrackPtr() ); } } void TestMemoryQueryMaker::testStringMemoryFilterSpeedMatchEnd() { //Test 3: match end of string TestStringMemoryFilter filter3; filter3.setFilter( QString( "cdef" ), false, true ); QBENCHMARK { filter3.filterMatches( Meta::TrackPtr() ); } } void TestMemoryQueryMaker::testStringMemoryFilterSpeedMatchAnywhere() { //Test 4: match anywhere in string TestStringMemoryFilter filter4; filter4.setFilter( QString( "bcde" ), false, false ); QBENCHMARK { filter4.filterMatches( Meta::TrackPtr() ); } } Meta::TrackList TestMemoryQueryMaker::executeQueryMaker( Collections::QueryMaker *qm ) { QSignalSpy doneSpy1( qm, &Collections::QueryMaker::queryDone ); QSignalSpy resultSpy1( qm, &Collections::QueryMaker::newTracksReady ); qm->setQueryType( Collections::QueryMaker::Track ); qm->run(); doneSpy1.wait( 1000 ); if( resultSpy1.count() != 1 ) return Meta::TrackList(); if( doneSpy1.count() != 1 ) return Meta::TrackList(); QList args1 = resultSpy1.takeFirst(); if( !args1.value(0).canConvert() ) return Meta::TrackList(); delete qm; return args1.value(0).value(); } void TestMemoryQueryMaker::testFilterTitle() { Meta::TrackList tracks; // -- just get all the tracks Collections::MemoryQueryMaker *qm = new Collections::MemoryQueryMaker( m_mc.toWeakRef(), "test" ); tracks = executeQueryMaker( qm ); QCOMPARE( tracks.count(), 3 ); // -- filter for title qm = new Collections::MemoryQueryMaker( m_mc.toWeakRef(), "test" ); qm->addFilter( Meta::valTitle, "Skater", true, false ); tracks = executeQueryMaker( qm ); QCOMPARE( tracks.count(), 1 ); QCOMPARE( tracks.first()->name(), QString("Skater Boy" ) ); // -- filter for album qm = new Collections::MemoryQueryMaker( m_mc.toWeakRef(), "test" ); qm->addFilter( Meta::valAlbum, "S", false, false ); tracks = executeQueryMaker( qm ); QCOMPARE( tracks.count(), 1 ); QCOMPARE( tracks.first()->name(), QString("Substitute" ) ); // -- filter for artist qm = new Collections::MemoryQueryMaker( m_mc.toWeakRef(), "test" ); qm->addFilter( Meta::valArtist, "Lavigne", false, true ); tracks = executeQueryMaker( qm ); QCOMPARE( tracks.count(), 1 ); QCOMPARE( tracks.first()->name(), QString("Skater Boy" ) ); } void TestMemoryQueryMaker::testFilterRating() { Meta::TrackList tracks; Collections::MemoryQueryMaker *qm = 0; // -- filter for Rating qm = new Collections::MemoryQueryMaker( m_mc.toWeakRef(), "test" ); qm->addNumberFilter( Meta::valRating, 3, Collections::QueryMaker::Equals ); tracks = executeQueryMaker( qm ); QCOMPARE( tracks.count(), 1 ); QCOMPARE( tracks.first()->name(), QString("Skater Boy" ) ); // -- filter for Rating qm = new Collections::MemoryQueryMaker( m_mc.toWeakRef(), "test" ); qm->addNumberFilter( Meta::valRating, 4, Collections::QueryMaker::LessThan ); tracks = executeQueryMaker( qm ); QCOMPARE( tracks.count(), 2 ); } void TestMemoryQueryMaker::testFilterAnd() { Meta::TrackList tracks; Collections::MemoryQueryMaker *qm = 0; qm = new Collections::MemoryQueryMaker( m_mc.toWeakRef(), "test" ); qm->beginAnd(); qm->addNumberFilter( Meta::valTrackNr, 1, Collections::QueryMaker::Equals ); qm->addFilter( Meta::valAlbum, "o", false, false ); qm->endAndOr(); tracks = executeQueryMaker( qm ); QCOMPARE( tracks.count(), 1 ); QCOMPARE( tracks.first()->album()->name(), QString("Rodeo Radio" ) ); } void TestMemoryQueryMaker::testFilterFormat() { Meta::TrackList tracks; Collections::MemoryQueryMaker *qm = 0; // -- filter for title qm = new Collections::MemoryQueryMaker( m_mc.toWeakRef(), "test" ); qm->addNumberFilter( Meta::valFormat, int(Amarok::Mp3), Collections::QueryMaker::Equals ); tracks = executeQueryMaker( qm ); QCOMPARE( tracks.count(), 0 ); } diff --git a/tests/core-impl/logger/TestProxyLogger.cpp b/tests/core-impl/logger/TestProxyLogger.cpp index 1633a0f904..f7173d86bd 100644 --- a/tests/core-impl/logger/TestProxyLogger.cpp +++ b/tests/core-impl/logger/TestProxyLogger.cpp @@ -1,209 +1,209 @@ /**************************************************************************************** * Copyright (c) 2010 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestProxyLogger.h" #include "core/interfaces/Logger.h" #include "core-impl/logger/ProxyLogger.h" #include "mocks/MockLogger.h" #include #include #include #include -QTEST_MAIN( TestProxyLogger ) +QTEST_GUILESS_MAIN( TestProxyLogger ) using ::testing::Return; using ::testing::AnyNumber; using ::testing::_; using ::testing::Mock; static ProxyLogger *s_logger; class DummyJob : public KJob { public: virtual void start() {} }; TestProxyLogger::TestProxyLogger() { int argc = 1; char **argv = (char **) malloc(sizeof(char *)); argv[0] = strdup( QCoreApplication::applicationName().toLocal8Bit().data() ); ::testing::InitGoogleMock( &argc, argv ); delete[] argv; } void TestProxyLogger::init() { s_logger = 0; } void TestProxyLogger::cleanup() { delete s_logger; } class ProgressJob : public QObject, public ThreadWeaver::Job { Q_OBJECT public: ProgressJob() : deleteJob( false ), deleteObject( false ) {} void run(ThreadWeaver::JobPointer self, ThreadWeaver::Thread *thread) { Q_UNUSED(self); Q_UNUSED(thread); KJob *job = new DummyJob(); QObject *obj = new QObject(); s_logger->newProgressOperation( job, QString( "foo" ), obj, "foo()" ); if( deleteJob ) delete job; if( deleteObject ) delete obj; } bool deleteJob; bool deleteObject; protected: void defaultBegin(const ThreadWeaver::JobPointer& self, ThreadWeaver::Thread *thread) { Q_EMIT started(self); ThreadWeaver::Job::defaultBegin(self, thread); } void defaultEnd(const ThreadWeaver::JobPointer& self, ThreadWeaver::Thread *thread) { ThreadWeaver::Job::defaultEnd(self, thread); if (!self->success()) { Q_EMIT failed(self); } Q_EMIT done(self); } Q_SIGNALS: /** This signal is emitted when this job is being processed by a thread. */ void started(ThreadWeaver::JobPointer); /** This signal is emitted when the job has been finished (no matter if it succeeded or not). */ void done(ThreadWeaver::JobPointer); /** This job has failed. * This signal is emitted when success() returns false after the job is executed. */ void failed(ThreadWeaver::JobPointer); }; void TestProxyLogger::testDoNotForwardDeletedJob() { s_logger = new ProxyLogger(); Amarok::MockLogger *mock = new Amarok::MockLogger(); EXPECT_CALL( *mock, newProgressOperation( An(), _, _, _, _ ) ).Times( 0 ); s_logger->setLogger( mock ); ProgressJob *job = new ProgressJob(); job->deleteJob = true; ThreadWeaver::Queue::instance()->enqueue( QSharedPointer(job) ); QTest::qSleep( 10 ); //ensure that the job has time to run QTest::qWait( 20 ); //give the ProxyLogger-internal timer time to fire QVERIFY( Mock::VerifyAndClearExpectations( &mock ) ); delete mock; } void TestProxyLogger::testDoNotForwardDeletedSlot() { s_logger = new ProxyLogger(); Amarok::MockLogger *mock = new Amarok::MockLogger(); EXPECT_CALL( *mock, newProgressOperation( An(), _, 0, 0, _ ) ).Times( 1 ).WillOnce( Return() ); s_logger->setLogger( mock ); ProgressJob *job = new ProgressJob(); job->deleteObject = true; ThreadWeaver::Queue::instance()->enqueue( QSharedPointer(job) ); QTest::qSleep( 10 ); //ensure that the job has time to run QTest::qWait( 20 ); //give the ProxyLogger-internal timer time to fire QVERIFY( Mock::VerifyAndClearExpectations( &mock ) ); delete mock; } void TestProxyLogger::testForwardLongMessage() { s_logger = new ProxyLogger(); Amarok::MockLogger *mock = new Amarok::MockLogger(); EXPECT_CALL( *mock, longMessage( _, _ ) ).Times( 1 ).WillOnce( Return() ); s_logger->setLogger( mock ); s_logger->longMessage( "foo", Amarok::Logger::Information ); QTest::qWait( 20 ); QVERIFY( Mock::VerifyAndClearExpectations( &mock ) ); delete mock; } void TestProxyLogger::testForwardProgressOperation() { s_logger = new ProxyLogger(); Amarok::MockLogger *mock = new Amarok::MockLogger(); EXPECT_CALL( *mock, newProgressOperation( An(), _, _, _, _ ) ).Times( 1 ).WillOnce( Return() ); s_logger->setLogger( mock ); s_logger->newProgressOperation( new DummyJob(), QString( "foo" ) ); QTest::qWait( 20 ); QVERIFY( Mock::VerifyAndClearExpectations( &mock ) ); delete mock; } void TestProxyLogger::testForwardShortMessage() { s_logger = new ProxyLogger(); Amarok::MockLogger *mock = new Amarok::MockLogger(); EXPECT_CALL( *mock, shortMessage( _ ) ).Times( 1 ).WillOnce( Return() ); s_logger->setLogger( mock ); s_logger->shortMessage( "foo" ); QTest::qWait( 20 ); QVERIFY( Mock::VerifyAndClearExpectations( &mock ) ); delete mock; } #include "TestProxyLogger.moc" diff --git a/tests/core-impl/meta/cue/TestCueFileSupport.cpp b/tests/core-impl/meta/cue/TestCueFileSupport.cpp index cbc47dc879..58bcaf037c 100644 --- a/tests/core-impl/meta/cue/TestCueFileSupport.cpp +++ b/tests/core-impl/meta/cue/TestCueFileSupport.cpp @@ -1,83 +1,83 @@ /**************************************************************************************** * Copyright (c) 2010 Nikolaj Hald Nielsen * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Pulic License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestCueFileSupport.h" #include "config-amarok-test.h" #include "core-impl/meta/cue/CueFileSupport.h" #include #include -QTEST_MAIN( TestCueFileSupport ) +QTEST_GUILESS_MAIN( TestCueFileSupport ) using namespace MetaCue; TestCueFileSupport::TestCueFileSupport() : QObject() { } void TestCueFileSupport::testLocateCueFile() { //Check that we find the right .cue file and that it passes the validator QUrl cueTestUrl = QUrl::fromLocalFile(dataPath( "data/cue/testsheet01-iso8859-1.cue" )); QUrl cueResultUrl = CueFileSupport::locateCueSheet( cueTestUrl ); QVERIFY( !cueResultUrl.url().isEmpty() ); QCOMPARE( cueResultUrl.url(), cueTestUrl.url() ); //Check that a nonexisting cue file returns an empty url QUrl testUrl = QUrl::fromLocalFile(dataPath( "data/cue/test_silence.ogg" )); cueResultUrl = CueFileSupport::locateCueSheet( testUrl ); QVERIFY( cueResultUrl.isEmpty() ); //Check that an existing but invalid cue file returns an empty url testUrl = QUrl::fromLocalFile(dataPath( "data/cue/invalid.cue" )); cueResultUrl = CueFileSupport::locateCueSheet( testUrl ); QVERIFY( cueResultUrl.isEmpty() ); } void TestCueFileSupport::testIso88591Cue() { QUrl testUrl = QUrl::fromLocalFile(dataPath( "data/cue/testsheet01-iso8859-1.cue" )); QUrl testTrackUrl = QUrl::fromLocalFile((QString( "Die Toten Hosen - In aller Stille (2008).mp3" ))); CueFileItemMap cueItemMap = CueFileSupport::loadCueFile( testUrl, testTrackUrl, 48000 ); QCOMPARE( cueItemMap.size(), 14 ); QCOMPARE( cueItemMap.value( cueItemMap.keys()[2] ).title(), QString( "Disco" ) ); QCOMPARE( cueItemMap.value( cueItemMap.keys()[2] ).artist(), QString( "Die Toten Hosen" ) ); } void TestCueFileSupport::testUtf8Cue() { QUrl testUrl = QUrl::fromLocalFile(dataPath( "data/cue/testsheet01-utf8.cue" )); QUrl testTrackUrl = QUrl::fromLocalFile(QString( "Die Toten Hosen - In aller Stille (2008).mp3" )); CueFileItemMap cueItemMap = CueFileSupport::loadCueFile( testUrl, testTrackUrl, 48000 ); QCOMPARE( cueItemMap.size(), 14 ); QCOMPARE( cueItemMap.value( cueItemMap.keys()[6] ).title(), QString( "Ertrinken" ) ); QCOMPARE( cueItemMap.value( cueItemMap.keys()[6] ).artist(), QString( "Die Toten Hosen" ) ); } QString TestCueFileSupport::dataPath( const QString &relPath ) { return QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + '/' + relPath ); } diff --git a/tests/core-impl/meta/file/TestMetaFileTrack.cpp b/tests/core-impl/meta/file/TestMetaFileTrack.cpp index af9b8ab906..dffc9f8980 100644 --- a/tests/core-impl/meta/file/TestMetaFileTrack.cpp +++ b/tests/core-impl/meta/file/TestMetaFileTrack.cpp @@ -1,456 +1,456 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestMetaFileTrack.h" #include "config-amarok-test.h" #include "amarokconfig.h" #include #include #include #include #include #include -QTEST_MAIN( TestMetaFileTrack ) +QTEST_GUILESS_MAIN( TestMetaFileTrack ) TestMetaFileTrack::TestMetaFileTrack() : m_tmpDir( 0 ) {} void TestMetaFileTrack::initTestCase() { AmarokConfig::instance("amarokrc"); m_tmpDir = new QTemporaryDir(); QVERIFY( m_tmpDir->isValid() ); m_origTrackPath = QString( AMAROK_TEST_DIR ) + "/data/audio/Platz 01.mp3"; QVERIFY( QFile::exists( m_origTrackPath ) ); } void TestMetaFileTrack::cleanupTestCase() { delete m_tmpDir; } void TestMetaFileTrack::init() { static const QString tmpFileNameBase( "tempfile.mp3" ); static int i = 0; // create new file name for every test: we need to start with clean statistics m_tmpFileName = QString( "%1%2-%3" ).arg( m_tmpDir->path() ).arg( i++ ).arg( tmpFileNameBase ); QVERIFY( QFile::copy( m_origTrackPath, m_tmpFileName ) ); m_track = new MetaFile::Track( QUrl::fromLocalFile(m_tmpFileName) ); QVERIFY( m_track ); } void TestMetaFileTrack::testNameAndSetTitle() { // why aren't those called set/getTitle? QCOMPARE( m_track->name(), QString( "Platz 01" ) ); m_track->setTitle( "" ); //when there is no title, we default to using the filename without extension QCOMPARE( m_track->name(), QString( "tempfile" ) ); m_track->setTitle( "test" ); QCOMPARE( m_track->name(), QString( "test" ) ); m_track->setTitle( "Another Test" ); QCOMPARE( m_track->name(), QString( "Another Test" ) ); m_track->setTitle( "Some Umlauts: äöü" ); QCOMPARE( m_track->name(), QString( "Some Umlauts: äöü" ) ); m_track->setTitle( "Platz 01" ); QCOMPARE( m_track->name(), QString( "Platz 01" ) ); } void TestMetaFileTrack::testPrettyName() { QCOMPARE( m_track->prettyName(), QString( "Platz 01" ) ); m_track->setTitle( "" ); //when there is no title, we default to using the filename without extension QCOMPARE( m_track->prettyName(), QString( "tempfile" ) ); m_track->setTitle( "test" ); QCOMPARE( m_track->prettyName(), QString( "test" ) ); m_track->setTitle( "Another Test" ); QCOMPARE( m_track->prettyName(), QString( "Another Test" ) ); m_track->setTitle( "Some Umlauts: äöü" ); QCOMPARE( m_track->prettyName(), QString( "Some Umlauts: äöü" ) ); m_track->setTitle( "Platz 01" ); QCOMPARE( m_track->prettyName(), QString( "Platz 01" ) ); } void TestMetaFileTrack::testSortableName() { QCOMPARE( m_track->sortableName(), QString( "Platz 01" ) ); m_track->setTitle( "test" ); QCOMPARE( m_track->sortableName(), QString( "test" ) ); m_track->setTitle( "Another Test" ); QCOMPARE( m_track->sortableName(), QString( "Another Test" ) ); m_track->setTitle( "Some Umlauts: äöü" ); QCOMPARE( m_track->sortableName(), QString( "Some Umlauts: äöü" ) ); m_track->setTitle( "Platz 01" ); QCOMPARE( m_track->sortableName(), QString( "Platz 01" ) ); } void TestMetaFileTrack::testPlayableUrl() { const QUrl tempUrl = m_track->playableUrl(); QCOMPARE( tempUrl.toLocalFile(), m_tmpFileName ); } void TestMetaFileTrack::testPrettyUrl() { const QUrl tempUrl = QUrl::fromLocalFile(m_track->prettyUrl()); QCOMPARE( tempUrl.toLocalFile(), m_tmpFileName ); } void TestMetaFileTrack::testUidUrl() { QUrl tempUrl(m_track->uidUrl()); QCOMPARE( tempUrl.toLocalFile(), m_tmpFileName ); } void TestMetaFileTrack::testIsPlayable() { QVERIFY( m_track->isPlayable() ); } void TestMetaFileTrack::testIsEditable() { QVERIFY( m_track->isEditable() ); QFile testFile( m_tmpFileName ); QVERIFY( testFile.setPermissions( 0x0000 ) ); /* When the tests are run as root under Linux, the file is accessible even when it * has no permission bits set. Just skip one verify in this case in order not to * break whole test. */ if( !QFileInfo( testFile ).isReadable() ) QVERIFY( !m_track->isEditable() ); QVERIFY( testFile.setPermissions( QFile::ReadOwner | QFile::WriteOwner ) ); QVERIFY( m_track->isEditable() ); } void TestMetaFileTrack::testSetGetAlbum() { QCOMPARE( m_track->album()->name(), QString( "" ) ); m_track->setAlbum( "test" ); QCOMPARE( m_track->album()->name(), QString( "test" ) ); m_track->setAlbum( "Another Test" ); QCOMPARE( m_track->album()->name(), QString( "Another Test" ) ); m_track->setAlbum( "Some Umlauts: äöü" ); QCOMPARE( m_track->album()->name(), QString( "Some Umlauts: äöü" ) ); m_track->setAlbum( "" ); QCOMPARE( m_track->album()->name(), QString( "" ) ); } void TestMetaFileTrack::testSetGetArtist() { QCOMPARE( m_track->artist()->name(), QString( "Free Music Charts" ) ); m_track->setArtist( "" ); QCOMPARE( m_track->artist()->name(), QString( "" ) ); m_track->setArtist( "test" ); QCOMPARE( m_track->artist()->name(), QString( "test" ) ); m_track->setArtist( "Another Test" ); QCOMPARE( m_track->artist()->name(), QString( "Another Test" ) ); m_track->setArtist( "Some Umlauts: äöü" ); QCOMPARE( m_track->artist()->name(), QString( "Some Umlauts: äöü" ) ); m_track->setArtist( "Free Music Charts" ); QCOMPARE( m_track->artist()->name(), QString( "Free Music Charts" ) ); } void TestMetaFileTrack::testSetGetGenre() { QCOMPARE( m_track->genre()->name(), QString( "Vocal" ) ); m_track->setGenre( "rock" ); QCOMPARE( m_track->genre()->name(), QString( "rock" ) ); m_track->setGenre( "rock / pop" ); QCOMPARE( m_track->genre()->name(), QString( "rock / pop" ) ); m_track->setGenre( "Some Umlauts: äöü" ); QCOMPARE( m_track->genre()->name(), QString( "Some Umlauts: äöü" ) ); m_track->setGenre( "" ); QCOMPARE( m_track->genre()->name(), QString( "" ) ); m_track->setGenre( "28 Vocal" ); QCOMPARE( m_track->genre()->name(), QString( "28 Vocal" ) ); } void TestMetaFileTrack::testSetGetComposer() { QCOMPARE( m_track->composer()->name(), QString( "" ) ); m_track->setComposer( "test" ); QCOMPARE( m_track->composer()->name(), QString( "test" ) ); m_track->setComposer( "Ludwig Van Beethoven" ); QCOMPARE( m_track->composer()->name(), QString( "Ludwig Van Beethoven" ) ); m_track->setComposer( "Georg Friedrich Händel" ); QCOMPARE( m_track->composer()->name(), QString( "Georg Friedrich Händel" ) ); m_track->setComposer( "" ); QCOMPARE( m_track->composer()->name(), QString( "" ) ); } void TestMetaFileTrack::testSetGetYear() { QCOMPARE( m_track->composer()->name(), QString( "" ) ); m_track->setComposer( "test" ); QCOMPARE( m_track->composer()->name(), QString( "test" ) ); m_track->setComposer( "2009" ); QCOMPARE( m_track->composer()->name(), QString( "2009" ) ); m_track->setComposer( "1" ); QCOMPARE( m_track->composer()->name(), QString( "1" ) ); m_track->setComposer( "0" ); QCOMPARE( m_track->composer()->name(), QString( "0" ) ); m_track->setComposer( "-1" ); QCOMPARE( m_track->composer()->name(), QString( "-1" ) ); m_track->setComposer( "" ); QCOMPARE( m_track->composer()->name(), QString( "" ) ); } void TestMetaFileTrack::testSetGetComment() { QCOMPARE( m_track->comment(), QString( "" ) ); m_track->setComment( "test" ); QCOMPARE( m_track->comment(), QString( "test" ) ); m_track->setComment( "2009" ); QCOMPARE( m_track->comment(), QString( "2009" ) ); m_track->setComment( QString::fromUtf8( "Some Umlauts: äöü" ) ); QCOMPARE( m_track->comment(), QString::fromUtf8( "Some Umlauts: äöü" ) ); m_track->setComment( "" ); QCOMPARE( m_track->comment(), QString( "" ) ); } void TestMetaFileTrack::testSetGetScore() { // try with write back enabled... AmarokConfig::setWriteBackStatistics( true ); Meta::StatisticsPtr statistics = m_track->statistics(); QCOMPARE( statistics->score(), 0.0 ); /* now the code actually stores the score in track and then it reads it back. * the precision it uses is pretty low and it was failing the qFuzzyCompare * Just make it use qFuzzyCompare() */ statistics->setScore( 3 ); QCOMPARE( float( statistics->score() ), float( 3.0 ) ); statistics->setScore( 12.55 ); QCOMPARE( float( statistics->score() ), float( 12.55 ) ); statistics->setScore( 100 ); QCOMPARE( float( statistics->score() ), float( 100.0 ) ); statistics->setScore( 0 ); QCOMPARE( float( statistics->score() ), float( 0.0 ) ); // and with writeback disabled AmarokConfig::setWriteBackStatistics( false ); statistics->setScore( 3 ); QCOMPARE( float( statistics->score() ), float( 0.0 ) ); statistics->setScore( 12.55 ); QCOMPARE( float( statistics->score() ), float( 0.0 ) ); } void TestMetaFileTrack::testSetGetRating() { // try with write back enabled... AmarokConfig::setWriteBackStatistics( true ); Meta::StatisticsPtr statistics = m_track->statistics(); QCOMPARE( m_track->statistics()->rating(), 0 ); m_track->statistics()->setRating( 1 ); QCOMPARE( m_track->statistics()->rating(), 1 ); m_track->statistics()->setRating( 23 ); QCOMPARE( m_track->statistics()->rating(), 23 ); // should this be possible? m_track->statistics()->setRating( 0 ); QCOMPARE( m_track->statistics()->rating(), 0 ); // and with writeback disabled AmarokConfig::setWriteBackStatistics( false ); m_track->statistics()->setRating( 1 ); QCOMPARE( m_track->statistics()->rating(), 0 ); m_track->statistics()->setRating( 23 ); QCOMPARE( m_track->statistics()->rating(), 0 ); } void TestMetaFileTrack::testSetGetTrackNumber() { QCOMPARE( m_track->trackNumber(), 0 ); m_track->setTrackNumber( 1 ); QCOMPARE( m_track->trackNumber(), 1 ); m_track->setTrackNumber( 23 ); QCOMPARE( m_track->trackNumber(), 23 ); m_track->setTrackNumber( -12 ); QCOMPARE( m_track->trackNumber(), -12 ); // should this be possible? m_track->setTrackNumber( 0 ); QCOMPARE( m_track->trackNumber(), 0 ); } void TestMetaFileTrack::testSetGetDiscNumber() { QCOMPARE( m_track->discNumber(), 0 ); m_track->setDiscNumber( 1 ); QCOMPARE( m_track->discNumber(), 1 ); m_track->setDiscNumber( 23 ); QCOMPARE( m_track->discNumber(), 23 ); m_track->setDiscNumber( -12 ); QCOMPARE( m_track->discNumber(), -12 ); // should this be possible? m_track->setDiscNumber( 0 ); QCOMPARE( m_track->discNumber(), 0 ); } void TestMetaFileTrack::testLength() { QCOMPARE( m_track->length(), 12000LL ); } void TestMetaFileTrack::testFilesize() { QCOMPARE( m_track->filesize(), 389454 ); } void TestMetaFileTrack::testSampleRate() { QCOMPARE( m_track->sampleRate(), 44100 ); } void TestMetaFileTrack::testBitrate() { QCOMPARE( m_track->bitrate(), 257 ); } void TestMetaFileTrack::testSetGetLastPlayed() { QSKIP( "lastPlayed reading/saving not (yet) available in MetaFile::Track", SkipAll ); QCOMPARE( m_track->statistics()->lastPlayed(), QDateTime() ); m_track->finishedPlaying( 1.0 ); QVERIFY( m_track->statistics()->lastPlayed().isValid() ); } void TestMetaFileTrack::testSetGetFirstPlayed() { QSKIP( "firstPlayed reading/saving not (yet) available in MetaFile::Track", SkipAll ); QCOMPARE( m_track->statistics()->firstPlayed(), QDateTime() ); m_track->finishedPlaying( 1.0 ); QVERIFY( m_track->statistics()->firstPlayed().isValid() ); } void TestMetaFileTrack::testSetGetPlayCount() { // try with write back enabled... AmarokConfig::setWriteBackStatistics( true ); QCOMPARE( m_track->statistics()->playCount(), 0 ); m_track->finishedPlaying( 1.0 ); QCOMPARE( m_track->statistics()->playCount(), 1 ); m_track->statistics()->setPlayCount( 0 ); QCOMPARE( m_track->statistics()->playCount(), 0 ); // and with writeback disabled AmarokConfig::setWriteBackStatistics( false ); m_track->finishedPlaying( 1.0 ); QCOMPARE( m_track->statistics()->playCount(), 0 ); m_track->statistics()->setPlayCount( 12 ); QCOMPARE( m_track->statistics()->playCount(), 0 ); } void TestMetaFileTrack::testReplayGain() { QCOMPARE( int(m_track->replayGain( Meta::ReplayGain_Track_Gain ) * 1000), -6655 ); QCOMPARE( int(m_track->replayGain( Meta::ReplayGain_Album_Gain ) * 1000), -6655 ); QCOMPARE( int(m_track->replayGain( Meta::ReplayGain_Track_Peak ) * 10000), 41263 ); QCOMPARE( int(m_track->replayGain( Meta::ReplayGain_Album_Peak ) * 10000), 41263 ); } void TestMetaFileTrack::testType() { QCOMPARE( m_track->type(), QString( "mp3" ) ); } void TestMetaFileTrack::testCreateDate() { QFileInfo fi( m_tmpFileName ); QDateTime created = fi.created(); // m_track->createDate() is rounded to full second because it is created from full seconds // created therefore also needs to be rounded QCOMPARE( m_track->createDate().toSecsSinceEpoch(), created.toSecsSinceEpoch() ); } diff --git a/tests/core-impl/meta/multi/TestMetaMultiTrack.cpp b/tests/core-impl/meta/multi/TestMetaMultiTrack.cpp index c6513ba1a1..5b41f45d28 100644 --- a/tests/core-impl/meta/multi/TestMetaMultiTrack.cpp +++ b/tests/core-impl/meta/multi/TestMetaMultiTrack.cpp @@ -1,178 +1,178 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestMetaMultiTrack.h" #include "core/support/Components.h" #include "EngineController.h" #include "config-amarok-test.h" #include "core-impl/collections/support/CollectionManager.h" #include "core-impl/meta/multi/MultiTrack.h" #include "core-impl/playlists/types/file/PlaylistFileSupport.h" #include #include #include #include #include #include -QTEST_MAIN( TestMetaMultiTrack ) +QTEST_GUILESS_MAIN( TestMetaMultiTrack ) TestMetaMultiTrack::TestMetaMultiTrack() : m_testMultiTrack( 0 ) { } void TestMetaMultiTrack::tracksLoaded( Playlists::PlaylistPtr playlist ) { emit tracksLoadedSignal( playlist ); } void TestMetaMultiTrack::initTestCase() { qRegisterMetaType( "Meta::TrackPtr" ); //apparently the engine controller is needed somewhere, or we will get a crash... EngineController *controller = new EngineController(); Amarok::Components::setEngineController( controller ); /* Collection manager needs to be instantiated in the main thread, but * MetaProxy::Tracks used by playlist may trigger its creation in a different thread. * Pre-create it explicitly */ CollectionManager::instance(); const QString path = QString( AMAROK_TEST_DIR ) + "/data/playlists/test.pls"; const QFileInfo file( QDir::toNativeSeparators( path ) ); QVERIFY( file.exists() ); const QString filePath = file.absoluteFilePath(); m_playlist = Playlists::loadPlaylistFile( QUrl::fromLocalFile(filePath) ).data(); QVERIFY( m_playlist ); // no playlist -> no test. that's life ;) subscribeTo( m_playlist ); m_playlist->triggerTrackLoad(); QSignalSpy spy( this, &TestMetaMultiTrack::tracksLoadedSignal ); if( m_playlist->trackCount() < 0 ) QVERIFY( spy.wait( 5000 ) ); QCOMPARE( m_playlist->name(), QString("test.pls") ); QCOMPARE( m_playlist->trackCount(), 4 ); // now wait for all MetaProxy::Tracks to actually load their real tracks: NotifyObserversWaiter wainter( m_playlist->tracks().toSet() ); QSignalSpy spyDone( &wainter, &NotifyObserversWaiter::done ); QVERIFY( spyDone.wait( 5000 ) ); } void TestMetaMultiTrack::cleanupTestCase() { // Wait for other jobs, like MetaProxys fetching meta data, to finish ThreadWeaver::Queue::instance()->finish(); } void TestMetaMultiTrack::init() { m_testMultiTrack = new Meta::MultiTrack( m_playlist ); } void TestMetaMultiTrack::cleanup() { delete m_testMultiTrack; } void TestMetaMultiTrack::testSources() { QStringList sources = m_testMultiTrack->sources(); QCOMPARE( sources.size(), 4 ); QCOMPARE( sources.at( 0 ), QString( "http://85.214.44.27:8000" ) ); QCOMPARE( sources.at( 1 ), QString( "http://217.20.121.40:8000" ) ); QCOMPARE( sources.at( 2 ), QString( "http://85.214.44.27:8100" ) ); QCOMPARE( sources.at( 3 ), QString( "http://85.214.44.27:8200" ) ); } void TestMetaMultiTrack::testSetSourceCurrentNextUrl() { QCOMPARE( m_testMultiTrack->current(), 0 ); QCOMPARE( m_testMultiTrack->playableUrl(), QUrl("http://85.214.44.27:8000") ); QCOMPARE( m_testMultiTrack->nextUrl(), QUrl("http://217.20.121.40:8000") ); m_testMultiTrack->setSource( 1 ); QCOMPARE( m_testMultiTrack->current(), 1 ); QCOMPARE( m_testMultiTrack->playableUrl(), QUrl("http://217.20.121.40:8000") ); QCOMPARE( m_testMultiTrack->nextUrl(), QUrl("http://85.214.44.27:8100") ); m_testMultiTrack->setSource( 2 ); QCOMPARE( m_testMultiTrack->current(), 2 ); QCOMPARE( m_testMultiTrack->playableUrl(), QUrl("http://85.214.44.27:8100") ); QCOMPARE( m_testMultiTrack->nextUrl(), QUrl("http://85.214.44.27:8200") ); m_testMultiTrack->setSource( 3 ); QCOMPARE( m_testMultiTrack->current(), 3 ); QCOMPARE( m_testMultiTrack->playableUrl(), QUrl("http://85.214.44.27:8200") ); QCOMPARE( m_testMultiTrack->nextUrl(), QUrl() ); m_testMultiTrack->setSource( 4 ); QCOMPARE( m_testMultiTrack->current(), 3 ); m_testMultiTrack->setSource( -1 ); QCOMPARE( m_testMultiTrack->current(), 3 ); } void TestMetaMultiTrack::testHasCapabilityInterface() { QVERIFY( m_testMultiTrack->hasCapabilityInterface( Capabilities::Capability::MultiSource ) ); } NotifyObserversWaiter::NotifyObserversWaiter( const QSet &tracks, QObject *parent ) : QObject( parent ) , m_tracks( tracks ) { // we need to filter already resovled tracks in the next event loop iteration because // the user wouldn't be able to get the done() signal yet. QTimer::singleShot( 0, this, &NotifyObserversWaiter::slotFilterResovled ); } void NotifyObserversWaiter::slotFilterResovled() { QMutexLocker locker( &m_mutex ); QMutableSetIterator it( m_tracks ); while( it.hasNext() ) { const Meta::TrackPtr &track = it.next(); const MetaProxy::Track *proxyTrack = dynamic_cast( track.data() ); Q_ASSERT( proxyTrack ); if( proxyTrack->isResolved() ) it.remove(); else subscribeTo( track ); } if( m_tracks.isEmpty() ) emit done(); } void NotifyObserversWaiter::metadataChanged( Meta::TrackPtr track ) { QMutexLocker locker( &m_mutex ); m_tracks.remove( track ); if( m_tracks.isEmpty() ) emit done(); } diff --git a/tests/core-impl/playlists/types/file/TestPlaylistFileSupport.cpp b/tests/core-impl/playlists/types/file/TestPlaylistFileSupport.cpp index e4ca25e2fb..86296f2303 100644 --- a/tests/core-impl/playlists/types/file/TestPlaylistFileSupport.cpp +++ b/tests/core-impl/playlists/types/file/TestPlaylistFileSupport.cpp @@ -1,65 +1,65 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestPlaylistFileSupport.h" #include "config-amarok-test.h" #include "core-impl/playlists/types/file/PlaylistFileSupport.h" #include "core/playlists/PlaylistFormat.h" #include #include -QTEST_MAIN( TestPlaylistFileSupport ) +QTEST_GUILESS_MAIN( TestPlaylistFileSupport ) TestPlaylistFileSupport::TestPlaylistFileSupport() {} void TestPlaylistFileSupport::initTestCase() { const QDir dir( QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + "/data/playlists" ) ); QVERIFY( dir.exists() ); m_testPlaylistPath = dir.absolutePath(); } void TestPlaylistFileSupport::testGetFormat() { QCOMPARE( Playlists::getFormat( QUrl::fromLocalFile(m_testPlaylistPath + "test.asx") ), Playlists::ASX ); QCOMPARE( Playlists::getFormat( QUrl::fromLocalFile(m_testPlaylistPath + "test.m3u") ), Playlists::M3U ); QCOMPARE( Playlists::getFormat( QUrl::fromLocalFile(m_testPlaylistPath + "test.pls") ), Playlists::PLS ); QCOMPARE( Playlists::getFormat( QUrl::fromLocalFile(m_testPlaylistPath + "test.ram") ), Playlists::RAM ); QCOMPARE( Playlists::getFormat( QUrl::fromLocalFile(m_testPlaylistPath + "test.smil") ), Playlists::SMIL ); // TODO: Playlists::XML <- what kind of playlist format is that? example? QCOMPARE( Playlists::getFormat( QUrl::fromLocalFile(m_testPlaylistPath + "test.xspf") ), Playlists::XSPF ); QCOMPARE( Playlists::getFormat( QUrl::fromLocalFile(m_testPlaylistPath + "no-playlist.png") ), Playlists::Unknown ); QCOMPARE( Playlists::getFormat( QUrl::fromLocalFile(m_testPlaylistPath + "no-playlist.png") ), Playlists::NotPlaylist ); } void TestPlaylistFileSupport::testIsPlaylist() { QCOMPARE( Playlists::isPlaylist( QUrl::fromLocalFile(m_testPlaylistPath + "test.asx") ), true ); QCOMPARE( Playlists::isPlaylist( QUrl::fromLocalFile(m_testPlaylistPath + "test.m3u") ), true ); QCOMPARE( Playlists::isPlaylist( QUrl::fromLocalFile(m_testPlaylistPath + "test.pls") ), true ); QCOMPARE( Playlists::isPlaylist( QUrl::fromLocalFile(m_testPlaylistPath + "test.ram") ), true ); QCOMPARE( Playlists::isPlaylist( QUrl::fromLocalFile(m_testPlaylistPath + "test.smil") ), true ); // TODO: Playlists::XML <- what kind of playlist format is that? example? QCOMPARE( Playlists::isPlaylist( QUrl::fromLocalFile(m_testPlaylistPath + "test.xspf") ), true ); QCOMPARE( Playlists::isPlaylist( QUrl::fromLocalFile(m_testPlaylistPath + "no-playlist.png") ), false ); } diff --git a/tests/core-impl/playlists/types/file/asx/TestASXPlaylist.cpp b/tests/core-impl/playlists/types/file/asx/TestASXPlaylist.cpp index adc37ccf69..51d4993d41 100644 --- a/tests/core-impl/playlists/types/file/asx/TestASXPlaylist.cpp +++ b/tests/core-impl/playlists/types/file/asx/TestASXPlaylist.cpp @@ -1,160 +1,160 @@ /*************************************************************************** * Copyright (c) 2013 Tatjana Gornak * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestASXPlaylist.h" #include "config-amarok-test.h" #include "core/support/Components.h" #include "core-impl/collections/support/CollectionManager.h" #include "core-impl/playlists/types/file/asx/ASXPlaylist.h" #include "EngineController.h" #include #include #include #include #include #include -QTEST_MAIN( TestASXPlaylist ) +QTEST_GUILESS_MAIN( TestASXPlaylist ) TestASXPlaylist::TestASXPlaylist() { } QString TestASXPlaylist::dataPath( const QString &relPath ) { return QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + '/' + relPath ); } void TestASXPlaylist::initTestCase() { m_tempDir = new QTemporaryDir; QVERIFY( m_tempDir->isValid() ); // EngineController is used in a connection in MetaProxy::Track; avoid null sender // warning EngineController *controller = new EngineController(); Amarok::Components::setEngineController( controller ); qRegisterMetaType( "Meta::TrackPtr" ); /* Collection manager needs to be instantiated in the main thread, but * MetaProxy::Tracks used by playlist may trigger its creation in a different thread. * Pre-create it explicitly */ CollectionManager::instance(); const QUrl url = QUrl::fromLocalFile(dataPath( "data/playlists/test.asx" )); QFile playlistFile1( url.toLocalFile() ); QTextStream playlistStream; QString tempPath = m_tempDir->path() + "/test.asx"; QFile::remove( tempPath ); QVERIFY( QFile::copy( url.toLocalFile(), tempPath ) ); QVERIFY( QFile::exists( tempPath ) ); QVERIFY( playlistFile1.open( QFile::ReadOnly ) ); playlistStream.setDevice( &playlistFile1 ); QVERIFY( playlistStream.device() ); m_testPlaylist = new Playlists::ASXPlaylist( QUrl::fromLocalFile(tempPath) ); QVERIFY( m_testPlaylist ); QVERIFY( m_testPlaylist->load( playlistStream ) ); QCOMPARE( m_testPlaylist->tracks().size(), 1 ); playlistFile1.close(); } void TestASXPlaylist::cleanupTestCase() { // Wait for other jobs, like MetaProxys fetching meta data, to finish ThreadWeaver::Queue::instance()->finish(); delete m_tempDir; delete m_testPlaylist; delete Amarok::Components::setEngineController( 0 ); } void TestASXPlaylist::testSetAndGetName() { QCOMPARE( m_testPlaylist->prettyName(), QString( "test.asx" ) ); QCOMPARE( m_testPlaylist->name(), QString( "test.asx" ) ); m_testPlaylist->setName( "set name test.asx" ); QCOMPARE( m_testPlaylist->name(), QString( "set name test.asx" ) ); m_testPlaylist->setName( "set name test aäoöuüß.asx" ); QCOMPARE( m_testPlaylist->name(), QString( "set name test aäoöuüß.asx" ) ); m_testPlaylist->setName( "test" ); m_testPlaylist->setName( "" ); QCOMPARE( m_testPlaylist->name(), QString( "test.asx" ) ); } void TestASXPlaylist::testTracks() { Meta::TrackList tracklist = m_testPlaylist->tracks(); QCOMPARE( tracklist.size(), 1 ); QCOMPARE( tracklist.at( 0 )->name(), QString( ":: Willkommen bei darkerradio - Tune in, turn on, burn out" ) ); } void TestASXPlaylist::testUidUrl() { QString tempPath = m_tempDir->path() + "/test.asx"; //we have chaged the name around so much, better reset it m_testPlaylist->setName( "test" ); QCOMPARE( m_testPlaylist->uidUrl().toLocalFile(), tempPath ); } void TestASXPlaylist::testSetAndGetGroups() { QStringList grouplist; QStringList newGrouplist; grouplist = m_testPlaylist->groups(); QCOMPARE( grouplist.size(), 0 ); newGrouplist.append( "test" ); m_testPlaylist->setGroups( newGrouplist ); grouplist = m_testPlaylist->groups(); QCOMPARE( grouplist.size(), 1 ); QCOMPARE( grouplist.at(0), QString( "test" ) ); } void TestASXPlaylist::testIsWritable() { QVERIFY( m_testPlaylist->isWritable() ); } void TestASXPlaylist::testSave() { QVERIFY( m_testPlaylist->save( false ) ); } diff --git a/tests/core-impl/playlists/types/file/m3u/TestM3UPlaylist.cpp b/tests/core-impl/playlists/types/file/m3u/TestM3UPlaylist.cpp index 2bd386ebe4..1d7939618d 100644 --- a/tests/core-impl/playlists/types/file/m3u/TestM3UPlaylist.cpp +++ b/tests/core-impl/playlists/types/file/m3u/TestM3UPlaylist.cpp @@ -1,145 +1,145 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestM3UPlaylist.h" #include "config-amarok-test.h" #include "core-impl/collections/support/CollectionManager.h" #include "core-impl/playlists/types/file/m3u/M3UPlaylist.h" #include #include #include #include #include #include -QTEST_MAIN( TestM3UPlaylist ) +QTEST_GUILESS_MAIN( TestM3UPlaylist ) TestM3UPlaylist::TestM3UPlaylist() { } QString TestM3UPlaylist::dataPath( const QString &relPath ) { return QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + '/' + relPath ); } void TestM3UPlaylist::initTestCase() { m_tempDir = new QTemporaryDir; QVERIFY( m_tempDir->isValid() ); qRegisterMetaType( "Meta::TrackPtr" ); /* Collection manager needs to be instantiated in the main thread, but * MetaProxy::Tracks used by playlist may trigger its creation in a different thread. * Pre-create it explicitly */ CollectionManager::instance(); const QUrl url = QUrl::fromLocalFile(dataPath( "data/playlists/test.m3u" )); QFile playlistFile1( url.toLocalFile() ); QTextStream playlistStream; QString tempPath = m_tempDir->path() + "/test.m3u"; QVERIFY( QFile::copy( url.toLocalFile(), tempPath ) ); QVERIFY( QFile::exists( tempPath ) ); QVERIFY( playlistFile1.open( QFile::ReadOnly ) ); playlistStream.setDevice( &playlistFile1 ); QVERIFY( playlistStream.device() ); m_testPlaylist = new Playlists::M3UPlaylist( QUrl::fromLocalFile(tempPath) ); QVERIFY( m_testPlaylist ); QVERIFY( m_testPlaylist->load( playlistStream ) ); QCOMPARE( m_testPlaylist->tracks().size(), 10 ); playlistFile1.close(); } void TestM3UPlaylist::cleanupTestCase() { // Wait for other jobs, like MetaProxys fetching meta data, to finish ThreadWeaver::Queue::instance()->finish(); delete m_testPlaylist; delete m_tempDir; } void TestM3UPlaylist::testSetAndGetName() { QCOMPARE( m_testPlaylist->prettyName(), QString( "test.m3u" ) ); QCOMPARE( m_testPlaylist->name(), QString( "test.m3u" ) ); m_testPlaylist->setName( "set name test" ); QCOMPARE( m_testPlaylist->name(), QString( "set name test.m3u" ) ); m_testPlaylist->setName( "set name test aäoöuüß.m3u" ); QCOMPARE( m_testPlaylist->name(), QString( "set name test aäoöuüß.m3u" ) ); m_testPlaylist->setName( "test" ); m_testPlaylist->setName( "" ); QCOMPARE( m_testPlaylist->name(), QString( "test.m3u" ) ); } void TestM3UPlaylist::testTracks() { Meta::TrackList tracklist = m_testPlaylist->tracks(); QCOMPARE( tracklist.size(), 10 ); QCOMPARE( tracklist.at( 0 )->name(), QString( "Platz 01" ) ); QCOMPARE( tracklist.at( 1 )->name(), QString( "Platz 02" ) ); QCOMPARE( tracklist.at( 2 )->name(), QString( "Platz 03" ) ); QCOMPARE( tracklist.at( 9 )->name(), QString( "Platz 10" ) ); } void TestM3UPlaylist::testUidUrl() { QString tempPath = m_tempDir->path() + "/test.m3u"; //we have chaged the name around so much, better reset it m_testPlaylist->setName( "test" ); QCOMPARE( m_testPlaylist->uidUrl().toLocalFile(), tempPath ); } void TestM3UPlaylist::testSetAndGetGroups() { QStringList grouplist; QStringList newGrouplist; grouplist = m_testPlaylist->groups(); QCOMPARE( grouplist.size(), 0 ); newGrouplist.append( "test" ); m_testPlaylist->setGroups( newGrouplist ); grouplist = m_testPlaylist->groups(); QCOMPARE( grouplist.size(), 1 ); QCOMPARE( grouplist.at(0), QString( "test" ) ); } void TestM3UPlaylist::testIsWritable() { QVERIFY( m_testPlaylist->isWritable() ); } void TestM3UPlaylist::testSave() { QVERIFY( m_testPlaylist->save( false ) ); } diff --git a/tests/core-impl/playlists/types/file/pls/TestPLSPlaylist.cpp b/tests/core-impl/playlists/types/file/pls/TestPLSPlaylist.cpp index 6bec9ac15e..0c0bbd1469 100644 --- a/tests/core-impl/playlists/types/file/pls/TestPLSPlaylist.cpp +++ b/tests/core-impl/playlists/types/file/pls/TestPLSPlaylist.cpp @@ -1,138 +1,138 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestPLSPlaylist.h" #include "core/support/Components.h" #include "config-amarok-test.h" #include "core-impl/collections/support/CollectionManager.h" #include "core-impl/playlists/types/file/pls/PLSPlaylist.h" #include "EngineController.h" #include #include #include #include #include #include -QTEST_MAIN( TestPLSPlaylist ) +QTEST_GUILESS_MAIN( TestPLSPlaylist ) TestPLSPlaylist::TestPLSPlaylist() {} QString TestPLSPlaylist::dataPath( const QString &relPath ) { return QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + '/' + relPath ); } void TestPLSPlaylist::initTestCase() { m_tempDir = new QTemporaryDir; QVERIFY( m_tempDir->isValid() ); // EngineController is used in a connection in MetaProxy::Track; avoid null sender // warning EngineController *controller = new EngineController(); Amarok::Components::setEngineController( controller ); qRegisterMetaType( "Meta::TrackPtr" ); /* Collection manager needs to be instantiated in the main thread, but * MetaProxy::Tracks used by playlist may trigger its creation in a different thread. * Pre-create it explicitly */ CollectionManager::instance(); const QString testPls = "data/playlists/test.pls"; const QUrl url = QUrl::fromLocalFile( dataPath(testPls) ); QFile playlistFile1( url.toLocalFile() ); QTextStream playlistStream; QString tempPath = m_tempDir->path() + "/test.pls"; QVERIFY( QFile::copy( url.toLocalFile(), tempPath ) ); QVERIFY( QFile::exists( tempPath ) ); QVERIFY( playlistFile1.open( QFile::ReadOnly ) ); playlistStream.setDevice( &playlistFile1 ); QVERIFY( playlistStream.device() ); m_testPlaylist1 = new Playlists::PLSPlaylist( QUrl::fromLocalFile(tempPath) ); QVERIFY( m_testPlaylist1 ); QVERIFY( m_testPlaylist1->load( playlistStream ) ); QCOMPARE( m_testPlaylist1->tracks().size(), 4 ); playlistFile1.close(); } void TestPLSPlaylist::cleanupTestCase() { // Wait for other jobs, like MetaProxys fetching meta data, to finish ThreadWeaver::Queue::instance()->finish(); delete m_testPlaylist1; delete m_tempDir; delete Amarok::Components::setEngineController( 0 ); } void TestPLSPlaylist::testSetAndGetName() { QCOMPARE( m_testPlaylist1->name(), QString( "test.pls" ) ); m_testPlaylist1->setName( "set name test" ); QCOMPARE( m_testPlaylist1->name(), QString( "set name test.pls" ) ); m_testPlaylist1->setName( "set name test aäoöuüß" ); QCOMPARE( m_testPlaylist1->name(), QString( "set name test aäoöuüß.pls" ) ); m_testPlaylist1->setName( "test" ); m_testPlaylist1->setName( "" ); QCOMPARE( m_testPlaylist1->name(), QString( "test.pls" ) ); } void TestPLSPlaylist::testPrettyName() { QCOMPARE( m_testPlaylist1->prettyName(), QString( "test.pls" ) ); } void TestPLSPlaylist::testTracks() { Meta::TrackList tracklist = m_testPlaylist1->tracks(); QCOMPARE( tracklist.at( 0 )->name(), QString( "::darkerradio:: - DIE Alternative im Netz ::www.darkerradio.de:: Tune In, Turn On, Burn Out!" ) ); QCOMPARE( tracklist.at( 1 )->name(), QString( "::darkerradio:: - DIE Alternative im Netz ::www.darkerradio.de:: Tune In, Turn On, Burn Out!" ) ); QCOMPARE( tracklist.at( 2 )->name(), QString( "::darkerradio:: - DIE Alternative im Netz ::www.darkerradio.de:: Tune In, Turn On, Burn Out!" ) ); QCOMPARE( tracklist.at( 3 )->name(), QString( "::darkerradio:: - DIE Alternative im Netz ::www.darkerradio.de:: Tune In, Turn On, Burn Out!" ) ); } void TestPLSPlaylist::testUidUrl() { QString tempPath = m_tempDir->path() + "/test.pls"; m_testPlaylist1->setName( "test" ); QCOMPARE( m_testPlaylist1->uidUrl().toLocalFile(), tempPath ); } void TestPLSPlaylist::testIsWritable() { QVERIFY( m_testPlaylist1->isWritable() ); } void TestPLSPlaylist::testSave() { QVERIFY( m_testPlaylist1->save( false ) ); } diff --git a/tests/core-impl/playlists/types/file/xspf/TestXSPFPlaylist.cpp b/tests/core-impl/playlists/types/file/xspf/TestXSPFPlaylist.cpp index d64f38d72d..003b9fd049 100644 --- a/tests/core-impl/playlists/types/file/xspf/TestXSPFPlaylist.cpp +++ b/tests/core-impl/playlists/types/file/xspf/TestXSPFPlaylist.cpp @@ -1,338 +1,338 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestXSPFPlaylist.h" #include "config-amarok-test.h" #include "EngineController.h" #include "core/support/Components.h" #include "core-impl/collections/support/CollectionManager.h" #include "core-impl/playlists/types/file/xspf/XSPFPlaylist.h" #include #include #include #include #include #include -QTEST_MAIN( TestXSPFPlaylist ) +QTEST_GUILESS_MAIN( TestXSPFPlaylist ) TestXSPFPlaylist::TestXSPFPlaylist() {} QString TestXSPFPlaylist::dataPath( const QString &relPath ) { return QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + '/' + relPath ); } void TestXSPFPlaylist::initTestCase() { // EngineController is used in a connection in MetaProxy::Track; avoid null sender // warning EngineController *controller = new EngineController(); Amarok::Components::setEngineController( controller ); qRegisterMetaType( "Meta::TrackPtr" ); /* Collection manager needs to be instantiated in the main thread, but * MetaProxy::Tracks used by playlist may trigger its creation in a different thread. * Pre-create it explicitly */ CollectionManager::instance(); const QString testXspf = "data/playlists/test.xspf"; const QUrl url = QUrl::fromLocalFile(dataPath( testXspf )); QFile playlistFile1( url.toLocalFile() ); QTextStream playlistStream1; QVERIFY( playlistFile1.open( QFile::ReadOnly ) ); playlistStream1.setDevice( &playlistFile1 ); QVERIFY( playlistStream1.device() ); qDebug() << "got playlist path: " << url.url(); //we need to copy this playlist file to a temp dir as some of the tests we do will delete/overwrite it m_tempDir = new QTemporaryDir;; QVERIFY( m_tempDir->isValid() ); QString tempPath = m_tempDir->path() + "/test.xspf"; qDebug() << "got temp path: " << tempPath; QVERIFY( QFile::copy( url.toLocalFile(), tempPath ) ); QVERIFY( QFile::exists( tempPath ) ); m_testPlaylist1 = new Playlists::XSPFPlaylist( QUrl::fromLocalFile(tempPath) ); QVERIFY( m_testPlaylist1 ); QVERIFY( m_testPlaylist1->load( playlistStream1 ) ); } void TestXSPFPlaylist::cleanupTestCase() { QFile::remove( QStandardPaths::locate( QStandardPaths::TempLocation, "test.xspf" ) ); // Wait for other jobs, like MetaProxys fetching meta data, to finish ThreadWeaver::Queue::instance()->finish(); delete m_testPlaylist1; delete m_tempDir; delete Amarok::Components::setEngineController( 0 ); } void TestXSPFPlaylist::testSetAndGetName() { QCOMPARE( m_testPlaylist1->name(), QString( "my playlist" ) ); m_testPlaylist1->setName( "test" ); QCOMPARE( m_testPlaylist1->name(), QString( "test" ) ); m_testPlaylist1->setName( "test aäoöuüß" ); QCOMPARE( m_testPlaylist1->name(), QString( "test aäoöuüß" ) ); m_testPlaylist1->setName( "" ); QCOMPARE( m_testPlaylist1->name(), QString( "" ) ); } void TestXSPFPlaylist::prettyName() { QCOMPARE( m_testPlaylist1->prettyName(), QString( "" ) ); } void TestXSPFPlaylist::testSetAndGetTracks() { Meta::TrackList tracklist = m_testPlaylist1->tracks(); QCOMPARE( tracklist.size(), 23 ); QCOMPARE( tracklist.at( 0 )->name(), QString( "Sunset" ) ); QCOMPARE( tracklist.at( 1 )->name(), QString( "Heaven" ) ); QCOMPARE( tracklist.at( 2 )->name(), QString( "Liquid Sun" ) ); QCOMPARE( tracklist.at( 3 )->name(), QString( "Restrained Mind" ) ); QCOMPARE( tracklist.at( 22 )->name(), QString( "Trash Bag" ) ); } void TestXSPFPlaylist::testSetAndGetTitle() { QCOMPARE( m_testPlaylist1->title(), QString( "" ) ); m_testPlaylist1->setTitle( "test" ); QCOMPARE( m_testPlaylist1->title(), QString( "test" ) ); m_testPlaylist1->setTitle( "test aäoöuüß" ); QCOMPARE( m_testPlaylist1->title(), QString( "test aäoöuüß" ) ); m_testPlaylist1->setTitle( "" ); QCOMPARE( m_testPlaylist1->title(), QString( "" ) ); } void TestXSPFPlaylist::testSetAndGetCreator() { QCOMPARE( m_testPlaylist1->creator(), QString( "" ) ); m_testPlaylist1->setCreator( "test" ); QCOMPARE( m_testPlaylist1->creator(), QString( "test" ) ); m_testPlaylist1->setCreator( "test aäoöuüß" ); QCOMPARE( m_testPlaylist1->creator(), QString( "test aäoöuüß" ) ); m_testPlaylist1->setCreator( "" ); QCOMPARE( m_testPlaylist1->creator(), QString( "" ) ); } void TestXSPFPlaylist::testSetAndGetAnnotation() { QCOMPARE( m_testPlaylist1->annotation(), QString( "" ) ); m_testPlaylist1->setAnnotation( "test" ); QCOMPARE( m_testPlaylist1->annotation(), QString( "test" ) ); m_testPlaylist1->setAnnotation( "test aäoöuüß" ); QCOMPARE( m_testPlaylist1->annotation(), QString( "test aäoöuüß" ) ); m_testPlaylist1->setAnnotation( "" ); QCOMPARE( m_testPlaylist1->annotation(), QString( "" ) ); } void TestXSPFPlaylist::testSetAndGetInfo() { QUrl testUrl; QCOMPARE( m_testPlaylist1->info(), QUrl( "" ) ); testUrl = QUrl::fromUserInput("http://amarok.kde.org"); m_testPlaylist1->setInfo( testUrl ); QCOMPARE( m_testPlaylist1->info(), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput("http://öko.de"); m_testPlaylist1->setInfo( testUrl ); QCOMPARE( m_testPlaylist1->info(), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput(""); m_testPlaylist1->setInfo( testUrl ); QCOMPARE( m_testPlaylist1->info(), QUrl( "" ) ); } void TestXSPFPlaylist::testSetAndGetLocation() { QUrl testUrl; QCOMPARE( m_testPlaylist1->location(), QUrl( "" ) ); testUrl = QUrl::fromUserInput("http://amarok.kde.org"); m_testPlaylist1->setLocation( testUrl ); QCOMPARE( m_testPlaylist1->location(), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput("http://öko.de"); m_testPlaylist1->setLocation( testUrl ); QCOMPARE( m_testPlaylist1->location(), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput(""); m_testPlaylist1->setLocation( testUrl ); QCOMPARE( m_testPlaylist1->location(), QUrl( "" ) ); } void TestXSPFPlaylist::testSetAndGetIdentifier() { QCOMPARE( m_testPlaylist1->identifier(), QString( "" ) ); m_testPlaylist1->setIdentifier( "test" ); QCOMPARE( m_testPlaylist1->identifier(), QString( "test" ) ); m_testPlaylist1->setIdentifier( "test aäoöuüß" ); QCOMPARE( m_testPlaylist1->identifier(), QString( "test aäoöuüß" ) ); m_testPlaylist1->setIdentifier( "" ); QCOMPARE( m_testPlaylist1->identifier(), QString( "" ) ); } void TestXSPFPlaylist::testSetAndGetImage() { QUrl testUrl; QCOMPARE( m_testPlaylist1->image(), QUrl( "" ) ); testUrl = QUrl::fromUserInput("http://amarok.kde.org"); m_testPlaylist1->setImage( testUrl ); QCOMPARE( m_testPlaylist1->image(), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput("http://öko.de"); m_testPlaylist1->setImage( testUrl ); QCOMPARE( m_testPlaylist1->image(), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput(""); m_testPlaylist1->setImage( testUrl ); QCOMPARE( m_testPlaylist1->image(), QUrl( "" ) ); } void TestXSPFPlaylist::testSetAndGetDate() { QDateTime testDateTime; QCOMPARE( m_testPlaylist1->date().toString(), QString( "" ) ); testDateTime = QDateTime::fromString( "2009/08/13 13:57:18", "yyyy/MM/dd hh:mm:ss" ); m_testPlaylist1->setDate( testDateTime ); QCOMPARE( m_testPlaylist1->date(), testDateTime ); testDateTime = QDateTime::fromString( "", "" ); m_testPlaylist1->setDate( testDateTime ); QCOMPARE( m_testPlaylist1->date(), testDateTime ); } void TestXSPFPlaylist::testSetAndGetLicense() { QUrl testUrl; QCOMPARE( m_testPlaylist1->license(), QUrl( "" ) ); testUrl = QUrl::fromUserInput("http://amarok.kde.org"); m_testPlaylist1->setLicense( testUrl ); QCOMPARE( m_testPlaylist1->license(), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput("http://öko.de"); m_testPlaylist1->setLicense( testUrl ); QCOMPARE( m_testPlaylist1->license(), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput(""); m_testPlaylist1->setLicense( testUrl ); QCOMPARE( m_testPlaylist1->license(), QUrl( "" ) ); } void TestXSPFPlaylist::testSetAndGetAttribution() { QUrl testUrl; QCOMPARE( m_testPlaylist1->attribution().size(), 0 ); testUrl = QUrl::fromUserInput("http://amarok.kde.org"); m_testPlaylist1->setAttribution( testUrl ); QCOMPARE( m_testPlaylist1->attribution().size(), 1 ); QCOMPARE( m_testPlaylist1->attribution().at( 0 ), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput("http://öko.de"); m_testPlaylist1->setAttribution( testUrl ); QCOMPARE( m_testPlaylist1->attribution().size(), 2 ); QCOMPARE( m_testPlaylist1->attribution().at( 0 ), QUrl( testUrl ) ); QCOMPARE( m_testPlaylist1->attribution().at( 1 ), QUrl("http://amarok.kde.org") ); testUrl = QUrl::fromUserInput("http://test.com"); m_testPlaylist1->setAttribution( testUrl, false ); QCOMPARE( m_testPlaylist1->attribution().size(), 1 ); QCOMPARE( m_testPlaylist1->attribution().at( 0 ), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput(""); m_testPlaylist1->setAttribution( testUrl ); QCOMPARE( m_testPlaylist1->attribution().size(), 1 ); // empty url won't be added, but size is 1 from last addition } void TestXSPFPlaylist::testSetAndGetLink() { QUrl testUrl; QCOMPARE( m_testPlaylist1->link(), QUrl( "" ) ); testUrl = QUrl::fromUserInput("http://amarok.kde.org"); m_testPlaylist1->setLink( testUrl ); QCOMPARE( m_testPlaylist1->link(), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput("http://öko.de"); m_testPlaylist1->setLink( testUrl ); QCOMPARE( m_testPlaylist1->link(), QUrl( testUrl ) ); testUrl = QUrl::fromUserInput(""); m_testPlaylist1->setLink( testUrl ); QCOMPARE( m_testPlaylist1->link(), QUrl( "" ) ); } void TestXSPFPlaylist::testUidUrl() { QString tempPath = m_tempDir->path() + "/test.xspf"; //we have chaged the name around so much, better reset it m_testPlaylist1->setName( "test" ); QCOMPARE( m_testPlaylist1->uidUrl().toLocalFile(), tempPath ); } void TestXSPFPlaylist::testIsWritable() { QVERIFY( m_testPlaylist1->isWritable() ); } void TestXSPFPlaylist::testSave() { QVERIFY( m_testPlaylist1->save( false ) ); } diff --git a/tests/core-impl/support/TestTrackLoader.cpp b/tests/core-impl/support/TestTrackLoader.cpp index 5132486b98..f619f34df9 100644 --- a/tests/core-impl/support/TestTrackLoader.cpp +++ b/tests/core-impl/support/TestTrackLoader.cpp @@ -1,171 +1,171 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * Copyright (c) 2013 Matěj Laitl * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestTrackLoader.h" #include "amarokconfig.h" #include "config-amarok-test.h" #include "core/meta/Meta.h" #include "core-impl/collections/support/CollectionManager.h" #include "core-impl/meta/proxy/MetaProxy.h" #include "core-impl/playlists/types/file/PlaylistFileSupport.h" #include "core-impl/support/TrackLoader.h" #include #include #include -QTEST_MAIN( TestTrackLoader ) +QTEST_GUILESS_MAIN( TestTrackLoader ) void TestTrackLoader::initTestCase() { AmarokConfig::instance("amarokrc"); qRegisterMetaType(); qRegisterMetaType(); CollectionManager::instance(); // create in the main thread } void TestTrackLoader::cleanupTestCase() { // Wait for other jobs, like MetaProxys fetching meta data, to finish ThreadWeaver::Queue::instance()->finish(); } void TestTrackLoader::testFullMetadataInit() { typedef QPair StringIntPair; QList pathsCounts; pathsCounts << qMakePair( dataPath( "data/audio/album" ), 3 ) << qMakePair( dataPath( "data/audio/album2" ), 2 ) << qMakePair( dataPath( "data/playlists/test.asx" ), 1 ) << qMakePair( dataPath( "data/playlists/test.m3u" ), 10 ) << qMakePair( dataPath( "data/playlists/test.pls" ), 4 ) << qMakePair( dataPath( "data/playlists/test.xspf" ), 23 ); // it is more probable to get unresolved MetaProxy::Track for small runs: for( const StringIntPair &pair : pathsCounts ) { TrackLoader *loader = new TrackLoader( TrackLoader::FullMetadataRequired ); QSignalSpy spy( loader, &TrackLoader::finished ); loader->init( QUrl::fromLocalFile( pair.first ) ); QVERIFY2( spy.wait( 15000 ), "loader did not finish within timeout" ); Meta::TrackList found = spy.first().first().value(); QCOMPARE( found.count(), pair.second ); for( const Meta::TrackPtr &track : found ) { MetaProxy::TrackPtr proxyTrack = MetaProxy::TrackPtr::dynamicCast( track ); if( !proxyTrack ) { qDebug() << track->prettyUrl() << "is not a MetaProxy::Track. Strange and we cannot test it"; continue; } QVERIFY2( proxyTrack->isResolved(), proxyTrack->prettyUrl().toLocal8Bit().data() ); } delete loader; } } void TestTrackLoader::testInit() { TrackLoader *loader1 = new TrackLoader(); QSignalSpy spy1( loader1, &TrackLoader::finished ); loader1->init( QUrl::fromLocalFile( dataPath( "data/audio" ) ) ); // test the convenience overload QVERIFY2( spy1.wait( 5000 ), "loader1 did not finish within timeout" ); Meta::TrackList found = spy1.first().first().value(); QCOMPARE( found.count(), 15 ); QVERIFY2( found.at( 0 )->uidUrl().endsWith( "audio/album/Track01.ogg" ), found.at( 0 )->uidUrl().toLocal8Bit().data() ); QVERIFY2( found.at( 1 )->uidUrl().endsWith( "audio/album/Track02.ogg" ), found.at( 1 )->uidUrl().toLocal8Bit().data() ); QVERIFY2( found.at( 2 )->uidUrl().endsWith( "audio/album/Track03.ogg" ), found.at( 2 )->uidUrl().toLocal8Bit().data() ); QVERIFY2( found.at( 3 )->uidUrl().endsWith( "audio/album2/Track01.ogg" ), found.at( 3 )->uidUrl().toLocal8Bit().data() ); QVERIFY2( found.at( 4 )->uidUrl().endsWith( "audio/album2/Track02.ogg" ), found.at( 4 )->uidUrl().toLocal8Bit().data() ); QVERIFY2( found.at( 5 )->uidUrl().endsWith( "audio/Platz 01.mp3" ), found.at( 5 )->uidUrl().toLocal8Bit().data() ); QVERIFY2( found.at( 10 )->uidUrl().endsWith( "audio/Platz 06.mp3" ), found.at( 10 )->uidUrl().toLocal8Bit().data() ); QVERIFY2( found.at( 14 )->uidUrl().endsWith( "audio/Platz 10.mp3" ), found.at( 14 )->uidUrl().toLocal8Bit().data() ); TrackLoader *loader2 = new TrackLoader(); QSignalSpy spy2( loader2, &TrackLoader::finished ); loader2->init( QList() << QUrl::fromLocalFile( dataPath( "data/audio/album2" ) ) ); QVERIFY2( spy2.wait( 5000 ), "loader2 did not finish within timeout" ); found = spy2.first().first().value(); QCOMPARE( found.count(), 2 ); QVERIFY2( found.at( 0 )->uidUrl().endsWith( "audio/album2/Track01.ogg" ), found.at( 0 )->uidUrl().toLocal8Bit().data() ); QVERIFY2( found.at( 1 )->uidUrl().endsWith( "audio/album2/Track02.ogg" ), found.at( 1 )->uidUrl().toLocal8Bit().data() ); } void TestTrackLoader::testInitWithPlaylists() { TrackLoader *loader = new TrackLoader(); QSignalSpy spy( loader, &TrackLoader::finished ); QList urls; urls << QUrl::fromLocalFile( dataPath( "data/playlists/test.asx" ) ) << QUrl::fromLocalFile( dataPath( "data/audio/album" ) ) << QUrl::fromLocalFile( dataPath( "data/playlists/test.xspf" ) ); loader->init( urls ); QVERIFY2( spy.wait( 5000 ), "loader did not finish within timeout" ); Meta::TrackList found = spy.first().first().value(); QCOMPARE( found.count(), 1 + 3 + 23 ); QVERIFY( found.at( 0 )->uidUrl().endsWith( "/audio/album/Track01.ogg" ) ); // "audio/album" folder QVERIFY( found.at( 1 )->uidUrl().endsWith( "/audio/album/Track02.ogg" ) ); QVERIFY( found.at( 2 )->uidUrl().endsWith( "/audio/album/Track03.ogg" ) ); QCOMPARE( found.at( 3 )->uidUrl(), QString( "http://85.214.44.27:8000" ) ); // test.asx playlist QCOMPARE( found.at( 4 )->uidUrl(), QString( "http://he3.magnatune.com/all/01-Sunset-Ammonite.ogg" ) ); // start of test.xspf playlist QCOMPARE( found.at( 5 )->uidUrl(), QString( "http://he3.magnatune.com/all/02-Heaven-Ammonite.ogg" ) ); } void TestTrackLoader::testDirectlyPassingPlaylists() { using namespace Playlists; TrackLoader *loader = new TrackLoader(); QSignalSpy spy( loader, &TrackLoader::finished ); PlaylistList playlists; playlists << PlaylistPtr::staticCast( loadPlaylistFile( QUrl::fromLocalFile( dataPath( "data/playlists/test.asx" ) ) ) ) << PlaylistPtr::staticCast( loadPlaylistFile( QUrl::fromLocalFile( dataPath( "data/playlists/test.xspf" ) ) ) ); loader->init( playlists ); QVERIFY2( spy.wait( 5000 ), "loader did not finish within timeout" ); Meta::TrackList found = spy.first().first().value(); QCOMPARE( found.count(), 1 + 23 ); QCOMPARE( found.at( 0 )->uidUrl(), QString( "http://85.214.44.27:8000" ) ); // test.asx playlist QCOMPARE( found.at( 1 )->uidUrl(), QString( "http://he3.magnatune.com/all/01-Sunset-Ammonite.ogg" ) ); // start of test.xspf playlist QCOMPARE( found.at( 2 )->uidUrl(), QString( "http://he3.magnatune.com/all/02-Heaven-Ammonite.ogg" ) ); } QString TestTrackLoader::dataPath( const QString &relPath ) { return QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + '/' + relPath ); } diff --git a/tests/core/collections/CollectionLocationTest.cpp b/tests/core/collections/CollectionLocationTest.cpp index dcbe57d4f1..ad24d6d899 100644 --- a/tests/core/collections/CollectionLocationTest.cpp +++ b/tests/core/collections/CollectionLocationTest.cpp @@ -1,184 +1,184 @@ /**************************************************************************************** * Copyright (c) 2009,2010 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "CollectionLocationTest.h" #include "core/support/Components.h" #include "core/collections/CollectionLocation.h" #include "core/support/Debug.h" #include "core/meta/support/MetaConstants.h" #include "../tests/mocks/MetaMock.h" #include "MockCollectionLocationDelegate.h" #include #include #include #include -QTEST_MAIN( CollectionLocationTest ) +QTEST_GUILESS_MAIN( CollectionLocationTest ) using ::testing::Return; using ::testing::AnyNumber; using ::testing::_; CollectionLocationTest::CollectionLocationTest() { qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); } namespace Collections { class TestRemoveCL : public CollectionLocation { public: void removeUrlsFromCollection( const Meta::TrackList &tracks ) { count += tracks.count(); slotRemoveOperationFinished(); } MOCK_CONST_METHOD0( isWritable, bool() ); MOCK_CONST_METHOD0( isOrganizable, bool() ); int count; }; } //namespace Collections void CollectionLocationTest::testSuccessfulCopy() { Collections::MockCollectionLocationDelegate *cld = new Collections::MockCollectionLocationDelegate(); EXPECT_CALL( *cld, reallyDelete( _, _) ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); Amarok::Components::setCollectionLocationDelegate( cld ); Collections::TestRemoveCL *cl = new Collections::TestRemoveCL(); QSignalSpy spy( cl, &Collections::TestRemoveCL::destroyed ); EXPECT_CALL( *cl, isWritable() ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); cl->setProperty( "removeSources", true ); cl->count = 0; QVariantMap map; map.insert( Meta::Field::URL, QUrl("file:///IDoNotExist.mp3") ); Meta::TrackPtr file1( new MetaMock( map ) ); cl->transferSuccessful( file1 ); QVERIFY2( cl->metaObject()->invokeMethod( cl, "slotFinishCopy", Qt::DirectConnection ), "Calling slot failed" ); QCOMPARE( cl->count, 1 ); QVERIFY( spy.wait( 5000 ) ); delete Amarok::Components::setCollectionLocationDelegate( 0 ); } void CollectionLocationTest::testFailedCopy() { Collections::MockCollectionLocationDelegate *cld = new Collections::MockCollectionLocationDelegate(); EXPECT_CALL( *cld, reallyDelete( _, _) ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); EXPECT_CALL( *cld, errorDeleting( _, _ ) ).Times( AnyNumber() ); Amarok::Components::setCollectionLocationDelegate( cld ); Collections::TestRemoveCL *cl = new Collections::TestRemoveCL(); EXPECT_CALL( *cl, isWritable() ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); QSignalSpy spy( cl, &Collections::TestRemoveCL::destroyed ); cl->setProperty( "removeSources", true ); cl->count = 0; QVariantMap map; map.insert( Meta::Field::URL, QUrl("file:///IDoNotExist.mp3") ); Meta::TrackPtr file1( new MetaMock( map ) ); cl->transferError( file1, "Test of CollectionLocation" ); QVERIFY2( cl->metaObject()->invokeMethod( cl, "slotFinishCopy", Qt::DirectConnection ), "Calling slot failed" ); QCOMPARE( cl->count, 0 ); QVERIFY( spy.wait( 5000 ) ); delete Amarok::Components::setCollectionLocationDelegate( 0 ); } void CollectionLocationTest::testCopyMultipleTracks() { Collections::MockCollectionLocationDelegate *cld = new Collections::MockCollectionLocationDelegate(); EXPECT_CALL( *cld, reallyDelete( _, _) ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); EXPECT_CALL( *cld, errorDeleting( _, _ ) ).Times( AnyNumber() ); Amarok::Components::setCollectionLocationDelegate( cld ); Collections::TestRemoveCL *cl = new Collections::TestRemoveCL(); QSignalSpy spy( cl, &Collections::TestRemoveCL::destroyed ); EXPECT_CALL( *cl, isWritable() ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); cl->setProperty( "removeSources", true ); cl->count = 0; QVariantMap map; map.insert( Meta::Field::URL, QUrl("file:///IDoNotExist.mp3") ); Meta::TrackPtr file1( new MetaMock( map ) ); map.insert( Meta::Field::URL, QUrl("file:///IDoNotExistAsWell.mp3") ); Meta::TrackPtr file2( new MetaMock( map ) ); map.insert( Meta::Field::URL, QUrl("file:///IDoNotExistAsWell.mp3") ); Meta::TrackPtr file3( new MetaMock( map ) ); cl->transferError( file1, "Test of CollectionLocation" ); cl->transferSuccessful( file2 ); cl->transferSuccessful( file3 ); cl->metaObject()->invokeMethod( cl, "slotFinishCopy", Qt::DirectConnection ); QCOMPARE( cl->count, 2 ); QVERIFY( spy.wait( 5000 ) ); delete Amarok::Components::setCollectionLocationDelegate( 0 ); } void CollectionLocationTest::testFailedCopyWithIncorrectUsageOfCopySuccesful() { Collections::MockCollectionLocationDelegate *cld = new Collections::MockCollectionLocationDelegate(); EXPECT_CALL( *cld, reallyDelete( _, _) ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); EXPECT_CALL( *cld, errorDeleting( _, _ ) ).Times( AnyNumber() ); Amarok::Components::setCollectionLocationDelegate( cld ); Collections::TestRemoveCL *cl = new Collections::TestRemoveCL(); EXPECT_CALL( *cl, isWritable() ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); QSignalSpy spy1( cl, &Collections::TestRemoveCL::destroyed ); cl->setProperty( "removeSources", true ); cl->count = 0; QVariantMap map; map.insert( Meta::Field::URL, QUrl("file:///IDoNotExist.mp3") ); Meta::TrackPtr file1( new MetaMock( map ) ); cl->transferError( file1, "Test of CollectionLocation" ); cl->transferSuccessful( file1 ); cl->metaObject()->invokeMethod( cl, "slotFinishCopy", Qt::DirectConnection ); QVERIFY2( cl->count == 0, "Expected no call to remove"); QVERIFY( spy1.wait( 5000 ) ); delete Amarok::Components::setCollectionLocationDelegate( 0 ); cld = new Collections::MockCollectionLocationDelegate(); EXPECT_CALL( *cld, reallyDelete( _, _) ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); EXPECT_CALL( *cld, errorDeleting( _, _ ) ).Times( AnyNumber() ); Amarok::Components::setCollectionLocationDelegate( cld ); cl = new Collections::TestRemoveCL(); EXPECT_CALL( *cl, isWritable() ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); QSignalSpy spy2( cl, &Collections::TestRemoveCL::destroyed ); cl->setProperty( "removeSources", true ); cl->count = 0; file1 = Meta::TrackPtr( new MetaMock( map ) ); cl->transferSuccessful( file1 ); cl->transferError( file1, "Test of CollectionLocation" ); cl->metaObject()->invokeMethod( cl, "slotFinishCopy", Qt::DirectConnection ); QVERIFY2( cl->count == 0, "Expected no call to remove after reversed method call"); QVERIFY( spy2.wait( 5000 ) ); delete Amarok::Components::setCollectionLocationDelegate( 0 ); } diff --git a/tests/core/collections/TestQueryMaker.cpp b/tests/core/collections/TestQueryMaker.cpp index 81255a4735..6520780743 100644 --- a/tests/core/collections/TestQueryMaker.cpp +++ b/tests/core/collections/TestQueryMaker.cpp @@ -1,80 +1,80 @@ /**************************************************************************************** * Copyright (c) 2012 Jasneet Singh Bhatti * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestQueryMaker.h" #include "mocks/MockQueryMaker.h" #include using namespace Collections; -QTEST_MAIN( TestQueryMaker ) +QTEST_GUILESS_MAIN( TestQueryMaker ) void TestQueryMaker::initTestCase() { m_mockQueryMaker = new MockQueryMaker(); QVERIFY( m_mockQueryMaker ); } void TestQueryMaker::cleanupTestCase() { if( !m_mockQueryMaker.isNull() ) delete m_mockQueryMaker; } void TestQueryMaker::testSetAutoDelete_data() { QTest::addColumn( "autoDelete" ); QTest::newRow( "false value" ) << false; QTest::newRow( "true value" ) << true; } void TestQueryMaker::testSetAutoDelete() { QFETCH( bool, autoDelete ); QSignalSpy spyQueryDone( m_mockQueryMaker, &MockQueryMaker::queryDone ); QSignalSpy spyDestroyed( m_mockQueryMaker, &MockQueryMaker::destroyed ); m_mockQueryMaker->setAutoDelete( autoDelete ); QVERIFY( m_mockQueryMaker ); m_mockQueryMaker->emitQueryDone(); // Ensure that queryDone() was indeed emitted QCOMPARE( spyQueryDone.count(), 1 ); spyDestroyed.wait( 5000 ); if( autoDelete ) { // Signal queryDone() is connected to slot deleteLater() // and the destroyed() signal is emitted QCOMPARE( spyDestroyed.count(), 1 ); } else { // Signal queryDone() is disconnected from slot deleteLater() // and no destroyed() signal is emitted QCOMPARE( spyDestroyed.count(), 0 ); } } diff --git a/tests/core/collections/support/TestTrackForUrlWorker.cpp b/tests/core/collections/support/TestTrackForUrlWorker.cpp index 1153657d23..08555a253f 100644 --- a/tests/core/collections/support/TestTrackForUrlWorker.cpp +++ b/tests/core/collections/support/TestTrackForUrlWorker.cpp @@ -1,118 +1,118 @@ /**************************************************************************************** * Copyright (c) 2012 Jasneet Singh Bhatti * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestTrackForUrlWorker.h" #include "amarokconfig.h" #include "config-amarok-test.h" #include "core-impl/collections/support/CollectionManager.h" #include "mocks/MockTrackForUrlWorker.h" #include #include #include #include #include -QTEST_MAIN( TestTrackForUrlWorker ) +QTEST_GUILESS_MAIN( TestTrackForUrlWorker ) void TestTrackForUrlWorker::initTestCase() { // To make queued signals/slots work with custom payload qRegisterMetaType( "Meta::TrackPtr" ); qRegisterMetaType( "ThreadWeaver::Job*" ); AmarokConfig::instance("amarokrc"); } QString TestTrackForUrlWorker::dataPath( const QString &relPath ) { return QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + '/' + relPath ); } void TestTrackForUrlWorker::testCompleteJobQUrl_data() { testCompleteJobInternal_data(); } void TestTrackForUrlWorker::testCompleteJobQUrl() { QUrl url; MockTrackForUrlWorker *trackForUrlWorker = new MockTrackForUrlWorker( url ); QVERIFY( trackForUrlWorker ); testCompleteJobInternal( trackForUrlWorker ); } void TestTrackForUrlWorker::testCompleteJobQString_data() { testCompleteJobInternal_data(); } void TestTrackForUrlWorker::testCompleteJobQString() { QString url; MockTrackForUrlWorker *trackForUrlWorker = new MockTrackForUrlWorker( url ); QVERIFY( trackForUrlWorker ); testCompleteJobInternal( trackForUrlWorker ); } void TestTrackForUrlWorker::testCompleteJobInternal_data() { QTest::addColumn( "track" ); QTest::newRow( "track 1" ) << CollectionManager::instance()->trackForUrl( QUrl::fromLocalFile(dataPath( "data/audio/album/Track01.ogg" )) ); QTest::newRow( "track 2" ) << CollectionManager::instance()->trackForUrl( QUrl::fromLocalFile(dataPath( "data/audio/album/Track02.ogg" )) ); QTest::newRow( "track 3" ) << CollectionManager::instance()->trackForUrl( QUrl::fromLocalFile(dataPath( "data/audio/album/Track03.ogg" )) ); } void TestTrackForUrlWorker::testCompleteJobInternal( MockTrackForUrlWorker *trackForUrlWorker ) { // Connect finishedLookup with setEmittedTrack() that will store the emitted track connect( trackForUrlWorker, &MockTrackForUrlWorker::finishedLookup, this, &TestTrackForUrlWorker::setEmittedTrack ); QSignalSpy spyFinishedLookup( trackForUrlWorker, &MockTrackForUrlWorker::finishedLookup ); QSignalSpy spyDone( trackForUrlWorker, &MockTrackForUrlWorker::done ); // Enqueue the job for execution and verify that it emits done when finished, which triggers completeJob ThreadWeaver::Queue::instance()->enqueue( QSharedPointer( trackForUrlWorker ) ); bool receivedDone = spyDone.wait( 1000 ); QVERIFY( receivedDone ); // Verify that finishedLookup was emitted QCOMPARE( spyFinishedLookup.count(), 1 ); // Verify that the track emitted with finishedLookup is indeed the track set by run() QFETCH( Meta::TrackPtr, track ); QCOMPARE( m_emittedTrack, track ); } void TestTrackForUrlWorker::setEmittedTrack( Meta::TrackPtr track ) { m_emittedTrack = track; } diff --git a/tests/core/meta/TestMetaTrack.cpp b/tests/core/meta/TestMetaTrack.cpp index 197676cad3..a0aae1b023 100644 --- a/tests/core/meta/TestMetaTrack.cpp +++ b/tests/core/meta/TestMetaTrack.cpp @@ -1,266 +1,266 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestMetaTrack.h" #include "amarokconfig.h" #include "config-amarok-test.h" #include "core/meta/Meta.h" #include "core/meta/Statistics.h" #include "core-impl/collections/support/CollectionManager.h" #include -QTEST_MAIN( TestMetaTrack ) +QTEST_GUILESS_MAIN( TestMetaTrack ) TestMetaTrack::TestMetaTrack() : m_trackPath( dataPath( "/data/audio/Platz 01.mp3" ) ) {} TestMetaTrack::~TestMetaTrack() { } QString TestMetaTrack::dataPath( const QString &relPath ) { return QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + '/' + relPath ); } void TestMetaTrack::initTestCase() { AmarokConfig::instance("amarokrc"); QString oldPath = m_trackPath; m_trackPath = m_tempDir.path() + "TestMetaTrack-testTrack.mp3"; QVERIFY( QFile::copy( oldPath, m_trackPath ) ); m_testTrack1 = CollectionManager::instance()->trackForUrl( QUrl::fromLocalFile(m_trackPath) ); // If the pointer is 0, it makes no sense to continue. We would crash with a qFatal(). QVERIFY2( m_testTrack1, "The pointer to the test track is 0." ); // we need to enable this, otherwise testSetAndGetScore, testSetAndGetRating fails AmarokConfig::setWriteBackStatistics( true ); } void TestMetaTrack::testPrettyName() { QCOMPARE( m_testTrack1->prettyName(), QString( "Platz 01" ) ); } void TestMetaTrack::testPlayableUrl() { QCOMPARE( m_testTrack1->playableUrl().path(), m_trackPath ); } void TestMetaTrack::testPrettyUrl() { QCOMPARE( m_testTrack1->prettyUrl(), m_trackPath ); } void TestMetaTrack::testUidUrl() { QCOMPARE( m_testTrack1->uidUrl(), QUrl::fromLocalFile(m_trackPath ).url() ); } void TestMetaTrack::testIsPlayable() { QCOMPARE( m_testTrack1->isPlayable(), true ); } void TestMetaTrack::testAlbum() { QCOMPARE( m_testTrack1->album()->name() , QString( "" ) ); } void TestMetaTrack::testArtist() { QCOMPARE( m_testTrack1->artist()->name(), QString( "Free Music Charts" ) ); } void TestMetaTrack::testComposer() { QCOMPARE( m_testTrack1->composer()->name(), QString( "" ) ); } void TestMetaTrack::testGenre() { QCOMPARE( m_testTrack1->genre()->name(), QString( "Vocal" ) ); } void TestMetaTrack::testYear() { QCOMPARE( m_testTrack1->year()->name(), QString( "2010" ) ); } void TestMetaTrack::testComment() { QCOMPARE( m_testTrack1->comment(), QString( "" ) ); } void TestMetaTrack::testSetAndGetScore() { Meta::StatisticsPtr statistics = m_testTrack1->statistics(); QCOMPARE( statistics->score(), 0.0 ); /* now the code actually stores the score in track and then it reads it back. * the precision it uses is pretty low and it was failing the qFuzzyCompare * Just make it use qFuzzyCompare() */ statistics->setScore( 3 ); QCOMPARE( float( statistics->score() ), float( 3.0 ) ); statistics->setScore( 12.55 ); QCOMPARE( float( statistics->score() ), float( 12.55 ) ); statistics->setScore( 100 ); QCOMPARE( float( statistics->score() ), float( 100.0 ) ); statistics->setScore( 0 ); QCOMPARE( float( statistics->score() ), float( 0.0 ) ); } void TestMetaTrack::testSetAndGetRating() { Meta::StatisticsPtr statistics = m_testTrack1->statistics(); QCOMPARE( statistics->rating(), 0 ); statistics->setRating( 3 ); QCOMPARE( statistics->rating(), 3 ); statistics->setRating( 10 ); QCOMPARE( statistics->rating(), 10 ); statistics->setRating( 0 ); QCOMPARE( statistics->rating(), 0 ); } void TestMetaTrack::testLength() { QCOMPARE( m_testTrack1->length(), 12000LL ); } void TestMetaTrack::testFilesize() { QCOMPARE( m_testTrack1->filesize(), 389454 ); } void TestMetaTrack::testSampleRate() { QCOMPARE( m_testTrack1->sampleRate(), 44100 ); } void TestMetaTrack::testBitrate() { QCOMPARE( m_testTrack1->bitrate(), 257 ); } void TestMetaTrack::testTrackNumber() { QCOMPARE( m_testTrack1->trackNumber(), 0 ); } void TestMetaTrack::testDiscNumber() { QCOMPARE( m_testTrack1->discNumber(), 0 ); } void TestMetaTrack::testLastPlayed() { QCOMPARE( m_testTrack1->statistics()->lastPlayed().toTime_t(), 4294967295U ); // portability? } void TestMetaTrack::testFirstPlayed() { QCOMPARE( m_testTrack1->statistics()->firstPlayed().toTime_t(), 4294967295U ); // portability? } void TestMetaTrack::testPlayCount() { QCOMPARE( m_testTrack1->statistics()->playCount(), 0 ); } void TestMetaTrack::testReplayGain() { QCOMPARE( int(m_testTrack1->replayGain( Meta::ReplayGain_Track_Gain ) * 1000), -6655 ); QCOMPARE( int(m_testTrack1->replayGain( Meta::ReplayGain_Album_Gain ) * 1000), -6655 ); QCOMPARE( int(m_testTrack1->replayGain( Meta::ReplayGain_Track_Peak ) * 10000), 41263 ); QCOMPARE( int(m_testTrack1->replayGain( Meta::ReplayGain_Album_Peak ) * 10000), 41263 ); } void TestMetaTrack::testType() { QCOMPARE( m_testTrack1->type(), QString( "mp3" ) ); } void TestMetaTrack::testInCollection() { QVERIFY( !m_testTrack1->inCollection() ); } void TestMetaTrack::testCollection() { QVERIFY( !m_testTrack1->collection() ); } void TestMetaTrack::testSetAndGetCachedLyrics() { /* TODO: setCachedLyrics is not yet implemented QCOMPARE( m_testTrack1->cachedLyrics(), QString( "" ) ); m_testTrack1->setCachedLyrics( "test" ); QCOMPARE( m_testTrack1->cachedLyrics(), QString( "test" ) ); m_testTrack1->setCachedLyrics( "aäaüoöß" ); QCOMPARE( m_testTrack1->cachedLyrics(), QString( "aäaüoöß" ) ); m_testTrack1->setCachedLyrics( "" ); QCOMPARE( m_testTrack1->cachedLyrics(), QString( "" ) ); */ } void TestMetaTrack::testOperatorEquals() { QVERIFY( m_testTrack1 == m_testTrack1 ); QVERIFY( m_testTrack1 != m_testTrack2 ); } void TestMetaTrack::testLessThan() { Meta::TrackPtr albumTrack1, albumTrack2, albumTrack3; albumTrack1 = CollectionManager::instance()->trackForUrl( QUrl::fromLocalFile(dataPath( "data/audio/album/Track01.ogg" )) ); albumTrack2 = CollectionManager::instance()->trackForUrl( QUrl::fromLocalFile(dataPath( "data/audio/album/Track02.ogg" )) ); albumTrack3 = CollectionManager::instance()->trackForUrl( QUrl::fromLocalFile(dataPath( "data/audio/album/Track03.ogg" )) ); QVERIFY( albumTrack1 ); QVERIFY( albumTrack2 ); QVERIFY( albumTrack3 ); QVERIFY( !Meta::Track::lessThan( m_testTrack1, m_testTrack1 ) ); QVERIFY( Meta::Track::lessThan( albumTrack1, albumTrack2 ) ); QVERIFY( Meta::Track::lessThan( albumTrack2, albumTrack3 ) ); QVERIFY( Meta::Track::lessThan( albumTrack1, albumTrack3 ) ); QVERIFY( !Meta::Track::lessThan( albumTrack3, albumTrack2 ) ); QVERIFY( !Meta::Track::lessThan( albumTrack3, albumTrack1 ) ); QVERIFY( !Meta::Track::lessThan( albumTrack3, albumTrack3 ) ); } diff --git a/tests/core/playlists/TestPlaylistFormat.cpp b/tests/core/playlists/TestPlaylistFormat.cpp index 3e2e244b66..8fda5df348 100644 --- a/tests/core/playlists/TestPlaylistFormat.cpp +++ b/tests/core/playlists/TestPlaylistFormat.cpp @@ -1,113 +1,113 @@ /**************************************************************************************** * Copyright (c) 2012 Jasneet Singh Bhatti * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestPlaylistFormat.h" #include "core/playlists/PlaylistFormat.h" #include // so that PlaylistFormat can be used in QTest::addColumn() Q_DECLARE_METATYPE( Playlists::PlaylistFormat ) -QTEST_MAIN( TestPlaylistFormat ) +QTEST_GUILESS_MAIN( TestPlaylistFormat ) TestPlaylistFormat::TestPlaylistFormat() { } void TestPlaylistFormat::testGetFormat_data() { QTest::addColumn( "filename" ); QTest::addColumn( "playlistFormat" ); // valid formats QTest::newRow( "m3u" ) << "playlist.m3u" << Playlists::M3U; QTest::newRow( "m3u8" ) << "playlist.m3u8" << Playlists::M3U; QTest::newRow( "pls" ) << "playlist.pls" << Playlists::PLS; QTest::newRow( "ram" ) << "playlist.ram" << Playlists::RAM; QTest::newRow( "smil" ) << "playlist.smil" << Playlists::SMIL; QTest::newRow( "asx" ) << "playlist.asx" << Playlists::ASX; QTest::newRow( "wax" ) << "playlist.wax" << Playlists::ASX; QTest::newRow( "xml" ) << "playlist.xml" << Playlists::XML; QTest::newRow( "xspf" ) << "playlist.xspf" << Playlists::XSPF; // unknown or invalid formats QTest::newRow( "vlc" ) << "playlist.vlc" << Playlists::Unknown; QTest::newRow( "invalidformat" ) << "playlist.invalidformat" << Playlists::NotPlaylist; QTest::newRow( "dotted invalid" ) << "this.is.an.invalid.format" << Playlists::NotPlaylist; QTest::newRow( "trailing dot" ) << "this.is.an.invalid.format.with.trailing.dot." << Playlists::NotPlaylist; QTest::newRow( "no dot" ) << "NoDots" << Playlists::NotPlaylist; QTest::newRow( "empty string" ) << "" << Playlists::NotPlaylist; } void TestPlaylistFormat::testGetFormat() { QFETCH( QString, filename ); QFETCH( Playlists::PlaylistFormat, playlistFormat ); QUrl url( "amarok:///playlists/" ); url = url.adjusted(QUrl::RemoveFilename); url.setPath(url.path() + filename ); QCOMPARE( Playlists::getFormat( url ), playlistFormat ); // file extensions in capitals must also pass this test url = url.adjusted(QUrl::RemoveFilename); url.setPath(url.path() + filename.toUpper() ); QCOMPARE( Playlists::getFormat( url ), playlistFormat ); } void TestPlaylistFormat::testIsPlaylist_data() { QTest::addColumn( "filename" ); QTest::addColumn( "isPlaylist" ); // valid formats QTest::newRow( "m3u" ) << "playlist.m3u" << true; QTest::newRow( "m3u8" ) << "playlist.m3u8" << true; QTest::newRow( "pls" ) << "playlist.pls" << true; QTest::newRow( "ram" ) << "playlist.ram" << true; QTest::newRow( "smil" ) << "playlist.smil" << true; QTest::newRow( "asx" ) << "playlist.asx" << true; QTest::newRow( "wax" ) << "playlist.wax" << true; QTest::newRow( "xml" ) << "playlist.xml" << true; QTest::newRow( "xspf" ) << "playlist.xspf" << true; // unknown or invalid formats QTest::newRow( "vlc" ) << "playlist.vlc" << false; QTest::newRow( "invalidformat" ) << "playlist.invalidformat" << false; QTest::newRow( "dotted invalid" ) << "this.is.an.invalid.format" << false; QTest::newRow( "trailing dot" ) << "this.is.an.invalid.format.with.trailing.dot." << false; QTest::newRow( "no dot" ) << "NoDots" << false; QTest::newRow( "empty string" ) << "" << false; } void TestPlaylistFormat::testIsPlaylist() { QFETCH( QString, filename ); QFETCH( bool, isPlaylist ); QUrl url( "amarok:///playlists/" ); url = url.adjusted(QUrl::RemoveFilename); url.setPath(url.path() + filename ); QCOMPARE( Playlists::isPlaylist( url ), isPlaylist ); // file extensions in capitals must also pass this test url = url.adjusted(QUrl::RemoveFilename); url.setPath(url.path() + filename.toUpper() ); QCOMPARE( Playlists::isPlaylist( url ), isPlaylist ); } diff --git a/tests/core/playlists/TestPlaylistObserver.cpp b/tests/core/playlists/TestPlaylistObserver.cpp index 8c64a0248a..bd1c64e809 100644 --- a/tests/core/playlists/TestPlaylistObserver.cpp +++ b/tests/core/playlists/TestPlaylistObserver.cpp @@ -1,145 +1,145 @@ /**************************************************************************************** * Copyright (c) 2012 Tatjana Gornak * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestPlaylistObserver.h" #include "EngineController.h" #include "config-amarok-test.h" #include "core/support/Components.h" #include "core-impl/collections/support/CollectionManager.h" #include "core-impl/playlists/types/file/xspf/XSPFPlaylist.h" #include #include #include #include #include #include #include #include -QTEST_MAIN( TestPlaylistObserver ) +QTEST_GUILESS_MAIN( TestPlaylistObserver ) TestPlaylistObserver::TestPlaylistObserver() : m_observer( 0 ) { } QString TestPlaylistObserver::dataPath( const QString &relPath ) { return QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + "/data/playlists/" + relPath ); } void TestPlaylistObserver::initTestCase() { EngineController *controller = new EngineController(); Amarok::Components::setEngineController( controller ); CollectionManager::instance(); qRegisterMetaType( "Meta::TrackPtr" ); } void TestPlaylistObserver::cleanupTestCase() { // Wait for other jobs, like MetaProxys fetching meta data, to finish ThreadWeaver::Queue::instance()->finish(); delete Amarok::Components::setEngineController( 0 ); } void TestPlaylistObserver::init() { const QString testXspf = "test.xspf"; const QUrl url = QUrl::fromLocalFile(dataPath( testXspf )); m_testPlaylist = new Playlists::XSPFPlaylist( url ); // test that behaviour before loading is correct QCOMPARE( m_testPlaylist->name(), QString( "test.xspf" ) ); QCOMPARE( m_testPlaylist->trackCount(), -1 ); m_observer = new Observer(); m_observer->subscribeTo( m_testPlaylist ); } void TestPlaylistObserver::cleanup() { delete m_observer; m_observer = 0; m_testPlaylist = 0; } void TestPlaylistObserver::testMetadataChanged( ) { QSKIP( "Functionality this test tests has not yet been implemented", SkipAll ); QSignalSpy spy( m_observer, &Observer::metadataChangedSignal ); m_testPlaylist->triggerTrackLoad(); QSignalSpy spyTracksLoaded(m_observer, &Observer::tracksLoadedSignal); QVERIFY( spyTracksLoaded.wait( 10000 ) ); QVERIFY( spy.count() > 0 ); // changed methadata means that we should get new name QCOMPARE( m_testPlaylist->name(), QString( "my playlist" ) ); } void TestPlaylistObserver::testTracksLoaded() { m_testPlaylist->triggerTrackLoad(); QSignalSpy spyTracksLoaded(m_observer, &Observer::tracksLoadedSignal); QVERIFY( spyTracksLoaded.wait( 10000 ) ); QCOMPARE( m_testPlaylist->trackCount(), 23 ); } void TestPlaylistObserver::testTrackAdded( ) { QSignalSpy spy( m_observer, &Observer::trackAddedSignal ); m_testPlaylist->triggerTrackLoad(); QSignalSpy spyTracksLoaded(m_observer, &Observer::tracksLoadedSignal); QVERIFY( spyTracksLoaded.wait( 10000 ) ); QCOMPARE( spy.count(), 23 ); } void TestPlaylistObserver::testTrackRemoved() { m_testPlaylist->triggerTrackLoad(); QSignalSpy spyTracksLoaded( m_observer, &Observer::tracksLoadedSignal ); QVERIFY( spyTracksLoaded.wait( 10000 ) ); QString newName = "test playlist written to.xspf"; m_testPlaylist->setName( newName ); // don't overwrite original playlist QSignalSpy spyTrackRemoved( m_observer, &Observer::trackRemovedSignal ); QCOMPARE( m_testPlaylist->trackCount(), 23 ); m_testPlaylist->removeTrack( -1 ); // no effect m_testPlaylist->removeTrack( 0 ); // has effect m_testPlaylist->removeTrack( 22 ); // no effect, too far m_testPlaylist->removeTrack( 21 ); // has effect QCOMPARE( m_testPlaylist->trackCount(), 21 ); QCOMPARE( spyTrackRemoved.count(), 2 ); qDebug() << dataPath( newName ); QVERIFY( QFile::remove( dataPath( newName ) ) ); } diff --git a/tests/dynamic/TestDynamicModel.cpp b/tests/dynamic/TestDynamicModel.cpp index 0ac8c564f8..3dc1049fee 100644 --- a/tests/dynamic/TestDynamicModel.cpp +++ b/tests/dynamic/TestDynamicModel.cpp @@ -1,358 +1,358 @@ /**************************************************************************************** * Copyright (c) 2011 Ralf Engels * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestDynamicModel.h" #include "amarokconfig.h" #include "dynamic/Bias.h" #include "dynamic/BiasedPlaylist.h" #include "dynamic/DynamicModel.h" #include "core/support/Amarok.h" #include "core/support/Debug.h" #include #include #include #include #include Q_DECLARE_METATYPE(QModelIndex); QTemporaryDir *s_tmpDir = 0; // Memory leak here now, but if it's deleted, we have a segfault // We return a special saveLocation. QString Amarok::saveLocation( const QString &directory ) { return s_tmpDir->path() + directory; } -QTEST_MAIN( TestDynamicModel ) +QTEST_GUILESS_MAIN( TestDynamicModel ) TestDynamicModel::TestDynamicModel() { qRegisterMetaType(); } void TestDynamicModel::init() { AmarokConfig::instance("amarokrc"); s_tmpDir = new QTemporaryDir(); QVERIFY( s_tmpDir->isValid() ); } void TestDynamicModel::cleanup() { } void TestDynamicModel::testData() { Dynamic::DynamicModel *model = Dynamic::DynamicModel::instance(); // load from the empty directory model->loadPlaylists(); // now we should have the four default playlists QModelIndex playlistIndex = model->index( 0, 0 ); QCOMPARE( model->data( playlistIndex ).toString(), QString("Random") ); QCOMPARE( model->data( playlistIndex, Qt::EditRole ).toString(), QString("Random") ); QVERIFY( model->data( playlistIndex, Dynamic::DynamicModel::PlaylistRole ).isValid() ); QVERIFY( !model->data( playlistIndex, Dynamic::DynamicModel::BiasRole ).isValid() ); QModelIndex biasIndex = model->index( 0, 0, playlistIndex ); QVERIFY( !model->data( biasIndex ).toString().isEmpty() ); QVERIFY( !model->data( biasIndex, Dynamic::DynamicModel::PlaylistRole ).isValid() ); QVERIFY( model->data( biasIndex, Dynamic::DynamicModel::BiasRole ).isValid() ); } void TestDynamicModel::testPlaylistIndex() { Dynamic::DynamicModel *model = Dynamic::DynamicModel::instance(); // load from the empty directory model->loadPlaylists(); // now we should have the four default playlists QCOMPARE( model->rowCount(), 4 ); QCOMPARE( model->columnCount(), 1 ); // -- random playlist with one bias QModelIndex playlistIndex = model->index( 0, 0 ); QModelIndex biasIndex = model->index( 0, 0, playlistIndex ); QCOMPARE( model->rowCount( playlistIndex ), 1 ); QCOMPARE( model->rowCount( biasIndex ), 0 ); QCOMPARE( playlistIndex.parent(), QModelIndex() ); QCOMPARE( biasIndex.parent(), playlistIndex ); // -- albumplay playlist with bias structure playlistIndex = model->index( 2, 0 ); biasIndex = model->index( 0, 0, playlistIndex ); QModelIndex subBiasIndex = model->index( 1, 0, biasIndex ); QCOMPARE( model->rowCount( playlistIndex ), 1 ); QCOMPARE( model->rowCount( biasIndex ), 2 ); QCOMPARE( model->rowCount( subBiasIndex ), 0 ); QCOMPARE( playlistIndex.parent(), QModelIndex() ); QCOMPARE( biasIndex.parent(), playlistIndex ); QCOMPARE( subBiasIndex.parent(), biasIndex ); // and now the non-model index functions: model->setActivePlaylist( 2 ); Dynamic::DynamicPlaylist* playlist = model->activePlaylist(); playlistIndex = model->index( model->activePlaylistIndex(), 0 ); QCOMPARE( model->index( playlist ), playlistIndex ); Dynamic::BiasPtr bias = qobject_cast(playlist)->bias(); biasIndex = model->index( 0, 0, playlistIndex ); QCOMPARE( model->index( bias ), biasIndex ); Dynamic::BiasPtr subBias = qobject_cast(bias.data())->biases().at(0); subBiasIndex = model->index( 0, 0, biasIndex ); QCOMPARE( model->index( subBias ), subBiasIndex ); } void TestDynamicModel::testSlots() { Dynamic::DynamicModel *model = Dynamic::DynamicModel::instance(); // load from the empty directory model->loadPlaylists(); QSignalSpy spy1( model, &Dynamic::DynamicModel::rowsAboutToBeRemoved ); QSignalSpy spy2( model, &Dynamic::DynamicModel::rowsRemoved ); QSignalSpy spy3( model, &Dynamic::DynamicModel::rowsAboutToBeInserted ); QSignalSpy spy4( model, &Dynamic::DynamicModel::rowsInserted ); // -- removeAt with playlist QModelIndex playlistIndex = model->index( 1, 0 ); QString oldName = model->data( playlistIndex ).toString(); model->removeAt( playlistIndex ); QCOMPARE( spy1.count(), 1 ); QCOMPARE( spy3.count(), 0 ); QList args1 = spy1.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value(), QModelIndex() ); QCOMPARE( args1.value(1).toInt(), 1 ); QCOMPARE( args1.value(2).toInt(), 1 ); QCOMPARE( spy2.count(), 1 ); spy2.takeFirst(); // name should be different playlistIndex = model->index( 1, 0 ); QVERIFY( model->data( playlistIndex ).toString() != oldName ); QCOMPARE( model->rowCount(), 3 ); // -- removeAt with bias playlistIndex = model->index( 1, 0 ); QModelIndex biasIndex = model->index( 0, 0, playlistIndex ); QModelIndex subBiasIndex = model->index( 0, 0, biasIndex ); QCOMPARE( model->rowCount( biasIndex ), 2 ); model->removeAt( subBiasIndex ); QCOMPARE( spy1.count(), 1 ); QCOMPARE( spy3.count(), 0 ); args1 = spy1.takeFirst(); QCOMPARE( args1.count(), 3 ); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value(), biasIndex ); QCOMPARE( args1.value(1).toInt(), 0 ); QCOMPARE( args1.value(2).toInt(), 0 ); QCOMPARE( spy2.count(), 1 ); spy2.takeFirst(); QCOMPARE( model->rowCount( biasIndex ), 1 ); QCOMPARE( model->rowCount(), 3 ); // only the bias was removed // -- cloneAt with level 2 bias playlistIndex = model->index( 1, 0 ); biasIndex = model->index( 0, 0, playlistIndex ); subBiasIndex = model->index( 0, 0, biasIndex ); QCOMPARE( model->rowCount( biasIndex ), 1 ); QModelIndex resultIndex = model->cloneAt(subBiasIndex); QCOMPARE( resultIndex.row(), 1 ); QCOMPARE( resultIndex.parent(), biasIndex ); QCOMPARE( spy3.count(), 1 ); args1 = spy3.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value(), biasIndex ); QCOMPARE( args1.value(1).toInt(), 1 ); QCOMPARE( args1.value(2).toInt(), 1 ); QCOMPARE( spy4.count(), 1 ); spy4.takeFirst(); QCOMPARE( model->rowCount( biasIndex ), 2 ); QCOMPARE( model->rowCount(), 3 ); // only the bias was cloned // -- newPlaylist QCOMPARE( spy1.count(), 0 ); QCOMPARE( spy3.count(), 0 ); QCOMPARE( model->rowCount(), 3 ); resultIndex = model->newPlaylist(); QCOMPARE( model->rowCount(), 4 ); QCOMPARE( resultIndex.row(), 3 ); QCOMPARE( resultIndex.parent(), QModelIndex() ); QCOMPARE( spy1.count(), 0 ); QCOMPARE( spy3.count(), 1 ); args1 = spy3.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value(), QModelIndex() ); QCOMPARE( args1.value(1).toInt(), 3 ); QCOMPARE( args1.value(2).toInt(), 3 ); QCOMPARE( spy4.count(), 1 ); spy4.takeFirst(); // -- cloneAt with playlist playlistIndex = model->index( 1, 0 ); QCOMPARE( model->rowCount(), 4 ); resultIndex = model->cloneAt(playlistIndex); QCOMPARE( model->rowCount(), 5 ); QCOMPARE( resultIndex.row(), 4 ); QCOMPARE( resultIndex.parent(), QModelIndex() ); QCOMPARE( model->rowCount( resultIndex ), 1 ); QCOMPARE( spy3.count(), 1 ); args1 = spy3.takeFirst(); QVERIFY( args1.value(0).canConvert() ); QCOMPARE( args1.value(0).value(), QModelIndex() ); QCOMPARE( args1.value(1).toInt(), 4 ); QCOMPARE( args1.value(2).toInt(), 4 ); QCOMPARE( spy4.count(), 1 ); spy4.takeFirst(); } QModelIndex TestDynamicModel::serializeUnserialize( const QModelIndex& index ) { Dynamic::DynamicModel *model = Dynamic::DynamicModel::instance(); QByteArray bytes; QDataStream stream( &bytes, QIODevice::WriteOnly ); model->serializeIndex( &stream, index ); QDataStream stream2( &bytes, QIODevice::ReadOnly ); return model->unserializeIndex( &stream2 ); } void TestDynamicModel::testSerializeIndex() { Dynamic::DynamicModel *model = Dynamic::DynamicModel::instance(); // load from the empty directory model->loadPlaylists(); QModelIndex playlistIndex = model->index( 2, 0 ); QModelIndex biasIndex = model->index( 0, 0, playlistIndex ); QModelIndex subBiasIndex = model->index( 0, 0, biasIndex ); QCOMPARE( QModelIndex(), serializeUnserialize( QModelIndex() ) ); QCOMPARE( biasIndex, serializeUnserialize( biasIndex ) ); QCOMPARE( subBiasIndex, serializeUnserialize( subBiasIndex ) ); } void TestDynamicModel::testDnD() { Dynamic::DynamicModel *model = Dynamic::DynamicModel::instance(); // load from the empty directory model->loadPlaylists(); // -- copy a playlist QModelIndex playlistIndex = model->index( 2, 0 ); QModelIndexList indexes; indexes << playlistIndex; int oldRowCount = model->rowCount(); QString oldName = model->data( playlistIndex ).toString(); QMimeData* data = model->mimeData( indexes ); QVERIFY( model->dropMimeData( data, Qt::CopyAction, 0, 0, QModelIndex() ) ); QCOMPARE( model->rowCount(), oldRowCount + 1 ); playlistIndex = model->index( 0, 0 ); QCOMPARE( oldName, model->data( playlistIndex ).toString() ); delete data; // -- move a playlist (to the end) playlistIndex = model->index( 0, 0 ); indexes.clear(); indexes << playlistIndex; oldRowCount = model->rowCount(); oldName = model->data( playlistIndex ).toString(); data = model->mimeData( indexes ); QVERIFY( model->dropMimeData( data, Qt::MoveAction, oldRowCount, 0, QModelIndex() ) ); QCOMPARE( model->rowCount(), oldRowCount ); playlistIndex = model->index( oldRowCount - 1, 0 ); QCOMPARE( oldName, model->data( playlistIndex ).toString() ); delete data; // -- copy a bias // TODO QModelIndex biasIndex = model->index( 0, 0, playlistIndex ); QModelIndex subBiasIndex = model->index( 0, 0, biasIndex ); } void TestDynamicModel::testRemoveActive() { Dynamic::DynamicModel *model = Dynamic::DynamicModel::instance(); // load from the empty directory model->loadPlaylists(); QCOMPARE( model->rowCount(), 4 ); // -- try to remove the active playlist model->setActivePlaylist( 2 ); QCOMPARE( model->activePlaylistIndex(), 2 ); Dynamic::DynamicPlaylist* pl = model->activePlaylist(); model->removeAt( model->index( pl ) ); QCOMPARE( model->rowCount(), 3 ); QVERIFY( model->activePlaylist() != pl ); // -- now remove all playlists remaining three playlists model->removeAt( model->index( model->activePlaylist() ) ); model->removeAt( model->index( model->activePlaylist() ) ); model->removeAt( model->index( model->activePlaylist() ) ); QCOMPARE( model->rowCount(), 0 ); QCOMPARE( model->activePlaylist(), static_cast(0) ); } diff --git a/tests/dynamic/TestTrackSet.cpp b/tests/dynamic/TestTrackSet.cpp index 263c19ca8d..ab7e5d2bc5 100644 --- a/tests/dynamic/TestTrackSet.cpp +++ b/tests/dynamic/TestTrackSet.cpp @@ -1,195 +1,195 @@ /**************************************************************************************** * Copyright (c) 2011 Ralf Engels * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestTrackSet.h" #include "dynamic/TrackSet.h" #include "core/support/Amarok.h" #include "core/support/Debug.h" -QTEST_MAIN( TestTrackSet ) +QTEST_GUILESS_MAIN( TestTrackSet ) TestTrackSet::TestTrackSet() { QStringList testUids; testUids << "uid-1" << "uid-2" << "uid-3" << "uid-4" << "uid-5" << "uid-6"; m_trackCollection = new Dynamic::TrackCollection( testUids ); QCOMPARE( m_trackCollection->count(), 6 ); } void TestTrackSet::init() { } void TestTrackSet::cleanup() { QCOMPARE( m_trackCollection->count(), 6 ); } void TestTrackSet::testOutstanding() { Dynamic::TrackSet set; QCOMPARE( set.isOutstanding(), true ); Dynamic::TrackSet set2( m_trackCollection, true ); QCOMPARE( set2.isOutstanding(), false ); } void TestTrackSet::testEmptyFull() { Dynamic::TrackSet set2( m_trackCollection, true ); QCOMPARE( set2.isEmpty(), false ); QCOMPARE( set2.isFull(), true ); set2.reset( false ); QCOMPARE( set2.isEmpty(), true ); QCOMPARE( set2.isFull(), false ); set2.reset( true ); QCOMPARE( set2.isEmpty(), false ); QCOMPARE( set2.isFull(), true ); QCOMPARE( set2.contains("uid-1"), true ); QStringList testUids; testUids << "uid-1"; set2.subtract( testUids ); QCOMPARE( set2.isEmpty(), false ); QCOMPARE( set2.isFull(), false ); QCOMPARE( set2.contains("uid-1"), false ); Dynamic::TrackSet set3( m_trackCollection, false ); QCOMPARE( set3.isEmpty(), true ); QCOMPARE( set3.isFull(), false ); } void TestTrackSet::testUnite() { Dynamic::TrackSet set( m_trackCollection, false ); // -- use string lists QStringList testUids; testUids << "uid-1" << "uid-2"; set.unite( testUids ); QCOMPARE( set.contains("uid-1"), true ); QCOMPARE( set.contains("uid-2"), true ); QCOMPARE( set.contains("uid-3"), false ); QStringList testUids2; testUids2 << "uid-2" << "uid-3"; set.unite( testUids2 ); QCOMPARE( set.contains("uid-1"), true ); QCOMPARE( set.contains("uid-2"), true ); QCOMPARE( set.contains("uid-3"), true ); // -- use another set QStringList testUids3; testUids3 << "uid-3" << "uid-4"; Dynamic::TrackSet set2( m_trackCollection, false ); set2.unite( testUids3 ); set.unite( set2 ); QCOMPARE( set.contains("uid-2"), true ); QCOMPARE( set.contains("uid-3"), true ); QCOMPARE( set.contains("uid-4"), true ); QCOMPARE( set.contains("uid-5"), false ); } void TestTrackSet::testIntersect() { Dynamic::TrackSet set( m_trackCollection, true ); // -- use string lists QStringList testUids; testUids << "uid-1" << "uid-2"; set.intersect( testUids ); QCOMPARE( set.contains("uid-1"), true ); QCOMPARE( set.contains("uid-2"), true ); QCOMPARE( set.contains("uid-3"), false ); QStringList testUids2; testUids2 << "uid-2" << "uid-3"; set.intersect( testUids2 ); QCOMPARE( set.contains("uid-1"), false ); QCOMPARE( set.contains("uid-2"), true ); QCOMPARE( set.contains("uid-3"), false ); // -- use another set QStringList testUids3; testUids3 << "uid-2" << "uid-3"; Dynamic::TrackSet set2( m_trackCollection, false ); set2.unite( testUids3 ); set.intersect( set2 ); QCOMPARE( set.contains("uid-2"), true ); QCOMPARE( set.contains("uid-3"), false ); QCOMPARE( set.contains("uid-4"), false ); } void TestTrackSet::testSubtract() { Dynamic::TrackSet set( m_trackCollection, true ); // -- use string lists QStringList testUids; testUids << "uid-1" << "uid-2"; set.subtract( testUids ); QCOMPARE( set.contains("uid-1"), false ); QCOMPARE( set.contains("uid-2"), false ); QCOMPARE( set.contains("uid-3"), true ); QStringList testUids2; testUids2 << "uid-2" << "uid-3"; set.subtract( testUids2 ); QCOMPARE( set.contains("uid-1"), false ); QCOMPARE( set.contains("uid-2"), false ); QCOMPARE( set.contains("uid-3"), false ); QCOMPARE( set.contains("uid-4"), true ); // -- use another set QStringList testUids3; testUids3 << "uid-3" << "uid-4"; Dynamic::TrackSet set2( m_trackCollection, false ); set2.unite( testUids3 ); set.subtract( set2 ); QCOMPARE( set.contains("uid-3"), false ); QCOMPARE( set.contains("uid-4"), false ); QCOMPARE( set.contains("uid-5"), true ); } void TestTrackSet::testEqual() { } diff --git a/tests/importers/TestImporterManager.cpp b/tests/importers/TestImporterManager.cpp index 8c2f1cad37..fa27dceab4 100644 --- a/tests/importers/TestImporterManager.cpp +++ b/tests/importers/TestImporterManager.cpp @@ -1,245 +1,245 @@ /**************************************************************************************** * Copyright (c) 2013 Konrad Zemek * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestImporterManager.h" #include "core/support/Amarok.h" #include "core/support/Components.h" #include #include -QTEST_MAIN( TestImporterManager ) +QTEST_GUILESS_MAIN( TestImporterManager ) using namespace ::testing; void TestImporterManager::initShouldLoadSettings() { QVariantMap config; config["uid"] = QString( "TestId" ); config["custom"] = QString( "custom" ); { NiceMock mock; EXPECT_CALL( mock, newInstance( Eq(config) ) ).WillOnce( Invoke( &mock, &MockManager::concreteNewInstance ) ); EXPECT_CALL( mock, type() ).WillRepeatedly( Return( QString( "TestMockManager" ) ) ); mock.init(); mock.createProvider( config ); } EXPECT_CALL( *m_mockManager, newInstance( Eq(config) ) ); EXPECT_CALL( *m_mockManager, type() ).WillRepeatedly( Return( QString( "TestMockManager" ) ) ); m_mockManager->init(); } void TestImporterManager::creatingProviderShouldSetConfigAndParent() { QVariantMap cfg; cfg["customField"] = QString( "I'm custom" ); m_mockManager->init(); StatSyncing::ProviderPtr providerPtr = m_mockManager->createProvider( cfg ); QVERIFY( dynamic_cast(providerPtr.data())->config().contains( "customField" ) ); QCOMPARE( dynamic_cast(providerPtr.data())->manager(), m_mockManager ); } void TestImporterManager::creatingProviderShouldSaveSettings() { QVariantMap cfg; cfg["uid"] = QString( "TestId" ); cfg["custom"] = QString( "custom" ); EXPECT_CALL( *m_mockManager, type() ).WillRepeatedly( Return( QString( "TestMockManager" ) ) ); m_mockManager->init(); m_mockManager->createProvider( cfg ); KConfigGroup group = m_mockManager->providerConfig( "TestId" ); QVERIFY( group.exists() ); QCOMPARE( group.readEntry( "uid", QString() ), QString( "TestId" ) ); QCOMPARE( group.readEntry( "custom", QString() ), QString( "custom" ) ); } void TestImporterManager::creatingProviderShouldSaveGeneratedId() { EXPECT_CALL( *m_mockManager, type() ).WillRepeatedly( Return( QString( "TestMockManager" ) ) ); QVERIFY( !m_mockManager->managerConfig().exists() ); m_mockManager->init(); StatSyncing::ProviderPtr provider = m_mockManager->createProvider( QVariantMap() ); KConfigGroup group = m_mockManager->managerConfig(); QVERIFY( group.exists() ); QVERIFY( !group.groupList().empty() ); group = m_mockManager->providerConfig( provider ); QVERIFY( group.exists() ); QCOMPARE( group.readEntry( "uid", QString() ), provider->id() ); } void TestImporterManager::creatingConfigWidgetShouldDelegate() { StatSyncing::ProviderConfigWidget *ptr = reinterpret_cast( 0x19 ); EXPECT_CALL( *m_mockManager, configWidget( QVariantMap() ) ).WillOnce( Return( ptr ) ); m_mockManager->init(); QCOMPARE( m_mockManager->createConfigWidget(), ptr ); } void TestImporterManager::createConfigWidgetShouldNotCrashOnNull() { StatSyncing::ProviderConfigWidget *ptr = 0; EXPECT_CALL( *m_mockManager, configWidget(_) ) .WillOnce( Return( ptr ) ); m_mockManager->init(); QCOMPARE( m_mockManager->createConfigWidget(), ptr ); } void TestImporterManager::createProviderShouldNotCrashOnNull() { m_mockManager->init(); EXPECT_CALL( *m_mockManager, newInstance(_) ) .WillOnce( Return( QSharedPointer() ) ); QVERIFY( !m_mockManager->createProvider( QVariantMap() ) ); } void TestImporterManager::createProviderShouldReplaceProviderIfExists() { m_mockManager->init(); EXPECT_CALL( *m_mockController, registerProvider(_) ).Times( 2 ); StatSyncing::ProviderPtr provider = m_mockManager->createProvider( QVariantMap() ); QVERIFY( m_mockManager->providers().contains( provider->id() ) ); QCOMPARE( m_mockManager->providers()[provider->id()], provider ); EXPECT_CALL( *m_mockController, unregisterProvider( provider ) ); QVariantMap cfg; cfg.insert( "uid", provider->id() ); StatSyncing::ProviderPtr replaceProvider = m_mockManager->createProvider( cfg ); QCOMPARE( m_mockManager->providers()[provider->id()], replaceProvider ); } void TestImporterManager::createProviderShouldRegisterProvider() { QVariantMap cfg; cfg["uid"] = "uid"; StatSyncing::ImporterProviderPtr providerPtr( new NiceMock( cfg, m_mockManager ) ); m_mockManager->init(); EXPECT_CALL( *m_mockManager, newInstance(_) ).WillOnce( Return( providerPtr ) ); EXPECT_CALL( *m_mockController, registerProvider( Eq(providerPtr) ) ); m_mockManager->createProvider( QVariantMap() ); } void TestImporterManager::forgetProviderShouldUnregisterProvider() { m_mockManager->init(); EXPECT_CALL( *m_mockController, registerProvider(_) ); StatSyncing::ProviderPtr providerPtr = m_mockManager->createProvider( QVariantMap() ); EXPECT_CALL( *m_mockController, unregisterProvider( Eq(providerPtr) ) ); m_mockManager->providerForgottenProxy( providerPtr->id() ); } void TestImporterManager::forgetProviderShouldForgetConfig() { QVariantMap cfg; cfg.insert( "uid", "TestId" ); EXPECT_CALL( *m_mockManager, type() ).WillRepeatedly( Return( QString( "TestMockManager" ) ) ); m_mockManager->init(); StatSyncing::ProviderPtr providerPtr = m_mockManager->createProvider( cfg ); KConfigGroup group = m_mockManager->providerConfig( providerPtr ); QVERIFY( group.exists() ); QVERIFY( group.hasKey( "uid" ) ); m_mockManager->providerForgottenProxy( providerPtr->id() ); QVERIFY( !m_mockManager->providerConfig( providerPtr ).exists() ); } void TestImporterManager::forgetProviderShouldHangleInvalidId() { EXPECT_CALL( *m_mockController, unregisterProvider(_) ).Times( 0 ); m_mockManager->init(); m_mockManager->providerForgottenProxy( QString() ); } void TestImporterManager::forgetProviderShouldNotCauseOtherProvidersToBeForgotten() { m_mockManager->init(); StatSyncing::ProviderPtr providerPtr1 = m_mockManager->createProvider( QVariantMap() ); StatSyncing::ProviderPtr providerPtr2 = m_mockManager->createProvider( QVariantMap() ); QVERIFY( m_mockManager->providerConfig( providerPtr1 ).exists() ); QVERIFY( m_mockManager->providerConfig( providerPtr2 ).exists() ); m_mockManager->providerForgottenProxy( providerPtr1->id() ); QVERIFY( !m_mockManager->providerConfig( providerPtr1 ).exists() ); QVERIFY( m_mockManager->providerConfig( providerPtr2 ).exists() ); } void TestImporterManager::managerShouldHandleMultipleProviders() { EXPECT_CALL( *m_mockController, registerProvider(_) ).Times( 10 ); QList providerPtrs; for( int i = 0; i < 10; ++i ) providerPtrs << m_mockManager->createProvider( QVariantMap() ); foreach( const StatSyncing::ProviderPtr &providerPtr, providerPtrs ) QVERIFY( m_mockManager->providers().contains( providerPtr->id() ) ); } diff --git a/tests/importers/TestImporterProvider.cpp b/tests/importers/TestImporterProvider.cpp index e5cf4bd1cf..ffe57f16af 100644 --- a/tests/importers/TestImporterProvider.cpp +++ b/tests/importers/TestImporterProvider.cpp @@ -1,136 +1,136 @@ /**************************************************************************************** * Copyright (c) 2013 Konrad Zemek * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestImporterProvider.h" #include "core/support/Amarok.h" #include "core/support/Components.h" #include #include -QTEST_MAIN( TestImporterProvider ) +QTEST_GUILESS_MAIN( TestImporterProvider ) using namespace ::testing; void TestImporterProvider::constructorShouldSetConfigAndManager() { QVariantMap cfg; cfg["nanananana"] = QString( "Batman" ); MockProvider provider( cfg, m_mockManager ); QVERIFY( provider.config().contains( QString( "nanananana" ) ) ); QCOMPARE( provider.manager(), m_mockManager ); } void TestImporterProvider::constructorShouldSetUidIfNotSet() { QVERIFY( !MockProvider( QVariantMap(), 0 ).id().isEmpty() ); } void TestImporterProvider::idShouldReturnConfiguredId() { QVariantMap cfg; cfg["uid"] = QString( "Joker" ); QCOMPARE( MockProvider( cfg, 0 ).config(), cfg ); } void TestImporterProvider::descriptionShouldDelegateToManager() { EXPECT_CALL( *m_mockManager, description() ).WillOnce( Return( QString( "Ivy" ) ) ); QCOMPARE( m_mockProvider->description(), QString( "Ivy" ) ); } void TestImporterProvider::iconShouldDelegateToManager() { EXPECT_CALL( *m_mockManager, icon() ).WillOnce( Return( QIcon::fromTheme( "amarok" ) ) ); QCOMPARE( m_mockProvider->icon().name(), QIcon::fromTheme( "amarok" ).name() ); } void TestImporterProvider::nameShouldReturnConfiguredName() { QVariantMap cfg; cfg["uid"] = QString( "Bane" ); cfg["name"] = QString( "Ra's" ); MockProvider provider( cfg, m_mockManager ); QCOMPARE( provider.prettyName(), QString( "Ra's" ) ); } void TestImporterProvider::nameShouldNotCrashIfNameIsNotConfigured() { QVariantMap cfg; cfg["uid"] = QString( "TwoFace" ); MockProvider provider( cfg, m_mockManager ); QCOMPARE( provider.prettyName(), QString() ); } void TestImporterProvider::isConfigurableShouldReturnTrue() { QVERIFY( m_mockProvider->isConfigurable() ); } void TestImporterProvider::configWidgetShouldDelegateToManager() { StatSyncing::ProviderConfigWidget *widget = 0; EXPECT_CALL( *m_mockManager, configWidget( Eq(m_mockProvider->config()) ) ) .WillOnce( Return( widget ) ); QCOMPARE( m_mockProvider->configWidget(), widget ); } void TestImporterProvider::reconfigureShouldEmitSignal() { QVariantMap cfg = m_mockProvider->config(); cfg["customField"] = QString( "Selena" ); QSignalSpy spy( m_mockProvider, &MockProvider::reconfigurationRequested ); m_mockProvider->reconfigure( cfg ); QCOMPARE( spy.count(), 1 ); QCOMPARE( spy.takeFirst().at( 0 ).toMap(), cfg ); } void TestImporterProvider::reconfigureShouldNotEmitSignalOnDifferentUid() { QVariantMap cfg; cfg["uid"] = "Different"; QSignalSpy spy( m_mockProvider, &MockProvider::reconfigurationRequested ); m_mockProvider->reconfigure( cfg ); QCOMPARE( spy.count(), 0 ); } void TestImporterProvider::defaultPreferenceShouldReturnNoByDefault() { QCOMPARE( m_mockProvider->defaultPreference(), StatSyncing::Provider::NoByDefault ); } diff --git a/tests/playlist/TestPlaylistModels.cpp b/tests/playlist/TestPlaylistModels.cpp index 3f7bd0c1b5..c37e8ad62e 100644 --- a/tests/playlist/TestPlaylistModels.cpp +++ b/tests/playlist/TestPlaylistModels.cpp @@ -1,236 +1,236 @@ /**************************************************************************************** * Copyright (c) 2010 Nikolaj Hald Nielsen * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Pulic License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestPlaylistModels.h" #include "amarokconfig.h" #include "core/support/Components.h" #include "EngineController.h" #include "playlist/PlaylistActions.h" #include "playlist/PlaylistController.h" #include "playlist/PlaylistModelStack.h" #include "playlist/PlaylistModel.h" #include "playlist/UndoCommands.h" #include "mocks/MetaMock.h" #include "mocks/MockTrack.h" #include #include using namespace Playlist; -QTEST_MAIN( TestPlaylistModels ) +QTEST_GUILESS_MAIN( TestPlaylistModels ) TestPlaylistModels::TestPlaylistModels() : QObject() { } void TestPlaylistModels::initTestCase() { AmarokConfig::instance("amarokrc"); //apparently the engine controller is needed somewhere, or we will get a crash... EngineController *controller = new EngineController(); Amarok::Components::setEngineController( controller ); // Initialize playlistAction before we set the playlist, lest our playlist be overwritten with Art Of Nations The::playlistActions(); The::playlistController()->removeRow( 0 ); //we want to add a few tracks to the playlist so we can test sorting, filtering and so on. So first create a bunch of dummy tracks we can use. Meta::TrackList tracks; QVariantMap map1; map1.insert( Meta::Field::TITLE, QString( "Cool as honey" ) ); MetaMock * metaMock = new MetaMock( map1 ); metaMock->m_artist = new MockArtist( "Bonzai Bees" ); metaMock->m_album = new MockAlbum( "The Hive", metaMock->m_artist ); tracks << Meta::TrackPtr( metaMock ); QVariantMap map2; map2.insert( Meta::Field::TITLE, QString( "xTreme buzzing sound" ) ); metaMock = new MetaMock( map2 ); metaMock->m_artist = new MockArtist( "Bonzai Bees" ); metaMock->m_album = new MockAlbum( "The Hive", metaMock->m_artist ); tracks << Meta::TrackPtr( metaMock ); QVariantMap map3; map3.insert( Meta::Field::TITLE, QString( "Alphabet soup" ) ); metaMock = new MetaMock( map3 ); metaMock->m_artist = new MockArtist( "Grumpy Grizzlies" ); metaMock->m_album = new MockAlbum( "The Hive", metaMock->m_artist ); tracks << Meta::TrackPtr( metaMock ); QVariantMap map4; map4.insert( Meta::Field::TITLE, QString( "Zlick" ) ); metaMock = new MetaMock( map4 ); metaMock->m_artist = new MockArtist( "Grumpy Grizzlies" ); metaMock->m_album = new MockAlbum( "Nice Long Nap", metaMock->m_artist ); tracks << Meta::TrackPtr( metaMock ); QVariantMap map5; map5.insert( Meta::Field::TITLE, QString( "23 hours is not enough" ) ); metaMock = new MetaMock( map5 ); metaMock->m_artist = new MockArtist( "Grumpy Grizzlies" ); metaMock->m_album = new MockAlbum( "Nice Long Nap", metaMock->m_artist ); tracks << Meta::TrackPtr( metaMock ); QVariantMap map6; map6.insert( Meta::Field::TITLE, QString( "1 song to rule them all" ) ); metaMock = new MetaMock( map6 ); metaMock->m_artist = new MockArtist( "Bonzai Bees" ); metaMock->m_album = new MockAlbum( "Pretty Flowers", metaMock->m_artist ); tracks << Meta::TrackPtr( metaMock ); QVariantMap map7; map7.insert( Meta::Field::TITLE, QString( "zz ambience sound" ) ); metaMock = new MetaMock( map7 ); // note: no artist, no album! tracks << Meta::TrackPtr( metaMock ); The::playlistController()->insertTracks( 0, tracks ); QCOMPARE( The::playlist()->trackAt( 3 )->prettyName(), QString( "Zlick" ) ); } void TestPlaylistModels::cleanup() { SortScheme scheme = SortScheme(); ModelStack::instance()->sortProxy()->updateSortMap( scheme ); ModelStack::instance()->filterProxy()->clearSearchTerm(); } void TestPlaylistModels::testSorting() { //simple sort by title //******************************// SortScheme scheme = SortScheme(); scheme.addLevel( SortLevel( Playlist::Title, Qt::AscendingOrder ) ); ModelStack::instance()->sortProxy()->updateSortMap( scheme ); AbstractModel * topModel = The::playlist(); QCOMPARE( topModel->trackAt( 0 )->prettyName(), QString( "1 song to rule them all" ) ); QCOMPARE( topModel->trackAt( 1 )->prettyName(), QString( "23 hours is not enough" ) ); QCOMPARE( topModel->trackAt( 2 )->prettyName(), QString( "Alphabet soup" ) ); QCOMPARE( topModel->trackAt( 3 )->prettyName(), QString( "Cool as honey" ) ); QCOMPARE( topModel->trackAt( 4 )->prettyName(), QString( "xTreme buzzing sound" ) ); QCOMPARE( topModel->trackAt( 5 )->prettyName(), QString( "Zlick" ) ); //Sort by Artist - Album - Title //******************************// SortScheme scheme2 = SortScheme(); scheme2.addLevel( SortLevel( Playlist::Artist, Qt::AscendingOrder ) ); scheme2.addLevel( SortLevel( Playlist::Album, Qt::AscendingOrder ) ); scheme2.addLevel( SortLevel( Playlist::Title, Qt::AscendingOrder ) ); QCOMPARE( scheme2.length(), 3 ); ModelStack::instance()->sortProxy()->updateSortMap( scheme2 ); topModel->qaim()->revert(); // the one without artist or album comes first QCOMPARE( topModel->trackAt( 0 )->prettyName(), QString( "zz ambience sound" ) ); QCOMPARE( topModel->trackAt( 1 )->prettyName(), QString( "1 song to rule them all" ) ); QCOMPARE( topModel->trackAt( 2 )->prettyName(), QString( "Cool as honey" ) ); QCOMPARE( topModel->trackAt( 3 )->prettyName(), QString( "xTreme buzzing sound" ) ); QCOMPARE( topModel->trackAt( 4 )->prettyName(), QString( "23 hours is not enough" ) ); QCOMPARE( topModel->trackAt( 5 )->prettyName(), QString( "Zlick" ) ); QCOMPARE( topModel->trackAt( 6 )->prettyName(), QString( "Alphabet soup" ) ); //reverse some stuff //******************************// SortScheme scheme3 = SortScheme(); scheme3.addLevel( SortLevel( Playlist::Artist, Qt::AscendingOrder ) ); scheme3.addLevel( SortLevel( Playlist::Album, Qt::DescendingOrder ) ); scheme3.addLevel( SortLevel( Playlist::Title, Qt::AscendingOrder ) ); ModelStack::instance()->sortProxy()->updateSortMap( scheme3 ); topModel->qaim()->revert(); QCOMPARE( topModel->trackAt( 0 )->prettyName(), QString( "zz ambience sound" ) ); QCOMPARE( topModel->trackAt( 1 )->prettyName(), QString( "Cool as honey" ) ); QCOMPARE( topModel->trackAt( 2 )->prettyName(), QString( "xTreme buzzing sound" ) ); QCOMPARE( topModel->trackAt( 3 )->prettyName(), QString( "1 song to rule them all" ) ); QCOMPARE( topModel->trackAt( 4 )->prettyName(), QString( "Alphabet soup" ) ); QCOMPARE( topModel->trackAt( 5 )->prettyName(), QString( "23 hours is not enough" ) ); QCOMPARE( topModel->trackAt( 6 )->prettyName(), QString( "Zlick" ) ); //Sort by album when tracks have same album name and different artists //******************************// SortScheme scheme4 = SortScheme(); scheme4.addLevel( SortLevel( Playlist::Album, Qt::AscendingOrder ) ); scheme4.addLevel( SortLevel( Playlist::Title, Qt::AscendingOrder ) ); ModelStack::instance()->sortProxy()->updateSortMap( scheme4 ); topModel->qaim()->revert(); QCOMPARE( topModel->trackAt( 0 )->prettyName(), QString( "zz ambience sound" ) ); QCOMPARE( topModel->trackAt( 1 )->prettyName(), QString( "23 hours is not enough" ) ); QCOMPARE( topModel->trackAt( 2 )->prettyName(), QString( "Zlick" ) ); QCOMPARE( topModel->trackAt( 3 )->prettyName(), QString( "1 song to rule them all" ) ); QCOMPARE( topModel->trackAt( 4 )->prettyName(), QString( "Cool as honey" ) ); QCOMPARE( topModel->trackAt( 5 )->prettyName(), QString( "xTreme buzzing sound" ) ); QCOMPARE( topModel->trackAt( 6 )->prettyName(), QString( "Alphabet soup" ) ); } void TestPlaylistModels::testFiltering() { ModelStack::instance()->filterProxy()->showOnlyMatches( true ); ModelStack::instance()->filterProxy()->find( "ou" ); ModelStack::instance()->filterProxy()->filterUpdated(); AbstractModel * topModel = The::playlist(); QCOMPARE( topModel->qaim()->rowCount(), 4 ); QCOMPARE( topModel->trackAt( 0 )->prettyName(), QString( "xTreme buzzing sound" ) ); QCOMPARE( topModel->trackAt( 1 )->prettyName(), QString( "Alphabet soup" ) ); QCOMPARE( topModel->trackAt( 2 )->prettyName(), QString( "23 hours is not enough" ) ); QCOMPARE( topModel->trackAt( 3 )->prettyName(), QString( "zz ambience sound" ) ); //TODO: More advanced filtering tests go here } void TestPlaylistModels::testSearching() { } void TestPlaylistModels::testShuffling() { Meta::TrackList oldTrackList = The::playlist()->tracks(); The::playlistActions()->shuffle(); QVERIFY( oldTrackList != The::playlist()->tracks() ); The::playlistController()->undo(); QCOMPARE( oldTrackList, The::playlist()->tracks() ); } diff --git a/tests/synchronization/TestMasterSlaveSynchronizationJob.cpp b/tests/synchronization/TestMasterSlaveSynchronizationJob.cpp index 5af56a463e..eab3dae0b7 100644 --- a/tests/synchronization/TestMasterSlaveSynchronizationJob.cpp +++ b/tests/synchronization/TestMasterSlaveSynchronizationJob.cpp @@ -1,453 +1,453 @@ /**************************************************************************************** * Copyright (c) 2010 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestMasterSlaveSynchronizationJob.h" #include "core/support/Debug.h" #include "core/collections/CollectionLocation.h" #include "core/collections/CollectionLocationDelegate.h" #include "core/support/Components.h" #include "synchronization/MasterSlaveSynchronizationJob.h" #include "CollectionTestImpl.h" #include "core/collections/MockCollectionLocationDelegate.h" #include "mocks/MockTrack.h" #include "mocks/MockAlbum.h" #include "mocks/MockArtist.h" #include #include -QTEST_MAIN( TestMasterSlaveSynchronizationJob ) +QTEST_GUILESS_MAIN( TestMasterSlaveSynchronizationJob ) using ::testing::Return; using ::testing::AnyNumber; using ::testing::_; static int trackCopyCount; static int trackRemoveCount; namespace Collections { class MyCollectionLocation : public CollectionLocation { public: Collections::CollectionTestImpl *coll; QString prettyLocation() const { return "foo"; } bool isWritable() const { return true; } void removeUrlsFromCollection( const Meta::TrackList &sources ) { trackRemoveCount += sources.count(); coll->mc->acquireWriteLock(); TrackMap map = coll->mc->trackMap(); foreach( const Meta::TrackPtr &track, sources ) map.remove( track->uidUrl() ); coll->mc->setTrackMap( map ); coll->mc->releaseLock(); slotRemoveOperationFinished(); } void copyUrlsToCollection(const QMap &sources, const Transcoding::Configuration& conf) { Q_UNUSED( conf ) trackCopyCount = sources.count(); foreach( const Meta::TrackPtr &track, sources.keys() ) { coll->mc->addTrack( track ); } } }; class MyCollectionTestImpl : public CollectionTestImpl { public: MyCollectionTestImpl( const QString &id ) : CollectionTestImpl( id ) {} CollectionLocation* location() { MyCollectionLocation *r = new MyCollectionLocation(); r->coll = this; return r; } }; } //namespace Collections void addMockTrack( Collections::CollectionTestImpl *coll, const QString &trackName, const QString &artistName, const QString &albumName ) { Meta::MockTrack *track = new Meta::MockTrack(); ::testing::Mock::AllowLeak( track ); Meta::TrackPtr trackPtr( track ); EXPECT_CALL( *track, name() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName ) ); EXPECT_CALL( *track, uidUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName + '_' + artistName + '_' + albumName ) ); EXPECT_CALL( *track, playableUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( QUrl( '/' + track->uidUrl() ) ) ); coll->mc->addTrack( trackPtr ); Meta::AlbumPtr albumPtr = coll->mc->albumMap().value( albumName, QString() /* no album artist */ ); Meta::MockAlbum *album; Meta::TrackList albumTracks; if( albumPtr ) { album = dynamic_cast( albumPtr.data() ); if( !album ) { QFAIL( "expected a Meta::MockAlbum" ); return; } albumTracks = albumPtr->tracks(); } else { album = new Meta::MockAlbum(); ::testing::Mock::AllowLeak( album ); albumPtr = Meta::AlbumPtr( album ); EXPECT_CALL( *album, name() ).Times( AnyNumber() ).WillRepeatedly( Return( albumName ) ); EXPECT_CALL( *album, hasAlbumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( false ) ); EXPECT_CALL( *album, albumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::ArtistPtr() ) ); coll->mc->addAlbum( albumPtr ); } albumTracks << trackPtr; EXPECT_CALL( *album, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( albumTracks ) ); EXPECT_CALL( *track, album() ).Times( AnyNumber() ).WillRepeatedly( Return( albumPtr ) ); Meta::ArtistPtr artistPtr = coll->mc->artistMap().value( artistName ); Meta::MockArtist *artist; Meta::TrackList artistTracks; if( artistPtr ) { artist = dynamic_cast( artistPtr.data() ); if( !artist ) { QFAIL( "expected a Meta::MockArtist" ); return; } artistTracks = artistPtr->tracks(); } else { artist = new Meta::MockArtist(); ::testing::Mock::AllowLeak( artist ); artistPtr = Meta::ArtistPtr( artist ); EXPECT_CALL( *artist, name() ).Times( AnyNumber() ).WillRepeatedly( Return( artistName ) ); coll->mc->addArtist( artistPtr ); } artistTracks << trackPtr; EXPECT_CALL( *artist, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( artistTracks ) ); EXPECT_CALL( *track, artist() ).Times( AnyNumber() ).WillRepeatedly( Return( artistPtr ) ); } TestMasterSlaveSynchronizationJob::TestMasterSlaveSynchronizationJob() { int argc = 1; char **argv = (char **) malloc(sizeof(char *)); argv[0] = strdup( QCoreApplication::applicationName().toLocal8Bit().data() ); ::testing::InitGoogleMock( &argc, argv ); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); } void TestMasterSlaveSynchronizationJob::init() { trackCopyCount = 0; trackRemoveCount = 0; } void TestMasterSlaveSynchronizationJob::testAddTracksToEmptySlave() { Collections::CollectionTestImpl *master = new Collections::MyCollectionTestImpl( "master" ); Collections::CollectionTestImpl *slave = new Collections::MyCollectionTestImpl( "slave" ); //setup master addMockTrack( master, "track1", "artist1", "album1" ); QCOMPARE( master->mc->trackMap().count(), 1 ); QCOMPARE( slave->mc->trackMap().count(), 0 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 0 ); MasterSlaveSynchronizationJob *job = new MasterSlaveSynchronizationJob(); QSignalSpy spy( job, &MasterSlaveSynchronizationJob::destroyed ); job->setMaster( master ); job->setSlave( slave ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount, 1 ); QCOMPARE( trackRemoveCount, 0 ); QCOMPARE( master->mc->trackMap().count(), 1 ); QCOMPARE( slave->mc->trackMap().count(), 1 ); delete master; delete slave; } void TestMasterSlaveSynchronizationJob::testAddSingleTrack() { Collections::CollectionTestImpl *master = new Collections::MyCollectionTestImpl( "master" ); Collections::CollectionTestImpl *slave = new Collections::MyCollectionTestImpl( "slave" ); //setup addMockTrack( master, "track1", "artist1", "album1" ); addMockTrack( slave, "track1", "artist1", "album1" ); addMockTrack( master, "track2", "artist1", "album1" ); QCOMPARE( master->mc->trackMap().count(), 2 ); QCOMPARE( slave->mc->trackMap().count(), 1 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 0 ); //test MasterSlaveSynchronizationJob *job = new MasterSlaveSynchronizationJob(); QSignalSpy spy( job, &MasterSlaveSynchronizationJob::destroyed ); job->setMaster( master ); job->setSlave( slave ); job->synchronize(); spy.wait( 1000 ); //verify QCOMPARE( trackCopyCount, 1 ); QCOMPARE( trackRemoveCount, 0 ); QCOMPARE( master->mc->trackMap().count(), 2 ); QCOMPARE( slave->mc->trackMap().count(), 2 ); delete master; delete slave; } void TestMasterSlaveSynchronizationJob::testAddAlbum() { Collections::CollectionTestImpl *master = new Collections::MyCollectionTestImpl( "master" ); Collections::CollectionTestImpl *slave = new Collections::MyCollectionTestImpl( "slave" ); //setup addMockTrack( master, "track1", "artist1", "album1" ); addMockTrack( slave, "track1", "artist1", "album1" ); addMockTrack( master, "track1", "artist1", "album2" ); QCOMPARE( master->mc->trackMap().count(), 2 ); QCOMPARE( slave->mc->trackMap().count(), 1 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 0 ); //test MasterSlaveSynchronizationJob *job = new MasterSlaveSynchronizationJob(); QSignalSpy spy( job, &MasterSlaveSynchronizationJob::destroyed ); job->setMaster( master ); job->setSlave( slave ); job->synchronize(); spy.wait( 1000 ); //verify QCOMPARE( trackCopyCount, 1 ); QCOMPARE( trackRemoveCount, 0 ); QCOMPARE( master->mc->trackMap().count(), 2 ); QCOMPARE( slave->mc->trackMap().count(), 2 ); delete master; delete slave; } void TestMasterSlaveSynchronizationJob::testAddArtist() { Collections::CollectionTestImpl *master = new Collections::MyCollectionTestImpl( "master" ); Collections::CollectionTestImpl *slave = new Collections::MyCollectionTestImpl( "slave" ); //setup addMockTrack( master, "track1", "artist1", "album1" ); addMockTrack( slave, "track1", "artist1", "album1" ); addMockTrack( master, "track1", "artist2", "album1" ); QCOMPARE( master->mc->trackMap().count(), 2 ); QCOMPARE( slave->mc->trackMap().count(), 1 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 0 ); //test MasterSlaveSynchronizationJob *job = new MasterSlaveSynchronizationJob(); QSignalSpy spy( job, &MasterSlaveSynchronizationJob::destroyed ); job->setMaster( master ); job->setSlave( slave ); job->synchronize(); spy.wait( 1000 ); //verify QCOMPARE( trackCopyCount, 1 ); QCOMPARE( trackRemoveCount, 0 ); QCOMPARE( master->mc->trackMap().count(), 2 ); QCOMPARE( slave->mc->trackMap().count(), 2 ); delete master; delete slave; } void TestMasterSlaveSynchronizationJob::testRemoveSingleTrack() { Collections::CollectionTestImpl *master = new Collections::MyCollectionTestImpl( "master" ); Collections::CollectionTestImpl *slave = new Collections::MyCollectionTestImpl( "slave" ); Collections::MockCollectionLocationDelegate *delegate = new Collections::MockCollectionLocationDelegate(); EXPECT_CALL( *delegate, reallyDelete( _, _) ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); Amarok::Components::setCollectionLocationDelegate( delegate ); //setup addMockTrack( master, "track1", "artist1", "album1" ); addMockTrack( slave, "track1", "artist1", "album1" ); addMockTrack( slave, "track2", "artist1", "album1" ); QCOMPARE( master->mc->trackMap().count(), 1 ); QCOMPARE( slave->mc->trackMap().count(), 2 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 0 ); //test MasterSlaveSynchronizationJob *job = new MasterSlaveSynchronizationJob(); QSignalSpy spy( job, &MasterSlaveSynchronizationJob::destroyed ); job->setMaster( master ); job->setSlave( slave ); job->synchronize(); spy.wait( 1000 ); //verify QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 1 ); QCOMPARE( master->mc->trackMap().count(), 1 ); QCOMPARE( slave->mc->trackMap().count(), 1 ); delete master; delete slave; delete Amarok::Components::setCollectionLocationDelegate( 0 ); } void TestMasterSlaveSynchronizationJob::testRemoveAlbum() { Collections::CollectionTestImpl *master = new Collections::MyCollectionTestImpl( "master" ); Collections::CollectionTestImpl *slave = new Collections::MyCollectionTestImpl( "slave" ); Collections::MockCollectionLocationDelegate *delegate = new Collections::MockCollectionLocationDelegate(); EXPECT_CALL( *delegate, reallyDelete( _, _) ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); Amarok::Components::setCollectionLocationDelegate( delegate ); //setup addMockTrack( master, "track1", "artist1", "album1" ); addMockTrack( slave, "track1", "artist1", "album1" ); addMockTrack( slave, "track1", "artist1", "album2" ); QCOMPARE( master->mc->trackMap().count(), 1 ); QCOMPARE( slave->mc->trackMap().count(), 2 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 0 ); //test MasterSlaveSynchronizationJob *job = new MasterSlaveSynchronizationJob(); QSignalSpy spy( job, &MasterSlaveSynchronizationJob::destroyed ); job->setMaster( master ); job->setSlave( slave ); job->synchronize(); spy.wait( 1000 ); //verify QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 1 ); QCOMPARE( master->mc->trackMap().count(), 1 ); QCOMPARE( slave->mc->trackMap().count(), 1 ); delete master; delete slave; delete Amarok::Components::setCollectionLocationDelegate( 0 ); } void TestMasterSlaveSynchronizationJob::testRemoveArtist() { Collections::CollectionTestImpl *master = new Collections::MyCollectionTestImpl( "master" ); Collections::CollectionTestImpl *slave = new Collections::MyCollectionTestImpl( "slave" ); Collections::MockCollectionLocationDelegate *delegate = new Collections::MockCollectionLocationDelegate(); EXPECT_CALL( *delegate, reallyDelete( _, _) ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); Amarok::Components::setCollectionLocationDelegate( delegate ); //setup addMockTrack( master, "track1", "artist1", "album1" ); addMockTrack( slave, "track1", "artist1", "album1" ); addMockTrack( slave, "track1", "artist2", "album1" ); QCOMPARE( master->mc->trackMap().count(), 1 ); QCOMPARE( slave->mc->trackMap().count(), 2 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 0 ); //test MasterSlaveSynchronizationJob *job = new MasterSlaveSynchronizationJob(); QSignalSpy spy( job, &MasterSlaveSynchronizationJob::destroyed ); job->setMaster( master ); job->setSlave( slave ); job->synchronize(); spy.wait( 1000 ); //verify QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 1 ); QCOMPARE( master->mc->trackMap().count(), 1 ); QCOMPARE( slave->mc->trackMap().count(), 1 ); delete master; delete slave; delete Amarok::Components::setCollectionLocationDelegate( 0 ); } void TestMasterSlaveSynchronizationJob::testEmptyMaster() { Collections::CollectionTestImpl *master = new Collections::MyCollectionTestImpl( "master" ); Collections::CollectionTestImpl *slave = new Collections::MyCollectionTestImpl( "slave" ); Collections::MockCollectionLocationDelegate *delegate = new Collections::MockCollectionLocationDelegate(); EXPECT_CALL( *delegate, reallyDelete( _, _) ).Times( AnyNumber() ).WillRepeatedly( Return( true ) ); Amarok::Components::setCollectionLocationDelegate( delegate ); //setup master addMockTrack( slave, "track1", "artist1", "album1" ); QCOMPARE( master->mc->trackMap().count(), 0 ); QCOMPARE( slave->mc->trackMap().count(), 1 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 0 ); MasterSlaveSynchronizationJob *job = new MasterSlaveSynchronizationJob(); QSignalSpy spy( job, &MasterSlaveSynchronizationJob::destroyed ); job->setMaster( master ); job->setSlave( slave ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( trackRemoveCount, 1 ); QCOMPARE( master->mc->trackMap().count(), 0 ); QCOMPARE( slave->mc->trackMap().count(), 0 ); delete master; delete slave; delete Amarok::Components::setCollectionLocationDelegate( 0 ); } diff --git a/tests/synchronization/TestOneWaySynchronizationJob.cpp b/tests/synchronization/TestOneWaySynchronizationJob.cpp index 584f96f1d7..77286b2693 100644 --- a/tests/synchronization/TestOneWaySynchronizationJob.cpp +++ b/tests/synchronization/TestOneWaySynchronizationJob.cpp @@ -1,331 +1,331 @@ /**************************************************************************************** * Copyright (c) 2010 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestOneWaySynchronizationJob.h" #include "core/support/Debug.h" #include "core/collections/CollectionLocation.h" #include "synchronization/OneWaySynchronizationJob.h" #include "CollectionTestImpl.h" #include "mocks/MockTrack.h" #include "mocks/MockAlbum.h" #include "mocks/MockArtist.h" #include #include -QTEST_MAIN( TestOneWaySynchronizationJob ) +QTEST_GUILESS_MAIN( TestOneWaySynchronizationJob ) using ::testing::Return; using ::testing::AnyNumber; static int trackCopyCount; namespace Collections { class MyCollectionLocation : public CollectionLocation { public: Collections::CollectionTestImpl *coll; QString prettyLocation() const { return "foo"; } bool isWritable() const { return true; } void copyUrlsToCollection(const QMap &sources, const Transcoding::Configuration& conf) { Q_UNUSED( conf ) // qDebug() << "adding " << sources.count() << " tracks to " << coll->collectionId(); trackCopyCount = sources.count(); foreach( const Meta::TrackPtr &track, sources.keys() ) { coll->mc->addTrack( track ); } } }; class MyCollectionTestImpl : public CollectionTestImpl { public: MyCollectionTestImpl( const QString &id ) : CollectionTestImpl( id ) {} CollectionLocation* location() { MyCollectionLocation *r = new MyCollectionLocation(); r->coll = this; return r; } }; } //namespace Collections void addMockTrack( Collections::CollectionTestImpl *coll, const QString &trackName, const QString &artistName, const QString &albumName ) { Meta::MockTrack *track = new Meta::MockTrack(); ::testing::Mock::AllowLeak( track ); Meta::TrackPtr trackPtr( track ); EXPECT_CALL( *track, name() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName ) ); EXPECT_CALL( *track, uidUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName + '_' + artistName + '_' + albumName ) ); EXPECT_CALL( *track, playableUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( QUrl( '/' + track->uidUrl() ) ) ); EXPECT_CALL( *track, composer() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::ComposerPtr() ) ); EXPECT_CALL( *track, genre() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::GenrePtr() ) ); EXPECT_CALL( *track, year() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::YearPtr() ) ); coll->mc->addTrack( trackPtr ); Meta::AlbumPtr albumPtr = coll->mc->albumMap().value( albumName, QString() /* no album artist */ ); Meta::MockAlbum *album; Meta::TrackList albumTracks; if( albumPtr ) { album = dynamic_cast( albumPtr.data() ); if( !album ) { QFAIL( "expected a Meta::MockAlbum" ); return; } albumTracks = albumPtr->tracks(); } else { album = new Meta::MockAlbum(); ::testing::Mock::AllowLeak( album ); albumPtr = Meta::AlbumPtr( album ); EXPECT_CALL( *album, name() ).Times( AnyNumber() ).WillRepeatedly( Return( albumName ) ); EXPECT_CALL( *album, hasAlbumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( false ) ); EXPECT_CALL( *album, albumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::ArtistPtr() ) ); coll->mc->addAlbum( albumPtr ); } albumTracks << trackPtr; EXPECT_CALL( *album, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( albumTracks ) ); EXPECT_CALL( *track, album() ).Times( AnyNumber() ).WillRepeatedly( Return( albumPtr ) ); Meta::ArtistPtr artistPtr = coll->mc->artistMap().value( artistName ); Meta::MockArtist *artist; Meta::TrackList artistTracks; if( artistPtr ) { artist = dynamic_cast( artistPtr.data() ); if( !artist ) { QFAIL( "expected a Meta::MockArtist" ); return; } artistTracks = artistPtr->tracks(); } else { artist = new Meta::MockArtist(); ::testing::Mock::AllowLeak( artist ); artistPtr = Meta::ArtistPtr( artist ); EXPECT_CALL( *artist, name() ).Times( AnyNumber() ).WillRepeatedly( Return( artistName ) ); coll->mc->addArtist( artistPtr ); } artistTracks << trackPtr; EXPECT_CALL( *artist, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( artistTracks ) ); EXPECT_CALL( *track, artist() ).Times( AnyNumber() ).WillRepeatedly( Return( artistPtr ) ); EXPECT_CALL( *album, albumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( artistPtr ) ); } TestOneWaySynchronizationJob::TestOneWaySynchronizationJob() : QObject() { int argc = 1; char **argv = (char **) malloc(sizeof(char *)); argv[0] = strdup( QCoreApplication::applicationName().toLocal8Bit().data() ); ::testing::InitGoogleMock( &argc, argv ); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); } void TestOneWaySynchronizationJob::init() { trackCopyCount = 0; } void TestOneWaySynchronizationJob::testAddTrackToTarget() { Collections::CollectionTestImpl *source = new Collections::MyCollectionTestImpl( "source" ); Collections::CollectionTestImpl *target = new Collections::MyCollectionTestImpl( "target" ); addMockTrack( source, "track1", "artist1", "album1" ); addMockTrack( source, "track2", "artist1", "album1" ); addMockTrack( target, "track1", "artist1", "album1" ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( source->mc->trackMap().count(), 2 ); QCOMPARE( target->mc->trackMap().count(), 1 ); OneWaySynchronizationJob *job = new OneWaySynchronizationJob(); QSignalSpy spy( job, &OneWaySynchronizationJob::destroyed ); job->setSource( source ); job->setTarget( target ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount, 1 ); QCOMPARE( source->mc->trackMap().count(), 2 ); QCOMPARE( target->mc->trackMap().count(), 2 ); delete source, delete target; } void TestOneWaySynchronizationJob::testAddAlbumToTarget() { Collections::CollectionTestImpl *source = new Collections::MyCollectionTestImpl( "source" ); Collections::CollectionTestImpl *target = new Collections::MyCollectionTestImpl( "target" ); addMockTrack( source, "track1", "artist1", "album1" ); addMockTrack( source, "track1", "artist1", "album2" ); addMockTrack( target, "track1", "artist1", "album1" ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( source->mc->trackMap().count(), 2 ); QCOMPARE( target->mc->trackMap().count(), 1 ); OneWaySynchronizationJob *job = new OneWaySynchronizationJob(); QSignalSpy spy( job, &OneWaySynchronizationJob::destroyed ); job->setSource( source ); job->setTarget( target ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount, 1 ); QCOMPARE( source->mc->trackMap().count(), 2 ); QCOMPARE( target->mc->trackMap().count(), 2 ); delete source, delete target; } void TestOneWaySynchronizationJob::testAddArtistToTarget() { Collections::CollectionTestImpl *source = new Collections::MyCollectionTestImpl( "source" ); Collections::CollectionTestImpl *target = new Collections::MyCollectionTestImpl( "target" ); addMockTrack( source, "track1", "artist1", "album1" ); addMockTrack( source, "track1", "artist2", "album1" ); addMockTrack( target, "track1", "artist1", "album1" ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( source->mc->trackMap().count(), 2 ); QCOMPARE( target->mc->trackMap().count(), 1 ); OneWaySynchronizationJob *job = new OneWaySynchronizationJob(); QSignalSpy spy( job, &OneWaySynchronizationJob::destroyed ); job->setSource( source ); job->setTarget( target ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount, 1 ); QCOMPARE( source->mc->trackMap().count(), 2 ); QCOMPARE( target->mc->trackMap().count(), 2 ); delete source, delete target; } void TestOneWaySynchronizationJob::testEmptyTarget() { Collections::CollectionTestImpl *source = new Collections::MyCollectionTestImpl( "source" ); Collections::CollectionTestImpl *target = new Collections::MyCollectionTestImpl( "target" ); addMockTrack( source, "track1", "artist1", "album1" ); addMockTrack( source, "track2", "artist1", "album1" ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( source->mc->trackMap().count(), 2 ); QCOMPARE( target->mc->trackMap().count(), 0 ); OneWaySynchronizationJob *job = new OneWaySynchronizationJob(); QSignalSpy spy( job, &OneWaySynchronizationJob::destroyed ); job->setSource( source ); job->setTarget( target ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount, 2 ); QCOMPARE( source->mc->trackMap().count(), 2 ); QCOMPARE( target->mc->trackMap().count(), 2 ); delete source, delete target; } void TestOneWaySynchronizationJob::testEmptySourceWithNonEmptyTarget() { Collections::CollectionTestImpl *source = new Collections::MyCollectionTestImpl( "source" ); Collections::CollectionTestImpl *target = new Collections::MyCollectionTestImpl( "target" ); addMockTrack( target, "track1", "artist1", "album1" ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( source->mc->trackMap().count(), 0 ); QCOMPARE( target->mc->trackMap().count(), 1 ); OneWaySynchronizationJob *job = new OneWaySynchronizationJob(); QSignalSpy spy( job, &OneWaySynchronizationJob::destroyed ); job->setSource( source ); job->setTarget( target ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( source->mc->trackMap().count(), 0 ); QCOMPARE( target->mc->trackMap().count(), 1 ); delete source, delete target; } void TestOneWaySynchronizationJob::testNoActionNecessary() { Collections::CollectionTestImpl *source = new Collections::MyCollectionTestImpl( "source" ); Collections::CollectionTestImpl *target = new Collections::MyCollectionTestImpl( "target" ); addMockTrack( source, "track1", "artist1", "album1" ); addMockTrack( source, "track2", "artist1", "album1" ); addMockTrack( target, "track1", "artist1", "album1" ); addMockTrack( target, "track2", "artist1", "album1" ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( source->mc->trackMap().count(), 2 ); QCOMPARE( target->mc->trackMap().count(), 2 ); OneWaySynchronizationJob *job = new OneWaySynchronizationJob(); QSignalSpy spy( job, &OneWaySynchronizationJob::destroyed ); job->setSource( source ); job->setTarget( target ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount, 0 ); QCOMPARE( source->mc->trackMap().count(), 2 ); QCOMPARE( target->mc->trackMap().count(), 2 ); delete source, delete target; } diff --git a/tests/synchronization/TestUnionJob.cpp b/tests/synchronization/TestUnionJob.cpp index 285367666e..534b404fcd 100644 --- a/tests/synchronization/TestUnionJob.cpp +++ b/tests/synchronization/TestUnionJob.cpp @@ -1,268 +1,268 @@ /**************************************************************************************** * Copyright (c) 2010 Maximilian Kossick * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see . * ****************************************************************************************/ #include "TestUnionJob.h" #include "core/support/Debug.h" #include "core/collections/CollectionLocation.h" #include "synchronization/UnionJob.h" #include "CollectionTestImpl.h" #include "mocks/MockTrack.h" #include "mocks/MockAlbum.h" #include "mocks/MockArtist.h" #include #include #include -QTEST_MAIN( TestUnionJob ) +QTEST_GUILESS_MAIN( TestUnionJob ) using ::testing::Return; using ::testing::AnyNumber; static QList trackCopyCount; namespace Collections { class MyCollectionLocation : public CollectionLocation { public: Collections::CollectionTestImpl *coll; QString prettyLocation() const { return "foo"; } bool isWritable() const { return true; } bool remove( const Meta::TrackPtr &track ) { coll->mc->acquireWriteLock(); //theoretically we should clean up the other maps as well... TrackMap map = coll->mc->trackMap(); map.remove( track->uidUrl() ); coll->mc->setTrackMap( map ); coll->mc->releaseLock(); return true; } void copyUrlsToCollection(const QMap &sources, const Transcoding::Configuration& conf) { Q_UNUSED( conf ) trackCopyCount << sources.count(); foreach( const Meta::TrackPtr &track, sources.keys() ) { coll->mc->addTrack( track ); } } }; class MyCollectionTestImpl : public CollectionTestImpl { public: MyCollectionTestImpl( const QString &id ) : CollectionTestImpl( id ) {} CollectionLocation* location() { MyCollectionLocation *r = new MyCollectionLocation(); r->coll = this; return r; } }; } //namespace Collections void addMockTrack( Collections::CollectionTestImpl *coll, const QString &trackName, const QString &artistName, const QString &albumName ) { Meta::MockTrack *track = new Meta::MockTrack(); ::testing::Mock::AllowLeak( track ); Meta::TrackPtr trackPtr( track ); EXPECT_CALL( *track, name() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName ) ); EXPECT_CALL( *track, uidUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( trackName + '_' + artistName + '_' + albumName ) ); EXPECT_CALL( *track, playableUrl() ).Times( AnyNumber() ).WillRepeatedly( Return( QUrl( '/' + track->uidUrl() ) ) ); coll->mc->addTrack( trackPtr ); Meta::AlbumPtr albumPtr = coll->mc->albumMap().value( albumName, QString() /* no album artist */ ); Meta::MockAlbum *album; Meta::TrackList albumTracks; if( albumPtr ) { album = dynamic_cast( albumPtr.data() ); if( !album ) { QFAIL( "expected a Meta::MockAlbum" ); return; } albumTracks = albumPtr->tracks(); } else { album = new Meta::MockAlbum(); ::testing::Mock::AllowLeak( album ); albumPtr = Meta::AlbumPtr( album ); EXPECT_CALL( *album, name() ).Times( AnyNumber() ).WillRepeatedly( Return( albumName ) ); EXPECT_CALL( *album, hasAlbumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( false ) ); EXPECT_CALL( *album, albumArtist() ).Times( AnyNumber() ).WillRepeatedly( Return( Meta::ArtistPtr() ) ); coll->mc->addAlbum( albumPtr ); } albumTracks << trackPtr; EXPECT_CALL( *album, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( albumTracks ) ); EXPECT_CALL( *track, album() ).Times( AnyNumber() ).WillRepeatedly( Return( albumPtr ) ); Meta::ArtistPtr artistPtr = coll->mc->artistMap().value( artistName ); Meta::MockArtist *artist; Meta::TrackList artistTracks; if( artistPtr ) { artist = dynamic_cast( artistPtr.data() ); if( !artist ) { QFAIL( "expected a Meta::MockArtist" ); return; } artistTracks = artistPtr->tracks(); } else { artist = new Meta::MockArtist(); ::testing::Mock::AllowLeak( artist ); artistPtr = Meta::ArtistPtr( artist ); EXPECT_CALL( *artist, name() ).Times( AnyNumber() ).WillRepeatedly( Return( artistName ) ); coll->mc->addArtist( artistPtr ); } artistTracks << trackPtr; EXPECT_CALL( *artist, tracks() ).Times( AnyNumber() ).WillRepeatedly( Return( artistTracks ) ); EXPECT_CALL( *track, artist() ).Times( AnyNumber() ).WillRepeatedly( Return( artistPtr ) ); } TestUnionJob::TestUnionJob() : QObject() { int argc = 1; char **argv = (char **) malloc(sizeof(char *)); argv[0] = strdup( QCoreApplication::applicationName().toLocal8Bit().data() ); ::testing::InitGoogleMock( &argc, argv ); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); } void TestUnionJob::init() { trackCopyCount.clear(); } void TestUnionJob::testEmptyA() { Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A"); Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B"); addMockTrack( collB, "track1", "artist1", "album1" ); QCOMPARE( collA->mc->trackMap().count(), 0 ); QCOMPARE( collB->mc->trackMap().count(), 1 ); QVERIFY( trackCopyCount.isEmpty() ); UnionJob *job = new UnionJob( collA, collB ); QSignalSpy spy( job, &UnionJob::destroyed ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount.size(), 1 ); QVERIFY( trackCopyCount.contains( 1 ) ); QCOMPARE( collA->mc->trackMap().count(), 1 ); QCOMPARE( collB->mc->trackMap().count(), 1 ); delete collA; delete collB; } void TestUnionJob::testEmptyB() { Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A"); Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B"); addMockTrack( collA, "track1", "artist1", "album1" ); QCOMPARE( collA->mc->trackMap().count(), 1 ); QCOMPARE( collB->mc->trackMap().count(), 0 ); QVERIFY( trackCopyCount.isEmpty() ); UnionJob *job = new UnionJob( collA, collB ); QSignalSpy spy( job, &UnionJob::destroyed ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount.size(), 1 ); QVERIFY( trackCopyCount.contains( 1 ) ); QCOMPARE( collA->mc->trackMap().count(), 1 ); QCOMPARE( collB->mc->trackMap().count(), 1 ); delete collA; delete collB; } void TestUnionJob::testAddTrackToBoth() { Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A"); Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B"); addMockTrack( collA, "track1", "artist1", "album1" ); addMockTrack( collB, "track2", "artist2", "album2" ); QCOMPARE( collA->mc->trackMap().count(), 1 ); QCOMPARE( collB->mc->trackMap().count(), 1 ); QVERIFY( trackCopyCount.isEmpty() ); UnionJob *job = new UnionJob( collA, collB ); QSignalSpy spy( job, &UnionJob::destroyed ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount.size(), 2 ); QCOMPARE( trackCopyCount.at( 0 ), 1 ); QCOMPARE( trackCopyCount.at( 1 ), 1 ); QCOMPARE( collA->mc->trackMap().count(), 2 ); QCOMPARE( collB->mc->trackMap().count(), 2 ); delete collA; delete collB; } void TestUnionJob::testTrackAlreadyInBoth() { Collections::CollectionTestImpl *collA = new Collections::MyCollectionTestImpl("A"); Collections::CollectionTestImpl *collB = new Collections::MyCollectionTestImpl("B"); addMockTrack( collA, "track1", "artist1", "album1" ); addMockTrack( collB, "track1", "artist1", "album1" ); addMockTrack( collB, "track2", "artist2", "album2" ); QCOMPARE( collA->mc->trackMap().count(), 1 ); QCOMPARE( collB->mc->trackMap().count(), 2 ); QVERIFY( trackCopyCount.isEmpty() ); UnionJob *job = new UnionJob( collA, collB ); QSignalSpy spy( job, &UnionJob::destroyed ); job->synchronize(); spy.wait( 1000 ); QCOMPARE( trackCopyCount.size(), 1 ); QVERIFY( trackCopyCount.contains( 1 ) ); QCOMPARE( collA->mc->trackMap().count(), 2 ); QCOMPARE( collB->mc->trackMap().count(), 2 ); delete collA; delete collB; } diff --git a/tests/timecode/TestTimecodeTrackProvider.cpp b/tests/timecode/TestTimecodeTrackProvider.cpp index ba3384f081..88d0e8f9ff 100644 --- a/tests/timecode/TestTimecodeTrackProvider.cpp +++ b/tests/timecode/TestTimecodeTrackProvider.cpp @@ -1,70 +1,70 @@ /*************************************************************************** * Copyright (c) 2009 Sven Krohlas * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TestTimecodeTrackProvider.h" #include "config-amarok-test.h" #include "core/meta/Meta.h" #include "core-impl/meta/timecode/TimecodeTrackProvider.h" #include -QTEST_MAIN( TestTimecodeTrackProvider ) +QTEST_GUILESS_MAIN( TestTimecodeTrackProvider ) TestTimecodeTrackProvider::TestTimecodeTrackProvider() {} void TestTimecodeTrackProvider::initTestCase() { m_testProvider = new TimecodeTrackProvider(); } void TestTimecodeTrackProvider::cleanupTestCase() { delete m_testProvider; } QString TestTimecodeTrackProvider::dataPath( const QString &relPath ) { return QDir::toNativeSeparators( QString( AMAROK_TEST_DIR ) + '/' + relPath ); } void TestTimecodeTrackProvider::testPossiblyContainsTrack() { QVERIFY( !m_testProvider->possiblyContainsTrack( QUrl("file:///home/test/test.mp3") ) ); QVERIFY( m_testProvider->possiblyContainsTrack( QUrl("file:///home/test/test.mp3:0-23") ) ); QVERIFY( m_testProvider->possiblyContainsTrack( QUrl("file:///home/test/test.mp3:23-42") ) ); QVERIFY( m_testProvider->possiblyContainsTrack( QUrl("file:///home/test/test.mp3:42-23") ) ); QVERIFY( !m_testProvider->possiblyContainsTrack( QUrl("file:///home/test/test.mp3:-12-42") ) ); } void TestTimecodeTrackProvider::testTrackForUrl() { QUrl testUrl; testUrl = QUrl::fromLocalFile(dataPath( "data/audio/album/" )); testUrl = testUrl.adjusted(QUrl::StripTrailingSlash); testUrl.setPath(testUrl.path() + '/' + ( "Track01.ogg:23-42" )); Meta::TrackPtr resultTrack = m_testProvider->trackForUrl( testUrl ); QVERIFY( resultTrack ); QCOMPARE( resultTrack->playableUrl().path(), dataPath( "data/audio/album/Track01.ogg" ) ); }