File: test_util_test.cc

package info (click to toggle)
libtoxcore 0.2.20-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,124 kB
  • sloc: ansic: 75,034; cpp: 4,933; sh: 1,115; python: 651; makefile: 329; perl: 39
file content (65 lines) | stat: -rw-r--r-- 1,725 bytes parent folder | download
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
#include "test_util.hh"

#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <array>

#include "crypto_core.h"
#include "crypto_core_test_util.hh"

namespace {

using ::testing::Each;
using ::testing::Eq;

TEST(CryptoCoreTestUtil, RandomBytesDoesNotTouchZeroSizeArray)
{
    const Test_Random rng;
    std::array<uint8_t, 32> bytes{};
    for (uint32_t i = 0; i < 100; ++i) {
        random_bytes(rng, bytes.data(), 0);
        ASSERT_THAT(bytes, Each(Eq(0x00)));
    }
}

TEST(CryptoCoreTestUtil, RandomBytesFillsEntireArray)
{
    const Test_Random rng;
    std::array<uint8_t, 32> bytes{};

    for (uint32_t size = 1; size < bytes.size(); ++size) {
        bool const success = [&]() {
            // Try a few times. There ought to be a non-zero byte in our randomness at
            // some point.
            for (uint32_t i = 0; i < 100; ++i) {
                random_bytes(rng, bytes.data(), bytes.size());
                if (bytes[size - 1] != 0x00) {
                    return true;
                }
            }
            return false;
        }();
        ASSERT_TRUE(success);
    }
}

TEST(CryptoCoreTestUtil, RandomBytesDoesNotBufferOverrun)
{
    const Test_Random rng;

    std::array<uint8_t, 32> bytes{};

    // Try a few times. It should never overrun.
    for (uint32_t i = 0; i < 100; ++i) {
        for (uint32_t diff = 1; diff < sizeof(uint64_t); ++diff) {
            bytes = {};
            random_bytes(rng, bytes.data(), bytes.size() - diff);
            // All bytes not in the range we want to write should be 0.
            ASSERT_THAT(std::vector<uint8_t>(bytes.begin() + (bytes.size() - diff), bytes.end()),
                Each(Eq(0x00)));
        }
    }
}

}  // namespace