1 // Copyright (c) Benjamin Kietzman (github.com/bkietz) 2 // 3 // Distributed under the Boost Software License, Version 1.0. (See accompanying 4 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 5 6 #include <gtest/gtest.h> 7 #include <dbus/connection.hpp> 8 #include <dbus/message.hpp> 9 #include <dbus/filter.hpp> 10 #include <dbus/match.hpp> 11 #include <dbus/functional.hpp> 12 #include <unistd.h> 13 14 15 class AvahiTest 16 : public testing::Test 17 { 18 protected: 19 static void SetUpTestCase() 20 { 21 } 22 static boost::asio::io_service io; 23 static dbus::connection system_bus; 24 static dbus::string browser_path; 25 }; 26 // It seems like these should be non-static, 27 // but I get a mysterious SEGFAULT for io 28 // ¿related: http://stackoverflow.com/questions/18009156/boost-asio-segfault-no-idea-why 29 // and a C++ exception with description 30 // "assign: File exists" for system_bus 31 // (probably indicates I should upgrade connection's constructor) 32 boost::asio::io_service AvahiTest::io; 33 dbus::connection AvahiTest::system_bus(io, dbus::bus::system); 34 dbus::string AvahiTest::browser_path; 35 36 37 TEST_F(AvahiTest, GetHostName) 38 { 39 using namespace boost::asio; 40 using namespace dbus; 41 using boost::system::error_code; 42 43 string avahi_hostname; 44 string unix_hostname; 45 46 { 47 // get hostname from a system call 48 char c[1024]; 49 gethostname(c, 1024); 50 unix_hostname = c; 51 } 52 53 // get hostname from the Avahi daemon 54 message m = message::new_call( 55 "org.freedesktop.Avahi", 56 "/", 57 "org.freedesktop.Avahi.Server", 58 "GetHostName"); 59 60 system_bus.async_send(m, [&](error_code ec, message r){ 61 r.unpack(avahi_hostname); 62 63 // this is only usually accurate 64 ASSERT_EQ(unix_hostname, avahi_hostname); 65 66 // eventually, connection should stop itself 67 io.stop(); 68 }); 69 70 io.run(); 71 } 72 73 74 TEST_F(AvahiTest, ServiceBrowser) 75 { 76 using namespace boost::asio; 77 using namespace dbus; 78 using boost::system::error_code; 79 80 // create new service browser 81 message m = message::new_call( 82 "org.freedesktop.Avahi", 83 "/", 84 "org.freedesktop.Avahi.Server", 85 "ServiceBrowserNew"); 86 87 m.pack<int32>(-1) 88 .pack<int32>(-1) 89 .pack<string>("_http._tcp") 90 .pack<string>("local") 91 .pack<uint32>(0); 92 93 message r = system_bus.send(m); 94 95 r.unpack(browser_path); 96 97 // RegEx match browser_path 98 // catch a possible exception 99 } 100 101 102 TEST_F(AvahiTest, BrowseForHttp) 103 { 104 using namespace boost::asio; 105 using namespace dbus; 106 using boost::system::error_code; 107 108 match m(system_bus, "type='signal',path='" + browser_path + "'"); 109 filter f(system_bus, [](message& m){ 110 return m.get_member() == "ItemNew"; }); 111 112 function<void(error_code, message)> h; 113 h = [&] (error_code ec, message m) {}; 114 f.async_dispatch(h); 115 io.run(); 116 } 117