<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/search_engines/search_terms_data.h"

#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/google/google_url_tracker.h"
#include "googleurl/src/gurl.h"

#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
#include "chrome/browser/rlz/rlz.h"
#include "chrome/installer/util/google_update_settings.h"
#endif

SearchTermsData::SearchTermsData() {
}

SearchTermsData::~SearchTermsData() {
}

std::string SearchTermsData::GoogleBaseSuggestURLValue() const {
  // The suggest base URL we want at the end is something like
  // "http://clients1.google.TLD/complete/".  The key bit we want from the
  // original Google base URL is the TLD.

  // Start with the Google base URL.
  const GURL base_url(GoogleBaseURLValue());
  DCHECK(base_url.is_valid());

  // Change "www." to "clients1." in the hostname.  If no "www." was found, just
  // prepend "clients1.".
  const std::string base_host(base_url.host());
  GURL::Replacements repl;
  const std::string suggest_host("clients1." +
      (base_host.compare(0, 4, "www.") ? base_host : base_host.substr(4)));
  repl.SetHostStr(suggest_host);

  // Replace any existing path with "/complete/".
  static const std::string suggest_path("/complete/");
  repl.SetPathStr(suggest_path);

  // Clear the query and ref.
  repl.ClearQuery();
  repl.ClearRef();
  return base_url.ReplaceComponents(repl).spec();
}

// static
std::string* UIThreadSearchTermsData::google_base_url_ = NULL;

UIThreadSearchTermsData::UIThreadSearchTermsData() {
  // GoogleURLTracker::GoogleURL() DCHECKs this also, but adding it here helps
  // us catch bad behavior at a more common place in this code.
  DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
}

std::string UIThreadSearchTermsData::GoogleBaseURLValue() const {
  DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
  return google_base_url_ ?
    (*google_base_url_) : GoogleURLTracker::GoogleURL().spec();
}

std::string UIThreadSearchTermsData::GetApplicationLocale() const {
  DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
  return g_browser_process->GetApplicationLocale();
}

#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
std::wstring UIThreadSearchTermsData::GetRlzParameterValue() const {
  DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
  std::wstring rlz_string;
  // For organic brandcodes do not use rlz at all. Empty brandcode usually
  // means a chromium install. This is ok.
  std::wstring brand;
  if (GoogleUpdateSettings::GetBrand(&brand) && !brand.empty() &&
      !GoogleUpdateSettings::IsOrganic(brand))
    RLZTracker::GetAccessPointRlz(rlz_lib::CHROME_OMNIBOX, &rlz_string);
  return rlz_string;
}
#endif

// static
void UIThreadSearchTermsData::SetGoogleBaseURL(std::string* google_base_url) {
  delete google_base_url_;
  google_base_url_ = google_base_url;
}
<commit_msg>Adding ScopedAllowIO to GetRlzParameterValue() while we evaluate wether the access to IO is ok here.<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/search_engines/search_terms_data.h"

#include "base/logging.h"
#include "base/thread_restrictions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/google/google_url_tracker.h"
#include "googleurl/src/gurl.h"

#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
#include "chrome/browser/rlz/rlz.h"
#include "chrome/installer/util/google_update_settings.h"
#endif

SearchTermsData::SearchTermsData() {
}

SearchTermsData::~SearchTermsData() {
}

std::string SearchTermsData::GoogleBaseSuggestURLValue() const {
  // The suggest base URL we want at the end is something like
  // "http://clients1.google.TLD/complete/".  The key bit we want from the
  // original Google base URL is the TLD.

  // Start with the Google base URL.
  const GURL base_url(GoogleBaseURLValue());
  DCHECK(base_url.is_valid());

  // Change "www." to "clients1." in the hostname.  If no "www." was found, just
  // prepend "clients1.".
  const std::string base_host(base_url.host());
  GURL::Replacements repl;
  const std::string suggest_host("clients1." +
      (base_host.compare(0, 4, "www.") ? base_host : base_host.substr(4)));
  repl.SetHostStr(suggest_host);

  // Replace any existing path with "/complete/".
  static const std::string suggest_path("/complete/");
  repl.SetPathStr(suggest_path);

  // Clear the query and ref.
  repl.ClearQuery();
  repl.ClearRef();
  return base_url.ReplaceComponents(repl).spec();
}

// static
std::string* UIThreadSearchTermsData::google_base_url_ = NULL;

UIThreadSearchTermsData::UIThreadSearchTermsData() {
  // GoogleURLTracker::GoogleURL() DCHECKs this also, but adding it here helps
  // us catch bad behavior at a more common place in this code.
  DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
}

std::string UIThreadSearchTermsData::GoogleBaseURLValue() const {
  DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
  return google_base_url_ ?
    (*google_base_url_) : GoogleURLTracker::GoogleURL().spec();
}

std::string UIThreadSearchTermsData::GetApplicationLocale() const {
  DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
  return g_browser_process->GetApplicationLocale();
}

#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
std::wstring UIThreadSearchTermsData::GetRlzParameterValue() const {
  DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
  std::wstring rlz_string;
  // For organic brandcodes do not use rlz at all. Empty brandcode usually
  // means a chromium install. This is ok.
  std::wstring brand;
  // See http://crbug.com/62337.
  base::ThreadRestrictions::ScopedAllowIO allow_io;
  if (GoogleUpdateSettings::GetBrand(&brand) && !brand.empty() &&
      !GoogleUpdateSettings::IsOrganic(brand))
    RLZTracker::GetAccessPointRlz(rlz_lib::CHROME_OMNIBOX, &rlz_string);
  return rlz_string;
}
#endif

// static
void UIThreadSearchTermsData::SetGoogleBaseURL(std::string* google_base_url) {
  delete google_base_url_;
  google_base_url_ = google_base_url;
}
<|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.

#include <limits>
#include <string>

#include "base/file_util.h"
#include "base/memory/scoped_temp_dir.h"
#include "chrome/browser/password_manager/encryptor.h"
#include "chrome/browser/sync/syncable/directory_manager.h"
#include "chrome/browser/sync/util/user_settings.h"
#include "chrome/common/sqlite_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

using browser_sync::APEncode;
using browser_sync::APDecode;
using browser_sync::ExecOrDie;
using browser_sync::UserSettings;

using std::numeric_limits;

static const FilePath::CharType kV10UserSettingsDB[] =
    FILE_PATH_LITERAL("Version10Settings.sqlite3");
static const FilePath::CharType kV11UserSettingsDB[] =
    FILE_PATH_LITERAL("Version11Settings.sqlite3");
static const FilePath::CharType kOldStyleSyncDataDB[] =
    FILE_PATH_LITERAL("OldStyleSyncData.sqlite3");

class UserSettingsTest : public testing::Test {
 public:
  UserSettingsTest() : sync_data_("Some sync data") { }

  virtual void SetUp() {
#if defined(OS_MACOSX)
    // Need to mock the Keychain for unit tests on Mac to avoid possible
    // blocking UI.  |SetAuthTokenForService| uses Encryptor.
    Encryptor::UseMockKeychain(true);
#endif
  }

  // Creates and populates the V10 database files within
  // |destination_directory|.
  void SetUpVersion10Databases(const FilePath& destination_directory) {
    sqlite3* primer_handle = NULL;
    v10_user_setting_db_path_ =
        destination_directory.Append(FilePath(kV10UserSettingsDB));
    ASSERT_EQ(SQLITE_OK, sqlite_utils::OpenSqliteDb(v10_user_setting_db_path_,
                                                    &primer_handle));
    sqlite_utils::scoped_sqlite_db_ptr db(primer_handle);

    old_style_sync_data_path_ =
        destination_directory.Append(FilePath(kOldStyleSyncDataDB));

    ASSERT_EQ(sync_data_.length(),
              static_cast<size_t>(file_util::WriteFile(
                  old_style_sync_data_path_, sync_data_.data(),
                  sync_data_.length())));

    // Create settings table.
    ExecOrDie(primer_handle, "CREATE TABLE settings"
              " (email, key, value, "
              "  PRIMARY KEY(email, key) ON CONFLICT REPLACE)");
    // Add a blank signin table.
    ExecOrDie(primer_handle, "CREATE TABLE signin_types"
              " (signin, signin_type)");
    // Create and populate version table.
    ExecOrDie(primer_handle, "CREATE TABLE db_version ( version )");
    {
      SQLStatement statement;
      const char query[] = "INSERT INTO db_version values ( ? )";
      statement.prepare(primer_handle, query);
      statement.bind_int(0, 10);
      if (SQLITE_DONE != statement.step()) {
        LOG(FATAL) << query << "\n" << sqlite3_errmsg(primer_handle);
      }
    }
    // Create shares table.
    ExecOrDie(primer_handle, "CREATE TABLE shares"
              " (email, share_name, file_name,"
              "  PRIMARY KEY(email, share_name) ON CONFLICT REPLACE)");
    // Populate a share.
    {
      SQLStatement statement;
      const char query[] = "INSERT INTO shares values ( ?, ?, ? )";
      statement.prepare(primer_handle, query);
      statement.bind_string(0, "foo@foo.com");
      statement.bind_string(1, "foo@foo.com");
#if defined(OS_WIN)
      statement.bind_string(2, WideToUTF8(old_style_sync_data_path_.value()));
#elif defined(OS_POSIX)
      statement.bind_string(2, old_style_sync_data_path_.value());
#endif
      if (SQLITE_DONE != statement.step()) {
        LOG(FATAL) << query << "\n" << sqlite3_errmsg(primer_handle);
      }
    }
  }

   // Creates and populates the V11 database file within
  // |destination_directory|.
  void SetUpVersion11Database(const FilePath& destination_directory) {
    sqlite3* primer_handle = NULL;
    v11_user_setting_db_path_ =
        destination_directory.Append(FilePath(kV11UserSettingsDB));
    ASSERT_EQ(SQLITE_OK, sqlite_utils::OpenSqliteDb(v11_user_setting_db_path_,
                                                    &primer_handle));
    sqlite_utils::scoped_sqlite_db_ptr db(primer_handle);

    // Create settings table.
    ExecOrDie(primer_handle, "CREATE TABLE settings"
              " (email, key, value, "
              "  PRIMARY KEY(email, key) ON CONFLICT REPLACE)");

    // Create and populate version table.
    ExecOrDie(primer_handle, "CREATE TABLE db_version ( version )");
    {
      SQLStatement statement;
      const char query[] = "INSERT INTO db_version values ( ? )";
      statement.prepare(primer_handle, query);
      statement.bind_int(0, 11);
      if (SQLITE_DONE != statement.step()) {
        LOG(FATAL) << query << "\n" << sqlite3_errmsg(primer_handle);
      }
    }

    ExecOrDie(primer_handle, "CREATE TABLE signin_types"
              " (signin, signin_type)");

    {
      SQLStatement statement;
      const char query[] = "INSERT INTO signin_types values ( ?, ? )";
      statement.prepare(primer_handle, query);
      statement.bind_string(0, "test");
      statement.bind_string(1, "test");
      if (SQLITE_DONE != statement.step()) {
        LOG(FATAL) << query << "\n" << sqlite3_errmsg(primer_handle);
      }
    }
  }

