<commit_before>// Copyright (c) 2012 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/command_line.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/test/net/url_request_mock_http_job.h"

using content::BrowserThread;

namespace {

void SetUrlRequestMock(const FilePath& path) {
  URLRequestMockHTTPJob::AddUrlHandler(path);
}

}

class PluginTest : public InProcessBrowserTest {
 protected:
  PluginTest() {}

  virtual void SetUpCommandLine(CommandLine* command_line) {
    // Some NPAPI tests schedule garbage collection to force object tear-down.
    command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose_gc");
    // For OpenPopupWindowWithPlugin.
    command_line->AppendSwitch(switches::kDisablePopupBlocking);
#if defined(OS_MACOSX)
    FilePath plugin_dir;
    PathService::Get(base::DIR_MODULE, &plugin_dir);
    plugin_dir = plugin_dir.AppendASCII("plugins");
    // The plugins directory isn't read by default on the Mac, so it needs to be
    // explicitly registered.
    command_line->AppendSwitchPath(switches::kExtraPluginDir, plugin_dir);
#endif
  }

  virtual void SetUpOnMainThread() OVERRIDE {
    FilePath path = ui_test_utils::GetTestFilePath(FilePath(), FilePath());
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE, base::Bind(&SetUrlRequestMock, path));
  }

  void LoadAndWait(const GURL& url, const char* title) {
    string16 expected_title(ASCIIToUTF16(title));
    ui_test_utils::TitleWatcher title_watcher(
        browser()->GetSelectedWebContents(), expected_title);
    title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
    ui_test_utils::NavigateToURL(browser(), url);
    EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
  }

  GURL GetURL(const char* filename) {
    return ui_test_utils::GetTestUrl(
      FilePath().AppendASCII("npapi"), FilePath().AppendASCII(filename));
  }

  void NavigateAway() {
    GURL url = ui_test_utils::GetTestUrl(
      FilePath(), FilePath().AppendASCII("simple.html"));
    LoadAndWait(url, "simple.html");
  }
};

// Make sure that navigating away from a plugin referenced by JS doesn't
// crash.
IN_PROC_BROWSER_TEST_F(PluginTest, UnloadNoCrash) {
  LoadAndWait(GetURL("layout_test_plugin.html"), "Layout Test Plugin Test");
  NavigateAway();
}

// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
// Flaky: http://crbug.com/59327
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginGetUrl) {
  LoadAndWait(GetURL("self_delete_plugin_geturl.html"), "OK");
}

// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
// Flaky. See http://crbug.com/30702
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvoke) {
  LoadAndWait(GetURL("self_delete_plugin_invoke.html"), "OK");
}

IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectReleasedOnDestruction) {
  ui_test_utils::NavigateToURL(
      browser(), GetURL("npobject_released_on_destruction.html"));
  NavigateAway();
}

// Test that a dialog is properly created when a plugin throws an
// exception.  Should be run for in and out of process plugins, but
// the more interesting case is out of process, where we must route
// the exception to the correct renderer.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectSetException) {
  LoadAndWait(GetURL("npobject_set_exception.html"), "OK");
}

#if defined(OS_WIN)
// Tests if a plugin executing a self deleting script in the context of
// a synchronous mouseup works correctly.
// This was never ported to Mac. The only thing remaining is to make
// ui_test_utils::SimulateMouseClick get to Mac plugins, currently it doesn't
// work.
IN_PROC_BROWSER_TEST_F(PluginTest,
                       SelfDeletePluginInvokeInSynchronousMouseUp) {
  ui_test_utils::NavigateToURL(
      browser(), GetURL("execute_script_delete_in_mouse_up.html"));

  string16 expected_title(ASCIIToUTF16("OK"));
  ui_test_utils::TitleWatcher title_watcher(
      browser()->GetSelectedWebContents(), expected_title);
  title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
  ui_test_utils::SimulateMouseClick(
      browser()->GetSelectedWebContents(), 150, 250);
  EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
#endif

// Flaky, http://crbug.com/60071.
IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRequest404Response) {
  GURL url(URLRequestMockHTTPJob::GetMockUrl(
      FilePath().AppendASCII("npapi").
                 AppendASCII("plugin_url_request_404.html")));
  LoadAndWait(url, "OK");
}

// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
// Disabled, flakily exceeds timeout, http://crbug.com/46257.
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvokeAlert) {
  ui_test_utils::NavigateToURL(
      browser(), GetURL("self_delete_plugin_invoke_alert.html"));

  string16 expected_title(ASCIIToUTF16("OK"));
  ui_test_utils::TitleWatcher title_watcher(
      browser()->GetSelectedWebContents(), expected_title);
  title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));

  ui_test_utils::WaitForAppModalDialogAndCloseIt();

  EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}

// Test passing arguments to a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, Arguments) {
  LoadAndWait(GetURL("arguments.html"), "OK");
}

// Test invoking many plugins within a single page.
IN_PROC_BROWSER_TEST_F(PluginTest, ManyPlugins) {
  LoadAndWait(GetURL("many_plugins.html"), "OK");
}

// Test various calls to GetURL from a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, GetURL) {
  LoadAndWait(GetURL("geturl.html"), "OK");
}

// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, GetJavaScriptURL) {
  LoadAndWait(GetURL("get_javascript_url.html"), "OK");
}

// Test that calling GetURL with a javascript URL and target=_self
// works properly when the plugin is embedded in a subframe.
IN_PROC_BROWSER_TEST_F(PluginTest, GetJavaScriptURL2) {
  LoadAndWait(GetURL("get_javascript_url2.html"), "OK");
}

// Test is flaky on linux/cros/win builders.  http://crbug.com/71904
IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRedirectNotification) {
  LoadAndWait(GetURL("geturl_redirect_notify.html"), "OK");
}

// Tests that identity is preserved for NPObjects passed from a plugin
// into JavaScript.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectIdentity) {
  LoadAndWait(GetURL("npobject_identity.html"), "OK");
}

// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy.  If this fails the plugin
// will crash.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectProxy) {
  LoadAndWait(GetURL("npobject_proxy.html"), "OK");
}

#if defined(OS_WIN) || defined(OS_MACOSX)
// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
// http://crbug.com/44960
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvokeInSynchronousPaint) {
  LoadAndWait(GetURL("execute_script_delete_in_paint.html"), "OK");
}
#endif

IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInNewStream) {
  LoadAndWait(GetURL("self_delete_plugin_stream.html"), "OK");
}

// If this test flakes use http://crbug.com/95558.
IN_PROC_BROWSER_TEST_F(PluginTest, DeletePluginInDeallocate) {
  LoadAndWait(GetURL("plugin_delete_in_deallocate.html"), "OK");
}

#if defined(OS_WIN)

IN_PROC_BROWSER_TEST_F(PluginTest, VerifyPluginWindowRect) {
  LoadAndWait(GetURL("verify_plugin_window_rect.html"), "OK");
}

// Tests that creating a new instance of a plugin while another one is handling
// a paint message doesn't cause deadlock.
IN_PROC_BROWSER_TEST_F(PluginTest, CreateInstanceInPaint) {
  LoadAndWait(GetURL("create_instance_in_paint.html"), "OK");
}

// Tests that putting up an alert in response to a paint doesn't deadlock.
IN_PROC_BROWSER_TEST_F(PluginTest, AlertInWindowMessage) {
  ui_test_utils::NavigateToURL(
      browser(), GetURL("alert_in_window_message.html"));

  ui_test_utils::WaitForAppModalDialogAndCloseIt();
  ui_test_utils::WaitForAppModalDialogAndCloseIt();
}

IN_PROC_BROWSER_TEST_F(PluginTest, VerifyNPObjectLifetimeTest) {
  LoadAndWait(GetURL("npobject_lifetime_test.html"), "OK");
}

// Tests that we don't crash or assert if NPP_New fails
IN_PROC_BROWSER_TEST_F(PluginTest, NewFails) {
  LoadAndWait(GetURL("new_fails.html"), "OK");
}

IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInNPNEvaluate) {
  LoadAndWait(GetURL("execute_script_delete_in_npn_evaluate.html"), "OK");
}

IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeleteCreatePluginInNPNEvaluate) {
  LoadAndWait(GetURL("npn_plugin_delete_create_in_evaluate.html"), "OK");
}

#endif  // OS_WIN

// If this flakes, reopen http://crbug.com/17645
// As of 6 July 2011, this test is flaky on Windows (perhaps due to timing out).
#if !defined(OS_MACOSX)
// Disabled on Mac because the plugin side isn't implemented yet, see
// "TODO(port)" in plugin_javascript_open_popup.cc.
IN_PROC_BROWSER_TEST_F(PluginTest, OpenPopupWindowWithPlugin) {
  LoadAndWait(GetURL("get_javascript_open_popup_with_plugin.html"), "OK");
}
#endif

// Test checking the privacy mode is off.
IN_PROC_BROWSER_TEST_F(PluginTest, PrivateDisabled) {
  LoadAndWait(GetURL("private.html"), "OK");
}

IN_PROC_BROWSER_TEST_F(PluginTest, ScheduleTimer) {
  LoadAndWait(GetURL("schedule_timer.html"), "OK");
}

IN_PROC_BROWSER_TEST_F(PluginTest, PluginThreadAsyncCall) {
  LoadAndWait(GetURL("plugin_thread_async_call.html"), "OK");
}

// Test checking the privacy mode is on.
// If this flakes on Linux, use http://crbug.com/104380
IN_PROC_BROWSER_TEST_F(PluginTest, PrivateEnabled) {
  LoadAndWait(GetURL("private.html"), "OK");
}

#if defined(OS_WIN) || defined(OS_MACOSX)
// Test a browser hang due to special case of multiple
// plugin instances indulged in sync calls across renderer.
IN_PROC_BROWSER_TEST_F(PluginTest, MultipleInstancesSyncCalls) {
  LoadAndWait(GetURL("multiple_instances_sync_calls.html"), "OK");
}
#endif

IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRequestFailWrite) {
  GURL url(URLRequestMockHTTPJob::GetMockUrl(
      FilePath().AppendASCII("npapi").
                 AppendASCII("plugin_url_request_fail_write.html")));
  LoadAndWait(url, "OK");
}

#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(PluginTest, EnsureScriptingWorksInDestroy) {
  LoadAndWait(GetURL("ensure_scripting_works_in_destroy.html"), "OK");
}

// This test uses a Windows Event to signal to the plugin that it should crash
// on NP_Initialize.
IN_PROC_BROWSER_TEST_F(PluginTest, NoHangIfInitCrashes) {
  HANDLE crash_event = CreateEvent(NULL, TRUE, FALSE, L"TestPluginCrashOnInit");
  SetEvent(crash_event);
  LoadAndWait(GetURL("no_hang_if_init_crashes.html"), "OK");
  CloseHandle(crash_event);
}
#endif

// If this flakes on Mac, use http://crbug.com/111508
IN_PROC_BROWSER_TEST_F(PluginTest, PluginReferrerTest) {
  GURL url(URLRequestMockHTTPJob::GetMockUrl(
      FilePath().AppendASCII("npapi").
                 AppendASCII("plugin_url_request_referrer_test.html")));
  LoadAndWait(url, "OK");
}

#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(PluginTest, PluginConvertPointTest) {
  gfx::NativeWindow window = NULL;
  gfx::Rect bounds(50, 50, 400, 400);
  ui_test_utils::GetNativeWindow(browser(), &window);
  ui_test_utils::SetWindowBounds(window, bounds);

  ui_test_utils::NavigateToURL(browser(), GetURL("convert_point.html"));

  string16 expected_title(ASCIIToUTF16("OK"));
  ui_test_utils::TitleWatcher title_watcher(
      browser()->GetSelectedWebContents(), expected_title);
  title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
  // TODO(stuartmorgan): When the automation system supports sending clicks,
  // change the test to trigger on mouse-down rather than window focus.
  static_cast<content::WebContentsDelegate*>(browser())->
      ActivateContents(browser()->GetSelectedWebContents());
  EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
