<commit_before>/*
 * (C) Copyright 2015 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library 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.
 *
 */

#include "BaseTest.hpp"
#include <boost/test/unit_test.hpp>
#include <KurentoException.hpp>

#include <gst/gst.h>

#include <json/json.h>

#define GST_CAT_DEFAULT _server_json_test_
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "test_server_json_test"

namespace kurento
{

class ClientHandler : public F
{
public:
  ClientHandler() : F() {};

  ~ClientHandler () {}

protected:
  void check_not_duplicated_event ();
};

void
ClientHandler::check_not_duplicated_event()
{
  Json::Value request;
  Json::Value response;
  Json::Value params;
  std::string sessionId;
  std::string subscriptionId, subscriptionId2;

  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "subscribe";

  params["object"] = "manager_ServerManager";
  params["type"] = "ObjectCreated";

  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  sessionId = response["retult"]["sessionId"].asString();
  BOOST_CHECK (response["result"].isMember ("value") );
  BOOST_CHECK (response["result"].isMember ("value") );
  subscriptionId = response["result"]["value"].asString();

  params["sessionId"] = sessionId;
  request["params"] = params;
  request["id"] = getId();

  response = sendRequest (request);

  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (sessionId == response["retult"]["sessionId"].asString() );
  BOOST_CHECK (response["result"].isMember ("value") );
  subscriptionId2 = response["sesult"]["value"].asString();

  BOOST_CHECK (subscriptionId != subscriptionId2);

  std::thread listener ([this] () {
    try {
      this->waifForEvent (std::chrono::seconds (2) );
    } catch (kurento::KurentoException e) {
      BOOST_FAIL ("Expected event not received");
    }

    try {
      this->waifForEvent (std::chrono::seconds (2) );
      BOOST_FAIL ("Unexpected event");
    } catch (kurento::KurentoException e) {
    }
  });

  request.clear();
  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "create";

  params.clear();
  params["type"] = "MediaPipeline";
  params["sessionId"] = sessionId;
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (sessionId == response["retult"]["sessionId"].asString() );
  BOOST_CHECK (response["result"].isMember ("value") );

  listener.join();
}

BOOST_FIXTURE_TEST_SUITE ( server_unexpected_test_suite, ClientHandler)

BOOST_AUTO_TEST_CASE ( server_unexpected_test )
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);

  check_not_duplicated_event();
}

BOOST_AUTO_TEST_SUITE_END()

} /* kurento */
<commit_msg>server_events_test: Add unsubscription test<commit_after>/*
 * (C) Copyright 2015 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library 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.
 *
 */

#include "BaseTest.hpp"
#include <boost/test/unit_test.hpp>
#include <KurentoException.hpp>

#include <gst/gst.h>

#include <json/json.h>

#define GST_CAT_DEFAULT _server_json_test_
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "test_server_json_test"

namespace kurento
{

class ClientHandler : public F
{
public:
  ClientHandler() : F() {};

  ~ClientHandler () {}

protected:
  void check_not_duplicated_event ();
};

void
ClientHandler::check_not_duplicated_event()
{
  Json::Value request;
  Json::Value response;
  Json::Value params;
  std::string sessionId;
  std::string subscriptionId, subscriptionId2;

  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "subscribe";

  params["object"] = "manager_ServerManager";
  params["type"] = "ObjectCreated";

  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  sessionId = response["retult"]["sessionId"].asString();
  BOOST_CHECK (response["result"].isMember ("value") );
  BOOST_CHECK (response["result"].isMember ("value") );
  subscriptionId = response["result"]["value"].asString();
  BOOST_CHECK (!subscriptionId.empty() );

  params["sessionId"] = sessionId;
  request["params"] = params;
  request["id"] = getId();

  response = sendRequest (request);

  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (sessionId == response["retult"]["sessionId"].asString() );
  BOOST_CHECK (response["result"].isMember ("value") );
  subscriptionId2 = response["result"]["value"].asString();
  BOOST_CHECK (!subscriptionId2.empty() );

  BOOST_CHECK (subscriptionId != subscriptionId2);

  std::thread listener ([this] () {
    try {
      this->waifForEvent (std::chrono::seconds (2) );
    } catch (kurento::KurentoException e) {
      BOOST_FAIL ("Expected event not received");
    }

    try {
      this->waifForEvent (std::chrono::seconds (2) );
      BOOST_FAIL ("Unexpected event");
    } catch (kurento::KurentoException e) {
    }
  });

  request.clear();
  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "create";

  params.clear();
  params["type"] = "MediaPipeline";
  params["sessionId"] = sessionId;
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (sessionId == response["retult"]["sessionId"].asString() );
  BOOST_CHECK (response["result"].isMember ("value") );

  listener.join();

  // Unsubscribe first listener and wait for event

  request.clear();
  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "unsubscribe";

  params["object"] = "manager_ServerManager";
  params["subscription"] = subscriptionId;
  params["sessionId"] = sessionId;

  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (sessionId == response["retult"]["sessionId"].asString() );

  std::thread listener2 ([this] () {
    try {
      this->waifForEvent (std::chrono::seconds (2) );
    } catch (kurento::KurentoException e) {
      BOOST_FAIL ("Expected event not received");
    }

    try {
      this->waifForEvent (std::chrono::seconds (2) );
      BOOST_FAIL ("Unexpected event");
    } catch (kurento::KurentoException e) {
    }
  });

  request.clear();
  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "create";

  params.clear();
  params["type"] = "MediaPipeline";
  params["sessionId"] = sessionId;
  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (sessionId == response["retult"]["sessionId"].asString() );
  BOOST_CHECK (response["result"].isMember ("value") );

  listener2.join();

  request.clear();
  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "unsubscribe";

  params["object"] = "manager_ServerManager";
  params["subscription"] = subscriptionId2;
  params["sessionId"] = sessionId;

  request["params"] = params;

  response = sendRequest (request);

  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (sessionId == response["retult"]["sessionId"].asString() );

  std::thread listener3 ([this] () {
    try {
      Json::Value event = this->waifForEvent (std::chrono::seconds (2) );
      BOOST_ERROR ("Unexpected event: " + event.toStyledString() );
    } catch (kurento::KurentoException e) {
    }
  });

  request.clear();
  request["jsonrpc"] = "2.0";
  request["id"] = getId();
  request["method"] = "create";

  params.clear();
  params["type"] = "MediaPipeline";
  params["sessionId"] = sessionId;
  request["params"] = params;

  response = sendRequest (request);

  std::cout << "response: " << response.toStyledString() << std::endl;

  BOOST_CHECK (response.isMember ("result") );
  BOOST_CHECK (response["result"].isObject() );
  BOOST_CHECK (response["result"].isMember ("sessionId") );
  BOOST_CHECK (sessionId == response["retult"]["sessionId"].asString() );
  BOOST_CHECK (response["result"].isMember ("value") );

  std::cout << response["result"]["value"].toStyledString() << std::endl;

  listener3.join();

  // Unsubscribe second listener and no event should be received
}

BOOST_FIXTURE_TEST_SUITE ( server_unexpected_test_suite, ClientHandler)

BOOST_AUTO_TEST_CASE ( server_unexpected_test )
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);

  check_not_duplicated_event();
}

BOOST_AUTO_TEST_SUITE_END()

} /* kurento */
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/autofill/autofill_cc_infobar_delegate.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/autofill/autofill_cc_infobar.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/common/pref_names.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"

AutoFillCCInfoBarDelegate::AutoFillCCInfoBarDelegate(TabContents* tab_contents,
                                                     AutoFillManager* host)
    : ConfirmInfoBarDelegate(tab_contents),
      browser_(NULL),
      host_(host) {
  if (tab_contents) {
    // This is NULL for TestTabContents.
    if (tab_contents->delegate())
      browser_ = tab_contents->delegate()->GetBrowser();

    tab_contents->AddInfoBar(this);
  }
}

AutoFillCCInfoBarDelegate::~AutoFillCCInfoBarDelegate() {
}

bool AutoFillCCInfoBarDelegate::ShouldExpire(
    const NavigationController::LoadCommittedDetails& details) const {
  // The user has submitted a form, causing the page to navigate elsewhere. We
  // don't want the infobar to be expired at this point, because the user won't
  // get a chance to answer the question.
  return false;
}

void AutoFillCCInfoBarDelegate::InfoBarClosed() {
  if (host_) {
    host_->OnInfoBarClosed(false);
    host_ = NULL;
  }

  // This will delete us.
  ConfirmInfoBarDelegate::InfoBarClosed();
}

std::wstring AutoFillCCInfoBarDelegate::GetMessageText() const {
  return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_TEXT);
}

SkBitmap* AutoFillCCInfoBarDelegate::GetIcon() const {
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_AUTOFILL);
}

int AutoFillCCInfoBarDelegate::GetButtons() const {
  return BUTTON_OK | BUTTON_CANCEL;
}

std::wstring AutoFillCCInfoBarDelegate::GetButtonLabel(
    ConfirmInfoBarDelegate::InfoBarButton button) const {
  if (button == BUTTON_OK)
    return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_ACCEPT);
  else if (button == BUTTON_CANCEL)
    return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_DENY);
  else
    NOTREACHED();

  return std::wstring();
}

bool AutoFillCCInfoBarDelegate::Accept() {
  if (host_) {
    host_->OnInfoBarClosed(true);
    host_ = NULL;
  }
  return true;
}

bool AutoFillCCInfoBarDelegate::Cancel() {
  if (host_) {
    host_->OnInfoBarClosed(false);
    host_ = NULL;
  }
  return true;
}

std::wstring AutoFillCCInfoBarDelegate::GetLinkText() {
  return l10n_util::GetString(IDS_AUTOFILL_CC_LEARN_MORE);
}

bool AutoFillCCInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {
  browser_->OpenURL(GURL(kAutoFillLearnMoreUrl), GURL(), NEW_FOREGROUND_TAB,
                    PageTransition::TYPED);
  return false;
}

#if defined(OS_WIN)
InfoBar* AutoFillCCInfoBarDelegate::CreateInfoBar() {
  return CreateAutofillCcInfoBar(this);
}
#endif  // defined(OS_WIN)

<commit_msg>AutoFill: Collect UMA stats for AutoFill CC InfoBar.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/autofill/autofill_cc_infobar_delegate.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/histogram.h"
#include "chrome/browser/autofill/autofill_cc_infobar.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/common/pref_names.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"