  const std::string& sync_data() const { return sync_data_; }
  const FilePath& v10_user_setting_db_path() const {
    return v10_user_setting_db_path_;
  }
  const FilePath& v11_user_setting_db_path() const {
    return v11_user_setting_db_path_;
  }
  const FilePath& old_style_sync_data_path() const {
    return old_style_sync_data_path_;
  }

 private:
  FilePath v10_user_setting_db_path_;
  FilePath old_style_sync_data_path_;

  FilePath v11_user_setting_db_path_;

  std::string sync_data_;
};

TEST_F(UserSettingsTest, MigrateFromV10ToV11) {
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  SetUpVersion10Databases(temp_dir.path());
  {
    // Create a UserSettings, which should trigger migration code. We do this
    // inside a scoped block so it closes itself and we can poke around to see
    // what happened later.
    UserSettings settings;
    settings.Init(v10_user_setting_db_path());
  }

  // Now poke around using sqlite to see if UserSettings migrated properly.
  sqlite3* handle = NULL;
  ASSERT_EQ(SQLITE_OK, sqlite_utils::OpenSqliteDb(v10_user_setting_db_path(),
                                                  &handle));
  sqlite_utils::scoped_sqlite_db_ptr db(handle);

  // Note that we don't use ScopedStatement to avoid closing the sqlite handle
  // before finalizing the statement.
  {
    SQLStatement version_query;
    version_query.prepare(handle, "SELECT version FROM db_version");
    ASSERT_EQ(SQLITE_ROW, version_query.step());
    const int version = version_query.column_int(0);
    EXPECT_GE(version, 11);
  }

  EXPECT_FALSE(file_util::PathExists(old_style_sync_data_path()));

  FilePath new_style_path = temp_dir.path().Append(
      syncable::DirectoryManager::GetSyncDataDatabaseFilename());

  std::string contents;
  ASSERT_TRUE(file_util::ReadFileToString(new_style_path, &contents));
  EXPECT_TRUE(sync_data() == contents);
}

TEST_F(UserSettingsTest, MigrateFromV11ToV12) {
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  SetUpVersion11Database(temp_dir.path());
  {
    UserSettings settings;
    settings.Init(v11_user_setting_db_path());
  }
  sqlite3* handle = NULL;
  ASSERT_EQ(SQLITE_OK, sqlite_utils::OpenSqliteDb(v11_user_setting_db_path(),
                                                  &handle));
  sqlite_utils::scoped_sqlite_db_ptr db(handle);

  {
    SQLStatement version_query;
    version_query.prepare(handle, "SELECT version FROM db_version");
    ASSERT_EQ(SQLITE_ROW, version_query.step());
    const int version = version_query.column_int(0);
    EXPECT_GE(version, 12);

    SQLStatement table_query;
    table_query.prepare(handle, "SELECT name FROM sqlite_master "
        "WHERE type='table' AND name='signin_types'");
    ASSERT_NE(SQLITE_ROW, table_query.step());
  }
}

TEST_F(UserSettingsTest, APEncode) {
  std::string test;
  char i;
  for (i = numeric_limits<char>::min(); i < numeric_limits<char>::max(); ++i)
    test.push_back(i);
  test.push_back(i);
  const std::string encoded = APEncode(test);
  const std::string decoded = APDecode(encoded);
  ASSERT_EQ(test, decoded);
}

TEST_F(UserSettingsTest, PersistEmptyToken) {
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  UserSettings settings;
  settings.Init(temp_dir.path().AppendASCII("UserSettings.sqlite3"));
  settings.SetAuthTokenForService("username", "service", "");
  std::string username;
  std::string token;
  ASSERT_TRUE(settings.GetLastUserAndServiceToken("service", &username,
      &token));
  EXPECT_EQ("", token);
  EXPECT_EQ("username", username);
}

