text:
using ::testing::Assign;
using ::testing::ContainerEq;
using ::testing::DoAll;
using ::testing::ElementsAre;
using ::testing::Mock;
using ::testing::NotNull;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::SaveArg;
using ::testing::StrictMock;
using ::testing::_;
using content::BrowserThread;
namespace safe_browsing {
namespace {
// A SafeBrowsingDatabaseManager implementation that returns a fixed result for
// a given URL.
class MockSafeBrowsingDatabaseManager : public SafeBrowsingDatabaseManager {
 public:
  explicit MockSafeBrowsingDatabaseManager(SafeBrowsingService* service)
      : SafeBrowsingDatabaseManager(service) { }

  MOCK_METHOD1(MatchDownloadWhitelistUrl, bool(const GURL&));
  MOCK_METHOD1(MatchDownloadWhitelistString, bool(const std::string&));
  MOCK_METHOD2(CheckDownloadUrl, bool(
      const std::vector<GURL>& url_chain,
      SafeBrowsingDatabaseManager::Client* client));

 private:
  virtual ~MockSafeBrowsingDatabaseManager() {}
  DISALLOW_COPY_AND_ASSIGN(MockSafeBrowsingDatabaseManager);
};

class FakeSafeBrowsingService : public SafeBrowsingService {
 public:
  FakeSafeBrowsingService() { }

  // Returned pointer has the same lifespan as the database_manager_ refcounted
  // object.
  MockSafeBrowsingDatabaseManager* mock_database_manager() {
    return mock_database_manager_;
  }

 protected:
  virtual ~FakeSafeBrowsingService() { }

  virtual SafeBrowsingDatabaseManager* CreateDatabaseManager() OVERRIDE {
    mock_database_manager_ = new MockSafeBrowsingDatabaseManager(this);
    return mock_database_manager_;
  }

 private:
  MockSafeBrowsingDatabaseManager* mock_database_manager_;

  DISALLOW_COPY_AND_ASSIGN(FakeSafeBrowsingService);
};

class MockSignatureUtil : public SignatureUtil {
 public:
  MockSignatureUtil() {}
  MOCK_METHOD2(CheckSignature, void (const base::FilePath&,
                                     ClientDownloadRequest_SignatureInfo*));

 protected:
  virtual ~MockSignatureUtil() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(MockSignatureUtil);
};
}  // namespace

ACTION_P(SetCertificateContents, contents) {
  arg1->add_certificate_chain()->add_element()->set_certificate(contents);
}

ACTION_P(TrustSignature, certificate_file) {
  arg1->set_trusted(true);
  // Add a certificate chain.  Note that we add the certificate twice so that
  // it appears as its own issuer.
  std::string cert_data;
  ASSERT_TRUE(file_util::ReadFileToString(certificate_file, &cert_data));
  ClientDownloadRequest_CertificateChain* chain =
      arg1->add_certificate_chain();
  chain->add_element()->set_certificate(cert_data);
  chain->add_element()->set_certificate(cert_data);
}

// We can't call OnSafeBrowsingResult directly because SafeBrowsingCheck does
// not have any copy constructor which means it can't be stored in a callback
// easily.  Note: check will be deleted automatically when the callback is
// deleted.
void OnSafeBrowsingResult(
    SafeBrowsingDatabaseManager::SafeBrowsingCheck* check) {
  check->client->OnSafeBrowsingResult(*check);
}

ACTION_P(CheckDownloadUrlDone, threat_type) {
  SafeBrowsingDatabaseManager::SafeBrowsingCheck* check =
      new SafeBrowsingDatabaseManager::SafeBrowsingCheck(
          arg0,
          std::vector<SBFullHash>(),
          arg1,
          safe_browsing_util::BINURL);
  for (size_t i = 0; i < check->url_results.size(); ++i)
    check->url_results[i] = threat_type;
  BrowserThread::PostTask(BrowserThread::IO,
                          FROM_HERE,
                          base::Bind(&OnSafeBrowsingResult,
                                     base::Owned(check)));
}

class DownloadProtectionServiceTest : public testing::Test {
 protected:
  virtual void SetUp() {
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kSbEnableDownloadFeedback);
    ui_thread_.reset(new content::TestBrowserThread(BrowserThread::UI,
                                                    &msg_loop_));
    // Start real threads for the IO and File threads so that the DCHECKs
    // to test that we're on the correct thread work.
    io_thread_.reset(new content::TestBrowserThread(BrowserThread::IO));
    ASSERT_TRUE(io_thread_->Start());
    sb_service_ = new StrictMock<FakeSafeBrowsingService>();
    sb_service_->Initialize();
    signature_util_ = new StrictMock<MockSignatureUtil>();
    download_service_ = sb_service_->download_protection_service();
    download_service_->signature_util_ = signature_util_;
    download_service_->SetEnabled(true);
    msg_loop_.RunUntilIdle();
    has_result_ = false;

    base::FilePath source_path;
    ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &source_path));
    testdata_path_ = source_path
        .AppendASCII("chrome")
        .AppendASCII("test")
        .AppendASCII("data")
        .AppendASCII("safe_browsing")
        .AppendASCII("download_protection");
  }

  virtual void TearDown() {
    sb_service_->ShutDown();
    // Flush all of the thread message loops to ensure that there are no
    // tasks currently running.
    FlushThreadMessageLoops();
    sb_service_ = NULL;
    io_thread_.reset();
    ui_thread_.reset();
  }

  bool RequestContainsResource(const ClientDownloadRequest& request,
                               ClientDownloadRequest::ResourceType type,
                               const std::string& url,
                               const std::string& referrer) {
    for (int i = 0; i < request.resources_size(); ++i) {
      if (request.resources(i).url() == url &&
          request.resources(i).type() == type &&
          (referrer.empty() || request.resources(i).referrer() == referrer)) {
        return true;
      }
    }
    return false;
  }

  // At this point we only set the server IP for the download itself.
  bool RequestContainsServerIp(const ClientDownloadRequest& request,
                               const std::string& remote_address) {
    for (int i = 0; i < request.resources_size(); ++i) {
      // We want the last DOWNLOAD_URL in the chain.
      if (request.resources(i).type() == ClientDownloadRequest::DOWNLOAD_URL &&
          (i + 1 == request.resources_size() ||
           request.resources(i + 1).type() !=
           ClientDownloadRequest::DOWNLOAD_URL)) {
        return remote_address == request.resources(i).remote_ip();
      }
    }
    return false;
  }

  // Flushes any pending tasks in the message loops of all threads.
  void FlushThreadMessageLoops() {
    BrowserThread::GetBlockingPool()->FlushForTesting();
    FlushMessageLoop(BrowserThread::IO);
    msg_loop_.RunUntilIdle();
  }

  // Proxy for private method.
  static void GetCertificateWhitelistStrings(
      const net::X509Certificate& certificate,
      const net::X509Certificate& issuer,
      std::vector<std::string>* whitelist_strings) {
    DownloadProtectionService::GetCertificateWhitelistStrings(
        certificate, issuer, whitelist_strings);
  }

  // Reads a single PEM-encoded certificate from the testdata directory.
  // Returns NULL on failure.
  scoped_refptr<net::X509Certificate> ReadTestCertificate(
      const std::string& filename) {
    std::string cert_data;
    if (!file_util::ReadFileToString(testdata_path_.AppendASCII(filename),
                                     &cert_data)) {
      return NULL;
    }
    net::CertificateList certs =
        net::X509Certificate::CreateCertificateListFromBytes(
            cert_data.data(),
            cert_data.size(),
            net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
    return certs.empty() ? NULL : certs[0];
  }

 private:
  // Helper functions for FlushThreadMessageLoops.
  void RunAllPendingAndQuitUI() {
    base::MessageLoop::current()->RunUntilIdle();
    BrowserThread::PostTask(
        BrowserThread::UI,
        FROM_HERE,
        base::Bind(&DownloadProtectionServiceTest::QuitMessageLoop,
                   base::Unretained(this)));
  }

  void QuitMessageLoop() {
    base::MessageLoop::current()->Quit();
  }

  void PostRunMessageLoopTask(BrowserThread::ID thread) {
    BrowserThread::PostTask(
        thread,
        FROM_HERE,
        base::Bind(&DownloadProtectionServiceTest::RunAllPendingAndQuitUI,
                   base::Unretained(this)));
  }

  void FlushMessageLoop(BrowserThread::ID thread) {
    BrowserThread::PostTask(
        BrowserThread::UI,
        FROM_HERE,
        base::Bind(&DownloadProtectionServiceTest::PostRunMessageLoopTask,
                   base::Unretained(this), thread));
    msg_loop_.Run();
  }

 public:
  void CheckDoneCallback(
      DownloadProtectionService::DownloadCheckResult result) {
    result_ = result;
    has_result_ = true;
    msg_loop_.Quit();
  }

  void SyncCheckDoneCallback(
      DownloadProtectionService::DownloadCheckResult result) {
    result_ = result;
    has_result_ = true;
  }

  void SendURLFetchComplete(net::TestURLFetcher* fetcher) {
    fetcher->delegate()->OnURLFetchComplete(fetcher);
  }

  testing::AssertionResult IsResult(
      DownloadProtectionService::DownloadCheckResult expected) {
    if (!has_result_)
      return testing::AssertionFailure() << "No result";
    has_result_ = false;
    return result_ == expected ?
        testing::AssertionSuccess() :
        testing::AssertionFailure() << "Expected " << expected <<
                                       ", got " << result_;
  }

 protected:
  scoped_refptr<FakeSafeBrowsingService> sb_service_;
  scoped_refptr<MockSignatureUtil> signature_util_;
  DownloadProtectionService* download_service_;
  base::MessageLoop msg_loop_;
  DownloadProtectionService::DownloadCheckResult result_;
  bool has_result_;
  scoped_ptr<content::TestBrowserThread> io_thread_;
  scoped_ptr<content::TestBrowserThread> ui_thread_;
  base::FilePath testdata_path_;
};

