~charlesk/keeper/add-keeper-dbusmock-template

« back to all changes in this revision

Viewing changes to tests/utils/dummy-file.cpp

  • Committer: Charles Kerr
  • Date: 2016-07-13 19:09:59 UTC
  • mfrom: (28.1.11 tmp)
  • Revision ID: charles.kerr@canonical.com-20160713190959-4x080d253394k27b
sync with trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * Copyright 2016 Canonical Ltd.
 
3
 *
 
4
 * This program is free software: you can redistribute it and/or modify it
 
5
 * under the terms of the GNU General Public License version 3, as published
 
6
 * by the Free Software Foundation.
 
7
 *
 
8
 * This program is distributed in the hope that it will be useful, but
 
9
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 
10
 * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
 
11
 * PURPOSE.  See the GNU General Public License for more details.
 
12
 *
 
13
 * You should have received a copy of the GNU General Public License along
 
14
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 
15
 *
 
16
 * Authors:
 
17
 *   Charles Kerr <charles.kerr@canonical.com>
 
18
 */
 
19
 
 
20
#include "tests/utils/dummy-file.h"
 
21
 
 
22
#include <QCryptographicHash>
 
23
#include <QDir>
 
24
#include <QFile>
 
25
#include <QString>
 
26
#include <QTemporaryFile>
 
27
 
 
28
DummyFile::Info
 
29
DummyFile::create(const QDir& dir, qint64 filesize)
 
30
{
 
31
    // NB we want to exercise long filenames, but this cutoff length is arbitrary
 
32
    static constexpr int MAX_BASENAME_LEN {200};
 
33
    int filename_len = qrand() % MAX_BASENAME_LEN;
 
34
    QString basename;
 
35
    for (int i=0; i<filename_len; ++i)
 
36
        basename += ('a' + char(qrand() % ('z'-'a')));
 
37
    basename += QStringLiteral("-XXXXXX");
 
38
    auto template_name = dir.absoluteFilePath(basename);
 
39
 
 
40
    // fill the file with noise
 
41
    QTemporaryFile f(template_name);
 
42
    f.setAutoRemove(false);
 
43
    f.open();
 
44
    static constexpr qint64 max_step = 1024;
 
45
    char buf[max_step];
 
46
    qint64 left = filesize;
 
47
    while(left > 0)
 
48
    {
 
49
        int this_step = std::min(max_step, left);
 
50
        for(int i=0; i<this_step; ++i)
 
51
            buf[i] = 'a' + char(qrand() % ('z'-'a'));
 
52
        f.write(buf, this_step);
 
53
        left -= this_step;
 
54
    }
 
55
    f.close();
 
56
 
 
57
    // get a checksum
 
58
    f.open();
 
59
    QCryptographicHash hash(QCryptographicHash::Sha1);
 
60
    hash.addData(&f);
 
61
    const auto checksum = hash.result();
 
62
    f.close();
 
63
 
 
64
    DummyFile::Info info;
 
65
    info.info = QFileInfo(f.fileName());
 
66
    info.checksum = checksum;
 
67
    return info;
 
68
}