#endif
<commit_msg>Don't run PluginTest.DeletePluginInDeallocate on mac debug since it asserts<commit_after>// Copyright (c) 2012 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/command_line.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/test/net/url_request_mock_http_job.h"

using content::BrowserThread;

namespace {

void SetUrlRequestMock(const FilePath& path) {
  URLRequestMockHTTPJob::AddUrlHandler(path);
}

}

class PluginTest : public InProcessBrowserTest {
 protected:
  PluginTest() {}

  virtual void SetUpCommandLine(CommandLine* command_line) {
    // Some NPAPI tests schedule garbage collection to force object tear-down.
    command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose_gc");
    // For OpenPopupWindowWithPlugin.
    command_line->AppendSwitch(switches::kDisablePopupBlocking);
#if defined(OS_MACOSX)
    FilePath plugin_dir;
    PathService::Get(base::DIR_MODULE, &plugin_dir);
    plugin_dir = plugin_dir.AppendASCII("plugins");
    // The plugins directory isn't read by default on the Mac, so it needs to be
    // explicitly registered.
    command_line->AppendSwitchPath(switches::kExtraPluginDir, plugin_dir);
#endif
  }

  virtual void SetUpOnMainThread() OVERRIDE {
    FilePath path = ui_test_utils::GetTestFilePath(FilePath(), FilePath());
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE, base::Bind(&SetUrlRequestMock, path));
  }

  void LoadAndWait(const GURL& url, const char* title) {
    string16 expected_title(ASCIIToUTF16(title));
    ui_test_utils::TitleWatcher title_watcher(
        browser()->GetSelectedWebContents(), expected_title);
    title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
    ui_test_utils::NavigateToURL(browser(), url);
    EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
  }

  GURL GetURL(const char* filename) {
    return ui_test_utils::GetTestUrl(
      FilePath().AppendASCII("npapi"), FilePath().AppendASCII(filename));
  }

  void NavigateAway() {
    GURL url = ui_test_utils::GetTestUrl(
      FilePath(), FilePath().AppendASCII("simple.html"));
    LoadAndWait(url, "simple.html");
  }
};

// Make sure that navigating away from a plugin referenced by JS doesn't
// crash.
IN_PROC_BROWSER_TEST_F(PluginTest, UnloadNoCrash) {
  LoadAndWait(GetURL("layout_test_plugin.html"), "Layout Test Plugin Test");
  NavigateAway();
}

// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
// Flaky: http://crbug.com/59327
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginGetUrl) {
  LoadAndWait(GetURL("self_delete_plugin_geturl.html"), "OK");
}

// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
// Flaky. See http://crbug.com/30702
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvoke) {
  LoadAndWait(GetURL("self_delete_plugin_invoke.html"), "OK");
}

IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectReleasedOnDestruction) {
  ui_test_utils::NavigateToURL(
      browser(), GetURL("npobject_released_on_destruction.html"));
  NavigateAway();
}

// Test that a dialog is properly created when a plugin throws an
// exception.  Should be run for in and out of process plugins, but
// the more interesting case is out of process, where we must route
// the exception to the correct renderer.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectSetException) {
  LoadAndWait(GetURL("npobject_set_exception.html"), "OK");
}

#if defined(OS_WIN)
// Tests if a plugin executing a self deleting script in the context of
// a synchronous mouseup works correctly.
// This was never ported to Mac. The only thing remaining is to make
// ui_test_utils::SimulateMouseClick get to Mac plugins, currently it doesn't
// work.
IN_PROC_BROWSER_TEST_F(PluginTest,
                       SelfDeletePluginInvokeInSynchronousMouseUp) {
  ui_test_utils::NavigateToURL(
      browser(), GetURL("execute_script_delete_in_mouse_up.html"));

  string16 expected_title(ASCIIToUTF16("OK"));
  ui_test_utils::TitleWatcher title_watcher(
      browser()->GetSelectedWebContents(), expected_title);
  title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
  ui_test_utils::SimulateMouseClick(
      browser()->GetSelectedWebContents(), 150, 250);
  EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
#endif

// Flaky, http://crbug.com/60071.
IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRequest404Response) {
  GURL url(URLRequestMockHTTPJob::GetMockUrl(
      FilePath().AppendASCII("npapi").
                 AppendASCII("plugin_url_request_404.html")));
  LoadAndWait(url, "OK");
}

// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
// Disabled, flakily exceeds timeout, http://crbug.com/46257.
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvokeAlert) {
  ui_test_utils::NavigateToURL(
      browser(), GetURL("self_delete_plugin_invoke_alert.html"));

  string16 expected_title(ASCIIToUTF16("OK"));
  ui_test_utils::TitleWatcher title_watcher(
      browser()->GetSelectedWebContents(), expected_title);
  title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));

  ui_test_utils::WaitForAppModalDialogAndCloseIt();

  EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}

// Test passing arguments to a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, Arguments) {
  LoadAndWait(GetURL("arguments.html"), "OK");
}

// Test invoking many plugins within a single page.
IN_PROC_BROWSER_TEST_F(PluginTest, ManyPlugins) {
  LoadAndWait(GetURL("many_plugins.html"), "OK");
}

// Test various calls to GetURL from a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, GetURL) {
  LoadAndWait(GetURL("geturl.html"), "OK");
}

// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
IN_PROC_BROWSER_TEST_F(PluginTest, GetJavaScriptURL) {
  LoadAndWait(GetURL("get_javascript_url.html"), "OK");
}

// Test that calling GetURL with a javascript URL and target=_self
// works properly when the plugin is embedded in a subframe.
IN_PROC_BROWSER_TEST_F(PluginTest, GetJavaScriptURL2) {
  LoadAndWait(GetURL("get_javascript_url2.html"), "OK");
}

// Test is flaky on linux/cros/win builders.  http://crbug.com/71904
IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRedirectNotification) {
  LoadAndWait(GetURL("geturl_redirect_notify.html"), "OK");
}

// Tests that identity is preserved for NPObjects passed from a plugin
// into JavaScript.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectIdentity) {
  LoadAndWait(GetURL("npobject_identity.html"), "OK");
}

// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy.  If this fails the plugin
// will crash.
IN_PROC_BROWSER_TEST_F(PluginTest, NPObjectProxy) {
  LoadAndWait(GetURL("npobject_proxy.html"), "OK");
}

#if defined(OS_WIN) || defined(OS_MACOSX)
// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
// http://crbug.com/44960
IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInvokeInSynchronousPaint) {
  LoadAndWait(GetURL("execute_script_delete_in_paint.html"), "OK");
}
#endif

IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInNewStream) {
  LoadAndWait(GetURL("self_delete_plugin_stream.html"), "OK");
}

// This test asserts on Mac in plugin_host in the NPNVWindowNPObject case.
#if !(defined(OS_MACOSX) && !defined(NDEBUG))
// If this test flakes use http://crbug.com/95558.
IN_PROC_BROWSER_TEST_F(PluginTest, DeletePluginInDeallocate) {
  LoadAndWait(GetURL("plugin_delete_in_deallocate.html"), "OK");
}
#endif

#if defined(OS_WIN)

IN_PROC_BROWSER_TEST_F(PluginTest, VerifyPluginWindowRect) {
  LoadAndWait(GetURL("verify_plugin_window_rect.html"), "OK");
}

// Tests that creating a new instance of a plugin while another one is handling
// a paint message doesn't cause deadlock.
IN_PROC_BROWSER_TEST_F(PluginTest, CreateInstanceInPaint) {
  LoadAndWait(GetURL("create_instance_in_paint.html"), "OK");
}

// Tests that putting up an alert in response to a paint doesn't deadlock.
IN_PROC_BROWSER_TEST_F(PluginTest, AlertInWindowMessage) {
  ui_test_utils::NavigateToURL(
      browser(), GetURL("alert_in_window_message.html"));

  ui_test_utils::WaitForAppModalDialogAndCloseIt();
  ui_test_utils::WaitForAppModalDialogAndCloseIt();
}

IN_PROC_BROWSER_TEST_F(PluginTest, VerifyNPObjectLifetimeTest) {
  LoadAndWait(GetURL("npobject_lifetime_test.html"), "OK");
}

// Tests that we don't crash or assert if NPP_New fails
IN_PROC_BROWSER_TEST_F(PluginTest, NewFails) {
  LoadAndWait(GetURL("new_fails.html"), "OK");
}

IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeletePluginInNPNEvaluate) {
  LoadAndWait(GetURL("execute_script_delete_in_npn_evaluate.html"), "OK");
}

IN_PROC_BROWSER_TEST_F(PluginTest, SelfDeleteCreatePluginInNPNEvaluate) {
  LoadAndWait(GetURL("npn_plugin_delete_create_in_evaluate.html"), "OK");
}

#endif  // OS_WIN

// If this flakes, reopen http://crbug.com/17645
// As of 6 July 2011, this test is flaky on Windows (perhaps due to timing out).
#if !defined(OS_MACOSX)
// Disabled on Mac because the plugin side isn't implemented yet, see
// "TODO(port)" in plugin_javascript_open_popup.cc.
IN_PROC_BROWSER_TEST_F(PluginTest, OpenPopupWindowWithPlugin) {
  LoadAndWait(GetURL("get_javascript_open_popup_with_plugin.html"), "OK");
}
#endif

// Test checking the privacy mode is off.
IN_PROC_BROWSER_TEST_F(PluginTest, PrivateDisabled) {
  LoadAndWait(GetURL("private.html"), "OK");
}

IN_PROC_BROWSER_TEST_F(PluginTest, ScheduleTimer) {
  LoadAndWait(GetURL("schedule_timer.html"), "OK");
}

IN_PROC_BROWSER_TEST_F(PluginTest, PluginThreadAsyncCall) {
  LoadAndWait(GetURL("plugin_thread_async_call.html"), "OK");
}

// Test checking the privacy mode is on.
// If this flakes on Linux, use http://crbug.com/104380
IN_PROC_BROWSER_TEST_F(PluginTest, PrivateEnabled) {
  LoadAndWait(GetURL("private.html"), "OK");
}

#if defined(OS_WIN) || defined(OS_MACOSX)
// Test a browser hang due to special case of multiple
// plugin instances indulged in sync calls across renderer.
IN_PROC_BROWSER_TEST_F(PluginTest, MultipleInstancesSyncCalls) {
  LoadAndWait(GetURL("multiple_instances_sync_calls.html"), "OK");
}
#endif

IN_PROC_BROWSER_TEST_F(PluginTest, GetURLRequestFailWrite) {
  GURL url(URLRequestMockHTTPJob::GetMockUrl(
      FilePath().AppendASCII("npapi").
                 AppendASCII("plugin_url_request_fail_write.html")));
  LoadAndWait(url, "OK");
}

#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(PluginTest, EnsureScriptingWorksInDestroy) {
  LoadAndWait(GetURL("ensure_scripting_works_in_destroy.html"), "OK");
}

// This test uses a Windows Event to signal to the plugin that it should crash
// on NP_Initialize.
IN_PROC_BROWSER_TEST_F(PluginTest, NoHangIfInitCrashes) {
  HANDLE crash_event = CreateEvent(NULL, TRUE, FALSE, L"TestPluginCrashOnInit");
  SetEvent(crash_event);
  LoadAndWait(GetURL("no_hang_if_init_crashes.html"), "OK");
  CloseHandle(crash_event);
}
#endif