TEST_F(DownloadProtectionServiceTest, CheckClientDownloadInvalidUrl) {
  base::FilePath a_tmp(FILE_PATH_LITERAL("a.tmp"));
  base::FilePath a_exe(FILE_PATH_LITERAL("a.exe"));
  std::vector<GURL> url_chain;
  GURL referrer("http://www.google.com/");

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_));
  EXPECT_CALL(item, RemoveObserver(_));
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(a_tmp));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(a_exe));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
  Mock::VerifyAndClearExpectations(&item);

  url_chain.push_back(GURL("file://www.google.com/"));
  EXPECT_CALL(item, AddObserver(_));
  EXPECT_CALL(item, RemoveObserver(_));
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(a_tmp));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(a_exe));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
}

TEST_F(DownloadProtectionServiceTest, CheckClientDownloadWhitelistedUrl) {
  base::FilePath a_tmp(FILE_PATH_LITERAL("a.tmp"));
  base::FilePath a_exe(FILE_PATH_LITERAL("a.exe"));
  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.evil.com/bla.exe"));
  url_chain.push_back(GURL("http://www.google.com/a.exe"));
  GURL referrer("http://www.google.com/");

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_)).Times(2);
  EXPECT_CALL(item, RemoveObserver(_)).Times(2);
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(a_tmp));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(a_exe));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(_))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(GURL("http://www.google.com/a.exe")))
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*signature_util_.get(), CheckSignature(a_tmp, _)).Times(2);

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));

  // Check that the referrer is matched against the whitelist.
  url_chain.pop_back();
  referrer = GURL("http://www.google.com/a.exe");
  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
}

TEST_F(DownloadProtectionServiceTest, CheckClientDownloadFetchFailed) {
  net::FakeURLFetcherFactory factory(NULL);
  // HTTP request will fail.
  factory.SetFakeResponse(
      DownloadProtectionService::GetDownloadRequestUrl(), std::string(), false);

  base::FilePath a_tmp(FILE_PATH_LITERAL("a.tmp"));
  base::FilePath a_exe(FILE_PATH_LITERAL("a.exe"));
  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.evil.com/a.exe"));
  GURL referrer("http://www.google.com/");
  std::string hash = "hash";

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_));
  EXPECT_CALL(item, RemoveObserver(_));
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(a_tmp));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(a_exe));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));
  EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(100));
  EXPECT_CALL(item, HasUserGesture()).WillRepeatedly(Return(true));
  EXPECT_CALL(item, GetRemoteAddress()).WillRepeatedly(Return(""));

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(_))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*signature_util_.get(), CheckSignature(a_tmp, _));

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
}

TEST_F(DownloadProtectionServiceTest, CheckClientDownloadSuccess) {
  ClientDownloadResponse response;
  response.set_verdict(ClientDownloadResponse::SAFE);
  net::FakeURLFetcherFactory factory(NULL);
  // Empty response means SAFE.
  factory.SetFakeResponse(
      DownloadProtectionService::GetDownloadRequestUrl(),
      response.SerializeAsString(),
      true);

  base::FilePath a_tmp(FILE_PATH_LITERAL("a.tmp"));
  base::FilePath a_exe(FILE_PATH_LITERAL("a.exe"));
  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.evil.com/a.exe"));
  GURL referrer("http://www.google.com/");
  std::string hash = "hash";

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_)).Times(5);
  EXPECT_CALL(item, RemoveObserver(_)).Times(5);
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(a_tmp));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(a_exe));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));
  EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(100));
  EXPECT_CALL(item, HasUserGesture()).WillRepeatedly(Return(true));
  EXPECT_CALL(item, GetRemoteAddress()).WillRepeatedly(Return(""));

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(_))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*signature_util_.get(), CheckSignature(a_tmp, _)).Times(5);

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));

  // Invalid response should be safe too.
  response.Clear();
  factory.SetFakeResponse(
      DownloadProtectionService::GetDownloadRequestUrl(),
      response.SerializePartialAsString(),
      true);

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
  std::string feedback_ping;
  std::string feedback_response;
  EXPECT_FALSE(DownloadFeedbackService::GetPingsForDownloadForTesting(
      item, &feedback_ping, &feedback_response));

  // If the response is dangerous the result should also be marked as dangerous.
  response.set_verdict(ClientDownloadResponse::DANGEROUS);
  factory.SetFakeResponse(
      DownloadProtectionService::GetDownloadRequestUrl(),
      response.SerializeAsString(),
      true);

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_FALSE(DownloadFeedbackService::GetPingsForDownloadForTesting(
      item, &feedback_ping, &feedback_response));
#if defined(OS_WIN)
  EXPECT_TRUE(IsResult(DownloadProtectionService::DANGEROUS));
#else
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
#endif

  // If the response is uncommon the result should also be marked as uncommon.
  response.set_verdict(ClientDownloadResponse::UNCOMMON);
  factory.SetFakeResponse(
      DownloadProtectionService::GetDownloadRequestUrl(),
      response.SerializeAsString(),
      true);

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
#if defined(OS_WIN)
  EXPECT_TRUE(IsResult(DownloadProtectionService::UNCOMMON));
  EXPECT_TRUE(DownloadFeedbackService::GetPingsForDownloadForTesting(
      item, &feedback_ping, &feedback_response));
  ClientDownloadRequest decoded_request;
  EXPECT_TRUE(decoded_request.ParseFromString(feedback_ping));
  EXPECT_EQ(url_chain.back().spec(), decoded_request.url());
  EXPECT_EQ(response.SerializeAsString(), feedback_response);
#else
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
#endif

  // If the response is dangerous_host the result should also be marked as
  // dangerous_host.
  response.set_verdict(ClientDownloadResponse::DANGEROUS_HOST);
  factory.SetFakeResponse(
      DownloadProtectionService::GetDownloadRequestUrl(),
      response.SerializeAsString(),
      true);

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
#if defined(OS_WIN)
  EXPECT_TRUE(IsResult(DownloadProtectionService::DANGEROUS_HOST));
  EXPECT_TRUE(DownloadFeedbackService::GetPingsForDownloadForTesting(
      item, &feedback_ping, &feedback_response));
  EXPECT_EQ(response.SerializeAsString(), feedback_response);
#else
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
#endif
}