TEST_F(UserSettingsTest, PersistNonEmptyToken) {
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  UserSettings settings;
  settings.Init(temp_dir.path().AppendASCII("UserSettings.sqlite3"));
  settings.SetAuthTokenForService("username", "service",
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah");
  std::string username;
  std::string token;
  ASSERT_TRUE(settings.GetLastUserAndServiceToken("service", &username,
      &token));
  EXPECT_EQ(
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah",
      token);
  EXPECT_EQ("username", username);
}
<commit_msg>Cleanup: Remove sqlite_utils.h from user_settings_unittest.cc<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 <limits>
#include <string>

#include "app/sql/statement.h"
#include "base/file_util.h"
#include "base/memory/scoped_temp_dir.h"
#include "base/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/password_manager/encryptor.h"
#include "chrome/browser/sync/syncable/directory_manager.h"
#include "chrome/browser/sync/util/user_settings.h"
#include "testing/gtest/include/gtest/gtest.h"

using std::numeric_limits;

namespace {

const FilePath::CharType kV10UserSettingsDB[] =
    FILE_PATH_LITERAL("Version10Settings.sqlite3");
const FilePath::CharType kV11UserSettingsDB[] =
    FILE_PATH_LITERAL("Version11Settings.sqlite3");
const FilePath::CharType kOldStyleSyncDataDB[] =
    FILE_PATH_LITERAL("OldStyleSyncData.sqlite3");

}  // namespace

class UserSettingsTest : public testing::Test {
 public:
  UserSettingsTest() : sync_data_("Some sync data") {}

  virtual void SetUp() {
#if defined(OS_MACOSX)
    // Need to mock the Keychain for unit tests on Mac to avoid possible
    // blocking UI.  |SetAuthTokenForService| uses Encryptor.
    Encryptor::UseMockKeychain(true);
#endif
  }

  // Creates and populates the V10 database files within
  // |destination_directory|.
  void SetUpVersion10Databases(const FilePath& destination_directory) {
    v10_user_setting_db_path_ =
        destination_directory.Append(FilePath(kV10UserSettingsDB));

    sql::Connection db;
    ASSERT_TRUE(db.Open(v10_user_setting_db_path_));

    old_style_sync_data_path_ =
        destination_directory.Append(FilePath(kOldStyleSyncDataDB));

    ASSERT_EQ(sync_data_.length(),
              static_cast<size_t>(file_util::WriteFile(
                  old_style_sync_data_path_, sync_data_.data(),
                  sync_data_.length())));

    // Create settings table.
    ASSERT_TRUE(db.Execute(
        "CREATE TABLE settings (email, key, value,  PRIMARY KEY(email, key)"
        " ON CONFLICT REPLACE)"));

    // Add a blank signin table.
    ASSERT_TRUE(db.Execute(
        "CREATE TABLE signin_types (signin, signin_type)"));

    // Create and populate version table.
    ASSERT_TRUE(db.Execute("CREATE TABLE db_version (version)"));
    {
      const char* query = "INSERT INTO db_version VALUES(?)";
      sql::Statement s(db.GetUniqueStatement(query));
      if (!s)
        LOG(FATAL) << query << "\n" << db.GetErrorMessage();

      s.BindInt(0, 10);
      if (!s.Run())
        LOG(FATAL) << query << "\n" << db.GetErrorMessage();
    }

    // Create shares table.
    ASSERT_TRUE(db.Execute(
        "CREATE TABLE shares (email, share_name, file_name,"
        " PRIMARY KEY(email, share_name) ON CONFLICT REPLACE)"));
    // Populate a share.
    {
      const char* query = "INSERT INTO shares VALUES(?, ?, ?)";
      sql::Statement s(db.GetUniqueStatement(query));
      if (!s)
        LOG(FATAL) << query << "\n" << db.GetErrorMessage();

      s.BindString(0, "foo@foo.com");
      s.BindString(1, "foo@foo.com");
#if defined(OS_WIN)
      s.BindString(2, WideToUTF8(old_style_sync_data_path_.value()));
#elif defined(OS_POSIX)
      s.BindString(2, old_style_sync_data_path_.value());
#endif
      if (!s.Run())
        LOG(FATAL) << query << "\n" << db.GetErrorMessage();
    }
  }

   // Creates and populates the V11 database file within
  // |destination_directory|.
  void SetUpVersion11Database(const FilePath& destination_directory) {
    v11_user_setting_db_path_ =
        destination_directory.Append(FilePath(kV11UserSettingsDB));

    sql::Connection db;
    ASSERT_TRUE(db.Open(v11_user_setting_db_path_));

    // Create settings table.
    ASSERT_TRUE(db.Execute(
        "CREATE TABLE settings (email, key, value, PRIMARY KEY(email, key)"
        " ON CONFLICT REPLACE)"));

    // Create and populate version table.
    ASSERT_TRUE(db.Execute("CREATE TABLE db_version (version)"));
    {
      const char* query = "INSERT INTO db_version VALUES(?)";
      sql::Statement s(db.GetUniqueStatement(query));
      if (!s)
        LOG(FATAL) << query << "\n" << db.GetErrorMessage();

      s.BindInt(0, 11);
      if (!s.Run())
        LOG(FATAL) << query << "\n" << db.GetErrorMessage();
    }

    ASSERT_TRUE(db.Execute(
        "CREATE TABLE signin_types (signin, signin_type)"));
    {
      const char* query = "INSERT INTO signin_types VALUES(?, ?)";
      sql::Statement s(db.GetUniqueStatement(query));
      if (!s)
        LOG(FATAL) << query << "\n" << db.GetErrorMessage();

      s.BindString(0, "test");
      s.BindString(1, "test");
      if (!s.Run())
        LOG(FATAL) << query << "\n" << db.GetErrorMessage();
    }
  }

  const std::string& sync_data() const { return sync_data_; }
  const FilePath& v10_user_setting_db_path() const {
    return v10_user_setting_db_path_;
  }
  const FilePath& v11_user_setting_db_path() const {
    return v11_user_setting_db_path_;
  }
  const FilePath& old_style_sync_data_path() const {
    return old_style_sync_data_path_;
  }

 private:
  FilePath v10_user_setting_db_path_;
  FilePath old_style_sync_data_path_;

  FilePath v11_user_setting_db_path_;

  std::string sync_data_;
};

TEST_F(UserSettingsTest, MigrateFromV10ToV11) {
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  SetUpVersion10Databases(temp_dir.path());
  {
    // Create a UserSettings, which should trigger migration code. We do this
    // inside a scoped block so it closes itself and we can poke around to see
    // what happened later.
    browser_sync::UserSettings settings;
    settings.Init(v10_user_setting_db_path());
  }

  // Now poke around using sqlite to see if UserSettings migrated properly.
  sql::Connection db;
  ASSERT_TRUE(db.Open(v10_user_setting_db_path()));

  // Note that we don't use ScopedStatement to avoid closing the sqlite handle
  // before finalizing the statement.
  {
    const char* query = "SELECT version FROM db_version";
    sql::Statement version_query(db.GetUniqueStatement(query));
    if (!version_query)
      LOG(FATAL) << query << "\n" << db.GetErrorMessage();

    ASSERT_TRUE(version_query.Step());
    const int version = version_query.ColumnInt(0);
    EXPECT_GE(version, 11);
  }

  EXPECT_FALSE(file_util::PathExists(old_style_sync_data_path()));

  FilePath new_style_path = temp_dir.path().Append(
      syncable::DirectoryManager::GetSyncDataDatabaseFilename());

  std::string contents;
  ASSERT_TRUE(file_util::ReadFileToString(new_style_path, &contents));
  EXPECT_TRUE(sync_data() == contents);
}

TEST_F(UserSettingsTest, MigrateFromV11ToV12) {
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  SetUpVersion11Database(temp_dir.path());
  {
    browser_sync::UserSettings settings;
    settings.Init(v11_user_setting_db_path());
  }
  sql::Connection db;
  ASSERT_TRUE(db.Open(v11_user_setting_db_path()));

  {
    const char* query = "SELECT version FROM db_version";
    sql::Statement version_query(db.GetUniqueStatement(query));
    if (!version_query)
      LOG(FATAL) << query << "\n" << db.GetErrorMessage();

    ASSERT_TRUE(version_query.Step());
    const int version = version_query.ColumnInt(0);
    EXPECT_GE(version, 12);

    const char* query2 = "SELECT name FROM sqlite_master "
                         "WHERE type='table' AND name='signin_types'";
    sql::Statement table_query(db.GetUniqueStatement(query2));
    if (!table_query)
      LOG(FATAL) << query2 << "\n" << db.GetErrorMessage();

    ASSERT_FALSE(table_query.Step());
  }
}

TEST_F(UserSettingsTest, APEncode) {
  std::string test;
  char i;
  for (i = numeric_limits<char>::min(); i < numeric_limits<char>::max(); ++i)
    test.push_back(i);
  test.push_back(i);
  const std::string encoded = browser_sync::APEncode(test);
  const std::string decoded = browser_sync::APDecode(encoded);
  ASSERT_EQ(test, decoded);
}

TEST_F(UserSettingsTest, PersistEmptyToken) {
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  browser_sync::UserSettings settings;
  settings.Init(temp_dir.path().AppendASCII("UserSettings.sqlite3"));
  settings.SetAuthTokenForService("username", "service", "");
  std::string username;
  std::string token;
  ASSERT_TRUE(settings.GetLastUserAndServiceToken("service", &username,
      &token));
  EXPECT_EQ("", token);
  EXPECT_EQ("username", username);
}

TEST_F(UserSettingsTest, PersistNonEmptyToken) {
  ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  browser_sync::UserSettings settings;
  settings.Init(temp_dir.path().AppendASCII("UserSettings.sqlite3"));
  settings.SetAuthTokenForService("username", "service",
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah");
  std::string username;
  std::string token;
  ASSERT_TRUE(settings.GetLastUserAndServiceToken("service", &username,
      &token));
  EXPECT_EQ(
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah"
      "oonetuhasonteuhasonetuhasonetuhasonetuhasouhasonetuhasonetuhasonetuhah",
      token);
  EXPECT_EQ("username", username);
}
<|endoftext|>


<commit_before>#include "abstractsimulatorbehavior.h"

#include <QThread>

AbstractSimulatorBehavior::AbstractSimulatorBehavior(QWidget *parent)
{
    mTimer = new QTimer(this);
    mDotMatrix = new QDotMatrix(parent, 20, 10, Qt::black);

    connect(mTimer, SIGNAL(timeout()), this, SLOT(loop()));

    FastLED.dotMatrix = mDotMatrix;
}

AbstractSimulatorBehavior::~AbstractSimulatorBehavior()
{
    delete mDotMatrix;
}

void AbstractSimulatorBehavior::startLoop()
{
    // TODO: Check Arduino main loop ~10ms?
    mTimer->start(10);
}

QDotMatrix* AbstractSimulatorBehavior::getDotMatrix()
{
    return this->mDotMatrix;
}

int AbstractSimulatorBehavior::random(int high)
{
    int low = 0;
    return qrand() % (high - low) + low;
}

void AbstractSimulatorBehavior::randomSeed(int seed)
{
    //TODO: use the seed!
}

void AbstractSimulatorBehavior::delay(int milliseconds)
{
    QThread::msleep(milliseconds);
}

void AbstractSimulatorBehavior::readInputs()
{
    delay(5 * 10);
}

void AbstractSimulatorBehavior::setCorrectColor(int x, int y, CRGB currentColor)
{
    //(*leds)[(*ledMatrix)[x][y]] = correctColor(x, color);
    mDotMatrix->setColor(x, y, currentColor);
}

void AbstractSimulatorBehavior::paintAll(CRGB color, boolean forceRefresh)
{

    for(int i=0; i < X_MAX; i++){
        for(int j=0; j < Y_MAX; j++){

            //(*leds)[(*ledMatrix)[i][j]] = correctColor(i, color);
            setCorrectColor(i, j, color);
        }
    }

    if (forceRefresh){
        FastLED.show();
    }
}

void AbstractSimulatorBehavior::setBrightness(int intensity)
{
    mDotMatrix->setIntensity(intensity);
}
<commit_msg>Fix Qt4 compilation<commit_after>#include "abstractsimulatorbehavior.h"

#include <QThread>

// QThread::msleep is only public on Qt5...
// Ugly tricks to process a sleep on Qt4
class SleepThread : public QThread {
public:
   static inline void msleep(unsigned long msecs) {
       QThread::msleep(msecs);
   }
};

AbstractSimulatorBehavior::AbstractSimulatorBehavior(QWidget *parent)
{
    mTimer = new QTimer(this);
    mDotMatrix = new QDotMatrix(parent, 20, 10, Qt::black);

    connect(mTimer, SIGNAL(timeout()), this, SLOT(loop()));

    FastLED.dotMatrix = mDotMatrix;
}

AbstractSimulatorBehavior::~AbstractSimulatorBehavior()
{
    delete mDotMatrix;
}

void AbstractSimulatorBehavior::startLoop()
{
    // TODO: Check Arduino main loop ~10ms?
    mTimer->start(10);
}

QDotMatrix* AbstractSimulatorBehavior::getDotMatrix()
{
    return this->mDotMatrix;
}

int AbstractSimulatorBehavior::random(int high)
{
    int low = 0;
    return qrand() % (high - low) + low;
}

void AbstractSimulatorBehavior::randomSeed(int seed)
{
    //TODO: use the seed!
}

void AbstractSimulatorBehavior::delay(int milliseconds)
{
    SleepThread::msleep(milliseconds);
}

void AbstractSimulatorBehavior::readInputs()
{
    delay(5 * 10);
}

void AbstractSimulatorBehavior::setCorrectColor(int x, int y, CRGB currentColor)
{
    //(*leds)[(*ledMatrix)[x][y]] = correctColor(x, color);
    mDotMatrix->setColor(x, y, currentColor);
}

void AbstractSimulatorBehavior::paintAll(CRGB color, boolean forceRefresh)
{

    for(int i=0; i < X_MAX; i++){
        for(int j=0; j < Y_MAX; j++){

            //(*leds)[(*ledMatrix)[i][j]] = correctColor(i, color);
            setCorrectColor(i, j, color);
        }
    }

    if (forceRefresh){
        FastLED.show();
    }
}

void AbstractSimulatorBehavior::setBrightness(int intensity)
{
    mDotMatrix->setIntensity(intensity);
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkArrayMap.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkArrayMap.h"

#include "vtkAbstractArray.h"
#include "vtkCellData.h"
#include "vtkDataArray.h"
#include "vtkDataSet.h"
#include "vtkDataSetAttributes.h"
#include "vtkGraph.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkStringArray.h"
#include "vtkVariant.h"
#include <ctype.h>

#include <vtkstd/map>
#include <vtkstd/utility>

vtkCxxRevisionMacro(vtkArrayMap, "1.5");
vtkStandardNewMacro(vtkArrayMap);

typedef vtkstd::map< vtkVariant, vtkVariant, vtkVariantLessThan > MapBase;
class vtkMapType : public MapBase {};

vtkArrayMap::vtkArrayMap()
{
  this->InputArrayName = 0;
  this->OutputArrayName = 0;
  this->SetOutputArrayName("ArrayMap");
  this->FieldType = vtkArrayMap::POINT_DATA;
  this->OutputArrayType = VTK_INT;
  this->PassArray = 0;
  this->FillValue = -1;

  this->Map = new vtkMapType;
}

vtkArrayMap::~vtkArrayMap()
{
  delete this->Map;
}

void vtkArrayMap::AddToMap(char *from, int to)
{
  this->Map->insert(vtkstd::make_pair< vtkVariant, vtkVariant >(from, to));

  this->Modified();
}

void vtkArrayMap::AddToMap(int from, int to)
{
  this->Map->insert(vtkstd::make_pair< vtkVariant, vtkVariant >(from, to));

  this->Modified();
}

void vtkArrayMap::AddToMap(int from, char *to)
{
  this->Map->insert(vtkstd::make_pair< vtkVariant, vtkVariant >(from, to));

  this->Modified();
}

void vtkArrayMap::AddToMap(char *from, char *to)
{
  this->Map->insert(vtkstd::make_pair< vtkVariant, vtkVariant >(from, to));

  this->Modified();
}

void vtkArrayMap::AddToMap(vtkVariant from, vtkVariant to)
{
  this->Map->insert(vtkstd::make_pair< vtkVariant, vtkVariant >(from, to));

  this->Modified();
}

void vtkArrayMap::ClearMap()
{
  this->Map->clear();

  this->Modified();
}

int vtkArrayMap::GetMapSize()
{
  return static_cast<int>(this->Map->size());
}

int vtkArrayMap::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // get the input and ouptut
  vtkDataObject *input = inInfo->Get(vtkDataObject::DATA_OBJECT());
  vtkDataObject *output = outInfo->Get(vtkDataObject::DATA_OBJECT());

  if(!this->InputArrayName)
    {
    vtkErrorMacro(<<"Input array not specified.");
    return 0;
    }

  vtkDataSetAttributes* ods=0;
  if (vtkDataSet::SafeDownCast(input))
    {
    vtkDataSet *dsInput = vtkDataSet::SafeDownCast(input);
    vtkDataSet *dsOutput = vtkDataSet::SafeDownCast(output);
    // This has to be here because it initialized all field datas.
    dsOutput->CopyStructure( dsInput );

    if ( dsOutput->GetFieldData() && dsInput->GetFieldData() )
      {
      dsOutput->GetFieldData()->PassData( dsInput->GetFieldData() );
      }
    dsOutput->GetPointData()->PassData( dsInput->GetPointData() );
    dsOutput->GetCellData()->PassData( dsInput->GetCellData() );
    switch (this->FieldType)
      {
      case vtkArrayMap::POINT_DATA:
        ods = dsOutput->GetPointData();
        break;
      case vtkArrayMap::CELL_DATA:
        ods = dsOutput->GetCellData();
        break;
      default:
        vtkErrorMacro(<<"Data must be point or cell for vtkDataSet");
        return 0;
      }
    }
  else
    {
    vtkGraph *graphInput = vtkGraph::SafeDownCast(input);
    vtkGraph *graphOutput = vtkGraph::SafeDownCast(output);
    graphOutput->ShallowCopy( graphInput );
    switch (this->FieldType)
      {
      case vtkArrayMap::VERTEX_DATA:
        ods = graphOutput->GetVertexData();
        break;
      case vtkArrayMap::EDGE_DATA:
        ods = graphOutput->GetEdgeData();
        break;
      default:
        vtkErrorMacro(<<"Data must be vertex or edge for vtkGraph");
        return 0;
      }
    }

  vtkAbstractArray *inputArray = ods->GetAbstractArray(this->InputArrayName);
  vtkAbstractArray *outputArray =
      vtkAbstractArray::CreateArray(this->OutputArrayType);
  vtkDataArray *outputDataArray = vtkDataArray::SafeDownCast(outputArray);
  vtkStringArray *outputStringArray =
      vtkStringArray::SafeDownCast(outputArray);
  outputArray->SetName(this->OutputArrayName);

  // Are we copying the input array values to the output array before
  // the mapping?
  if(this->PassArray)
    {
    // Make sure the DeepCopy will succeed
    if((inputArray->IsA("vtkDataArray") && outputArray->IsA("vtkDataArray") ||
      (inputArray->IsA("vtkStringArray") && outputArray->IsA("vtkStringArray"))))
      {
      outputArray->DeepCopy(inputArray);
      }
    else
      {
      vtkErrorMacro(<<"When PassArray is turned on, input and output array "
                    <<"types must be compatible.");
      return 0;
      }
    }
  else
    {
    outputArray->SetNumberOfTuples(inputArray->GetNumberOfTuples());
    outputArray->SetNumberOfComponents(inputArray->GetNumberOfComponents());

    // Fill the output array with a default value
    if(outputDataArray)
      {
      outputDataArray->FillComponent(0, this->FillValue);
      }
    }

  // Use the internal map to set the mapped values in the output array
  vtkIdList* results = vtkIdList::New();
  for(MapBase::iterator i = this->Map->begin(); i != this->Map->end(); ++i)
    {
    inputArray->LookupValue(i->first, results);
    for(vtkIdType j=0; j<results->GetNumberOfIds(); ++j)
      {
      if(outputDataArray)
        {
        outputDataArray->SetComponent(results->GetId(j), 0, i->second.ToDouble());
        }
      else if(outputStringArray)
        {
        outputStringArray->SetValue(results->GetId(j), i->second.ToString());
        }
      }
    }

  // Finally, add the array to the appropriate vtkDataSetAttributes
  ods->AddArray(outputArray);

  results->Delete();
  outputArray->Delete();

  return 1;
}

int vtkArrayMap::FillInputPortInformation(int vtkNotUsed(port), vtkInformation* info)
{
  // This algorithm may accept a vtkPointSet or vtkGraph.
  info->Remove(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE());
  info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
  info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkGraph");
  return 1;
}

void vtkArrayMap::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "Input array name: ";
  if (this->InputArrayName)
    {
    os << this->InputArrayName << endl;
    }
  else
    {
    os << "(none)" << endl;
    }

  os << indent << "Output array name: ";
  if (this->OutputArrayName)
    {
    os << this->OutputArrayName << endl;
    }
  else
    {
    os << "(none)" << endl;
    }
  os << indent << "Field type: " << this->FieldType << endl;
  os << indent << "Output array type: " << this->OutputArrayType << endl;
  os << indent << "PassArray: " << this->PassArray << endl;
  os << indent << "FillValue: " << this->FillValue << endl;
}
<commit_msg>ENH: Merge changes from main tree into VTK-5-2 branch. (cvs -q up -j1.6 -j1.7 Infovis/vtkArrayMap.cxx)<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkArrayMap.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkArrayMap.h"

#include "vtkAbstractArray.h"
#include "vtkCellData.h"
#include "vtkDataArray.h"
#include "vtkDataSet.h"
#include "vtkDataSetAttributes.h"
#include "vtkGraph.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkStringArray.h"
#include "vtkVariant.h"
#include <ctype.h>

#include <vtkstd/map>
#include <vtkstd/utility>

vtkCxxRevisionMacro(vtkArrayMap, "1.5.2.1");
vtkStandardNewMacro(vtkArrayMap);

typedef vtkstd::map< vtkVariant, vtkVariant, vtkVariantLessThan > MapBase;
class vtkMapType : public MapBase {};

vtkArrayMap::vtkArrayMap()
{
  this->InputArrayName = 0;
  this->OutputArrayName = 0;
  this->SetOutputArrayName("ArrayMap");
  this->FieldType = vtkArrayMap::POINT_DATA;
  this->OutputArrayType = VTK_INT;
  this->PassArray = 0;
  this->FillValue = -1;

  this->Map = new vtkMapType;
}

vtkArrayMap::~vtkArrayMap()
{
  this->SetInputArrayName(0);
  this->SetOutputArrayName(0);
  delete this->Map;
}

void vtkArrayMap::AddToMap(char *from, int to)
{
  this->Map->insert(vtkstd::make_pair< vtkVariant, vtkVariant >(from, to));

  this->Modified();
}

void vtkArrayMap::AddToMap(int from, int to)
{
  this->Map->insert(vtkstd::make_pair< vtkVariant, vtkVariant >(from, to));

  this->Modified();
}

void vtkArrayMap::AddToMap(int from, char *to)
{
  this->Map->insert(vtkstd::make_pair< vtkVariant, vtkVariant >(from, to));

  this->Modified();
}

void vtkArrayMap::AddToMap(char *from, char *to)
{
  this->Map->insert(vtkstd::make_pair< vtkVariant, vtkVariant >(from, to));

  this->Modified();
}

void vtkArrayMap::AddToMap(vtkVariant from, vtkVariant to)
{
  this->Map->insert(vtkstd::make_pair< vtkVariant, vtkVariant >(from, to));

  this->Modified();
}

void vtkArrayMap::ClearMap()
{
  this->Map->clear();

  this->Modified();
}

int vtkArrayMap::GetMapSize()
{
  return static_cast<int>(this->Map->size());
}

int vtkArrayMap::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  // get the info objects
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // get the input and ouptut
  vtkDataObject *input = inInfo->Get(vtkDataObject::DATA_OBJECT());
  vtkDataObject *output = outInfo->Get(vtkDataObject::DATA_OBJECT());

  if(!this->InputArrayName)
    {
    vtkErrorMacro(<<"Input array not specified.");
    return 0;
    }

  vtkDataSetAttributes* ods=0;
  if (vtkDataSet::SafeDownCast(input))
    {
    vtkDataSet *dsInput = vtkDataSet::SafeDownCast(input);
    vtkDataSet *dsOutput = vtkDataSet::SafeDownCast(output);
    // This has to be here because it initialized all field datas.
    dsOutput->CopyStructure( dsInput );

    if ( dsOutput->GetFieldData() && dsInput->GetFieldData() )
      {
      dsOutput->GetFieldData()->PassData( dsInput->GetFieldData() );
      }
    dsOutput->GetPointData()->PassData( dsInput->GetPointData() );
    dsOutput->GetCellData()->PassData( dsInput->GetCellData() );
    switch (this->FieldType)
      {
      case vtkArrayMap::POINT_DATA:
        ods = dsOutput->GetPointData();
        break;
      case vtkArrayMap::CELL_DATA:
        ods = dsOutput->GetCellData();
        break;
      default:
        vtkErrorMacro(<<"Data must be point or cell for vtkDataSet");
        return 0;
      }
    }
  else
    {
    vtkGraph *graphInput = vtkGraph::SafeDownCast(input);
    vtkGraph *graphOutput = vtkGraph::SafeDownCast(output);
    graphOutput->ShallowCopy( graphInput );
    switch (this->FieldType)
      {
      case vtkArrayMap::VERTEX_DATA:
        ods = graphOutput->GetVertexData();
        break;
      case vtkArrayMap::EDGE_DATA:
        ods = graphOutput->GetEdgeData();
        break;
      default:
        vtkErrorMacro(<<"Data must be vertex or edge for vtkGraph");
        return 0;
      }
    }

  vtkAbstractArray *inputArray = ods->GetAbstractArray(this->InputArrayName);
  vtkAbstractArray *outputArray =
      vtkAbstractArray::CreateArray(this->OutputArrayType);
  vtkDataArray *outputDataArray = vtkDataArray::SafeDownCast(outputArray);
  vtkStringArray *outputStringArray =
      vtkStringArray::SafeDownCast(outputArray);
  outputArray->SetName(this->OutputArrayName);

  // Are we copying the input array values to the output array before
  // the mapping?
  if(this->PassArray)
    {
    // Make sure the DeepCopy will succeed
      if((inputArray->IsA("vtkDataArray") && outputArray->IsA("vtkDataArray"))
         || (inputArray->IsA("vtkStringArray")
             && outputArray->IsA("vtkStringArray")))
      {
      outputArray->DeepCopy(inputArray);
      }
    else
      {
      vtkErrorMacro(<<"When PassArray is turned on, input and output array "
                    <<"types must be compatible.");
      return 0;
      }
    }
  else
    {
    outputArray->SetNumberOfTuples(inputArray->GetNumberOfTuples());
    outputArray->SetNumberOfComponents(inputArray->GetNumberOfComponents());

    // Fill the output array with a default value
    if(outputDataArray)
      {
      outputDataArray->FillComponent(0, this->FillValue);
      }
    }

  // Use the internal map to set the mapped values in the output array
  vtkIdList* results = vtkIdList::New();
  for(MapBase::iterator i = this->Map->begin(); i != this->Map->end(); ++i)
    {
    inputArray->LookupValue(i->first, results);
    for(vtkIdType j=0; j<results->GetNumberOfIds(); ++j)
      {
      if(outputDataArray)
        {
        outputDataArray->SetComponent(results->GetId(j), 0, i->second.ToDouble());
        }
      else if(outputStringArray)
        {
        outputStringArray->SetValue(results->GetId(j), i->second.ToString());
        }
      }
    }

  // Finally, add the array to the appropriate vtkDataSetAttributes
  ods->AddArray(outputArray);

  results->Delete();
  outputArray->Delete();

  return 1;
}

