Network-related operations of the TorrentManager class

This commit adds the downloadTorrentFile, download_file_manifest, download_data_packet methods

Change-Id: Ie221bc07907eb58117e83e317eca578174142d6d
Refs: #3505
diff --git a/tests/unit-tests/file-manifest.t.cpp b/tests/unit-tests/file-manifest.t.cpp
index 80a344e..72316f8 100644
--- a/tests/unit-tests/file-manifest.t.cpp
+++ b/tests/unit-tests/file-manifest.t.cpp
@@ -345,11 +345,11 @@
     // Negative tests
     //   non-existent file
     {128          , 128          , "tests/testdata/foo/fake.txt", "/NTORRENT/foo/", false, true },
-    //   // prefix mismatch
+    // prefix mismatch
     {128          , 128          , "tests/testdata/foo/bar.txt", "/NTORRENT/bar/",  false, true },
-    //  scaling test
+    // scaling test
     // {10240         , 5120 ,         "tests/testdata/foo/huge_file", "/NTORRENT/foo/", false, false },
-      // assertion failures (tests not supported on platforms)
+    // assertion failures (tests not supported on platforms)
     // {0            , 128          , "tests/testdata/foo/bar.txt", "/NTORRENT/bar/", true },
     // {128          , 0            , "tests/testdata/foo/bar.txt", "/NTORRENT/bar/", true },
   };
diff --git a/tests/unit-tests/torrent-manager.t.cpp b/tests/unit-tests/torrent-manager.t.cpp
index 722173b..bb16344 100644
--- a/tests/unit-tests/torrent-manager.t.cpp
+++ b/tests/unit-tests/torrent-manager.t.cpp
@@ -23,11 +23,13 @@
 
 #include "torrent-manager.hpp"
 #include "torrent-file.hpp"
+#include "unit-test-time-fixture.hpp"
 
 #include <set>
 
 #include <boost/filesystem.hpp>
 
+#include <ndn-cxx/util/dummy-client-face.hpp>
 #include <ndn-cxx/util/io.hpp>
 
 namespace ndn {
@@ -36,6 +38,7 @@
 
 using std::vector;
 using ndn::Name;
+using ndn::util::DummyClientFace;
 
 namespace fs = boost::filesystem;
 
@@ -44,7 +47,15 @@
   TestTorrentManager(const ndn::Name&   torrentFileName,
                      const std::string& filePath)
   : TorrentManager(torrentFileName, filePath)
-  {}
+  {
+  }
+
+  TestTorrentManager(const ndn::Name&   torrentFileName,
+                     const std::string& filePath,
+                     DummyClientFace& face)
+  : TorrentManager(torrentFileName, filePath, face)
+  {
+  }
 
   std::vector<TorrentFile> torrentSegments() const {
     return m_torrentSegments;
@@ -74,6 +85,28 @@
   }
 };
 
+class FaceFixture : public UnitTestTimeFixture
+{
+public:
+  explicit
+  FaceFixture(bool enableRegistrationReply = true)
+    : face(io, { true, enableRegistrationReply })
+  {
+  }
+
+public:
+  DummyClientFace face;
+};
+
+class FacesNoRegistrationReplyFixture : public FaceFixture
+{
+public:
+  FacesNoRegistrationReplyFixture()
+    : FaceFixture(false)
+  {
+  }
+};
+
 BOOST_AUTO_TEST_SUITE(TestTorrentManagerInitialize)
 
 BOOST_AUTO_TEST_CASE(CheckInitializeComplete)
@@ -233,6 +266,163 @@
   fs::remove_all(dirPath);
 }
 
