blob: dbbe8177783003cf2601df2cd11dc85e0ad9ea65 [file] [log] [blame]
Austin Schuh977a5ed2020-12-02 23:20:04 -08001#include "aos/flatbuffers.h"
2
davidjevans8b9b52f2021-09-17 08:57:30 -07003#include "absl/strings/str_cat.h"
Philipp Schrader790cb542023-07-05 21:06:52 -07004#include "gtest/gtest.h"
5
Austin Schuh977a5ed2020-12-02 23:20:04 -08006#include "aos/json_to_flatbuffer.h"
7#include "aos/json_to_flatbuffer_generated.h"
davidjevans8b9b52f2021-09-17 08:57:30 -07008#include "aos/testing/tmpdir.h"
Austin Schuh977a5ed2020-12-02 23:20:04 -08009
10namespace aos {
11namespace testing {
12
13// Tests that Verify works.
14TEST(FlatbufferTest, Verify) {
15 FlatbufferDetachedBuffer<Configuration> fb =
16 JsonToFlatbuffer<Configuration>("{}");
17 FlatbufferSpan<Configuration> fb_span(fb);
18 EXPECT_TRUE(fb.Verify());
19 EXPECT_TRUE(fb_span.Verify());
20
21 // Now confirm it works on an empty flatbuffer.
22 FlatbufferSpan<Configuration> empty(absl::Span<const uint8_t>(nullptr, 0));
23 EXPECT_FALSE(empty.Verify());
24}
25
davidjevans8b9b52f2021-09-17 08:57:30 -070026// Tests the ability to map a flatbuffer on disk to memory
27TEST(FlatbufferMMapTest, Verify) {
28 FlatbufferDetachedBuffer<Configuration> fb =
29 JsonToFlatbuffer<Configuration>("{\"foo_int\": 3}");
30
31 const std::string fb_path = absl::StrCat(TestTmpDir(), "/fb.bfbs");
32 WriteFlatbufferToFile(fb_path, fb);
33
34 FlatbufferMMap<Configuration> fb_mmap(fb_path);
35 EXPECT_TRUE(fb.Verify());
36 EXPECT_TRUE(fb_mmap.Verify());
37 ASSERT_EQ(fb_mmap.message().foo_int(), 3);
38
39 // Verify that copying works
40 {
41 FlatbufferMMap<Configuration> fb_mmap2(fb_path);
42 fb_mmap2 = fb_mmap;
43 EXPECT_TRUE(fb_mmap.Verify());
44 EXPECT_TRUE(fb_mmap2.Verify());
45 ASSERT_EQ(fb_mmap2.message().foo_int(), 3);
46 ASSERT_EQ(fb_mmap.message().foo_int(), 3);
47 }
48 EXPECT_TRUE(fb_mmap.Verify());
49 ASSERT_EQ(fb_mmap.message().foo_int(), 3);
50
51 // Verify that moving works
52 {
53 FlatbufferMMap<Configuration> fb_mmap3(fb_path);
54 fb_mmap3 = std::move(fb_mmap);
55 EXPECT_TRUE(fb_mmap3.Verify());
56 ASSERT_EQ(fb_mmap3.message().foo_int(), 3);
57 }
58}
Austin Schuhe4d1a682021-10-01 15:04:50 -070059
60// Tests the ability to modify a flatbuffer mmaped from on disk in memory
61TEST(FlatbufferMMapTest, Writeable) {
62 FlatbufferDetachedBuffer<Configuration> fb =
63 JsonToFlatbuffer<Configuration>("{\"foo_int\": 3}");
64
65 const std::string fb_path = absl::StrCat(TestTmpDir(), "/fb.bfbs");
66 WriteFlatbufferToFile(fb_path, fb);
67
68 {
69 FlatbufferMMap<Configuration> fb_mmap(fb_path,
70 util::FileOptions::kWriteable);
71 fb_mmap.mutable_message()->mutate_foo_int(5);
72 }
73
74 {
75 FlatbufferMMap<Configuration> fb_mmap(fb_path);
76 EXPECT_EQ(fb_mmap.message().foo_int(), 5);
77 }
78}
79
Austin Schuh977a5ed2020-12-02 23:20:04 -080080} // namespace testing
81} // namespace aos