int vtkArrayMap::FillInputPortInformation(int vtkNotUsed(port), vtkInformation* info)
{
  // This algorithm may accept a vtkPointSet or vtkGraph.
  info->Remove(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE());
  info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
  info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkGraph");
  return 1;
}

void vtkArrayMap::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "Input array name: ";
  if (this->InputArrayName)
    {
    os << this->InputArrayName << endl;
    }
  else
    {
    os << "(none)" << endl;
    }

  os << indent << "Output array name: ";
  if (this->OutputArrayName)
    {
    os << this->OutputArrayName << endl;
    }
  else
    {
    os << "(none)" << endl;
    }
  os << indent << "Field type: " << this->FieldType << endl;
  os << indent << "Output array type: " << this->OutputArrayType << endl;
  os << indent << "PassArray: " << this->PassArray << endl;
  os << indent << "FillValue: " << this->FillValue << endl;
}
<|endoftext|>


<commit_before>/*
 * DryRunFlagTest.cpp
 *
 */

#include "AlwaysFailsLayer.hpp"
#include <columns/buildandrun.hpp>
#include <sys/types.h>
#include <unistd.h>
#include <utils/PVAssert.hpp>

int deleteOutputDirectory(PV::Communicator *comm);
void compareParamsFiles(char const *paramsFile1, char const *paramsFile2, PV::Communicator *comm);
void compareParameterGroups(PV::ParameterGroup *group1, PV::ParameterGroup *group2);
void compareParameterNumericStacks(
      char const *groupName,
      PV::ParameterStack *stack1,
      PV::ParameterStack *stack2);
