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 <dbus/connection.hpp> 7 #include <dbus/endpoint.hpp> 8 #include <dbus/filter.hpp> 9 #include <dbus/match.hpp> 10 #include <dbus/message.hpp> 11 #include <functional> 12 13 #include <unistd.h> 14 #include <gtest/gtest.h> 15 16 TEST(AvahiTest, GetHostName) { 17 dbus::endpoint test_daemon("org.freedesktop.Avahi", "/", 18 "org.freedesktop.Avahi.Server"); 19 boost::asio::io_service io; 20 dbus::connection system_bus(io, dbus::bus::system); 21 22 dbus::message m = dbus::message::new_call(test_daemon, "GetHostName"); 23 24 system_bus.async_send( 25 m, [&](const boost::system::error_code ec, dbus::message r) { 26 27 std::string avahi_hostname; 28 std::string hostname; 29 30 // get hostname from a system call 31 char c[1024]; 32 gethostname(c, 1024); 33 hostname = c; 34 35 r.unpack(avahi_hostname); 36 37 // Get only the host name, not the fqdn 38 auto unix_hostname = hostname.substr(0, hostname.find(".")); 39 EXPECT_EQ(unix_hostname, avahi_hostname); 40 41 io.stop(); 42 }); 43 boost::asio::deadline_timer t(io, boost::posix_time::seconds(10)); 44 t.async_wait([&](const boost::system::error_code& /*e*/) { 45 io.stop(); 46 FAIL() << "Callback was never called\n"; 47 }); 48 io.run(); 49 } 50 51 TEST(AvahiTest, ServiceBrowser) { 52 boost::asio::io_service io; 53 dbus::connection system_bus(io, dbus::bus::system); 54 55 dbus::endpoint test_daemon("org.freedesktop.Avahi", "/", 56 "org.freedesktop.Avahi.Server"); 57 // create new service browser 58 dbus::message m1 = dbus::message::new_call(test_daemon, "ServiceBrowserNew"); 59 m1.pack<int32_t>(-1) 60 .pack<int32_t>(-1) 61 .pack<std::string>("_http._tcp") 62 .pack<std::string>("local") 63 .pack<uint32_t>(0); 64 65 dbus::message r = system_bus.send(m1); 66 std::string browser_path; 67 r.unpack(browser_path); 68 testing::Test::RecordProperty("browserPath", browser_path); 69 70 dbus::match ma(system_bus, "type='signal',path='" + browser_path + "'"); 71 dbus::filter f(system_bus, [](dbus::message& m) { 72 auto member = m.get_member(); 73 return member == "NameAcquired"; 74 }); 75 76 std::function<void(boost::system::error_code, dbus::message)> event_handler = 77 [&](boost::system::error_code ec, dbus::message s) { 78 testing::Test::RecordProperty("firstSignal", s.get_member()); 79 std::string a = s.get_member(); 80 std::string dude; 81 s.unpack(dude); 82 f.async_dispatch(event_handler); 83 io.stop(); 84 }; 85 f.async_dispatch(event_handler); 86 87 boost::asio::deadline_timer t(io, boost::posix_time::seconds(10)); 88 t.async_wait([&](const boost::system::error_code& /*e*/) { 89 io.stop(); 90 FAIL() << "Callback was never called\n"; 91 }); 92 io.run(); 93 } 94