TEST_F(DownloadProtectionServiceTest, CheckClientDownloadHTTPS) {
  ClientDownloadResponse response;
  response.set_verdict(ClientDownloadResponse::DANGEROUS);
  net::FakeURLFetcherFactory factory(NULL);
  factory.SetFakeResponse(
      DownloadProtectionService::GetDownloadRequestUrl(),
      response.SerializeAsString(),
      true);

  base::FilePath a_tmp(FILE_PATH_LITERAL("a.tmp"));
  base::FilePath a_exe(FILE_PATH_LITERAL("a.exe"));
  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.evil.com/a.exe"));
  GURL referrer("http://www.google.com/");
  std::string hash = "hash";

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_)).Times(1);
  EXPECT_CALL(item, RemoveObserver(_)).Times(1);
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(a_tmp));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(a_exe));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));
  EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(100));
  EXPECT_CALL(item, HasUserGesture()).WillRepeatedly(Return(true));
  EXPECT_CALL(item, GetRemoteAddress()).WillRepeatedly(Return(""));

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(_))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*signature_util_.get(), CheckSignature(a_tmp, _)).Times(1);

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
#if defined(OS_WIN)
  EXPECT_TRUE(IsResult(DownloadProtectionService::DANGEROUS));
#else
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
#endif
}

TEST_F(DownloadProtectionServiceTest, CheckClientDownloadZip) {
  ClientDownloadResponse response;
  response.set_verdict(ClientDownloadResponse::SAFE);
  net::FakeURLFetcherFactory factory(NULL);
  // Empty response means SAFE.
  factory.SetFakeResponse(
      DownloadProtectionService::GetDownloadRequestUrl(),
      response.SerializeAsString(),
      true);

  base::ScopedTempDir download_dir;
  ASSERT_TRUE(download_dir.CreateUniqueTempDir());

  base::FilePath a_tmp(download_dir.path().Append(FILE_PATH_LITERAL("a.tmp")));
  base::FilePath a_zip(FILE_PATH_LITERAL("a.zip"));
  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.evil.com/a.zip"));
  GURL referrer("http://www.google.com/");
  std::string hash = "hash";

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_)).Times(3);
  EXPECT_CALL(item, RemoveObserver(_)).Times(3);
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(a_tmp));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(a_zip));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));
  EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(100));
  EXPECT_CALL(item, HasUserGesture()).WillRepeatedly(Return(true));
  EXPECT_CALL(item, GetRemoteAddress()).WillRepeatedly(Return(""));

  // Write out a zip archive to the temporary file.  In this case, it
  // only contains a text file.
  base::ScopedTempDir zip_source_dir;
  ASSERT_TRUE(zip_source_dir.CreateUniqueTempDir());
  std::string file_contents = "dummy file";
  ASSERT_EQ(static_cast<int>(file_contents.size()), file_util::WriteFile(
      zip_source_dir.path().Append(FILE_PATH_LITERAL("file.txt")),
      file_contents.data(), file_contents.size()));
  ASSERT_TRUE(zip::Zip(zip_source_dir.path(), a_tmp, false));

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
  Mock::VerifyAndClearExpectations(sb_service_.get());
  Mock::VerifyAndClearExpectations(signature_util_.get());

  // Now check with an executable in the zip file as well.
  ASSERT_EQ(static_cast<int>(file_contents.size()), file_util::WriteFile(
      zip_source_dir.path().Append(FILE_PATH_LITERAL("file.exe")),
      file_contents.data(), file_contents.size()));
  ASSERT_TRUE(zip::Zip(zip_source_dir.path(), a_tmp, false));

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(_))
      .WillRepeatedly(Return(false));

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
  Mock::VerifyAndClearExpectations(signature_util_.get());

  // If the response is dangerous the result should also be marked as
  // dangerous.
  response.set_verdict(ClientDownloadResponse::DANGEROUS);
  factory.SetFakeResponse(
      DownloadProtectionService::GetDownloadRequestUrl(),
      response.SerializeAsString(),
      true);

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
#if defined(OS_WIN)
  EXPECT_TRUE(IsResult(DownloadProtectionService::DANGEROUS));
#else
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
#endif
  Mock::VerifyAndClearExpectations(signature_util_.get());
}

TEST_F(DownloadProtectionServiceTest, CheckClientDownloadCorruptZip) {
  base::ScopedTempDir download_dir;
  ASSERT_TRUE(download_dir.CreateUniqueTempDir());

  base::FilePath a_tmp(download_dir.path().Append(FILE_PATH_LITERAL("a.tmp")));
  base::FilePath a_zip(FILE_PATH_LITERAL("a.zip"));
  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.evil.com/a.zip"));
  GURL referrer("http://www.google.com/");
  std::string hash = "hash";

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_)).Times(1);
  EXPECT_CALL(item, RemoveObserver(_)).Times(1);
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(a_tmp));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(a_zip));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));
  EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(100));
  EXPECT_CALL(item, HasUserGesture()).WillRepeatedly(Return(true));
  EXPECT_CALL(item, GetRemoteAddress()).WillRepeatedly(Return(""));

  std::string file_contents = "corrupt zip file";
  ASSERT_EQ(static_cast<int>(file_contents.size()), file_util::WriteFile(
      a_tmp, file_contents.data(), file_contents.size()));

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
  Mock::VerifyAndClearExpectations(sb_service_.get());
  Mock::VerifyAndClearExpectations(signature_util_.get());
}

TEST_F(DownloadProtectionServiceTest, CheckClientCrxDownloadSuccess) {
  ClientDownloadResponse response;
  // Even if the server verdict is dangerous we should return SAFE because
  // DownloadProtectionService::IsSupportedDownload() will return false
  // for crx downloads.
  response.set_verdict(ClientDownloadResponse::DANGEROUS);
  net::FakeURLFetcherFactory factory(NULL);
  // Empty response means SAFE.
  factory.SetFakeResponse(
      DownloadProtectionService::GetDownloadRequestUrl(),
      response.SerializeAsString(),
      true);

  base::FilePath a_tmp(FILE_PATH_LITERAL("a.tmp"));
  base::FilePath a_crx(FILE_PATH_LITERAL("a.crx"));
  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.evil.com/a.crx"));
  GURL referrer("http://www.google.com/");
  std::string hash = "hash";

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_)).Times(1);
  EXPECT_CALL(item, RemoveObserver(_)).Times(1);
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(a_tmp));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(a_crx));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));
  EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(100));
  EXPECT_CALL(item, HasUserGesture()).WillRepeatedly(Return(true));
  EXPECT_CALL(item, GetRemoteAddress()).WillRepeatedly(Return(""));

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(_))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*signature_util_.get(), CheckSignature(a_tmp, _)).Times(1);

  EXPECT_FALSE(download_service_->IsSupportedDownload(item, a_crx));
  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
}

TEST_F(DownloadProtectionServiceTest, CheckClientDownloadValidateRequest) {
  net::TestURLFetcherFactory factory;

  base::FilePath tmp_path(FILE_PATH_LITERAL("bla.tmp"));
  base::FilePath final_path(FILE_PATH_LITERAL("bla.exe"));
  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.google.com/"));
  url_chain.push_back(GURL("http://www.google.com/bla.exe"));
  GURL referrer("http://www.google.com/");
  std::string hash = "hash";
  std::string remote_address = "10.11.12.13";

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_)).Times(1);
  EXPECT_CALL(item, RemoveObserver(_)).Times(1);
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(tmp_path));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(final_path));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));
  EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(100));
  EXPECT_CALL(item, HasUserGesture()).WillRepeatedly(Return(true));
  EXPECT_CALL(item, GetRemoteAddress()).WillRepeatedly(Return(remote_address));

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(_))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*signature_util_.get(), CheckSignature(tmp_path, _))
      .WillOnce(SetCertificateContents("dummy cert data"));
  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));

#if !defined(OS_WIN)
  // SendRequest is not called.  Wait for FinishRequest to call our callback.
  msg_loop_.Run();
  net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
  EXPECT_EQ(NULL, fetcher);
