summaryrefslogtreecommitdiff
path: root/test/test_common.cpp
blob: 784cb0dc431e44d911f41ab78a0737246579f455 (plain)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
 * libfud
 * Copyright 2024 Dominick Allen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "test_common.hpp"

#include "fud_string.hpp"

#include <cstdlib>
#include <ftw.h>
#include <gtest/gtest.h>

namespace fud {

void* MockFudAlloc::operator()(size_t size)
{
    return malloc(size);
}

void MockFudDealloc::operator()(void* pointer)
{
    return free(pointer);
}

MockFudAlloc globalDefaultMockAlloc{};

MockFudDealloc globalDefaultMockDealloc{};

void* MockFudAllocator::allocate(size_t size)
{
    return (*m_allocator)(size);
}

void MockFudAllocator::deallocate(void* pointer)
{
    return (*m_deallocator)(pointer);
}

MockFudAllocator globalMockFudAlloc{};

void* fudAlloc(size_t size)
{
    return globalMockFudAlloc.allocate(size);
}

void fudFree(void* ptr)
{
    return globalMockFudAlloc.deallocate(ptr);
}

int unlink_cb(const char* fpath, const struct stat* sb_unused, int typeflag, struct FTW* ftwbuf)
{
    static_cast<void>(sb_unused);
    int retValue = remove(fpath);

    EXPECT_EQ(retValue, 0);
    if (retValue != 0) {
        perror(fpath);
    }

    return retValue;
}

FudStatus removeRecursive(const String& path)
{
    if (!path.utf8Valid()) {
        return FudStatus::Utf8Invalid;
    }
    if (path.length() < 5) {
        return FudStatus::ArgumentInvalid;
    }
    auto prefix{String::makeFromCString("/tmp/").takeOkay()};
    auto diffResult = compareMem(path.data(), path.length(), prefix.data(), prefix.length());
    if (diffResult.isError()) {
        return FudStatus::ArgumentInvalid;
    }
    auto diff = diffResult.getOkay();
    if (diff != 0) {
        return FudStatus::ArgumentInvalid;
    }
    constexpr int maxOpenFd = 64;
    auto status = nftw(path.c_str(), unlink_cb, maxOpenFd, FTW_DEPTH | FTW_PHYS);
    if (status == 0) {
        return FudStatus::Success;
    }

    if (errno == ENOENT) {
        return FudStatus::Success;
    }

    return FudStatus::Failure;
}

} // namespace fud