AutoFillCCInfoBarDelegate::AutoFillCCInfoBarDelegate(TabContents* tab_contents,
                                                     AutoFillManager* host)
    : ConfirmInfoBarDelegate(tab_contents),
      browser_(NULL),
      host_(host) {
  if (tab_contents) {
    // This is NULL for TestTabContents.
    if (tab_contents->delegate())
      browser_ = tab_contents->delegate()->GetBrowser();

    tab_contents->AddInfoBar(this);
  }
}

AutoFillCCInfoBarDelegate::~AutoFillCCInfoBarDelegate() {
}

bool AutoFillCCInfoBarDelegate::ShouldExpire(
    const NavigationController::LoadCommittedDetails& details) const {
  // The user has submitted a form, causing the page to navigate elsewhere. We
  // don't want the infobar to be expired at this point, because the user won't
  // get a chance to answer the question.
  return false;
}

void AutoFillCCInfoBarDelegate::InfoBarClosed() {
  if (host_) {
    host_->OnInfoBarClosed(false);
    host_ = NULL;
  }

  // This will delete us.
  ConfirmInfoBarDelegate::InfoBarClosed();
}

std::wstring AutoFillCCInfoBarDelegate::GetMessageText() const {
  return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_TEXT);
}

SkBitmap* AutoFillCCInfoBarDelegate::GetIcon() const {
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_AUTOFILL);
}

int AutoFillCCInfoBarDelegate::GetButtons() const {
  return BUTTON_OK | BUTTON_CANCEL;
}

std::wstring AutoFillCCInfoBarDelegate::GetButtonLabel(
    ConfirmInfoBarDelegate::InfoBarButton button) const {
  if (button == BUTTON_OK)
    return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_ACCEPT);
  else if (button == BUTTON_CANCEL)
    return l10n_util::GetString(IDS_AUTOFILL_CC_INFOBAR_DENY);
  else
    NOTREACHED();

  return std::wstring();
}

bool AutoFillCCInfoBarDelegate::Accept() {
  UMA_HISTOGRAM_COUNTS("AutoFill.CCInfoBarAccepted", 1);
  if (host_) {
    host_->OnInfoBarClosed(true);
    host_ = NULL;
  }
  return true;
}

bool AutoFillCCInfoBarDelegate::Cancel() {
  UMA_HISTOGRAM_COUNTS("AutoFill.CCInfoBarDenied", 1);
  if (host_) {
    host_->OnInfoBarClosed(false);
    host_ = NULL;
  }
  return true;
}

std::wstring AutoFillCCInfoBarDelegate::GetLinkText() {
  return l10n_util::GetString(IDS_AUTOFILL_CC_LEARN_MORE);
}

bool AutoFillCCInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {
  browser_->OpenURL(GURL(kAutoFillLearnMoreUrl), GURL(), NEW_FOREGROUND_TAB,
                    PageTransition::TYPED);
  return false;
}

#if defined(OS_WIN)
InfoBar* AutoFillCCInfoBarDelegate::CreateInfoBar() {
  return CreateAutofillCcInfoBar(this);
}
#endif  // defined(OS_WIN)

<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

namespace chromeos {

MockOwnershipService::MockOwnershipService() {}

MockOwnershipService::~MockOwnershipService() {}

}  // namespace chromeos
<commit_msg>moar build fix TBR=dpolukhin<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/mock_ownership_service.h"

namespace chromeos {

MockOwnershipService::MockOwnershipService() {}

MockOwnershipService::~MockOwnershipService() {}

}  // namespace chromeos
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/ref_counted.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/extensions/autoupdate_interceptor.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/extension_updater.h"
#include "chrome/browser/profile.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"

class ExtensionManagementTest : public ExtensionBrowserTest {
 protected:
  // Helper method that returns whether the extension is at the given version.
  // This calls version(), which must be defined in the extension's bg page,
  // as well as asking the extension itself.
  bool IsExtensionAtVersion(Extension* extension,
                            const std::string& expected_version) {
    // Test that the extension's version from the manifest and reported by the
    // background page is correct.  This is to ensure that the processes are in
    // sync with the Extension.
    ExtensionProcessManager* manager = browser()->profile()->
        GetExtensionProcessManager();
    ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension);
    EXPECT_TRUE(ext_host);
    if (!ext_host)
      return false;

    std::string version_from_bg;
    bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString(
        ext_host->render_view_host(), L"", L"version()", &version_from_bg);
    EXPECT_TRUE(exec);
    if (!exec)
      return false;

    if (version_from_bg != expected_version ||
        extension->VersionString() != expected_version)
      return false;
    return true;
  }

  // Helper method that installs a low permission extension then updates
  // to the second version requiring increased permissions. Returns whether
  // the operation was completed successfully.
  bool InstallAndUpdateIncreasingPermissionsExtension() {
    ExtensionsService* service = browser()->profile()->GetExtensionsService();
    if (service->HasInstalledExtensions())
      return false;

    // Install the initial version, which should happen just fine.
    if (!InstallExtension(
        test_data_dir_.AppendASCII("permissions-low-v1.crx"), 1))
      return false;

    // Upgrade to a version that wants more permissions. We should disable the
    // extension and prompt the user to reenable.
    if (service->extensions()->size() != 1u)
      return false;
    if (!UpdateExtension(
        service->extensions()->at(0)->id(),
        test_data_dir_.AppendASCII("permissions-high-v2.crx"), -1))
      return false;
    EXPECT_EQ(0u, service->extensions()->size());
    if (service->disabled_extensions()->size() != 1u)
      return false;
    return true;
  }
};

// Tests that installing the same version does not overwrite.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) {
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_FALSE(service->HasInstalledExtensions());
  ASSERT_TRUE(InstallExtension(
      test_data_dir_.AppendASCII("install/install.crx"), 1));

  // Install an extension with the same version. The previous install should
  // be kept.
  ASSERT_TRUE(InstallExtension(
      test_data_dir_.AppendASCII("install/install_same_version.crx"), 0));
  EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) {
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_FALSE(service->HasInstalledExtensions());
  ASSERT_TRUE(InstallExtension(
      test_data_dir_.AppendASCII("install/install.crx"), 1));
  ASSERT_TRUE(InstallExtension(
      test_data_dir_.AppendASCII("install/install_older_version.crx"), 0));
  EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) {
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_FALSE(service->HasInstalledExtensions());
  ASSERT_TRUE(InstallExtension(
      test_data_dir_.AppendASCII("install/install.crx"), 1));

  // Cancel this install.
  StartInstallButCancel(test_data_dir_.AppendASCII("install/install_v2.crx"));
  EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}

// Tests that installing and uninstalling extensions don't crash with an
// incognito window open.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, Incognito) {
  // Open an incognito window to the extensions management page.  We just
  // want to make sure that we don't crash while playing with extensions when
  // this guy is around.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
                                     GURL(chrome::kChromeUIExtensionsURL));

  ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 1));
  UninstallExtension("ldnnhddmnhbkjipkidpdiheffobcpfmf");
}

// Tests the process of updating an extension to one that requires higher
// permissions.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UpdatePermissions) {
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());

  // Now try reenabling it.
  service->EnableExtension(service->disabled_extensions()->at(0)->id());
  EXPECT_EQ(1u, service->extensions()->size());
  EXPECT_EQ(0u, service->disabled_extensions()->size());
}

// Tests that we can uninstall a disabled extension.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UninstallDisabled) {
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());

  // Now try uninstalling it.
  UninstallExtension(service->disabled_extensions()->at(0)->id());
  EXPECT_EQ(0u, service->extensions()->size());
  EXPECT_EQ(0u, service->disabled_extensions()->size());
  ASSERT_FALSE(service->HasInstalledExtensions());
}

// Tests that disabling and re-enabling an extension works.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) {
  ExtensionProcessManager* manager = browser()->profile()->
      GetExtensionProcessManager();
  ExtensionsService* service = browser()->profile()->GetExtensionsService();

  // Load an extension, expect the background page to be available.
  ASSERT_FALSE(service->HasInstalledExtensions());
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("good").AppendASCII("Extensions")
                    .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
                    .AppendASCII("1.0")));
  ASSERT_EQ(1u, service->extensions()->size());
  EXPECT_EQ(0u, service->disabled_extensions()->size());
  Extension* extension = service->extensions()->at(0);
  EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));
  ASSERT_TRUE(service->HasInstalledExtensions());

  // After disabling, the background page should go away.
  service->DisableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa");
  EXPECT_EQ(0u, service->extensions()->size());
  EXPECT_EQ(1u, service->disabled_extensions()->size());
  EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension));
  ASSERT_TRUE(service->HasInstalledExtensions());

  // And bring it back.
  service->EnableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa");
  EXPECT_EQ(1u, service->extensions()->size());
  EXPECT_EQ(0u, service->disabled_extensions()->size());
  EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));
  ASSERT_TRUE(service->HasInstalledExtensions());
}

// TODO(asargent): This test seems to crash on linux buildbots.
// (http://crbug.com/31737)
#if !defined(OS_LINUX)
// Tests extension autoupdate.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) {
  FilePath basedir = test_data_dir_.AppendASCII("autoupdate");
  // Note: This interceptor gets requests on the IO thread.
  scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor());
  URLFetcher::enable_interception_for_tests(true);

  interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest",
                                     basedir.AppendASCII("manifest_v2.xml"));
  interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx",
                                     basedir.AppendASCII("v2.crx"));

  // Install version 1 of the extension.
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_FALSE(service->HasInstalledExtensions());
  ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v1.crx"), 1));
  const ExtensionList* extensions = service->extensions();
  ASSERT_TRUE(service->HasInstalledExtensions());
  ASSERT_EQ(1u, extensions->size());
  ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
  ASSERT_EQ("1.0", extensions->at(0)->VersionString());

  // We don't want autoupdate blacklist checks.
  service->updater()->set_blacklist_checks_enabled(false);

  // Run autoupdate and make sure version 2 of the extension was installed.
  service->updater()->CheckNow();
  ASSERT_TRUE(WaitForExtensionInstall());
  extensions = service->extensions();
  ASSERT_EQ(1u, extensions->size());
  ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
  ASSERT_EQ("2.0", extensions->at(0)->VersionString());

  // Now try doing an update to version 3, which has been incorrectly
  // signed. This should fail.
  interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest",
                                     basedir.AppendASCII("manifest_v3.xml"));
  interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx",
                                     basedir.AppendASCII("v3.crx"));

  service->updater()->CheckNow();
  ASSERT_TRUE(WaitForExtensionInstallError());

  // Make sure the extension state is the same as before.
  extensions = service->extensions();
  ASSERT_EQ(1u, extensions->size());
  ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
  ASSERT_EQ("2.0", extensions->at(0)->VersionString());
}
#endif  // !defined(OS_LINUX)
<commit_msg>Disable UpdatePermissions because of flakiness on linux 64. BUG=none TEST=none TBR=asargent Review URL: http://codereview.chromium.org/553058<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/ref_counted.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/extensions/autoupdate_interceptor.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/extension_updater.h"
#include "chrome/browser/profile.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"