#else
  // Run the message loop(s) until SendRequest is called.
  FlushThreadMessageLoops();
  net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
  ASSERT_TRUE(fetcher);
  ClientDownloadRequest request;
  EXPECT_TRUE(request.ParseFromString(fetcher->upload_data()));
  EXPECT_EQ("http://www.google.com/bla.exe", request.url());
  EXPECT_EQ(hash, request.digests().sha256());
  EXPECT_EQ(item.GetReceivedBytes(), request.length());
  EXPECT_EQ(item.HasUserGesture(), request.user_initiated());
  EXPECT_TRUE(RequestContainsServerIp(request, remote_address));
  EXPECT_EQ(2, request.resources_size());
  EXPECT_TRUE(RequestContainsResource(request,
                                      ClientDownloadRequest::DOWNLOAD_REDIRECT,
                                      "http://www.google.com/", ""));
  EXPECT_TRUE(RequestContainsResource(request,
                                      ClientDownloadRequest::DOWNLOAD_URL,
                                      "http://www.google.com/bla.exe",
                                      referrer.spec()));
  EXPECT_TRUE(request.has_signature());
  ASSERT_EQ(1, request.signature().certificate_chain_size());
  const ClientDownloadRequest_CertificateChain& chain =
      request.signature().certificate_chain(0);
  ASSERT_EQ(1, chain.element_size());
  EXPECT_EQ("dummy cert data", chain.element(0).certificate());

  // Simulate the request finishing.
  base::MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&DownloadProtectionServiceTest::SendURLFetchComplete,
                 base::Unretained(this), fetcher));
  msg_loop_.Run();
#endif
}

// Similar to above, but with an unsigned binary.
TEST_F(DownloadProtectionServiceTest,
       CheckClientDownloadValidateRequestNoSignature) {
  net::TestURLFetcherFactory factory;

  base::FilePath tmp_path(FILE_PATH_LITERAL("bla.tmp"));
  base::FilePath final_path(FILE_PATH_LITERAL("bla.exe"));
  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.google.com/"));
  url_chain.push_back(GURL("ftp://www.google.com/bla.exe"));
  GURL referrer("http://www.google.com/");
  std::string hash = "hash";
  std::string remote_address = "10.11.12.13";

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_)).Times(1);
  EXPECT_CALL(item, RemoveObserver(_)).Times(1);
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(tmp_path));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(final_path));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));
  EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(100));
  EXPECT_CALL(item, HasUserGesture()).WillRepeatedly(Return(true));
  EXPECT_CALL(item, GetRemoteAddress()).WillRepeatedly(Return(remote_address));

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(_))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*signature_util_.get(), CheckSignature(tmp_path, _));
  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));

#if !defined(OS_WIN)
  // SendRequest is not called.  Wait for FinishRequest to call our callback.
  msg_loop_.Run();
  net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
  EXPECT_EQ(NULL, fetcher);
#else
  // Run the message loop(s) until SendRequest is called.
  FlushThreadMessageLoops();
  net::TestURLFetcher* fetcher = factory.GetFetcherByID(0);
  ASSERT_TRUE(fetcher);
  ClientDownloadRequest request;
  EXPECT_TRUE(request.ParseFromString(fetcher->upload_data()));
  EXPECT_EQ("ftp://www.google.com/bla.exe", request.url());
  EXPECT_EQ(hash, request.digests().sha256());
  EXPECT_EQ(item.GetReceivedBytes(), request.length());
  EXPECT_EQ(item.HasUserGesture(), request.user_initiated());
  EXPECT_EQ(2, request.resources_size());
  EXPECT_TRUE(RequestContainsResource(request,
                                      ClientDownloadRequest::DOWNLOAD_REDIRECT,
                                      "http://www.google.com/", ""));
  EXPECT_TRUE(RequestContainsResource(request,
                                      ClientDownloadRequest::DOWNLOAD_URL,
                                      "ftp://www.google.com/bla.exe",
                                      referrer.spec()));
  EXPECT_TRUE(request.has_signature());
  EXPECT_EQ(0, request.signature().certificate_chain_size());

  // Simulate the request finishing.
  base::MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&DownloadProtectionServiceTest::SendURLFetchComplete,
                 base::Unretained(this), fetcher));
  msg_loop_.Run();
#endif
}

TEST_F(DownloadProtectionServiceTest, TestCheckDownloadUrl) {
  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.google.com/"));
  url_chain.push_back(GURL("http://www.google.com/bla.exe"));
  GURL referrer("http://www.google.com/");
  std::string hash = "hash";

  content::MockDownloadItem item;
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));

  // CheckDownloadURL returns immediately which means the client object callback
  // will never be called.  Nevertheless the callback provided to
  // CheckClientDownload must still be called.
  EXPECT_CALL(*sb_service_->mock_database_manager(),
              CheckDownloadUrl(ContainerEq(url_chain), NotNull()))
      .WillOnce(Return(true));
  download_service_->CheckDownloadUrl(
      item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
  Mock::VerifyAndClearExpectations(sb_service_.get());

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              CheckDownloadUrl(ContainerEq(url_chain), NotNull()))
      .WillOnce(DoAll(CheckDownloadUrlDone(SB_THREAT_TYPE_SAFE),
                      Return(false)));
  download_service_->CheckDownloadUrl(
      item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
  Mock::VerifyAndClearExpectations(sb_service_.get());

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              CheckDownloadUrl(ContainerEq(url_chain), NotNull()))
      .WillOnce(DoAll(
          CheckDownloadUrlDone(SB_THREAT_TYPE_URL_MALWARE),
          Return(false)));
  download_service_->CheckDownloadUrl(
      item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
  Mock::VerifyAndClearExpectations(sb_service_.get());

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              CheckDownloadUrl(ContainerEq(url_chain),
                               NotNull()))
      .WillOnce(DoAll(
          CheckDownloadUrlDone(SB_THREAT_TYPE_BINARY_MALWARE_URL),
          Return(false)));
  download_service_->CheckDownloadUrl(
      item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::DANGEROUS));
}

TEST_F(DownloadProtectionServiceTest, TestDownloadRequestTimeout) {
  net::TestURLFetcherFactory factory;

  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.evil.com/bla.exe"));
  GURL referrer("http://www.google.com/");
  base::FilePath tmp_path(FILE_PATH_LITERAL("a.tmp"));
  base::FilePath final_path(FILE_PATH_LITERAL("a.exe"));
  std::string hash = "hash";

  content::MockDownloadItem item;
  EXPECT_CALL(item, AddObserver(_)).Times(1);
  EXPECT_CALL(item, RemoveObserver(_)).Times(1);
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(tmp_path));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(final_path));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));
  EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(100));
  EXPECT_CALL(item, HasUserGesture()).WillRepeatedly(Return(true));
  EXPECT_CALL(item, GetRemoteAddress()).WillRepeatedly(Return(""));

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(_))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*signature_util_.get(), CheckSignature(tmp_path, _));

  download_service_->download_request_timeout_ms_ = 10;
  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::CheckDoneCallback,
                 base::Unretained(this)));

  // The request should time out because the HTTP request hasn't returned
  // anything yet.
  msg_loop_.Run();
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
}

TEST_F(DownloadProtectionServiceTest, TestDownloadItemDestroyed) {
  net::TestURLFetcherFactory factory;

  std::vector<GURL> url_chain;
  url_chain.push_back(GURL("http://www.evil.com/bla.exe"));
  GURL referrer("http://www.google.com/");
  base::FilePath tmp_path(FILE_PATH_LITERAL("a.tmp"));
  base::FilePath final_path(FILE_PATH_LITERAL("a.exe"));
  std::string hash = "hash";

  content::MockDownloadItem item;
  content::DownloadItem::Observer* observer = NULL;
  EXPECT_CALL(item, AddObserver(_)).WillOnce(SaveArg<0>(&observer));
  EXPECT_CALL(item, RemoveObserver(_)).WillOnce(Assign(
      &observer, static_cast<content::DownloadItem::Observer*>(NULL)));
  EXPECT_CALL(item, GetFullPath()).WillRepeatedly(ReturnRef(tmp_path));
  EXPECT_CALL(item, GetTargetFilePath()).WillRepeatedly(ReturnRef(final_path));
  EXPECT_CALL(item, GetUrlChain()).WillRepeatedly(ReturnRef(url_chain));
  EXPECT_CALL(item, GetReferrerUrl()).WillRepeatedly(ReturnRef(referrer));
  EXPECT_CALL(item, GetHash()).WillRepeatedly(ReturnRef(hash));
  EXPECT_CALL(item, GetReceivedBytes()).WillRepeatedly(Return(100));
  EXPECT_CALL(item, HasUserGesture()).WillRepeatedly(Return(true));
  EXPECT_CALL(item, GetRemoteAddress()).WillRepeatedly(Return(""));

  EXPECT_CALL(*sb_service_->mock_database_manager(),
              MatchDownloadWhitelistUrl(_))
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*signature_util_.get(), CheckSignature(tmp_path, _));

  download_service_->CheckClientDownload(
      &item,
      base::Bind(&DownloadProtectionServiceTest::SyncCheckDoneCallback,
                 base::Unretained(this)));

  ASSERT_TRUE(observer != NULL);
  observer->OnDownloadDestroyed(&item);

  EXPECT_TRUE(observer == NULL);
  EXPECT_TRUE(IsResult(DownloadProtectionService::SAFE));
}

