| 1 | // |
| 2 | // NTPClientTest.cpp |
| 3 | // |
| 4 | // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. |
| 5 | // and Contributors. |
| 6 | // |
| 7 | // SPDX-License-Identifier: BSL-1.0 |
| 8 | // |
| 9 | |
| 10 | |
| 11 | #include "NTPClientTest.h" |
| 12 | #include "Poco/CppUnit/TestCaller.h" |
| 13 | #include "Poco/CppUnit/TestSuite.h" |
| 14 | #include "Poco/Net/NTPClient.h" |
| 15 | #include "Poco/Net/NTPEventArgs.h" |
| 16 | #include "Poco/Net/SocketAddress.h" |
| 17 | #include "Poco/Net/ICMPClient.h" |
| 18 | #include "Poco/Net/NetException.h" |
| 19 | #include "Poco/AutoPtr.h" |
| 20 | #include "Poco/Delegate.h" |
| 21 | #include "Poco/DateTimeFormatter.h" |
| 22 | #include "Poco/DateTimeFormat.h" |
| 23 | #include <sstream> |
| 24 | #include <iostream> |
| 25 | |
| 26 | |
| 27 | using Poco::Net::NTPClient; |
| 28 | using Poco::Net::NTPEventArgs; |
| 29 | using Poco::Net::SocketAddress; |
| 30 | using Poco::Net::IPAddress; |
| 31 | using Poco::Net::ICMPClient; |
| 32 | using Poco::Net::HostNotFoundException; |
| 33 | using Poco::Delegate; |
| 34 | using Poco::AutoPtr; |
| 35 | |
| 36 | |
| 37 | NTPClientTest::NTPClientTest(const std::string& name): |
| 38 | CppUnit::TestCase(name), |
| 39 | _ntpClient(IPAddress::IPv4) |
| 40 | { |
| 41 | } |
| 42 | |
| 43 | |
| 44 | NTPClientTest::~NTPClientTest() |
| 45 | { |
| 46 | } |
| 47 | |
| 48 | |
| 49 | void NTPClientTest::testTimeSync() |
| 50 | { |
| 51 | #if POCO_OS != POCO_OS_ANDROID |
| 52 | if (ICMPClient::pingIPv4("pool.ntp.org" ) <= 0) |
| 53 | { |
| 54 | std::cerr << "pool.ntp.org not accessibe, test skipped" << std::endl; |
| 55 | return; |
| 56 | } |
| 57 | #endif |
| 58 | |
| 59 | assertTrue (_ntpClient.request("pool.ntp.org" ) > 0); |
| 60 | } |
| 61 | |
| 62 | |
| 63 | void NTPClientTest::setUp() |
| 64 | { |
| 65 | _ntpClient.response += Delegate<NTPClientTest, NTPEventArgs>(this, &NTPClientTest::onResponse); |
| 66 | } |
| 67 | |
| 68 | |
| 69 | void NTPClientTest::tearDown() |
| 70 | { |
| 71 | _ntpClient.response -= Delegate<NTPClientTest, NTPEventArgs>(this, &NTPClientTest::onResponse); |
| 72 | } |
| 73 | |
| 74 | |
| 75 | void NTPClientTest::onResponse(const void* pSender, NTPEventArgs& args) |
| 76 | { |
| 77 | std::ostringstream os; |
| 78 | os << std::endl << "Received from " << args.hostName() << " [" << args.hostAddress() << "] with " |
| 79 | << Poco::DateTimeFormatter::format(args.packet().referenceTime(), Poco::DateTimeFormat::ISO8601_FORMAT) |
| 80 | << " reference typestamp" << std::endl; |
| 81 | std::cout << os.str() << std::endl; |
| 82 | } |
| 83 | |
| 84 | |
| 85 | CppUnit::Test* NTPClientTest::suite() |
| 86 | { |
| 87 | CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NTPClientTest" ); |
| 88 | |
| 89 | CppUnit_addTest(pSuite, NTPClientTest, testTimeSync); |
| 90 | |
| 91 | return pSuite; |
| 92 | } |
| 93 | |