void compareParameterNumeric(
      char const *groupName,
      PV::Parameter *parameter1,
      PV::Parameter *parameter2);
void compareParameterArrayStacks(
      char const *groupName,
      PV::ParameterArrayStack *stack1,
      PV::ParameterArrayStack *stack2);
void compareParameterArray(
      char const *groupName,
      PV::ParameterArray *array1,
      PV::ParameterArray *array2);
void compareParameterStringStacks(
      char const *groupName,
      PV::ParameterStringStack *stack1,
      PV::ParameterStringStack *stack2);
void compareParameterString(
      char const *groupName,
      PV::ParameterString *string1,
      PV::ParameterString *string2);

int main(int argc, char *argv[]) {

   int status = PV_SUCCESS;

   PV::PV_Init pv_obj(&argc, &argv, false /*allowUnrecognizedArguments*/);
   pv_obj.registerKeyword("AlwaysFailsLayer", Factory::create<AlwaysFailsLayer>);

   pv_obj.setDryRunFlag(true);

   if (pv_obj.isExtraProc()) {
      return EXIT_SUCCESS;
   }

   pvErrorIf(
         pv_obj.getParamsFile() != nullptr,
         "%s should be called without the -p argument; the necessary params file is hard-coded.\n");
   pv_obj.setParams("input/DryRunFlagTest.params");

   int rank = pv_obj.getCommunicator()->globalCommRank();

   status = deleteOutputDirectory(pv_obj.getCommunicator());
   if (status != PV_SUCCESS) {
      pvError().printf("%s: error cleaning generated files from any previous run.\n", argv[0]);
   }

   status = buildandrun(&pv_obj);

   if (status != PV_SUCCESS) {
      pvError().printf("%s: running with dry-run flag set failed on process %d.\n", argv[0], rank);
   }

   compareParamsFiles("output/pv.params", "input/correct.params", pv_obj.getCommunicator());
}

int deleteOutputDirectory(PV::Communicator *comm) {
   int status = PV_SUCCESS;
   if (comm->globalCommRank() == 0) {
      if (system("rm -rf output") != PV_SUCCESS) {
         status = PV_FAILURE;
      }
   }
   MPI_Bcast(&status, 1, MPI_INT, 0, comm->communicator());
   return status;
}

void compareParamsFiles(char const *paramsFile1, char const *paramsFile2, PV::Communicator *comm) {
   PV::PVParams params1{paramsFile1, INITIAL_LAYER_ARRAY_SIZE, comm};
   PV::PVParams params2{paramsFile2, INITIAL_LAYER_ARRAY_SIZE, comm};

   // create a map between groups in paramsFile1 and those in paramsFile2.
   std::map<PV::ParameterGroup *, PV::ParameterGroup *> parameterGroupMap;
   char const *groupName = nullptr;
   for (int idx = 0; groupName = params1.groupNameFromIndex(idx); idx++) {
      PV::ParameterGroup *g1 = params1.group(groupName);
      PV::ParameterGroup *g2 = params2.group(groupName);
      pvErrorIf(
            g2 == nullptr,
            "Group name \"%s\" is in \"%s\" but not in \"%s\".\n",
            groupName,
            paramsFile1,
            paramsFile2);
      parameterGroupMap.emplace(std::make_pair(g1, g2));
   }
   for (int idx = 0; groupName = params2.groupNameFromIndex(idx); idx++) {
      pvErrorIf(
            params1.group(groupName) == nullptr,
            "Group name \"%s\" is in \"%s\" but not in \"%s\".\n",
            groupName,
            paramsFile2,
            paramsFile1);
   }

   for (auto &p : parameterGroupMap) {
      compareParameterGroups(p.first, p.second);
   }
   return;
}

void compareParameterGroups(PV::ParameterGroup *group1, PV::ParameterGroup *group2) {
   pvAssert(!strcmp(group1->name(), group2->name()));
   pvErrorIf(
         strcmp(group1->getGroupKeyword(), group2->getGroupKeyword()),
         "Keywords for group \"%s\" do not match (\"%s\" versus \"%s\").\n",
         group1->name(),
         group1->getGroupKeyword(),
         group2->getGroupKeyword());
   PV::ParameterStack *numericStack1 = group1->copyStack();
   PV::ParameterStack *numericStack2 = group2->copyStack();
   compareParameterNumericStacks(group1->name(), numericStack1, numericStack2);

   PV::ParameterArrayStack *arrayStack1 = group1->copyArrayStack();
   PV::ParameterArrayStack *arrayStack2 = group2->copyArrayStack();
   compareParameterArrayStacks(group1->name(), arrayStack1, arrayStack2);

   PV::ParameterStringStack *stringStack1 = group1->copyStringStack();
   PV::ParameterStringStack *stringStack2 = group2->copyStringStack();
   compareParameterStringStacks(group1->name(), stringStack1, stringStack2);
}

void compareParameterNumericStacks(
      char const *groupName,
      PV::ParameterStack *stack1,
      PV::ParameterStack *stack2) {
   pvErrorIf(
         stack1->size() != stack2->size(),
         "Numeric stacks for \"%s\" have different sizes: %d versus %d.\n",
         groupName,
         stack1->size(),
         stack2->size());
   // create a map between stack1 and stack2
   int const size = stack1->size();
   std::map<PV::Parameter *, PV::Parameter *> parameterMap;
   for (int i = 0; i < size; i++) {
      PV::Parameter *param1  = stack1->peek(i);
      char const *paramName1 = param1->name();
      bool found             = false;
      for (int j = 0; j < size; j++) {
         PV::Parameter *param2  = stack2->peek(j);
         char const *paramName2 = param2->name();
         if (!strcmp(paramName1, paramName2)) {
            parameterMap.emplace(std::make_pair(param1, param2));
            found = true;
            break;
         }
      }
      if (!found) {
         pvError() << "Parameter \"" << paramName1 << "\" was found in group \"" << groupName
                   << "\" of one stack but not the other.\n";
      }
   }
   pvAssert(parameterMap.size() == size);

   for (auto &p : parameterMap) {
      compareParameterNumeric(groupName, p.first, p.second);
   }
}

void compareParameterNumeric(
      char const *groupName,
      PV::Parameter *parameter1,
      PV::Parameter *parameter2) {
   pvAssert(!strcmp(parameter1->name(), parameter2->name()));
   pvErrorIf(
         parameter1->value() != parameter2->value(),
         "Numeric parameter \"%s\" in group \"%s\" differs (%f versus %f).\n",
         parameter1->name(),
         groupName,
         parameter1->value(),
         parameter2->value());
}

void compareParameterArrayStacks(
      char const *groupName,
      PV::ParameterArrayStack *stack1,
      PV::ParameterArrayStack *stack2) {
   pvErrorIf(
         stack1->size() != stack2->size(),
         "Numeric stacks for \"%s\" have different sizes: %d versus %d.\n",
         groupName,
         stack1->size(),
         stack2->size());
   // create a map between stack1 and stack2
   int const size = stack1->size();
   std::map<PV::ParameterArray *, PV::ParameterArray *> parameterArrayMap;
   for (int i = 0; i < size; i++) {
      PV::ParameterArray *param1 = stack1->peek(i);
      char const *paramName1     = param1->name();
      bool found                 = false;
      for (int j = 0; j < size; j++) {
         PV::ParameterArray *param2 = stack2->peek(j);
         char const *paramName2     = param2->name();
         if (!strcmp(paramName1, paramName2)) {
            parameterArrayMap.emplace(std::make_pair(param1, param2));
            found = true;
            break;
         }
      }
      if (!found) {
         pvError() << "Parameter \"" << paramName1 << "\" was found in group \"" << groupName
                   << "\" of one stack but not the other.\n";
      }
   }
   pvAssert(parameterArrayMap.size() == size);

   for (auto &p : parameterArrayMap) {
      compareParameterArray(groupName, p.first, p.second);
   }
}

void compareParameterArray(
      char const *groupName,
      PV::ParameterArray *array1,
      PV::ParameterArray *array2) {
   pvAssert(!strcmp(array1->name(), array2->name()));
   pvErrorIf(
         array1->getArraySize() != array2->getArraySize(),
         "Array \"%s\" in group \"%s\" differs in size (%d versus %d).\n",
         array1->name(),
         groupName,
         array1->getArraySize(),
         array2->getArraySize());
   int size              = array1->getArraySize();
   double const *values1 = array1->getValuesDbl(&size);
   double const *values2 = array2->getValuesDbl(&size);
   int badIndex          = 0;
   for (int i = 0; i < size; i++) {
      if (values1[i] != values2[i]) {
         badIndex = i + 1;
         pvErrorNoExit() << "Group " << groupName << ", array " << array1->name() << ", index "
                         << badIndex << " differs (" << values1[i] << " versus " << values2[i]
                         << ").\n";
      }
   }
   if (badIndex > 0) {
      exit(EXIT_FAILURE);
   }
}

void compareParameterStringStacks(
      char const *groupName,
      PV::ParameterStringStack *stack1,
      PV::ParameterStringStack *stack2) {
   pvErrorIf(
         stack1->size() != stack2->size(),
         "Numeric stacks for \"%s\" have different sizes: %d versus %d.\n",
         groupName,
         stack1->size(),
         stack2->size());
   // create a map between stack1 and stack2
   int const size = stack1->size();
   std::map<PV::ParameterString *, PV::ParameterString *> parameterStringMap;
   for (int i = 0; i < size; i++) {
      PV::ParameterString *param1 = stack1->peek(i);
      char const *paramName1      = param1->getName();
      bool found                  = false;
      for (int j = 0; j < size; j++) {
         PV::ParameterString *param2 = stack2->peek(j);
         char const *paramName2      = param2->getName();
         if (!strcmp(paramName1, paramName2)) {
            parameterStringMap.emplace(std::make_pair(param1, param2));
            found = true;
            break;
         }
      }
      if (!found) {
         pvError() << "Parameter \"" << paramName1 << "\" was found in group \"" << groupName
                   << "\" of one stack but not the other.\n";
      }
   }
   pvAssert(parameterStringMap.size() == size);

   for (auto &p : parameterStringMap) {
      compareParameterString(groupName, p.first, p.second);
   }
}