TEST_F(DownloadProtectionServiceTest, GetCertificateWhitelistStrings) {
  // We'll pass this cert in as the "issuer", even though it isn't really
  // used to sign the certs below.  GetCertificateWhitelistStirngs doesn't care
  // about this.
  scoped_refptr<net::X509Certificate> issuer_cert(
      ReadTestCertificate("issuer.pem"));
  ASSERT_TRUE(issuer_cert.get());
  std::string cert_base = "cert/" + base::HexEncode(
      issuer_cert->fingerprint().data,
      sizeof(issuer_cert->fingerprint().data));

  scoped_refptr<net::X509Certificate> cert(ReadTestCertificate("test_cn.pem"));
  ASSERT_TRUE(cert.get());
  std::vector<std::string> whitelist_strings;
  GetCertificateWhitelistStrings(
      *cert.get(), *issuer_cert.get(), &whitelist_strings);
  // This also tests escaping of characters in the certificate attributes.
  EXPECT_THAT(whitelist_strings, ElementsAre(
      cert_base + "/CN=subject%2F%251"));

  cert = ReadTestCertificate("test_cn_o.pem");
  ASSERT_TRUE(cert.get());
  whitelist_strings.clear();
  GetCertificateWhitelistStrings(
      *cert.get(), *issuer_cert.get(), &whitelist_strings);
  EXPECT_THAT(whitelist_strings,
              ElementsAre(cert_base + "/CN=subject",
                          cert_base + "/CN=subject/O=org",
                          cert_base + "/O=org"));

  cert = ReadTestCertificate("test_cn_o_ou.pem");
  ASSERT_TRUE(cert.get());
  whitelist_strings.clear();
  GetCertificateWhitelistStrings(
      *cert.get(), *issuer_cert.get(), &whitelist_strings);
  EXPECT_THAT(whitelist_strings,
              ElementsAre(cert_base + "/CN=subject",
                          cert_base + "/CN=subject/O=org",
                          cert_base + "/CN=subject/O=org/OU=unit",
                          cert_base + "/CN=subject/OU=unit",
                          cert_base + "/O=org",
                          cert_base + "/O=org/OU=unit",
                          cert_base + "/OU=unit"));

  cert = ReadTestCertificate("test_cn_ou.pem");
  ASSERT_TRUE(cert.get());
  whitelist_strings.clear();
  GetCertificateWhitelistStrings(
      *cert.get(), *issuer_cert.get(), &whitelist_strings);
  EXPECT_THAT(whitelist_strings,
              ElementsAre(cert_base + "/CN=subject",
                          cert_base + "/CN=subject/OU=unit",
                          cert_base + "/OU=unit"));

  cert = ReadTestCertificate("test_o.pem");
  ASSERT_TRUE(cert.get());
  whitelist_strings.clear();
  GetCertificateWhitelistStrings(
      *cert.get(), *issuer_cert.get(), &whitelist_strings);
  EXPECT_THAT(whitelist_strings, ElementsAre(cert_base + "/O=org"));

  cert = ReadTestCertificate("test_o_ou.pem");
  ASSERT_TRUE(cert.get());
  whitelist_strings.clear();
  GetCertificateWhitelistStrings(
      *cert.get(), *issuer_cert.get(), &whitelist_strings);
  EXPECT_THAT(whitelist_strings,
              ElementsAre(cert_base + "/O=org",
                          cert_base + "/O=org/OU=unit",
                          cert_base + "/OU=unit"));

  cert = ReadTestCertificate("test_ou.pem");
  ASSERT_TRUE(cert.get());
  whitelist_strings.clear();
  GetCertificateWhitelistStrings(
      *cert.get(), *issuer_cert.get(), &whitelist_strings);
  EXPECT_THAT(whitelist_strings, ElementsAre(cert_base + "/OU=unit"));

  cert = ReadTestCertificate("test_c.pem");
  ASSERT_TRUE(cert.get());
  whitelist_strings.clear();
  GetCertificateWhitelistStrings(
      *cert.get(), *issuer_cert.get(), &whitelist_strings);
  EXPECT_THAT(whitelist_strings, ElementsAre());
}
}  // namespace safe_browsing


text:
package io.reactivex.rxjava3.internal.operators.maybe;

import org.junit.Test;

import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.exceptions.TestException;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.testsupport.TestHelper;

public class MaybeConcatMapCompletableTest extends RxJavaTest {

    @Test
    public void dispose() {
        TestHelper.checkDisposed(Maybe.just(1).concatMapCompletable(new Function<Integer, Completable>() {
            @Override
            public Completable apply(Integer v) throws Exception {
                return Completable.complete();
            }
        }));
    }

    @Test
    public void mapperThrows() {
        Maybe.just(1)
        .concatMapCompletable(new Function<Integer, Completable>() {
            @Override
            public Completable apply(Integer v) throws Exception {
                throw new TestException();
            }
        })
        .test()
        .assertFailure(TestException.class);
    }

    @Test
    public void mapperReturnsNull() {
        Maybe.just(1)
        .concatMapCompletable(new Function<Integer, Completable>() {
            @Override
            public Completable apply(Integer v) throws Exception {
                return null;
            }
        })
        .test()
        .assertFailure(NullPointerException.class);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.voicerecognizersp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!--  <uses-permission android:name="android.permission.READ_SMS"/>
	<uses-permission android:name="android.permission.RECEIVE_SMS"/> -->

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:largeHeap="true"
        >
        <activity
            android:name=".BindingActivity"
            android:label="@string/title_name"
            android:screenOrientation="portrait"
            >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <service
  			android:name=".MfccService"
  			android:exported="false"

  			>
		</service>

	   <!-- <receiver
		    android:name=".TelephonyBraodcastReceiver"
		    android:enabled="true"
		    android:exported="true">
		    <intent-filter android:priority="999">
		        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
		    </intent-filter>
		</receiver> -->

    </application>

</manifest>


text:
<?php

require __DIR__ . DIRECTORY_SEPARATOR . 'cli-config.php';

$helperSet = isset($helperSet) ? $helperSet : new \Symfony\Component\Console\Helper\HelperSet();
foreach ($helpers as $name => $helper) {
    $helperSet->set($helper, $name);
}

$cli = new \Symfony\Component\Console\Application('Doctrine ODM MongoDB Command Line Interface', Doctrine\ODM\MongoDB\Version::VERSION);
$cli->setCatchExceptions(true);
$cli->setHelperSet($helperSet);
$cli->addCommands(array(
    new \Doctrine\ODM\MongoDB\Tools\Console\Command\QueryCommand(),
    new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateDocumentsCommand(),
    new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateRepositoriesCommand(),
    new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateProxiesCommand(),
    new \Doctrine\ODM\MongoDB\Tools\Console\Command\GenerateHydratorsCommand(),
    new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\CreateCommand(),
    new \Doctrine\ODM\MongoDB\Tools\Console\Command\Schema\DropCommand(),
));
$cli->run();


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace ArkNet.Model.Peer
{
    public class ArkPeerAddress
    {
        public string Ip { get; set; }
        public int Port { get; set; }
    }
}


text:
<?php

namespace phpDocumentor\Descriptor\Type;

class IntegerDescriptorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers phpDocumentor\Descriptor\Type\IntegerDescriptor::getName
     * @covers phpDocumentor\Descriptor\Type\IntegerDescriptor::__toString
     */
    public function testIfNameCanBeReturned()
    {
        $fixture = new IntegerDescriptor();

        $this->assertSame('integer', $fixture->getName());
        $this->assertSame('integer', (string)$fixture);
    }
}


text:
(function(scope) {
var MoreRouting = scope.MoreRouting = scope.MoreRouting || {};
MoreRouting.Emitter = Object.create(null);  // Minimal set of properties.

/**
 * A dumb prototype that provides very simple event subscription.
 *
 * You are responsible for initializing `__listeners` as an array on objects
 * that make use of this.
 */
Object.defineProperties(MoreRouting.Emitter, {

  /**
   * Registers a callback that will be called each time any parameter managed by
   * this object (or its parents) have changed.
   *
   * @param {!Function} callback
   * @return {{close: function()}}
   */
  __subscribe: {
    value: function __subscribe(callback) {
      this.__listeners.push(callback);

      return {
        close: this.__unsubscribe.bind(this, callback),
      };
    },
  },

  /**
   * Unsubscribes a previously registered callback.
   *
   * @param {!Function} callback
   */
  __unsubscribe: {
    value: function __unsubscribe(callback) {
      var index = this.__listeners.indexOf(callback);
      if (index < 0) {
        console.warn(this, 'attempted unsubscribe of unregistered listener:', callback);
        return;
      }
      this.__listeners.splice(index, 1);
    },
  },

  /**
   * Notifies subscribed callbacks.
   */
  __notify: {
    value: function __notify(key, value) {
      if (this.__silent) return;
      var args = Array.prototype.slice.call(arguments);
      // Notify listeners on parents first.
      var parent = Object.getPrototypeOf(this);
      if (parent && parent.__notify && parent.__listeners) {
        parent.__notify.apply(parent, args);
      }

      this.__listeners.forEach(function(listener) {
        listener.apply(null, args);
      }.bind(this));
    },
  },

});

})(window);


text:
var fs = require('fs')
  , highlight = require('./highlight');

module.exports = function highlightFileSync (fullPath, opts) {
  var code = fs.readFileSync(fullPath, 'utf-8');
  opts = opts || { };
  return highlight(code, opts);
};


text:
		<form class="form-inline text-left" name="editForm" keypress-enter="submit()" keypress-esc="cancel()">

