blob: b75596769244e277d91f9ad723ba72d4598d726f [file] [log] [blame]
Chirantan Ekbotebccb4752018-10-31 13:53:08 -07001// Copyright 2018 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "vm_tools/concierge/subnet.h"
6
7#include <arpa/inet.h>
8#include <stdint.h>
9
10#include <base/bind.h>
11#include <gtest/gtest.h>
12
13namespace vm_tools {
14namespace concierge {
15namespace {
16
17constexpr size_t kContainerBaseAddress = 0x64735cc0; // 100.115.92.192
18constexpr size_t kVmBaseAddress = 0x64735c00; // 100.115.92.0
19
20constexpr size_t kContainerSubnetPrefix = 28;
21constexpr size_t kVmSubnetPrefix = 30;
22
23class VmSubnetTest : public ::testing::TestWithParam<size_t> {};
24class ContainerSubnetTest : public ::testing::TestWithParam<size_t> {};
25class PrefixTest : public ::testing::TestWithParam<size_t> {};
26
27void DoNothing() {}
28
29void SetTrue(bool* value) {
30 *value = true;
31}
32
33} // namespace
34
35TEST_P(VmSubnetTest, AddressAtOffset) {
36 size_t index = GetParam();
37 Subnet subnet(kVmBaseAddress + index * 4, kVmSubnetPrefix,
38 base::Bind(&DoNothing));
39
40 for (uint32_t offset = 0; offset < subnet.AvailableCount(); ++offset) {
41 uint32_t address = htonl(kVmBaseAddress + index * 4 + offset + 1);
42 EXPECT_EQ(address, subnet.AddressAtOffset(offset));
43 }
44}
45
46INSTANTIATE_TEST_CASE_P(AllValues,
47 VmSubnetTest,
48 ::testing::Range(size_t{1}, size_t{32}));
49
50TEST_P(ContainerSubnetTest, AddressAtOffset) {
51 size_t index = GetParam();
52 Subnet subnet(kContainerBaseAddress + index * 16, kContainerSubnetPrefix,
53 base::Bind(&DoNothing));
54
55 for (uint32_t offset = 0; offset < subnet.AvailableCount(); ++offset) {
56 uint32_t address = htonl(kContainerBaseAddress + index * 16 + offset + 1);
57 EXPECT_EQ(address, subnet.AddressAtOffset(offset));
58 }
59}
60
61INSTANTIATE_TEST_CASE_P(AllValues,
62 ContainerSubnetTest,
63 ::testing::Range(size_t{1}, size_t{4}));
64
65TEST_P(PrefixTest, AvailableCount) {
66 size_t prefix = GetParam();
67
68 Subnet subnet(0, prefix, base::Bind(&DoNothing));
69 EXPECT_EQ((1ull << (32 - prefix)) - 2, subnet.AvailableCount());
70}
71
72TEST_P(PrefixTest, Netmask) {
73 size_t prefix = GetParam();
74
75 Subnet subnet(0, prefix, base::Bind(&DoNothing));
76 EXPECT_EQ(htonl(0xffffffff << (32 - prefix)), subnet.Netmask());
77}
78
79INSTANTIATE_TEST_CASE_P(AllValues,
80 PrefixTest,
81 ::testing::Range(size_t{0}, size_t{32}));
82
83// Tests that the Subnet runs the provided cleanup callback when it gets
84// destroyed.
85TEST(Subnet, Cleanup) {
86 bool called = false;
87
88 { Subnet subnet(0, 24, base::Bind(&SetTrue, &called)); }
89
90 EXPECT_TRUE(called);
91}
92
93} // namespace concierge
94} // namespace vm_tools