// If this flakes on Mac, use http://crbug.com/111508
IN_PROC_BROWSER_TEST_F(PluginTest, PluginReferrerTest) {
  GURL url(URLRequestMockHTTPJob::GetMockUrl(
      FilePath().AppendASCII("npapi").
                 AppendASCII("plugin_url_request_referrer_test.html")));
  LoadAndWait(url, "OK");
}

#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(PluginTest, PluginConvertPointTest) {
  gfx::NativeWindow window = NULL;
  gfx::Rect bounds(50, 50, 400, 400);
  ui_test_utils::GetNativeWindow(browser(), &window);
  ui_test_utils::SetWindowBounds(window, bounds);

  ui_test_utils::NavigateToURL(browser(), GetURL("convert_point.html"));

  string16 expected_title(ASCIIToUTF16("OK"));
  ui_test_utils::TitleWatcher title_watcher(
      browser()->GetSelectedWebContents(), expected_title);
  title_watcher.AlsoWaitForTitle(ASCIIToUTF16("FAIL"));
  // TODO(stuartmorgan): When the automation system supports sending clicks,
  // change the test to trigger on mouse-down rather than window focus.
  static_cast<content::WebContentsDelegate*>(browser())->
      ActivateContents(browser()->GetSelectedWebContents());
  EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
}
#endif
<|endoftext|>


<commit_before><commit_msg>jnitools: fix spelling in error message<commit_after><|endoftext|>


<commit_before><commit_msg>fix a bug about degree measure and radian measure.<commit_after><|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
#include "socket.h"
//-----------------------------------------------------------------------------
Socket::Socket(unsigned int port)
:status(false)
{
	int error = WSAStartup (0x0202, &wsaData);   // Fill in WSA info
	SOCKADDR_IN addr; // The address structure for a TCP socket

	if (error)
		exit(1);

	//Did we get the right Winsock version?
	if (wsaData.wVersion != 0x0202)
	{
		WSACleanup(); //Clean up Winsock
		exit(1);
	}

	addr.sin_family = AF_INET;      // Address family
	addr.sin_port = htons (port);   // Assign port to this socket
	addr.sin_addr.s_addr = htonl (INADDR_ANY);
	sockfd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); // Create socket
}
//-----------------------------------------------------------------------------
Socket::~Socket() {
	// TODO Auto-generated destructor stub
}
//-----------------------------------------------------------------------------

<commit_msg>Close Socket for windows<commit_after>//-----------------------------------------------------------------------------
#include "socket.h"
//-----------------------------------------------------------------------------
Socket::Socket(unsigned int port)
:status(false)
{
	int error = WSAStartup (0x0202, &wsaData);   // Fill in WSA info
	SOCKADDR_IN addr; // The address structure for a TCP socket

	if (error)
		exit(1);

	//Did we get the right Winsock version?
	if (wsaData.wVersion != 0x0202)
	{
		WSACleanup(); //Clean up Winsock
		exit(1);
	}

	addr.sin_family = AF_INET;      // Address family
	addr.sin_port = htons (port);   // Assign port to this socket
	addr.sin_addr.s_addr = htonl (INADDR_ANY);
	sockfd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); // Create socket
}
//-----------------------------------------------------------------------------
Socket::~Socket() {

	if (sockfd)
		closesocket(sockfd);
	WSACleanup(); //Clean up Winsock
}
//-----------------------------------------------------------------------------

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed 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.txt
 *
 *  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.
 *
 *=========================================================================*/

#include "itkDisplacementFieldToBSplineImageFilter.h"

int itkDisplacementFieldToBSplineImageFilterTest( int, char * [] )
{
  const unsigned int   ImageDimension = 2;

  typedef itk::Vector<float, ImageDimension>         VectorType;
  typedef itk::Image<VectorType, ImageDimension>     DisplacementFieldType;
  typedef itk::PointSet<VectorType, ImageDimension>  PointSetType;

  // Create a displacement field
  DisplacementFieldType::PointType     origin;
  DisplacementFieldType::SpacingType   spacing;
  DisplacementFieldType::SizeType      size;
  DisplacementFieldType::DirectionType direction;

  direction.SetIdentity();
  origin.Fill( 0.0 );
  spacing.Fill( 0.5 );
  size.Fill( 100 );

  VectorType ones( 1 );

  DisplacementFieldType::Pointer field = DisplacementFieldType::New();
  field->SetOrigin( origin );
  field->SetSpacing( spacing );
  field->SetRegions( size );
  field->SetDirection( direction );
  field->Allocate();
  field->FillBuffer( ones );

  typedef itk::DisplacementFieldToBSplineImageFilter
    <DisplacementFieldType, PointSetType>                   BSplineFilterType;
  typedef BSplineFilterType::RealImageType                  RealImageType;

  RealImageType::Pointer confidenceImage = RealImageType::New();
  confidenceImage->CopyInformation( field );
  confidenceImage->SetRegions( size );
  confidenceImage->Allocate();
  confidenceImage->FillBuffer( 1.0 );

  PointSetType::Pointer pointSet = PointSetType::New();
  pointSet->Initialize();

  // Assign some random points within the b-spline domain
  PointSetType::PointType point1;
  point1[0] = 23.75;
  point1[1] = 5.125;
  pointSet->SetPoint( 0, point1 );
  pointSet->SetPointData( 0, ones );

  PointSetType::PointType point2;
  point2[0] = 1.75;
  point2[1] = 45.125;
  pointSet->SetPoint( 1, point2 );
  pointSet->SetPointData( 1, ones );

  PointSetType::PointType point3;
  point3[0] = 45.75;
  point3[1] = 2.125;
  pointSet->SetPoint( 2, point3 );
  pointSet->SetPointData( 2, ones );

  BSplineFilterType::ArrayType numberOfControlPoints;
  numberOfControlPoints.Fill( 4 );

  BSplineFilterType::Pointer bspliner = BSplineFilterType::New();
  bspliner->SetDisplacementField( field );
  bspliner->SetConfidenceImage( confidenceImage );
  bspliner->SetPointSet( pointSet );
  bspliner->SetUseInputFieldToDefineTheBSplineDomain( true );
  bspliner->SetNumberOfControlPoints( numberOfControlPoints );
  bspliner->SetSplineOrder( 3 );
  bspliner->SetNumberOfFittingLevels( 8 );
  bspliner->EnforceStationaryBoundaryOff();
  bspliner->EnforceStationaryBoundaryOn();
  bspliner->SetEnforceStationaryBoundary( false );
  bspliner->EstimateInverseOff();
  bspliner->EstimateInverseOn();
  bspliner->SetEstimateInverse( false );
  bspliner->Update();
  std::cout << "spline order: " << bspliner->GetSplineOrder() << std::endl;
  std::cout << "number of control points: " << bspliner->GetNumberOfControlPoints() << std::endl;
  std::cout << "number of fitting levels: " << bspliner->GetNumberOfFittingLevels() << std::endl;
  std::cout << "enforce stationary boundary: " << bspliner->GetEnforceStationaryBoundary() << std::endl;
  std::cout << "estimate inverse: " << bspliner->GetEstimateInverse() << std::endl;

  try
    {
    bspliner->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown " << std::endl;
    std::cerr << excp << std::endl;
    }

  DisplacementFieldType::IndexType index;
  index[0] = 50;
  index[1] = 50;

  VectorType v = bspliner->GetOutput()->GetPixel( index );

  if( vnl_math_abs( v.GetNorm() - 1.414214 ) >= 0.01 )
    {
    std::cerr << "Failed to find the correct forward displacement vector." << std::endl;
    return EXIT_FAILURE;
    }

  bspliner->SetNumberOfControlPoints( numberOfControlPoints );
  bspliner->SetSplineOrder( 3 );
  bspliner->SetNumberOfFittingLevels( 5 );
  bspliner->EnforceStationaryBoundaryOff();
  bspliner->EnforceStationaryBoundaryOn();
  bspliner->SetEnforceStationaryBoundary( false );
  bspliner->SetEstimateInverse( true );
  bspliner->Update();

  v = bspliner->GetOutput()->GetPixel( index );

  if( vnl_math_abs( v.GetNorm() - 1.414214 ) >= 0.01 )
    {
    std::cerr << "Failed to find the correct inverse displacement vector." << std::endl;
    return EXIT_FAILURE;
    }

  bspliner->Print( std::cout, 3 );

  /** do a second run using only the point set. */

  BSplineFilterType::Pointer bspliner2 = BSplineFilterType::New();
  bspliner2->SetPointSet( pointSet );
  bspliner2->SetUseInputFieldToDefineTheBSplineDomain( false );
  bspliner2->SetBSplineDomainFromImage( field );
  bspliner2->SetNumberOfControlPoints( numberOfControlPoints );
  bspliner2->SetSplineOrder( 3 );
  bspliner2->SetNumberOfFittingLevels( 8 );
  bspliner2->EnforceStationaryBoundaryOff();
  bspliner2->EnforceStationaryBoundaryOn();
  bspliner2->SetEnforceStationaryBoundary( false );
  bspliner2->EstimateInverseOff();
  bspliner2->EstimateInverseOn();
  bspliner2->SetEstimateInverse( false );
  bspliner2->Update();

  try
    {
    bspliner2->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown " << std::endl;
    std::cerr << excp << std::endl;
    }

  return EXIT_SUCCESS;
}
<commit_msg>COMP: Fixed the compiler error of itkDisplacementFieldToBSplineImageFilterTest<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed 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.txt
 *
 *  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.
 *
 *=========================================================================*/

#include "itkDisplacementFieldToBSplineImageFilter.h"