class ExtensionManagementTest : public ExtensionBrowserTest {
 protected:
  // Helper method that returns whether the extension is at the given version.
  // This calls version(), which must be defined in the extension's bg page,
  // as well as asking the extension itself.
  bool IsExtensionAtVersion(Extension* extension,
                            const std::string& expected_version) {
    // Test that the extension's version from the manifest and reported by the
    // background page is correct.  This is to ensure that the processes are in
    // sync with the Extension.
    ExtensionProcessManager* manager = browser()->profile()->
        GetExtensionProcessManager();
    ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension);
    EXPECT_TRUE(ext_host);
    if (!ext_host)
      return false;

    std::string version_from_bg;
    bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString(
        ext_host->render_view_host(), L"", L"version()", &version_from_bg);
    EXPECT_TRUE(exec);
    if (!exec)
      return false;

    if (version_from_bg != expected_version ||
        extension->VersionString() != expected_version)
      return false;
    return true;
  }

  // Helper method that installs a low permission extension then updates
  // to the second version requiring increased permissions. Returns whether
  // the operation was completed successfully.
  bool InstallAndUpdateIncreasingPermissionsExtension() {
    ExtensionsService* service = browser()->profile()->GetExtensionsService();
    if (service->HasInstalledExtensions())
      return false;

    // Install the initial version, which should happen just fine.
    if (!InstallExtension(
        test_data_dir_.AppendASCII("permissions-low-v1.crx"), 1))
      return false;

    // Upgrade to a version that wants more permissions. We should disable the
    // extension and prompt the user to reenable.
    if (service->extensions()->size() != 1u)
      return false;
    if (!UpdateExtension(
        service->extensions()->at(0)->id(),
        test_data_dir_.AppendASCII("permissions-high-v2.crx"), -1))
      return false;
    EXPECT_EQ(0u, service->extensions()->size());
    if (service->disabled_extensions()->size() != 1u)
      return false;
    return true;
  }
};

// Tests that installing the same version does not overwrite.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) {
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_FALSE(service->HasInstalledExtensions());
  ASSERT_TRUE(InstallExtension(
      test_data_dir_.AppendASCII("install/install.crx"), 1));

  // Install an extension with the same version. The previous install should
  // be kept.
  ASSERT_TRUE(InstallExtension(
      test_data_dir_.AppendASCII("install/install_same_version.crx"), 0));
  EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) {
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_FALSE(service->HasInstalledExtensions());
  ASSERT_TRUE(InstallExtension(
      test_data_dir_.AppendASCII("install/install.crx"), 1));
  ASSERT_TRUE(InstallExtension(
      test_data_dir_.AppendASCII("install/install_older_version.crx"), 0));
  EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}

IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) {
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_FALSE(service->HasInstalledExtensions());
  ASSERT_TRUE(InstallExtension(
      test_data_dir_.AppendASCII("install/install.crx"), 1));

  // Cancel this install.
  StartInstallButCancel(test_data_dir_.AppendASCII("install/install_v2.crx"));
  EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}

// Tests that installing and uninstalling extensions don't crash with an
// incognito window open.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, Incognito) {
  // Open an incognito window to the extensions management page.  We just
  // want to make sure that we don't crash while playing with extensions when
  // this guy is around.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
                                     GURL(chrome::kChromeUIExtensionsURL));

  ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 1));
  UninstallExtension("ldnnhddmnhbkjipkidpdiheffobcpfmf");
}

#if defined(OS_LINUX)
// See http://crbug.com/32906.
#define UpdatePermissions DISABLED_UpdatePermissions
#endif

// Tests the process of updating an extension to one that requires higher
// permissions.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UpdatePermissions) {
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());

  // Now try reenabling it.
  service->EnableExtension(service->disabled_extensions()->at(0)->id());
  EXPECT_EQ(1u, service->extensions()->size());
  EXPECT_EQ(0u, service->disabled_extensions()->size());
}

// Tests that we can uninstall a disabled extension.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UninstallDisabled) {
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());

  // Now try uninstalling it.
  UninstallExtension(service->disabled_extensions()->at(0)->id());
  EXPECT_EQ(0u, service->extensions()->size());
  EXPECT_EQ(0u, service->disabled_extensions()->size());
  ASSERT_FALSE(service->HasInstalledExtensions());
}

// Tests that disabling and re-enabling an extension works.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) {
  ExtensionProcessManager* manager = browser()->profile()->
      GetExtensionProcessManager();
  ExtensionsService* service = browser()->profile()->GetExtensionsService();

  // Load an extension, expect the background page to be available.
  ASSERT_FALSE(service->HasInstalledExtensions());
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("good").AppendASCII("Extensions")
                    .AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
                    .AppendASCII("1.0")));
  ASSERT_EQ(1u, service->extensions()->size());
  EXPECT_EQ(0u, service->disabled_extensions()->size());
  Extension* extension = service->extensions()->at(0);
  EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));
  ASSERT_TRUE(service->HasInstalledExtensions());

  // After disabling, the background page should go away.
  service->DisableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa");
  EXPECT_EQ(0u, service->extensions()->size());
  EXPECT_EQ(1u, service->disabled_extensions()->size());
  EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension));
  ASSERT_TRUE(service->HasInstalledExtensions());

  // And bring it back.
  service->EnableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa");
  EXPECT_EQ(1u, service->extensions()->size());
  EXPECT_EQ(0u, service->disabled_extensions()->size());
  EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));
  ASSERT_TRUE(service->HasInstalledExtensions());
}

// TODO(asargent): This test seems to crash on linux buildbots.
// (http://crbug.com/31737)
#if !defined(OS_LINUX)
// Tests extension autoupdate.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) {
  FilePath basedir = test_data_dir_.AppendASCII("autoupdate");
  // Note: This interceptor gets requests on the IO thread.
  scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor());
  URLFetcher::enable_interception_for_tests(true);

  interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest",
                                     basedir.AppendASCII("manifest_v2.xml"));
  interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx",
                                     basedir.AppendASCII("v2.crx"));

  // Install version 1 of the extension.
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  ASSERT_FALSE(service->HasInstalledExtensions());
  ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v1.crx"), 1));
  const ExtensionList* extensions = service->extensions();
  ASSERT_TRUE(service->HasInstalledExtensions());
  ASSERT_EQ(1u, extensions->size());
  ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
  ASSERT_EQ("1.0", extensions->at(0)->VersionString());

  // We don't want autoupdate blacklist checks.
  service->updater()->set_blacklist_checks_enabled(false);

  // Run autoupdate and make sure version 2 of the extension was installed.
  service->updater()->CheckNow();
  ASSERT_TRUE(WaitForExtensionInstall());
  extensions = service->extensions();
  ASSERT_EQ(1u, extensions->size());
  ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
  ASSERT_EQ("2.0", extensions->at(0)->VersionString());

  // Now try doing an update to version 3, which has been incorrectly
  // signed. This should fail.
  interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest",
                                     basedir.AppendASCII("manifest_v3.xml"));
  interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx",
                                     basedir.AppendASCII("v3.crx"));

  service->updater()->CheckNow();
  ASSERT_TRUE(WaitForExtensionInstallError());

  // Make sure the extension state is the same as before.
  extensions = service->extensions();
  ASSERT_EQ(1u, extensions->size());
  ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
  ASSERT_EQ("2.0", extensions->at(0)->VersionString());
}
#endif  // !defined(OS_LINUX)
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/sync/notifier/chrome_system_resources.h"

#include <cstdlib>
#include <cstring>
#include <string>

#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/sync/notifier/invalidation_util.h"

namespace sync_notifier {

ChromeSystemResources::ChromeSystemResources() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
}

ChromeSystemResources::~ChromeSystemResources() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  StopScheduler();
}

invalidation::Time ChromeSystemResources::current_time() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  return base::Time::Now();
}

void ChromeSystemResources::StartScheduler() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  scoped_runnable_method_factory_.reset(
      new ScopedRunnableMethodFactory<ChromeSystemResources>(this));
}

void ChromeSystemResources::StopScheduler() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  scoped_runnable_method_factory_.reset();
  STLDeleteElements(&posted_tasks_);
}

void ChromeSystemResources::ScheduleWithDelay(
    invalidation::TimeDelta delay,
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  Task* task_to_post = MakeTaskToPost(task);
  if (!task_to_post) {
    return;
  }
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE, task_to_post, delay.InMillisecondsRoundedUp());
}

void ChromeSystemResources::ScheduleImmediately(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  Task* task_to_post = MakeTaskToPost(task);
  if (!task_to_post) {
    return;
  }
  MessageLoop::current()->PostTask(FROM_HERE, task_to_post);
}

// The listener thread is just our current thread.
void ChromeSystemResources::ScheduleOnListenerThread(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  ScheduleImmediately(task);
}

// We're already on a separate thread, so always return true.
bool ChromeSystemResources::IsRunningOnInternalThread() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  return true;
}

void ChromeSystemResources::Log(
    LogLevel level, const char* file, int line,
    const char* format, ...) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  logging::LogSeverity log_severity = logging::LOG_INFO;
  switch (level) {
    case INFO_LEVEL:
      log_severity = logging::LOG_INFO;
      break;
    case WARNING_LEVEL:
      log_severity = logging::LOG_WARNING;
      break;
    case ERROR_LEVEL:
      log_severity = logging::LOG_ERROR;
      break;
  }
  // We treat LOG(INFO) as VLOG(1).
  if ((log_severity >= logging::GetMinLogLevel()) &&
      ((log_severity != logging::LOG_INFO) ||
       (1 <= logging::GetVlogLevelHelper(file, ::strlen(file))))) {
    va_list ap;
    va_start(ap, format);
    std::string result;
    StringAppendV(&result, format, ap);
    logging::LogMessage(file, line, log_severity).stream() << result;
    va_end(ap);
  }
}

void ChromeSystemResources::WriteState(
    const invalidation::string& state,
    invalidation::StorageCallback* callback) {
  // TODO(akalin): Write the given state to persistent storage.
  callback->Run(false);
  delete callback;
}

