libweave: Clang format of moved files
Now changes, just git 'clang-format -f m/master'.
BUG=brillo:1235
TEST=FEATURES=test emerge-gizmo buffet
Change-Id: I1ba6bc6cd09c5bd728d73d3ea675950362839781
Reviewed-on: https://chromium-review.googlesource.com/283580
Tested-by: Vitaly Buka <vitalybuka@chromium.org>
Reviewed-by: Alex Vakulenko <avakulenko@chromium.org>
Commit-Queue: Alex Vakulenko <avakulenko@chromium.org>
diff --git a/libweave/src/buffet_config_unittest.cc b/libweave/src/buffet_config_unittest.cc
index 5274c5a..4b458fe 100644
--- a/libweave/src/buffet_config_unittest.cc
+++ b/libweave/src/buffet_config_unittest.cc
@@ -121,8 +121,10 @@
config_->backup_polling_period());
EXPECT_FALSE(config_->wifi_auto_setup_enabled());
std::set<privetd::PairingType> pairing_types{
- privetd::PairingType::kPinCode, privetd::PairingType::kEmbeddedCode,
- privetd::PairingType::kUltrasound32, privetd::PairingType::kAudible32};
+ privetd::PairingType::kPinCode,
+ privetd::PairingType::kEmbeddedCode,
+ privetd::PairingType::kUltrasound32,
+ privetd::PairingType::kAudible32};
EXPECT_EQ(pairing_types, config_->pairing_modes());
EXPECT_EQ("/conf_code", config_->embedded_code_path().value());
EXPECT_EQ("conf_name", config_->name());
diff --git a/libweave/src/buffet_testrunner.cc b/libweave/src/buffet_testrunner.cc
index 575f952..072461d 100644
--- a/libweave/src/buffet_testrunner.cc
+++ b/libweave/src/buffet_testrunner.cc
@@ -5,7 +5,7 @@
#include <base/at_exit.h>
#include <gtest/gtest.h>
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
base::AtExitManager exit_manager;
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
diff --git a/libweave/src/commands/cloud_command_proxy.cc b/libweave/src/commands/cloud_command_proxy.cc
index 7f9afcc..0ef511f 100644
--- a/libweave/src/commands/cloud_command_proxy.cc
+++ b/libweave/src/commands/cloud_command_proxy.cc
@@ -26,7 +26,7 @@
cloud_backoff_entry_{std::move(backoff_entry)} {
callback_token_ = state_change_queue_->AddOnStateUpdatedCallback(
base::Bind(&CloudCommandProxy::OnDeviceStateUpdated,
- weak_ptr_factory_.GetWeakPtr()));
+ weak_ptr_factory_.GetWeakPtr()));
}
void CloudCommandProxy::OnResultsChanged() {
@@ -94,9 +94,8 @@
<< cloud_backoff_entry_->GetTimeUntilRelease()
<< " due to backoff policy";
task_runner_->PostDelayedTask(
- FROM_HERE,
- base::Bind(&CloudCommandProxy::SendCommandUpdate,
- backoff_weak_ptr_factory_.GetWeakPtr()),
+ FROM_HERE, base::Bind(&CloudCommandProxy::SendCommandUpdate,
+ backoff_weak_ptr_factory_.GetWeakPtr()),
cloud_backoff_entry_->GetTimeUntilRelease());
return;
}
diff --git a/libweave/src/commands/cloud_command_proxy_unittest.cc b/libweave/src/commands/cloud_command_proxy_unittest.cc
index 518d45f..5452f93 100644
--- a/libweave/src/commands/cloud_command_proxy_unittest.cc
+++ b/libweave/src/commands/cloud_command_proxy_unittest.cc
@@ -37,19 +37,21 @@
class MockCloudCommandUpdateInterface : public CloudCommandUpdateInterface {
public:
- MOCK_METHOD4(UpdateCommand, void(const std::string&,
- const base::DictionaryValue&,
- const base::Closure&,
- const base::Closure&));
+ MOCK_METHOD4(UpdateCommand,
+ void(const std::string&,
+ const base::DictionaryValue&,
+ const base::Closure&,
+ const base::Closure&));
};
// Mock-like task runner that allow the tests to inspect the calls to
// TaskRunner::PostDelayedTask and verify the delays.
class TestTaskRunner : public base::TaskRunner {
public:
- MOCK_METHOD3(PostDelayedTask, bool(const tracked_objects::Location&,
- const base::Closure&,
- base::TimeDelta));
+ MOCK_METHOD3(PostDelayedTask,
+ bool(const tracked_objects::Location&,
+ const base::Closure&,
+ base::TimeDelta));
bool RunsTasksOnCurrentThread() const override { return true; }
};
@@ -148,9 +150,12 @@
new TestBackoffEntry{&policy, &clock_}};
// Finally construct the CloudCommandProxy we are going to test here.
- std::unique_ptr<CloudCommandProxy> proxy{new CloudCommandProxy{
- command_instance_.get(), &cloud_updater_, &state_change_queue_,
- std::move(backoff), task_runner_}};
+ std::unique_ptr<CloudCommandProxy> proxy{
+ new CloudCommandProxy{command_instance_.get(),
+ &cloud_updater_,
+ &state_change_queue_,
+ std::move(backoff),
+ task_runner_}};
command_instance_->AddProxy(std::move(proxy));
}
diff --git a/libweave/src/commands/command_definition.cc b/libweave/src/commands/command_definition.cc
index 4dfa51e..0b7bcb3 100644
--- a/libweave/src/commands/command_definition.cc
+++ b/libweave/src/commands/command_definition.cc
@@ -35,10 +35,10 @@
} else if (value == commands::attributes::kCommand_Visibility_Cloud) {
cloud = true;
} else {
- chromeos::Error::AddToPrintf(
- error, FROM_HERE, errors::commands::kDomain,
- errors::commands::kInvalidPropValue,
- "Invalid command visibility value '%s'", value.c_str());
+ chromeos::Error::AddToPrintf(error, FROM_HERE, errors::commands::kDomain,
+ errors::commands::kInvalidPropValue,
+ "Invalid command visibility value '%s'",
+ value.c_str());
return false;
}
}
diff --git a/libweave/src/commands/command_definition.h b/libweave/src/commands/command_definition.h
index 55dcae6..21eed9c 100644
--- a/libweave/src/commands/command_definition.h
+++ b/libweave/src/commands/command_definition.h
@@ -71,7 +71,7 @@
std::string category_; // Cmd category. Could be "powerd" for "base.reboot".
std::unique_ptr<const ObjectSchema> parameters_; // Command parameters def.
std::unique_ptr<const ObjectSchema> progress_; // Command progress def.
- std::unique_ptr<const ObjectSchema> results_; // Command results def.
+ std::unique_ptr<const ObjectSchema> results_; // Command results def.
Visibility visibility_; // Available to all by default.
// Minimal role required to execute command.
UserRole minimal_role_{UserRole::kUser};
diff --git a/libweave/src/commands/command_dictionary.cc b/libweave/src/commands/command_dictionary.cc
index f8103be..92dd316 100644
--- a/libweave/src/commands/command_dictionary.cc
+++ b/libweave/src/commands/command_dictionary.cc
@@ -56,11 +56,10 @@
}
const base::DictionaryValue* command_def_json = nullptr;
if (!command_iter.value().GetAsDictionary(&command_def_json)) {
- chromeos::Error::AddToPrintf(error, FROM_HERE,
- errors::commands::kDomain,
- errors::commands::kTypeMismatch,
- "Expecting an object for command '%s'",
- command_name.c_str());
+ chromeos::Error::AddToPrintf(
+ error, FROM_HERE, errors::commands::kDomain,
+ errors::commands::kTypeMismatch,
+ "Expecting an object for command '%s'", command_name.c_str());
return false;
}
// Construct the compound command name as "pkg_name.cmd_name".
@@ -101,11 +100,8 @@
}
auto parameters_schema = BuildObjectSchema(
- command_def_json,
- commands::attributes::kCommand_Parameters,
- base_parameters_def,
- full_command_name,
- error);
+ command_def_json, commands::attributes::kCommand_Parameters,
+ base_parameters_def, full_command_name, error);
if (!parameters_schema)
return false;
@@ -116,11 +112,8 @@
return false;
auto results_schema = BuildObjectSchema(
- command_def_json,
- commands::attributes::kCommand_Results,
- base_results_def,
- full_command_name,
- error);
+ command_def_json, commands::attributes::kCommand_Results,
+ base_results_def, full_command_name, error);
if (!results_schema)
return false;
@@ -202,8 +195,7 @@
}
if (!object_schema->FromJson(schema_def, base_def, error)) {
- chromeos::Error::AddToPrintf(error, FROM_HERE,
- errors::commands::kDomain,
+ chromeos::Error::AddToPrintf(error, FROM_HERE, errors::commands::kDomain,
errors::commands::kInvalidObjectSchema,
"Invalid definition for command '%s'",
command_name.c_str());
diff --git a/libweave/src/commands/command_dictionary_unittest.cc b/libweave/src/commands/command_dictionary_unittest.cc
index 45aa59b..e087943 100644
--- a/libweave/src/commands/command_dictionary_unittest.cc
+++ b/libweave/src/commands/command_dictionary_unittest.cc
@@ -161,12 +161,14 @@
})");
base_dict.LoadCommands(*json, "", nullptr, &error);
EXPECT_TRUE(dict.LoadCommands(*json, "robotd", &base_dict, &error));
- auto json2 = CreateDictionaryValue(
- "{'base':{'jump':{'parameters':{},'results':{}}}}");
+ auto json2 =
+ CreateDictionaryValue("{'base':{'jump':{'parameters':{},'results':{}}}}");
EXPECT_FALSE(dict.LoadCommands(*json2, "robotd", &base_dict, &error));
EXPECT_EQ("invalid_command_name", error->GetCode());
- EXPECT_EQ("The name of custom command 'jump' in package 'base' must start "
- "with '_'", error->GetMessage());
+ EXPECT_EQ(
+ "The name of custom command 'jump' in package 'base' must start "
+ "with '_'",
+ error->GetMessage());
error.reset();
// If the command starts with "_", then it's Ok.
@@ -379,9 +381,9 @@
})";
EXPECT_JSON_EQ(expected, *json);
- json = dict.GetCommandsAsJson(
- [](const CommandDefinition* def) { return def->GetVisibility().local; },
- false, nullptr);
+ json = dict.GetCommandsAsJson([](const CommandDefinition* def) {
+ return def->GetVisibility().local;
+ }, false, nullptr);
ASSERT_NE(nullptr, json.get());
expected = R"({
'test': {
@@ -393,9 +395,9 @@
})";
EXPECT_JSON_EQ(expected, *json);
- json = dict.GetCommandsAsJson(
- [](const CommandDefinition* def) { return def->GetVisibility().cloud; },
- false, nullptr);
+ json = dict.GetCommandsAsJson([](const CommandDefinition* def) {
+ return def->GetVisibility().cloud;
+ }, false, nullptr);
ASSERT_NE(nullptr, json.get());
expected = R"({
'test': {
@@ -407,10 +409,9 @@
})";
EXPECT_JSON_EQ(expected, *json);
- json = dict.GetCommandsAsJson(
- [](const CommandDefinition* def) {
- return def->GetVisibility().local && def->GetVisibility().cloud;
- }, false, nullptr);
+ json = dict.GetCommandsAsJson([](const CommandDefinition* def) {
+ return def->GetVisibility().local && def->GetVisibility().cloud;
+ }, false, nullptr);
ASSERT_NE(nullptr, json.get());
expected = R"({
'test': {
diff --git a/libweave/src/commands/command_instance_unittest.cc b/libweave/src/commands/command_instance_unittest.cc
index 53fe646..0da58d8 100644
--- a/libweave/src/commands/command_instance_unittest.cc
+++ b/libweave/src/commands/command_instance_unittest.cc
@@ -72,8 +72,7 @@
StringPropType str_prop;
IntPropType int_prop;
native_types::Object params;
- params["phrase"] = str_prop.CreateValue(std::string("iPityDaFool"),
- nullptr);
+ params["phrase"] = str_prop.CreateValue(std::string("iPityDaFool"), nullptr);
params["volume"] = int_prop.CreateValue(5, nullptr);
CommandInstance instance{
"robot.speak", "cloud", dict_.FindCommand("robot.speak"), params};
@@ -200,8 +199,7 @@
first->GetMessage());
auto inner = error->GetInnerError();
EXPECT_EQ("invalid_parameter_value", inner->GetCode());
- EXPECT_EQ("Invalid value for property 'volume'",
- inner->GetMessage());
+ EXPECT_EQ("Invalid value for property 'volume'", inner->GetMessage());
EXPECT_EQ("command_failed", error->GetCode());
EXPECT_EQ("Failed to validate command 'robot.speak'", error->GetMessage());
}
diff --git a/libweave/src/commands/command_manager.cc b/libweave/src/commands/command_manager.cc
index e636837..d8bc226 100644
--- a/libweave/src/commands/command_manager.cc
+++ b/libweave/src/commands/command_manager.cc
@@ -39,8 +39,8 @@
bool CommandManager::LoadBaseCommands(const base::FilePath& json_file_path,
chromeos::ErrorPtr* error) {
- std::unique_ptr<const base::DictionaryValue> json = LoadJsonDict(
- json_file_path, error);
+ std::unique_ptr<const base::DictionaryValue> json =
+ LoadJsonDict(json_file_path, error);
if (!json)
return false;
return LoadBaseCommands(*json, error);
@@ -58,8 +58,8 @@
bool CommandManager::LoadCommands(const base::FilePath& json_file_path,
chromeos::ErrorPtr* error) {
- std::unique_ptr<const base::DictionaryValue> json = LoadJsonDict(
- json_file_path, error);
+ std::unique_ptr<const base::DictionaryValue> json =
+ LoadJsonDict(json_file_path, error);
if (!json)
return false;
std::string category = json_file_path.BaseName().RemoveExtension().value();
@@ -80,8 +80,7 @@
base::FilePath device_command_dir{root.Append("commands")};
VLOG(2) << "Looking for commands in " << root.value();
base::FileEnumerator enumerator(device_command_dir, false,
- base::FileEnumerator::FILES,
- pattern);
+ base::FileEnumerator::FILES, pattern);
base::FilePath json_file_path = enumerator.Next();
while (!json_file_path.empty()) {
LOG(INFO) << "Loading command schema from " << json_file_path.value();
diff --git a/libweave/src/commands/command_manager.h b/libweave/src/commands/command_manager.h
index 6a6b6dc..a404256 100644
--- a/libweave/src/commands/command_manager.h
+++ b/libweave/src/commands/command_manager.h
@@ -24,7 +24,6 @@
} // namespace dbus_utils
} // namespace chromeos
-
namespace buffet {
class CommandInstance;
@@ -111,7 +110,7 @@
private:
CommandDictionary base_dictionary_; // Base/std command definitions/schemas.
- CommandDictionary dictionary_; // Command definitions/schemas.
+ CommandDictionary dictionary_; // Command definitions/schemas.
DBusCommandDispacher command_dispatcher_;
CommandQueue command_queue_;
std::vector<base::Callback<void()>> on_command_changed_;
diff --git a/libweave/src/commands/command_manager_unittest.cc b/libweave/src/commands/command_manager_unittest.cc
index da37057..3087a49 100644
--- a/libweave/src/commands/command_manager_unittest.cc
+++ b/libweave/src/commands/command_manager_unittest.cc
@@ -152,12 +152,10 @@
test_commands_path.Append("test.json"));
manager.Startup(base_path, test_path);
EXPECT_EQ(3, manager.GetCommandDictionary().GetSize());
- EXPECT_NE(nullptr,
- manager.GetCommandDictionary().FindCommand("robot._jump"));
+ EXPECT_NE(nullptr, manager.GetCommandDictionary().FindCommand("robot._jump"));
EXPECT_NE(nullptr,
manager.GetCommandDictionary().FindCommand("robot._speak"));
- EXPECT_NE(nullptr,
- manager.GetCommandDictionary().FindCommand("test._yo"));
+ EXPECT_NE(nullptr, manager.GetCommandDictionary().FindCommand("test._yo"));
}
TEST(CommandManager, UpdateCommandVisibility) {
diff --git a/libweave/src/commands/command_queue_unittest.cc b/libweave/src/commands/command_queue_unittest.cc
index 662cf82..6b78709 100644
--- a/libweave/src/commands/command_queue_unittest.cc
+++ b/libweave/src/commands/command_queue_unittest.cc
@@ -50,12 +50,10 @@
class FakeDispatcher {
public:
explicit FakeDispatcher(CommandQueue* queue) {
- queue->AddOnCommandAddedCallback(
- base::Bind(&FakeDispatcher::OnCommandAdded,
- weak_ptr_factory_.GetWeakPtr()));
- queue->AddOnCommandRemovedCallback(
- base::Bind(&FakeDispatcher::OnCommandRemoved,
- weak_ptr_factory_.GetWeakPtr()));
+ queue->AddOnCommandAddedCallback(base::Bind(
+ &FakeDispatcher::OnCommandAdded, weak_ptr_factory_.GetWeakPtr()));
+ queue->AddOnCommandRemovedCallback(base::Bind(
+ &FakeDispatcher::OnCommandRemoved, weak_ptr_factory_.GetWeakPtr()));
}
void OnCommandAdded(CommandInstance* command_instance) {
diff --git a/libweave/src/commands/dbus_command_dispatcher.h b/libweave/src/commands/dbus_command_dispatcher.h
index 4217582..12fdf78 100644
--- a/libweave/src/commands/dbus_command_dispatcher.h
+++ b/libweave/src/commands/dbus_command_dispatcher.h
@@ -30,8 +30,9 @@
// command queue and D-Bus ExportedObjectManager.
class DBusCommandDispacher final {
public:
- explicit DBusCommandDispacher(const base::WeakPtr<
- chromeos::dbus_utils::ExportedObjectManager>& object_manager);
+ explicit DBusCommandDispacher(
+ const base::WeakPtr<chromeos::dbus_utils::ExportedObjectManager>&
+ object_manager);
void OnCommandAdded(CommandInstance* command_instance);
diff --git a/libweave/src/commands/dbus_command_dispatcher_unittest.cc b/libweave/src/commands/dbus_command_dispatcher_unittest.cc
index 00c2da1..3f56ba1 100644
--- a/libweave/src/commands/dbus_command_dispatcher_unittest.cc
+++ b/libweave/src/commands/dbus_command_dispatcher_unittest.cc
@@ -52,12 +52,12 @@
EXPECT_CALL(*bus_, AssertOnOriginThread()).Times(AnyNumber());
EXPECT_CALL(*bus_, AssertOnDBusThread()).Times(AnyNumber());
// Use a mock exported object manager.
- mock_exported_object_manager_ = new dbus::MockExportedObject(
- bus_.get(), kExportedObjectManagerPath);
+ mock_exported_object_manager_ =
+ new dbus::MockExportedObject(bus_.get(), kExportedObjectManagerPath);
EXPECT_CALL(*bus_, GetExportedObject(kExportedObjectManagerPath))
.WillRepeatedly(Return(mock_exported_object_manager_.get()));
- EXPECT_CALL(*mock_exported_object_manager_,
- ExportMethod(_, _, _, _)).Times(AnyNumber());
+ EXPECT_CALL(*mock_exported_object_manager_, ExportMethod(_, _, _, _))
+ .Times(AnyNumber());
om_.reset(new chromeos::dbus_utils::ExportedObjectManager(
bus_.get(), kExportedObjectManagerPath));
om_->RegisterAsync(AsyncEventSequencer::GetDefaultCompletionAction());
@@ -66,8 +66,8 @@
base::Bind(&DBusCommandDispacher::OnCommandAdded,
base::Unretained(command_dispatcher_.get())));
// Use a mock exported object for command proxy.
- mock_exported_command_proxy_ = new dbus::MockExportedObject(
- bus_.get(), kCmdObjPath);
+ mock_exported_command_proxy_ =
+ new dbus::MockExportedObject(bus_.get(), kCmdObjPath);
EXPECT_CALL(*bus_, GetExportedObject(kCmdObjPath))
.WillRepeatedly(Return(mock_exported_command_proxy_.get()));
EXPECT_CALL(*mock_exported_command_proxy_, ExportMethod(_, _, _, _))
@@ -104,11 +104,10 @@
on_exported_callback.Run(interface_name, method_name, true);
}
-
void AddNewCommand(const std::string& json, const std::string& id) {
- auto command_instance = CommandInstance::FromJson(
- CreateDictionaryValue(json.c_str()).get(), "cloud", dictionary_,
- nullptr, nullptr);
+ auto command_instance =
+ CommandInstance::FromJson(CreateDictionaryValue(json.c_str()).get(),
+ "cloud", dictionary_, nullptr, nullptr);
command_instance->SetID(id);
// Two interfaces are added - Command and Properties.
EXPECT_CALL(*mock_exported_object_manager_, SendSignal(_)).Times(2);
@@ -120,16 +119,13 @@
return static_cast<DBusCommandProxy*>(command_instance->proxies_[0].get());
}
- void FinishCommand(DBusCommandProxy* proxy) {
- proxy->Done();
- }
+ void FinishCommand(DBusCommandProxy* proxy) { proxy->Done(); }
void SetProgress(DBusCommandProxy* proxy,
const native_types::Object& progress) {
EXPECT_TRUE(proxy->SetProgress(nullptr, ObjectToDBusVariant(progress)));
}
-
scoped_refptr<dbus::MockBus> bus_;
scoped_refptr<dbus::MockExportedObject> mock_exported_object_manager_;
scoped_refptr<dbus::MockExportedObject> mock_exported_command_proxy_;
@@ -176,7 +172,8 @@
'parameters': {
'delay': 20
}
- })", id);
+ })",
+ id);
CommandInstance* command_instance = command_queue_.Find(id);
ASSERT_NE(nullptr, command_instance);
DBusCommandProxy* command_proxy = FindProxy(command_instance);
@@ -203,5 +200,4 @@
EXPECT_EQ(nullptr, command_queue_.Find(id));
}
-
} // namespace buffet
diff --git a/libweave/src/commands/dbus_command_proxy.cc b/libweave/src/commands/dbus_command_proxy.cc
index 1807a0e..d7cbd14 100644
--- a/libweave/src/commands/dbus_command_proxy.cc
+++ b/libweave/src/commands/dbus_command_proxy.cc
@@ -27,7 +27,7 @@
}
void DBusCommandProxy::RegisterAsync(
- const AsyncEventSequencer::CompletionAction& completion_callback) {
+ const AsyncEventSequencer::CompletionAction& completion_callback) {
dbus_adaptor_.RegisterWithDBusObject(&dbus_object_);
// Set the initial property values before registering the DBus object.
@@ -39,10 +39,10 @@
ObjectToDBusVariant(command_instance_->GetProgress()));
dbus_adaptor_.SetOrigin(command_instance_->GetOrigin());
- dbus_adaptor_.SetParameters(ObjectToDBusVariant(
- command_instance_->GetParameters()));
- dbus_adaptor_.SetResults(ObjectToDBusVariant(
- command_instance_->GetResults()));
+ dbus_adaptor_.SetParameters(
+ ObjectToDBusVariant(command_instance_->GetParameters()));
+ dbus_adaptor_.SetResults(
+ ObjectToDBusVariant(command_instance_->GetResults()));
// Register the command DBus object and expose its methods and properties.
dbus_object_.RegisterAsync(completion_callback);
@@ -80,8 +80,8 @@
bool DBusCommandProxy::SetResults(chromeos::ErrorPtr* error,
const chromeos::VariantDictionary& results) {
- LOG(INFO) << "Received call to Command<"
- << command_instance_->GetName() << ">::SetResults()";
+ LOG(INFO) << "Received call to Command<" << command_instance_->GetName()
+ << ">::SetResults()";
auto results_schema = command_instance_->GetCommandDefinition()->GetResults();
native_types::Object obj;
@@ -93,22 +93,21 @@
}
void DBusCommandProxy::Abort() {
- LOG(INFO) << "Received call to Command<"
- << command_instance_->GetName() << ">::Abort()";
+ LOG(INFO) << "Received call to Command<" << command_instance_->GetName()
+ << ">::Abort()";
command_instance_->Abort();
}
void DBusCommandProxy::Cancel() {
- LOG(INFO) << "Received call to Command<"
- << command_instance_->GetName() << ">::Cancel()";
+ LOG(INFO) << "Received call to Command<" << command_instance_->GetName()
+ << ">::Cancel()";
command_instance_->Cancel();
}
void DBusCommandProxy::Done() {
- LOG(INFO) << "Received call to Command<"
- << command_instance_->GetName() << ">::Done()";
+ LOG(INFO) << "Received call to Command<" << command_instance_->GetName()
+ << ">::Done()";
command_instance_->Done();
}
-
} // namespace buffet
diff --git a/libweave/src/commands/dbus_command_proxy_unittest.cc b/libweave/src/commands/dbus_command_proxy_unittest.cc
index c211166..d933958 100644
--- a/libweave/src/commands/dbus_command_proxy_unittest.cc
+++ b/libweave/src/commands/dbus_command_proxy_unittest.cc
@@ -103,10 +103,11 @@
// Use a mock exported object for the exported object manager.
mock_exported_object_command_ =
new dbus::MockExportedObject(bus_.get(), kCmdObjPath);
- EXPECT_CALL(*bus_, GetExportedObject(kCmdObjPath)).Times(AnyNumber())
+ EXPECT_CALL(*bus_, GetExportedObject(kCmdObjPath))
+ .Times(AnyNumber())
.WillRepeatedly(Return(mock_exported_object_command_.get()));
- EXPECT_CALL(*mock_exported_object_command_,
- ExportMethod(_, _, _, _)).Times(AnyNumber());
+ EXPECT_CALL(*mock_exported_object_command_, ExportMethod(_, _, _, _))
+ .Times(AnyNumber());
std::unique_ptr<CommandProxyInterface> command_proxy(
new DBusCommandProxy(nullptr, bus_, command_instance_.get(), cmd_path));
@@ -145,8 +146,7 @@
TEST_F(DBusCommandProxyTest, Init) {
VariantDictionary params = {
- {"height", int32_t{53}},
- {"_jumpType", std::string{"_withKick"}},
+ {"height", int32_t{53}}, {"_jumpType", std::string{"_withKick"}},
};
EXPECT_EQ(CommandInstance::kStatusQueued, GetCommandAdaptor()->GetStatus());
EXPECT_EQ(params, GetCommandAdaptor()->GetParameters());
@@ -178,8 +178,7 @@
TEST_F(DBusCommandProxyTest, SetResults) {
EXPECT_CALL(*mock_exported_object_command_, SendSignal(_)).Times(1);
const VariantDictionary results = {
- {"foo", int32_t{42}},
- {"bar", std::string{"foobar"}},
+ {"foo", int32_t{42}}, {"bar", std::string{"foobar"}},
};
EXPECT_TRUE(GetCommandInterface()->SetResults(nullptr, results));
EXPECT_EQ(results, GetCommandAdaptor()->GetResults());
@@ -188,7 +187,7 @@
TEST_F(DBusCommandProxyTest, SetResults_UnknownProperty) {
EXPECT_CALL(*mock_exported_object_command_, SendSignal(_)).Times(0);
const VariantDictionary results = {
- {"quux", int32_t{42}},
+ {"quux", int32_t{42}},
};
EXPECT_FALSE(GetCommandInterface()->SetResults(nullptr, results));
}
@@ -196,8 +195,7 @@
TEST_F(DBusCommandProxyTest, Abort) {
EXPECT_CALL(*mock_exported_object_command_, SendSignal(_)).Times(1);
GetCommandInterface()->Abort();
- EXPECT_EQ(CommandInstance::kStatusAborted,
- GetCommandAdaptor()->GetStatus());
+ EXPECT_EQ(CommandInstance::kStatusAborted, GetCommandAdaptor()->GetStatus());
}
TEST_F(DBusCommandProxyTest, Cancel) {
diff --git a/libweave/src/commands/object_schema.cc b/libweave/src/commands/object_schema.cc
index 0fcf3ac..2fec07b 100644
--- a/libweave/src/commands/object_schema.cc
+++ b/libweave/src/commands/object_schema.cc
@@ -59,10 +59,9 @@
// Helper function for PropFromJson to handle the case of parameter being
// defined as a JSON string like this:
// "prop":"..."
-std::unique_ptr<PropType> PropFromJsonString(
- const base::Value& value,
- const PropType* base_schema,
- chromeos::ErrorPtr* error) {
+std::unique_ptr<PropType> PropFromJsonString(const base::Value& value,
+ const PropType* base_schema,
+ chromeos::ErrorPtr* error) {
std::string type_name;
CHECK(value.GetAsString(&type_name)) << "Unable to get string value";
std::unique_ptr<PropType> prop = CreatePropType(type_name, error);
@@ -86,41 +85,41 @@
const base::Value* first_element = nullptr;
if (list->Get(0, &first_element)) {
switch (first_element->GetType()) {
- case base::Value::TYPE_BOOLEAN:
- type_name = PropType::GetTypeStringFromType(ValueType::Boolean);
- break;
- case base::Value::TYPE_INTEGER:
- type_name = PropType::GetTypeStringFromType(ValueType::Int);
- break;
- case base::Value::TYPE_DOUBLE:
- type_name = PropType::GetTypeStringFromType(ValueType::Double);
- break;
- case base::Value::TYPE_STRING:
- type_name = PropType::GetTypeStringFromType(ValueType::String);
- break;
- case base::Value::TYPE_DICTIONARY:
- type_name = PropType::GetTypeStringFromType(ValueType::Object);
- break;
- case base::Value::TYPE_LIST: {
- if (allow_arrays) {
- type_name = PropType::GetTypeStringFromType(ValueType::Array);
- const base::ListValue* first_element_list = nullptr;
- if (first_element->GetAsList(&first_element_list)) {
- // We do not allow arrays of arrays.
- auto child_type = DetectArrayType(first_element_list, nullptr,
- false);
- if (child_type.empty()) {
- type_name.clear();
- } else {
- type_name += '.' + child_type;
+ case base::Value::TYPE_BOOLEAN:
+ type_name = PropType::GetTypeStringFromType(ValueType::Boolean);
+ break;
+ case base::Value::TYPE_INTEGER:
+ type_name = PropType::GetTypeStringFromType(ValueType::Int);
+ break;
+ case base::Value::TYPE_DOUBLE:
+ type_name = PropType::GetTypeStringFromType(ValueType::Double);
+ break;
+ case base::Value::TYPE_STRING:
+ type_name = PropType::GetTypeStringFromType(ValueType::String);
+ break;
+ case base::Value::TYPE_DICTIONARY:
+ type_name = PropType::GetTypeStringFromType(ValueType::Object);
+ break;
+ case base::Value::TYPE_LIST: {
+ if (allow_arrays) {
+ type_name = PropType::GetTypeStringFromType(ValueType::Array);
+ const base::ListValue* first_element_list = nullptr;
+ if (first_element->GetAsList(&first_element_list)) {
+ // We do not allow arrays of arrays.
+ auto child_type =
+ DetectArrayType(first_element_list, nullptr, false);
+ if (child_type.empty()) {
+ type_name.clear();
+ } else {
+ type_name += '.' + child_type;
+ }
}
}
+ break;
}
- break;
- }
- default:
- // The rest are unsupported.
- break;
+ default:
+ // The rest are unsupported.
+ break;
}
}
}
@@ -130,10 +129,9 @@
// Helper function for PropFromJson to handle the case of parameter being
// defined as a JSON array like this:
// "prop":[...]
-std::unique_ptr<PropType> PropFromJsonArray(
- const base::Value& value,
- const PropType* base_schema,
- chromeos::ErrorPtr* error) {
+std::unique_ptr<PropType> PropFromJsonArray(const base::Value& value,
+ const PropType* base_schema,
+ chromeos::ErrorPtr* error) {
std::unique_ptr<PropType> prop;
const base::ListValue* list = nullptr;
CHECK(value.GetAsList(&list)) << "Unable to get array value";
@@ -203,8 +201,8 @@
// If we have "enum", it's an array. Detect type from array elements.
const base::ListValue* list = nullptr;
- if (dict->GetListWithoutPathExpansion(
- commands::attributes::kOneOf_Enum, &list))
+ if (dict->GetListWithoutPathExpansion(commands::attributes::kOneOf_Enum,
+ &list))
return DetectArrayType(list, base_schema, true);
// If we have "default", try to use it for type detection.
@@ -233,10 +231,9 @@
// Helper function for PropFromJson to handle the case of parameter being
// defined as a JSON object like this:
// "prop":{...}
-std::unique_ptr<PropType> PropFromJsonObject(
- const base::Value& value,
- const PropType* base_schema,
- chromeos::ErrorPtr* error) {
+std::unique_ptr<PropType> PropFromJsonObject(const base::Value& value,
+ const PropType* base_schema,
+ chromeos::ErrorPtr* error) {
std::unique_ptr<PropType> prop;
const base::DictionaryValue* dict = nullptr;
CHECK(value.GetAsDictionary(&dict)) << "Unable to get dictionary value";
@@ -265,8 +262,10 @@
} // anonymous namespace
-ObjectSchema::ObjectSchema() {}
-ObjectSchema::~ObjectSchema() {}
+ObjectSchema::ObjectSchema() {
+}
+ObjectSchema::~ObjectSchema() {
+}
std::unique_ptr<ObjectSchema> ObjectSchema::Clone() const {
std::unique_ptr<ObjectSchema> cloned{new ObjectSchema};
@@ -289,7 +288,8 @@
}
std::unique_ptr<base::DictionaryValue> ObjectSchema::ToJson(
- bool full_schema, chromeos::ErrorPtr* error) const {
+ bool full_schema,
+ chromeos::ErrorPtr* error) const {
std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue);
for (const auto& pair : properties_) {
auto PropDef = pair.second->ToJson(full_schema, error);
@@ -341,17 +341,17 @@
return PropFromJsonObject(value, base_schema, error);
}
static const std::map<base::Value::Type, const char*> type_names = {
- {base::Value::TYPE_NULL, "Null"},
- {base::Value::TYPE_BOOLEAN, "Boolean"},
- {base::Value::TYPE_INTEGER, "Integer"},
- {base::Value::TYPE_DOUBLE, "Double"},
- {base::Value::TYPE_STRING, "String"},
- {base::Value::TYPE_BINARY, "Binary"},
- {base::Value::TYPE_DICTIONARY, "Object"},
- {base::Value::TYPE_LIST, "Array"},
+ {base::Value::TYPE_NULL, "Null"},
+ {base::Value::TYPE_BOOLEAN, "Boolean"},
+ {base::Value::TYPE_INTEGER, "Integer"},
+ {base::Value::TYPE_DOUBLE, "Double"},
+ {base::Value::TYPE_STRING, "String"},
+ {base::Value::TYPE_BINARY, "Binary"},
+ {base::Value::TYPE_DICTIONARY, "Object"},
+ {base::Value::TYPE_LIST, "Array"},
};
- const char* type_name = chromeos::GetOrDefault(type_names, value.GetType(),
- "<unknown>");
+ const char* type_name =
+ chromeos::GetOrDefault(type_names, value.GetType(), "<unknown>");
chromeos::Error::AddToPrintf(error, FROM_HERE, errors::commands::kDomain,
errors::commands::kUnknownType,
"Unexpected JSON value type: %s", type_name);
diff --git a/libweave/src/commands/object_schema.h b/libweave/src/commands/object_schema.h
index 4add1c7..d6eafed 100644
--- a/libweave/src/commands/object_schema.h
+++ b/libweave/src/commands/object_schema.h
@@ -63,7 +63,8 @@
// then all properties and constraints are saved, otherwise, only
// the overridden (not inherited) ones are saved.
std::unique_ptr<base::DictionaryValue> ToJson(
- bool full_schema, chromeos::ErrorPtr* error) const;
+ bool full_schema,
+ chromeos::ErrorPtr* error) const;
// Loads the object schema from JSON. If |object_schema| is not nullptr, it is
// used as a base schema to inherit omitted properties and constraints from.
diff --git a/libweave/src/commands/object_schema_unittest.cc b/libweave/src/commands/object_schema_unittest.cc
index 04ca232..12bf8a5 100644
--- a/libweave/src/commands/object_schema_unittest.cc
+++ b/libweave/src/commands/object_schema_unittest.cc
@@ -73,11 +73,10 @@
IntPropType param2;
param2.FromJson(CreateDictionaryValue("{}").get(), &prop, nullptr);
EXPECT_JSON_EQ("{}", *param2.ToJson(false, nullptr));
- param2.FromJson(CreateDictionaryValue("{'minimum':3}").get(),
- &prop, nullptr);
+ param2.FromJson(CreateDictionaryValue("{'minimum':3}").get(), &prop, nullptr);
EXPECT_JSON_EQ("{'minimum':3}", *param2.ToJson(false, nullptr));
- param2.FromJson(CreateDictionaryValue("{'maximum':-7}").get(),
- &prop, nullptr);
+ param2.FromJson(CreateDictionaryValue("{'maximum':-7}").get(), &prop,
+ nullptr);
EXPECT_JSON_EQ("{'maximum':-7}", *param2.ToJson(false, nullptr));
param2.FromJson(CreateDictionaryValue("{'minimum':0,'maximum':5}").get(),
&prop, nullptr);
@@ -85,8 +84,8 @@
param2.FromJson(CreateDictionaryValue("{'enum':[1,2,3]}").get(), &prop,
nullptr);
EXPECT_JSON_EQ("[1,2,3]", *param2.ToJson(false, nullptr));
- param2.FromJson(CreateDictionaryValue("{'default':123}").get(),
- &prop, nullptr);
+ param2.FromJson(CreateDictionaryValue("{'default':123}").get(), &prop,
+ nullptr);
EXPECT_JSON_EQ("{'default':123}", *param2.ToJson(false, nullptr));
}
@@ -100,14 +99,13 @@
EXPECT_EQ(2, prop.GetMinValue());
EXPECT_EQ(8, prop.GetMaxValue());
prop.AddMinMaxConstraint(-2, 30);
- param2.FromJson(CreateDictionaryValue("{'minimum':7}").get(),
- &prop, nullptr);
+ param2.FromJson(CreateDictionaryValue("{'minimum':7}").get(), &prop, nullptr);
EXPECT_TRUE(param2.HasOverriddenAttributes());
EXPECT_TRUE(param2.IsBasedOnSchema());
EXPECT_EQ(7, param2.GetMinValue());
EXPECT_EQ(30, param2.GetMaxValue());
- param2.FromJson(CreateDictionaryValue("{'maximum':17}").get(),
- &prop, nullptr);
+ param2.FromJson(CreateDictionaryValue("{'maximum':17}").get(), &prop,
+ nullptr);
EXPECT_TRUE(param2.HasOverriddenAttributes());
EXPECT_TRUE(param2.IsBasedOnSchema());
EXPECT_EQ(-2, param2.GetMinValue());
@@ -198,15 +196,14 @@
EXPECT_JSON_EQ("[true,false]", *param2.ToJson(false, nullptr));
EXPECT_JSON_EQ("{'enum':[true,false],'type':'boolean'}",
*param2.ToJson(true, nullptr));
- param2.FromJson(CreateDictionaryValue("{'default':true}").get(),
- &prop, nullptr);
+ param2.FromJson(CreateDictionaryValue("{'default':true}").get(), &prop,
+ nullptr);
EXPECT_JSON_EQ("{'default':true}", *param2.ToJson(false, nullptr));
}
TEST(CommandSchema, BoolPropType_FromJson) {
BooleanPropType prop;
- prop.FromJson(CreateDictionaryValue("{'enum':[true]}").get(), &prop,
- nullptr);
+ prop.FromJson(CreateDictionaryValue("{'enum':[true]}").get(), &prop, nullptr);
BooleanPropType param2;
param2.FromJson(CreateDictionaryValue("{}").get(), &prop, nullptr);
EXPECT_FALSE(param2.HasOverriddenAttributes());
@@ -224,8 +221,7 @@
TEST(CommandSchema, BoolPropType_Validate) {
BooleanPropType prop;
- prop.FromJson(CreateDictionaryValue("{'enum':[true]}").get(), &prop,
- nullptr);
+ prop.FromJson(CreateDictionaryValue("{'enum':[true]}").get(), &prop, nullptr);
chromeos::ErrorPtr error;
EXPECT_FALSE(prop.ValidateValue(CreateValue("false").get(), &error));
EXPECT_EQ("out_of_range", error->GetCode());
@@ -284,8 +280,7 @@
DoublePropType param2;
param2.FromJson(CreateDictionaryValue("{}").get(), &prop, nullptr);
EXPECT_JSON_EQ("{}", *param2.ToJson(false, nullptr));
- param2.FromJson(CreateDictionaryValue("{'minimum':3}").get(), &prop,
- nullptr);
+ param2.FromJson(CreateDictionaryValue("{'minimum':3}").get(), &prop, nullptr);
EXPECT_JSON_EQ("{'minimum':3.0}", *param2.ToJson(false, nullptr));
param2.FromJson(CreateDictionaryValue("{'maximum':-7}").get(), &prop,
nullptr);
@@ -294,8 +289,8 @@
&prop, nullptr);
EXPECT_JSON_EQ("{'maximum':5.0,'minimum':0.0}",
*param2.ToJson(false, nullptr));
- param2.FromJson(CreateDictionaryValue("{'default':12.3}").get(),
- &prop, nullptr);
+ param2.FromJson(CreateDictionaryValue("{'default':12.3}").get(), &prop,
+ nullptr);
EXPECT_JSON_EQ("{'default':12.3}", *param2.ToJson(false, nullptr));
}
@@ -309,8 +304,7 @@
EXPECT_DOUBLE_EQ(2.5, prop.GetMinValue());
EXPECT_DOUBLE_EQ(8.7, prop.GetMaxValue());
prop.AddMinMaxConstraint(-2.2, 30.4);
- param2.FromJson(CreateDictionaryValue("{'minimum':7}").get(), &prop,
- nullptr);
+ param2.FromJson(CreateDictionaryValue("{'minimum':7}").get(), &prop, nullptr);
EXPECT_TRUE(param2.HasOverriddenAttributes());
EXPECT_TRUE(param2.IsBasedOnSchema());
EXPECT_DOUBLE_EQ(7.0, param2.GetMinValue());
@@ -413,8 +407,8 @@
&prop, nullptr);
EXPECT_JSON_EQ("{'maxLength':5,'minLength':0}",
*param2.ToJson(false, nullptr));
- param2.FromJson(CreateDictionaryValue("{'default':'abcd'}").get(),
- &prop, nullptr);
+ param2.FromJson(CreateDictionaryValue("{'default':'abcd'}").get(), &prop,
+ nullptr);
EXPECT_JSON_EQ("{'default':'abcd'}", *param2.ToJson(false, nullptr));
}
@@ -440,8 +434,8 @@
EXPECT_TRUE(param2.IsBasedOnSchema());
EXPECT_EQ(3, param2.GetMinLength());
EXPECT_EQ(8, param2.GetMaxLength());
- param2.FromJson(CreateDictionaryValue(
- "{'minLength':1,'maxLength':7}").get(), &prop, nullptr);
+ param2.FromJson(CreateDictionaryValue("{'minLength':1,'maxLength':7}").get(),
+ &prop, nullptr);
EXPECT_TRUE(param2.HasOverriddenAttributes());
EXPECT_TRUE(param2.IsBasedOnSchema());
EXPECT_EQ(1, param2.GetMinLength());
@@ -567,9 +561,11 @@
EXPECT_JSON_EQ(expected, *prop2.ToJson(true, nullptr));
ObjectPropType prop3;
- ASSERT_TRUE(prop3.FromJson(CreateDictionaryValue(
- "{'default':{'expires':3,'password':'abracadabra'}}").get(), &prop2,
- nullptr));
+ ASSERT_TRUE(
+ prop3.FromJson(CreateDictionaryValue(
+ "{'default':{'expires':3,'password':'abracadabra'}}")
+ .get(),
+ &prop2, nullptr));
expected = R"({
'default': {
'expires': 3,
@@ -599,10 +595,12 @@
EXPECT_JSON_EQ(expected, *prop3.ToJson(true, nullptr));
ObjectPropType prop4;
- ASSERT_TRUE(prop4.FromJson(CreateDictionaryValue(
- "{'additionalProperties':true,"
- "'default':{'expires':3,'password':'abracadabra'}}").get(), &prop2,
- nullptr));
+ ASSERT_TRUE(
+ prop4.FromJson(CreateDictionaryValue(
+ "{'additionalProperties':true,"
+ "'default':{'expires':3,'password':'abracadabra'}}")
+ .get(),
+ &prop2, nullptr));
expected = R"({
'additionalProperties': true,
'default': {
@@ -642,9 +640,10 @@
TEST(CommandSchema, ObjectPropType_FromJson) {
ObjectPropType base_prop;
- EXPECT_TRUE(base_prop.FromJson(CreateDictionaryValue(
- "{'properties':{'name':'string','age':'integer'}}").get(), nullptr,
- nullptr));
+ EXPECT_TRUE(base_prop.FromJson(
+ CreateDictionaryValue("{'properties':{'name':'string','age':'integer'}}")
+ .get(),
+ nullptr, nullptr));
auto schema = base_prop.GetObject()->GetObjectSchemaPtr();
const PropType* prop = schema->GetProp("name");
EXPECT_EQ(ValueType::String, prop->GetType());
@@ -652,9 +651,12 @@
EXPECT_EQ(ValueType::Int, prop->GetType());
ObjectPropType prop2;
- ASSERT_TRUE(prop2.FromJson(CreateDictionaryValue(
- "{'properties':{'name':'string','age':'integer'},"
- "'default':{'name':'Bob','age':33}}").get(), nullptr, nullptr));
+ ASSERT_TRUE(
+ prop2.FromJson(CreateDictionaryValue(
+ "{'properties':{'name':'string','age':'integer'},"
+ "'default':{'name':'Bob','age':33}}")
+ .get(),
+ nullptr, nullptr));
ASSERT_NE(nullptr, prop2.GetDefaultValue());
const ObjectValue* defval = prop2.GetDefaultValue()->GetObject();
ASSERT_NE(nullptr, defval);
@@ -666,26 +668,26 @@
TEST(CommandSchema, ObjectPropType_Validate) {
ObjectPropType prop;
prop.FromJson(CreateDictionaryValue(
- "{'properties':{'expires':'integer',"
- "'password':{'maxLength':100,'minLength':6}}}").get(), nullptr,
- nullptr);
+ "{'properties':{'expires':'integer',"
+ "'password':{'maxLength':100,'minLength':6}}}")
+ .get(),
+ nullptr, nullptr);
chromeos::ErrorPtr error;
- EXPECT_TRUE(prop.ValidateValue(CreateValue(
- "{'expires':10,'password':'abcdef'}").get(), &error));
+ EXPECT_TRUE(prop.ValidateValue(
+ CreateValue("{'expires':10,'password':'abcdef'}").get(), &error));
error.reset();
- EXPECT_FALSE(prop.ValidateValue(CreateValue(
- "{'expires':10}").get(), &error));
+ EXPECT_FALSE(prop.ValidateValue(CreateValue("{'expires':10}").get(), &error));
EXPECT_EQ("parameter_missing", error->GetCode());
error.reset();
- EXPECT_FALSE(prop.ValidateValue(CreateValue(
- "{'password':'abcdef'}").get(), &error));
+ EXPECT_FALSE(
+ prop.ValidateValue(CreateValue("{'password':'abcdef'}").get(), &error));
EXPECT_EQ("parameter_missing", error->GetCode());
error.reset();
- EXPECT_FALSE(prop.ValidateValue(CreateValue(
- "{'expires':10,'password':'abcde'}").get(), &error));
+ EXPECT_FALSE(prop.ValidateValue(
+ CreateValue("{'expires':10,'password':'abcde'}").get(), &error));
EXPECT_EQ("out_of_range", error->GetFirstError()->GetCode());
error.reset();
@@ -693,29 +695,32 @@
EXPECT_EQ("type_mismatch", error->GetCode());
error.reset();
- EXPECT_FALSE(prop.ValidateValue(CreateValue(
- "{'expires':10,'password':'abcdef','retry':true}").get(), &error));
+ EXPECT_FALSE(prop.ValidateValue(
+ CreateValue("{'expires':10,'password':'abcdef','retry':true}").get(),
+ &error));
EXPECT_EQ("unexpected_parameter", error->GetCode());
error.reset();
}
TEST(CommandSchema, ObjectPropType_Validate_Enum) {
ObjectPropType prop;
- EXPECT_TRUE(prop.FromJson(CreateDictionaryValue(
- "{'properties':{'width':'integer','height':'integer'},"
- "'enum':[{'width':10,'height':20},{'width':100,'height':200}]}").get(),
+ EXPECT_TRUE(prop.FromJson(
+ CreateDictionaryValue(
+ "{'properties':{'width':'integer','height':'integer'},"
+ "'enum':[{'width':10,'height':20},{'width':100,'height':200}]}")
+ .get(),
nullptr, nullptr));
chromeos::ErrorPtr error;
- EXPECT_TRUE(prop.ValidateValue(CreateValue(
- "{'height':20,'width':10}").get(), &error));
+ EXPECT_TRUE(prop.ValidateValue(CreateValue("{'height':20,'width':10}").get(),
+ &error));
error.reset();
- EXPECT_TRUE(prop.ValidateValue(CreateValue(
- "{'height':200,'width':100}").get(), &error));
+ EXPECT_TRUE(prop.ValidateValue(
+ CreateValue("{'height':200,'width':100}").get(), &error));
error.reset();
- EXPECT_FALSE(prop.ValidateValue(CreateValue(
- "{'height':12,'width':10}").get(), &error));
+ EXPECT_FALSE(prop.ValidateValue(CreateValue("{'height':12,'width':10}").get(),
+ &error));
EXPECT_EQ("out_of_range", error->GetCode());
error.reset();
}
@@ -723,9 +728,11 @@
TEST(CommandSchema, ObjectPropType_CreateValue) {
ObjectPropType prop;
IntPropType int_type;
- ASSERT_TRUE(prop.FromJson(CreateDictionaryValue(
- "{'properties':{'width':'integer','height':'integer'},"
- "'enum':[{'width':10,'height':20},{'width':100,'height':200}]}").get(),
+ ASSERT_TRUE(prop.FromJson(
+ CreateDictionaryValue(
+ "{'properties':{'width':'integer','height':'integer'},"
+ "'enum':[{'width':10,'height':20},{'width':100,'height':200}]}")
+ .get(),
nullptr, nullptr));
native_types::Object obj{
{"width", int_type.CreateValue(10, nullptr)},
@@ -779,8 +786,8 @@
prop2.FromJson(CreateDictionaryValue("{}").get(), &prop, nullptr);
EXPECT_JSON_EQ("{}", *prop2.ToJson(false, nullptr));
EXPECT_TRUE(prop2.IsBasedOnSchema());
- prop2.FromJson(CreateDictionaryValue("{'default':[1,2,3]}").get(),
- &prop, nullptr);
+ prop2.FromJson(CreateDictionaryValue("{'default':[1,2,3]}").get(), &prop,
+ nullptr);
EXPECT_JSON_EQ("{'default':[1,2,3]}", *prop2.ToJson(false, nullptr));
EXPECT_JSON_EQ(
"{'default':[1,2,3],'items':{'type':'integer'},'type':'array'}",
@@ -789,14 +796,16 @@
TEST(CommandSchema, ArrayPropType_FromJson) {
ArrayPropType prop;
- EXPECT_TRUE(prop.FromJson(
- CreateDictionaryValue("{'items':'integer'}").get(), nullptr, nullptr));
+ EXPECT_TRUE(prop.FromJson(CreateDictionaryValue("{'items':'integer'}").get(),
+ nullptr, nullptr));
EXPECT_EQ(ValueType::Int, prop.GetItemTypePtr()->GetType());
ArrayPropType prop2;
- ASSERT_TRUE(prop2.FromJson(CreateDictionaryValue(
- "{'items':'string','default':['foo', 'bar', 'baz']}").get(), nullptr,
- nullptr));
+ ASSERT_TRUE(
+ prop2.FromJson(CreateDictionaryValue(
+ "{'items':'string','default':['foo', 'bar', 'baz']}")
+ .get(),
+ nullptr, nullptr));
ASSERT_NE(nullptr, prop2.GetDefaultValue());
const ArrayValue* defval = prop2.GetDefaultValue()->GetArray();
ASSERT_NE(nullptr, defval);
@@ -806,9 +815,9 @@
TEST(CommandSchema, ArrayPropType_Validate) {
ArrayPropType prop;
- prop.FromJson(CreateDictionaryValue(
- "{'items':{'minimum':2.3, 'maximum':10.5}}").get(), nullptr,
- nullptr);
+ prop.FromJson(
+ CreateDictionaryValue("{'items':{'minimum':2.3, 'maximum':10.5}}").get(),
+ nullptr, nullptr);
chromeos::ErrorPtr error;
EXPECT_TRUE(prop.ValidateValue(CreateValue("[3,4,10.5]").get(), &error));
@@ -829,9 +838,10 @@
TEST(CommandSchema, ArrayPropType_Validate_Enum) {
ArrayPropType prop;
- prop.FromJson(CreateDictionaryValue(
- "{'items':'integer', 'enum':[[1], [2,3], [4,5,6]]}").get(), nullptr,
- nullptr);
+ prop.FromJson(
+ CreateDictionaryValue("{'items':'integer', 'enum':[[1], [2,3], [4,5,6]]}")
+ .get(),
+ nullptr, nullptr);
chromeos::ErrorPtr error;
EXPECT_TRUE(prop.ValidateValue(CreateValue("[2,3]").get(), &error));
@@ -850,8 +860,10 @@
TEST(CommandSchema, ArrayPropType_CreateValue) {
ArrayPropType prop;
- ASSERT_TRUE(prop.FromJson(CreateDictionaryValue(
- "{'items':{'properties':{'width':'integer','height':'integer'}}}").get(),
+ ASSERT_TRUE(prop.FromJson(
+ CreateDictionaryValue(
+ "{'items':{'properties':{'width':'integer','height':'integer'}}}")
+ .get(),
nullptr, nullptr));
chromeos::ErrorPtr error;
@@ -865,8 +877,10 @@
IntPropType int_type;
ObjectPropType obj_type;
- ASSERT_TRUE(obj_type.FromJson(CreateDictionaryValue(
- "{'properties':{'width':'integer','height':'integer'}}").get(),
+ ASSERT_TRUE(obj_type.FromJson(
+ CreateDictionaryValue(
+ "{'properties':{'width':'integer','height':'integer'}}")
+ .get(),
nullptr, nullptr));
arr.push_back(obj_type.CreateValue(
native_types::Object{
@@ -897,8 +911,9 @@
TEST(CommandSchema, ArrayPropType_NestedArrays_NotSupported) {
ArrayPropType prop;
chromeos::ErrorPtr error;
- EXPECT_FALSE(prop.FromJson(CreateDictionaryValue(
- "{'items':{'items':'integer'}}").get(), nullptr, &error));
+ EXPECT_FALSE(prop.FromJson(
+ CreateDictionaryValue("{'items':{'items':'integer'}}").get(), nullptr,
+ &error));
EXPECT_EQ(errors::commands::kInvalidObjectSchema, error->GetCode());
error.reset();
}
@@ -907,7 +922,8 @@
TEST(CommandSchema, ObjectSchema_FromJson_Shorthand_TypeName) {
ObjectSchema schema;
- const char* schema_str = "{"
+ const char* schema_str =
+ "{"
"'param1':'integer',"
"'param2':'number',"
"'param3':'string'"
@@ -936,7 +952,8 @@
TEST(CommandSchema, ObjectSchema_FromJson_Full_TypeName) {
ObjectSchema schema;
- const char* schema_str = "{"
+ const char* schema_str =
+ "{"
"'param1':{'type':'integer'},"
"'param2':{'type':'number'},"
"'param3':{'type':'string'},"
@@ -971,7 +988,8 @@
TEST(CommandSchema, ObjectSchema_FromJson_Shorthand_TypeDeduction_Scalar) {
ObjectSchema schema;
- const char* schema_str = "{"
+ const char* schema_str =
+ "{"
"'param1' :{'minimum':2},"
"'param2' :{'maximum':10},"
"'param3' :{'maximum':8, 'minimum':2},"
@@ -1011,12 +1029,10 @@
EXPECT_EQ("string", schema.GetProp("param16")->GetTypeAsString());
EXPECT_EQ("array", schema.GetProp("param17")->GetTypeAsString());
auto prop17 = schema.GetProp("param17");
- EXPECT_EQ("integer",
- prop17->GetArray()->GetItemTypePtr()->GetTypeAsString());
+ EXPECT_EQ("integer", prop17->GetArray()->GetItemTypePtr()->GetTypeAsString());
EXPECT_EQ("array", schema.GetProp("param18")->GetTypeAsString());
auto prop18 = schema.GetProp("param18");
- EXPECT_EQ("number",
- prop18->GetArray()->GetItemTypePtr()->GetTypeAsString());
+ EXPECT_EQ("number", prop18->GetArray()->GetItemTypePtr()->GetTypeAsString());
int min_int = (std::numeric_limits<int>::min)();
int max_int = (std::numeric_limits<int>::max)();
@@ -1065,7 +1081,8 @@
TEST(CommandSchema, ObjectSchema_FromJson_Shorthand_TypeDeduction_Array) {
ObjectSchema schema;
- const char* schema_str = "{"
+ const char* schema_str =
+ "{"
"'param1' :[0,1,2,3],"
"'param2' :[0.0,1.1,2.2],"
"'param3' :['id1', 'id2'],"
@@ -1079,7 +1096,7 @@
"'param11':[[0,1],[2,3]],"
"'param12':[['foo','bar']],"
"'param13':{'enum':[['id0', 'id1']]}"
- "}";
+ "}";
EXPECT_TRUE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
nullptr));
EXPECT_EQ("integer", schema.GetProp("param1")->GetTypeAsString());
@@ -1130,7 +1147,8 @@
}
TEST(CommandSchema, ObjectSchema_FromJson_Inheritance) {
- const char* base_schema_str = "{"
+ const char* base_schema_str =
+ "{"
"'param0' :{'minimum':1, 'maximum':5},"
"'param1' :{'minimum':1, 'maximum':5},"
"'param2' :{'minimum':1, 'maximum':5},"
@@ -1158,7 +1176,8 @@
ObjectSchema base_schema;
EXPECT_TRUE(base_schema.FromJson(CreateDictionaryValue(base_schema_str).get(),
nullptr, nullptr));
- const char* schema_str = "{"
+ const char* schema_str =
+ "{"
"'param1' :{},"
"'param2' :{'minimum':2},"
"'param3' :{'maximum':9},"
@@ -1254,17 +1273,18 @@
TEST(CommandSchema, ObjectSchema_UseDefaults) {
ObjectPropType prop;
- const char* schema_str = "{'properties':{"
+ const char* schema_str =
+ "{'properties':{"
"'param1':{'default':true},"
"'param2':{'default':2},"
"'param3':{'default':3.3},"
"'param4':{'default':'four'},"
"'param5':{'default':{'x':5,'y':6},"
- "'properties':{'x':'integer','y':'integer'}},"
+ "'properties':{'x':'integer','y':'integer'}},"
"'param6':{'default':[1,2,3]}"
"}}";
- ASSERT_TRUE(prop.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
- nullptr));
+ ASSERT_TRUE(
+ prop.FromJson(CreateDictionaryValue(schema_str).get(), nullptr, nullptr));
// Omit all.
auto value = prop.CreateValue();
@@ -1282,7 +1302,8 @@
// Specify some.
value = prop.CreateValue();
- const char* val_json = "{"
+ const char* val_json =
+ "{"
"'param1':false,"
"'param3':33.3,"
"'param5':{'x':-5,'y':-6}"
@@ -1301,7 +1322,8 @@
// Specify all.
value = prop.CreateValue();
- val_json = "{"
+ val_json =
+ "{"
"'param1':false,"
"'param2':22,"
"'param3':333.3,"
@@ -1325,7 +1347,8 @@
TEST(CommandSchema, ObjectSchema_FromJson_BaseSchema_Failures) {
ObjectSchema schema;
chromeos::ErrorPtr error;
- const char* schema_str = "{"
+ const char* schema_str =
+ "{"
"'param1':{}"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1333,7 +1356,8 @@
EXPECT_EQ("no_type_info", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':{'type':'foo'}"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1341,7 +1365,8 @@
EXPECT_EQ("unknown_type", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':[]"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1349,7 +1374,8 @@
EXPECT_EQ("no_type_info", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':{'minimum':'foo'}"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1357,7 +1383,8 @@
EXPECT_EQ("type_mismatch", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':[1,2.2]"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1365,7 +1392,8 @@
EXPECT_EQ("type_mismatch", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':{'minimum':1, 'enum':[1,2,3]}" // can't have min/max & enum.
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1373,7 +1401,8 @@
EXPECT_EQ("unexpected_parameter", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':{'maximum':1, 'blah':2}" // 'blah' is unexpected.
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1381,7 +1410,8 @@
EXPECT_EQ("unexpected_parameter", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':{'enum':[1,2,3],'default':5}" // 'default' must be 1, 2, or 3.
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1389,7 +1419,8 @@
EXPECT_EQ("out_of_range", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':[[1,2.3]]"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1397,7 +1428,8 @@
EXPECT_EQ("type_mismatch", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':[[1,2],[3,4],['blah']]"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1405,7 +1437,8 @@
EXPECT_EQ("type_mismatch", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':{'default':[]}"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1413,7 +1446,8 @@
EXPECT_EQ("no_type_info", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':[[[1]],[[2]]]"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1421,7 +1455,8 @@
EXPECT_EQ("no_type_info", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':{'enum':[[['foo']]]}"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
@@ -1429,7 +1464,8 @@
EXPECT_EQ("no_type_info", error->GetFirstError()->GetCode());
error.reset();
- schema_str = "{"
+ schema_str =
+ "{"
"'param1':{'default':[[1],[2]]}"
"}";
EXPECT_FALSE(schema.FromJson(CreateDictionaryValue(schema_str).get(), nullptr,
diff --git a/libweave/src/commands/prop_constraints.cc b/libweave/src/commands/prop_constraints.cc
index c8f78e4..29d3348 100644
--- a/libweave/src/commands/prop_constraints.cc
+++ b/libweave/src/commands/prop_constraints.cc
@@ -26,7 +26,8 @@
} // anonymous namespace
// Constraint ----------------------------------------------------------------
-Constraint::~Constraint() {}
+Constraint::~Constraint() {
+}
bool Constraint::ReportErrorLessThan(chromeos::ErrorPtr* error,
const std::string& val,
@@ -34,8 +35,8 @@
chromeos::Error::AddToPrintf(
error, FROM_HERE, errors::commands::kDomain,
errors::commands::kOutOfRange,
- "Value %s is out of range. It must not be less than %s",
- val.c_str(), limit.c_str());
+ "Value %s is out of range. It must not be less than %s", val.c_str(),
+ limit.c_str());
return false;
}
@@ -45,8 +46,8 @@
chromeos::Error::AddToPrintf(
error, FROM_HERE, errors::commands::kDomain,
errors::commands::kOutOfRange,
- "Value %s is out of range. It must not be greater than %s",
- val.c_str(), limit.c_str());
+ "Value %s is out of range. It must not be greater than %s", val.c_str(),
+ limit.c_str());
return false;
}
@@ -75,8 +76,11 @@
// ConstraintStringLength -----------------------------------------------------
ConstraintStringLength::ConstraintStringLength(
- const InheritableAttribute<int>& limit) : limit_(limit) {}
-ConstraintStringLength::ConstraintStringLength(int limit) : limit_(limit) {}
+ const InheritableAttribute<int>& limit)
+ : limit_(limit) {
+}
+ConstraintStringLength::ConstraintStringLength(int limit) : limit_(limit) {
+}
bool ConstraintStringLength::HasOverriddenAttributes() const {
return !limit_.is_inherited;
@@ -89,9 +93,12 @@
// ConstraintStringLengthMin --------------------------------------------------
ConstraintStringLengthMin::ConstraintStringLengthMin(
- const InheritableAttribute<int>& limit) : ConstraintStringLength(limit) {}
+ const InheritableAttribute<int>& limit)
+ : ConstraintStringLength(limit) {
+}
ConstraintStringLengthMin::ConstraintStringLengthMin(int limit)
- : ConstraintStringLength(limit) {}
+ : ConstraintStringLength(limit) {
+}
bool ConstraintStringLengthMin::Validate(const PropValue& value,
chromeos::ErrorPtr* error) const {
@@ -115,22 +122,24 @@
return true;
}
-std::unique_ptr<Constraint>
-ConstraintStringLengthMin::Clone() const {
+std::unique_ptr<Constraint> ConstraintStringLengthMin::Clone() const {
return std::unique_ptr<Constraint>{new ConstraintStringLengthMin{limit_}};
}
-std::unique_ptr<Constraint>
-ConstraintStringLengthMin::CloneAsInherited() const {
+std::unique_ptr<Constraint> ConstraintStringLengthMin::CloneAsInherited()
+ const {
return std::unique_ptr<Constraint>{
new ConstraintStringLengthMin{limit_.value}};
}
// ConstraintStringLengthMax --------------------------------------------------
ConstraintStringLengthMax::ConstraintStringLengthMax(
- const InheritableAttribute<int>& limit) : ConstraintStringLength(limit) {}
+ const InheritableAttribute<int>& limit)
+ : ConstraintStringLength(limit) {
+}
ConstraintStringLengthMax::ConstraintStringLengthMax(int limit)
- : ConstraintStringLength(limit) {}
+ : ConstraintStringLength(limit) {
+}
bool ConstraintStringLengthMax::Validate(const PropValue& value,
chromeos::ErrorPtr* error) const {
@@ -148,22 +157,23 @@
return true;
}
-std::unique_ptr<Constraint>
-ConstraintStringLengthMax::Clone() const {
+std::unique_ptr<Constraint> ConstraintStringLengthMax::Clone() const {
return std::unique_ptr<Constraint>{new ConstraintStringLengthMax{limit_}};
}
-std::unique_ptr<Constraint>
-ConstraintStringLengthMax::CloneAsInherited() const {
+std::unique_ptr<Constraint> ConstraintStringLengthMax::CloneAsInherited()
+ const {
return std::unique_ptr<Constraint>{
new ConstraintStringLengthMax{limit_.value}};
}
// ConstraintOneOf --------------------------------------------------
ConstraintOneOf::ConstraintOneOf(InheritableAttribute<native_types::Array> set)
- : set_(std::move(set)) {}
+ : set_(std::move(set)) {
+}
ConstraintOneOf::ConstraintOneOf(native_types::Array set)
- : set_(std::move(set)) {}
+ : set_(std::move(set)) {
+}
bool ConstraintOneOf::Validate(const PropValue& value,
chromeos::ErrorPtr* error) const {
diff --git a/libweave/src/commands/prop_constraints.h b/libweave/src/commands/prop_constraints.h
index ccfaaf0..71d273a 100644
--- a/libweave/src/commands/prop_constraints.h
+++ b/libweave/src/commands/prop_constraints.h
@@ -20,13 +20,7 @@
namespace buffet {
-enum class ConstraintType {
- Min,
- Max,
- StringLengthMin,
- StringLengthMax,
- OneOf
-};
+enum class ConstraintType { Min, Max, StringLengthMin, StringLengthMax, OneOf };
// Abstract base class for all parameter constraints. Many constraints are
// type-dependent. Thus, a numeric parameter could have "minimum" and/or
@@ -102,18 +96,15 @@
// ConstraintMinMaxBase is a base class for numeric Minimum and Maximum
// constraints.
-template<typename T>
+template <typename T>
class ConstraintMinMaxBase : public Constraint {
public:
explicit ConstraintMinMaxBase(const InheritableAttribute<T>& limit)
: limit_(limit) {}
- explicit ConstraintMinMaxBase(const T& limit)
- : limit_(limit) {}
+ explicit ConstraintMinMaxBase(const T& limit) : limit_(limit) {}
// Implementation of Constraint::HasOverriddenAttributes().
- bool HasOverriddenAttributes() const override {
- return !limit_.is_inherited;
- }
+ bool HasOverriddenAttributes() const override { return !limit_.is_inherited; }
// Implementation of Constraint::ToJson().
std::unique_ptr<base::Value> ToJson(
@@ -131,13 +122,12 @@
};
// Implementation of Minimum value constraint for Integer/Double types.
-template<typename T>
+template <typename T>
class ConstraintMin : public ConstraintMinMaxBase<T> {
public:
explicit ConstraintMin(const InheritableAttribute<T>& limit)
: ConstraintMinMaxBase<T>(limit) {}
- explicit ConstraintMin(const T& limit)
- : ConstraintMinMaxBase<T>(limit) {}
+ explicit ConstraintMin(const T& limit) : ConstraintMinMaxBase<T>(limit) {}
// Implementation of Constraint::GetType().
ConstraintType GetType() const override { return ConstraintType::Min; }
@@ -173,13 +163,12 @@
};
// Implementation of Maximum value constraint for Integer/Double types.
-template<typename T>
+template <typename T>
class ConstraintMax : public ConstraintMinMaxBase<T> {
public:
explicit ConstraintMax(const InheritableAttribute<T>& limit)
: ConstraintMinMaxBase<T>(limit) {}
- explicit ConstraintMax(const T& limit)
- : ConstraintMinMaxBase<T>(limit) {}
+ explicit ConstraintMax(const T& limit) : ConstraintMinMaxBase<T>(limit) {}
// Implementation of Constraint::GetType().
ConstraintType GetType() const override { return ConstraintType::Max; }
@@ -301,14 +290,10 @@
explicit ConstraintOneOf(native_types::Array set);
// Implementation of Constraint::GetType().
- ConstraintType GetType() const override {
- return ConstraintType::OneOf;
- }
+ ConstraintType GetType() const override { return ConstraintType::OneOf; }
// Implementation of Constraint::HasOverriddenAttributes().
- bool HasOverriddenAttributes() const override {
- return !set_.is_inherited;
- }
+ bool HasOverriddenAttributes() const override { return !set_.is_inherited; }
// Implementation of Constraint::Validate().
bool Validate(const PropValue& value,
diff --git a/libweave/src/commands/prop_types.cc b/libweave/src/commands/prop_types.cc
index 8da4260..bfd1b50 100644
--- a/libweave/src/commands/prop_types.cc
+++ b/libweave/src/commands/prop_types.cc
@@ -225,12 +225,12 @@
const PropType::TypeMap& PropType::GetTypeMap() {
static TypeMap map = {
- {ValueType::Int, "integer"},
- {ValueType::Double, "number"},
- {ValueType::String, "string"},
- {ValueType::Boolean, "boolean"},
- {ValueType::Object, "object"},
- {ValueType::Array, "array"},
+ {ValueType::Int, "integer"},
+ {ValueType::Double, "number"},
+ {ValueType::String, "string"},
+ {ValueType::Boolean, "boolean"},
+ {ValueType::Object, "object"},
+ {ValueType::Array, "array"},
};
return map;
}
@@ -257,37 +257,37 @@
std::unique_ptr<PropType> PropType::Create(ValueType type) {
PropType* prop = nullptr;
switch (type) {
- case buffet::ValueType::Int:
- prop = new IntPropType;
- break;
- case buffet::ValueType::Double:
- prop = new DoublePropType;
- break;
- case buffet::ValueType::String:
- prop = new StringPropType;
- break;
- case buffet::ValueType::Boolean:
- prop = new BooleanPropType;
- break;
- case buffet::ValueType::Object:
- prop = new ObjectPropType;
- break;
- case buffet::ValueType::Array:
- prop = new ArrayPropType;
- break;
+ case buffet::ValueType::Int:
+ prop = new IntPropType;
+ break;
+ case buffet::ValueType::Double:
+ prop = new DoublePropType;
+ break;
+ case buffet::ValueType::String:
+ prop = new StringPropType;
+ break;
+ case buffet::ValueType::Boolean:
+ prop = new BooleanPropType;
+ break;
+ case buffet::ValueType::Object:
+ prop = new ObjectPropType;
+ break;
+ case buffet::ValueType::Array:
+ prop = new ArrayPropType;
+ break;
}
return std::unique_ptr<PropType>(prop);
}
bool PropType::GenerateErrorValueTypeMismatch(chromeos::ErrorPtr* error) const {
chromeos::Error::AddToPrintf(error, FROM_HERE, errors::commands::kDomain,
- errors::commands::kTypeMismatch,
- "Unable to convert value to type '%s'",
- GetTypeAsString().c_str());
+ errors::commands::kTypeMismatch,
+ "Unable to convert value to type '%s'",
+ GetTypeAsString().c_str());
return false;
}
-template<typename T>
+template <typename T>
static std::unique_ptr<Constraint> LoadOneOfConstraint(
const base::DictionaryValue* value,
const PropType* prop_type,
@@ -306,7 +306,7 @@
return constraint;
}
-template<class ConstraintClass, typename T>
+template <class ConstraintClass, typename T>
static std::unique_ptr<Constraint> LoadMinMaxConstraint(
const char* dict_key,
const base::DictionaryValue* value,
@@ -326,7 +326,7 @@
// PropTypeBase ----------------------------------------------------------------
-template<class Derived, class Value, typename T>
+template <class Derived, class Value, typename T>
bool PropTypeBase<Derived, Value, T>::ConstraintsFromJson(
const base::DictionaryValue* value,
std::set<std::string>* processed_keys,
@@ -351,7 +351,7 @@
// NumericPropTypeBase ---------------------------------------------------------
-template<class Derived, class Value, typename T>
+template <class Derived, class Value, typename T>
bool NumericPropTypeBase<Derived, Value, T>::ConstraintsFromJson(
const base::DictionaryValue* value,
std::set<std::string>* processed_keys,
@@ -388,10 +388,9 @@
// StringPropType -------------------------------------------------------------
-bool StringPropType::ConstraintsFromJson(
- const base::DictionaryValue* value,
- std::set<std::string>* processed_keys,
- chromeos::ErrorPtr* error) {
+bool StringPropType::ConstraintsFromJson(const base::DictionaryValue* value,
+ std::set<std::string>* processed_keys,
+ chromeos::ErrorPtr* error) {
if (!Base::ConstraintsFromJson(value, processed_keys, error))
return false;
@@ -445,11 +444,11 @@
// ObjectPropType -------------------------------------------------------------
ObjectPropType::ObjectPropType()
- : object_schema_{ObjectSchema::Create(), false} {}
+ : object_schema_{ObjectSchema::Create(), false} {
+}
bool ObjectPropType::HasOverriddenAttributes() const {
- return PropType::HasOverriddenAttributes() ||
- !object_schema_.is_inherited;
+ return PropType::HasOverriddenAttributes() || !object_schema_.is_inherited;
}
std::unique_ptr<PropType> ObjectPropType::Clone() const {
@@ -462,7 +461,8 @@
}
std::unique_ptr<base::Value> ObjectPropType::ToJson(
- bool full_schema, chromeos::ErrorPtr* error) const {
+ bool full_schema,
+ chromeos::ErrorPtr* error) const {
std::unique_ptr<base::Value> value = PropType::ToJson(full_schema, error);
if (value) {
base::DictionaryValue* dict = nullptr;
@@ -577,11 +577,11 @@
// ArrayPropType -------------------------------------------------------------
-ArrayPropType::ArrayPropType() {}
+ArrayPropType::ArrayPropType() {
+}
bool ArrayPropType::HasOverriddenAttributes() const {
- return PropType::HasOverriddenAttributes() ||
- !item_type_.is_inherited;
+ return PropType::HasOverriddenAttributes() || !item_type_.is_inherited;
}
std::unique_ptr<PropType> ArrayPropType::Clone() const {
@@ -593,7 +593,8 @@
}
std::unique_ptr<base::Value> ArrayPropType::ToJson(
- bool full_schema, chromeos::ErrorPtr* error) const {
+ bool full_schema,
+ chromeos::ErrorPtr* error) const {
std::unique_ptr<base::Value> value = PropType::ToJson(full_schema, error);
if (value) {
base::DictionaryValue* dict = nullptr;
diff --git a/libweave/src/commands/prop_types.h b/libweave/src/commands/prop_types.h
index 1c31d04..156b556 100644
--- a/libweave/src/commands/prop_types.h
+++ b/libweave/src/commands/prop_types.h
@@ -38,8 +38,7 @@
// of particular type. Also it is expected to have at most one constraint
// of each type (e.g. it makes no sense to impose two "minimum" constraints
// onto a numeric parameter).
- using ConstraintMap = std::map<ConstraintType,
- std::unique_ptr<Constraint>>;
+ using ConstraintMap = std::map<ConstraintType, std::unique_ptr<Constraint>>;
PropType();
virtual ~PropType();
@@ -55,9 +54,7 @@
// is available.
const PropValue* GetDefaultValue() const { return default_.value.get(); }
// Gets the constraints specified for the parameter, if any.
- const ConstraintMap& GetConstraints() const {
- return constraints_;
- }
+ const ConstraintMap& GetConstraints() const { return constraints_; }
// Checks if any of the type attributes were overridden from the base
// schema definition. If this type does not inherit from a base schema,
// this method returns true.
@@ -87,7 +84,8 @@
// type as a factory class.
virtual std::unique_ptr<PropValue> CreateValue() const = 0;
virtual std::unique_ptr<PropValue> CreateValue(
- const chromeos::Any& val, chromeos::ErrorPtr* error) const = 0;
+ const chromeos::Any& val,
+ chromeos::ErrorPtr* error) const = 0;
// Converts an array of PropValue containing the values of the types described
// by this instance of PropType into an Any containing std::vector<T>, where
@@ -196,7 +194,7 @@
// Base class for all the derived concrete implementations of property
// type classes. Provides implementations for common methods of PropType base.
-template<class Derived, class Value, typename T>
+template <class Derived, class Value, typename T>
class PropTypeBase : public PropType {
public:
// Overrides from PropType.
@@ -209,7 +207,8 @@
}
std::unique_ptr<PropValue> CreateValue(
- const chromeos::Any& v, chromeos::ErrorPtr* error) const override {
+ const chromeos::Any& v,
+ chromeos::ErrorPtr* error) const override {
std::unique_ptr<PropValue> prop_value;
if (v.IsTypeCompatible<T>()) {
std::unique_ptr<Value> value{new Value{Clone()}};
@@ -255,7 +254,7 @@
};
// Helper base class for Int and Double parameter types.
-template<class Derived, class Value, typename T>
+template <class Derived, class Value, typename T>
class NumericPropTypeBase : public PropTypeBase<Derived, Value, T> {
public:
using Base = PropTypeBase<Derived, Value, T>;
@@ -268,10 +267,10 @@
void AddMinMaxConstraint(T min_value, T max_value) {
InheritableAttribute<T> min_attr(min_value, false);
InheritableAttribute<T> max_attr(max_value, false);
- this->AddConstraint(std::unique_ptr<ConstraintMin<T>>{
- new ConstraintMin<T>{min_attr}});
- this->AddConstraint(std::unique_ptr<ConstraintMax<T>>{
- new ConstraintMax<T>{max_attr}});
+ this->AddConstraint(
+ std::unique_ptr<ConstraintMin<T>>{new ConstraintMin<T>{min_attr}});
+ this->AddConstraint(
+ std::unique_ptr<ConstraintMax<T>>{new ConstraintMax<T>{max_attr}});
}
T GetMinValue() const {
auto mmc = static_cast<const ConstraintMin<T>*>(
@@ -354,7 +353,7 @@
chromeos::ErrorPtr* error) override;
chromeos::Any ConvertArrayToDBusVariant(
- const native_types::Array& source) const override;
+ const native_types::Array& source) const override;
bool ConvertDBusVariantToArray(const chromeos::Any& source,
native_types::Array* result,
diff --git a/libweave/src/commands/prop_values.cc b/libweave/src/commands/prop_values.cc
index 62a67be..28a2c43 100644
--- a/libweave/src/commands/prop_values.cc
+++ b/libweave/src/commands/prop_values.cc
@@ -9,11 +9,13 @@
namespace buffet {
PropValue::PropValue(std::unique_ptr<const PropType> type)
- : type_{std::move(type)} {}
+ : type_{std::move(type)} {
+}
-PropValue::PropValue(const PropType* type_ptr)
- : type_{type_ptr->Clone()} {}
+PropValue::PropValue(const PropType* type_ptr) : type_{type_ptr->Clone()} {
+}
-PropValue::~PropValue() {}
+PropValue::~PropValue() {
+}
} // namespace buffet
diff --git a/libweave/src/commands/prop_values.h b/libweave/src/commands/prop_values.h
index 5f46452..b178330 100644
--- a/libweave/src/commands/prop_values.h
+++ b/libweave/src/commands/prop_values.h
@@ -45,20 +45,29 @@
// native C++ data representation.
// The generic GetValueType<T>() is undefined, however particular
// type specializations return the appropriate ValueType.
-template<typename T> ValueType GetValueType(); // Undefined.
-template<>
-inline ValueType GetValueType<int>() { return ValueType::Int; }
-template<>
-inline ValueType GetValueType<double>() { return ValueType::Double; }
-template<>
-inline ValueType GetValueType<std::string>() { return ValueType::String; }
-template<>
-inline ValueType GetValueType<bool>() { return ValueType::Boolean; }
-template<>
+template <typename T>
+ValueType GetValueType(); // Undefined.
+template <>
+inline ValueType GetValueType<int>() {
+ return ValueType::Int;
+}
+template <>
+inline ValueType GetValueType<double>() {
+ return ValueType::Double;
+}
+template <>
+inline ValueType GetValueType<std::string>() {
+ return ValueType::String;
+}
+template <>
+inline ValueType GetValueType<bool>() {
+ return ValueType::Boolean;
+}
+template <>
inline ValueType GetValueType<native_types::Object>() {
return ValueType::Object;
}
-template<>
+template <>
inline ValueType GetValueType<native_types::Array>() {
return ValueType::Array;
}
@@ -127,7 +136,7 @@
};
// A helper template base class for implementing value classes.
-template<typename Derived, typename T>
+template <typename Derived, typename T>
class TypedValueBase : public PropValue {
public:
// To help refer to this base class from derived classes, define Base to
diff --git a/libweave/src/commands/schema_utils.cc b/libweave/src/commands/schema_utils.cc
index c46bcbb..c0067ab 100644
--- a/libweave/src/commands/schema_utils.cc
+++ b/libweave/src/commands/schema_utils.cc
@@ -31,12 +31,12 @@
// Template version of ReportJsonTypeMismatch that deduces the type of expected
// data from the value_out parameter passed to particular overload of
// TypedValueFromJson() function. Always returns false.
-template<typename T>
-bool ReportUnexpectedJson(const base::Value* value_in, T*,
+template <typename T>
+bool ReportUnexpectedJson(const base::Value* value_in,
+ T*,
chromeos::ErrorPtr* error) {
- ReportJsonTypeMismatch(value_in,
- PropType::GetTypeStringFromType(GetValueType<T>()),
- error);
+ ReportJsonTypeMismatch(
+ value_in, PropType::GetTypeStringFromType(GetValueType<T>()), error);
return false;
}
@@ -148,11 +148,10 @@
<< "Unable to get parameter";
if (!value->FromJson(param_value, error) ||
!pair.second->ValidateValue(value->GetValueAsAny(), error)) {
- chromeos::Error::AddToPrintf(error, FROM_HERE,
- errors::commands::kDomain,
- errors::commands::kInvalidPropValue,
- "Invalid value for property '%s'",
- pair.first.c_str());
+ chromeos::Error::AddToPrintf(
+ error, FROM_HERE, errors::commands::kDomain,
+ errors::commands::kInvalidPropValue,
+ "Invalid value for property '%s'", pair.first.c_str());
return false;
}
value_out->emplace_hint(value_out->end(), pair.first, std::move(value));
@@ -278,8 +277,8 @@
return value->GetValueAsAny();
}
-chromeos::VariantDictionary
-ObjectToDBusVariant(const native_types::Object& object) {
+chromeos::VariantDictionary ObjectToDBusVariant(
+ const native_types::Object& object) {
chromeos::VariantDictionary dict;
for (const auto& pair : object) {
// Since we are inserting the elements from native_types::Object which is
@@ -317,8 +316,7 @@
<< "An object type must have a schema defined for it";
native_types::Object obj;
if (!ObjectFromDBusVariant(type->GetObject()->GetObjectSchemaPtr(),
- value.Get<chromeos::VariantDictionary>(),
- &obj,
+ value.Get<chromeos::VariantDictionary>(), &obj,
error)) {
return result;
}
@@ -347,11 +345,10 @@
CHECK(prop_type) << "Value property type must be available";
auto prop_value = PropValueFromDBusVariant(prop_type, it->second, error);
if (!prop_value) {
- chromeos::Error::AddToPrintf(error, FROM_HERE,
- errors::commands::kDomain,
- errors::commands::kInvalidPropValue,
- "Invalid value for property '%s'",
- pair.first.c_str());
+ chromeos::Error::AddToPrintf(
+ error, FROM_HERE, errors::commands::kDomain,
+ errors::commands::kInvalidPropValue,
+ "Invalid value for property '%s'", pair.first.c_str());
return false;
}
obj->emplace_hint(obj->end(), pair.first, std::move(prop_value));
@@ -369,11 +366,10 @@
if (!object_schema->GetExtraPropertiesAllowed()) {
for (const auto& pair : dict) {
if (keys_processed.find(pair.first) == keys_processed.end()) {
- chromeos::Error::AddToPrintf(error, FROM_HERE,
- errors::commands::kDomain,
- errors::commands::kUnknownProperty,
- "Unrecognized property '%s'",
- pair.first.c_str());
+ chromeos::Error::AddToPrintf(
+ error, FROM_HERE, errors::commands::kDomain,
+ errors::commands::kUnknownProperty, "Unrecognized property '%s'",
+ pair.first.c_str());
return false;
}
}
diff --git a/libweave/src/commands/schema_utils.h b/libweave/src/commands/schema_utils.h
index 8d02477..d16374c 100644
--- a/libweave/src/commands/schema_utils.h
+++ b/libweave/src/commands/schema_utils.h
@@ -42,7 +42,7 @@
// The |value| still specifies the actual attribute values, whether it
// is inherited or overridden, while |is_inherited| can be used to identify
// if the attribute was inherited (true) or overridden (false).
-template<typename T>
+template <typename T>
class InheritableAttribute final {
public:
InheritableAttribute() = default;
@@ -69,7 +69,7 @@
chromeos::ErrorPtr* error);
std::unique_ptr<base::Value> TypedValueToJson(const native_types::Array& value,
chromeos::ErrorPtr* error);
-template<typename T>
+template <typename T>
std::unique_ptr<base::Value> TypedValueToJson(const std::vector<T>& values,
chromeos::ErrorPtr* error) {
std::unique_ptr<base::ListValue> list(new base::ListValue);
@@ -125,14 +125,14 @@
// which should work reliably for floating points also ("number" type).
// Compare exact types using ==.
-template<typename T>
+template <typename T>
inline typename std::enable_if<!std::is_floating_point<T>::value, bool>::type
CompareValue(const T& v1, const T& v2) {
return v1 == v2;
}
// Compare non-exact types (such as double) using precision margin (epsilon).
-template<typename T>
+template <typename T>
inline typename std::enable_if<std::is_floating_point<T>::value, bool>::type
CompareValue(const T& v1, const T& v2) {
return std::abs(v1 - v2) <= std::numeric_limits<T>::epsilon();
@@ -144,8 +144,8 @@
chromeos::Any PropValueToDBusVariant(const PropValue* value);
// Converts native_types::Object to chromeos::VariantDictionary
// with proper conversion of all nested properties.
-chromeos::VariantDictionary
-ObjectToDBusVariant(const native_types::Object& object);
+chromeos::VariantDictionary ObjectToDBusVariant(
+ const native_types::Object& object);
// Converts D-Bus variant to PropValue.
// Has special handling for Object types where chromeos::VariantDictionary
// is converted to native_types::Object.
diff --git a/libweave/src/commands/schema_utils_unittest.cc b/libweave/src/commands/schema_utils_unittest.cc
index 7e3debe..92194dd 100644
--- a/libweave/src/commands/schema_utils_unittest.cc
+++ b/libweave/src/commands/schema_utils_unittest.cc
@@ -177,9 +177,8 @@
&type, &value, nullptr));
native_types::Object value2;
value2.insert(std::make_pair("age", age_prop.CreateValue(20, nullptr)));
- value2.insert(std::make_pair("name",
- name_prop.CreateValue(std::string("Bob"),
- nullptr)));
+ value2.insert(std::make_pair(
+ "name", name_prop.CreateValue(std::string("Bob"), nullptr)));
EXPECT_EQ(value2, value);
chromeos::ErrorPtr error;
@@ -228,9 +227,11 @@
EXPECT_EQ("foo", PropValueToDBusVariant(prop_value.get()).Get<std::string>());
ObjectPropType obj_type;
- ASSERT_TRUE(obj_type.FromJson(CreateDictionaryValue(
- "{'properties':{'width':'integer','height':'integer'},"
- "'enum':[{'width':10,'height':20},{'width':100,'height':200}]}").get(),
+ ASSERT_TRUE(obj_type.FromJson(
+ CreateDictionaryValue(
+ "{'properties':{'width':'integer','height':'integer'},"
+ "'enum':[{'width':10,'height':20},{'width':100,'height':200}]}")
+ .get(),
nullptr, nullptr));
native_types::Object obj{
{"width", int_type.CreateValue(10, nullptr)},
@@ -290,7 +291,7 @@
TEST(CommandSchemaUtils, PropValueFromDBusVariant_Double) {
DoublePropType dbl_type;
ASSERT_TRUE(dbl_type.FromJson(CreateDictionaryValue("{'maximum':2.0}").get(),
- nullptr, nullptr));
+ nullptr, nullptr));
auto prop_value = PropValueFromDBusVariant(&dbl_type, 1.0, nullptr);
ASSERT_NE(nullptr, prop_value.get());
@@ -306,10 +307,10 @@
TEST(CommandSchemaUtils, PropValueFromDBusVariant_String) {
StringPropType str_type;
ASSERT_TRUE(str_type.FromJson(CreateDictionaryValue("{'minLength': 4}").get(),
- nullptr, nullptr));
+ nullptr, nullptr));
- auto prop_value = PropValueFromDBusVariant(&str_type, std::string{"blah"},
- nullptr);
+ auto prop_value =
+ PropValueFromDBusVariant(&str_type, std::string{"blah"}, nullptr);
ASSERT_NE(nullptr, prop_value.get());
EXPECT_EQ("blah", prop_value->GetValueAsAny().Get<std::string>());
@@ -322,14 +323,15 @@
TEST(CommandSchemaUtils, PropValueFromDBusVariant_Object) {
ObjectPropType obj_type;
- ASSERT_TRUE(obj_type.FromJson(CreateDictionaryValue(
- "{'properties':{'width':'integer','height':'integer'},"
- "'enum':[{'width':10,'height':20},{'width':100,'height':200}]}").get(),
+ ASSERT_TRUE(obj_type.FromJson(
+ CreateDictionaryValue(
+ "{'properties':{'width':'integer','height':'integer'},"
+ "'enum':[{'width':10,'height':20},{'width':100,'height':200}]}")
+ .get(),
nullptr, nullptr));
VariantDictionary obj{
- {"width", 100},
- {"height", 200},
+ {"width", 100}, {"height", 200},
};
auto prop_value = PropValueFromDBusVariant(&obj_type, obj, nullptr);
ASSERT_NE(nullptr, prop_value.get());
diff --git a/libweave/src/commands/unittest_utils.h b/libweave/src/commands/unittest_utils.h
index b514204..1674084 100644
--- a/libweave/src/commands/unittest_utils.h
+++ b/libweave/src/commands/unittest_utils.h
@@ -49,15 +49,15 @@
return make_prop_value<BooleanValue, bool>(value);
}
-inline std::unique_ptr<const StringValue>
-make_string_prop_value(const std::string& value) {
+inline std::unique_ptr<const StringValue> make_string_prop_value(
+ const std::string& value) {
return make_prop_value<StringValue, std::string>(value);
}
} // namespace unittests
} // namespace buffet
-#define EXPECT_JSON_EQ(expected, actual) \
+#define EXPECT_JSON_EQ(expected, actual) \
EXPECT_PRED2(buffet::unittests::IsEqualValue, \
*buffet::unittests::CreateValue(expected), actual)
diff --git a/libweave/src/device_registration_info.cc b/libweave/src/device_registration_info.cc
index 25ab205..f19b973 100644
--- a/libweave/src/device_registration_info.cc
+++ b/libweave/src/device_registration_info.cc
@@ -138,15 +138,14 @@
command_manager_->AddOnCommandDefChanged(
base::Bind(&DeviceRegistrationInfo::OnCommandDefsChanged,
weak_factory_.GetWeakPtr()));
- state_manager_->AddOnChangedCallback(
- base::Bind(&DeviceRegistrationInfo::OnStateChanged,
- weak_factory_.GetWeakPtr()));
+ state_manager_->AddOnChangedCallback(base::Bind(
+ &DeviceRegistrationInfo::OnStateChanged, weak_factory_.GetWeakPtr()));
}
DeviceRegistrationInfo::~DeviceRegistrationInfo() = default;
std::pair<std::string, std::string>
- DeviceRegistrationInfo::GetAuthorizationHeader() const {
+DeviceRegistrationInfo::GetAuthorizationHeader() const {
return BuildAuthHeader("Bearer", access_token_);
}
@@ -192,19 +191,20 @@
base::TimeDelta min_delay =
base::TimeDelta::FromSeconds(kMinStartDeviceRetryDelaySeconds);
base::TimeDelta retry_delay = later * 2;
- if (retry_delay > max_delay) { retry_delay = max_delay; }
- if (retry_delay < min_delay) { retry_delay = min_delay; }
+ if (retry_delay > max_delay) {
+ retry_delay = max_delay;
+ }
+ if (retry_delay < min_delay) {
+ retry_delay = min_delay;
+ }
task_runner_->PostDelayedTask(
- FROM_HERE,
- base::Bind(&DeviceRegistrationInfo::StartDevice,
- weak_factory_.GetWeakPtr(), nullptr,
- retry_delay),
+ FROM_HERE, base::Bind(&DeviceRegistrationInfo::StartDevice,
+ weak_factory_.GetWeakPtr(), nullptr, retry_delay),
later);
}
bool DeviceRegistrationInfo::HaveRegistrationCredentials() const {
- return !config_->refresh_token().empty() &&
- !config_->device_id().empty() &&
+ return !config_->refresh_token().empty() && !config_->device_id().empty() &&
!config_->robot_account().empty();
}
@@ -264,23 +264,22 @@
std::make_shared<CloudRequestErrorCallback>(error_callback);
auto on_refresh_error = [shared_error_callback](
- chromeos::http::RequestID id,
- const chromeos::Error* error) {
+ chromeos::http::RequestID id, const chromeos::Error* error) {
shared_error_callback->Run(error);
};
chromeos::http::FormFieldList form_data{
- {"refresh_token", config_->refresh_token()},
- {"client_id", config_->client_id()},
- {"client_secret", config_->client_secret()},
- {"grant_type", "refresh_token"},
+ {"refresh_token", config_->refresh_token()},
+ {"client_id", config_->client_id()},
+ {"client_secret", config_->client_secret()},
+ {"grant_type", "refresh_token"},
};
chromeos::http::PostFormData(
GetOAuthURL("token"), form_data, {}, transport_,
base::Bind(&DeviceRegistrationInfo::OnRefreshAccessTokenSuccess,
- weak_factory_.GetWeakPtr(),
- success_callback, shared_error_callback),
+ weak_factory_.GetWeakPtr(), success_callback,
+ shared_error_callback),
base::Bind(on_refresh_error));
}
@@ -298,8 +297,7 @@
int expires_in = 0;
if (!json->GetString("access_token", &access_token_) ||
- !json->GetInteger("expires_in", &expires_in) ||
- access_token_.empty() ||
+ !json->GetInteger("expires_in", &expires_in) || access_token_.empty() ||
expires_in <= 0) {
LOG(ERROR) << "Access token unavailable.";
chromeos::Error::AddTo(&error, FROM_HERE, kErrorDomainOAuth2,
@@ -308,8 +306,8 @@
error_callback->Run(error.get());
return;
}
- access_token_expiration_ = base::Time::Now() +
- base::TimeDelta::FromSeconds(expires_in);
+ access_token_expiration_ =
+ base::Time::Now() + base::TimeDelta::FromSeconds(expires_in);
LOG(INFO) << "Access token is refreshed for additional " << expires_in
<< " seconds.";
@@ -438,8 +436,8 @@
{{"key", config_->api_key()}});
std::unique_ptr<chromeos::http::Response> response =
chromeos::http::PatchJsonAndBlock(url, &req_json, {}, transport_, error);
- auto json_resp = chromeos::http::ParseJsonResponse(response.get(), nullptr,
- error);
+ auto json_resp =
+ chromeos::http::ParseJsonResponse(response.get(), nullptr, error);
if (!json_resp)
return std::string();
if (!response->IsSuccessful()) {
@@ -447,8 +445,8 @@
return std::string();
}
- url = GetServiceURL("registrationTickets/" + ticket_id +
- "/finalize?key=" + config_->api_key());
+ url = GetServiceURL("registrationTickets/" + ticket_id + "/finalize?key=" +
+ config_->api_key());
response = chromeos::http::SendRequestWithNoDataAndBlock(
chromeos::http::request_type::kPost, url, {}, transport_, error);
if (!response)
@@ -474,14 +472,15 @@
}
// Now get access_token and refresh_token
- response = chromeos::http::PostFormDataAndBlock(GetOAuthURL("token"), {
- {"code", auth_code},
- {"client_id", config_->client_id()},
- {"client_secret", config_->client_secret()},
- {"redirect_uri", "oob"},
- {"scope", "https://www.googleapis.com/auth/clouddevices"},
- {"grant_type", "authorization_code"}
- }, {}, transport_, error);
+ response = chromeos::http::PostFormDataAndBlock(
+ GetOAuthURL("token"),
+ {{"code", auth_code},
+ {"client_id", config_->client_id()},
+ {"client_secret", config_->client_secret()},
+ {"redirect_uri", "oob"},
+ {"scope", "https://www.googleapis.com/auth/clouddevices"},
+ {"grant_type", "authorization_code"}},
+ {}, transport_, error);
if (!response)
return std::string();
@@ -492,14 +491,14 @@
!json_resp->GetString("refresh_token", &refresh_token) ||
!json_resp->GetInteger("expires_in", &expires_in) ||
access_token_.empty() || refresh_token.empty() || expires_in <= 0) {
- chromeos::Error::AddTo(error, FROM_HERE,
- kErrorDomainGCD, "unexpected_response",
+ chromeos::Error::AddTo(error, FROM_HERE, kErrorDomainGCD,
+ "unexpected_response",
"Device access_token missing in response");
return std::string();
}
- access_token_expiration_ = base::Time::Now() +
- base::TimeDelta::FromSeconds(expires_in);
+ access_token_expiration_ =
+ base::Time::Now() + base::TimeDelta::FromSeconds(expires_in);
BuffetConfig::Transaction change{config_.get()};
change.set_device_id(device_id);
@@ -554,9 +553,8 @@
<< cloud_backoff_entry_->GetTimeUntilRelease()
<< " due to backoff policy";
task_runner_->PostDelayedTask(
- FROM_HERE,
- base::Bind(&DeviceRegistrationInfo::SendCloudRequest, AsWeakPtr(),
- data),
+ FROM_HERE, base::Bind(&DeviceRegistrationInfo::SendCloudRequest,
+ AsWeakPtr(), data),
cloud_backoff_entry_->GetTimeUntilRelease());
return;
}
@@ -602,8 +600,8 @@
}
chromeos::ErrorPtr error;
- auto json_resp = chromeos::http::ParseJsonResponse(response.get(), nullptr,
- &error);
+ auto json_resp =
+ chromeos::http::ParseJsonResponse(response.get(), nullptr, &error);
if (!json_resp) {
data->error_callback.Run(error.get());
return;
@@ -655,29 +653,25 @@
data->error_callback.Run(error);
}
-void DeviceRegistrationInfo::StartDevice(
- chromeos::ErrorPtr* error,
- const base::TimeDelta& retry_delay) {
+void DeviceRegistrationInfo::StartDevice(chromeos::ErrorPtr* error,
+ const base::TimeDelta& retry_delay) {
if (!VerifyRegistrationCredentials(error))
return;
- auto handle_start_device_failure_cb = base::Bind(
- &IgnoreCloudErrorWithCallback,
- base::Bind(&DeviceRegistrationInfo::ScheduleStartDevice,
- weak_factory_.GetWeakPtr(),
- retry_delay));
+ auto handle_start_device_failure_cb =
+ base::Bind(&IgnoreCloudErrorWithCallback,
+ base::Bind(&DeviceRegistrationInfo::ScheduleStartDevice,
+ weak_factory_.GetWeakPtr(), retry_delay));
// "Starting" a device just means that we:
// 1) push an updated device resource
// 2) fetch an initial set of outstanding commands
// 3) abort any commands that we've previously marked as "in progress"
// or as being in an error state; publish queued commands
- auto abort_commands_cb = base::Bind(
- &DeviceRegistrationInfo::ProcessInitialCommandList,
- weak_factory_.GetWeakPtr());
+ auto abort_commands_cb =
+ base::Bind(&DeviceRegistrationInfo::ProcessInitialCommandList,
+ weak_factory_.GetWeakPtr());
auto fetch_commands_cb = base::Bind(
- &DeviceRegistrationInfo::FetchCommands,
- weak_factory_.GetWeakPtr(),
- abort_commands_cb,
- handle_start_device_failure_cb);
+ &DeviceRegistrationInfo::FetchCommands, weak_factory_.GetWeakPtr(),
+ abort_commands_cb, handle_start_device_failure_cb);
UpdateDeviceResource(fetch_commands_cb, handle_start_device_failure_cb);
}
@@ -745,25 +739,21 @@
const base::DictionaryValue& command_patch,
const base::Closure& on_success,
const base::Closure& on_error) {
- DoCloudRequest(
- chromeos::http::request_type::kPatch,
- GetServiceURL("commands/" + command_id),
- &command_patch,
- base::Bind(&IgnoreCloudResultWithCallback, on_success),
- base::Bind(&IgnoreCloudErrorWithCallback, on_error));
+ DoCloudRequest(chromeos::http::request_type::kPatch,
+ GetServiceURL("commands/" + command_id), &command_patch,
+ base::Bind(&IgnoreCloudResultWithCallback, on_success),
+ base::Bind(&IgnoreCloudErrorWithCallback, on_error));
}
-void DeviceRegistrationInfo::NotifyCommandAborted(
- const std::string& command_id,
- chromeos::ErrorPtr error) {
+void DeviceRegistrationInfo::NotifyCommandAborted(const std::string& command_id,
+ chromeos::ErrorPtr error) {
base::DictionaryValue command_patch;
command_patch.SetString(commands::attributes::kCommand_State,
CommandInstance::kStatusAborted);
if (error) {
command_patch.SetString(commands::attributes::kCommand_ErrorCode,
- chromeos::string_utils::Join(":",
- error->GetDomain(),
- error->GetCode()));
+ chromeos::string_utils::Join(
+ ":", error->GetDomain(), error->GetCode()));
std::vector<std::string> messages;
const chromeos::Error* current_error = error.get();
while (current_error) {
@@ -773,22 +763,19 @@
command_patch.SetString(commands::attributes::kCommand_ErrorMessage,
chromeos::string_utils::Join(";", messages));
}
- UpdateCommand(command_id,
- command_patch,
- base::Bind(&base::DoNothing),
+ UpdateCommand(command_id, command_patch, base::Bind(&base::DoNothing),
base::Bind(&DeviceRegistrationInfo::RetryNotifyCommandAborted,
- weak_factory_.GetWeakPtr(),
- command_id, base::Passed(std::move(error))));
+ weak_factory_.GetWeakPtr(), command_id,
+ base::Passed(std::move(error))));
}
void DeviceRegistrationInfo::RetryNotifyCommandAborted(
const std::string& command_id,
chromeos::ErrorPtr error) {
task_runner_->PostDelayedTask(
- FROM_HERE,
- base::Bind(&DeviceRegistrationInfo::NotifyCommandAborted,
- weak_factory_.GetWeakPtr(),
- command_id, base::Passed(std::move(error))),
+ FROM_HERE, base::Bind(&DeviceRegistrationInfo::NotifyCommandAborted,
+ weak_factory_.GetWeakPtr(), command_id,
+ base::Passed(std::move(error))),
base::TimeDelta::FromSeconds(kAbortCommandRetryDelaySeconds));
}
@@ -822,9 +809,7 @@
}
DoCloudRequest(
- chromeos::http::request_type::kPut,
- GetDeviceURL(),
- device_resource.get(),
+ chromeos::http::request_type::kPut, GetDeviceURL(), device_resource.get(),
base::Bind(&DeviceRegistrationInfo::OnUpdateDeviceResourceSuccess,
AsWeakPtr()),
base::Bind(&DeviceRegistrationInfo::OnUpdateDeviceResourceError,
@@ -890,8 +875,7 @@
LOG(WARNING) << "Command with no state at " << *command;
continue;
}
- if (command_state == "error" &&
- command_state == "inProgress" &&
+ if (command_state == "error" && command_state == "inProgress" &&
command_state == "paused") {
// It's a limbo command, abort it.
std::string command_id;
@@ -903,11 +887,10 @@
std::unique_ptr<base::DictionaryValue> cmd_copy{command_dict->DeepCopy()};
cmd_copy->SetString("state", "aborted");
// TODO(wiley) We could consider handling this error case more gracefully.
- DoCloudRequest(
- chromeos::http::request_type::kPut,
- GetServiceURL("commands/" + command_id),
- cmd_copy.get(),
- base::Bind(&IgnoreCloudResult), base::Bind(&IgnoreCloudError));
+ DoCloudRequest(chromeos::http::request_type::kPut,
+ GetServiceURL("commands/" + command_id), cmd_copy.get(),
+ base::Bind(&IgnoreCloudResult),
+ base::Bind(&IgnoreCloudError));
} else {
// Normal command, publish it to local clients.
PublishCommand(*command_dict);
@@ -947,9 +930,11 @@
std::unique_ptr<chromeos::BackoffEntry> backoff_entry{
new chromeos::BackoffEntry{cloud_backoff_policy_.get()}};
std::unique_ptr<CommandProxyInterface> cloud_proxy{
- new CloudCommandProxy{command_instance.get(), this,
+ new CloudCommandProxy{command_instance.get(),
+ this,
state_manager_->GetStateChangeQueue(),
- std::move(backoff_entry), task_runner_}};
+ std::move(backoff_entry),
+ task_runner_}};
command_instance->AddProxy(std::move(cloud_proxy));
command_manager_->AddCommand(std::move(command_instance));
}
@@ -963,7 +948,7 @@
StateChangeQueueInterface::UpdateID update_id = 0;
std::vector<StateChange> state_changes;
std::tie(update_id, state_changes) =
- state_manager_->GetAndClearRecordedStateChanges();
+ state_manager_->GetAndClearRecordedStateChanges();
if (state_changes.empty())
return;
diff --git a/libweave/src/device_registration_info.h b/libweave/src/device_registration_info.h
index 56cae31..8c9cf80 100644
--- a/libweave/src/device_registration_info.h
+++ b/libweave/src/device_registration_info.h
@@ -106,14 +106,14 @@
// The base URL used to construct the full URL looks like this:
// https://www.googleapis.com/clouddevices/v1/devices/<device_id>/
std::string GetDeviceURL(
- const std::string& subpath = {},
- const chromeos::data_encoding::WebParamList& params = {}) const;
+ const std::string& subpath = {},
+ const chromeos::data_encoding::WebParamList& params = {}) const;
// Similar to GetServiceURL, GetOAuthURL() returns a URL of OAuth 2.0 server.
// The base URL used is https://accounts.google.com/o/oauth2/.
std::string GetOAuthURL(
- const std::string& subpath = {},
- const chromeos::data_encoding::WebParamList& params = {}) const;
+ const std::string& subpath = {},
+ const chromeos::data_encoding::WebParamList& params = {}) const;
// Starts GCD device if credentials available.
void Start();
@@ -196,7 +196,8 @@
// Parse the OAuth response, and sets registration status to
// kInvalidCredentials if our registration is no longer valid.
std::unique_ptr<base::DictionaryValue> ParseOAuthResponse(
- chromeos::http::Response* response, chromeos::ErrorPtr* error);
+ chromeos::http::Response* response,
+ chromeos::ErrorPtr* error);
// This attempts to open a notification channel. The channel needs to be
// restarted anytime the access_token is refreshed.
@@ -207,12 +208,11 @@
// and device removal. It is a recommended way to do cloud API
// requests.
// TODO(antonm): Consider moving into some other class.
- void DoCloudRequest(
- const std::string& method,
- const std::string& url,
- const base::DictionaryValue* body,
- const CloudRequestCallback& success_callback,
- const CloudRequestErrorCallback& error_callback);
+ void DoCloudRequest(const std::string& method,
+ const std::string& url,
+ const base::DictionaryValue* body,
+ const CloudRequestCallback& success_callback,
+ const CloudRequestErrorCallback& error_callback);
// Helper for DoCloudRequest().
struct CloudRequestData {
@@ -227,17 +227,14 @@
const std::shared_ptr<const CloudRequestData>& data,
chromeos::http::RequestID request_id,
std::unique_ptr<chromeos::http::Response> response);
- void OnCloudRequestError(
- const std::shared_ptr<const CloudRequestData>& data,
- chromeos::http::RequestID request_id,
- const chromeos::Error* error);
- void RetryCloudRequest(
- const std::shared_ptr<const CloudRequestData>& data);
+ void OnCloudRequestError(const std::shared_ptr<const CloudRequestData>& data,
+ chromeos::http::RequestID request_id,
+ const chromeos::Error* error);
+ void RetryCloudRequest(const std::shared_ptr<const CloudRequestData>& data);
void OnAccessTokenRefreshed(
const std::shared_ptr<const CloudRequestData>& data);
- void OnAccessTokenError(
- const std::shared_ptr<const CloudRequestData>& data,
- const chromeos::Error* error);
+ void OnAccessTokenError(const std::shared_ptr<const CloudRequestData>& data,
+ const chromeos::Error* error);
void UpdateDeviceResource(const base::Closure& on_success,
const CloudRequestErrorCallback& on_failure);
diff --git a/libweave/src/device_registration_info_unittest.cc b/libweave/src/device_registration_info_unittest.cc
index 43bec4d..ba5a4e4 100644
--- a/libweave/src/device_registration_info_unittest.cc
+++ b/libweave/src/device_registration_info_unittest.cc
@@ -32,30 +32,38 @@
namespace test_data {
-const char kServiceURL[] = "http://gcd.server.com/";
-const char kOAuthURL[] = "http://oauth.server.com/";
-const char kApiKey[] = "GOadRdTf9FERf0k4w6EFOof56fUJ3kFDdFL3d7f";
-const char kClientId[] = "123543821385-sfjkjshdkjhfk234sdfsdfkskd"
- "fkjh7f.apps.googleusercontent.com";
-const char kClientSecret[] = "5sdGdGlfolGlrFKfdFlgP6FG";
-const char kDeviceId[] = "4a7ea2d1-b331-1e1f-b206-e863c7635196";
-const char kClaimTicketId[] = "RTcUE";
-const char kAccessToken[] = "ya29.1.AADtN_V-dLUM-sVZ0qVjG9Dxm5NgdS9J"
- "Mx_JLUqhC9bED_YFjzHZtYt65ZzXCS35NMAeaVZ"
- "Dei530-w0yE2urpQ";
-const char kRefreshToken[] = "1/zQmxR6PKNvhcxf9SjXUrCjcmCrcqRKXctc6cp"
- "1nI-GQ";
-const char kRobotAccountAuthCode[] = "4/Mf_ujEhPejVhOq-OxW9F5cSOnWzx."
- "YgciVjTYGscRshQV0ieZDAqiTIjMigI";
-const char kRobotAccountEmail[] = "6ed0b3f54f9bd619b942f4ad2441c252@"
- "clouddevices.gserviceaccount.com";
-const char kUserAccountAuthCode[] = "2/sd_GD1TGFKpJOLJ34-0g5fK0fflp.GlT"
- "I0F5g7hNtFgj5HFGOf8FlGK9eflO";
-const char kUserAccessToken[] = "sd56.4.FGDjG_F-gFGF-dFG6gGOG9Dxm5NgdS9"
- "JMx_JLUqhC9bED_YFjLKjlkjLKJlkjLKjlKJea"
- "VZDei530-w0yE2urpQ";
-const char kUserRefreshToken[] = "1/zQLKjlKJlkLkLKjLkjLKjLkjLjLkjl0ftc6"
- "cp1nI-GQ";
+const char kServiceURL[] = "http://gcd.server.com/";
+const char kOAuthURL[] = "http://oauth.server.com/";
+const char kApiKey[] = "GOadRdTf9FERf0k4w6EFOof56fUJ3kFDdFL3d7f";
+const char kClientId[] =
+ "123543821385-sfjkjshdkjhfk234sdfsdfkskd"
+ "fkjh7f.apps.googleusercontent.com";
+const char kClientSecret[] = "5sdGdGlfolGlrFKfdFlgP6FG";
+const char kDeviceId[] = "4a7ea2d1-b331-1e1f-b206-e863c7635196";
+const char kClaimTicketId[] = "RTcUE";
+const char kAccessToken[] =
+ "ya29.1.AADtN_V-dLUM-sVZ0qVjG9Dxm5NgdS9J"
+ "Mx_JLUqhC9bED_YFjzHZtYt65ZzXCS35NMAeaVZ"
+ "Dei530-w0yE2urpQ";
+const char kRefreshToken[] =
+ "1/zQmxR6PKNvhcxf9SjXUrCjcmCrcqRKXctc6cp"
+ "1nI-GQ";
+const char kRobotAccountAuthCode[] =
+ "4/Mf_ujEhPejVhOq-OxW9F5cSOnWzx."
+ "YgciVjTYGscRshQV0ieZDAqiTIjMigI";
+const char kRobotAccountEmail[] =
+ "6ed0b3f54f9bd619b942f4ad2441c252@"
+ "clouddevices.gserviceaccount.com";
+const char kUserAccountAuthCode[] =
+ "2/sd_GD1TGFKpJOLJ34-0g5fK0fflp.GlT"
+ "I0F5g7hNtFgj5HFGOf8FlGK9eflO";
+const char kUserAccessToken[] =
+ "sd56.4.FGDjG_F-gFGF-dFG6gGOG9Dxm5NgdS9"
+ "JMx_JLUqhC9bED_YFjLKjlkjLKJlkjLKjlKJea"
+ "VZDei530-w0yE2urpQ";
+const char kUserRefreshToken[] =
+ "1/zQLKjlKJlkLkLKjLkjLKjLkjLjLkjl0ftc6"
+ "cp1nI-GQ";
} // namespace test_data
// Add the test device registration information.
@@ -107,8 +115,7 @@
response->ReplyJson(chromeos::http::status_code::Ok, &json);
}
-void OAuth2HandlerFail(const ServerRequest& request,
- ServerResponse* response) {
+void OAuth2HandlerFail(const ServerRequest& request, ServerResponse* response) {
base::DictionaryValue json;
EXPECT_EQ("refresh_token", request.GetFormField("grant_type"));
EXPECT_EQ(test_data::kRefreshToken, request.GetFormField("refresh_token"));
@@ -134,12 +141,13 @@
auth += test_data::kAccessToken;
EXPECT_EQ(auth,
request.GetHeader(chromeos::http::request_header::kAuthorization));
- response->ReplyJson(chromeos::http::status_code::Ok, {
- {"channel.supportedType", "xmpp"},
- {"deviceKind", "vendor"},
- {"id", test_data::kDeviceId},
- {"kind", "clouddevices#device"},
- });
+ response->ReplyJson(chromeos::http::status_code::Ok,
+ {
+ {"channel.supportedType", "xmpp"},
+ {"deviceKind", "vendor"},
+ {"id", test_data::kDeviceId},
+ {"kind", "clouddevices#device"},
+ });
}
void FinalizeTicketHandler(const ServerRequest& request,
@@ -147,17 +155,19 @@
EXPECT_EQ(test_data::kApiKey, request.GetFormField("key"));
EXPECT_TRUE(request.GetData().empty());
- response->ReplyJson(chromeos::http::status_code::Ok, {
- {"id", test_data::kClaimTicketId},
- {"kind", "clouddevices#registrationTicket"},
- {"oauthClientId", test_data::kClientId},
- {"userEmail", "user@email.com"},
- {"deviceDraft.id", test_data::kDeviceId},
- {"deviceDraft.kind", "clouddevices#device"},
- {"deviceDraft.channel.supportedType", "xmpp"},
- {"robotAccountEmail", test_data::kRobotAccountEmail},
- {"robotAccountAuthorizationCode", test_data::kRobotAccountAuthCode},
- });
+ response->ReplyJson(
+ chromeos::http::status_code::Ok,
+ {
+ {"id", test_data::kClaimTicketId},
+ {"kind", "clouddevices#registrationTicket"},
+ {"oauthClientId", test_data::kClientId},
+ {"userEmail", "user@email.com"},
+ {"deviceDraft.id", test_data::kDeviceId},
+ {"deviceDraft.kind", "clouddevices#device"},
+ {"deviceDraft.channel.supportedType", "xmpp"},
+ {"robotAccountEmail", test_data::kRobotAccountEmail},
+ {"robotAccountAuthorizationCode", test_data::kRobotAccountAuthCode},
+ });
}
} // anonymous namespace
@@ -174,9 +184,13 @@
std::unique_ptr<BuffetConfig> config{new BuffetConfig{std::move(storage)}};
config_ = config.get();
- dev_reg_.reset(new DeviceRegistrationInfo{command_manager_, state_manager_,
- std::move(config), transport_,
- nullptr, true, nullptr});
+ dev_reg_.reset(new DeviceRegistrationInfo{command_manager_,
+ state_manager_,
+ std::move(config),
+ transport_,
+ nullptr,
+ true,
+ nullptr});
ReloadConfig();
}
@@ -186,8 +200,8 @@
config_store.SetString("client_id", test_data::kClientId);
config_store.SetString("client_secret", test_data::kClientSecret);
config_store.SetString("api_key", test_data::kApiKey);
- config_store.SetString("device_kind", "vendor");
- config_store.SetString("name", "Coffee Pot");
+ config_store.SetString("device_kind", "vendor");
+ config_store.SetString("name", "Coffee Pot");
config_store.SetString("description", "Easy to clean");
config_store.SetString("location", "Kitchen");
config_store.SetString("local_anonymous_access_role", "viewer");
@@ -222,9 +236,7 @@
return succeeded;
}
- void SetAccessToken() {
- dev_reg_->access_token_ = test_data::kAccessToken;
- }
+ void SetAccessToken() { dev_reg_->access_token_ = test_data::kAccessToken; }
RegistrationStatus GetRegistrationStatus() const {
return dev_reg_->registration_status_;
@@ -248,14 +260,14 @@
EXPECT_EQ(url, dev_reg_->GetServiceURL("registrationTickets"));
url += "?key=";
url += test_data::kApiKey;
- EXPECT_EQ(url, dev_reg_->GetServiceURL("registrationTickets", {
- {"key", test_data::kApiKey}
- }));
+ EXPECT_EQ(url, dev_reg_->GetServiceURL("registrationTickets",
+ {{"key", test_data::kApiKey}}));
url += "&restart=true";
- EXPECT_EQ(url, dev_reg_->GetServiceURL("registrationTickets", {
- {"key", test_data::kApiKey},
- {"restart", "true"},
- }));
+ EXPECT_EQ(url, dev_reg_->GetServiceURL(
+ "registrationTickets",
+ {
+ {"key", test_data::kApiKey}, {"restart", "true"},
+ }));
}
TEST_F(DeviceRegistrationInfoTest, GetOAuthURL) {
@@ -266,12 +278,12 @@
url += "response_type=code&";
url += "client_id=";
url += test_data::kClientId;
- EXPECT_EQ(url, dev_reg_->GetOAuthURL("auth", {
- {"scope", "https://www.googleapis.com/auth/clouddevices"},
- {"redirect_uri", "urn:ietf:wg:oauth:2.0:oob"},
- {"response_type", "code"},
- {"client_id", test_data::kClientId}
- }));
+ EXPECT_EQ(url, dev_reg_->GetOAuthURL(
+ "auth",
+ {{"scope", "https://www.googleapis.com/auth/clouddevices"},
+ {"redirect_uri", "urn:ietf:wg:oauth:2.0:oob"},
+ {"response_type", "code"},
+ {"client_id", test_data::kClientId}}));
}
TEST_F(DeviceRegistrationInfoTest, HaveRegistrationCredentials) {
@@ -339,8 +351,8 @@
base::RunLoop run_loop;
bool succeeded = false;
- auto on_success =
- [&run_loop, &succeeded, this](const base::DictionaryValue& info) {
+ auto on_success = [&run_loop, &succeeded, this](
+ const base::DictionaryValue& info) {
EXPECT_EQ(1, transport_->GetRequestCount());
std::string id;
EXPECT_TRUE(info.GetString("id", &id));
@@ -456,13 +468,12 @@
})");
EXPECT_TRUE(command_manager_->LoadCommands(*json_cmds, "", nullptr));
- transport_->AddHandler(dev_reg_->GetServiceURL(
- std::string("registrationTickets/") + test_data::kClaimTicketId),
- chromeos::http::request_type::kPatch,
- base::Bind(update_ticket));
- std::string ticket_url =
- dev_reg_->GetServiceURL("registrationTickets/" +
- std::string(test_data::kClaimTicketId));
+ transport_->AddHandler(
+ dev_reg_->GetServiceURL(std::string("registrationTickets/") +
+ test_data::kClaimTicketId),
+ chromeos::http::request_type::kPatch, base::Bind(update_ticket));
+ std::string ticket_url = dev_reg_->GetServiceURL(
+ "registrationTickets/" + std::string(test_data::kClaimTicketId));
transport_->AddHandler(ticket_url + "/finalize",
chromeos::http::request_type::kPost,
base::Bind(FinalizeTicketHandler));
@@ -534,8 +545,7 @@
ASSERT_NE(nullptr, command);
StringPropType string_type;
native_types::Object results{
- {"status", string_type.CreateValue(std::string{"Ok"}, nullptr)}
- };
+ {"status", string_type.CreateValue(std::string{"Ok"}, nullptr)}};
// UpdateCommand when setting command results.
auto update_command_results = [](const ServerRequest& request,
@@ -546,8 +556,7 @@
chromeos::http::FormFieldList{});
};
- transport_->AddHandler(command_url,
- chromeos::http::request_type::kPatch,
+ transport_->AddHandler(command_url, chromeos::http::request_type::kPatch,
base::Bind(update_command_results));
command->SetResults(results);
@@ -567,8 +576,7 @@
chromeos::http::FormFieldList{});
};
- transport_->AddHandler(command_url,
- chromeos::http::request_type::kPatch,
+ transport_->AddHandler(command_url, chromeos::http::request_type::kPatch,
base::Bind(update_command_progress));
native_types::Object progress{
@@ -584,12 +592,10 @@
chromeos::http::FormFieldList{});
};
- transport_->AddHandler(command_url,
- chromeos::http::request_type::kPatch,
+ transport_->AddHandler(command_url, chromeos::http::request_type::kPatch,
base::Bind(update_command_state));
command->Cancel();
}
-
} // namespace buffet
diff --git a/libweave/src/notification/notification_parser.cc b/libweave/src/notification/notification_parser.cc
index 4663050..1fe8878 100644
--- a/libweave/src/notification/notification_parser.cc
+++ b/libweave/src/notification/notification_parser.cc
@@ -67,5 +67,4 @@
return true;
}
-
} // namespace buffet
diff --git a/libweave/src/notification/pull_channel.cc b/libweave/src/notification/pull_channel.cc
index 249c1e9..69f20d1 100644
--- a/libweave/src/notification/pull_channel.cc
+++ b/libweave/src/notification/pull_channel.cc
@@ -13,8 +13,7 @@
PullChannel::PullChannel(
base::TimeDelta pull_interval,
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)
- : pull_interval_{pull_interval},
- timer_{true, true} {
+ : pull_interval_{pull_interval}, timer_{true, true} {
timer_.SetTaskRunner(task_runner);
}
@@ -22,7 +21,9 @@
return "pull";
}
-bool PullChannel::IsConnected() const { return true; }
+bool PullChannel::IsConnected() const {
+ return true;
+}
void PullChannel::AddChannelParameters(base::DictionaryValue* channel_json) {
// No extra parameters needed for "Pull" channel.
@@ -31,9 +32,9 @@
void PullChannel::Start(NotificationDelegate* delegate) {
CHECK(delegate);
delegate_ = delegate;
- timer_.Start(FROM_HERE, pull_interval_,
- base::Bind(&PullChannel::OnTimer,
- weak_ptr_factory_.GetWeakPtr()));
+ timer_.Start(
+ FROM_HERE, pull_interval_,
+ base::Bind(&PullChannel::OnTimer, weak_ptr_factory_.GetWeakPtr()));
}
void PullChannel::Stop() {
diff --git a/libweave/src/notification/xml_node.cc b/libweave/src/notification/xml_node.cc
index 692710e..040d8eb 100644
--- a/libweave/src/notification/xml_node.cc
+++ b/libweave/src/notification/xml_node.cc
@@ -11,7 +11,8 @@
XmlNode::XmlNode(const std::string& name,
std::map<std::string, std::string> attributes)
- : name_{name}, attributes_{std::move(attributes)} {}
+ : name_{name}, attributes_{std::move(attributes)} {
+}
const std::string& XmlNode::name() const {
return name_;
diff --git a/libweave/src/notification/xml_node.h b/libweave/src/notification/xml_node.h
index 3b68a13..16c3b21 100644
--- a/libweave/src/notification/xml_node.h
+++ b/libweave/src/notification/xml_node.h
@@ -108,7 +108,6 @@
bool recursive,
std::vector<const XmlNode*>* children) const;
-
const XmlNode* parent_{nullptr}; // Weak pointer to the parent node, if any.
std::string name_;
std::string text_;
@@ -121,4 +120,3 @@
} // namespace buffet
#endif // LIBWEAVE_SRC_NOTIFICATION_XML_NODE_H_
-
diff --git a/libweave/src/notification/xml_node_unittest.cc b/libweave/src/notification/xml_node_unittest.cc
index bd26364..6cbc9ec 100644
--- a/libweave/src/notification/xml_node_unittest.cc
+++ b/libweave/src/notification/xml_node_unittest.cc
@@ -42,14 +42,12 @@
class XmlNodeTest : public testing::Test {
public:
void SetUp() override {
- node_.reset(new XmlNode{"test_node",
- {{"attr1", "val1"}, {"attr2", "val2"}}});
+ node_.reset(
+ new XmlNode{"test_node", {{"attr1", "val1"}, {"attr2", "val2"}}});
}
// Accessor helpers for private members of XmlNode.
- static const XmlNode* GetParent(const XmlNode& node) {
- return node.parent_;
- }
+ static const XmlNode* GetParent(const XmlNode& node) { return node.parent_; }
static void SetText(XmlNode* node, const std::string& text) {
node->SetText(text);
@@ -99,10 +97,8 @@
}
TEST_F(XmlNodeTest, Attributes) {
- const std::map<std::string, std::string> expected_attrs{
- {"attr1", "val1"},
- {"attr2", "val2"}
- };
+ const std::map<std::string, std::string> expected_attrs{{"attr1", "val1"},
+ {"attr2", "val2"}};
EXPECT_EQ(expected_attrs, node_->attributes());
std::string attr = "bar";
EXPECT_FALSE(node_->GetAttribute("foo", &attr));
diff --git a/libweave/src/notification/xmpp_channel.cc b/libweave/src/notification/xmpp_channel.cc
index 6c0a0e7..542ad61 100644
--- a/libweave/src/notification/xmpp_channel.cc
+++ b/libweave/src/notification/xmpp_channel.cc
@@ -24,24 +24,24 @@
std::string BuildXmppStartStreamCommand() {
return "<stream:stream to='clouddevices.gserviceaccount.com' "
- "xmlns:stream='http://etherx.jabber.org/streams' "
- "xml:lang='*' version='1.0' xmlns='jabber:client'>";
+ "xmlns:stream='http://etherx.jabber.org/streams' "
+ "xml:lang='*' version='1.0' xmlns='jabber:client'>";
}
-std::string BuildXmppAuthenticateCommand(
- const std::string& account, const std::string& token) {
+std::string BuildXmppAuthenticateCommand(const std::string& account,
+ const std::string& token) {
chromeos::Blob credentials;
credentials.push_back(0);
credentials.insert(credentials.end(), account.begin(), account.end());
credentials.push_back(0);
credentials.insert(credentials.end(), token.begin(), token.end());
- std::string msg = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' "
+ std::string msg =
+ "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' "
"mechanism='X-OAUTH2' auth:service='oauth2' "
"auth:allow-non-google-login='true' "
"auth:client-uses-full-bind-result='true' "
"xmlns:auth='http://www.google.com/talk/protocol/auth'>" +
- chromeos::data_encoding::Base64Encode(credentials) +
- "</auth>";
+ chromeos::data_encoding::Base64Encode(credentials) + "</auth>";
return msg;
}
@@ -49,29 +49,29 @@
// Note: In order to ensure a minimum of 20 seconds between server errors,
// we have a 30s +- 10s (33%) jitter initial backoff.
const chromeos::BackoffEntry::Policy kDefaultBackoffPolicy = {
- // Number of initial errors (in sequence) to ignore before applying
- // exponential back-off rules.
- 0,
+ // Number of initial errors (in sequence) to ignore before applying
+ // exponential back-off rules.
+ 0,
- // Initial delay for exponential back-off in ms.
- 30 * 1000, // 30 seconds.
+ // Initial delay for exponential back-off in ms.
+ 30 * 1000, // 30 seconds.
- // Factor by which the waiting time will be multiplied.
- 2,
+ // Factor by which the waiting time will be multiplied.
+ 2,
- // Fuzzing percentage. ex: 10% will spread requests randomly
- // between 90%-100% of the calculated time.
- 0.33, // 33%.
+ // Fuzzing percentage. ex: 10% will spread requests randomly
+ // between 90%-100% of the calculated time.
+ 0.33, // 33%.
- // Maximum amount of time we are willing to delay our request in ms.
- 10 * 60 * 1000, // 10 minutes.
+ // Maximum amount of time we are willing to delay our request in ms.
+ 10 * 60 * 1000, // 10 minutes.
- // Time to keep an entry from being discarded even when it
- // has no significant state, -1 to never discard.
- -1,
+ // Time to keep an entry from being discarded even when it
+ // has no significant state, -1 to never discard.
+ -1,
- // Don't use initial delay unless the last request was an error.
- false,
+ // Don't use initial delay unless the last request was an error.
+ false,
};
const char kDefaultXmppHost[] = "talk.google.com";
@@ -251,8 +251,9 @@
return;
}
state_ = XmppState::kSubscribeStarted;
- std::string body = "<subscribe xmlns='google:push'>"
- "<item channel='cloud_devices' from=''/></subscribe>";
+ std::string body =
+ "<subscribe xmlns='google:push'>"
+ "<item channel='cloud_devices' from=''/></subscribe>";
iq_stanza_handler_->SendRequest(
"set", "", account_, body,
base::Bind(&XmppChannel::OnSubscribed, task_ptr_factory_.GetWeakPtr()),
@@ -370,14 +371,15 @@
Restart();
}
-void XmppChannel::Connect(const std::string& host, uint16_t port,
+void XmppChannel::Connect(const std::string& host,
+ uint16_t port,
const base::Closure& callback) {
state_ = XmppState::kConnecting;
LOG(INFO) << "Starting XMPP connection to " << host << ":" << port;
int socket_fd = ConnectSocket(host, port);
if (socket_fd >= 0) {
raw_socket_ =
- chromeos::FileStream::FromFileDescriptor(socket_fd, true, nullptr);
+ chromeos::FileStream::FromFileDescriptor(socket_fd, true, nullptr);
if (!raw_socket_) {
close(socket_fd);
socket_fd = -1;
diff --git a/libweave/src/notification/xmpp_channel.h b/libweave/src/notification/xmpp_channel.h
index ab09418..9402b65 100644
--- a/libweave/src/notification/xmpp_channel.h
+++ b/libweave/src/notification/xmpp_channel.h
@@ -77,7 +77,8 @@
protected:
// These methods are internal helpers that can be overloaded by unit tests
// to help provide unit-test-specific functionality.
- virtual void Connect(const std::string& host, uint16_t port,
+ virtual void Connect(const std::string& host,
+ uint16_t port,
const base::Closure& callback);
virtual void SchedulePing(base::TimeDelta interval, base::TimeDelta timeout);
void ScheduleRegularPing();
@@ -170,4 +171,3 @@
} // namespace buffet
#endif // LIBWEAVE_SRC_NOTIFICATION_XMPP_CHANNEL_H_
-
diff --git a/libweave/src/notification/xmpp_channel_unittest.cc b/libweave/src/notification/xmpp_channel_unittest.cc
index 7f5acc0..5f401ba 100644
--- a/libweave/src/notification/xmpp_channel_unittest.cc
+++ b/libweave/src/notification/xmpp_channel_unittest.cc
@@ -51,8 +51,7 @@
"<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\">"
"<jid>110cc78f78d7032cc7bf2c6e14c1fa7d@clouddevices.gserviceaccount.com"
"/19853128</jid></bind></iq>";
-constexpr char kSessionResponse[] =
- "<iq type=\"result\" id=\"2\"/>";
+constexpr char kSessionResponse[] = "<iq type=\"result\" id=\"2\"/>";
constexpr char kSubscribedResponse[] =
"<iq to=\""
"110cc78f78d7032cc7bf2c6e14c1fa7d@clouddevices.gserviceaccount.com/"
@@ -87,9 +86,10 @@
// TaskRunner::PostDelayedTask and verify the delays.
class TestTaskRunner : public base::SingleThreadTaskRunner {
public:
- MOCK_METHOD3(PostDelayedTask, bool(const tracked_objects::Location&,
- const base::Closure&,
- base::TimeDelta));
+ MOCK_METHOD3(PostDelayedTask,
+ bool(const tracked_objects::Location&,
+ const base::Closure&,
+ base::TimeDelta));
MOCK_METHOD3(PostNonNestableDelayedTask,
bool(const tracked_objects::Location&,
const base::Closure&,
@@ -104,13 +104,15 @@
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
base::Clock* clock)
: XmppChannel{kAccountName, kAccessToken, task_runner, nullptr},
- fake_stream_{chromeos::Stream::AccessMode::READ_WRITE, task_runner,
+ fake_stream_{chromeos::Stream::AccessMode::READ_WRITE,
+ task_runner,
clock} {}
XmppState state() const { return state_; }
void set_state(XmppState state) { state_ = state; }
- void Connect(const std::string& host, uint16_t port,
+ void Connect(const std::string& host,
+ uint16_t port,
const base::Closure& callback) override {
set_state(XmppState::kConnecting);
stream_ = &fake_stream_;
@@ -168,9 +170,7 @@
}
}
- void SetIgnoreDelayedTasks(bool ignore) {
- ignore_delayed_tasks_ = true;
- }
+ void SetIgnoreDelayedTasks(bool ignore) { ignore_delayed_tasks_ = true; }
std::unique_ptr<FakeXmppChannel> xmpp_client_;
base::SimpleTestClock clock_;
@@ -194,8 +194,7 @@
TEST_F(XmppChannelTest, HandleTLSCompleted) {
StartWithState(XmppChannel::XmppState::kTlsCompleted);
- xmpp_client_->fake_stream_.AddReadPacketString(
- {}, kTlsStreamResponse);
+ xmpp_client_->fake_stream_.AddReadPacketString({}, kTlsStreamResponse);
xmpp_client_->fake_stream_.ExpectWritePacketString({},
kAuthenticationMessage);
RunTasks(4);
@@ -215,8 +214,8 @@
TEST_F(XmppChannelTest, HandleAuthenticationFailedResponse) {
StartWithState(XmppChannel::XmppState::kAuthenticationStarted);
- xmpp_client_->fake_stream_.AddReadPacketString(
- {}, kAuthenticationFailedResponse);
+ xmpp_client_->fake_stream_.AddReadPacketString({},
+ kAuthenticationFailedResponse);
RunTasks(3);
EXPECT_EQ(XmppChannel::XmppState::kAuthenticationFailed,
xmpp_client_->state());
@@ -228,28 +227,26 @@
xmpp_client_->fake_stream_.AddReadPacketString({}, kRestartStreamResponse);
xmpp_client_->fake_stream_.ExpectWritePacketString({}, kBindMessage);
RunTasks(3);
- EXPECT_EQ(XmppChannel::XmppState::kBindSent,
- xmpp_client_->state());
+ EXPECT_EQ(XmppChannel::XmppState::kBindSent, xmpp_client_->state());
EXPECT_TRUE(xmpp_client_->jid().empty());
xmpp_client_->fake_stream_.AddReadPacketString({}, kBindResponse);
xmpp_client_->fake_stream_.ExpectWritePacketString({}, kSessionMessage);
RunTasks(9);
- EXPECT_EQ(XmppChannel::XmppState::kSessionStarted,
- xmpp_client_->state());
- EXPECT_EQ("110cc78f78d7032cc7bf2c6e14c1fa7d@clouddevices.gserviceaccount.com"
- "/19853128", xmpp_client_->jid());
+ EXPECT_EQ(XmppChannel::XmppState::kSessionStarted, xmpp_client_->state());
+ EXPECT_EQ(
+ "110cc78f78d7032cc7bf2c6e14c1fa7d@clouddevices.gserviceaccount.com"
+ "/19853128",
+ xmpp_client_->jid());
xmpp_client_->fake_stream_.AddReadPacketString({}, kSessionResponse);
xmpp_client_->fake_stream_.ExpectWritePacketString({}, kSubscribeMessage);
RunTasks(4);
- EXPECT_EQ(XmppChannel::XmppState::kSubscribeStarted,
- xmpp_client_->state());
+ EXPECT_EQ(XmppChannel::XmppState::kSubscribeStarted, xmpp_client_->state());
xmpp_client_->fake_stream_.AddReadPacketString({}, kSubscribedResponse);
RunTasks(5);
- EXPECT_EQ(XmppChannel::XmppState::kSubscribed,
- xmpp_client_->state());
+ EXPECT_EQ(XmppChannel::XmppState::kSubscribed, xmpp_client_->state());
}
} // namespace buffet
diff --git a/libweave/src/notification/xmpp_iq_stanza_handler.cc b/libweave/src/notification/xmpp_iq_stanza_handler.cc
index 95d3cc0..75529fa 100644
--- a/libweave/src/notification/xmpp_iq_stanza_handler.cc
+++ b/libweave/src/notification/xmpp_iq_stanza_handler.cc
@@ -39,9 +39,9 @@
<< "Source address contains invalid XML characters";
base::StringAppendF(&from_attr, " from='%s'", from.c_str());
}
- return base::StringPrintf("<iq id='%s' type='%s'%s%s>%s</iq>",
- id.c_str(), type.c_str(), from_attr.c_str(),
- to_attr.c_str(), body.c_str());
+ return base::StringPrintf("<iq id='%s' type='%s'%s%s>%s</iq>", id.c_str(),
+ type.c_str(), from_attr.c_str(), to_attr.c_str(),
+ body.c_str());
}
} // anonymous namespace
@@ -49,15 +49,15 @@
IqStanzaHandler::IqStanzaHandler(
XmppChannelInterface* xmpp_channel,
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)
- : xmpp_channel_{xmpp_channel}, task_runner_{task_runner} {}
+ : xmpp_channel_{xmpp_channel}, task_runner_{task_runner} {
+}
-void IqStanzaHandler::SendRequest(
- const std::string& type,
- const std::string& from,
- const std::string& to,
- const std::string& body,
- const ResponseCallback& response_callback,
- const TimeoutCallback& timeout_callback) {
+void IqStanzaHandler::SendRequest(const std::string& type,
+ const std::string& from,
+ const std::string& to,
+ const std::string& body,
+ const ResponseCallback& response_callback,
+ const TimeoutCallback& timeout_callback) {
return SendRequestWithCustomTimeout(
type, from, to, body,
base::TimeDelta::FromSeconds(kTimeoutIntervalSeconds), response_callback,
@@ -83,8 +83,8 @@
timeout);
}
- std::string message = BuildIqStanza(std::to_string(last_request_id_),
- type, to, from, body);
+ std::string message =
+ BuildIqStanza(std::to_string(last_request_id_), type, to, from, body);
xmpp_channel_->SendMessage(message);
}
@@ -112,8 +112,7 @@
auto p = requests_.find(id);
if (p != requests_.end()) {
task_runner_->PostTask(
- FROM_HERE,
- base::Bind(p->second, base::Passed(std::move(stanza))));
+ FROM_HERE, base::Bind(p->second, base::Passed(std::move(stanza))));
requests_.erase(p);
}
} else {
@@ -123,10 +122,9 @@
"<error type='modify'>"
"<feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>"
"</error>";
- std::string message = BuildIqStanza(id_str, "error",
- stanza->GetAttributeOrEmpty("from"),
- stanza->GetAttributeOrEmpty("to"),
- error_body);
+ std::string message =
+ BuildIqStanza(id_str, "error", stanza->GetAttributeOrEmpty("from"),
+ stanza->GetAttributeOrEmpty("to"), error_body);
xmpp_channel_->SendMessage(message);
}
return true;
diff --git a/libweave/src/notification/xmpp_iq_stanza_handler.h b/libweave/src/notification/xmpp_iq_stanza_handler.h
index 4e80900..af19395 100644
--- a/libweave/src/notification/xmpp_iq_stanza_handler.h
+++ b/libweave/src/notification/xmpp_iq_stanza_handler.h
@@ -22,8 +22,7 @@
class IqStanzaHandler {
public:
- using ResponseCallback =
- base::Callback<void(std::unique_ptr<XmlNode>)>;
+ using ResponseCallback = base::Callback<void(std::unique_ptr<XmlNode>)>;
using TimeoutCallback = base::Closure;
IqStanzaHandler(
@@ -79,4 +78,3 @@
} // namespace buffet
#endif // LIBWEAVE_SRC_NOTIFICATION_XMPP_IQ_STANZA_HANDLER_H_
-
diff --git a/libweave/src/notification/xmpp_iq_stanza_handler_unittest.cc b/libweave/src/notification/xmpp_iq_stanza_handler_unittest.cc
index 36cf691..a953252 100644
--- a/libweave/src/notification/xmpp_iq_stanza_handler_unittest.cc
+++ b/libweave/src/notification/xmpp_iq_stanza_handler_unittest.cc
@@ -28,9 +28,10 @@
public:
TestTaskRunner() = default;
- MOCK_METHOD3(PostDelayedTask, bool(const tracked_objects::Location&,
- const base::Closure&,
- base::TimeDelta));
+ MOCK_METHOD3(PostDelayedTask,
+ bool(const tracked_objects::Location&,
+ const base::Closure&,
+ base::TimeDelta));
MOCK_METHOD3(PostNonNestableDelayedTask,
bool(const tracked_objects::Location&,
const base::Closure&,
@@ -163,7 +164,8 @@
TEST_F(IqStanzaHandlerTest, SequentialResponses) {
EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, _))
- .Times(2).WillRepeatedly(Return(true));
+ .Times(2)
+ .WillRepeatedly(Return(true));
EXPECT_CALL(mock_xmpp_channel_, SendMessage(_)).Times(2);
iq_stanza_handler_->SendRequest("set", "", "", "<body/>",
@@ -172,7 +174,8 @@
receiver_.callback(2), {});
EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, _))
- .Times(2).WillRepeatedly(Invoke(task_invoker_));
+ .Times(2)
+ .WillRepeatedly(Invoke(task_invoker_));
EXPECT_CALL(receiver_, OnResponse(1, "foo"));
auto request = XmlParser{}.Parse("<iq id='1' type='result'><foo/></iq>");
@@ -185,7 +188,8 @@
TEST_F(IqStanzaHandlerTest, OutOfOrderResponses) {
EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, _))
- .Times(2).WillRepeatedly(Return(true));
+ .Times(2)
+ .WillRepeatedly(Return(true));
EXPECT_CALL(mock_xmpp_channel_, SendMessage(_)).Times(2);
iq_stanza_handler_->SendRequest("set", "", "", "<body/>",
@@ -194,7 +198,8 @@
receiver_.callback(2), {});
EXPECT_CALL(*task_runner_, PostDelayedTask(_, _, _))
- .Times(2).WillRepeatedly(Invoke(task_invoker_));
+ .Times(2)
+ .WillRepeatedly(Invoke(task_invoker_));
EXPECT_CALL(receiver_, OnResponse(2, "bar"));
auto request = XmlParser{}.Parse("<iq id='2' type='result'><bar/></iq>");
diff --git a/libweave/src/notification/xmpp_stream_parser.cc b/libweave/src/notification/xmpp_stream_parser.cc
index b7bc939..9480e88 100644
--- a/libweave/src/notification/xmpp_stream_parser.cc
+++ b/libweave/src/notification/xmpp_stream_parser.cc
@@ -11,8 +11,7 @@
XmppStreamParser::XmppStreamParser(Delegate* delegate) : delegate_{delegate} {
parser_ = XML_ParserCreate(nullptr);
XML_SetUserData(parser_, this);
- XML_SetElementHandler(parser_,
- &XmppStreamParser::HandleElementStart,
+ XML_SetElementHandler(parser_, &XmppStreamParser::HandleElementStart,
&XmppStreamParser::HandleElementEnd);
XML_SetCharacterDataHandler(parser_, &XmppStreamParser::HandleCharData);
}
diff --git a/libweave/src/notification/xmpp_stream_parser.h b/libweave/src/notification/xmpp_stream_parser.h
index 2a1c401..2f5c87b 100644
--- a/libweave/src/notification/xmpp_stream_parser.h
+++ b/libweave/src/notification/xmpp_stream_parser.h
@@ -86,4 +86,3 @@
} // namespace buffet
#endif // LIBWEAVE_SRC_NOTIFICATION_XMPP_STREAM_PARSER_H_
-
diff --git a/libweave/src/notification/xmpp_stream_parser_unittest.cc b/libweave/src/notification/xmpp_stream_parser_unittest.cc
index 33c5e55..08cc4e5 100644
--- a/libweave/src/notification/xmpp_stream_parser_unittest.cc
+++ b/libweave/src/notification/xmpp_stream_parser_unittest.cc
@@ -43,9 +43,7 @@
class XmppStreamParserTest : public testing::Test,
public XmppStreamParser::Delegate {
public:
- void SetUp() override {
- parser_.reset(new XmppStreamParser{this});
- }
+ void SetUp() override { parser_.reset(new XmppStreamParser{this}); }
void OnStreamStart(const std::string& node_name,
std::map<std::string, std::string> attributes) override {
@@ -91,10 +89,8 @@
parser_->ParseData("<foo bar=\"baz\" quux=\"1\">");
EXPECT_TRUE(stream_started_);
EXPECT_EQ("foo", stream_start_node_name_);
- const std::map<std::string, std::string> expected_attrs{
- {"bar", "baz"},
- {"quux", "1"}
- };
+ const std::map<std::string, std::string> expected_attrs{{"bar", "baz"},
+ {"quux", "1"}};
EXPECT_EQ(expected_attrs, stream_start_node_attributes_);
}
@@ -109,10 +105,8 @@
parser_->ParseData("=\"1\">");
EXPECT_TRUE(stream_started_);
EXPECT_EQ("foo", stream_start_node_name_);
- const std::map<std::string, std::string> expected_attrs{
- {"bar", "baz"},
- {"quux", "1"}
- };
+ const std::map<std::string, std::string> expected_attrs{{"bar", "baz"},
+ {"quux", "1"}};
EXPECT_EQ(expected_attrs, stream_start_node_attributes_);
}
@@ -124,8 +118,7 @@
{"id", "76EEB8FDB4495558"},
{"version", "1.0"},
{"xmlns:stream", "http://etherx.jabber.org/streams"},
- {"xmlns", "jabber:client"}
- };
+ {"xmlns", "jabber:client"}};
// Try splitting the data into pieces from 1 character in size to the whole
// data block and verify that we still can parse the whole message correctly.
// Here |step| is the size of each individual data chunk.
@@ -159,11 +152,15 @@
EXPECT_EQ("message", stanza2->name());
ASSERT_EQ(2u, stanza2->attributes().size());
EXPECT_TRUE(stanza2->GetAttribute("from", &value));
- EXPECT_EQ("cloud-devices@clouddevices.google.com/"
- "srvenc-xgbCfg9hX6tCpxoMYsExqg==", value);
+ EXPECT_EQ(
+ "cloud-devices@clouddevices.google.com/"
+ "srvenc-xgbCfg9hX6tCpxoMYsExqg==",
+ value);
EXPECT_TRUE(stanza2->GetAttribute("to", &value));
- EXPECT_EQ("4783f652b387449fc52a76f9a16e616f@clouddevices.gserviceaccount."
- "com/5A85ED9C", value);
+ EXPECT_EQ(
+ "4783f652b387449fc52a76f9a16e616f@clouddevices.gserviceaccount."
+ "com/5A85ED9C",
+ value);
ASSERT_EQ(1u, stanza2->children().size());
const XmlNode* child = stanza2->children().back().get();
@@ -179,15 +176,18 @@
EXPECT_EQ("push:recipient", child1->name());
ASSERT_EQ(1u, child1->attributes().size());
EXPECT_TRUE(child1->GetAttribute("to", &value));
- EXPECT_EQ("4783f652b387449fc52a76f9a16e616f@clouddevices.gserviceaccount."
- "com", value);
+ EXPECT_EQ(
+ "4783f652b387449fc52a76f9a16e616f@clouddevices.gserviceaccount."
+ "com",
+ value);
EXPECT_TRUE(child1->children().empty());
child2 = child->children()[1].get();
EXPECT_EQ("push:data", child2->name());
EXPECT_TRUE(child2->attributes().empty());
EXPECT_TRUE(child2->children().empty());
- const std::string expected_data = "eyJraW5kIjoiY2xvdWRkZXZpY2VzI25vdGlmaWNh"
+ const std::string expected_data =
+ "eyJraW5kIjoiY2xvdWRkZXZpY2VzI25vdGlmaWNh"
"dGlvbiIsInR5cGUiOiJDT01NQU5EX0NSRUFURUQiLCJjb21tYW5kSWQiOiIwNWE3MTA5MC"
"1hZWE4LWMzNzQtOTYwNS0xZTRhY2JhNDRmM2Y4OTAzZmM3Yy01NjExLWI5ODAtOTkyMy0y"
"Njc2YjYwYzkxMGMiLCJkZXZpY2VJZCI6IjA1YTcxMDkwLWFlYTgtYzM3NC05NjA1LTFlNG"
diff --git a/libweave/src/privet/privet_handler.cc b/libweave/src/privet/privet_handler.cc
index 9b34498..67df4e7 100644
--- a/libweave/src/privet/privet_handler.cc
+++ b/libweave/src/privet/privet_handler.cc
@@ -597,9 +597,10 @@
CreateManifestSection(model_id, *cloud_).release());
output.Set(kInfoServicesKey, ToValue(cloud_->GetServices()).release());
- output.Set(kInfoAuthenticationKey,
- CreateInfoAuthSection(
- *security_, GetAnonymousMaxScope(*cloud_, wifi_)).release());
+ output.Set(
+ kInfoAuthenticationKey,
+ CreateInfoAuthSection(*security_, GetAnonymousMaxScope(*cloud_, wifi_))
+ .release());
output.Set(kInfoEndpointsKey, CreateEndpointsSection(*device_).release());
diff --git a/libweave/src/privet/privet_handler_unittest.cc b/libweave/src/privet/privet_handler_unittest.cc
index a5491ff..a903d21 100644
--- a/libweave/src/privet/privet_handler_unittest.cc
+++ b/libweave/src/privet/privet_handler_unittest.cc
@@ -161,8 +161,8 @@
EXPECT_CALL(cloud_, GetCloudId()).WillRepeatedly(Return(""));
EXPECT_CALL(cloud_, GetConnectionState())
.WillRepeatedly(ReturnRef(gcd_disabled_state_));
- auto set_error =
- [](const std::string&, const std::string&, chromeos::ErrorPtr* error) {
+ auto set_error = [](const std::string&, const std::string&,
+ chromeos::ErrorPtr* error) {
chromeos::Error::AddTo(error, FROM_HERE, errors::kDomain,
"setupUnavailable", "");
};
@@ -531,7 +531,8 @@
TEST_F(PrivetHandlerSetupTest, SetupNameDescriptionLocation) {
EXPECT_CALL(cloud_, UpdateDeviceInfo("testName", "testDescription",
- "testLocation", _, _)).Times(1);
+ "testLocation", _, _))
+ .Times(1);
const char kInput[] = R"({
'name': 'testName',
'description': 'testDescription',
@@ -572,8 +573,8 @@
'passphrase': 'testPass'
}
})";
- auto set_error =
- [](const std::string&, const std::string&, chromeos::ErrorPtr* error) {
+ auto set_error = [](const std::string&, const std::string&,
+ chromeos::ErrorPtr* error) {
chromeos::Error::AddTo(error, FROM_HERE, errors::kDomain, "deviceBusy", "");
};
EXPECT_CALL(wifi_, ConfigureCredentials(_, _, _))
@@ -614,8 +615,8 @@
}
})";
- auto set_error =
- [](const std::string&, const std::string&, chromeos::ErrorPtr* error) {
+ auto set_error = [](const std::string&, const std::string&,
+ chromeos::ErrorPtr* error) {
chromeos::Error::AddTo(error, FROM_HERE, errors::kDomain, "deviceBusy", "");
};
EXPECT_CALL(cloud_, Setup(_, _, _))
diff --git a/libweave/src/states/mock_state_change_queue_interface.h b/libweave/src/states/mock_state_change_queue_interface.h
index c11177a..5a2fcef 100644
--- a/libweave/src/states/mock_state_change_queue_interface.h
+++ b/libweave/src/states/mock_state_change_queue_interface.h
@@ -23,7 +23,7 @@
MOCK_CONST_METHOD0(GetLastStateChangeId, UpdateID());
MOCK_METHOD1(MockAddOnStateUpdatedCallback,
base::CallbackList<void(UpdateID)>::Subscription*(
- const base::Callback<void(UpdateID)>&));
+ const base::Callback<void(UpdateID)>&));
MOCK_METHOD1(NotifyStateUpdatedOnServer, void(UpdateID));
private:
diff --git a/libweave/src/states/state_change_queue_unittest.cc b/libweave/src/states/state_change_queue_unittest.cc
index c7778ee..e19ab08 100644
--- a/libweave/src/states/state_change_queue_unittest.cc
+++ b/libweave/src/states/state_change_queue_unittest.cc
@@ -2,7 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-
#include "libweave/src/states/state_change_queue.h"
#include <chromeos/bind_lambda.h>
@@ -14,13 +13,9 @@
class StateChangeQueueTest : public ::testing::Test {
public:
- void SetUp() override {
- queue_.reset(new StateChangeQueue(100));
- }
+ void SetUp() override { queue_.reset(new StateChangeQueue(100)); }
- void TearDown() override {
- queue_.reset();
- }
+ void TearDown() override { queue_.reset(); }
std::unique_ptr<StateChangeQueue> queue_;
};
@@ -33,9 +28,8 @@
TEST_F(StateChangeQueueTest, UpdateOne) {
StateChange change{
- base::Time::Now(),
- native_types::Object{{"prop.name", unittests::make_int_prop_value(23)}}
- };
+ base::Time::Now(),
+ native_types::Object{{"prop.name", unittests::make_int_prop_value(23)}}};
ASSERT_TRUE(queue_->NotifyPropertiesUpdated(change.timestamp,
change.changed_properties));
EXPECT_FALSE(queue_->IsEmpty());
@@ -51,19 +45,17 @@
TEST_F(StateChangeQueueTest, UpdateMany) {
StateChange change1{
- base::Time::Now(),
- native_types::Object{{"prop.name1", unittests::make_int_prop_value(23)}}
- };
+ base::Time::Now(),
+ native_types::Object{{"prop.name1", unittests::make_int_prop_value(23)}}};
ASSERT_TRUE(queue_->NotifyPropertiesUpdated(change1.timestamp,
change1.changed_properties));
StateChange change2{
- base::Time::Now(),
- native_types::Object{
- {"prop.name1", unittests::make_int_prop_value(17)},
- {"prop.name2", unittests::make_double_prop_value(1.0)},
- {"prop.name3", unittests::make_bool_prop_value(false)},
- }
- };
+ base::Time::Now(),
+ native_types::Object{
+ {"prop.name1", unittests::make_int_prop_value(17)},
+ {"prop.name2", unittests::make_double_prop_value(1.0)},
+ {"prop.name3", unittests::make_bool_prop_value(false)},
+ }};
ASSERT_TRUE(queue_->NotifyPropertiesUpdated(change2.timestamp,
change2.changed_properties));
EXPECT_EQ(2, queue_->GetLastStateChangeId());
@@ -103,11 +95,11 @@
ASSERT_EQ(2, changes.size());
native_types::Object expected1{
- {"prop.name1", unittests::make_int_prop_value(3)},
- {"prop.name2", unittests::make_int_prop_value(2)},
+ {"prop.name1", unittests::make_int_prop_value(3)},
+ {"prop.name2", unittests::make_int_prop_value(2)},
};
native_types::Object expected2{
- {"prop.name1", unittests::make_int_prop_value(4)},
+ {"prop.name1", unittests::make_int_prop_value(4)},
};
EXPECT_EQ(timestamp, changes[0].timestamp);
EXPECT_EQ(expected1, changes[0].changed_properties);
@@ -122,24 +114,23 @@
base::TimeDelta time_delta2 = base::TimeDelta::FromMinutes(3);
ASSERT_TRUE(queue_->NotifyPropertiesUpdated(
- start_time,
- native_types::Object{
- {"prop.name1", unittests::make_int_prop_value(1)},
- {"prop.name2", unittests::make_int_prop_value(2)},
- }));
+ start_time, native_types::Object{
+ {"prop.name1", unittests::make_int_prop_value(1)},
+ {"prop.name2", unittests::make_int_prop_value(2)},
+ }));
ASSERT_TRUE(queue_->NotifyPropertiesUpdated(
start_time + time_delta1,
native_types::Object{
- {"prop.name1", unittests::make_int_prop_value(3)},
- {"prop.name3", unittests::make_int_prop_value(4)},
+ {"prop.name1", unittests::make_int_prop_value(3)},
+ {"prop.name3", unittests::make_int_prop_value(4)},
}));
ASSERT_TRUE(queue_->NotifyPropertiesUpdated(
start_time + time_delta2,
native_types::Object{
- {"prop.name10", unittests::make_int_prop_value(10)},
- {"prop.name11", unittests::make_int_prop_value(11)},
+ {"prop.name10", unittests::make_int_prop_value(10)},
+ {"prop.name11", unittests::make_int_prop_value(11)},
}));
EXPECT_EQ(3, queue_->GetLastStateChangeId());
@@ -147,16 +138,16 @@
ASSERT_EQ(2, changes.size());
native_types::Object expected1{
- {"prop.name1", unittests::make_int_prop_value(3)},
- {"prop.name2", unittests::make_int_prop_value(2)},
- {"prop.name3", unittests::make_int_prop_value(4)},
+ {"prop.name1", unittests::make_int_prop_value(3)},
+ {"prop.name2", unittests::make_int_prop_value(2)},
+ {"prop.name3", unittests::make_int_prop_value(4)},
};
EXPECT_EQ(start_time + time_delta1, changes[0].timestamp);
EXPECT_EQ(expected1, changes[0].changed_properties);
native_types::Object expected2{
- {"prop.name10", unittests::make_int_prop_value(10)},
- {"prop.name11", unittests::make_int_prop_value(11)},
+ {"prop.name10", unittests::make_int_prop_value(10)},
+ {"prop.name11", unittests::make_int_prop_value(11)},
};
EXPECT_EQ(start_time + time_delta2, changes[1].timestamp);
EXPECT_EQ(expected2, changes[1].changed_properties);
@@ -175,11 +166,10 @@
TEST_F(StateChangeQueueTest, DelayedStateChangeNotification) {
// When queue is not empty, registering a new callback will not trigger it.
ASSERT_TRUE(queue_->NotifyPropertiesUpdated(
- base::Time::Now(),
- native_types::Object{
- {"prop.name1", unittests::make_int_prop_value(1)},
- {"prop.name2", unittests::make_int_prop_value(2)},
- }));
+ base::Time::Now(), native_types::Object{
+ {"prop.name1", unittests::make_int_prop_value(1)},
+ {"prop.name2", unittests::make_int_prop_value(2)},
+ }));
auto callback = [](StateChangeQueueInterface::UpdateID id) {
FAIL() << "This should not be called";
diff --git a/libweave/src/states/state_manager.cc b/libweave/src/states/state_manager.cc
index 4358c40..504f25b 100644
--- a/libweave/src/states/state_manager.cc
+++ b/libweave/src/states/state_manager.cc
@@ -24,7 +24,6 @@
} // namespace
-
StateManager::StateManager(StateChangeQueueInterface* state_change_queue)
: state_change_queue_(state_change_queue) {
CHECK(state_change_queue_) << "State change queue not specified";
@@ -89,17 +88,15 @@
} else {
LOG(ERROR) << "Failed to read file for firmwareVersion.";
}
- CHECK(SetPropertyValue(kBaseStateFirmwareVersion,
- firmware_version,
- base::Time::Now(),
- nullptr));
+ CHECK(SetPropertyValue(kBaseStateFirmwareVersion, firmware_version,
+ base::Time::Now(), nullptr));
for (const auto& cb : on_changed_)
cb.Run();
}
std::unique_ptr<base::DictionaryValue> StateManager::GetStateValuesAsJson(
- chromeos::ErrorPtr* error) const {
+ chromeos::ErrorPtr* error) const {
std::unique_ptr<base::DictionaryValue> dict{new base::DictionaryValue};
for (const auto& pair : packages_) {
auto pkg_value = pair.second->GetValuesAsJson(error);
@@ -152,16 +149,16 @@
StatePackage* package = FindPackage(package_name);
if (package == nullptr) {
chromeos::Error::AddToPrintf(error, FROM_HERE, errors::state::kDomain,
- errors::state::kPropertyNotDefined,
- "Unknown state property package '%s'",
- package_name.c_str());
+ errors::state::kPropertyNotDefined,
+ "Unknown state property package '%s'",
+ package_name.c_str());
return false;
}
if (!package->SetPropertyValue(property_name, value, error))
return false;
- native_types::Object prop_set{{full_property_name,
- package->GetProperty(property_name)}};
+ native_types::Object prop_set{
+ {full_property_name, package->GetProperty(property_name)}};
state_change_queue_->NotifyPropertiesUpdated(timestamp, prop_set);
return true;
}
@@ -191,11 +188,10 @@
}
const base::DictionaryValue* package_dict = nullptr;
if (!iter.value().GetAsDictionary(&package_dict)) {
- chromeos::Error::AddToPrintf(error, FROM_HERE,
- chromeos::errors::json::kDomain,
- chromeos::errors::json::kObjectExpected,
- "State package '%s' must be an object",
- package_name.c_str());
+ chromeos::Error::AddToPrintf(
+ error, FROM_HERE, chromeos::errors::json::kDomain,
+ chromeos::errors::json::kObjectExpected,
+ "State package '%s' must be an object", package_name.c_str());
return false;
}
StatePackage* package = FindOrCreatePackage(package_name);
@@ -227,8 +223,7 @@
if (!LoadStateDefinition(*json, category, error)) {
chromeos::Error::AddToPrintf(error, FROM_HERE, kErrorDomainBuffet,
- kFileReadError,
- "Failed to load file '%s'",
+ kFileReadError, "Failed to load file '%s'",
json_file_path.value().c_str());
return false;
}
@@ -243,8 +238,7 @@
return false;
if (!LoadStateDefinition(*json, kDefaultCategory, error)) {
chromeos::Error::AddToPrintf(error, FROM_HERE, kErrorDomainBuffet,
- kFileReadError,
- "Failed to load file '%s'",
+ kFileReadError, "Failed to load file '%s'",
json_file_path.value().c_str());
return false;
}
@@ -264,11 +258,10 @@
}
const base::DictionaryValue* package_dict = nullptr;
if (!iter.value().GetAsDictionary(&package_dict)) {
- chromeos::Error::AddToPrintf(error, FROM_HERE,
- chromeos::errors::json::kDomain,
- chromeos::errors::json::kObjectExpected,
- "State package '%s' must be an object",
- package_name.c_str());
+ chromeos::Error::AddToPrintf(
+ error, FROM_HERE, chromeos::errors::json::kDomain,
+ chromeos::errors::json::kObjectExpected,
+ "State package '%s' must be an object", package_name.c_str());
return false;
}
StatePackage* package = FindPackage(package_name);
@@ -295,8 +288,7 @@
return false;
if (!LoadStateDefaults(*json, error)) {
chromeos::Error::AddToPrintf(error, FROM_HERE, kErrorDomainBuffet,
- kFileReadError,
- "Failed to load file '%s'",
+ kFileReadError, "Failed to load file '%s'",
json_file_path.value().c_str());
return false;
}
@@ -313,8 +305,8 @@
StatePackage* package = FindPackage(package_name);
if (package == nullptr) {
std::unique_ptr<StatePackage> new_package{new StatePackage(package_name)};
- package = packages_.emplace(package_name,
- std::move(new_package)).first->second.get();
+ package = packages_.emplace(package_name, std::move(new_package))
+ .first->second.get();
}
return package;
}
diff --git a/libweave/src/states/state_manager.h b/libweave/src/states/state_manager.h
index 83d1fdb..e502381 100644
--- a/libweave/src/states/state_manager.h
+++ b/libweave/src/states/state_manager.h
@@ -53,9 +53,7 @@
// Returns all the categories the state properties are registered from.
// As with GCD command handling, the category normally represent a device
// service (daemon) that is responsible for a set of properties.
- const std::set<std::string>& GetCategories() const {
- return categories_;
- }
+ const std::set<std::string>& GetCategories() const { return categories_; }
// Returns the recorded state changes since last time this method has been
// called.
diff --git a/libweave/src/states/state_package.cc b/libweave/src/states/state_package.cc
index 0b26006..825374e 100644
--- a/libweave/src/states/state_package.cc
+++ b/libweave/src/states/state_package.cc
@@ -28,9 +28,9 @@
for (const auto& pair : schema.GetProps()) {
if (types_.GetProp(pair.first)) {
chromeos::Error::AddToPrintf(error, FROM_HERE, errors::state::kDomain,
- errors::state::kPropertyRedefinition,
- "State property '%s.%s' is already defined",
- name_.c_str(), pair.first.c_str());
+ errors::state::kPropertyRedefinition,
+ "State property '%s.%s' is already defined",
+ name_.c_str(), pair.first.c_str());
return false;
}
}
@@ -53,9 +53,9 @@
auto it = values_.find(property_name);
if (it == values_.end()) {
chromeos::Error::AddToPrintf(error, FROM_HERE, errors::state::kDomain,
- errors::state::kPropertyNotDefined,
- "State property '%s.%s' is not defined",
- name_.c_str(), property_name.c_str());
+ errors::state::kPropertyNotDefined,
+ "State property '%s.%s' is not defined",
+ name_.c_str(), property_name.c_str());
return false;
}
auto new_value = it->second->GetPropType()->CreateValue();
@@ -68,7 +68,7 @@
}
std::unique_ptr<base::DictionaryValue> StatePackage::GetValuesAsJson(
- chromeos::ErrorPtr* error) const {
+ chromeos::ErrorPtr* error) const {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
for (const auto& pair : values_) {
auto value = pair.second->ToJson(error);
@@ -86,9 +86,9 @@
auto it = values_.find(property_name);
if (it == values_.end()) {
chromeos::Error::AddToPrintf(error, FROM_HERE, errors::state::kDomain,
- errors::state::kPropertyNotDefined,
- "State property '%s.%s' is not defined",
- name_.c_str(), property_name.c_str());
+ errors::state::kPropertyNotDefined,
+ "State property '%s.%s' is not defined",
+ name_.c_str(), property_name.c_str());
return chromeos::Any();
}
return PropValueToDBusVariant(it->second.get());
@@ -100,13 +100,13 @@
auto it = values_.find(property_name);
if (it == values_.end()) {
chromeos::Error::AddToPrintf(error, FROM_HERE, errors::state::kDomain,
- errors::state::kPropertyNotDefined,
- "State property '%s.%s' is not defined",
- name_.c_str(), property_name.c_str());
+ errors::state::kPropertyNotDefined,
+ "State property '%s.%s' is not defined",
+ name_.c_str(), property_name.c_str());
return false;
}
- auto new_value = PropValueFromDBusVariant(it->second->GetPropType(),
- value, error);
+ auto new_value =
+ PropValueFromDBusVariant(it->second->GetPropType(), value, error);
if (!new_value)
return false;
it->second = std::move(new_value);
diff --git a/libweave/src/states/state_package.h b/libweave/src/states/state_package.h
index 9666870..c2471f0 100644
--- a/libweave/src/states/state_package.h
+++ b/libweave/src/states/state_package.h
@@ -53,7 +53,7 @@
// }
// }
std::unique_ptr<base::DictionaryValue> GetValuesAsJson(
- chromeos::ErrorPtr* error) const;
+ chromeos::ErrorPtr* error) const;
// Gets the value for a specific state property. |property_name| must not
// include the package name as part of the property name.
@@ -65,11 +65,11 @@
const chromeos::Any& value,
chromeos::ErrorPtr* error);
- std::shared_ptr<const PropValue>
- GetProperty(const std::string& property_name) const {
+ std::shared_ptr<const PropValue> GetProperty(
+ const std::string& property_name) const {
auto it = values_.find(property_name);
- return it != values_.end() ?
- it->second : std::shared_ptr<const PropValue>{};
+ return it != values_.end() ? it->second
+ : std::shared_ptr<const PropValue>{};
}
// Returns the name of the this package.
diff --git a/libweave/src/states/state_package_unittest.cc b/libweave/src/states/state_package_unittest.cc
index 28aa62c..0b860cd 100644
--- a/libweave/src/states/state_package_unittest.cc
+++ b/libweave/src/states/state_package_unittest.cc
@@ -67,9 +67,7 @@
ASSERT_TRUE(package_->AddSchemaFromJson(GetTestSchema().get(), nullptr));
ASSERT_TRUE(package_->AddValuesFromJson(GetTestValues().get(), nullptr));
}
- void TearDown() override {
- package_.reset();
- }
+ void TearDown() override { package_.reset(); }
std::unique_ptr<StatePackage> package_;
};
@@ -250,13 +248,12 @@
EXPECT_TRUE(value.IsEmpty());
EXPECT_EQ(errors::state::kDomain, error->GetDomain());
EXPECT_EQ(errors::state::kPropertyNotDefined, error->GetCode());
- EXPECT_EQ("State property 'test.volume' is not defined",
- error->GetMessage());
+ EXPECT_EQ("State property 'test.volume' is not defined", error->GetMessage());
}
TEST_F(StatePackageTest, SetPropertyValue_Simple) {
- EXPECT_TRUE(package_->SetPropertyValue("color", std::string{"blue"},
- nullptr));
+ EXPECT_TRUE(
+ package_->SetPropertyValue("color", std::string{"blue"}, nullptr));
chromeos::Any value = package_->GetPropertyValue("color", nullptr);
EXPECT_EQ("blue", value.TryGet<std::string>());
@@ -271,8 +268,7 @@
TEST_F(StatePackageTest, SetPropertyValue_Object) {
chromeos::VariantDictionary direction{
- {"altitude", double{45.0}},
- {"azimuth", double{15.0}},
+ {"altitude", double{45.0}}, {"azimuth", double{15.0}},
};
EXPECT_TRUE(package_->SetPropertyValue("direction", direction, nullptr));
@@ -314,8 +310,7 @@
TEST_F(StatePackageTest, SetPropertyValue_Error_Object_TypeMismatch) {
chromeos::ErrorPtr error;
chromeos::VariantDictionary direction{
- {"altitude", double{45.0}},
- {"azimuth", int{15}},
+ {"altitude", double{45.0}}, {"azimuth", int{15}},
};
ASSERT_FALSE(package_->SetPropertyValue("direction", direction, &error));
EXPECT_EQ(errors::commands::kDomain, error->GetDomain());
@@ -330,8 +325,7 @@
TEST_F(StatePackageTest, SetPropertyValue_Error_Object_OutOfRange) {
chromeos::ErrorPtr error;
chromeos::VariantDictionary direction{
- {"altitude", double{100.0}},
- {"azimuth", double{290.0}},
+ {"altitude", double{100.0}}, {"azimuth", double{290.0}},
};
ASSERT_FALSE(package_->SetPropertyValue("direction", direction, &error));
EXPECT_EQ(errors::commands::kDomain, error->GetDomain());
@@ -347,9 +341,9 @@
TEST_F(StatePackageTest, SetPropertyValue_Error_Object_UnknownProperty) {
chromeos::ErrorPtr error;
chromeos::VariantDictionary direction{
- {"altitude", double{10.0}},
- {"azimuth", double{20.0}},
- {"spin", double{30.0}},
+ {"altitude", double{10.0}},
+ {"azimuth", double{20.0}},
+ {"spin", double{30.0}},
};
ASSERT_FALSE(package_->SetPropertyValue("direction", direction, &error));
EXPECT_EQ(errors::commands::kDomain, error->GetDomain());
@@ -360,7 +354,7 @@
TEST_F(StatePackageTest, SetPropertyValue_Error_Object_MissingProperty) {
chromeos::ErrorPtr error;
chromeos::VariantDictionary direction{
- {"altitude", double{10.0}},
+ {"altitude", double{10.0}},
};
ASSERT_FALSE(package_->SetPropertyValue("direction", direction, &error));
EXPECT_EQ(errors::commands::kDomain, error->GetDomain());
@@ -373,8 +367,7 @@
ASSERT_FALSE(package_->SetPropertyValue("volume", int{100}, &error));
EXPECT_EQ(errors::state::kDomain, error->GetDomain());
EXPECT_EQ(errors::state::kPropertyNotDefined, error->GetCode());
- EXPECT_EQ("State property 'test.volume' is not defined",
- error->GetMessage());
+ EXPECT_EQ("State property 'test.volume' is not defined", error->GetMessage());
}
} // namespace buffet
diff --git a/libweave/src/storage_impls.cc b/libweave/src/storage_impls.cc
index 78b01cd..44a8925 100644
--- a/libweave/src/storage_impls.cc
+++ b/libweave/src/storage_impls.cc
@@ -14,7 +14,8 @@
namespace buffet {
FileStorage::FileStorage(const base::FilePath& file_path)
- : file_path_(file_path) { }
+ : file_path_(file_path) {
+}
std::unique_ptr<base::DictionaryValue> FileStorage::Load() {
std::string json;
diff --git a/libweave/src/utils.cc b/libweave/src/utils.cc
index 547d371..411e74d 100644
--- a/libweave/src/utils.cc
+++ b/libweave/src/utils.cc
@@ -44,8 +44,7 @@
if (!base::ReadFileToString(json_file_path, &json_string)) {
chromeos::errors::system::AddSystemError(error, FROM_HERE, errno);
chromeos::Error::AddToPrintf(error, FROM_HERE, kErrorDomainBuffet,
- kFileReadError,
- "Failed to read file '%s'",
+ kFileReadError, "Failed to read file '%s'",
json_file_path.value().c_str());
return {};
}
@@ -60,12 +59,11 @@
auto value = base::JSONReader::ReadAndReturnError(
json_string, base::JSON_PARSE_RFC, nullptr, &error_message);
if (!value) {
- chromeos::Error::AddToPrintf(error, FROM_HERE,
- chromeos::errors::json::kDomain,
- chromeos::errors::json::kParseError,
- "Error parsing JSON string '%s': %s",
- LimitString(json_string, kMaxStrLen).c_str(),
- error_message.c_str());
+ chromeos::Error::AddToPrintf(
+ error, FROM_HERE, chromeos::errors::json::kDomain,
+ chromeos::errors::json::kParseError,
+ "Error parsing JSON string '%s': %s",
+ LimitString(json_string, kMaxStrLen).c_str(), error_message.c_str());
return result;
}
base::DictionaryValue* dict_value = nullptr;