int itkDisplacementFieldToBSplineImageFilterTest( int, char * [] )
{
  const unsigned int   ImageDimension = 2;

  typedef itk::Vector<float, ImageDimension>         VectorType;
  typedef itk::Image<VectorType, ImageDimension>     DisplacementFieldType;
  typedef itk::PointSet<VectorType, ImageDimension>  PointSetType;

  // Create a displacement field
  DisplacementFieldType::PointType     origin;
  DisplacementFieldType::SpacingType   spacing;
  DisplacementFieldType::SizeType      size;
  DisplacementFieldType::DirectionType direction;

  direction.SetIdentity();
  origin.Fill( 0.0 );
  spacing.Fill( 0.5 );
  size.Fill( 100 );

  VectorType ones( 1 );

  DisplacementFieldType::Pointer field = DisplacementFieldType::New();
  field->SetOrigin( origin );
  field->SetSpacing( spacing );
  field->SetRegions( size );
  field->SetDirection( direction );
  field->Allocate();
  field->FillBuffer( ones );

  typedef itk::DisplacementFieldToBSplineImageFilter
    <DisplacementFieldType, PointSetType>                   BSplineFilterType;
  typedef BSplineFilterType::RealImageType                  RealImageType;

  RealImageType::Pointer confidenceImage = RealImageType::New();
  confidenceImage->CopyInformation( field );
  confidenceImage->SetRegions( size );
  confidenceImage->Allocate();
  confidenceImage->FillBuffer( 1.0 );

  PointSetType::Pointer pointSet = PointSetType::New();
  pointSet->Initialize();

  VectorType ones_points( 1.0 );

  // Assign some random points within the b-spline domain
  PointSetType::PointType point1;
  point1[0] = 23.75;
  point1[1] = 5.125;
  pointSet->SetPoint( 0, point1 );
  pointSet->SetPointData( 0, ones_points );

  PointSetType::PointType point2;
  point2[0] = 1.75;
  point2[1] = 45.125;
  pointSet->SetPoint( 1, point2 );
  pointSet->SetPointData( 1, ones_points );

  PointSetType::PointType point3;
  point3[0] = 45.75;
  point3[1] = 2.125;
  pointSet->SetPoint( 2, point3 );
  pointSet->SetPointData( 2, ones_points );

  BSplineFilterType::ArrayType numberOfControlPoints;
  numberOfControlPoints.Fill( 4 );

  BSplineFilterType::Pointer bspliner = BSplineFilterType::New();
  bspliner->SetDisplacementField( field );
  bspliner->SetConfidenceImage( confidenceImage );
  bspliner->SetPointSet( pointSet );
  bspliner->SetUseInputFieldToDefineTheBSplineDomain( true );
  bspliner->SetNumberOfControlPoints( numberOfControlPoints );
  bspliner->SetSplineOrder( 3 );
  bspliner->SetNumberOfFittingLevels( 8 );
  bspliner->EnforceStationaryBoundaryOff();
  bspliner->EnforceStationaryBoundaryOn();
  bspliner->SetEnforceStationaryBoundary( false );
  bspliner->EstimateInverseOff();
  bspliner->EstimateInverseOn();
  bspliner->SetEstimateInverse( false );
  bspliner->Update();
  std::cout << "spline order: " << bspliner->GetSplineOrder() << std::endl;
  std::cout << "number of control points: " << bspliner->GetNumberOfControlPoints() << std::endl;
  std::cout << "number of fitting levels: " << bspliner->GetNumberOfFittingLevels() << std::endl;
  std::cout << "enforce stationary boundary: " << bspliner->GetEnforceStationaryBoundary() << std::endl;
  std::cout << "estimate inverse: " << bspliner->GetEstimateInverse() << std::endl;

  try
    {
    bspliner->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown " << std::endl;
    std::cerr << excp << std::endl;
    }

  DisplacementFieldType::IndexType index;
  index[0] = 50;
  index[1] = 50;

  VectorType v = bspliner->GetOutput()->GetPixel( index );

  if( vnl_math_abs( v.GetNorm() - 1.414214 ) >= 0.01 )
    {
    std::cerr << "Failed to find the correct forward displacement vector." << std::endl;
    return EXIT_FAILURE;
    }

  bspliner->SetNumberOfControlPoints( numberOfControlPoints );
  bspliner->SetSplineOrder( 3 );
  bspliner->SetNumberOfFittingLevels( 5 );
  bspliner->EnforceStationaryBoundaryOff();
  bspliner->EnforceStationaryBoundaryOn();
  bspliner->SetEnforceStationaryBoundary( false );
  bspliner->SetEstimateInverse( true );
  bspliner->Update();

  v = bspliner->GetOutput()->GetPixel( index );

  if( vnl_math_abs( v.GetNorm() - 1.414214 ) >= 0.01 )
    {
    std::cerr << "Failed to find the correct inverse displacement vector." << std::endl;
    return EXIT_FAILURE;
    }

  bspliner->Print( std::cout, 3 );

  /** do a second run using only the point set. */

  BSplineFilterType::Pointer bspliner2 = BSplineFilterType::New();
  bspliner2->SetPointSet( pointSet );
  bspliner2->SetUseInputFieldToDefineTheBSplineDomain( false );
  bspliner2->SetBSplineDomainFromImage( field );
  bspliner2->SetNumberOfControlPoints( numberOfControlPoints );
  bspliner2->SetSplineOrder( 3 );
  bspliner2->SetNumberOfFittingLevels( 8 );
  bspliner2->EnforceStationaryBoundaryOff();
  bspliner2->EnforceStationaryBoundaryOn();
  bspliner2->SetEnforceStationaryBoundary( false );
  bspliner2->EstimateInverseOff();
  bspliner2->EstimateInverseOn();
  bspliner2->SetEstimateInverse( false );
  bspliner2->Update();

  try
    {
    bspliner2->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown " << std::endl;
    std::cerr << excp << std::endl;
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "build_skins.h"
#include "build_common.h"

#include "platform/platform.hpp"

#include <array>
#include <algorithm>
#include <exception>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <fstream>

#include <QtCore/QDir>

namespace
{
enum SkinType
{
  SkinMDPI,
  SkinHDPI,
  SkinXHDPI,
  SkinXXHDPI,
  Skin6Plus,
  SkinXXXHDPI,

  // SkinCount MUST BE last
  SkinCount
};

using SkinInfo = std::tuple<const char*, int, bool>;
SkinInfo const g_skinInfo[SkinCount] =
{
  std::make_tuple("mdpi", 18, false),
  std::make_tuple("hdpi", 27, false),
  std::make_tuple("xhdpi", 36, false),
  std::make_tuple("xxhdpi", 54, false),
  std::make_tuple("6plus", 54, false),
  std::make_tuple("xxxhdpi", 64, false),
};

std::array<SkinType, SkinCount> const g_skinTypes =
{{
  SkinMDPI,
  SkinHDPI,
  SkinXHDPI,
  SkinXXHDPI,
  Skin6Plus,
  SkinXXXHDPI,
}};

inline const char * SkinSuffix(SkinType s) { return std::get<0>(g_skinInfo[s]); }
inline int SkinSize(SkinType s) { return std::get<1>(g_skinInfo[s]); }
inline bool SkinCoorrectColor(SkinType s) { return std::get<2>(g_skinInfo[s]); }

QString GetSkinGeneratorPath()
{
  QString path = GetExternalPath("skin_generator_tool", "skin_generator_tool.app/Contents/MacOS", "");
  if (path.isEmpty())
    throw std::runtime_error("Can't find skin_generator_tool");
  ASSERT(QFileInfo::exists(path), (path.toStdString()));
  return path;
}

class RAII
{
public:
  RAII(std::function<void()> && f) : m_f(std::move(f)) {}
  ~RAII() { m_f(); }
private:
  function<void()> const m_f;
};

std::string trim(std::string && s)
{
  s.erase(std::remove_if(s.begin(), s.end(), &isspace), s.end());
  return s;
}
}  // namespace

namespace build_style
{
std::unordered_map<string, int> GetSkinSizes(QString const & file)
{
  std::unordered_map<string, int> skinSizes;

  for (SkinType s : g_skinTypes)
    skinSizes.insert(make_pair(SkinSuffix(s), SkinSize(s)));

  try
  {
    std::ifstream ifs(to_string(file));

    std::string line;
    while (std::getline(ifs, line))
    {
      size_t const pos = line.find('=');
      if (pos == std::string::npos)
        continue;

      std::string name(line.begin(), line.begin() + pos);
      std::string valueTxt(line.begin() + pos + 1, line.end());

      name = trim(std::move(name));
      int value = std::stoi(trim(std::move(valueTxt)));

      if (value <= 0)
        continue;

      skinSizes[name] = value;
    }
  }
  catch (std::exception const & e)
  {
    // reset
    for (SkinType s : g_skinTypes)
      skinSizes[SkinSuffix(s)] = SkinSize(s);
  }

  return skinSizes;
}

void BuildSkinImpl(QString const & styleDir, QString const & suffix,
                   int size, bool colorCorrection, QString const & outputDir)
{
  QString const symbolsDir = JoinPathQt({styleDir, "symbols"});

  // Check symbols directory exists
  if (!QDir(symbolsDir).exists())
    throw std::runtime_error("Symbols directory does not exist");

  // Caller ensures that output directory is clear
  if (QDir(outputDir).exists())
    throw std::runtime_error("Output directory is not clear");

  // Create output skin directory
  if (!QDir().mkdir(outputDir))
    throw std::runtime_error("Cannot create output skin directory");

  // Create symbolic link for symbols/png
  QString const pngOriginDir = styleDir + suffix;
  QString const pngDir = JoinPathQt({styleDir, "symbols", "png"});
  QFile::remove(pngDir);
  if (!QFile::link(pngOriginDir, pngDir))
    throw std::runtime_error("Unable to create symbols/png link");
  RAII const cleaner([=]() { QFile::remove(pngDir); });

  // Prepare command line
  QStringList params;
  params << GetSkinGeneratorPath() <<
          "--symbolWidth" << to_string(size).c_str() <<
          "--symbolHeight" << to_string(size).c_str() <<
          "--symbolsDir" << symbolsDir <<
          "--skinName" << JoinPathQt({outputDir, "basic"}) <<
          "--skinSuffix=\"\"";
  if (colorCorrection)
    params << "--colorCorrection true";
  QString const cmd = params.join(' ');

  // Run the script
  auto res = ExecProcess(cmd);

  // If script returns non zero then it is error
  if (res.first != 0)
  {
    QString msg = QString("System error ") + to_string(res.first).c_str();
    if (!res.second.isEmpty())
      msg = msg + "\n" + res.second;
    throw std::runtime_error(to_string(msg));
  }

  // Check files were created
  if (QFile(JoinPathQt({outputDir, "symbols.png"})).size() == 0 ||
      QFile(JoinPathQt({outputDir, "symbols.sdf"})).size() == 0)
  {
    throw std::runtime_error("Skin files have not been created");
  }
}

void BuildSkins(QString const & styleDir, QString const & outputDir)
{
  QString const resolutionFilePath = JoinPathQt({styleDir, "resolutions.txt"});

  auto const resolution2size = GetSkinSizes(resolutionFilePath);

  for (SkinType s : g_skinTypes)
  {
    QString const suffix = SkinSuffix(s);
    QString const outputSkinDir = JoinPathQt({outputDir, "resources-" + suffix + "_design"});
    int const size = resolution2size.at(to_string(suffix)); // SkinSize(s);
    bool const colorCorrection = SkinCoorrectColor(s);

    BuildSkinImpl(styleDir, suffix, size, colorCorrection, outputSkinDir);
  }
}

void ApplySkins(QString const & outputDir)
{
  QString const resourceDir = GetPlatform().ResourcesDir().c_str();

  for (SkinType s : g_skinTypes)
  {
    QString const suffix = SkinSuffix(s);
    QString const outputSkinDir = JoinPathQt({outputDir, "resources-" + suffix + "_design"});
    QString const resourceSkinDir = JoinPathQt({resourceDir, "resources-" + suffix + "_design"});

    if (!QFileInfo::exists(resourceSkinDir) && !QDir().mkdir(resourceSkinDir))
      throw std::runtime_error("Cannot create resource skin directory: " + resourceSkinDir.toStdString());

    if (!CopyFile(JoinPathQt({outputSkinDir, "symbols.png"}),
                  JoinPathQt({resourceSkinDir, "symbols.png"})) ||
        !CopyFile(JoinPathQt({outputSkinDir, "symbols.sdf"}),
                  JoinPathQt({resourceSkinDir, "symbols.sdf"})))
    {
      throw std::runtime_error("Cannot copy skins files");
    }
  }
}
}  // namespace build_style
<commit_msg>[qt] fix warning<commit_after>#include "build_skins.h"
#include "build_common.h"

#include "platform/platform.hpp"

#include <array>
#include <algorithm>
#include <exception>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <fstream>

#include <QtCore/QDir>

namespace
{
enum SkinType
{
  SkinMDPI,
  SkinHDPI,
  SkinXHDPI,
  SkinXXHDPI,
  Skin6Plus,
  SkinXXXHDPI,

  // SkinCount MUST BE last
  SkinCount
};

using SkinInfo = std::tuple<const char*, int, bool>;
SkinInfo const g_skinInfo[SkinCount] =
{
  std::make_tuple("mdpi", 18, false),
  std::make_tuple("hdpi", 27, false),
  std::make_tuple("xhdpi", 36, false),
  std::make_tuple("xxhdpi", 54, false),
  std::make_tuple("6plus", 54, false),
  std::make_tuple("xxxhdpi", 64, false),
};

std::array<SkinType, SkinCount> const g_skinTypes =
{{
  SkinMDPI,
  SkinHDPI,
  SkinXHDPI,
  SkinXXHDPI,
  Skin6Plus,
  SkinXXXHDPI,
}};

inline const char * SkinSuffix(SkinType s) { return std::get<0>(g_skinInfo[s]); }
inline int SkinSize(SkinType s) { return std::get<1>(g_skinInfo[s]); }
inline bool SkinCoorrectColor(SkinType s) { return std::get<2>(g_skinInfo[s]); }

QString GetSkinGeneratorPath()
{
  QString path = GetExternalPath("skin_generator_tool", "skin_generator_tool.app/Contents/MacOS", "");
  if (path.isEmpty())
    throw std::runtime_error("Can't find skin_generator_tool");
  ASSERT(QFileInfo::exists(path), (path.toStdString()));
  return path;
}

class RAII
{
public:
  RAII(std::function<void()> && f) : m_f(std::move(f)) {}
  ~RAII() { m_f(); }
private:
  function<void()> const m_f;
};

std::string trim(std::string && s)
{
  s.erase(std::remove_if(s.begin(), s.end(), &isspace), s.end());
  return std::move(s);
}
}  // namespace

namespace build_style
{
std::unordered_map<string, int> GetSkinSizes(QString const & file)
{
  std::unordered_map<string, int> skinSizes;

  for (SkinType s : g_skinTypes)
    skinSizes.insert(make_pair(SkinSuffix(s), SkinSize(s)));

  try
  {
    std::ifstream ifs(to_string(file));

    std::string line;
    while (std::getline(ifs, line))
    {
      size_t const pos = line.find('=');
      if (pos == std::string::npos)
        continue;

      std::string name(line.begin(), line.begin() + pos);
      std::string valueTxt(line.begin() + pos + 1, line.end());

      name = trim(std::move(name));
      int value = std::stoi(trim(std::move(valueTxt)));

      if (value <= 0)
        continue;

      skinSizes[name] = value;
    }
  }
  catch (std::exception const & e)
  {
    // reset
    for (SkinType s : g_skinTypes)
      skinSizes[SkinSuffix(s)] = SkinSize(s);
  }

  return skinSizes;
}

void BuildSkinImpl(QString const & styleDir, QString const & suffix,
                   int size, bool colorCorrection, QString const & outputDir)
{
  QString const symbolsDir = JoinPathQt({styleDir, "symbols"});

  // Check symbols directory exists
  if (!QDir(symbolsDir).exists())
    throw std::runtime_error("Symbols directory does not exist");

  // Caller ensures that output directory is clear
  if (QDir(outputDir).exists())
    throw std::runtime_error("Output directory is not clear");

  // Create output skin directory
  if (!QDir().mkdir(outputDir))
    throw std::runtime_error("Cannot create output skin directory");

  // Create symbolic link for symbols/png
  QString const pngOriginDir = styleDir + suffix;
  QString const pngDir = JoinPathQt({styleDir, "symbols", "png"});
  QFile::remove(pngDir);
  if (!QFile::link(pngOriginDir, pngDir))
    throw std::runtime_error("Unable to create symbols/png link");
  RAII const cleaner([=]() { QFile::remove(pngDir); });

  // Prepare command line
  QStringList params;
  params << GetSkinGeneratorPath() <<
          "--symbolWidth" << to_string(size).c_str() <<
          "--symbolHeight" << to_string(size).c_str() <<
          "--symbolsDir" << symbolsDir <<
          "--skinName" << JoinPathQt({outputDir, "basic"}) <<
          "--skinSuffix=\"\"";
  if (colorCorrection)
    params << "--colorCorrection true";
  QString const cmd = params.join(' ');

  // Run the script
  auto res = ExecProcess(cmd);

  // If script returns non zero then it is error
  if (res.first != 0)
  {
    QString msg = QString("System error ") + to_string(res.first).c_str();
    if (!res.second.isEmpty())
      msg = msg + "\n" + res.second;
    throw std::runtime_error(to_string(msg));
  }

  // Check files were created
  if (QFile(JoinPathQt({outputDir, "symbols.png"})).size() == 0 ||
      QFile(JoinPathQt({outputDir, "symbols.sdf"})).size() == 0)
  {
    throw std::runtime_error("Skin files have not been created");
  }
}

void BuildSkins(QString const & styleDir, QString const & outputDir)
{
  QString const resolutionFilePath = JoinPathQt({styleDir, "resolutions.txt"});

  auto const resolution2size = GetSkinSizes(resolutionFilePath);

  for (SkinType s : g_skinTypes)
  {
    QString const suffix = SkinSuffix(s);
    QString const outputSkinDir = JoinPathQt({outputDir, "resources-" + suffix + "_design"});
    int const size = resolution2size.at(to_string(suffix)); // SkinSize(s);
    bool const colorCorrection = SkinCoorrectColor(s);

    BuildSkinImpl(styleDir, suffix, size, colorCorrection, outputSkinDir);
  }
}

void ApplySkins(QString const & outputDir)
{
  QString const resourceDir = GetPlatform().ResourcesDir().c_str();

  for (SkinType s : g_skinTypes)
  {
    QString const suffix = SkinSuffix(s);
    QString const outputSkinDir = JoinPathQt({outputDir, "resources-" + suffix + "_design"});
    QString const resourceSkinDir = JoinPathQt({resourceDir, "resources-" + suffix + "_design"});

    if (!QFileInfo::exists(resourceSkinDir) && !QDir().mkdir(resourceSkinDir))
      throw std::runtime_error("Cannot create resource skin directory: " + resourceSkinDir.toStdString());

    if (!CopyFile(JoinPathQt({outputSkinDir, "symbols.png"}),
                  JoinPathQt({resourceSkinDir, "symbols.png"})) ||
        !CopyFile(JoinPathQt({outputSkinDir, "symbols.sdf"}),
                  JoinPathQt({resourceSkinDir, "symbols.sdf"})))
    {
      throw std::runtime_error("Cannot copy skins files");
    }
  }
}
}  // namespace build_style
<|endoftext|>


<commit_before>//===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the auto-upgrade helper functions
//
//===----------------------------------------------------------------------===//

#include "llvm/AutoUpgrade.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instruction.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/IRBuilder.h"
#include <cstring>
using namespace llvm;

static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
  assert(F && "Illegal to upgrade a non-existent Function.");

  // Quickly eliminate it, if it's not a candidate.
  StringRef Name = F->getName();
  if (Name.size() <= 8 || !Name.startswith("llvm."))
    return false;
  Name = Name.substr(5); // Strip off "llvm."

  switch (Name[0]) {
  default: break;
  case 'c': {
    if (Name.startswith("ctlz.") && F->arg_size() == 1) {
      F->setName(Name + ".old");
      NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
                                        F->arg_begin()->getType());
      return true;
    }
    if (Name.startswith("cttz.") && F->arg_size() == 1) {
      F->setName(Name + ".old");
      NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
                                        F->arg_begin()->getType());
      return true;
    }
    break;
  }
  }

  //  This may not belong here. This function is effectively being overloaded
  //  to both detect an intrinsic which needs upgrading, and to provide the
  //  upgraded form of the intrinsic. We should perhaps have two separate
  //  functions for this.
  return false;
}

bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
  NewFn = 0;
  bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);

  // Upgrade intrinsic attributes.  This does not change the function.
  if (NewFn)
    F = NewFn;
  if (unsigned id = F->getIntrinsicID())
    F->setAttributes(Intrinsic::getAttributes((Intrinsic::ID)id));
  return Upgraded;
}

bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
  // Nothing to do yet.
  return false;
}

// UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the
// upgraded intrinsic. All argument and return casting must be provided in
// order to seamlessly integrate with existing context.
void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
  Function *F = CI->getCalledFunction();
  LLVMContext &C = CI->getContext();

  assert(F && "CallInst has no function associated with it.");

  if (!NewFn) return;

  IRBuilder<> Builder(C);
  Builder.SetInsertPoint(CI->getParent(), CI);

  switch (NewFn->getIntrinsicID()) {
  default:
    llvm_unreachable("Unknown function for CallInst upgrade.");

  case Intrinsic::ctlz:
  case Intrinsic::cttz:
    assert(CI->getNumArgOperands() == 1 &&
           "Mismatch between function args and call args");
    StringRef Name = CI->getName();
    CI->setName(Name + ".old");
    CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
                                               Builder.getFalse(), Name));
    CI->eraseFromParent();
    return;
  }
}

// This tests each Function to determine if it needs upgrading. When we find
// one we are interested in, we then upgrade all calls to reflect the new
// function.
void llvm::UpgradeCallsToIntrinsic(Function* F) {
  assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");

  // Upgrade the function and check if it is a totaly new function.
  Function *NewFn;
  if (UpgradeIntrinsicFunction(F, NewFn)) {
    if (NewFn != F) {
      // Replace all uses to the old function with the new one if necessary.
      for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
           UI != UE; ) {
        if (CallInst *CI = dyn_cast<CallInst>(*UI++))
          UpgradeIntrinsicCall(CI, NewFn);
      }
      // Remove old function, no longer used, from the module.
      F->eraseFromParent();
    }
  }
}

<commit_msg>Fix unused value warning for value used only in assert.<commit_after>//===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the auto-upgrade helper functions
//
//===----------------------------------------------------------------------===//

#include "llvm/AutoUpgrade.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instruction.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/IRBuilder.h"
#include <cstring>
using namespace llvm;

static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
  assert(F && "Illegal to upgrade a non-existent Function.");

  // Quickly eliminate it, if it's not a candidate.
  StringRef Name = F->getName();
  if (Name.size() <= 8 || !Name.startswith("llvm."))
    return false;
  Name = Name.substr(5); // Strip off "llvm."

  switch (Name[0]) {
  default: break;
  case 'c': {
    if (Name.startswith("ctlz.") && F->arg_size() == 1) {
      F->setName(Name + ".old");
      NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
                                        F->arg_begin()->getType());
      return true;
    }
    if (Name.startswith("cttz.") && F->arg_size() == 1) {
      F->setName(Name + ".old");
      NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
                                        F->arg_begin()->getType());
      return true;
    }
    break;
  }
  }

  //  This may not belong here. This function is effectively being overloaded
  //  to both detect an intrinsic which needs upgrading, and to provide the
  //  upgraded form of the intrinsic. We should perhaps have two separate
  //  functions for this.
  return false;
}

bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
  NewFn = 0;
  bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);

  // Upgrade intrinsic attributes.  This does not change the function.
  if (NewFn)
    F = NewFn;
  if (unsigned id = F->getIntrinsicID())
    F->setAttributes(Intrinsic::getAttributes((Intrinsic::ID)id));
  return Upgraded;
}

bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
  // Nothing to do yet.
  return false;
}

// UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the
// upgraded intrinsic. All argument and return casting must be provided in
// order to seamlessly integrate with existing context.
void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
  assert(CI->getCalledFunction() && "Intrinsic call is not direct?");
  if (!NewFn) return;

  LLVMContext &C = CI->getContext();
  IRBuilder<> Builder(C);
  Builder.SetInsertPoint(CI->getParent(), CI);

  switch (NewFn->getIntrinsicID()) {
  default:
    llvm_unreachable("Unknown function for CallInst upgrade.");

  case Intrinsic::ctlz:
  case Intrinsic::cttz:
    assert(CI->getNumArgOperands() == 1 &&
           "Mismatch between function args and call args");
    StringRef Name = CI->getName();
    CI->setName(Name + ".old");
    CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
                                               Builder.getFalse(), Name));
    CI->eraseFromParent();
    return;
  }
}

// This tests each Function to determine if it needs upgrading. When we find
// one we are interested in, we then upgrade all calls to reflect the new
// function.
void llvm::UpgradeCallsToIntrinsic(Function* F) {
  assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");

  // Upgrade the function and check if it is a totaly new function.
  Function *NewFn;
  if (UpgradeIntrinsicFunction(F, NewFn)) {
    if (NewFn != F) {
      // Replace all uses to the old function with the new one if necessary.
      for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
           UI != UE; ) {
        if (CallInst *CI = dyn_cast<CallInst>(*UI++))
          UpgradeIntrinsicCall(CI, NewFn);
      }
      // Remove old function, no longer used, from the module.
      F->eraseFromParent();
    }
  }
}