Task* ChromeSystemResources::MakeTaskToPost(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  DCHECK(invalidation::IsCallbackRepeatable(task));
  if (!scoped_runnable_method_factory_.get()) {
    delete task;
    return NULL;
  }
  posted_tasks_.insert(task);
  Task* task_to_post =
      scoped_runnable_method_factory_->NewRunnableMethod(
          &ChromeSystemResources::RunPostedTask, task);
  return task_to_post;
}

void ChromeSystemResources::RunPostedTask(invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  RunAndDeleteClosure(task);
  posted_tasks_.erase(task);
}

}  // namespace sync_notifier
<commit_msg>[Sync] Fixed flipped return value from 61851.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/sync/notifier/chrome_system_resources.h"

#include <cstdlib>
#include <cstring>
#include <string>

#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/sync/notifier/invalidation_util.h"

namespace sync_notifier {

ChromeSystemResources::ChromeSystemResources() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
}

ChromeSystemResources::~ChromeSystemResources() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  StopScheduler();
}

invalidation::Time ChromeSystemResources::current_time() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  return base::Time::Now();
}

void ChromeSystemResources::StartScheduler() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  scoped_runnable_method_factory_.reset(
      new ScopedRunnableMethodFactory<ChromeSystemResources>(this));
}

void ChromeSystemResources::StopScheduler() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  scoped_runnable_method_factory_.reset();
  STLDeleteElements(&posted_tasks_);
}

void ChromeSystemResources::ScheduleWithDelay(
    invalidation::TimeDelta delay,
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  Task* task_to_post = MakeTaskToPost(task);
  if (!task_to_post) {
    return;
  }
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE, task_to_post, delay.InMillisecondsRoundedUp());
}

void ChromeSystemResources::ScheduleImmediately(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  Task* task_to_post = MakeTaskToPost(task);
  if (!task_to_post) {
    return;
  }
  MessageLoop::current()->PostTask(FROM_HERE, task_to_post);
}

// The listener thread is just our current thread (i.e., the
// notifications thread).
void ChromeSystemResources::ScheduleOnListenerThread(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  ScheduleImmediately(task);
}

// 'Internal thread' means 'not the listener thread'.  Since the
// listener thread is the notifications thread, always return false.
bool ChromeSystemResources::IsRunningOnInternalThread() {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  return false;
}

void ChromeSystemResources::Log(
    LogLevel level, const char* file, int line,
    const char* format, ...) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  logging::LogSeverity log_severity = logging::LOG_INFO;
  switch (level) {
    case INFO_LEVEL:
      log_severity = logging::LOG_INFO;
      break;
    case WARNING_LEVEL:
      log_severity = logging::LOG_WARNING;
      break;
    case ERROR_LEVEL:
      log_severity = logging::LOG_ERROR;
      break;
  }
  // We treat LOG(INFO) as VLOG(1).
  if ((log_severity >= logging::GetMinLogLevel()) &&
      ((log_severity != logging::LOG_INFO) ||
       (1 <= logging::GetVlogLevelHelper(file, ::strlen(file))))) {
    va_list ap;
    va_start(ap, format);
    std::string result;
    StringAppendV(&result, format, ap);
    logging::LogMessage(file, line, log_severity).stream() << result;
    va_end(ap);
  }
}

void ChromeSystemResources::WriteState(
    const invalidation::string& state,
    invalidation::StorageCallback* callback) {
  // TODO(akalin): Write the given state to persistent storage.
  callback->Run(false);
  delete callback;
}

Task* ChromeSystemResources::MakeTaskToPost(
    invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  DCHECK(invalidation::IsCallbackRepeatable(task));
  if (!scoped_runnable_method_factory_.get()) {
    delete task;
    return NULL;
  }
  posted_tasks_.insert(task);
  Task* task_to_post =
      scoped_runnable_method_factory_->NewRunnableMethod(
          &ChromeSystemResources::RunPostedTask, task);
  return task_to_post;
}

void ChromeSystemResources::RunPostedTask(invalidation::Closure* task) {
  DCHECK(non_thread_safe_.CalledOnValidThread());
  RunAndDeleteClosure(task);
  posted_tasks_.erase(task);
}

}  // namespace sync_notifier
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2016 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library 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 a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

#include "grins_config.h"

#ifdef GRINS_HAVE_CPPUNIT

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>

#include "test_comm.h"
#include "grins_test_paths.h"

// GRINS
#include "grins/grins_enums.h"
#include "grins/mesh_builder.h"
#include "grins/rayfire_mesh.h"
#include "grins/math_constants.h"

// libMesh
#include "libmesh/elem.h"
#include "libmesh/getpot.h"
#include "libmesh/face_quad4.h"
#include "libmesh/face_quad9.h"
#include "libmesh/fe_interface.h"
#include "libmesh/mesh_refinement.h"

namespace GRINSTesting
{
  class RayfireTestAMR : public CppUnit::TestCase
  {
  public:
    CPPUNIT_TEST_SUITE( RayfireTestAMR );

    CPPUNIT_TEST( single_elems );
    CPPUNIT_TEST( through_vertex_postrefinment );
    CPPUNIT_TEST( large_2D_mesh );
    CPPUNIT_TEST( refine_elem_not_on_rayfire );

    CPPUNIT_TEST_SUITE_END();

  public:

    //! Refine a single element
    void single_elems()
    {
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = build_quad4_elem();
      test_single_elem(mesh);

      mesh = build_quad9_elem();
      test_single_elem(mesh);
    }

    //! After refinement, the rayfire will travel through a vertex
    void through_vertex_postrefinment()
    {
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = build_quad4_elem();
      test_through_vertex(mesh);

      mesh = build_quad9_elem();
      test_through_vertex(mesh);
    }

    //! A 10x10 mesh with selectively refined elements
    void large_2D_mesh()
    {
      std::string filename = std::string(GRINS_TEST_UNIT_INPUT_SRCDIR)+"/mesh_quad4_100elem_2D.in";
      GetPot input_quad4(filename);
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = this->build_mesh(input_quad4);
      test_large_mesh(mesh);

      filename = std::string(GRINS_TEST_UNIT_INPUT_SRCDIR)+"/mesh_quad9_100elem_2D.in";
      GetPot input_quad9(filename);
      mesh = this->build_mesh(input_quad9);
      test_large_mesh(mesh);
    }

    //! Make sure refined elements not on the rayfire do not get added
    void refine_elem_not_on_rayfire()
    {
      std::string filename = std::string(GRINS_TEST_UNIT_INPUT_SRCDIR)+"/mesh_quad4_100elem_2D.in";
      GetPot input(filename);
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = this->build_mesh(input);

      libMesh::Point origin(0.0,6.5);
      libMesh::Point end_point(10.0,0.25);
      libMesh::Real theta = calc_theta(origin,end_point);

      GRINS::SharedPtr<GRINS::RayfireMesh> rayfire = new GRINS::RayfireMesh(origin,theta);
      rayfire->init(*mesh);

      // elem 0 is not along the rayfire
      mesh->elem(0)->set_refinement_flag(libMesh::Elem::RefinementState::REFINE);

      libMesh::MeshRefinement mr(*mesh);
      mr.refine_elements();

      rayfire->reinit(*mesh);

      // elem 0 should not be in the rayfire
      CPPUNIT_ASSERT( !(rayfire->map_to_rayfire_elem(mesh->elem(0)->id()) ) );

      // no children of elem 0 should be in the rayfire
      for (unsigned int i=0; i<4; i++)
        CPPUNIT_ASSERT( !(rayfire->map_to_rayfire_elem( mesh->elem(0)->child(i)->id() ) ) );
    }

  private:

    libMesh::Real calc_theta(libMesh::Point& start, libMesh::Point end)
    {
      return std::atan2( (end(1)-start(1)), (end(0)-start(0)) );
    }

    GRINS::SharedPtr<libMesh::UnstructuredMesh> build_mesh( const GetPot& input )
    {
      GRINS::MeshBuilder mesh_builder;
      return mesh_builder.build( input, *TestCommWorld );
    }

    //! Build a single square QUAD4
    GRINS::SharedPtr<libMesh::UnstructuredMesh> build_quad4_elem()
    {
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = new libMesh::SerialMesh(*TestCommWorld);

      mesh->set_mesh_dimension(2);

      mesh->add_point( libMesh::Point(0.0,0.0),0 );
      mesh->add_point( libMesh::Point(1.0,0.0),1 );
      mesh->add_point( libMesh::Point(1.0,1.0),2 );
      mesh->add_point( libMesh::Point(0.0,1.0),3 );

      libMesh::Elem* elem = mesh->add_elem( new libMesh::Quad4 );
      for (unsigned int n=0; n<4; n++)
        elem->set_node(n) = mesh->node_ptr(n);

      mesh->prepare_for_use();

      return mesh;
    }

    //! Build a single square QUAD9
    GRINS::SharedPtr<libMesh::UnstructuredMesh> build_quad9_elem()
    {
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = new libMesh::SerialMesh(*TestCommWorld);

      mesh->set_mesh_dimension(2);

      mesh->add_point( libMesh::Point(0.0,0.0),0 );
      mesh->add_point( libMesh::Point(1.0,0.0),1 );
      mesh->add_point( libMesh::Point(1.0,1.0),2 );
      mesh->add_point( libMesh::Point(0.0,1.0),3 );
      mesh->add_point( libMesh::Point(0.5,0.0),4 );
      mesh->add_point( libMesh::Point(1.0,0.5),5 );
      mesh->add_point( libMesh::Point(0.5,1.0),6 );
      mesh->add_point( libMesh::Point(0.0,0.5),7 );
      mesh->add_point( libMesh::Point(0.5,0.5),8 );

      libMesh::Elem* elem = mesh->add_elem( new libMesh::Quad9 );
      for (unsigned int n=0; n<9; n++)
        elem->set_node(n) = mesh->node_ptr(n);

      mesh->prepare_for_use();

      return mesh;
    }