			<fieldset ng-show="dataReceived">

						Name

							<input id="inputName"
								   name="inputName"
								   type="text"
								   class="form-control"
								   placeholder="Name"
								   ng-model="obj.name"
								   ng-readonly="readOnly"
								   required auto-focus />

						Surname

							<input id="inputSurname"
								   name="inputSurname"
								   type="text"
								   class="form-control"
								   placeholder="Surname"
								   ng-model="obj.surname"
								   ng-readonly="readOnly"
								   required />

						Photo

							<image-selector
								   id="inputPhoto"
								   name="inputPhoto"
								   ng-model="obj.photo"
								   readonly="readOnly"
								   ng-required="false"
								   width="150"
								   options=""/>

						Blog

							<input id="inputBlog"
								   name="inputBlog"
								   type="text"
								   class="form-control"
								   placeholder="Blog"
								   ng-model="obj.blog"
								   ng-readonly="readOnly"
								    />

						Twitter

							<input id="inputTwitter"
								   name="inputTwitter"
								   type="text"
								   class="form-control"
								   placeholder="Twitter"
								   ng-model="obj.twitter"
								   ng-readonly="readOnly"
								    />

						Linkedin

							<input id="inputLinkedin"
								   name="inputLinkedin"
								   type="text"
								   class="form-control"
								   placeholder="Linkedin"
								   ng-model="obj.linkedin"
								   ng-readonly="readOnly"
								    />

						Github

							<input id="inputGithub"
								   name="inputGithub"
								   type="text"
								   class="form-control"
								   placeholder="Github"
								   ng-model="obj.github"
								   ng-readonly="readOnly"
								    />

						Bio

							<input id="inputBio"
								   name="inputBio"
								   type="text"
								   class="form-control"
								   placeholder="Bio"
								   ng-model="obj.bio"
								   ng-readonly="readOnly"
								    />

			</fieldset>

				<error-zone ng-model="errors"></error-zone>

				<button type="button" ng-show="isView" class="btn btn-default" ng-click="cancel($event)">

				</button>
				<button type="button" ng-show="isCreation" class="btn btn-primary" ng-click="add()" ng-disabled="editForm.$invalid" >

				</button>
				<button type="button" ng-show="isEdition" class="btn btn-primary" ng-click="update()" ng-disabled="editForm.$invalid" >

				</button>
				<button type="button" ng-show="isDeletion" class="btn btn-primary" ng-click="delete()">

				</button>
				<button type="button" ng-show="canEdit" class="btn btn-primary" ng-click="gotoEdit()" ng-disabled="editForm.$invalid" >

				</button>
				<button type="button" ng-hide="isView" class="btn btn-default" ng-click="cancel($event)">

				</button>
				<button type="button" ng-show="canDelete" class="btn btn-primary pull-right" ng-click="gotoDelete()" ng-disabled="editForm.$invalid" >

				</button>