<|endoftext|>


<commit_before>
#include <functional>
#include <string>

#include "glog/logging.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/BIPM.hpp"
#include "quantities/constants.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/algebra.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
#include "testing_utilities/vanishes_before.hpp"

namespace principia {

using astronomy::EarthMass;
using astronomy::JulianYear;
using astronomy::JupiterMass;
using astronomy::LightYear;
using astronomy::LunarDistance;
using astronomy::Parsec;
using astronomy::SolarMass;
using constants::ElectronMass;
using constants::GravitationalConstant;
using constants::SpeedOfLight;
using constants::StandardGravity;
using constants::VacuumPermeability;
using constants::VacuumPermittivity;
using si::Ampere;
using si::AstronomicalUnit;
using si::Candela;
using si::Cycle;
using si::Day;
using si::Degree;
using si::Hour;
using si::Kelvin;
using si::Kilogram;
using si::Mega;
using si::Metre;
using si::Mole;
using si::Radian;
using si::Second;
using si::Steradian;
using testing_utilities::AlmostEquals;
using testing_utilities::RelativeError;
using testing_utilities::VanishesBefore;
using uk::Foot;
using uk::Furlong;
using uk::Mile;
using uk::Rood;
using ::testing::Lt;
using ::testing::MatchesRegex;

namespace quantities {

class QuantitiesTest : public testing::Test {
 protected:
};

using QuantitiesDeathTest = QuantitiesTest;

TEST_F(QuantitiesTest, AbsoluteValue) {
  EXPECT_EQ(Abs(-1729), 1729);
  EXPECT_EQ(Abs(1729), 1729);
}

TEST_F(QuantitiesTest, DimensionfulComparisons) {
  testing_utilities::TestOrder(EarthMass, JupiterMass);
  testing_utilities::TestOrder(LightYear, Parsec);
  testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight);
  testing_utilities::TestOrder(SpeedOfLight * Day, LightYear);
}

TEST_F(QuantitiesTest, DimensionlfulOperations) {
  testing_utilities::TestVectorSpace(
      0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour,
      -340.29 * Metre / Second, 0.0, 1.0, -2 * π, 1729.0, 0, 2);
  // Dimensionful multiplication is a tensor product, see [Tao 2012].
  testing_utilities::TestBilinearMap(
      std::multiplies<>(), SolarMass,
      ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 0, 2);
}

TEST_F(QuantitiesTest, DimensionlessExponentiation) {
  double const number   = π - 42;
  double positivePower = 1;
  double negativePower = 1;
  EXPECT_EQ(positivePower, Pow<0>(number));
  positivePower *= number;
  negativePower /= number;
  EXPECT_EQ(positivePower, Pow<1>(number));
  EXPECT_EQ(negativePower, Pow<-1>(number));
  positivePower *= number;
  negativePower /= number;
  EXPECT_EQ(positivePower, Pow<2>(number));
  EXPECT_EQ(negativePower, Pow<-2>(number));
  positivePower *= number;
  negativePower /= number;
  EXPECT_EQ(positivePower, Pow<3>(number));
  EXPECT_EQ(negativePower, Pow<-3>(number));
  positivePower *= number;
  negativePower /= number;
  // This one calls |std::pow|.
  EXPECT_THAT(positivePower, AlmostEquals(Pow<4>(number), 0, 1));
  EXPECT_THAT(negativePower, AlmostEquals(Pow<-4>(number), 0, 1));
}

// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)

TEST_F(QuantitiesTest, Formatting) {
  auto const all_the_units = 1 * Metre * Kilogram * Second * Ampere * Kelvin /
                                 (Mole * Candela * Cycle * Radian * Steradian);
  std::string const expected = std::string("+1e+00 m kg s A K mol^-1") +
                               " cd^-1 cycle^-1 rad^-1 sr^-1";
  std::string const actual = DebugString(all_the_units, 0);
  EXPECT_EQ(expected, actual);
  std::string const π17 = "\\+3\\.1415926535897931.e\\+00";
  EXPECT_THAT(DebugString(π), MatchesRegex(π17));
  std::string const minus_e17 = "\\-2\\.718281828459045..e\\+00";
  EXPECT_THAT(DebugString(-e), MatchesRegex(minus_e17));
}

TEST_F(QuantitiesTest, PhysicalConstants) {
  // By definition.
  EXPECT_THAT(1 / Pow<2>(SpeedOfLight),
              AlmostEquals(VacuumPermittivity * VacuumPermeability, 1));
  // The Keplerian approximation for the mass of the Sun
  // is fairly accurate.
  EXPECT_THAT(RelativeError(
                  4 * Pow<2>(π) * Pow<3>(AstronomicalUnit) /
                      (GravitationalConstant * Pow<2>(JulianYear)),
                  SolarMass),
              Lt(4E-5));
  EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6));
  // The Keplerian approximation for the mass of the Earth
  // is pretty bad, but the error is still only 1%.
  EXPECT_THAT(RelativeError(
                  4 * Pow<2>(π) * Pow<3>(LunarDistance) /
                      (GravitationalConstant * Pow<2>(27.321582 * Day)),
                  EarthMass),
              Lt(1E-2));
  EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4));
  // Delambre & Méchain.
  EXPECT_THAT(RelativeError(
                  GravitationalConstant * EarthMass /
                      Pow<2>(40 * Mega(Metre) / (2 * π)),
                  StandardGravity),
              Lt(4E-3));
  // Talleyrand.
  EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second),
              Lt(4E-3));
}

#pragma warning(default: 4566)

TEST_F(QuantitiesTest, TrigonometricFunctions) {
  EXPECT_EQ(Cos(0 * Degree), 1);
  EXPECT_EQ(Sin(0 * Degree), 0);
  EXPECT_THAT(Cos(90 * Degree), VanishesBefore(1.0, 0));
  EXPECT_EQ(Sin(90 * Degree), 1);
  EXPECT_EQ(Cos(180 * Degree), -1);
  EXPECT_THAT(Sin(180 * Degree), VanishesBefore(1.0, 1));
  EXPECT_THAT(Cos(-90 * Degree), VanishesBefore(1.0, 0));
  EXPECT_EQ(Sin(-90 * Degree), -1);
  for (int k = 1; k < 360; ++k) {
    // Don't test for multiples of 90 degrees as zeros lead to horrible
    // conditioning.
    if (k % 90 != 0) {
      EXPECT_THAT(Cos((90 - k) * Degree),
                  AlmostEquals(Sin(k * Degree), 0, 46));
      EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree),
                  AlmostEquals(Tan(k * Degree), 0, 2));
      EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
                  AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)),
                               0, 77));
      EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
                  AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit,
                                      Cos(k * Degree) * AstronomicalUnit),
                               0, 77));
      EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))),
                  AlmostEquals(Cos(k * Degree), 0, 7));
      EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))),
                  AlmostEquals(Sin(k * Degree), 0, 1));
    }
  }
  // Horribly conditioned near 0, so not in the loop above.
  EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree));
}

TEST_F(QuantitiesTest, HyperbolicFunctions) {
  EXPECT_EQ(Sinh(0 * Radian), 0);
  EXPECT_EQ(Cosh(0 * Radian), 1);
  EXPECT_EQ(Tanh(0 * Radian), 0);
  // Limits:
  EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian));
  EXPECT_EQ(Tanh(20 * Radian), 1);
  EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian));
  EXPECT_EQ(Tanh(-20 * Radian), -1);

  EXPECT_THAT(Sinh(2 * Radian) / Cosh(2 * Radian),
              AlmostEquals(Tanh(2 * Radian), 0, 1));
  EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)),
              AlmostEquals(-10 * Degree, 0, 1));
  EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)),
              AlmostEquals(10 * Degree, 19, 20));
  EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)),
              AlmostEquals(-10 * Degree, 0, 1));
}

TEST_F(QuantitiesTest, ExpLogAndSqrt) {
  EXPECT_THAT(std::exp(std::log(2) / 2), AlmostEquals(Sqrt(2), 1));
  EXPECT_EQ(std::exp(std::log(Rood / Pow<2>(Foot)) / 2) * Foot, Sqrt(Rood));
}

TEST_F(QuantitiesDeathTest, SerializationError) {
  EXPECT_DEATH({
    serialization::Quantity message;
    message.set_dimensions(0x7C00);
    message.set_magnitude(1.0);
    Speed const speed_of_light = Speed::ReadFromMessage(message);
  }, "representation.*dimensions");
}

TEST_F(QuantitiesTest, SerializationSuccess) {
  serialization::Quantity message;
  SpeedOfLight.WriteToMessage(&message);
  EXPECT_EQ(0x7C01, message.dimensions());
  EXPECT_EQ(299792458.0, message.magnitude());
  Speed const speed_of_light = Speed::ReadFromMessage(message);
  EXPECT_EQ(SpeedOfLight, speed_of_light);
}

}  // namespace quantities
}  // namespace principia
<commit_msg>Trig.<commit_after>
#include <functional>
#include <string>