    //! Runs the test on single square QUADs of unit length and width
    void test_single_elem(GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh)
    {
      CPPUNIT_ASSERT_EQUAL( mesh->n_elem(), (libMesh::dof_id_type)1 );

      libMesh::Point origin(0.0,0.1);
      libMesh::Point end_point(1.0,0.2);
      libMesh::Real theta = calc_theta(origin,end_point);

      GRINS::SharedPtr<GRINS::RayfireMesh> rayfire = new GRINS::RayfireMesh(origin,theta);
      rayfire->init(*mesh);

      libMesh::Elem* elem = mesh->elem(0);
      CPPUNIT_ASSERT(elem);

      elem->set_refinement_flag(libMesh::Elem::RefinementState::REFINE);

      libMesh::MeshRefinement mr(*mesh);
      mr.refine_elements();

      rayfire->reinit(*mesh);

      const libMesh::Elem* rayfire_elem0 = rayfire->map_to_rayfire_elem( elem->child(0)->id() );
      CPPUNIT_ASSERT(rayfire_elem0);

      const libMesh::Elem* rayfire_elem1 = rayfire->map_to_rayfire_elem( elem->child(1)->id() );
      CPPUNIT_ASSERT(rayfire_elem1);

      CPPUNIT_ASSERT( (rayfire_elem0->get_node(0))->absolute_fuzzy_equals(origin) );
      CPPUNIT_ASSERT( (rayfire_elem0->get_node(1))->absolute_fuzzy_equals(libMesh::Point(0.5,0.15)) );
      CPPUNIT_ASSERT( (rayfire_elem1->get_node(0))->absolute_fuzzy_equals(libMesh::Point(0.5,0.15)) );
      CPPUNIT_ASSERT( (rayfire_elem1->get_node(1))->absolute_fuzzy_equals(end_point) );
    }

    void test_through_vertex(GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh)
    {
      libMesh::Point origin(0.0,0.0);
      libMesh::Point end_point(1.0,1.0);
      libMesh::Real theta = calc_theta(origin,end_point);

      GRINS::SharedPtr<GRINS::RayfireMesh> rayfire = new GRINS::RayfireMesh(origin,theta);
      rayfire->init(*mesh);

      libMesh::Elem* elem = mesh->elem(0);
      CPPUNIT_ASSERT(elem);

      elem->set_refinement_flag(libMesh::Elem::RefinementState::REFINE);

      libMesh::MeshRefinement mr(*mesh);
      mr.refine_elements();

      rayfire->reinit(*mesh);

      const libMesh::Elem* rayfire_elem0 = rayfire->map_to_rayfire_elem( elem->child(0)->id() );
      CPPUNIT_ASSERT(rayfire_elem0);

      const libMesh::Elem* rayfire_elem1 = rayfire->map_to_rayfire_elem( elem->child(3)->id() );
      CPPUNIT_ASSERT(rayfire_elem1);

      CPPUNIT_ASSERT( (rayfire_elem0->get_node(0))->absolute_fuzzy_equals(origin) );
      CPPUNIT_ASSERT( (rayfire_elem0->get_node(1))->absolute_fuzzy_equals(libMesh::Point(0.5,0.5)) );
      CPPUNIT_ASSERT( (rayfire_elem1->get_node(0))->absolute_fuzzy_equals(libMesh::Point(0.5,0.5)) );
      CPPUNIT_ASSERT( (rayfire_elem1->get_node(1))->absolute_fuzzy_equals(end_point) );
    }

    //! Refine specific elements on a large mesh
    void test_large_mesh(GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh)
    {
      libMesh::Point origin(0.0,6.5);
      libMesh::Point end_point(10.0,0.25);
      libMesh::Real theta = calc_theta(origin,end_point);

      GRINS::SharedPtr<GRINS::RayfireMesh> rayfire = new GRINS::RayfireMesh(origin,theta);
      rayfire->init(*mesh);

      // manually refine specific elements
      // map index 0: main_elem id to refine
      // map index 1: children that should be in the rayfire post-refinement
      std::map<unsigned int,std::vector<unsigned int> > refine_elems;
      refine_elems[60] = std::vector<unsigned int>();
      refine_elems[60].push_back(0);
      refine_elems[60].push_back(1);

      refine_elems[52] = std::vector<unsigned int>();
      refine_elems[52].push_back(0);

      refine_elems[34] = std::vector<unsigned int>();
      refine_elems[34].push_back(1);
      refine_elems[34].push_back(2);
      refine_elems[34].push_back(3);

      refine_elems[25] = std::vector<unsigned int>();
      refine_elems[25].push_back(3);

      refine_elems[26] = std::vector<unsigned int>();
      refine_elems[26].push_back(0);
      refine_elems[26].push_back(1);
      refine_elems[26].push_back(2);

      refine_elems[17] = std::vector<unsigned int>();
      refine_elems[17].push_back(2);
      refine_elems[17].push_back(3);

      refine_elems[9] = std::vector<unsigned int>();
      refine_elems[9].push_back(1);
      refine_elems[9].push_back(2);
      refine_elems[9].push_back(3);

      // check to make sure those elements are along the rayfire
      // and then set their refinement flags
      std::map<unsigned int,std::vector<unsigned int> >::iterator it = refine_elems.begin();
      for(; it != refine_elems.end(); it++)
        {
          libMesh::Elem* elem = mesh->elem( it->first );
          CPPUNIT_ASSERT( rayfire->map_to_rayfire_elem(elem->id()) );
          elem->set_refinement_flag(libMesh::Elem::RefinementState::REFINE);
        }

      // refine the elements
      libMesh::MeshRefinement mr(*mesh);
      mr.refine_elements();

      // reinitialize the rayfire
      rayfire->reinit(*mesh);

      // check the refined elements and their children
      it = refine_elems.begin();
      for(; it != refine_elems.end(); it++)
        {
          libMesh::Elem* elem = mesh->elem( it->first );

          // make sure it was refined
          CPPUNIT_ASSERT_EQUAL( elem->refinement_flag(), libMesh::Elem::RefinementState::INACTIVE );

          // make sure it was deleted from the rayfire
          CPPUNIT_ASSERT( !( rayfire->map_to_rayfire_elem(elem->id()) ) );

          // check that the computed children are in the rayfire
          // and that the rest are not
          std::vector<unsigned int> children = it->second;
          unsigned int index = 0;
          for(unsigned int c=0; c<elem->n_children(); c++)
            {
              if (c==children[index] && index<children.size())
                {
                  index++;
                  std::cout <<it->first <<" child: " <<c <<std::endl;
                  CPPUNIT_ASSERT( rayfire->map_to_rayfire_elem( elem->child(c)->id() ) );
                }
              else
                CPPUNIT_ASSERT( !(rayfire->map_to_rayfire_elem( elem->child(c)->id() )) );
            }
        }
    }

  };

  CPPUNIT_TEST_SUITE_REGISTRATION( RayfireTestAMR );

} // end namespace GRINSTesting

#endif // GRINS_HAVE_CPPUNIT
<commit_msg>Add another missing serial_mesh.h include<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2016 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library 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 a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

#include "grins_config.h"

#ifdef GRINS_HAVE_CPPUNIT

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>

#include "test_comm.h"
#include "grins_test_paths.h"

// GRINS
#include "grins/grins_enums.h"
#include "grins/mesh_builder.h"
#include "grins/rayfire_mesh.h"
#include "grins/math_constants.h"

// libMesh
#include "libmesh/elem.h"
#include "libmesh/getpot.h"
#include "libmesh/face_quad4.h"
#include "libmesh/face_quad9.h"
#include "libmesh/fe_interface.h"
#include "libmesh/mesh_refinement.h"
#include "libmesh/serial_mesh.h"

namespace GRINSTesting
{
  class RayfireTestAMR : public CppUnit::TestCase
  {
  public:
    CPPUNIT_TEST_SUITE( RayfireTestAMR );

    CPPUNIT_TEST( single_elems );
    CPPUNIT_TEST( through_vertex_postrefinment );
    CPPUNIT_TEST( large_2D_mesh );
    CPPUNIT_TEST( refine_elem_not_on_rayfire );

    CPPUNIT_TEST_SUITE_END();

  public:

    //! Refine a single element
    void single_elems()
    {
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = build_quad4_elem();
      test_single_elem(mesh);

      mesh = build_quad9_elem();
      test_single_elem(mesh);
    }

    //! After refinement, the rayfire will travel through a vertex
    void through_vertex_postrefinment()
    {
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = build_quad4_elem();
      test_through_vertex(mesh);

      mesh = build_quad9_elem();
      test_through_vertex(mesh);
    }

    //! A 10x10 mesh with selectively refined elements
    void large_2D_mesh()
    {
      std::string filename = std::string(GRINS_TEST_UNIT_INPUT_SRCDIR)+"/mesh_quad4_100elem_2D.in";
      GetPot input_quad4(filename);
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = this->build_mesh(input_quad4);
      test_large_mesh(mesh);

      filename = std::string(GRINS_TEST_UNIT_INPUT_SRCDIR)+"/mesh_quad9_100elem_2D.in";
      GetPot input_quad9(filename);
      mesh = this->build_mesh(input_quad9);
      test_large_mesh(mesh);
    }

    //! Make sure refined elements not on the rayfire do not get added
    void refine_elem_not_on_rayfire()
    {
      std::string filename = std::string(GRINS_TEST_UNIT_INPUT_SRCDIR)+"/mesh_quad4_100elem_2D.in";
      GetPot input(filename);
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = this->build_mesh(input);

      libMesh::Point origin(0.0,6.5);
      libMesh::Point end_point(10.0,0.25);
      libMesh::Real theta = calc_theta(origin,end_point);

      GRINS::SharedPtr<GRINS::RayfireMesh> rayfire = new GRINS::RayfireMesh(origin,theta);
      rayfire->init(*mesh);

      // elem 0 is not along the rayfire
      mesh->elem(0)->set_refinement_flag(libMesh::Elem::RefinementState::REFINE);

      libMesh::MeshRefinement mr(*mesh);
      mr.refine_elements();

      rayfire->reinit(*mesh);

      // elem 0 should not be in the rayfire
      CPPUNIT_ASSERT( !(rayfire->map_to_rayfire_elem(mesh->elem(0)->id()) ) );

      // no children of elem 0 should be in the rayfire
      for (unsigned int i=0; i<4; i++)
        CPPUNIT_ASSERT( !(rayfire->map_to_rayfire_elem( mesh->elem(0)->child(i)->id() ) ) );
    }

  private:

    libMesh::Real calc_theta(libMesh::Point& start, libMesh::Point end)
    {
      return std::atan2( (end(1)-start(1)), (end(0)-start(0)) );
    }

    GRINS::SharedPtr<libMesh::UnstructuredMesh> build_mesh( const GetPot& input )
    {
      GRINS::MeshBuilder mesh_builder;
      return mesh_builder.build( input, *TestCommWorld );
    }