void compareParameterString(
      char const *groupName,
      PV::ParameterString *string1,
      PV::ParameterString *string2) {
   pvAssert(!strcmp(string1->getName(), string2->getName()));
   char const *nullString = "(null)";
   char const *value1     = string1->getValue();
   if (value1 == nullptr) {
      value1 = nullString;
   }
   char const *value2 = string2->getValue();
   if (value2 == nullptr) {
      value2 = nullString;
   }
   pvErrorIf(
         strcmp(value1, value2),
         "String parameter \"%s\" in group \"%s\" differs (\"%s\" versus \"%s\").\n",
         string1->getName(),
         groupName,
         value1,
         value2);
}
<commit_msg>Addresses clang warnings in DryRunFlagTest<commit_after>/*
 * DryRunFlagTest.cpp
 *
 */

#include "AlwaysFailsLayer.hpp"
#include <columns/buildandrun.hpp>
#include <sys/types.h>
#include <unistd.h>
#include <utils/PVAssert.hpp>

int deleteOutputDirectory(PV::Communicator *comm);
void compareParamsFiles(char const *paramsFile1, char const *paramsFile2, PV::Communicator *comm);
void compareParameterGroups(PV::ParameterGroup *group1, PV::ParameterGroup *group2);
void compareParameterNumericStacks(
      char const *groupName,
      PV::ParameterStack *stack1,
      PV::ParameterStack *stack2);
void compareParameterNumeric(
      char const *groupName,
      PV::Parameter *parameter1,
      PV::Parameter *parameter2);
void compareParameterArrayStacks(
      char const *groupName,
      PV::ParameterArrayStack *stack1,
      PV::ParameterArrayStack *stack2);
void compareParameterArray(
      char const *groupName,
      PV::ParameterArray *array1,
      PV::ParameterArray *array2);
void compareParameterStringStacks(
      char const *groupName,
      PV::ParameterStringStack *stack1,
      PV::ParameterStringStack *stack2);
void compareParameterString(
      char const *groupName,
      PV::ParameterString *string1,
      PV::ParameterString *string2);

int main(int argc, char *argv[]) {

   int status = PV_SUCCESS;

   PV::PV_Init pv_obj(&argc, &argv, false /*allowUnrecognizedArguments*/);
   pv_obj.registerKeyword("AlwaysFailsLayer", Factory::create<AlwaysFailsLayer>);

   pv_obj.setDryRunFlag(true);

   if (pv_obj.isExtraProc()) {
      return EXIT_SUCCESS;
   }

   pvErrorIf(
         pv_obj.getParamsFile() != nullptr,
         "%s should be called without the -p argument; the necessary params file is hard-coded.\n");
   pv_obj.setParams("input/DryRunFlagTest.params");

   int rank = pv_obj.getCommunicator()->globalCommRank();

   status = deleteOutputDirectory(pv_obj.getCommunicator());
   if (status != PV_SUCCESS) {
      pvError().printf("%s: error cleaning generated files from any previous run.\n", argv[0]);
   }

   status = buildandrun(&pv_obj);

   if (status != PV_SUCCESS) {
      pvError().printf("%s: running with dry-run flag set failed on process %d.\n", argv[0], rank);
   }

   compareParamsFiles("output/pv.params", "input/correct.params", pv_obj.getCommunicator());
}

int deleteOutputDirectory(PV::Communicator *comm) {
   int status = PV_SUCCESS;
   if (comm->globalCommRank() == 0) {
      if (system("rm -rf output") != PV_SUCCESS) {
         status = PV_FAILURE;
      }
   }
   MPI_Bcast(&status, 1, MPI_INT, 0, comm->communicator());
   return status;
}

void compareParamsFiles(char const *paramsFile1, char const *paramsFile2, PV::Communicator *comm) {
   PV::PVParams params1{paramsFile1, INITIAL_LAYER_ARRAY_SIZE, comm};
   PV::PVParams params2{paramsFile2, INITIAL_LAYER_ARRAY_SIZE, comm};

   // create a map between groups in paramsFile1 and those in paramsFile2.
   std::map<PV::ParameterGroup *, PV::ParameterGroup *> parameterGroupMap;
   char const *groupName = nullptr;
   for (int idx = 0; (groupName = params1.groupNameFromIndex(idx))!=nullptr; idx++) {
      PV::ParameterGroup *g1 = params1.group(groupName);
      PV::ParameterGroup *g2 = params2.group(groupName);
      pvErrorIf(
            g2 == nullptr,
            "Group name \"%s\" is in \"%s\" but not in \"%s\".\n",
            groupName,
            paramsFile1,
            paramsFile2);
      parameterGroupMap.emplace(std::make_pair(g1, g2));
   }
   for (int idx = 0; (groupName = params2.groupNameFromIndex(idx))!=nullptr; idx++) {
      pvErrorIf(
            params1.group(groupName) == nullptr,
            "Group name \"%s\" is in \"%s\" but not in \"%s\".\n",
            groupName,
            paramsFile2,
            paramsFile1);
   }

   for (auto &p : parameterGroupMap) {
      compareParameterGroups(p.first, p.second);
   }
   return;
}

void compareParameterGroups(PV::ParameterGroup *group1, PV::ParameterGroup *group2) {
   pvAssert(!strcmp(group1->name(), group2->name()));
   pvErrorIf(
         strcmp(group1->getGroupKeyword(), group2->getGroupKeyword()),
         "Keywords for group \"%s\" do not match (\"%s\" versus \"%s\").\n",
         group1->name(),
         group1->getGroupKeyword(),
         group2->getGroupKeyword());
   PV::ParameterStack *numericStack1 = group1->copyStack();
   PV::ParameterStack *numericStack2 = group2->copyStack();
   compareParameterNumericStacks(group1->name(), numericStack1, numericStack2);

   PV::ParameterArrayStack *arrayStack1 = group1->copyArrayStack();
   PV::ParameterArrayStack *arrayStack2 = group2->copyArrayStack();
   compareParameterArrayStacks(group1->name(), arrayStack1, arrayStack2);

   PV::ParameterStringStack *stringStack1 = group1->copyStringStack();
   PV::ParameterStringStack *stringStack2 = group2->copyStringStack();
   compareParameterStringStacks(group1->name(), stringStack1, stringStack2);
}

void compareParameterNumericStacks(
      char const *groupName,
      PV::ParameterStack *stack1,
      PV::ParameterStack *stack2) {
   pvErrorIf(
         stack1->size() != stack2->size(),
         "Numeric stacks for \"%s\" have different sizes: %d versus %d.\n",
         groupName,
         stack1->size(),
         stack2->size());
   // create a map between stack1 and stack2
   int const size = stack1->size();
   std::map<PV::Parameter *, PV::Parameter *> parameterMap;
   for (int i = 0; i < size; i++) {
      PV::Parameter *param1  = stack1->peek(i);
      char const *paramName1 = param1->name();
      bool found             = false;
      for (int j = 0; j < size; j++) {
         PV::Parameter *param2  = stack2->peek(j);
         char const *paramName2 = param2->name();
         if (!strcmp(paramName1, paramName2)) {
            parameterMap.emplace(std::make_pair(param1, param2));
            found = true;
            break;
         }
      }
      if (!found) {
         pvError() << "Parameter \"" << paramName1 << "\" was found in group \"" << groupName
                   << "\" of one stack but not the other.\n";
      }
   }
   pvAssert(parameterMap.size() == size);

   for (auto &p : parameterMap) {
      compareParameterNumeric(groupName, p.first, p.second);
   }
}

void compareParameterNumeric(
      char const *groupName,
      PV::Parameter *parameter1,
      PV::Parameter *parameter2) {
   pvAssert(!strcmp(parameter1->name(), parameter2->name()));
   pvErrorIf(
         parameter1->value() != parameter2->value(),
         "Numeric parameter \"%s\" in group \"%s\" differs (%f versus %f).\n",
         parameter1->name(),
         groupName,
         parameter1->value(),
         parameter2->value());
}

void compareParameterArrayStacks(
      char const *groupName,
      PV::ParameterArrayStack *stack1,
      PV::ParameterArrayStack *stack2) {
   pvErrorIf(
         stack1->size() != stack2->size(),
         "Numeric stacks for \"%s\" have different sizes: %d versus %d.\n",
         groupName,
         stack1->size(),
         stack2->size());
   // create a map between stack1 and stack2
   int const size = stack1->size();
   std::map<PV::ParameterArray *, PV::ParameterArray *> parameterArrayMap;
   for (int i = 0; i < size; i++) {
      PV::ParameterArray *param1 = stack1->peek(i);
      char const *paramName1     = param1->name();
      bool found                 = false;
      for (int j = 0; j < size; j++) {
         PV::ParameterArray *param2 = stack2->peek(j);
         char const *paramName2     = param2->name();
         if (!strcmp(paramName1, paramName2)) {
            parameterArrayMap.emplace(std::make_pair(param1, param2));
            found = true;
            break;
         }
      }
      if (!found) {
         pvError() << "Parameter \"" << paramName1 << "\" was found in group \"" << groupName
                   << "\" of one stack but not the other.\n";
      }
   }
   pvAssert(parameterArrayMap.size() == size);

   for (auto &p : parameterArrayMap) {
      compareParameterArray(groupName, p.first, p.second);
   }
}

void compareParameterArray(
      char const *groupName,
      PV::ParameterArray *array1,
      PV::ParameterArray *array2) {
   pvAssert(!strcmp(array1->name(), array2->name()));
   pvErrorIf(
         array1->getArraySize() != array2->getArraySize(),
         "Array \"%s\" in group \"%s\" differs in size (%d versus %d).\n",
         array1->name(),
         groupName,
         array1->getArraySize(),
         array2->getArraySize());
   int size              = array1->getArraySize();
   double const *values1 = array1->getValuesDbl(&size);
   double const *values2 = array2->getValuesDbl(&size);
   int badIndex          = 0;
   for (int i = 0; i < size; i++) {
      if (values1[i] != values2[i]) {
         badIndex = i + 1;
         pvErrorNoExit() << "Group " << groupName << ", array " << array1->name() << ", index "
                         << badIndex << " differs (" << values1[i] << " versus " << values2[i]
                         << ").\n";
      }
   }
   if (badIndex > 0) {
      exit(EXIT_FAILURE);
   }
}

void compareParameterStringStacks(
      char const *groupName,
      PV::ParameterStringStack *stack1,
      PV::ParameterStringStack *stack2) {
   pvErrorIf(
         stack1->size() != stack2->size(),
         "Numeric stacks for \"%s\" have different sizes: %d versus %d.\n",
         groupName,
         stack1->size(),
         stack2->size());
   // create a map between stack1 and stack2
   int const size = stack1->size();
   std::map<PV::ParameterString *, PV::ParameterString *> parameterStringMap;
   for (int i = 0; i < size; i++) {
      PV::ParameterString *param1 = stack1->peek(i);
      char const *paramName1      = param1->getName();
      bool found                  = false;
      for (int j = 0; j < size; j++) {
         PV::ParameterString *param2 = stack2->peek(j);
         char const *paramName2      = param2->getName();
         if (!strcmp(paramName1, paramName2)) {
            parameterStringMap.emplace(std::make_pair(param1, param2));
            found = true;
            break;
         }
      }
      if (!found) {
         pvError() << "Parameter \"" << paramName1 << "\" was found in group \"" << groupName
                   << "\" of one stack but not the other.\n";
      }
   }
   pvAssert(parameterStringMap.size() == size);

   for (auto &p : parameterStringMap) {
      compareParameterString(groupName, p.first, p.second);
   }
}