#include "glog/logging.h"
#include "gtest/gtest.h"
#include "quantities/astronomy.hpp"
#include "quantities/BIPM.hpp"
#include "quantities/constants.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
#include "quantities/uk.hpp"
#include "testing_utilities/algebra.hpp"
#include "testing_utilities/almost_equals.hpp"
#include "testing_utilities/numerics.hpp"
#include "testing_utilities/vanishes_before.hpp"
namespace principia {

using astronomy::EarthMass;
using astronomy::JulianYear;
using astronomy::JupiterMass;
using astronomy::LightYear;
using astronomy::LunarDistance;
using astronomy::Parsec;
using astronomy::SolarMass;
using constants::ElectronMass;
using constants::GravitationalConstant;
using constants::SpeedOfLight;
using constants::StandardGravity;
using constants::VacuumPermeability;
using constants::VacuumPermittivity;
using si::Ampere;
using si::AstronomicalUnit;
using si::Candela;
using si::Cycle;
using si::Day;
using si::Degree;
using si::Hour;
using si::Kelvin;
using si::Kilogram;
using si::Mega;
using si::Metre;
using si::Mole;
using si::Radian;
using si::Second;
using si::Steradian;
using testing_utilities::AlmostEquals;
using testing_utilities::RelativeError;
using testing_utilities::VanishesBefore;
using uk::Foot;
using uk::Furlong;
using uk::Mile;
using uk::Rood;
using ::testing::Lt;
using ::testing::MatchesRegex;

namespace quantities {

class QuantitiesTest : public testing::Test {
 protected:
};

using QuantitiesDeathTest = QuantitiesTest;

TEST_F(QuantitiesTest, AbsoluteValue) {
  EXPECT_EQ(Abs(-1729), 1729);
  EXPECT_EQ(Abs(1729), 1729);
}

TEST_F(QuantitiesTest, DimensionfulComparisons) {
  testing_utilities::TestOrder(EarthMass, JupiterMass);
  testing_utilities::TestOrder(LightYear, Parsec);
  testing_utilities::TestOrder(-SpeedOfLight, SpeedOfLight);
  testing_utilities::TestOrder(SpeedOfLight * Day, LightYear);
}

TEST_F(QuantitiesTest, DimensionlfulOperations) {
  testing_utilities::TestVectorSpace(
      0 * Metre / Second, SpeedOfLight, 88 * Mile / Hour,
      -340.29 * Metre / Second, 0.0, 1.0, -2 * π, 1729.0, 0, 2);
  // Dimensionful multiplication is a tensor product, see [Tao 2012].
  testing_utilities::TestBilinearMap(
      std::multiplies<>(), SolarMass,
      ElectronMass, SpeedOfLight, 1 * Furlong / JulianYear, -e, 0, 2);
}

TEST_F(QuantitiesTest, DimensionlessExponentiation) {
  double const number   = π - 42;
  double positivePower = 1;
  double negativePower = 1;
  EXPECT_EQ(positivePower, Pow<0>(number));
  positivePower *= number;
  negativePower /= number;
  EXPECT_EQ(positivePower, Pow<1>(number));
  EXPECT_EQ(negativePower, Pow<-1>(number));
  positivePower *= number;
  negativePower /= number;
  EXPECT_EQ(positivePower, Pow<2>(number));
  EXPECT_EQ(negativePower, Pow<-2>(number));
  positivePower *= number;
  negativePower /= number;
  EXPECT_EQ(positivePower, Pow<3>(number));
  EXPECT_EQ(negativePower, Pow<-3>(number));
  positivePower *= number;
  negativePower /= number;
  // This one calls |std::pow|.
  EXPECT_THAT(positivePower, AlmostEquals(Pow<4>(number), 0, 1));
  EXPECT_THAT(negativePower, AlmostEquals(Pow<-4>(number), 0, 1));
}

// The Greek letters cause a warning when stringified by the macros, because
// apparently Visual Studio doesn't encode strings in UTF-8 by default.
#pragma warning(disable: 4566)

TEST_F(QuantitiesTest, Formatting) {
  auto const all_the_units = 1 * Metre * Kilogram * Second * Ampere * Kelvin /
                                 (Mole * Candela * Cycle * Radian * Steradian);
  std::string const expected = std::string("+1e+00 m kg s A K mol^-1") +
                               " cd^-1 cycle^-1 rad^-1 sr^-1";
  std::string const actual = DebugString(all_the_units, 0);
  EXPECT_EQ(expected, actual);
  std::string const π17 = "\\+3\\.1415926535897931.e\\+00";
  EXPECT_THAT(DebugString(π), MatchesRegex(π17));
  std::string const minus_e17 = "\\-2\\.718281828459045..e\\+00";
  EXPECT_THAT(DebugString(-e), MatchesRegex(minus_e17));
}

TEST_F(QuantitiesTest, PhysicalConstants) {
  // By definition.
  EXPECT_THAT(1 / Pow<2>(SpeedOfLight),
              AlmostEquals(VacuumPermittivity * VacuumPermeability, 1));
  // The Keplerian approximation for the mass of the Sun
  // is fairly accurate.
  EXPECT_THAT(RelativeError(
                  4 * Pow<2>(π) * Pow<3>(AstronomicalUnit) /
                      (GravitationalConstant * Pow<2>(JulianYear)),
                  SolarMass),
              Lt(4E-5));
  EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2E-6));
  // The Keplerian approximation for the mass of the Earth
  // is pretty bad, but the error is still only 1%.
  EXPECT_THAT(RelativeError(
                  4 * Pow<2>(π) * Pow<3>(LunarDistance) /
                      (GravitationalConstant * Pow<2>(27.321582 * Day)),
                  EarthMass),
              Lt(1E-2));
  EXPECT_THAT(RelativeError(1 * SolarMass, 1047 * JupiterMass), Lt(4E-4));
  // Delambre & Méchain.
  EXPECT_THAT(RelativeError(
                  GravitationalConstant * EarthMass /
                      Pow<2>(40 * Mega(Metre) / (2 * π)),
                  StandardGravity),
              Lt(4E-3));
  // Talleyrand.
  EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second),
              Lt(4E-3));
}

#pragma warning(default: 4566)

TEST_F(QuantitiesTest, TrigonometricFunctions) {
  EXPECT_EQ(Cos(0 * Degree), 1);
  EXPECT_EQ(Sin(0 * Degree), 0);
  EXPECT_THAT(Cos(90 * Degree), VanishesBefore(1.0, 0));
  EXPECT_EQ(Sin(90 * Degree), 1);
  EXPECT_EQ(Cos(180 * Degree), -1);
  EXPECT_THAT(Sin(180 * Degree), VanishesBefore(1.0, 1));
  EXPECT_THAT(Cos(-90 * Degree), VanishesBefore(1.0, 0));
  EXPECT_EQ(Sin(-90 * Degree), -1);
  for (int k = 1; k < 360; ++k) {
    // Don't test for multiples of 90 degrees as zeros lead to horrible
    // conditioning.
    if (k % 90 != 0) {
      EXPECT_THAT(Cos((90 - k) * Degree),
                  AlmostEquals(Sin(k * Degree), 0, 47));
      EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree),
                  AlmostEquals(Tan(k * Degree), 0, 2));
      EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
                  AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)),
                               0, 77));
      EXPECT_THAT(((k + 179) % 360 - 179) * Degree,
                  AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit,
                                      Cos(k * Degree) * AstronomicalUnit),
                               0, 77));
      EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))),
                  AlmostEquals(Cos(k * Degree), 0, 7));
      EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))),
                  AlmostEquals(Sin(k * Degree), 0, 1));
    }
  }
  // Horribly conditioned near 0, so not in the loop above.
  EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree));
}

TEST_F(QuantitiesTest, HyperbolicFunctions) {
  EXPECT_EQ(Sinh(0 * Radian), 0);
  EXPECT_EQ(Cosh(0 * Radian), 1);
  EXPECT_EQ(Tanh(0 * Radian), 0);
  // Limits:
  EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian));
  EXPECT_EQ(Tanh(20 * Radian), 1);
  EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian));
  EXPECT_EQ(Tanh(-20 * Radian), -1);

  EXPECT_THAT(Sinh(2 * Radian) / Cosh(2 * Radian),
              AlmostEquals(Tanh(2 * Radian), 0, 1));
  EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)),
              AlmostEquals(-10 * Degree, 0, 1));
  EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)),
              AlmostEquals(10 * Degree, 19, 20));
  EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)),
              AlmostEquals(-10 * Degree, 0, 1));
}

TEST_F(QuantitiesTest, ExpLogAndSqrt) {
  EXPECT_THAT(std::exp(std::log(2) / 2), AlmostEquals(Sqrt(2), 1));
  EXPECT_EQ(std::exp(std::log(Rood / Pow<2>(Foot)) / 2) * Foot, Sqrt(Rood));
}

TEST_F(QuantitiesDeathTest, SerializationError) {
  EXPECT_DEATH({
    serialization::Quantity message;
    message.set_dimensions(0x7C00);
    message.set_magnitude(1.0);
    Speed const speed_of_light = Speed::ReadFromMessage(message);
  }, "representation.*dimensions");
}

TEST_F(QuantitiesTest, SerializationSuccess) {
  serialization::Quantity message;
  SpeedOfLight.WriteToMessage(&message);
  EXPECT_EQ(0x7C01, message.dimensions());
  EXPECT_EQ(299792458.0, message.magnitude());
  Speed const speed_of_light = Speed::ReadFromMessage(message);
  EXPECT_EQ(SpeedOfLight, speed_of_light);
}

}  // namespace quantities
}  // namespace principia
<|endoftext|>


<commit_before><commit_msg>Always send Retrieve in Network::registerCaller()<commit_after><|endoftext|>


<commit_before>// Copyright (C) 2011 The Libphonenumber Authors
//
// Licensed 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.

// Author: Philippe Liard

#include <iostream>

#include <gtest/gtest.h>

#include "phonenumbers/unicodestring.h"

using std::ostream;

// Used by GTest to print the expected and actual results in case of failure.
ostream& operator<<(ostream& out, const i18n::phonenumbers::UnicodeString& s) {
  string utf8;
  s.toUTF8String(utf8);
  out << utf8;
  return out;
}

namespace i18n {
namespace phonenumbers {

TEST(UnicodeString, ToUTF8StringWithEmptyString) {
  UnicodeString s;
  string utf8;
  s.toUTF8String(utf8);
  EXPECT_EQ("", utf8);
}

TEST(UnicodeString, ToUTF8String) {
  UnicodeString s("hello");
  string utf8;
  s.toUTF8String(utf8);
  EXPECT_EQ("hello", utf8);
}

TEST(UnicodeString, ToUTF8StringWithNonAscii) {
  UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" /* "５３" */);
  string utf8;
  s.toUTF8String(utf8);
  EXPECT_EQ("\xEF\xBC\x95\xEF\xBC\x93", utf8);
}

TEST(UnicodeString, AppendCodepoint) {
  UnicodeString s;
  s.append('h');
  ASSERT_EQ(UnicodeString("h"), s);
  s.append('e');
  EXPECT_EQ(UnicodeString("he"), s);
}

TEST(UnicodeString, AppendCodepointWithNonAscii) {
  UnicodeString s;
  s.append(0xFF15 /* ５ */);
  ASSERT_EQ(UnicodeString("\xEF\xBC\x95" /* ５ */), s);
  s.append(0xFF13 /* ３ */);
  EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" /* ５３ */), s);
}

TEST(UnicodeString, AppendUnicodeString) {
  UnicodeString s;
  s.append(UnicodeString("he"));
  ASSERT_EQ(UnicodeString("he"), s);
  s.append(UnicodeString("llo"));
  EXPECT_EQ(UnicodeString("hello"), s);
}

TEST(UnicodeString, AppendUnicodeStringWithNonAscii) {
  UnicodeString s;
  s.append(UnicodeString("\xEF\xBC\x95" /* ５ */));
  ASSERT_EQ(UnicodeString("\xEF\xBC\x95"), s);
  s.append(UnicodeString("\xEF\xBC\x93" /* ３ */));
  EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" /* ５３ */), s);
}

TEST(UnicodeString, IndexOf) {
  UnicodeString s("hello");
  EXPECT_EQ(0, s.indexOf('h'));
  EXPECT_EQ(2, s.indexOf('l'));
  EXPECT_EQ(4, s.indexOf('o'));
}

TEST(UnicodeString, IndexOfWithNonAscii) {
  UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" /* ５３ */);
  EXPECT_EQ(1, s.indexOf(0xFF13 /* ３ */));
}

TEST(UnicodeString, ReplaceWithEmptyInputs) {
  UnicodeString s;
  s.replace(0, 0, UnicodeString(""));
  EXPECT_EQ(UnicodeString(""), s);
}

TEST(UnicodeString, ReplaceWithEmptyReplacement) {
  UnicodeString s("hello");
  s.replace(0, 5, UnicodeString(""));
  EXPECT_EQ(UnicodeString(""), s);
}

TEST(UnicodeString, ReplaceBegining) {
  UnicodeString s("hello world");
  s.replace(0, 5, UnicodeString("HELLO"));
  EXPECT_EQ(UnicodeString("HELLO world"), s);
}

TEST(UnicodeString, ReplaceMiddle) {
  UnicodeString s("hello world");
  s.replace(5, 1, UnicodeString("AB"));
  EXPECT_EQ(UnicodeString("helloABworld"), s);
}

TEST(UnicodeString, ReplaceEnd) {
  UnicodeString s("hello world");
  s.replace(10, 1, UnicodeString("AB"));
  EXPECT_EQ(UnicodeString("hello worlAB"), s);
}

TEST(UnicodeString, ReplaceWithNonAscii) {
  UnicodeString s("hello world");
  s.replace(3, 2, UnicodeString("\xEF\xBC\x91\xEF\xBC\x90" /* １０ */));
  EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90 world"), s);
}

TEST(UnicodeString, SetCharBegining) {
  UnicodeString s("hello");
  s.setCharAt(0, 'H');
  EXPECT_EQ(UnicodeString("Hello"), s);
}

TEST(UnicodeString, SetCharMiddle) {
  UnicodeString s("hello");
  s.setCharAt(2, 'L');
  EXPECT_EQ(UnicodeString("heLlo"), s);
}

TEST(UnicodeString, SetCharEnd) {
  UnicodeString s("hello");
  s.setCharAt(4, 'O');
  EXPECT_EQ(UnicodeString("hellO"), s);
}

TEST(UnicodeString, SetCharWithNonAscii) {
  UnicodeString s("hello");
  s.setCharAt(4, 0xFF10 /* ０ */);
  EXPECT_EQ(UnicodeString("hell\xEF\xBC\x90" /* ０ */), s);
}

TEST(UnicodeString, TempSubStringWithEmptyString) {
  EXPECT_EQ(UnicodeString(""), UnicodeString().tempSubString(0, 0));
}

TEST(UnicodeString, TempSubStringWithInvalidInputs) {
  UnicodeString s("hello");
  // tempSubString() returns an empty unicode string if one of the provided
  // paramaters is out of range.
  EXPECT_EQ(UnicodeString(""), s.tempSubString(6));
  EXPECT_EQ(UnicodeString(""), s.tempSubString(2, 6));
}

TEST(UnicodeString, TempSubString) {
  UnicodeString s("hello");
  EXPECT_EQ(UnicodeString(""), s.tempSubString(0, 0));
  EXPECT_EQ(UnicodeString("h"), s.tempSubString(0, 1));
  EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0, 5));
  EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2, 3));
}