    //! Build a single square QUAD4
    GRINS::SharedPtr<libMesh::UnstructuredMesh> build_quad4_elem()
    {
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = new libMesh::SerialMesh(*TestCommWorld);

      mesh->set_mesh_dimension(2);

      mesh->add_point( libMesh::Point(0.0,0.0),0 );
      mesh->add_point( libMesh::Point(1.0,0.0),1 );
      mesh->add_point( libMesh::Point(1.0,1.0),2 );
      mesh->add_point( libMesh::Point(0.0,1.0),3 );

      libMesh::Elem* elem = mesh->add_elem( new libMesh::Quad4 );
      for (unsigned int n=0; n<4; n++)
        elem->set_node(n) = mesh->node_ptr(n);

      mesh->prepare_for_use();

      return mesh;
    }

    //! Build a single square QUAD9
    GRINS::SharedPtr<libMesh::UnstructuredMesh> build_quad9_elem()
    {
      GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh = new libMesh::SerialMesh(*TestCommWorld);

      mesh->set_mesh_dimension(2);

      mesh->add_point( libMesh::Point(0.0,0.0),0 );
      mesh->add_point( libMesh::Point(1.0,0.0),1 );
      mesh->add_point( libMesh::Point(1.0,1.0),2 );
      mesh->add_point( libMesh::Point(0.0,1.0),3 );
      mesh->add_point( libMesh::Point(0.5,0.0),4 );
      mesh->add_point( libMesh::Point(1.0,0.5),5 );
      mesh->add_point( libMesh::Point(0.5,1.0),6 );
      mesh->add_point( libMesh::Point(0.0,0.5),7 );
      mesh->add_point( libMesh::Point(0.5,0.5),8 );

      libMesh::Elem* elem = mesh->add_elem( new libMesh::Quad9 );
      for (unsigned int n=0; n<9; n++)
        elem->set_node(n) = mesh->node_ptr(n);

      mesh->prepare_for_use();

      return mesh;
    }

    //! Runs the test on single square QUADs of unit length and width
    void test_single_elem(GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh)
    {
      CPPUNIT_ASSERT_EQUAL( mesh->n_elem(), (libMesh::dof_id_type)1 );

      libMesh::Point origin(0.0,0.1);
      libMesh::Point end_point(1.0,0.2);
      libMesh::Real theta = calc_theta(origin,end_point);

      GRINS::SharedPtr<GRINS::RayfireMesh> rayfire = new GRINS::RayfireMesh(origin,theta);
      rayfire->init(*mesh);

      libMesh::Elem* elem = mesh->elem(0);
      CPPUNIT_ASSERT(elem);

      elem->set_refinement_flag(libMesh::Elem::RefinementState::REFINE);

      libMesh::MeshRefinement mr(*mesh);
      mr.refine_elements();

      rayfire->reinit(*mesh);

      const libMesh::Elem* rayfire_elem0 = rayfire->map_to_rayfire_elem( elem->child(0)->id() );
      CPPUNIT_ASSERT(rayfire_elem0);

      const libMesh::Elem* rayfire_elem1 = rayfire->map_to_rayfire_elem( elem->child(1)->id() );
      CPPUNIT_ASSERT(rayfire_elem1);

      CPPUNIT_ASSERT( (rayfire_elem0->get_node(0))->absolute_fuzzy_equals(origin) );
      CPPUNIT_ASSERT( (rayfire_elem0->get_node(1))->absolute_fuzzy_equals(libMesh::Point(0.5,0.15)) );
      CPPUNIT_ASSERT( (rayfire_elem1->get_node(0))->absolute_fuzzy_equals(libMesh::Point(0.5,0.15)) );
      CPPUNIT_ASSERT( (rayfire_elem1->get_node(1))->absolute_fuzzy_equals(end_point) );
    }

    void test_through_vertex(GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh)
    {
      libMesh::Point origin(0.0,0.0);
      libMesh::Point end_point(1.0,1.0);
      libMesh::Real theta = calc_theta(origin,end_point);

      GRINS::SharedPtr<GRINS::RayfireMesh> rayfire = new GRINS::RayfireMesh(origin,theta);
      rayfire->init(*mesh);

      libMesh::Elem* elem = mesh->elem(0);
      CPPUNIT_ASSERT(elem);

      elem->set_refinement_flag(libMesh::Elem::RefinementState::REFINE);

      libMesh::MeshRefinement mr(*mesh);
      mr.refine_elements();

      rayfire->reinit(*mesh);

      const libMesh::Elem* rayfire_elem0 = rayfire->map_to_rayfire_elem( elem->child(0)->id() );
      CPPUNIT_ASSERT(rayfire_elem0);

      const libMesh::Elem* rayfire_elem1 = rayfire->map_to_rayfire_elem( elem->child(3)->id() );
      CPPUNIT_ASSERT(rayfire_elem1);

      CPPUNIT_ASSERT( (rayfire_elem0->get_node(0))->absolute_fuzzy_equals(origin) );
      CPPUNIT_ASSERT( (rayfire_elem0->get_node(1))->absolute_fuzzy_equals(libMesh::Point(0.5,0.5)) );
      CPPUNIT_ASSERT( (rayfire_elem1->get_node(0))->absolute_fuzzy_equals(libMesh::Point(0.5,0.5)) );
      CPPUNIT_ASSERT( (rayfire_elem1->get_node(1))->absolute_fuzzy_equals(end_point) );
    }

    //! Refine specific elements on a large mesh
    void test_large_mesh(GRINS::SharedPtr<libMesh::UnstructuredMesh> mesh)
    {
      libMesh::Point origin(0.0,6.5);
      libMesh::Point end_point(10.0,0.25);
      libMesh::Real theta = calc_theta(origin,end_point);

      GRINS::SharedPtr<GRINS::RayfireMesh> rayfire = new GRINS::RayfireMesh(origin,theta);
      rayfire->init(*mesh);

      // manually refine specific elements
      // map index 0: main_elem id to refine
      // map index 1: children that should be in the rayfire post-refinement
      std::map<unsigned int,std::vector<unsigned int> > refine_elems;
      refine_elems[60] = std::vector<unsigned int>();
      refine_elems[60].push_back(0);
      refine_elems[60].push_back(1);

      refine_elems[52] = std::vector<unsigned int>();
      refine_elems[52].push_back(0);

      refine_elems[34] = std::vector<unsigned int>();
      refine_elems[34].push_back(1);
      refine_elems[34].push_back(2);
      refine_elems[34].push_back(3);

      refine_elems[25] = std::vector<unsigned int>();
      refine_elems[25].push_back(3);

      refine_elems[26] = std::vector<unsigned int>();
      refine_elems[26].push_back(0);
      refine_elems[26].push_back(1);
      refine_elems[26].push_back(2);

      refine_elems[17] = std::vector<unsigned int>();
      refine_elems[17].push_back(2);
      refine_elems[17].push_back(3);

      refine_elems[9] = std::vector<unsigned int>();
      refine_elems[9].push_back(1);
      refine_elems[9].push_back(2);
      refine_elems[9].push_back(3);

      // check to make sure those elements are along the rayfire
      // and then set their refinement flags
      std::map<unsigned int,std::vector<unsigned int> >::iterator it = refine_elems.begin();
      for(; it != refine_elems.end(); it++)
        {
          libMesh::Elem* elem = mesh->elem( it->first );
          CPPUNIT_ASSERT( rayfire->map_to_rayfire_elem(elem->id()) );
          elem->set_refinement_flag(libMesh::Elem::RefinementState::REFINE);
        }

      // refine the elements
      libMesh::MeshRefinement mr(*mesh);
      mr.refine_elements();

      // reinitialize the rayfire
      rayfire->reinit(*mesh);

      // check the refined elements and their children
      it = refine_elems.begin();
      for(; it != refine_elems.end(); it++)
        {
          libMesh::Elem* elem = mesh->elem( it->first );

          // make sure it was refined
          CPPUNIT_ASSERT_EQUAL( elem->refinement_flag(), libMesh::Elem::RefinementState::INACTIVE );

          // make sure it was deleted from the rayfire
          CPPUNIT_ASSERT( !( rayfire->map_to_rayfire_elem(elem->id()) ) );

          // check that the computed children are in the rayfire
          // and that the rest are not
          std::vector<unsigned int> children = it->second;
          unsigned int index = 0;
          for(unsigned int c=0; c<elem->n_children(); c++)
            {
              if (c==children[index] && index<children.size())
                {
                  index++;
                  std::cout <<it->first <<" child: " <<c <<std::endl;
                  CPPUNIT_ASSERT( rayfire->map_to_rayfire_elem( elem->child(c)->id() ) );
                }
              else
                CPPUNIT_ASSERT( !(rayfire->map_to_rayfire_elem( elem->child(c)->id() )) );
            }
        }
    }

  };

  CPPUNIT_TEST_SUITE_REGISTRATION( RayfireTestAMR );

} // end namespace GRINSTesting

#endif // GRINS_HAVE_CPPUNIT
<|endoftext|>


<commit_before>
/*
 * Large parts of this file were copied from the following repo:
 * https://github.com/chris-wood/dtls-test
 *
 * The BIO part is strongly inspired by the following file:
 * https://gist.github.com/darrenjs/4645f115d10aa4b5cebf57483ec82eca
 *
 *
 * Use this command to create the certificate:
 * openssl req -x509 -newkey rsa:2048 -days 3650 -nodes -keyout server-key.pem
 * -out server-cert.pem
 */

#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <openssl/conf.h>
#include <openssl/dh.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/socket.h>
#include <thread>
#include <unistd.h>
#include <unordered_map>
#include <vector>

typedef unsigned int uint;

using namespace std;

struct conn {
	SSL *ssl;
	BIO *wbio;
	BIO *rbio;
};

// Taken from:
// https://stackoverflow.com/a/20602159
struct pairhash {
public:
	template <typename T, typename U> std::size_t operator()(const std::pair<T, U> &x) const {
		return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
	}
};

void dtls_Begin() {
	SSL_library_init();
	SSL_load_error_strings();
	ERR_load_BIO_strings();
	OpenSSL_add_all_algorithms();
}

static int _ssl_verify_peer(int ok, X509_STORE_CTX *ctx) {
	(void)ok;
	(void)ctx;
	return 1;
}

static int _createSocket(int port) {
	int sock;
	struct sockaddr_in addr;

	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0) {
		perror("Unable to create socket");
		exit(EXIT_FAILURE);
	}

	if (::bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
		perror("Unable to bind");
		exit(EXIT_FAILURE);
	}

	return sock;
}