+BOOST_FIXTURE_TEST_SUITE(TestTorrentManagerNetworkingStuff, FaceFixture)
+
+BOOST_AUTO_TEST_CASE(TestDownloadingTorrentFile)
+{
+  vector<FileManifest> manifests;
+  vector<TorrentFile> torrentSegments;
+  std::string filePath = ".appdata/foo/";
+  // get torrent files and manifests
+  {
+    auto temp = TorrentFile::generate("tests/testdata/foo", 1, 10, 10, false);
+
+    torrentSegments = temp.first;
+    auto temp1      = temp.second;
+    temp1.pop_back(); // remove the manifests for the last file
+    for (const auto& ms : temp1) {
+      for (const auto& m : ms.first) {
+        manifests.push_back(m);
+      }
+    }
+  }
+
+  TestTorrentManager manager("/NTORRENT/foo/torrent-file/sha256digest=946b92641d2b87bf4f5913930be20e3789ff5fb5d72739614f93f677d90fbd9d",
+                             filePath, face);
+  manager.Initialize();
+
+  // Test download torrent file segments
+  uint32_t counter = 0;
+  manager.downloadTorrentFile(filePath + "torrent_files", [&counter, &torrentSegments] (const ndn::Name& name) {
+                                          BOOST_CHECK_EQUAL(torrentSegments[counter].getName(), name);
+                                          counter++;
+                                        },
+                                        bind([] {
+                                          BOOST_FAIL("Unexpected failure");
+                                        }));
+
+  for (auto i = torrentSegments.begin(); i != torrentSegments.end(); i++) {
+    advanceClocks(time::milliseconds(1), 40);
+    face.receive(dynamic_cast<Data&>(*i));
+  }
+
+  fs::remove_all(filePath);
+}
+
+BOOST_AUTO_TEST_CASE(TestDownloadingFileManifests)
+{
+  vector<FileManifest> manifests;
+  vector<TorrentFile> torrentSegments;
+  std::string filePath = ".appdata/foo/";
+  // get torrent files and manifests
+  {
+    auto temp = TorrentFile::generate("tests/testdata/foo", 1, 10, 10, false);
+
+    torrentSegments = temp.first;
+    auto temp1      = temp.second;
+    temp1.pop_back(); // remove the manifests for the last file
+    for (const auto& ms : temp1) {
+      for (const auto& m : ms.first) {
+        manifests.push_back(m);
+      }
+    }
+  }
+
+  TestTorrentManager manager("/NTORRENT/foo/torrent-file/sha256digest=946b92641d2b87bf4f5913930be20e3789ff5fb5d72739614f93f677d90fbd9d",
+                             filePath, face);
+  manager.Initialize();
+
+  // Test download manifest segments -- 2 files (the first one segment, the second multiple)
+  int counter = 0;
+  manager.download_file_manifest(manifests[0].getFullName(), filePath + "manifests",
+                                [&counter, &manifests]
+                                (const std::vector<ndn::Name>& vec) {
+                                  uint32_t packetIndex = 0;
+                                  for (auto j = vec.begin(); j != vec.end(); j++) {
+                                    BOOST_CHECK_EQUAL(manifests[counter].catalog()[packetIndex],
+                                                      *j);
+                                    packetIndex++;
+                                  }
+                                  counter++;
+                                },
+                                [](const ndn::Name& name, const std::string& reason) {
+                                  BOOST_FAIL("Unexpected failure");
+                                });
+
+  advanceClocks(time::milliseconds(1), 40);
+  face.receive(dynamic_cast<Data&>(manifests[0]));
+
+  manager.download_file_manifest(manifests[1].getFullName(), filePath + "manifests",
+                                [&counter, &manifests]
+                                (const std::vector<ndn::Name>& vec) {
+                                  uint32_t packetIndex = 0;
+                                  for (auto j = vec.begin(); j != vec.end(); j++) {
+                                    BOOST_CHECK_EQUAL(manifests[counter].catalog()[packetIndex],
+                                                      *j);
+                                    // if we have read all the packet names from a
+                                    // segment, move to the next one
+                                    if (packetIndex == manifests[counter].catalog().size() - 1) {
+                                      packetIndex = 0;
+                                      counter++;
+                                    }
+                                    else {
+                                      packetIndex++;
+                                    }
+                                  }
+                                },
+                                [](const ndn::Name& name, const std::string& reason) {
+                                  BOOST_FAIL("Unexpected failure");
+                                });
+
+  for (auto i = manifests.begin() + 1; i != manifests.end(); i++) {
+    advanceClocks(time::milliseconds(1), 40);
+    face.receive(dynamic_cast<Data&>(*i));
+  }
+
+  fs::remove_all(filePath);
+}
+
+BOOST_AUTO_TEST_CASE(TestDownloadingDataPackets)
+{
+  std::string filePath = ".appdata/foo/";
+  TestTorrentManager manager("/NTORRENT/foo/torrent-file/sha256digest=946b92641d2b87bf4f5913930be20e3789ff5fb5d72739614f93f677d90fbd9d",
+                             filePath, face);
+  manager.Initialize();
+
+  Name dataName("/test/ucla");
+
+  // Download data successfully
+  manager.download_data_packet(dataName,
+                              [&dataName] (const ndn::Name& name) {
+                                BOOST_CHECK_EQUAL(name, dataName);
+                              },
+                              [](const ndn::Name& name, const std::string& reason) {
+                                BOOST_FAIL("Unexpected failure");
+                              });
+
+  auto data = make_shared<Data>(dataName);
+  SignatureSha256WithRsa fakeSignature;
+  fakeSignature.setValue(encoding::makeEmptyBlock(tlv::SignatureValue));
+  data->setSignature(fakeSignature);
+  data->wireEncode();
+
+  advanceClocks(time::milliseconds(1), 40);
+  face.receive(*data);
+
+  // Fail to download data
+  manager.download_data_packet(dataName,
+                              [] (const ndn::Name& name) {
+                                BOOST_FAIL("Unexpected failure");
+                              },
+                              [&dataName](const ndn::Name& name, const std::string& reason) {
+                                BOOST_CHECK_EQUAL(name, dataName);
+                              });
+
+  advanceClocks(time::milliseconds(1), 2100);
+
+  fs::remove_all(filePath);
+}
+
 BOOST_AUTO_TEST_SUITE_END()
 
 BOOST_AUTO_TEST_SUITE(CheckTorrentManagerUtilities)
