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/endpoint.hpp> 10 #include <dbus/filter.hpp> 11 #include <dbus/match.hpp> 12 #include <dbus/functional.hpp> 13 #include <unistd.h> 14 15 16 class AvahiTest 17 : public testing::Test 18 { 19 protected: 20 static void SetUpTestCase() 21 { 22 } 23 static boost::asio::io_service io; 24 static dbus::string browser_path; 25 static dbus::endpoint avahi_daemon; 26 }; 27 // It seems like these should be non-static, 28 // but I get a mysterious SEGFAULT for io 29 // ¿related: http://stackoverflow.com/questions/18009156/boost-asio-segfault-no-idea-why 30 boost::asio::io_service AvahiTest::io; 31 dbus::string AvahiTest::browser_path; 32 dbus::endpoint AvahiTest::avahi_daemon( 33 "org.freedesktop.Avahi", 34 "/", 35 "org.freedesktop.Avahi.Server"); 36 37 38 TEST_F(AvahiTest, GetHostName) 39 { 40 using namespace boost::asio; 41 using namespace dbus; 42 using boost::system::error_code; 43 44 connection system_bus(io, "unix:path=/var/run/dbus/system_bus_socket"); 45 string avahi_hostname; 46 string unix_hostname; 47 48 { 49 // get hostname from a system call 50 char c[1024]; 51 gethostname(c, 1024); 52 unix_hostname = c; 53 } 54 55 // get hostname from the Avahi daemon 56 message m = message::new_call( 57 avahi_daemon, 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 connection system_bus(io, bus::system); 81 82 // create new service browser 83 message m = message::new_call( 84 avahi_daemon, 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 connection system_bus(io, bus::system); 109 110 match m(system_bus, "type='signal',path='" + browser_path + "'"); 111 filter f(system_bus, [](message& m){ 112 return m.get_member() == "ItemNew"; }); 113 114 function<void(error_code, message)> h; 115 h = [&] (error_code ec, message m) {}; 116 f.async_dispatch(h); 117 io.run(); 118 } 119