int dtls_InitContextFromKeystore(SSL_CTX **ctx, const char *keyname) {
	int result = 0;

	// Create a new context using DTLS
	*ctx = SSL_CTX_new(DTLS_method());
	if (ctx == NULL) {
		printf("Error: cannot create SSL_CTX.\n");
		ERR_print_errors_fp(stderr);
		return -1;
	}

	// Set our supported ciphers
	result = SSL_CTX_set_cipher_list(*ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
	if (result != 1) {
		printf("Error: cannot set the cipher list.\n");
		ERR_print_errors_fp(stderr);
		return -2;
	}

	// The client doesn't have to send it's certificate
	SSL_CTX_set_verify(*ctx, SSL_VERIFY_PEER, _ssl_verify_peer);

	// Load key and certificate
	char certfile[1024];
	char keyfile[1024];
	sprintf(certfile, "./%s-cert.pem", keyname);
	sprintf(keyfile, "./%s-key.pem", keyname);

	// Load the certificate file; contains also the public key
	result = SSL_CTX_use_certificate_file(*ctx, certfile, SSL_FILETYPE_PEM);
	if (result != 1) {
		printf("Error: cannot load certificate file.\n");
		ERR_print_errors_fp(stderr);
		return -4;
	}

	// Load private key
	result = SSL_CTX_use_PrivateKey_file(*ctx, keyfile, SSL_FILETYPE_PEM);
	if (result != 1) {
		printf("Error: cannot load private key file.\n");
		ERR_print_errors_fp(stderr);
		return -5;
	}

	// Check if the private key is valid
	result = SSL_CTX_check_private_key(*ctx);
	if (result != 1) {
		printf("Error: checking the private key failed. \n");
		ERR_print_errors_fp(stderr);
		return -6;
	}

	return 0;
}

conn *createNewConn(SSL_CTX *ctx) {
	SSL *ssl = SSL_new(ctx);
	if (ssl == NULL) {
		cout << "SSL_new() failed" << endl;
		exit(EXIT_FAILURE);
	}

	BIO *wbio = BIO_new(BIO_s_memQ());
	if (wbio == NULL) {
		cout << "BIO_new() failed" << endl;
		exit(EXIT_FAILURE);
	}

	BIO *rbio = BIO_new(BIO_s_memQ());
	if (rbio == NULL) {
		cout << "BIO_new() failed" << endl;
		exit(EXIT_FAILURE);
	}

	SSL_set_accept_state(ssl);
	SSL_set_bio(ssl, rbio, wbio);

	conn *c = new conn();

	c->ssl = ssl;
	c->wbio = wbio;
	c->rbio = rbio;

	return c;
}

int handlePacket(int fd, struct conn *conn, char *buf, int bufLen, int recvBytes,
	struct sockaddr_in *src_addr) {

	if (BIO_write(conn->rbio, buf, recvBytes) != recvBytes) {
		cout << "BIO_write() failed" << endl;
		exit(EXIT_FAILURE);
	}

	if (SSL_is_init_finished(conn->ssl)) {
		// Here the handshake is already finished

		// Try to read incoming byte from the connection
		int readLen = SSL_read(conn->ssl, buf, bufLen);
		if ((readLen <= 0) && (SSL_get_shutdown(conn->ssl) == 0)) {
			cout << "SSL_read() failed" << endl;
			cout << "shutdown: " << SSL_get_shutdown(conn->ssl) << endl;
			exit(EXIT_FAILURE);
		}

		// Try to write the same bytes to the connection
		if (readLen > 0) {
			int writeLen = SSL_write(conn->ssl, buf, readLen);
			if (writeLen <= 0) {
				cout << "SSL_write() failed" << endl;
				exit(EXIT_FAILURE);
			}
		}
	} else {
		// We are currently conducting a handshake

		// The return code is pretty useless, throw it away
		SSL_accept(conn->ssl);
	}

	// Write out all data
	int readCount;
	while ((readCount = BIO_read(conn->wbio, buf, bufLen)) > 0) {
		int sendBytes = sendto(
			fd, buf, readCount, 0, (struct sockaddr *)src_addr, sizeof(struct sockaddr_in));
		if (sendBytes != readCount) {
			perror("sendto() failed");
			exit(EXIT_FAILURE);
		}
	}

	if (SSL_get_shutdown(conn->ssl) != 0) {
		if (SSL_shutdown(conn->ssl) == 1) {
			SSL_free(conn->ssl);
			delete (conn);
			return 1;
		}
	}

	return 0;
}

int main() {
	// Initialize whatever OpenSSL state is necessary to execute the DTLS protocol.
	dtls_Begin();

	SSL_CTX *ctx;

	if (dtls_InitContextFromKeystore(&ctx, "server") < 0) {
		exit(EXIT_FAILURE);
	}

	// Create the server UDP listener socket
	int sock = _createSocket(4433);

	unordered_map<pair<unsigned long, unsigned short>, struct conn *, pairhash> connections;

	char buf[2048];

	while (true) {
		struct sockaddr_in src_addr;
		socklen_t addrlen = sizeof(struct sockaddr_in);

		// Try and recv a packet
		int ret =
			recvfrom(sock, (void *)buf, 2048, 0, (struct sockaddr *)&src_addr, &addrlen);
		if (ret < 0) {
			perror("recvfrom failed");
			exit(EXIT_FAILURE);
		}

		// Look up if there already exists a connection
	conn_lockup:
		auto conn_it = connections.find({src_addr.sin_addr.s_addr, src_addr.sin_port});
		if (conn_it == connections.end()) {
			connections.insert(
				{{src_addr.sin_addr.s_addr, src_addr.sin_port}, createNewConn(ctx)});
			goto conn_lockup;
		}

		// Just double checking
		if (conn_it == connections.end()) {
			cout << "conn_it is invalid..." << endl;
			exit(EXIT_FAILURE);
		}

		if (handlePacket(sock, conn_it->second, buf, 2048, ret, &src_addr) == 1) {
			connections.erase(conn_it);
		}
	}

	close(sock);
}
<commit_msg>make the DTLS server more verbose<commit_after>
/*
 * Large parts of this file were copied from the following repo:
 * https://github.com/chris-wood/dtls-test
 *
 * The BIO part is strongly inspired by the following file:
 * https://gist.github.com/darrenjs/4645f115d10aa4b5cebf57483ec82eca
 *
 *
 * Use this command to create the certificate:
 * openssl req -x509 -newkey rsa:2048 -days 3650 -nodes -keyout server-key.pem
 * -out server-cert.pem
 */

#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <openssl/conf.h>
#include <openssl/dh.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/socket.h>
#include <thread>
#include <unistd.h>
#include <unordered_map>
#include <vector>

typedef unsigned int uint;

using namespace std;

struct conn {
	SSL *ssl;
	BIO *wbio;
	BIO *rbio;
};

// Taken from:
// https://stackoverflow.com/a/20602159
struct pairhash {
public:
	template <typename T, typename U> std::size_t operator()(const std::pair<T, U> &x) const {
		return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
	}
};

void dtls_Begin() {
	SSL_library_init();
	SSL_load_error_strings();
	ERR_load_BIO_strings();
	OpenSSL_add_all_algorithms();
}

static int _ssl_verify_peer(int ok, X509_STORE_CTX *ctx) {
	(void)ok;
	(void)ctx;
	return 1;
}

static int _createSocket(int port) {
	int sock;
	struct sockaddr_in addr;

	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0) {
		perror("Unable to create socket");
		exit(EXIT_FAILURE);
	}

	if (::bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
		perror("Unable to bind");
		exit(EXIT_FAILURE);
	}

	return sock;
}