@@ -472,9 +662,10 @@
   }
 }
 
+BOOST_AUTO_TEST_SUITE_END()
 
 BOOST_AUTO_TEST_SUITE_END()
 
 } // namespace tests
 } // namespace nTorrent
-} // namespace ndn
\ No newline at end of file
+} // namespace ndn
diff --git a/tests/unit-tests/unit-test-time-fixture.hpp b/tests/unit-tests/unit-test-time-fixture.hpp
new file mode 100644
index 0000000..d50f22f
--- /dev/null
+++ b/tests/unit-tests/unit-test-time-fixture.hpp
@@ -0,0 +1,71 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+* Copyright (c) 2016 Regents of the University of California.
+*
+* This file is part of the nTorrent codebase.
+*
+* nTorrent is free software: you can redistribute it and/or modify it under the
+* terms of the GNU Lesser General Public License as published by the Free Software
+* Foundation, either version 3 of the License, or (at your option) any later version.
+*
+* nTorrent is distributed in the hope that it will be useful, but WITHOUT ANY
+* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+*
+* You should have received copies of the GNU General Public License and GNU Lesser
+* General Public License along with nTorrent, e.g., in COPYING.md file. If not, see
+* <http://www.gnu.org/licenses/>.
+*
+* See AUTHORS for complete list of nTorrent authors and contributors.
+*/
+
+#ifndef NDN_TESTS_UNIT_TESTS_UNIT_TEST_TIME_FIXTURE_HPP
+#define NDN_TESTS_UNIT_TESTS_UNIT_TEST_TIME_FIXTURE_HPP
+
+#include <ndn-cxx/util/time-unit-test-clock.hpp>
+
+#include <boost/asio/io_service.hpp>
+
+namespace ndn {
+namespace ntorrent {
+namespace tests {
+
+class UnitTestTimeFixture
+{
+public:
+  UnitTestTimeFixture()
+    : steadyClock(make_shared<time::UnitTestSteadyClock>())
+    , systemClock(make_shared<time::UnitTestSystemClock>())
+  {
+    time::setCustomClocks(steadyClock, systemClock);
+  }
+
+  ~UnitTestTimeFixture()
+  {
+    time::setCustomClocks(nullptr, nullptr);
+  }
+
+  void
+  advanceClocks(const time::nanoseconds& tick, size_t nTicks = 1)
+  {
+    for (size_t i = 0; i < nTicks; ++i) {
+      steadyClock->advance(tick);
+      systemClock->advance(tick);
+
+      if (io.stopped())
+        io.reset();
+      io.poll();
+    }
+  }
+
+public:
+  shared_ptr<time::UnitTestSteadyClock> steadyClock;
+  shared_ptr<time::UnitTestSystemClock> systemClock;
+  boost::asio::io_service io;
+};
+
+} // namespace tests
+} // namespace ntorrent
+} // namespace ndn
+
+#endif // NDN_TESTS_UNIT_TESTS_UNIT_TEST_TIME_FIXTURE_HPP