sandbox.h 1.83 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
// Copyright (C) 2019 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef SANDBOX_H
#define SANDBOX_H

#include <exceptions/exceptions.h>

#include <iostream>
#include <string>
14 15 16
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
17 18 19 20 21 22 23 24 25 26 27 28
#include <ftw.h>

namespace isc {
namespace test {

/// @brief A Sandbox class that provides access to unit test unique
///    temporary folder.
///
/// The sandbox's temporary folder is created in constructor ie.
/// in unit test setup phase, and then it is deleted with its content
/// in destructor ie. in unit test tear down phase.
class Sandbox {
29
private:
30 31 32 33
    /// Path to temporary folder
    std::string path_;

    /// @brief Method for deleting files and folders, used in nftw traversal function.
34
    static int rmFile(const char *fpath, const struct stat *, int , struct FTW *) {
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
        return(remove(fpath));
    }

public:
    /// @brief Sandbox constructor.
    Sandbox() {
        char tmpl[] = {P_tmpdir "/kea-XXXXXX"};
        path_ = mkdtemp(tmpl);
    }

    /// @brief Destructor, it deletes temporary folder with its content.
    ~Sandbox() {
        // Delete content of path_ recursively.
        if (nftw(path_.c_str(), Sandbox::rmFile, 10, FTW_DEPTH | FTW_MOUNT | FTW_PHYS) < 0) {
            isc_throw(isc::Unexpected, "Some issue occured while deleting unit test sandbox.");
        }
    }

53 54 55
    /// @brief Join sandbox path with indicated file subpath.
    ///
    /// @param file A path to file that should be joined to base path of sandbox.
56
    std::string join(std::string file) {
57
        return(path_ + "/" + file);
58 59 60 61 62 63 64 65
    }
};


}; // end of isc::test namespace
}; // end of isc namespace

#endif // SANDBOX_H