int dtls_InitContextFromKeystore(SSL_CTX **ctx, const char *keyname) {
	int result = 0;

	// Create a new context using DTLS
	*ctx = SSL_CTX_new(DTLS_method());
	if (ctx == NULL) {
		printf("Error: cannot create SSL_CTX.\n");
		ERR_print_errors_fp(stderr);
		return -1;
	}

	// Set our supported ciphers
	result = SSL_CTX_set_cipher_list(*ctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
	if (result != 1) {
		printf("Error: cannot set the cipher list.\n");
		ERR_print_errors_fp(stderr);
		return -2;
	}

	// The client doesn't have to send it's certificate
	SSL_CTX_set_verify(*ctx, SSL_VERIFY_PEER, _ssl_verify_peer);

	// Load key and certificate
	char certfile[1024];
	char keyfile[1024];
	sprintf(certfile, "./%s-cert.pem", keyname);
	sprintf(keyfile, "./%s-key.pem", keyname);

	// Load the certificate file; contains also the public key
	result = SSL_CTX_use_certificate_file(*ctx, certfile, SSL_FILETYPE_PEM);
	if (result != 1) {
		printf("Error: cannot load certificate file.\n");
		printf("IN CASE YOU DIDN'T CREATE ONE:\n");
		printf("openssl req -x509 -newkey rsa:2048 -days 3650 -nodes -keyout server-key.pem "
			   "-out server-cert.pem\n\n");

		ERR_print_errors_fp(stderr);
		return -4;
	}

	// Load private key
	result = SSL_CTX_use_PrivateKey_file(*ctx, keyfile, SSL_FILETYPE_PEM);
	if (result != 1) {
		printf("Error: cannot load private key file.\n");
		ERR_print_errors_fp(stderr);
		return -5;
	}

	// Check if the private key is valid
	result = SSL_CTX_check_private_key(*ctx);
	if (result != 1) {
		printf("Error: checking the private key failed. \n");
		ERR_print_errors_fp(stderr);
		return -6;
	}

	return 0;
}

conn *createNewConn(SSL_CTX *ctx) {
	SSL *ssl = SSL_new(ctx);
	if (ssl == NULL) {
		cout << "SSL_new() failed" << endl;
		exit(EXIT_FAILURE);
	}

	BIO *wbio = BIO_new(BIO_s_memQ());
	if (wbio == NULL) {
		cout << "BIO_new() failed" << endl;
		exit(EXIT_FAILURE);
	}

	BIO *rbio = BIO_new(BIO_s_memQ());
	if (rbio == NULL) {
		cout << "BIO_new() failed" << endl;
		exit(EXIT_FAILURE);
	}

	SSL_set_accept_state(ssl);
	SSL_set_bio(ssl, rbio, wbio);

	conn *c = new conn();

	c->ssl = ssl;
	c->wbio = wbio;
	c->rbio = rbio;

	return c;
}

int handlePacket(int fd, struct conn *conn, char *buf, int bufLen, int recvBytes,
	struct sockaddr_in *src_addr) {

	if (BIO_write(conn->rbio, buf, recvBytes) != recvBytes) {
		cout << "BIO_write() failed" << endl;
		exit(EXIT_FAILURE);
	}

	if (SSL_is_init_finished(conn->ssl)) {
		// Here the handshake is already finished

		// Try to read incoming byte from the connection
		int readLen = SSL_read(conn->ssl, buf, bufLen);
		if ((readLen <= 0) && (SSL_get_shutdown(conn->ssl) == 0)) {
			cout << "SSL_read() failed" << endl;
			cout << "shutdown: " << SSL_get_shutdown(conn->ssl) << endl;
			exit(EXIT_FAILURE);
		}

		// Try to write the same bytes to the connection
		if (readLen > 0) {
			int writeLen = SSL_write(conn->ssl, buf, readLen);
			if (writeLen <= 0) {
				cout << "SSL_write() failed" << endl;
				exit(EXIT_FAILURE);
			}
		}
	} else {
		// We are currently conducting a handshake

		// The return code is pretty useless, throw it away
		SSL_accept(conn->ssl);
	}

	// Write out all data
	int readCount;
	while ((readCount = BIO_read(conn->wbio, buf, bufLen)) > 0) {
		int sendBytes = sendto(
			fd, buf, readCount, 0, (struct sockaddr *)src_addr, sizeof(struct sockaddr_in));
		if (sendBytes != readCount) {
			perror("sendto() failed");
			exit(EXIT_FAILURE);
		}
	}

	if (SSL_get_shutdown(conn->ssl) != 0) {
		if (SSL_shutdown(conn->ssl) == 1) {
			SSL_free(conn->ssl);
			delete (conn);
			return 1;
		}
	}

	return 0;
}

int main() {
	// Initialize whatever OpenSSL state is necessary to execute the DTLS protocol.
	dtls_Begin();

	SSL_CTX *ctx;

	if (dtls_InitContextFromKeystore(&ctx, "server") < 0) {
		exit(EXIT_FAILURE);
	}

	// Create the server UDP listener socket
	int sock = _createSocket(4433);

	unordered_map<pair<unsigned long, unsigned short>, struct conn *, pairhash> connections;

	char buf[2048];

	while (true) {
		struct sockaddr_in src_addr;
		socklen_t addrlen = sizeof(struct sockaddr_in);

		// Try and recv a packet
		int ret =
			recvfrom(sock, (void *)buf, 2048, 0, (struct sockaddr *)&src_addr, &addrlen);
		if (ret < 0) {
			perror("recvfrom failed");
			exit(EXIT_FAILURE);
		}

		// Look up if there already exists a connection
	conn_lockup:
		auto conn_it = connections.find({src_addr.sin_addr.s_addr, src_addr.sin_port});
		if (conn_it == connections.end()) {
			cout << "Connection from new client" << endl;
			connections.insert(
				{{src_addr.sin_addr.s_addr, src_addr.sin_port}, createNewConn(ctx)});
			goto conn_lockup;
		}

		// Just double checking
		if (conn_it == connections.end()) {
			cout << "conn_it is invalid..." << endl;
			exit(EXIT_FAILURE);
		}

		if (handlePacket(sock, conn_it->second, buf, 2048, ret, &src_addr) == 1) {
			connections.erase(conn_it);
		}
	}

	close(sock);
}
<|endoftext|>


<commit_before>///
/// @file      retdec/file_tests.cpp
/// @copyright (c) 2015 by Petr Zemek (s3rvac@gmail.com) and contributors
/// @license   MIT, see the @c LICENSE file for more details
/// @brief     Tests for the decompilation.
///

#include <gtest/gtest.h>

#include "retdec/file.h"
#include "retdec/internal/utilities/os.h"

using namespace testing;

namespace retdec {
namespace tests {

///
/// Tests for File.
///
class FileTests: public Test {};

TEST_F(FileTests,
FromContentWithNameReturnsFileWithCorrectContentAndName) {
	auto file = File::fromContentWithName("content", "file.txt");
	EXPECT_EQ("content", file->getContent());
	EXPECT_EQ("file.txt", file->getName());
}

TEST_F(FileTests,
FromFilesystemReturnsFileWithCorrectName) {
#ifdef RETDEC_OS_WINDOWS
	auto file = File::fromFilesystem(R"(C:\\/path/to/file.txt)")
#else
	auto file = File::fromFilesystem("/path/to/file.txt");
#endif
	EXPECT_EQ("file.txt", file->getName());
}

TEST_F(FileTests,
FromFilesystemWithOtherNameReturnsFileWithCorrectName) {
#ifdef RETDEC_OS_WINDOWS
	auto file = File::fromFilesystemWithOtherName(
		R"(C:\\/path/to/file.txt)", "other.txt")
#else
	auto file = File::fromFilesystemWithOtherName(
		"/path/to/file.txt", "other.txt");
#endif
	EXPECT_EQ("other.txt", file->getName());
}

} // namespace tests
} // namespace retdec
<commit_msg>Fix a typo in file_tests.cpp.<commit_after>///
/// @file      retdec/file_tests.cpp
/// @copyright (c) 2015 by Petr Zemek (s3rvac@gmail.com) and contributors
/// @license   MIT, see the @c LICENSE file for more details
/// @brief     Tests for the files.
///

#include <gtest/gtest.h>

#include "retdec/file.h"
#include "retdec/internal/utilities/os.h"

using namespace testing;

namespace retdec {
namespace tests {

///
/// Tests for File.
///
class FileTests: public Test {};

TEST_F(FileTests,
FromContentWithNameReturnsFileWithCorrectContentAndName) {
	auto file = File::fromContentWithName("content", "file.txt");
	EXPECT_EQ("content", file->getContent());
	EXPECT_EQ("file.txt", file->getName());
}

TEST_F(FileTests,
FromFilesystemReturnsFileWithCorrectName) {
#ifdef RETDEC_OS_WINDOWS
	auto file = File::fromFilesystem(R"(C:\\/path/to/file.txt)")
#else
	auto file = File::fromFilesystem("/path/to/file.txt");
#endif
	EXPECT_EQ("file.txt", file->getName());
}

TEST_F(FileTests,
FromFilesystemWithOtherNameReturnsFileWithCorrectName) {
#ifdef RETDEC_OS_WINDOWS
	auto file = File::fromFilesystemWithOtherName(
		R"(C:\\/path/to/file.txt)", "other.txt")
#else
	auto file = File::fromFilesystemWithOtherName(
		"/path/to/file.txt", "other.txt");
#endif
	EXPECT_EQ("other.txt", file->getName());
}

} // namespace tests
} // namespace retdec
<|endoftext|>


<commit_before>#include <chrono>
#include <iostream>
#include <memory>
#include <string.h>
#include "../lcd/LcdDisplay.h"
#include "../src2/HealthStatus.h"

using namespace std;
using namespace std::chrono;

int main() {
    unique_ptr<LcdDisplay> lcd(LcdDisplay::getLcdDisplayInstance());
    lcd->init();
    StatusInformation status;
    beacon_info beacon;
    memset(&beacon, sizeof(beacon), 0);
    status.setScannerID("Room206");

    // Add some events
    sprintf(beacon.uuid, "UUID-%.10d", 66);
    beacon.minor = 66;
    beacon.major = 1;
    beacon.manufacturer = 0xdead;
    beacon.code = 0xbeef;
    beacon.count = 3;
    beacon.rssi = -68;
    milliseconds now = duration_cast<milliseconds >(high_resolution_clock::now().time_since_epoch());
    beacon.time = now.count();
    status.addEvent(beacon, false);

    beacon.isHeartbeat = true;
    beacon.minor = 206;
    beacon.time += 10;
    status.addEvent(beacon, true);

    beacon.isHeartbeat = false;
    beacon.minor = 56;
    beacon.time += 10;
    status.addEvent(beacon, false);

    beacon.isHeartbeat = true;
    beacon.minor = 206;
    beacon.time += 10;
    status.addEvent(beacon, true);

    HealthStatus healthStatus;
    healthStatus.calculateStatus(status);
    Properties statusProps = healthStatus.getLastStatus();
    char tmp[20];
    snprintf(tmp, 20, "%s: HC:%.5d RSSI:%d", status.getScannerID().c_str(), status.getHeartbeatCount(), status.getHeartbeatRSSI());
    lcd->displayText(tmp, 0, 0);
    const char *uptime = statusProps["Uptime"].c_str();
    snprintf(tmp, 20, "UP: %s: ", uptime);
    lcd->displayText(tmp, 0, 1);
    const char *load = statusProps["LoadAverage"].c_str();

    cout << "Enter any key to exit: ";
    std::string line; std::getline(std::cin, line);
    lcd->clear();
}
<commit_msg>Correct the status information passing<commit_after>#include <chrono>
#include <iostream>
#include <memory>
#include <string.h>
#include "../lcd/LcdDisplay.h"
#include "../src2/HealthStatus.h"

using namespace std;
using namespace std::chrono;

int main() {
    unique_ptr<LcdDisplay> lcd(LcdDisplay::getLcdDisplayInstance());
    lcd->init();
    StatusInformation status;
    beacon_info beacon;
    memset(&beacon, sizeof(beacon), 0);
    status.setScannerID("Room206");

    // Add some events
    sprintf(beacon.uuid, "UUID-%.10d", 66);
    beacon.minor = 66;
    beacon.major = 1;
    beacon.manufacturer = 0xdead;
    beacon.code = 0xbeef;
    beacon.count = 3;
    beacon.rssi = -68;
    milliseconds now = duration_cast<milliseconds >(high_resolution_clock::now().time_since_epoch());
    beacon.time = now.count();
    status.addEvent(beacon, false);

    beacon.isHeartbeat = true;
    beacon.minor = 206;
    beacon.time += 10;
    status.addEvent(beacon, true);

    beacon.isHeartbeat = false;
    beacon.minor = 56;
    beacon.time += 10;
    status.addEvent(beacon, false);

    beacon.isHeartbeat = true;
    beacon.minor = 206;
    beacon.time += 10;
    status.addEvent(beacon, true);

    HealthStatus healthStatus;
    healthStatus.calculateStatus(status);
    Properties statusProps = healthStatus.getLastStatus();
    char tmp[20];
    snprintf(tmp, 20, "%s:%.5d;%d", status.getScannerID().c_str(), status.getHeartbeatCount(), status.getHeartbeatRSSI());
    lcd->displayText(tmp, 0, 0);
    string uptime = statusProps["Uptime"];
    printf("%s; length=%d\n", uptime.c_str(), uptime.size());
    snprintf(tmp, 20, "UP: %s: ", uptime);
    lcd->displayText(tmp, 0, 1);
    const char *load = statusProps["LoadAverage"].c_str();
    lcd->displayText(tmp, 0, 2);

    cout << "Enter any key to exit: ";
    std::string line; std::getline(std::cin, line);
    lcd->clear();
}
<|endoftext|>