TEST(UnicodeString, TempSubStringWithNoLength) {
  UnicodeString s("hello");
  EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0));
  EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2));
}

TEST(UnicodeString, TempSubStringWithNonAscii) {
  UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" /* １０ */);
  EXPECT_EQ(UnicodeString("\xEF\xBC\x91" /* １ */), s.tempSubString(3, 1));
}

TEST(UnicodeString, OperatorEqual) {
  UnicodeString s("hello");
  s = UnicodeString("Hello");
  EXPECT_EQ(UnicodeString("Hello"), s);
}

TEST(UnicodeString, OperatorEqualWithNonAscii) {
  UnicodeString s("hello");
  s = UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90" /* １０ */);
  EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90"), s);
}

TEST(UnicodeString, OperatorBracket) {
  UnicodeString s("hello");
  EXPECT_EQ('h', s[0]);
  EXPECT_EQ('e', s[1]);
  EXPECT_EQ('l', s[2]);
  EXPECT_EQ('l', s[3]);
  EXPECT_EQ('o', s[4]);
}

TEST(UnicodeString, OperatorBracketWithNonAscii) {
  UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" /* １０ */);
  EXPECT_EQ('h', s[0]);
  EXPECT_EQ('e', s[1]);
  EXPECT_EQ('l', s[2]);
  EXPECT_EQ(0xFF11 /* １ */, s[3]);
  EXPECT_EQ(0xFF10 /* ０ */, s[4]);
}

TEST(UnicodeString, OperatorBracketWithIteratorCacheInvalidation) {
  UnicodeString s("hello");
  EXPECT_EQ('h', s[0]);
  EXPECT_EQ('e', s[1]);
  // Modify the string which should invalidate the iterator cache.
  s.setCharAt(1, 'E');
  EXPECT_EQ(UnicodeString("hEllo"), s);
  EXPECT_EQ('E', s[1]);
  // Get the previous character which should invalidate the iterator cache.
  EXPECT_EQ('h', s[0]);
  EXPECT_EQ('o', s[4]);
}

}  // namespace phonenumbers
}  // namespace i18n
<commit_msg>CPP: Fix compilation error on Clang. Patch contributed by KushalP.<commit_after>// Copyright (C) 2011 The Libphonenumber Authors
//
// Licensed 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.

// Author: Philippe Liard

#include <iostream>

#include <gtest/gtest.h>

#include "phonenumbers/unicodestring.h"

using std::ostream;

namespace i18n {
namespace phonenumbers {

// Used by GTest to print the expected and actual results in case of failure.
ostream& operator<<(ostream& out, const UnicodeString& s) {
  string utf8;
  s.toUTF8String(utf8);
  out << utf8;
  return out;
}

TEST(UnicodeString, ToUTF8StringWithEmptyString) {
  UnicodeString s;
  string utf8;
  s.toUTF8String(utf8);
  EXPECT_EQ("", utf8);
}

TEST(UnicodeString, ToUTF8String) {
  UnicodeString s("hello");
  string utf8;
  s.toUTF8String(utf8);
  EXPECT_EQ("hello", utf8);
}

TEST(UnicodeString, ToUTF8StringWithNonAscii) {
  UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" /* "５３" */);
  string utf8;
  s.toUTF8String(utf8);
  EXPECT_EQ("\xEF\xBC\x95\xEF\xBC\x93", utf8);
}

TEST(UnicodeString, AppendCodepoint) {
  UnicodeString s;
  s.append('h');
  ASSERT_EQ(UnicodeString("h"), s);
  s.append('e');
  EXPECT_EQ(UnicodeString("he"), s);
}

TEST(UnicodeString, AppendCodepointWithNonAscii) {
  UnicodeString s;
  s.append(0xFF15 /* ５ */);
  ASSERT_EQ(UnicodeString("\xEF\xBC\x95" /* ５ */), s);
  s.append(0xFF13 /* ３ */);
  EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" /* ５３ */), s);
}

TEST(UnicodeString, AppendUnicodeString) {
  UnicodeString s;
  s.append(UnicodeString("he"));
  ASSERT_EQ(UnicodeString("he"), s);
  s.append(UnicodeString("llo"));
  EXPECT_EQ(UnicodeString("hello"), s);
}

TEST(UnicodeString, AppendUnicodeStringWithNonAscii) {
  UnicodeString s;
  s.append(UnicodeString("\xEF\xBC\x95" /* ５ */));
  ASSERT_EQ(UnicodeString("\xEF\xBC\x95"), s);
  s.append(UnicodeString("\xEF\xBC\x93" /* ３ */));
  EXPECT_EQ(UnicodeString("\xEF\xBC\x95\xEF\xBC\x93" /* ５３ */), s);
}

TEST(UnicodeString, IndexOf) {
  UnicodeString s("hello");
  EXPECT_EQ(0, s.indexOf('h'));
  EXPECT_EQ(2, s.indexOf('l'));
  EXPECT_EQ(4, s.indexOf('o'));
}

TEST(UnicodeString, IndexOfWithNonAscii) {
  UnicodeString s("\xEF\xBC\x95\xEF\xBC\x93" /* ５３ */);
  EXPECT_EQ(1, s.indexOf(0xFF13 /* ３ */));
}

TEST(UnicodeString, ReplaceWithEmptyInputs) {
  UnicodeString s;
  s.replace(0, 0, UnicodeString(""));
  EXPECT_EQ(UnicodeString(""), s);
}

TEST(UnicodeString, ReplaceWithEmptyReplacement) {
  UnicodeString s("hello");
  s.replace(0, 5, UnicodeString(""));
  EXPECT_EQ(UnicodeString(""), s);
}

TEST(UnicodeString, ReplaceBegining) {
  UnicodeString s("hello world");
  s.replace(0, 5, UnicodeString("HELLO"));
  EXPECT_EQ(UnicodeString("HELLO world"), s);
}

TEST(UnicodeString, ReplaceMiddle) {
  UnicodeString s("hello world");
  s.replace(5, 1, UnicodeString("AB"));
  EXPECT_EQ(UnicodeString("helloABworld"), s);
}

TEST(UnicodeString, ReplaceEnd) {
  UnicodeString s("hello world");
  s.replace(10, 1, UnicodeString("AB"));
  EXPECT_EQ(UnicodeString("hello worlAB"), s);
}

TEST(UnicodeString, ReplaceWithNonAscii) {
  UnicodeString s("hello world");
  s.replace(3, 2, UnicodeString("\xEF\xBC\x91\xEF\xBC\x90" /* １０ */));
  EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90 world"), s);
}

TEST(UnicodeString, SetCharBegining) {
  UnicodeString s("hello");
  s.setCharAt(0, 'H');
  EXPECT_EQ(UnicodeString("Hello"), s);
}

TEST(UnicodeString, SetCharMiddle) {
  UnicodeString s("hello");
  s.setCharAt(2, 'L');
  EXPECT_EQ(UnicodeString("heLlo"), s);
}

TEST(UnicodeString, SetCharEnd) {
  UnicodeString s("hello");
  s.setCharAt(4, 'O');
  EXPECT_EQ(UnicodeString("hellO"), s);
}

TEST(UnicodeString, SetCharWithNonAscii) {
  UnicodeString s("hello");
  s.setCharAt(4, 0xFF10 /* ０ */);
  EXPECT_EQ(UnicodeString("hell\xEF\xBC\x90" /* ０ */), s);
}

TEST(UnicodeString, TempSubStringWithEmptyString) {
  EXPECT_EQ(UnicodeString(""), UnicodeString().tempSubString(0, 0));
}

TEST(UnicodeString, TempSubStringWithInvalidInputs) {
  UnicodeString s("hello");
  // tempSubString() returns an empty unicode string if one of the provided
  // paramaters is out of range.
  EXPECT_EQ(UnicodeString(""), s.tempSubString(6));
  EXPECT_EQ(UnicodeString(""), s.tempSubString(2, 6));
}

TEST(UnicodeString, TempSubString) {
  UnicodeString s("hello");
  EXPECT_EQ(UnicodeString(""), s.tempSubString(0, 0));
  EXPECT_EQ(UnicodeString("h"), s.tempSubString(0, 1));
  EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0, 5));
  EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2, 3));
}

TEST(UnicodeString, TempSubStringWithNoLength) {
  UnicodeString s("hello");
  EXPECT_EQ(UnicodeString("hello"), s.tempSubString(0));
  EXPECT_EQ(UnicodeString("llo"), s.tempSubString(2));
}

TEST(UnicodeString, TempSubStringWithNonAscii) {
  UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" /* １０ */);
  EXPECT_EQ(UnicodeString("\xEF\xBC\x91" /* １ */), s.tempSubString(3, 1));
}

TEST(UnicodeString, OperatorEqual) {
  UnicodeString s("hello");
  s = UnicodeString("Hello");
  EXPECT_EQ(UnicodeString("Hello"), s);
}

TEST(UnicodeString, OperatorEqualWithNonAscii) {
  UnicodeString s("hello");
  s = UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90" /* １０ */);
  EXPECT_EQ(UnicodeString("hel\xEF\xBC\x91\xEF\xBC\x90"), s);
}

TEST(UnicodeString, OperatorBracket) {
  UnicodeString s("hello");
  EXPECT_EQ('h', s[0]);
  EXPECT_EQ('e', s[1]);
  EXPECT_EQ('l', s[2]);
  EXPECT_EQ('l', s[3]);
  EXPECT_EQ('o', s[4]);
}

TEST(UnicodeString, OperatorBracketWithNonAscii) {
  UnicodeString s("hel\xEF\xBC\x91\xEF\xBC\x90" /* １０ */);
  EXPECT_EQ('h', s[0]);
  EXPECT_EQ('e', s[1]);
  EXPECT_EQ('l', s[2]);
  EXPECT_EQ(0xFF11 /* １ */, s[3]);
  EXPECT_EQ(0xFF10 /* ０ */, s[4]);
}

TEST(UnicodeString, OperatorBracketWithIteratorCacheInvalidation) {
  UnicodeString s("hello");
  EXPECT_EQ('h', s[0]);
  EXPECT_EQ('e', s[1]);
  // Modify the string which should invalidate the iterator cache.
  s.setCharAt(1, 'E');
  EXPECT_EQ(UnicodeString("hEllo"), s);
  EXPECT_EQ('E', s[1]);
  // Get the previous character which should invalidate the iterator cache.
  EXPECT_EQ('h', s[0]);
  EXPECT_EQ('o', s[4]);
}

}  // namespace phonenumbers
}  // namespace i18n
<|endoftext|>