blob: dac43b3725b39770746312cf128d255cd4ef3348 [file] [log] [blame]
Vishwanatha Subbannaca4ce1b2017-10-16 23:17:18 +05301#include "watch.hpp"
2#include "types.hpp"
3
4#include <gtest/gtest.h>
5
6#include <fstream>
7#include <experimental/filesystem>
8
9static constexpr auto TRIGGER_FILE = "/tmp/netif_state";
10
11namespace fs = std::experimental::filesystem;
12
13class WatchTest : public ::testing::Test
14{
15 public:
16 // systemd event handler
17 sd_event* events;
18
19 // Need this so that events can be initialized.
20 int rc;
21
22 // Gets called as part of each TEST_F construction
23 WatchTest()
24 : rc(sd_event_default(&events)),
25 eventPtr(events)
26 {
27 // Create a file containing DNS entries like in netif/state
28 std::ofstream file(TRIGGER_FILE);
29 file << "";
30
31 // Check for successful creation of
32 // event handler
33 EXPECT_GE(rc, 0);
34 }
35
36 // Gets called as part of each TEST_F destruction
37 ~WatchTest()
38 {
39 if (fs::exists(TRIGGER_FILE))
40 {
41 fs::remove(TRIGGER_FILE);
42 }
43 }
44
45 // unique_ptr for sd_event
46 phosphor::network::EventPtr eventPtr;
47
48 // Count of callback invocation
49 int count = 0;
50
51 // This is supposed to get hit twice
52 // Once at the beginning to see if there is anything
53 // and the second time when the data is fired.
54 void callBackHandler(const fs::path& file)
55 {
56 count++;
57
58 // Expect that the file is what we wanted
59 EXPECT_EQ(file, TRIGGER_FILE);
60 }
61};
62
63/** @brief Makes sure that the inotify event is fired
64 */
65TEST_F(WatchTest, validateEventNotification)
66{
67 // Create a watch object and register the handler
68 phosphor::network::inotify::Watch watch(eventPtr, TRIGGER_FILE,
69 std::bind(&WatchTest::callBackHandler, this,
70 std::placeholders::_1));
71
72 // Reading the event post subscription
73 callBackHandler(TRIGGER_FILE);
74
75 // Callback function must have hit by now
76 EXPECT_EQ(1, count);
77
78 // Make a run and see that no changes
79 sd_event_run(eventPtr.get(), 10);
80 EXPECT_EQ(1, count);
81
82 // Pump the data and get notification
83 {
84 std::ofstream file(TRIGGER_FILE);
85 file <<"DNS=1.2.3.4\n";
86 }
87
88 sd_event_run(eventPtr.get(), 10);
89 EXPECT_EQ(2, count);
90}