FileManagerTest.cc 17.6 KB
Newer Older
Don Gagne's avatar
Don Gagne committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*=====================================================================
 
 QGroundControl Open Source Ground Control Station
 
 (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 
 This file is part of the QGROUNDCONTROL project
 
 QGROUNDCONTROL 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 3 of the License, or
 (at your option) any later version.
 
 QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
 
 ======================================================================*/

/// @file
///     @author Don Gagne <don@thegagnes.com>

27 28 29
#include "FileManagerTest.h"
#include "UASManager.h"

30
//UT_REGISTER_TEST(FileManagerTest)
Don Gagne's avatar
Don Gagne committed
31

32
FileManagerTest::FileManagerTest(void) :
33 34
    _mockLink(NULL),
    _fileServer(NULL),
Don Gagne's avatar
Don Gagne committed
35 36 37
    _fileManager(NULL),
    _multiSpy(NULL)
{
38

Don Gagne's avatar
Don Gagne committed
39 40 41
}

// Called before every test case
42
void FileManagerTest::init(void)
Don Gagne's avatar
Don Gagne committed
43
{
Don Gagne's avatar
Don Gagne committed
44 45
    UnitTest::init();
    
46 47 48 49 50 51 52
    _mockLink = new MockLink();
    Q_CHECK_PTR(_mockLink);
    LinkManager::instance()->_addLink(_mockLink);
    LinkManager::instance()->connectLink(_mockLink);

    _fileServer = _mockLink->getFileServer();
    QVERIFY(_fileServer != NULL);
Don Gagne's avatar
Don Gagne committed
53
    
54 55 56 57 58 59 60 61 62 63 64 65 66
    // Wait or the UAS to show up
    UASManagerInterface* uasManager = UASManager::instance();
    QSignalSpy spyUasCreate(uasManager, SIGNAL(UASCreated(UASInterface*)));
    if (!uasManager->getActiveUAS()) {
        QCOMPARE(spyUasCreate.wait(10000), true);
    }
    UASInterface* uas = uasManager->getActiveUAS();
    QVERIFY(uas != NULL);
    
    _fileManager = uas->getFileManager();
    QVERIFY(_fileManager != NULL);
    
    Q_ASSERT(_multiSpy == NULL);
Don Gagne's avatar
Don Gagne committed
67
    
68
    // Reset any internal state back to normal
69
    _fileServer->setErrorMode(MockLinkFileServer::errModeNone);
70
    _fileListReceived.clear();
Don Gagne's avatar
Don Gagne committed
71

72
    connect(_fileManager, &FileManager::listEntry, this, &FileManagerTest::listEntry);
Don Gagne's avatar
Don Gagne committed
73

74
    _rgSignals[listEntrySignalIndex] = SIGNAL(listEntry(const QString&));
75 76
    _rgSignals[commandCompleteSignalIndex] = SIGNAL(commandComplete(void));
    _rgSignals[commandErrorSignalIndex] = SIGNAL(commandError(const QString&));
77

Don Gagne's avatar
Don Gagne committed
78 79 80 81 82 83
    _multiSpy = new MultiSignalSpy();
    Q_CHECK_PTR(_multiSpy);
    QCOMPARE(_multiSpy->init(_fileManager, _rgSignals, _cSignals), true);
}

// Called after every test case
84
void FileManagerTest::cleanup(void)
Don Gagne's avatar
Don Gagne committed
85 86 87 88
{
    Q_ASSERT(_multiSpy);
    Q_ASSERT(_fileManager);
    
89 90 91 92 93 94 95
    // Disconnecting the link will prompt for log file save
    setExpectedFileDialog(getSaveFileName, QStringList());
    LinkManager::instance()->disconnectLink(_mockLink);
    _fileServer = NULL;
    _mockLink = NULL;
    _fileManager = NULL;
    
Don Gagne's avatar
Don Gagne committed
96 97 98
    delete _multiSpy;
    
    _multiSpy = NULL;
Don Gagne's avatar
Don Gagne committed
99 100
    
    UnitTest::cleanup();
Don Gagne's avatar
Don Gagne committed
101 102
}

103 104
/// @brief Connected to FileManager listEntry signal in order to catch list entries
void FileManagerTest::listEntry(const QString& entry)
Don Gagne's avatar
Don Gagne committed
105 106
{
    // Keep a list of all names received so we can test it for correctness
107
    _fileListReceived += entry;
Don Gagne's avatar
Don Gagne committed
108 109 110
}


111
void FileManagerTest::_ackTest(void)
Don Gagne's avatar
Don Gagne committed
112 113 114 115 116 117 118 119
{
    Q_ASSERT(_fileManager);
    Q_ASSERT(_multiSpy);
    Q_ASSERT(_multiSpy->checkNoSignals() == true);
    
    // If the file manager doesn't receive an ack it will timeout and emit an error. So make sure
    // we don't get any error signals.
    QVERIFY(_fileManager->_sendCmdTestAck());
120
    QTest::qWait(_ackTimerTimeoutMsecs); // Let the file manager timeout
Don Gagne's avatar
Don Gagne committed
121
    QVERIFY(_multiSpy->checkNoSignals());
122
    
123
    // Setup for no response from ack. This should cause a timeout error
124
    _fileServer->setErrorMode(MockLinkFileServer::errModeNoResponse);
125
    QVERIFY(_fileManager->_sendCmdTestAck());
126 127
    _multiSpy->waitForSignalByIndex(commandErrorSignalIndex, _ackTimerTimeoutMsecs);
    QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
128 129 130
    _multiSpy->clearAllSignals();

    // Setup for a bad sequence number in the ack. This should cause an error;
131
    _fileServer->setErrorMode(MockLinkFileServer::errModeBadSequence);
132
    QVERIFY(_fileManager->_sendCmdTestAck());
133 134
    _multiSpy->waitForSignalByIndex(commandErrorSignalIndex, _ackTimerTimeoutMsecs);
    QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
135
    _multiSpy->clearAllSignals();
Don Gagne's avatar
Don Gagne committed
136 137
}

138
void FileManagerTest::_noAckTest(void)
Don Gagne's avatar
Don Gagne committed
139 140 141 142 143 144 145
{
    Q_ASSERT(_fileManager);
    Q_ASSERT(_multiSpy);
    Q_ASSERT(_multiSpy->checkNoSignals() == true);
    
    // This should not get the ack back and timeout.
    QVERIFY(_fileManager->_sendCmdTestNoAck());
146
    QTest::qWait(_ackTimerTimeoutMsecs); // Let the file manager timeout
147
    QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
Don Gagne's avatar
Don Gagne committed
148 149
}

150
void FileManagerTest::_listTest(void)
Don Gagne's avatar
Don Gagne committed
151 152 153 154 155
{
    Q_ASSERT(_fileManager);
    Q_ASSERT(_multiSpy);
    Q_ASSERT(_multiSpy->checkNoSignals() == true);
    
156
    // FileManager::listDirectory signalling as follows:
157
    //  Emits a listEntry signal for each list entry
158
    //  Emits an commandError signal if:
159 160 161 162
    //      It gets a Nak back
    //      Sequence number is incorrrect on any response
    //      CRC is incorrect on any responses
    //      List entry is formatted incorrectly
163 164 165
    //  It is possible to get a number of good listEntry signals, followed by an commandError signal
    //  Emits commandComplete after it receives the final list entry
    //      If an commandError signal is signalled no listComplete is signalled
166
    
Don Gagne's avatar
Don Gagne committed
167
    // Send a bogus path
168
    //  We should get a single commandError signal
169
    _fileManager->listDirectory("/bogus");
170 171
    _multiSpy->waitForSignalByIndex(commandErrorSignalIndex, _ackTimerTimeoutMsecs);
    QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
Don Gagne's avatar
Don Gagne committed
172 173
    _multiSpy->clearAllSignals();

174
    // Setup the mock file server with a valid directory list
Don Gagne's avatar
Don Gagne committed
175 176
    QStringList fileList;
    fileList << "Ddir" << "Ffoo" << "Fbar";
177 178 179 180 181 182 183 184 185 186 187 188 189
    _fileServer->setFileList(fileList);
    
    // Send a list command at the root of the directory tree which should succeed
    _fileManager->listDirectory("/");
    QTest::qWait(_ackTimerTimeoutMsecs); // Let the file manager timeout
    QCOMPARE(_multiSpy->checkSignalByMask(commandCompleteSignalMask), true);
    QCOMPARE(_multiSpy->checkNoSignalByMask(commandErrorSignalMask), true);
    QCOMPARE(_multiSpy->getSpyByIndex(listEntrySignalIndex)->count(), fileList.count());
    QVERIFY(_fileListReceived == fileList);
    
    // Set everything back to initial state
    _fileListReceived.clear();
    _multiSpy->clearAllSignals();
Don Gagne's avatar
Don Gagne committed
190
    
191
    // Run through the various server side failure modes
192 193
    for (size_t i=0; i<MockLinkFileServer::cFailureModes; i++) {
        MockLinkFileServer::ErrorMode_t errMode = MockLinkFileServer::rgFailureModes[i];
194
        qDebug() << "Testing failure mode:" << errMode;
195
        _fileServer->setErrorMode(errMode);
196 197 198 199
        
        _fileManager->listDirectory("/");
        QTest::qWait(_ackTimerTimeoutMsecs); // Let the file manager timeout
        
200
        if (errMode == MockLinkFileServer::errModeNoSecondResponse || errMode == MockLinkFileServer::errModeNakSecondResponse) {
201 202 203
            // For simulated server errors on subsequent Acks, the first Ack will go through. This means we should have gotten some
            // partial results. In the case of the directory list test set, all entries fit into the first ack, so we should have
            // gotten back all of them.
204 205
            QCOMPARE(_multiSpy->getSpyByIndex(listEntrySignalIndex)->count(), fileList.count());
            _multiSpy->clearSignalByIndex(listEntrySignalIndex);
206 207
            
            // And then it should have errored out because the next list Request would have failed.
208
            QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
209 210 211
        } else {
            // For the simulated errors which failed the intial response we should not have gotten any results back at all.
            // Just an error.
212
            QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
213 214 215 216 217
        }

        // Set everything back to initial state
        _fileListReceived.clear();
        _multiSpy->clearAllSignals();
218
        _fileServer->setErrorMode(MockLinkFileServer::errModeNone);
219
    }
Don Gagne's avatar
Don Gagne committed
220
}
221

222 223 224
#if 0
// Trying to write test code for read and burst mode download as well as implement support in MockLineFileServer reached a point
// of diminishing returns where the test code and mock server were generating more bugs in themselves than finding problems.
225
void FileManagerTest::_readDownloadTest(void)
226 227 228 229 230
{
    Q_ASSERT(_fileManager);
    Q_ASSERT(_multiSpy);
    Q_ASSERT(_multiSpy->checkNoSignals() == true);
    
231 232 233
    // We setup a spy on the Reset command signal of the mock file server so that we can determine that a
    // Reset command was correctly sent after the Open/Read commands complete.
    QSignalSpy resetSpy(_fileServer, SIGNAL(resetCommandReceived()));
234
    
235 236
    // Send a bogus path
    _fileManager->downloadPath("bogus", QDir::temp());
237 238
    _multiSpy->waitForSignalByIndex(commandErrorSignalIndex, _ackTimerTimeoutMsecs);
    QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
239
    _multiSpy->clearAllSignals();
240 241
    QCOMPARE(resetSpy.count(), 0);

242
    // Clean previous downloads
243 244
    for (size_t i=0; i<MockLinkFileServer::cFileTestCases; i++) {
        QString filePath = QDir::temp().absoluteFilePath(MockLinkFileServer::rgFileTestCases[i].filename);
245 246 247
        if (QFile::exists(filePath)) {
            Q_ASSERT(QFile::remove(filePath));
        }
248
    }
249
    
250
    // Run through the set of file test cases
251 252
    for (size_t i=0; i<MockLinkFileServer::cFileTestCases; i++) {
        const MockLinkFileServer::FileTestCase* testCase = &MockLinkFileServer::rgFileTestCases[i];
253 254
        
        // Run through the various failure modes for this test case
255 256
        for (size_t j=0; j<MockLinkFileServer::cFailureModes; j++) {
            qDebug() << "Testing successful download";
257
			
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
            // Run what should be a successful file download test case. No servers errors are being simulated.
            _fileServer->setErrorMode(MockLinkFileServer::errModeNone);
            _fileManager->downloadPath(testCase->filename, QDir::temp());
            QTest::qWait(_ackTimerTimeoutMsecs); // Let the file manager timeout
            
            // This should be a succesful download
            QCOMPARE(_multiSpy->checkOnlySignalByMask(commandCompleteSignalMask), true);
            _multiSpy->clearAllSignals();
            
            // We should get a single Reset command to close the session
            QCOMPARE(resetSpy.count(), 1);
            resetSpy.clear();
            
            // Validate file contents
            QString filePath = QDir::temp().absoluteFilePath(MockLinkFileServer::rgFileTestCases[i].filename);
            _validateFileContents(filePath, MockLinkFileServer::rgFileTestCases[i].length);
            MockLinkFileServer::ErrorMode_t errMode = MockLinkFileServer::rgFailureModes[j];
            
276
            qDebug() << "Testing failure mode:" << errMode;
277
            _fileServer->setErrorMode(errMode);
278
            
279
            _fileManager->downloadPath(testCase->filename, QDir::temp());
280 281
            QTest::qWait(_ackTimerTimeoutMsecs); // Let the file manager timeout
            
282 283 284 285 286 287
            if (errMode == MockLinkFileServer::errModeNakResponse) {
                // This will Nak the Open call which will fail the download, but not cause a Reset
                QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
                QCOMPARE(resetSpy.count(), 0);
            } else {
                if (testCase->packetCount == 1 && (errMode == MockLinkFileServer::errModeNoSecondResponse || errMode == MockLinkFileServer::errModeNakSecondResponse)) {
288
                    // The downloaded file fits within a single Ack response, hence there is no second Read issued.
289 290 291
                    // This should result in a successful download, followed by a Reset
                    QCOMPARE(_multiSpy->checkOnlySignalByMask(commandCompleteSignalMask), true);
                    QCOMPARE(resetSpy.count(), 1);
292 293
                    
                    // Validate file contents
294 295
                    QString filePath = QDir::temp().absoluteFilePath(testCase->filename);
                    _validateFileContents(filePath, testCase->length);
296 297 298 299
                } else {
                    // Download should have failed, followed by a aReset
                    QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
                    QCOMPARE(resetSpy.count(), 1);
300 301 302 303 304
                }
            }

            // Cleanup for next iteration
            _multiSpy->clearAllSignals();
305 306
            resetSpy.clear();
            _fileServer->setErrorMode(MockLinkFileServer::errModeNone);
307
        }
308
    }
309
}
310 311 312

void FileManagerTest::_streamDownloadTest(void)
{
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    Q_ASSERT(_fileManager);
    Q_ASSERT(_multiSpy);
    Q_ASSERT(_multiSpy->checkNoSignals() == true);
    
    // We setup a spy on the Reset command signal of the mock file server so that we can determine that a
    // Reset command was correctly sent after the Open/Read commands complete.
    QSignalSpy resetSpy(_fileServer, SIGNAL(resetCommandReceived()));
    
    // Send a bogus path
    _fileManager->streamPath("bogus", QDir::temp());
    _multiSpy->waitForSignalByIndex(commandErrorSignalIndex, _ackTimerTimeoutMsecs);
    QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
    _multiSpy->clearAllSignals();
    QCOMPARE(resetSpy.count(), 0);

    // Clean previous downloads
    for (size_t i=0; i<MockLinkFileServer::cFileTestCases; i++) {
        QString filePath = QDir::temp().absoluteFilePath(MockLinkFileServer::rgFileTestCases[i].filename);
        if (QFile::exists(filePath)) {
            Q_ASSERT(QFile::remove(filePath));
        }
    }
    
    // Run through the set of file test cases
    for (size_t i=0; i<MockLinkFileServer::cFileTestCases; i++) {
        const MockLinkFileServer::FileTestCase* testCase = &MockLinkFileServer::rgFileTestCases[i];
        
        // Run through the various failure modes for this test case
        for (size_t j=0; j<MockLinkFileServer::cFailureModes; j++) {
            qDebug() << "Testing successful download";
343
			
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
            // Run what should be a successful file download test case. No servers errors are being simulated.
            _fileServer->setErrorMode(MockLinkFileServer::errModeNone);
            _fileManager->streamPath(testCase->filename, QDir::temp());
            QTest::qWait(_ackTimerTimeoutMsecs); // Let the file manager timeout
            
            // This should be a succesful download
            QCOMPARE(_multiSpy->checkOnlySignalByMask(commandCompleteSignalMask), true);
            _multiSpy->clearAllSignals();
            
            // We should get a single Reset command to close the session
            QCOMPARE(resetSpy.count(), 1);
            resetSpy.clear();
            
            // Validate file contents
            QString filePath = QDir::temp().absoluteFilePath(MockLinkFileServer::rgFileTestCases[i].filename);
            _validateFileContents(filePath, MockLinkFileServer::rgFileTestCases[i].length);
            MockLinkFileServer::ErrorMode_t errMode = MockLinkFileServer::rgFailureModes[j];
            
            qDebug() << "Testing failure mode:" << errMode;
            _fileServer->setErrorMode(errMode);
            
            _fileManager->downloadPath(testCase->filename, QDir::temp());
            QTest::qWait(_ackTimerTimeoutMsecs); // Let the file manager timeout
            
            if (errMode == MockLinkFileServer::errModeNakResponse) {
                // This will Nak the Open call which will fail the download, but not cause a Reset
                QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
                QCOMPARE(resetSpy.count(), 0);
            } else {
                if (testCase->packetCount == 1 && (errMode == MockLinkFileServer::errModeNoSecondResponse || errMode == MockLinkFileServer::errModeNakSecondResponse)) {
                    // The downloaded file fits within a single Ack response, hence there is no second Read issued.
                    // This should result in a successful download, followed by a Reset
                    QCOMPARE(_multiSpy->checkOnlySignalByMask(commandCompleteSignalMask), true);
                    QCOMPARE(resetSpy.count(), 1);
                    
                    // Validate file contents
                    QString filePath = QDir::temp().absoluteFilePath(testCase->filename);
                    _validateFileContents(filePath, testCase->length);
                } else {
                    // Download should have failed, followed by a aReset
                    QCOMPARE(_multiSpy->checkOnlySignalByMask(commandErrorSignalMask), true);
                    QCOMPARE(resetSpy.count(), 1);
                }
            }

            // Cleanup for next iteration
            _multiSpy->clearAllSignals();
            resetSpy.clear();
            _fileServer->setErrorMode(MockLinkFileServer::errModeNone);
        }
    }
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
}

void FileManagerTest::_validateFileContents(const QString& filePath, uint8_t length)
{
	QFile file(filePath);
	
	// Make sure file size is correct
	QCOMPARE(file.size(), (qint64)length);
	
	// Read data
	QVERIFY(file.open(QIODevice::ReadOnly));
	QByteArray bytes = file.readAll();
	file.close();
	
	// Validate file contents:
	//      Repeating 0x00, 0x01 .. 0xFF until file is full
	for (uint8_t i=0; i<bytes.length(); i++) {
		QCOMPARE((uint8_t)bytes[i], (uint8_t)(i & 0xFF));
	}
}
415
#endif