void compareParameterString(
      char const *groupName,
      PV::ParameterString *string1,
      PV::ParameterString *string2) {
   pvAssert(!strcmp(string1->getName(), string2->getName()));
   char const *nullString = "(null)";
   char const *value1     = string1->getValue();
   if (value1 == nullptr) {
      value1 = nullString;
   }
   char const *value2 = string2->getValue();
   if (value2 == nullptr) {
      value2 = nullString;
   }
   pvErrorIf(
         strcmp(value1, value2),
         "String parameter \"%s\" in group \"%s\" differs (\"%s\" versus \"%s\").\n",
         string1->getName(),
         groupName,
         value1,
         value2);
}
<|endoftext|>


<commit_before>// ========================================================================== //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2016 Jefferson Amstutz                                       //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// in all copies or substantial portions of the Software.                     //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
// ========================================================================== //

#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <tests/doctest.h>
#include <CPW/parallel_for.h>

#include <algorithm>
#include <vector>

TEST_CASE("parallel_for")
{
  const size_t N_ELEMENTS = 1000000;

  const int bad_value  = 0;
  const int good_value = 1;

  std::vector<int> v(N_ELEMENTS);
  std::fill(v.begin(), v.end(), bad_value);

  CPW::parallel_for(N_ELEMENTS,[&](decltype(N_ELEMENTS) taskIndex) {
    v[taskIndex] = good_value;
  });

  auto found = std::find(v.begin(), v.end(), bad_value);

  REQUIRE(found == v.end());
}
<commit_msg>increase the amount of work in the parallel_for test<commit_after>// ========================================================================== //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2016 Jefferson Amstutz                                       //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// in all copies or substantial portions of the Software.                     //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
// ========================================================================== //

#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <tests/doctest.h>
#include <CPW/parallel_for.h>

#include <algorithm>
#include <vector>

