blob: bfaecbaa2189a2a901b710596b7b8149f9353932 [file] [log] [blame]
Parker Schuhecd057f2017-03-11 20:03:01 -08001#include "aos/common/ring_buffer.h"
2
3#include "gtest/gtest.h"
4
5namespace aos {
6namespace testing {
7
8class RingBufferTest : public ::testing::Test {
9 public:
10 RingBufferTest() {}
11
12 protected:
13 RingBuffer<int, 10> buffer_;
14};
15
16// Test if the RingBuffer is empty when initialized properly
17TEST_F(RingBufferTest, DefaultIsEmpty) {
18 // The RingBuffer should have a size of 0, a capacity of 10 (note that it was
19 // initialized as 10), have no items, and not be full
20 ASSERT_EQ(0u, buffer_.size());
21 ASSERT_EQ(10u, buffer_.capacity());
22 ASSERT_TRUE(buffer_.empty());
23 ASSERT_FALSE(buffer_.full());
24}
25
26// Test that the RingBuffer can fill it's entire capacity and read back the data
27TEST_F(RingBufferTest, CanAddData) {
28 ASSERT_TRUE(buffer_.empty());
29
30 // Add sequential numbers to the RingBuffer
31 // (the value of each item is it's index #)
32 for (size_t i = 0; i < buffer_.capacity(); ++i) {
33 // The buffer shouldn't be full yet, and it's size should be how many items
34 // we've added so far. Once that happens, we add another item
35 ASSERT_FALSE(buffer_.full());
36 ASSERT_EQ(i, buffer_.size());
37 buffer_.Push(i);
38
39 // The buffer shouldn't be empty and it's size should be 1 more since we
40 // just
41 // added an item. Also, the last item in the buffer should equal the one we
42 // just added
43 ASSERT_FALSE(buffer_.empty());
44 ASSERT_EQ(i + 1, buffer_.size());
45 ASSERT_EQ(i, buffer_[i]);
46 }
47
48 ASSERT_TRUE(buffer_.full());
49}
50
51// Tests that the RingBuffer properly loops back and starts overwriting from the
52// first element after being filled up
53TEST_F(RingBufferTest, OverfillData) {
54 // Add numbers 0-24 to the RingBuffer
55 for (int i = 0; i < 25; ++i) {
56 buffer_.Push(i);
57 }
58
59 // It should now be full
60 ASSERT_TRUE(buffer_.full());
61
62 // Since the buffer is a size of 10 and has been filled up 2.5 times, it
63 // should
64 // now contain the numbers 15-24
65 for (size_t i = 0; i < buffer_.size(); ++i) {
66 ASSERT_EQ(15 + i, buffer_[i]);
67 }
68}
69
Parker Schuh208a58d2017-04-12 20:51:38 -070070// Tests shifting from the front of the ringbuffer.
71TEST_F(RingBufferTest, RingBufferShift) {
72 // Add numbers 0-24 to the RingBuffer
73 for (int i = 0; i < 25; ++i) {
74 buffer_.Push(i);
75 }
76
77 // It should now be full
78 ASSERT_TRUE(buffer_.full());
79
80 buffer_.Shift();
81 buffer_.Shift();
82 buffer_.Shift();
83
84 ASSERT_EQ(buffer_.size(), 7);
85
86 // The buffer should now contain the numbers 18-24
87 for (size_t i = 0; i < buffer_.size(); ++i) {
88 ASSERT_EQ(18 + i, buffer_[i]);
89 }
90}
91
Parker Schuhecd057f2017-03-11 20:03:01 -080092} // namespace testing
93} // namespace aos