		</form>


text:
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
	license agreements. See the NOTICE file distributed with this work for additional
	information regarding copyright ownership. The ASF licenses this file to
	You under the Apache License, Version 2.0 (the "License"); you may not use
	this file except in compliance with the License. You may obtain a copy of
	the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
	by applicable law or agreed to in writing, software distributed under the
	License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
	OF ANY KIND, either express or implied. See the License for the specific
	language governing permissions and limitations under the License. -->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>wfmanager</artifactId>
	<groupId>org.apache.ambari.contrib.views</groupId>
	<name>WF Manager View</name>
	<parent>
		<groupId>org.apache.ambari.contrib.views</groupId>
		<artifactId>ambari-contrib-views</artifactId>
		<version>${revision}</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.apache.ambari.contrib.views</groupId>
			<artifactId>ambari-views-utils</artifactId>
			<version>${revision}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.ambari</groupId>
			<artifactId>ambari-views</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.ambari.contrib.views</groupId>
			<artifactId>ambari-views-commons</artifactId>
			<version>${revision}</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-core</artifactId>
		</dependency>
		<!-- <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId>
			<version>2.2.2</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId>
			<artifactId>jaxb-impl</artifactId> <version>2.1.2</version> </dependency> -->
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-client</artifactId>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-json</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.20</version>
		</dependency>
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-common</artifactId>
			<version>${hadoop.version}</version>
			<exclusions>
				<exclusion>
					<groupId>tomcat</groupId>
					<artifactId>jasper-runtime</artifactId>
				</exclusion>
				<!--removed for security bugs in version : 9.3.19.v20170502-->
				<exclusion>
					<groupId>org.eclipse.jetty</groupId>
					<artifactId>jetty-util</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-hdfs</artifactId>
			<version>${hadoop.version}</version>
			<exclusions>
				<exclusion>
					<groupId>tomcat</groupId>
					<artifactId>jasper-runtime</artifactId>
				</exclusion>
        <!--removed for security bugs in version : 9.3.19.v20170502-->
        <exclusion>
          <groupId>org.eclipse.jetty</groupId>
          <artifactId>jetty-util</artifactId>
        </exclusion>
      </exclusions>
		</dependency>
	</dependencies>
	<properties>
		<uicode.dir>../</uicode.dir>
		<checkstyle.skip>true</checkstyle.skip>
                <ambari.dir>${project.parent.parent.parent.basedir}</ambari.dir>
                <ui.directory>${basedir}/src/main/resources/ui</ui.directory>
	</properties>
	<build>
		<plugins>
	      <plugin>
	        <groupId>org.apache.maven.plugins</groupId>
	        <artifactId>maven-clean-plugin</artifactId>
	        <version>2.5</version>
	        <configuration>
	          <filesets>
	            <fileset>
	              <directory>${ui.directory}</directory>
	              <followSymlinks>false</followSymlinks>
	              <includes>
	                <include>tmp/**</include>
	                <!--
	                <include>node_modules/**</include>
	                <include>bower_components/**</include>
	                -->
	                <include>node/**</include>
	              </includes>
	            </fileset>
	          </filesets>
	        </configuration>
	      </plugin>
			<plugin>
				<groupId>com.github.eirslett</groupId>
				<artifactId>frontend-maven-plugin</artifactId>
				<version>1.4</version>
				<configuration>
					<nodeVersion>v4.5.0</nodeVersion>
					<yarnVersion>v0.23.2</yarnVersion>
					<workingDirectory>src/main/resources/ui/</workingDirectory>
					<npmInheritsProxyConfigFromMaven>false</npmInheritsProxyConfigFromMaven>
                    <!-- setting npm_config_tmp environment variable is a workaround for
                     https://github.com/Medium/phantomjs/issues/673 -->
                    <environmentVariables>
                      <npm_config_tmp>/tmp/npm_config_tmp</npm_config_tmp>
                    </environmentVariables>
				</configuration>
				<executions>
					<execution>
						<id>install node and yarn</id>
						<phase>generate-sources</phase>
						<goals>
							<goal>install-node-and-yarn</goal>
						</goals>
					</execution>
					<execution>
						<id>yarn install --pure-lockfile</id>
						<phase>generate-sources</phase>
						<goals>
							<goal>yarn</goal>
						</goals>
						<configuration>
							<arguments>install
								--python="${project.basedir}/../src/main/unix/ambari-python-wrap"
								--unsafe-perm</arguments>
							<arguments>--ignore-engines</arguments>
						</configuration>
					</execution>
				</executions>
				</plugin>
               <plugin>
                    <artifactId>exec-maven-plugin</artifactId>
                    <groupId>org.codehaus.mojo</groupId>
                    <version>1.3.2</version>
                    <executions>
					<execution>
						<id>Bower install</id>
						<phase>generate-sources</phase>
						<goals>
						  <goal>exec</goal>
						</goals>
						<configuration>
						  <workingDirectory>${ui.directory}</workingDirectory>
						  <executable>${ui.directory}/node/${node.executable}</executable>
						  <arguments>
							<argument>${ui.directory}/node_modules/bower/bin/bower</argument>
							<argument>install</argument>
							<argument>--allow-root</argument>
						  </arguments>
						</configuration>
					  </execution>
					<execution>
						<id>Files build</id>
						<phase>generate-sources</phase>
						<goals>
							<goal>exec</goal>
						</goals>
						<configuration>
							<workingDirectory>${ui.directory}</workingDirectory>
							<executable>${ui.directory}/node/${node.executable}</executable>
							<arguments>
								<argument>${ui.directory}/node_modules/.bin/${ember.executable}</argument>
								<argument>build</argument>
								<argument>-prod</argument>
							</arguments>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
					<execution>
						<phase>generate-resources</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
							<includeScope>runtime</includeScope>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>false</filtering>
				<includes>
					<include>META-INF/**/*</include>
					<include>view.xml</include>
					<include>view.log4j.properties</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources/ui/dist</directory>
				<filtering>false</filtering>
			</resource>
			<!-- <resource> <directory>src/main/resources/ui/</directory> <filtering>false</filtering>
				</resource> -->
			<resource>
				<directory>${uicode.dir}/dist</directory>
				<filtering>false</filtering>
			</resource>
			<resource>
				<targetPath>WEB-INF/lib</targetPath>
				<filtering>false</filtering>
				<directory>target/lib</directory>
			</resource>
		</resources>
	</build>
    <profiles>
      <profile>
        <id>windows</id>
        <activation>
          <os>
            <family>win</family>
          </os>
        </activation>
        <properties>
          <node.executable>node.exe</node.executable>
          <ember.executable>ember.cmd</ember.executable>
          <skip.nodegyp.chmod>true</skip.nodegyp.chmod>
        </properties>
      </profile>
      <profile>
        <id>linux</id>
        <activation>
          <os>
            <family>unix</family>
          </os>
        </activation>
        <properties>
          <node.executable>node</node.executable>
          <ember.executable>ember</ember.executable>
          <skip.nodegyp.chmod>false</skip.nodegyp.chmod>
        </properties>
      </profile>
    </profiles>
</project>


text:
package com.amazonaws.services.cloudsearchv2.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.cloudsearchv2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * DescribeScalingParametersRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeScalingParametersRequestMarshaller implements Marshaller<Request<DescribeScalingParametersRequest>, DescribeScalingParametersRequest> {

    public Request<DescribeScalingParametersRequest> marshall(DescribeScalingParametersRequest describeScalingParametersRequest) {

        if (describeScalingParametersRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<DescribeScalingParametersRequest> request = new DefaultRequest<DescribeScalingParametersRequest>(describeScalingParametersRequest,
                "AmazonCloudSearchv2");
        request.addParameter("Action", "DescribeScalingParameters");
        request.addParameter("Version", "2013-01-01");
        request.setHttpMethod(HttpMethodName.POST);

        if (describeScalingParametersRequest.getDomainName() != null) {
            request.addParameter("DomainName", StringUtils.fromString(describeScalingParametersRequest.getDomainName()));
        }

        return request;
    }

}


text:
package ru.stqa.training.selenium.LiteCart;

import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;

import static org.junit.Assert.assertTrue;

public class AdminMainMenu extends LoginLocal{

    @Test
    public void menuClick() {

        String fistPointMenu = "#app-";
        String nextMenu = "li.selected+*";
        String headerCssSelector = "td#content h1";

        LoginAdmin(new LoginData("admin", "admin"));

        wd.findElement(By.cssSelector(fistPointMenu)).click();
        assert wd.findElement(By.cssSelector(headerCssSelector)).isDisplayed();
        do {
            wd.findElement(By.cssSelector(nextMenu)).click();
            assert wd.findElement(By.cssSelector(headerCssSelector)).isDisplayed();

        } while (isElementPresent(wd, nextMenu));
    }

        boolean isElementPresent(WebDriver wd, String cssSelector) {
            try {
                wd.findElement(By.cssSelector(cssSelector));
                return true;
            } catch (NoSuchElementException ex) {
                return false;
            }
//        Читерский способ ))
//        wd.findElement(By.xpath("//span[2]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[2]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[2]/a/span[2]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[2]/ul/li[2]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[4]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[5]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[6]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[7]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[8]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[9]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[3]/a/span[2]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[10]/a/span[2]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[6]/a/span[2]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[7]/a/span[2]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[7]/ul/li[2]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[8]/a/span[2]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[8]/ul/li[2]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-shipping > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-payment > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-order_total > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-order_success > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-order_action > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("(//li[@id='app-']/a/span[2])[9]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-order_statuses > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("(//li[@id='app-']/a/span[2])[10]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("(//li[@id='app-']/a/span[2])[11]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-most_sold_products > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-most_shopping_customers > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("(//li[@id='app-']/a/span[2])[12]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-defaults > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-general > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-listings > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-images > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-checkout > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-advanced > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-security > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("(//li[@id='app-']/a/span[2])[13]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("(//li[@id='app-']/a/span[2])[14]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-tax_rates > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("(//li[@id='app-']/a/span[2])[15]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-scan > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.cssSelector("#doc-csv > a > span.name")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("(//li[@id='app-']/a/span[2])[16]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("(//li[@id='app-']/a/span[2])[17]")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
//        wd.findElement(By.xpath("//li[3]/a/span")).click();
//        assert wd.findElement(By.cssSelector("#content > h1")).isDisplayed();
    }

}


text:
package org.apache.wicket.extensions.markup.html.repeater.data.table;

import org.apache.wicket.IClusterable;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.StringResourceModel;

/**
 * Label that provides Showing x to y of z message given for a DataTable. The message can be
 * overridden using the NavigatorLabel property key, the default message is used is
 * of the format Showing ${from} to ${to} of ${of}. The message can also be
 * configured pragmatically by setting it as the model object of the label.
 *
 * @author Igor Vaynberg (ivaynberg)
 *
 */
public class NavigatorLabel extends Label
{
	private static final long serialVersionUID = 1L;

	// TODO Factor this interface out and let dataview/datatable implement it
	private static interface PageableComponent extends IClusterable
	{
		/**
		 * @return total number of rows across all pages
		 */
		int getRowCount();

		/**
		 * @return current page
		 */
		int getCurrentPage();

		/**
		 * @return rows per page
		 */
		int getRowsPerPage();
	}

	/**
	 * @param id
	 *            component id
	 * @param table
	 *            dataview
	 */
	public NavigatorLabel(final String id, final DataTable<?> table)
	{
		this(id, new PageableComponent()
		{

			/**
			 *
			 */
			private static final long serialVersionUID = 1L;

			public int getCurrentPage()
			{
				return table.getCurrentPage();
			}

			public int getRowCount()
			{
				return table.getRowCount();
			}

			public int getRowsPerPage()
			{
				return table.getRowsPerPage();
			}

		});

	}

	/**
	 * @param id
	 *            component id
	 * @param table
	 *            pageable view
	 */
	public NavigatorLabel(final String id, final DataView<?> table)
	{
		this(id, new PageableComponent()
		{

			/**
			 *
			 */
			private static final long serialVersionUID = 1L;

			public int getCurrentPage()
			{
				return table.getCurrentPage();
			}

			public int getRowCount()
			{
				return table.getRowCount();
			}

			public int getRowsPerPage()
			{
				return table.getItemsPerPage();
			}

		});

	}

	private NavigatorLabel(final String id, final PageableComponent table)
	{
		super(id);
		setDefaultModel(new StringResourceModel("NavigatorLabel", this,
			new Model<LabelModelObject>(new LabelModelObject(table)),
			"Showing ${from} to ${to} of ${of}"));
	}

	private class LabelModelObject implements IClusterable
	{
		private static final long serialVersionUID = 1L;
		private final PageableComponent table;

		/**
		 * Construct.
		 *
		 * @param table
		 */
		public LabelModelObject(PageableComponent table)
		{
			this.table = table;
		}

		/**
		 * @return "z" in "Showing x to y of z"
		 */
		public int getOf()
		{
			return table.getRowCount();
		}

		/**
		 * @return "x" in "Showing x to y of z"
		 */
		public int getFrom()
		{
			if (getOf() == 0)
			{
				return 0;
			}
			return (table.getCurrentPage() * table.getRowsPerPage()) + 1;
		}

		/**
		 * @return "y" in "Showing x to y of z"
		 */
		public int getTo()
		{
			if (getOf() == 0)
			{
				return 0;
			}
			return Math.min(getOf(), getFrom() + table.getRowsPerPage() - 1);
		}

	}
}


text:
import { AURELIA_TEMPLATE_ATTRIBUTE_KEYWORD_LIST } from '../constants';

/**
 * @example
 *   const input = 'inter-bindable.bind'
 *                                ^
 *   getAureliaAttributeKeywordIndex(input) // 14
 */
export function getAureliaAttributeKeywordIndex(input: string): number {
  let index = NaN;

  AURELIA_TEMPLATE_ATTRIBUTE_KEYWORD_LIST.find((keyword) => {
    const withDot = `.${keyword}`;
    const match = input.indexOf(withDot);
    if (match >= 0) {
      index = match;
      return true;
    }
    return false;
  });

  return index;
}

/**
 * @example
 *   const input = 'inter-bindable.bind'
 *
 *   getBindableNameFromAttritute(input) // inter-bindable
 */
export function getBindableNameFromAttritute(input: string): string {
  // Sth like: .(bind|call)$
  const asRegex = new RegExp(
    `.(${AURELIA_TEMPLATE_ATTRIBUTE_KEYWORD_LIST.join('|')})$`
  );
  const result = input.replace(asRegex, '');
  return result;
}

// getBindableNameFromAttritute('inter-bindable.bind');


text:
void zero(int **p) {
  *p = 0;
  // expected-note@-1 {{Null pointer value stored to 'a'}}
}

void testZero(int *a) {
  zero(&a);
  // expected-note@-1 {{Calling 'zero'}}
  // expected-note@-2 {{Returning from 'zero'}}
  *a = 1; // expected-warning{{Dereference of null pointer}}
  // expected-note@-1 {{Dereference of null pointer (loaded from variable 'a')}}
}

void testCheck(int *a) {
  if (a) {
    // expected-note@-1 + {{Assuming 'a' is null}}
    // expected-note@-2 + {{Taking false branch}}
    ;
  }
  *a = 1; // expected-warning{{Dereference of null pointer}}
  // expected-note@-1 {{Dereference of null pointer (loaded from variable 'a')}}
}

int *getPointer();

void testInitCheck() {
  int *a = getPointer();
  // expected-note@-1 {{'a' initialized here}}
  if (a) {
    // expected-note@-1 + {{Assuming 'a' is null}}
    // expected-note@-2 + {{Taking false branch}}
    ;
  }
  *a = 1; // expected-warning{{Dereference of null pointer}}
  // expected-note@-1 {{Dereference of null pointer (loaded from variable 'a')}}
}

void testStoreCheck(int *a) {
  a = getPointer();
  // expected-note@-1 {{Value assigned to 'a'}}
  if (a) {
    // expected-note@-1 + {{Assuming 'a' is null}}
    // expected-note@-2 + {{Taking false branch}}
    ;
  }
  *a = 1; // expected-warning{{Dereference of null pointer}}
  // expected-note@-1 {{Dereference of null pointer (loaded from variable 'a')}}
}

int *getZero() {
  int *p = 0;
  // expected-note@-1 + {{'p' initialized to a null pointer value}}
  // ^ This note checks that we add a second visitor for the return value.
  return p;
  // expected-note@-1 + {{Returning null pointer (loaded from 'p')}}
}

void testReturnZero() {
  *getZero() = 1; // expected-warning{{Dereference of null pointer}}
  // expected-note@-1 {{Calling 'getZero'}}
  // expected-note@-2 {{Returning from 'getZero'}}
  // expected-note@-3 {{Dereference of null pointer}}
}

int testReturnZero2() {
  return *getZero(); // expected-warning{{Dereference of null pointer}}
  // expected-note@-1 {{Calling 'getZero'}}
  // expected-note@-2 {{Returning from 'getZero'}}
  // expected-note@-3 {{Dereference of null pointer}}
}

void testInitZero() {
  int *a = getZero();
  // expected-note@-1 {{Calling 'getZero'}}
  // expected-note@-2 {{Returning from 'getZero'}}
  // expected-note@-3 {{'a' initialized to a null pointer value}}
  *a = 1; // expected-warning{{Dereference of null pointer}}
  // expected-note@-1 {{Dereference of null pointer (loaded from variable 'a')}}
}

void testStoreZero(int *a) {
  a = getZero();
  // expected-note@-1 {{Calling 'getZero'}}
  // expected-note@-2 {{Returning from 'getZero'}}
  // expected-note@-3 {{Null pointer value stored to 'a'}}
  *a = 1; // expected-warning{{Dereference of null pointer}}
  // expected-note@-1 {{Dereference of null pointer (loaded from variable 'a')}}
}

void usePointer(int *p) {
  *p = 1; // expected-warning{{Dereference of null pointer}}
  // expected-note@-1 {{Dereference of null pointer}}
}

void testUseOfNullPointer() {
  // Test the case where an argument expression is itself a call.
  usePointer(getZero());
  // expected-note@-1 {{Calling 'getZero'}}
  // expected-note@-2 {{Returning from 'getZero'}}
  // expected-note@-3 {{Passing null pointer value via 1st parameter 'p'}}
  // expected-note@-4 {{Calling 'usePointer'}}
}

struct X { char *p; };

void setFieldToNull(struct X *x) {
	x->p = 0; // expected-note {{Null pointer value stored to field 'p'}}
}

int testSetFieldToNull(struct X *x) {
  setFieldToNull(x); // expected-note {{Calling 'setFieldToNull'}}
                     // expected-note@-1{{Returning from 'setFieldToNull'}}
  return *x->p;
  // expected-warning@-1 {{Dereference of null pointer (loaded from field 'p')}}
  // expected-note@-2 {{Dereference of null pointer (loaded from field 'p')}}
}

struct Outer {
  struct Inner {
    int *p;
  } inner;
};

void test(struct Outer *wrapperPtr) {
  wrapperPtr->inner.p = 0;  // expected-note {{Null pointer value stored to field 'p'}}
  *wrapperPtr->inner.p = 1; //expected-warning {{Dereference of null pointer (loaded from field 'p')}}
                            // expected-note@-1 {{Dereference of null pointer (loaded from field 'p')}}
}

void test4(int **p) {
  if (*p) return; // expected-note {{Taking false branch}}
                  // expected-note@-1 {{Assuming pointer value is null}}
  **p = 1; // expected-warning {{Dereference of null pointer}}
           // expected-note@-1 {{Dereference of null pointer}}
}

void boringCallee() {
}

void interestingCallee(int *x) {
  *x = 0; // expected-note{{The value 0 is assigned to 'x'}}
  boringCallee(); // no-note
}

int testBoringCalleeOfInterestingCallee() {
  int x;
  interestingCallee(&x); // expected-note{{Calling 'interestingCallee'}}
                         // expected-note@-1{{Returning from 'interestingCallee'}}
  return 1 / x; // expected-warning{{Division by zero}}
                // expected-note@-1{{Division by zero}}
}