TEST_CASE("parallel_for")
{
  const size_t N_ELEMENTS = 1e8;

  const int bad_value  = 0;
  const int good_value = 1;

  std::vector<int> v(N_ELEMENTS);
  std::fill(v.begin(), v.end(), bad_value);

  CPW::parallel_for(N_ELEMENTS,[&](decltype(N_ELEMENTS) taskIndex) {
    v[taskIndex] = good_value;
  });

  auto found = std::find(v.begin(), v.end(), bad_value);

  REQUIRE(found == v.end());
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QSignalSpy>
#include <QEventLoop>
#include <QTimer>

#include <private/qmldebugclient_p.h>
#include <private/qmldebugservice_p.h>

#include "debugutil_p.h"

bool QmlDebugTest::waitForSignal(QObject *receiver, const char *member, int timeout) {
    QEventLoop loop;
    QTimer timer;
    QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    QObject::connect(receiver, member, &loop, SLOT(quit()));
    timer.start(timeout);
    loop.exec();
    return timer.isActive();
}

QmlDebugTestData::QmlDebugTestData(QEventLoop *el)
    : exitCode(-1), loop(el)
{
}

QmlDebugTestData::~QmlDebugTestData()
{
    qDeleteAll(items);
}

void QmlDebugTestData::testsFinished(int code)
{
    exitCode = code;
    loop->quit();
}

QmlDebugTestService::QmlDebugTestService(const QString &s, QObject *parent)
    : QmlDebugService(s, parent), enabled(false)
{
}

void QmlDebugTestService::messageReceived(const QByteArray &ba)
{
    sendMessage(ba);
}

void QmlDebugTestService::enabledChanged(bool e)
{
    enabled = e;
    emit enabledStateChanged();
}

QmlDebugTestClient::QmlDebugTestClient(const QString &s, QmlDebugConnection *c)
    : QmlDebugClient(s, c)
{
}

QByteArray QmlDebugTestClient::waitForResponse()
{
    lastMsg.clear();
    QmlDebugTest::waitForSignal(this, SIGNAL(serverMessage(QByteArray)));
    if (lastMsg.isEmpty()) {
        qWarning() << "tst_QmlDebugClient: no response from server!";
        return QByteArray();
    }
    return lastMsg;
}

void QmlDebugTestClient::messageReceived(const QByteArray &ba)
{
    lastMsg = ba;
    emit serverMessage(ba);
}

tst_QmlDebug_Thread::tst_QmlDebug_Thread(QmlDebugTestData *data, QmlTestFactory *factory)
    : m_ready(false), m_data(data), m_factory(factory)
{
}

void tst_QmlDebug_Thread::run()
{
    QTest::qWait(1000);

    QmlDebugConnection conn;
    conn.connectToHost("127.0.0.1", 3768);
    bool ok = conn.waitForConnected(5000);
    Q_ASSERT(ok);

    while (!m_ready)
        QTest::qWait(100);

    m_data->conn = &conn;

    Q_ASSERT(m_factory);
    QObject *test = m_factory->createTest(m_data);
    Q_ASSERT(test);
    int code = QTest::qExec(test);
    emit testsFinished(code);
}

int QmlDebugTest::runTests(QmlTestFactory *factory, const QList<QByteArray> &qml)
{
    qputenv("QML_DEBUG_SERVER_PORT", "3768");

    QEventLoop loop;
    QmlDebugTestData data(&loop);

    tst_QmlDebug_Thread thread(&data, factory);
    QObject::connect(&thread, SIGNAL(testsFinished(int)), &data, SLOT(testsFinished(int)));
    thread.start();

    QmlEngine engine;  // blocks until client connects

    foreach (const QByteArray &code, qml) {
        QmlComponent c(&engine);
        c.setData(code, QUrl::fromLocalFile(""));
        Q_ASSERT(c.isReady());  // fails if bad syntax
        data.items << qobject_cast<QmlGraphicsItem*>(c.create());
    }

    // start the test
    data.engine = &engine;
    thread.m_ready = true;

    loop.exec();

    return data.exitCode;
}

<commit_msg>Must pass app arguments onto qExec() or else test system cannot get test results with -xml mode.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QSignalSpy>
#include <QEventLoop>
#include <QTimer>

#include <private/qmldebugclient_p.h>
#include <private/qmldebugservice_p.h>

#include "debugutil_p.h"

bool QmlDebugTest::waitForSignal(QObject *receiver, const char *member, int timeout) {
    QEventLoop loop;
    QTimer timer;
    QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
    QObject::connect(receiver, member, &loop, SLOT(quit()));
    timer.start(timeout);
    loop.exec();
    return timer.isActive();
}

QmlDebugTestData::QmlDebugTestData(QEventLoop *el)
    : exitCode(-1), loop(el)
{
}

QmlDebugTestData::~QmlDebugTestData()
{
    qDeleteAll(items);
}

void QmlDebugTestData::testsFinished(int code)
{
    exitCode = code;
    loop->quit();
}

QmlDebugTestService::QmlDebugTestService(const QString &s, QObject *parent)
    : QmlDebugService(s, parent), enabled(false)
{
}

void QmlDebugTestService::messageReceived(const QByteArray &ba)
{
    sendMessage(ba);
}

void QmlDebugTestService::enabledChanged(bool e)
{
    enabled = e;
    emit enabledStateChanged();
}

QmlDebugTestClient::QmlDebugTestClient(const QString &s, QmlDebugConnection *c)
    : QmlDebugClient(s, c)
{
}

QByteArray QmlDebugTestClient::waitForResponse()
{
    lastMsg.clear();
    QmlDebugTest::waitForSignal(this, SIGNAL(serverMessage(QByteArray)));
    if (lastMsg.isEmpty()) {
        qWarning() << "tst_QmlDebugClient: no response from server!";
        return QByteArray();
    }
    return lastMsg;
}

void QmlDebugTestClient::messageReceived(const QByteArray &ba)
{
    lastMsg = ba;
    emit serverMessage(ba);
}

tst_QmlDebug_Thread::tst_QmlDebug_Thread(QmlDebugTestData *data, QmlTestFactory *factory)
    : m_ready(false), m_data(data), m_factory(factory)
{
}

void tst_QmlDebug_Thread::run()
{
    QTest::qWait(1000);

    QmlDebugConnection conn;
    conn.connectToHost("127.0.0.1", 3768);
    bool ok = conn.waitForConnected(5000);
    Q_ASSERT(ok);

    while (!m_ready)
        QTest::qWait(100);

    m_data->conn = &conn;

    Q_ASSERT(m_factory);
    QObject *test = m_factory->createTest(m_data);
    Q_ASSERT(test);
    int code = QTest::qExec(test, QCoreApplication::arguments());
    emit testsFinished(code);
}

int QmlDebugTest::runTests(QmlTestFactory *factory, const QList<QByteArray> &qml)
{
    qputenv("QML_DEBUG_SERVER_PORT", "3768");

    QEventLoop loop;
    QmlDebugTestData data(&loop);

    tst_QmlDebug_Thread thread(&data, factory);
    QObject::connect(&thread, SIGNAL(testsFinished(int)), &data, SLOT(testsFinished(int)));
    thread.start();

    QmlEngine engine;  // blocks until client connects

    foreach (const QByteArray &code, qml) {
        QmlComponent c(&engine);
        c.setData(code, QUrl::fromLocalFile(""));
        Q_ASSERT(c.isReady());  // fails if bad syntax
        data.items << qobject_cast<QmlGraphicsItem*>(c.create());
    }

    // start the test
    data.engine = &engine;
    thread.m_ready = true;

    loop.exec();

    return data.exitCode;
}

<|endoftext|>


<commit_before>#include <UnitTest++.h>

#include "stdio_fixture.h"

SUITE(PrintF)
{
    TEST_FIXTURE(StdIOFixture, BasicPrintFTest)
    {
        int r = fslc_fprintf(&stream, "Hello, World!\n");

        CHECK_EQUAL("Hello, World!\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFStringTest)
    {
        int r = fslc_fprintf(&stream, "Hello from %s!\n", "PrintF");

        CHECK_EQUAL("Hello from PrintF!\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintF2StringsTest)
    {
        int r = fslc_fprintf(&stream, "%s from %s!\n", "Hello", "PrintF");

        CHECK_EQUAL("Hello from PrintF!\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFCharTest)
    {
        int r = fslc_fprintf(&stream, "Hello, %corld!\n", 'W');

        CHECK_EQUAL("Hello, World!\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFPercentTest)
    {
        int r = fslc_fprintf(&stream, "Special offer: 50%% off!");

        CHECK_EQUAL("Special offer: 50% off!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFPrePostMultiTest)
    {
        stream.pre_output = fixture_preop;
        stream.post_output = fixture_postop;

        int r = fslc_fprintf(&stream, "Testing %s%% of all possibilities%c", "a few ", '!');

        const char *expected_str = "Testing a few % of all possibilities!";

        std::vector<FuncCallItem> expected_calls;
        expected_calls.push_back({ CalledFunc::PreOp, 0 });
        for (const char *c = expected_str; *c; ++c)
            expected_calls.push_back({ CalledFunc::PutC, *c });
        expected_calls.push_back({ CalledFunc::PostOp, 0 });

        CHECK(r >= 0);
        CHECK_EQUAL(expected_calls.size(), FuncCallLog.size());
        CHECK_ARRAY_EQUAL(expected_calls, FuncCallLog, FuncCallLog.size());

        CHECK_EQUAL(expected_str, ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFPrePostMultiEofTest)
    {
        stream.pre_output = fixture_preop;
        stream.post_output = fixture_postop;

        eof_counter = 20;

        int r = fslc_fprintf(&stream, "Testing %s%% of all possibilities%c", "a few ", '!');

        const char *expected_str = "Testing a few % of a";
        //                          12345678901234567890

        std::vector<FuncCallItem> expected_calls;
        expected_calls.push_back({ CalledFunc::PreOp, 0 });
        for (const char *c = expected_str; *c; ++c)
            expected_calls.push_back({ CalledFunc::PutC, *c });
        expected_calls.push_back({ CalledFunc::PutC, 'l' }); // EOF
        expected_calls.push_back({ CalledFunc::PostOp, 0 });

        CHECK(r < 0);
        CHECK_EQUAL(expected_calls.size(), FuncCallLog.size());
        CHECK_ARRAY_EQUAL(expected_calls, FuncCallLog, FuncCallLog.size());

        CHECK_EQUAL(expected_str, ostring.str());
    }

    TEST_FIXTURE(StdIOFixture, PrintFBasicIntTest)
    {
        int r = fslc_fprintf(&stream, "The answer is %d!", 42);

        CHECK(r >= 0);
        CHECK_EQUAL("The answer is 42!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFZeroIntTest)
    {
        int r = fslc_fprintf(&stream, "Zero is %d!", 0);

        CHECK(r >= 0);
        CHECK_EQUAL("Zero is 0!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFNegativeTest)
    {
        int r = fslc_fprintf(&stream, "Less than zero: %d!", -54);

        CHECK(r >= 0);
        CHECK_EQUAL("Less than zero: -54!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFUIntMaxTest)
    {
        int r = fslc_fprintf(&stream, "Max uint is %u\n", -1);

        CHECK(r >= 0);
        CHECK_EQUAL("Max uint is 4294967295\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFBasicHexTest)
    {
        int r = fslc_fprintf(&stream, "The answer is %x!", 0x74df);

        CHECK(r >= 0);
        CHECK_EQUAL("The answer is 74df!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFBasicUpperHexTest)
    {
        int r = fslc_fprintf(&stream, "The answer is %X!", 0x74df);

        CHECK(r >= 0);
        CHECK_EQUAL("The answer is 74DF!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFZeroHexTest)
    {
        int r = fslc_fprintf(&stream, "Zero is %x!", 0);

        CHECK(r >= 0);
        CHECK_EQUAL("Zero is 0!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFUHExMaxTest)
    {
        int r = fslc_fprintf(&stream, "Max hex is %x\n", -1);

        CHECK(r >= 0);
        CHECK_EQUAL("Max hex is ffffffff\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }
}
<commit_msg>Unit tests for Long and Very Long ints<commit_after>#include <UnitTest++.h>

#include "stdio_fixture.h"

SUITE(PrintF)
{
    TEST_FIXTURE(StdIOFixture, BasicPrintFTest)
    {
        int r = fslc_fprintf(&stream, "Hello, World!\n");

        CHECK_EQUAL("Hello, World!\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFStringTest)
    {
        int r = fslc_fprintf(&stream, "Hello from %s!\n", "PrintF");

        CHECK_EQUAL("Hello from PrintF!\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintF2StringsTest)
    {
        int r = fslc_fprintf(&stream, "%s from %s!\n", "Hello", "PrintF");

        CHECK_EQUAL("Hello from PrintF!\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFCharTest)
    {
        int r = fslc_fprintf(&stream, "Hello, %corld!\n", 'W');

        CHECK_EQUAL("Hello, World!\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFPercentTest)
    {
        int r = fslc_fprintf(&stream, "Special offer: 50%% off!");

        CHECK_EQUAL("Special offer: 50% off!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFPrePostMultiTest)
    {
        stream.pre_output = fixture_preop;
        stream.post_output = fixture_postop;

        int r = fslc_fprintf(&stream, "Testing %s%% of all possibilities%c", "a few ", '!');

        const char *expected_str = "Testing a few % of all possibilities!";

        std::vector<FuncCallItem> expected_calls;
        expected_calls.push_back({ CalledFunc::PreOp, 0 });
        for (const char *c = expected_str; *c; ++c)
            expected_calls.push_back({ CalledFunc::PutC, *c });
        expected_calls.push_back({ CalledFunc::PostOp, 0 });

        CHECK(r >= 0);
        CHECK_EQUAL(expected_calls.size(), FuncCallLog.size());
        CHECK_ARRAY_EQUAL(expected_calls, FuncCallLog, FuncCallLog.size());

        CHECK_EQUAL(expected_str, ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFPrePostMultiEofTest)
    {
        stream.pre_output = fixture_preop;
        stream.post_output = fixture_postop;

        eof_counter = 20;

        int r = fslc_fprintf(&stream, "Testing %s%% of all possibilities%c", "a few ", '!');

        const char *expected_str = "Testing a few % of a";
        //                          12345678901234567890

        std::vector<FuncCallItem> expected_calls;
        expected_calls.push_back({ CalledFunc::PreOp, 0 });
        for (const char *c = expected_str; *c; ++c)
            expected_calls.push_back({ CalledFunc::PutC, *c });
        expected_calls.push_back({ CalledFunc::PutC, 'l' }); // EOF
        expected_calls.push_back({ CalledFunc::PostOp, 0 });

        CHECK(r < 0);
        CHECK_EQUAL(expected_calls.size(), FuncCallLog.size());
        CHECK_ARRAY_EQUAL(expected_calls, FuncCallLog, FuncCallLog.size());

        CHECK_EQUAL(expected_str, ostring.str());
    }

    TEST_FIXTURE(StdIOFixture, PrintFBasicIntTest)
    {
        int r = fslc_fprintf(&stream, "The answer is %d!", 42);

        CHECK(r >= 0);
        CHECK_EQUAL("The answer is 42!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFZeroIntTest)
    {
        int r = fslc_fprintf(&stream, "Zero is %d!", 0);

        CHECK(r >= 0);
        CHECK_EQUAL("Zero is 0!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFNegativeTest)
    {
        int r = fslc_fprintf(&stream, "Less than zero: %d!", -54);

        CHECK(r >= 0);
        CHECK_EQUAL("Less than zero: -54!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFUIntMaxTest)
    {
        int r = fslc_fprintf(&stream, "Max uint is %u\n", -1);

        CHECK(r >= 0);
        CHECK_EQUAL("Max uint is 4294967295\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFBasicHexTest)
    {
        int r = fslc_fprintf(&stream, "The answer is %x!", 0x74df);

        CHECK(r >= 0);
        CHECK_EQUAL("The answer is 74df!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFBasicUpperHexTest)
    {
        int r = fslc_fprintf(&stream, "The answer is %X!", 0x74df);

        CHECK(r >= 0);
        CHECK_EQUAL("The answer is 74DF!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFZeroHexTest)
    {
        int r = fslc_fprintf(&stream, "Zero is %x!", 0);

        CHECK(r >= 0);
        CHECK_EQUAL("Zero is 0!", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFUHExMaxTest)
    {
        int r = fslc_fprintf(&stream, "Max hex is %x\n", -1);

        CHECK(r >= 0);
        CHECK_EQUAL("Max hex is ffffffff\n", ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFLongIntTest)
    {
        int r = fslc_fprintf(&stream, "The answer is %ld!", 435434432L);

        int e = eprintf("The answer is %ld!", 435434432L);

        CHECK_EQUAL(e, r);
        CHECK_EQUAL(expected_fstring.get(), ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFLongNegativeTest)
    {
        int r = fslc_fprintf(&stream, "Less than zero: %ld!", -57299223L);

        int e = eprintf("Less than zero: %ld!", -57299223L);

        CHECK_EQUAL(e, r);
        CHECK_EQUAL(expected_fstring.get(), ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFULongMaxTest)
    {
        int r = fslc_fprintf(&stream, "Max ulong is %lu\n", -1L);

        int e = eprintf("Max ulong is %lu\n", -1L);

        CHECK_EQUAL(e, r);
        CHECK_EQUAL(expected_fstring.get(), ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFULongHexMaxTest)
    {
        int r = fslc_fprintf(&stream, "Max long hex is %lx\n", -1L);

        int e = eprintf("Max long hex is %lx\n", -1L);

        CHECK_EQUAL(e, r);
        CHECK_EQUAL(expected_fstring.get(), ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFULongHexUpperMaxTest)
    {
        int r = fslc_fprintf(&stream, "Max long hex is %lX\n", -1L);

        int e = eprintf("Max long hex is %lX\n", -1L);

        CHECK_EQUAL(e, r);
        CHECK_EQUAL(expected_fstring.get(), ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFVeryLongIntTest)
    {
        int r = fslc_fprintf(&stream, "The answer is %lld!", 435432343442444432LL);

        int e = eprintf("The answer is %lld!", 435432343442444432LL);

        CHECK_EQUAL(e, r);
        CHECK_EQUAL(expected_fstring.get(), ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFVeryLongNegativeTest)
    {
        int r = fslc_fprintf(&stream, "Less than zero: %lld!", -5729932434424223L);

        int e = eprintf("Less than zero: %lld!", -5729932434424223L);

        CHECK_EQUAL(e, r);
        CHECK_EQUAL(expected_fstring.get(), ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFUVeryLongMaxTest)
    {
        int r = fslc_fprintf(&stream, "Max ulonglong is %llu\n", -1L);

        int e = eprintf("Max ulonglong is %llu\n", -1L);

        CHECK_EQUAL(e, r);
        CHECK_EQUAL(expected_fstring.get(), ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFUVeryLongHexMaxTest)
    {
        int r = fslc_fprintf(&stream, "Max long long hex is %llx\n", -1L);

        int e = eprintf("Max long long hex is %llx\n", -1L);

        CHECK_EQUAL(e, r);
        CHECK_EQUAL(expected_fstring.get(), ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }

    TEST_FIXTURE(StdIOFixture, PrintFUVeryLongUpperHexMaxTest)
    {
        int r = fslc_fprintf(&stream, "Max long long hex is %llX\n", -1L);

        int e = eprintf("Max long long hex is %llX\n", -1L);

        CHECK_EQUAL(e, r);
        CHECK_EQUAL(expected_fstring.get(), ostring.str());
        CHECK_EQUAL(ostring.str().size(), r);
    }
}
<|endoftext|>