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::connection system_bus; 25 static dbus::string browser_path; 26 static dbus::endpoint avahi_daemon; 27 }; 28 // It seems like these should be non-static, 29 // but I get a mysterious SEGFAULT for io 30 // ¿related: http://stackoverflow.com/questions/18009156/boost-asio-segfault-no-idea-why 31 // and a C++ exception with description 32 // "assign: File exists" for system_bus 33 // (probably indicates I should upgrade connection's constructor) 34 boost::asio::io_service AvahiTest::io; 35 dbus::connection AvahiTest::system_bus(io, dbus::bus::system); 36 dbus::string AvahiTest::browser_path; 37 dbus::endpoint AvahiTest::avahi_daemon( 38 "org.freedesktop.Avahi", 39 "/", 40 "org.freedesktop.Avahi.Server"); 41 42 43 TEST_F(AvahiTest, GetHostName) 44 { 45 using namespace boost::asio; 46 using namespace dbus; 47 using boost::system::error_code; 48 49 string avahi_hostname; 50 string unix_hostname; 51 52 { 53 // get hostname from a system call 54 char c[1024]; 55 gethostname(c, 1024); 56 unix_hostname = c; 57 } 58 59 // get hostname from the Avahi daemon 60 message m = message::new_call( 61 avahi_daemon, 62 "GetHostName"); 63 64 system_bus.async_send(m, [&](error_code ec, message r){ 65 r.unpack(avahi_hostname); 66 67 // this is only usually accurate 68 ASSERT_EQ(unix_hostname, avahi_hostname); 69 70 // eventually, connection should stop itself 71 io.stop(); 72 }); 73 74 io.run(); 75 } 76 77 78 TEST_F(AvahiTest, ServiceBrowser) 79 { 80 using namespace boost::asio; 81 using namespace dbus; 82 using boost::system::error_code; 83 84 // create new service browser 85 message m = message::new_call( 86 avahi_daemon, 87 "ServiceBrowserNew"); 88 89 m.pack<int32>(-1) 90 .pack<int32>(-1) 91 .pack<string>("_http._tcp") 92 .pack<string>("local") 93 .pack<uint32>(0); 94 95 message r = system_bus.send(m); 96 97 r.unpack(browser_path); 98 99 // RegEx match browser_path 100 // catch a possible exception 101 } 102 103 104 TEST_F(AvahiTest, BrowseForHttp) 105 { 106 using namespace boost::asio; 107 using namespace dbus; 108 using boost::system::error_code; 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