id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20,571
|
test_base_virtual_machine.cpp
|
canonical_multipass/tests/test_base_virtual_machine.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "dummy_ssh_key_provider.h"
#include "file_operations.h"
#include "mock_cloud_init_file_ops.h"
#include "mock_logger.h"
#include "mock_snapshot.h"
#include "mock_ssh_test_fixture.h"
#include "mock_utils.h"
#include "mock_virtual_machine.h"
#include "temp_dir.h"
#include <shared/base_virtual_machine.h>
#include <multipass/exceptions/file_open_failed_exception.h>
#include <multipass/exceptions/internal_timeout_exception.h>
#include <multipass/exceptions/ip_unavailable_exception.h>
#include <multipass/exceptions/snapshot_exceptions.h>
#include <multipass/exceptions/ssh_exception.h>
#include <multipass/logging/level.h>
#include <multipass/snapshot.h>
#include <multipass/ssh/ssh_session.h>
#include <multipass/vm_specs.h>
#include <algorithm>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
using St = mp::VirtualMachine::State;
namespace
{
struct MockBaseVirtualMachine : public mpt::MockVirtualMachineT<mp::BaseVirtualMachine>
{
template <typename... Args>
MockBaseVirtualMachine(Args&&... args)
: mpt::MockVirtualMachineT<mp::BaseVirtualMachine>{std::forward<Args>(args)...}
{
const auto& const_self = *this;
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, get_all_ipv4, mp::BaseVirtualMachine);
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, view_snapshots, mp::BaseVirtualMachine);
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, get_num_snapshots, mp::BaseVirtualMachine);
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, take_snapshot, mp::BaseVirtualMachine);
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, rename_snapshot, mp::BaseVirtualMachine);
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, delete_snapshot, mp::BaseVirtualMachine);
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, restore_snapshot, mp::BaseVirtualMachine);
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, load_snapshots, mp::BaseVirtualMachine);
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, get_childrens_names, mp::BaseVirtualMachine);
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, get_snapshot_count, mp::BaseVirtualMachine);
MP_DELEGATE_MOCK_CALLS_ON_BASE_WITH_MATCHERS(*this, get_snapshot, mp::BaseVirtualMachine, (An<int>()));
MP_DELEGATE_MOCK_CALLS_ON_BASE_WITH_MATCHERS(const_self, get_snapshot, mp::BaseVirtualMachine, (An<int>()));
MP_DELEGATE_MOCK_CALLS_ON_BASE_WITH_MATCHERS(*this,
get_snapshot,
mp::BaseVirtualMachine,
(A<const std::string&>()));
MP_DELEGATE_MOCK_CALLS_ON_BASE_WITH_MATCHERS(const_self,
get_snapshot,
mp::BaseVirtualMachine,
(A<const std::string&>()));
}
MOCK_METHOD(void, require_snapshots_support, (), (const, override));
MOCK_METHOD(std::shared_ptr<mp::Snapshot>, make_specific_snapshot, (const QString& filename), (override));
MOCK_METHOD(std::shared_ptr<mp::Snapshot>,
make_specific_snapshot,
(const std::string& snapshot_name,
const std::string& comment,
const std::string& instance_id,
const mp::VMSpecs& specs,
std::shared_ptr<mp::Snapshot> parent),
(override));
using mp::BaseVirtualMachine::renew_ssh_session; // promote to public
void simulate_state(St state)
{
this->state = state;
ON_CALL(*this, current_state).WillByDefault(Return(state));
}
void simulate_ssh_exec() // use if premocking libssh stuff
{
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, ssh_exec, mp::BaseVirtualMachine);
}
void simulate_waiting_for_ssh() // use if premocking libssh stuff
{
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, wait_until_ssh_up, mp::BaseVirtualMachine);
}
void simulate_cloud_init()
{
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, wait_for_cloud_init, mp::BaseVirtualMachine);
}
void simulate_no_snapshots_support() const // doing this here to access protected method on the base
{
MP_DELEGATE_MOCK_CALLS_ON_BASE(*this, require_snapshots_support, mp::BaseVirtualMachine);
}
};
struct StubBaseVirtualMachine : public mp::BaseVirtualMachine
{
StubBaseVirtualMachine(St s = St::off) : StubBaseVirtualMachine{s, std::make_unique<mpt::TempDir>()}
{
}
StubBaseVirtualMachine(St s, std::unique_ptr<mpt::TempDir> tmp_dir)
: mp::BaseVirtualMachine{s, "stub", mpt::StubSSHKeyProvider{}, tmp_dir->path()}, tmp_dir{std::move(tmp_dir)}
{
}
void start() override
{
state = St::running;
}
void shutdown(ShutdownPolicy shutdown_policy = ShutdownPolicy::Powerdown) override
{
state = St::off;
}
void suspend() override
{
state = St::suspended;
}
St current_state() override
{
return state;
}
int ssh_port() override
{
return 42;
}
std::string ssh_hostname(std::chrono::milliseconds /*timeout*/) override
{
return "localhost";
}
std::string ssh_username() override
{
return "ubuntu";
}
std::string management_ipv4() override
{
return "1.2.3.4";
}
std::string ipv6() override
{
return "";
}
void wait_until_ssh_up(std::chrono::milliseconds) override
{
}
void ensure_vm_is_running() override
{
}
void update_state() override
{
}
void update_cpus(int num_cores) override
{
}
void resize_memory(const mp::MemorySize&) override
{
}
void resize_disk(const mp::MemorySize&) override
{
}
void require_snapshots_support() const override // pretend we support it here
{
}
std::unique_ptr<mpt::TempDir> tmp_dir;
};
struct BaseVM : public Test
{
void mock_snapshotting()
{
EXPECT_CALL(vm, make_specific_snapshot(_, _, _, _, _))
.WillRepeatedly(WithArgs<0, 4>([this](const std::string& name, std::shared_ptr<mp::Snapshot> parent) {
auto ret = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*ret, get_name).WillRepeatedly(Return(name));
EXPECT_CALL(*ret, get_index).WillRepeatedly(Return(vm.get_snapshot_count() + 1));
EXPECT_CALL(*ret, get_parent()).WillRepeatedly(Return(parent));
EXPECT_CALL(Const(*ret), get_parent()).WillRepeatedly(Return(parent));
EXPECT_CALL(*ret, get_parents_index).WillRepeatedly(Return(parent ? parent->get_index() : 0));
snapshot_album.push_back(ret);
return ret;
}));
}
QString get_snapshot_file_path(int idx) const
{
assert(idx > 0 && "need positive index");
return vm.tmp_dir->filePath(QString::fromStdString(fmt::format("{:04}.snapshot.json", idx)));
}
static std::string n_occurrences(const std::string& regex, int n)
{
assert(n > 0 && "need positive n");
return
#ifdef MULTIPASS_PLATFORM_WINDOWS
fmt::to_string(fmt::join(std::vector(n, regex), ""));
#else
fmt::format("{}{{{}}}", regex, n);
#endif
}
static auto make_index_file_contents_matcher(int idx)
{
assert(idx > 0 && "need positive index");
return MatchesRegex(fmt::format("{0}*{1}{0}*", space_char_class, idx));
}
mpt::MockSSHTestFixture mock_ssh_test_fixture;
const mpt::DummyKeyProvider key_provider{"keeper of the seven keys"};
NiceMock<MockBaseVirtualMachine> vm{"mock-vm", key_provider};
std::vector<std::shared_ptr<mpt::MockSnapshot>> snapshot_album;
QString head_path = vm.tmp_dir->filePath(head_filename);
QString count_path = vm.tmp_dir->filePath(count_filename);
const mpt::MockCloudInitFileOps::GuardedMock mock_cloud_init_file_ops_injection =
mpt::MockCloudInitFileOps::inject<NiceMock>();
static constexpr bool on_windows =
#ifdef MULTIPASS_PLATFORM_WINDOWS
true;
#else
false;
#endif
static constexpr auto* head_filename = "snapshot-head";
static constexpr auto* count_filename = "snapshot-count";
static constexpr auto space_char_class = on_windows ? "\\s" : "[[:space:]]";
static constexpr auto digit_char_class = on_windows ? "\\d" : "[[:digit:]]";
};
TEST_F(BaseVM, get_all_ipv4_works_when_ssh_throws_opening_a_session)
{
vm.simulate_state(St::running);
vm.simulate_ssh_exec();
REPLACE(ssh_new, []() { return nullptr; }); // This makes SSH throw when opening a new session.
auto ip_list = vm.get_all_ipv4();
EXPECT_EQ(ip_list.size(), 0u);
}
TEST_F(BaseVM, get_all_ipv4_works_when_ssh_throws_executing)
{
vm.simulate_state(St::running);
vm.simulate_ssh_exec();
// Make SSH throw when trying to execute something.
mock_ssh_test_fixture.request_exec.returnValue(SSH_ERROR);
auto ip_list = vm.get_all_ipv4();
EXPECT_EQ(ip_list.size(), 0u);
}
TEST_F(BaseVM, get_all_ipv4_works_when_instance_is_off)
{
vm.simulate_state(St::off);
EXPECT_EQ(vm.get_all_ipv4().size(), 0u);
}
TEST_F(BaseVM, add_network_interface_throws)
{
StubBaseVirtualMachine base_vm(St::off);
MP_EXPECT_THROW_THAT(base_vm.add_network_interface(1, "", {"eth1", "52:54:00:00:00:00", true}),
mp::NotImplementedOnThisBackendException,
mpt::match_what(HasSubstr("networks")));
}
struct IpTestParams
{
int exit_status;
std::string output;
std::vector<std::string> expected_ips;
};
struct IpExecution : public BaseVM, public WithParamInterface<IpTestParams>
{
};
TEST_P(IpExecution, get_all_ipv4_works_when_ssh_works)
{
vm.simulate_state(St::running);
vm.simulate_ssh_exec();
auto test_params = GetParam();
auto remaining = test_params.output.size();
ssh_channel_callbacks callbacks{nullptr};
auto add_channel_cbs = [&callbacks](ssh_channel, ssh_channel_callbacks cb) {
callbacks = cb;
return SSH_OK;
};
REPLACE(ssh_add_channel_callbacks, add_channel_cbs);
auto event_dopoll = [&callbacks, &test_params](ssh_event, int timeout) {
EXPECT_TRUE(callbacks);
callbacks->channel_exit_status_function(nullptr, nullptr, test_params.exit_status, callbacks->userdata);
return SSH_OK;
};
REPLACE(ssh_event_dopoll, event_dopoll);
auto channel_read = [&test_params, &remaining](ssh_channel, void* dest, uint32_t count, int is_stderr, int) {
const auto num_to_copy = std::min(count, static_cast<uint32_t>(remaining));
const auto begin = test_params.output.begin() + test_params.output.size() - remaining;
std::copy_n(begin, num_to_copy, reinterpret_cast<char*>(dest));
remaining -= num_to_copy;
return num_to_copy;
};
REPLACE(ssh_channel_read_timeout, channel_read);
auto ip_list = vm.get_all_ipv4();
EXPECT_EQ(ip_list, test_params.expected_ips);
}
INSTANTIATE_TEST_SUITE_P(
BaseVM, IpExecution,
Values(IpTestParams{0, "eth0 UP 192.168.2.168/24 \n", {"192.168.2.168"}},
IpTestParams{0, "eth1 UP 192.168.2.169/24 metric 100 \n", {"192.168.2.169"}},
IpTestParams{0,
"wlp4s0 UP 192.168.2.8/24 \n"
"virbr0 DOWN 192.168.3.1/24 \n"
"tun0 UNKNOWN 10.172.66.5/18 \n",
{"192.168.2.8", "192.168.3.1", "10.172.66.5"}},
IpTestParams{0, "", {}}));
TEST_F(BaseVM, startsWithNoSnapshots)
{
EXPECT_EQ(vm.get_num_snapshots(), 0);
}
TEST_F(BaseVM, throwsOnSnapshotsRequestIfNotSupported)
{
vm.simulate_no_snapshots_support();
MP_EXPECT_THROW_THAT(vm.get_num_snapshots(),
mp::NotImplementedOnThisBackendException,
mpt::match_what(HasSubstr("snapshots")));
}
TEST_F(BaseVM, takesSnapshots)
{
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*snapshot, capture).Times(1);
EXPECT_CALL(vm, make_specific_snapshot(_, _, _, _, _)).WillOnce(Return(snapshot));
vm.take_snapshot(mp::VMSpecs{}, "s1", "");
EXPECT_EQ(vm.get_num_snapshots(), 1);
}
TEST_F(BaseVM, takeSnasphotThrowsIfSpecificSnapshotNotOverridden)
{
StubBaseVirtualMachine stub{};
MP_EXPECT_THROW_THAT(stub.take_snapshot({}, "stub-snap", ""),
mp::NotImplementedOnThisBackendException,
mpt::match_what(HasSubstr("snapshots")));
}
TEST_F(BaseVM, deletesSnapshots)
{
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*snapshot, erase).Times(1);
EXPECT_CALL(vm, make_specific_snapshot(_, _, _, _, _)).WillOnce(Return(snapshot));
vm.take_snapshot(mp::VMSpecs{}, "s1", "");
vm.delete_snapshot("s1");
EXPECT_EQ(vm.get_num_snapshots(), 0);
}
TEST_F(BaseVM, countsCurrentSnapshots)
{
const mp::VMSpecs specs{};
EXPECT_EQ(vm.get_num_snapshots(), 0);
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(vm, make_specific_snapshot(_, _, _, _, _)).WillRepeatedly(Return(snapshot));
vm.take_snapshot(specs, "s1", "");
EXPECT_EQ(vm.get_num_snapshots(), 1);
vm.take_snapshot(specs, "s2", "");
vm.take_snapshot(specs, "s3", "");
EXPECT_EQ(vm.get_num_snapshots(), 3);
vm.delete_snapshot("s1");
EXPECT_EQ(vm.get_num_snapshots(), 2);
vm.delete_snapshot("s2");
vm.delete_snapshot("s3");
EXPECT_EQ(vm.get_num_snapshots(), 0);
vm.take_snapshot(specs, "s4", "");
EXPECT_EQ(vm.get_num_snapshots(), 1);
}
TEST_F(BaseVM, countsTotalSnapshots)
{
const mp::VMSpecs specs{};
EXPECT_EQ(vm.get_num_snapshots(), 0);
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(vm, make_specific_snapshot(_, _, _, _, _)).WillRepeatedly(Return(snapshot));
vm.take_snapshot(specs, "s1", "");
vm.take_snapshot(specs, "s2", "");
vm.take_snapshot(specs, "s3", "");
EXPECT_EQ(vm.get_snapshot_count(), 3);
vm.take_snapshot(specs, "s4", "");
vm.take_snapshot(specs, "s5", "");
EXPECT_EQ(vm.get_snapshot_count(), 5);
vm.delete_snapshot("s1");
vm.delete_snapshot("s2");
EXPECT_EQ(vm.get_snapshot_count(), 5);
vm.delete_snapshot("s4");
EXPECT_EQ(vm.get_snapshot_count(), 5);
vm.take_snapshot(specs, "s6", "");
EXPECT_EQ(vm.get_snapshot_count(), 6);
}
TEST_F(BaseVM, providesSnapshotsView)
{
mock_snapshotting();
const mp::VMSpecs specs{};
auto sname = [](int i) { return fmt::format("s{}", i); };
for (int i = 1; i < 6; ++i) // +5
vm.take_snapshot(specs, sname(i), "");
for (int i = 3; i < 5; ++i) // -2
vm.delete_snapshot(sname(i));
for (int i = 6; i < 9; ++i) // +3
vm.take_snapshot(specs, sname(i), "");
for (int i : {1, 7}) // -2
vm.delete_snapshot(sname(i));
ASSERT_EQ(vm.get_num_snapshots(), 4);
auto snapshots = vm.view_snapshots();
EXPECT_THAT(snapshots, SizeIs(4));
std::vector<int> snapshot_indices{};
std::transform(snapshots.begin(), snapshots.end(), std::back_inserter(snapshot_indices), [](const auto& snapshot) {
return snapshot->get_index();
});
EXPECT_THAT(snapshot_indices, UnorderedElementsAre(2, 5, 6, 8));
}
TEST_F(BaseVM, providesSnapshotsByIndex)
{
mock_snapshotting();
const mp::VMSpecs specs{};
vm.take_snapshot(specs, "foo", "");
vm.take_snapshot(specs, "bar", "this and that");
vm.delete_snapshot("foo");
vm.take_snapshot(specs, "baz", "this and that");
for (const auto i : {2, 3})
{
EXPECT_THAT(vm.get_snapshot(i), Pointee(Property(&mp::Snapshot::get_index, Eq(i))));
}
}
TEST_F(BaseVM, providesSnapshotsByName)
{
mock_snapshotting();
const mp::VMSpecs specs{};
const std::string target_name = "pick";
vm.take_snapshot(specs, "foo", "irrelevant");
vm.take_snapshot(specs, target_name, "fetch me");
vm.take_snapshot(specs, "bar", "whatever");
vm.take_snapshot(specs, "baz", "");
vm.delete_snapshot("bar");
vm.take_snapshot(specs, "asdf", "");
EXPECT_THAT(vm.get_snapshot(target_name), Pointee(Property(&mp::Snapshot::get_name, Eq(target_name))));
}
TEST_F(BaseVM, logsSnapshotHead)
{
mock_snapshotting();
const auto name = "asdf";
auto logger_scope = mpt::MockLogger::inject(mpl::Level::debug);
logger_scope.mock_logger->expect_log(mpl::Level::debug, name);
vm.take_snapshot({}, name, "");
}
TEST_F(BaseVM, generatesSnapshotNameFromTotalCount)
{
mock_snapshotting();
mp::VMSpecs specs{};
for (int i = 1; i <= 5; ++i)
{
vm.take_snapshot(specs, "", "");
EXPECT_EQ(vm.get_snapshot(i)->get_name(), fmt::format("snapshot{}", i));
}
}
TEST_F(BaseVM, throwsOnMissingSnapshotByIndex)
{
mock_snapshotting();
auto expect_throw = [this](int i) {
MP_EXPECT_THROW_THAT(vm.get_snapshot(i),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr(vm.vm_name), HasSubstr(std::to_string(i)))));
};
for (int i = -2; i < 4; ++i)
expect_throw(i);
const mp::VMSpecs specs{};
vm.take_snapshot(specs, "foo", "I know kung fu");
vm.take_snapshot(specs, "bar", "blue pill");
vm.take_snapshot(specs, "baz", "red pill");
for (int i : {-2, -1, 0, 4, 5, 100})
expect_throw(i);
}
TEST_F(BaseVM, throwsOnMissingSnapshotByName)
{
mock_snapshotting();
auto expect_throws = [this]() {
std::array<std::string, 3> missing_names = {"neo", "morpheus", "trinity"};
for (const auto& name : missing_names)
{
MP_EXPECT_THROW_THAT(vm.get_snapshot(name),
mp::NoSuchSnapshotException,
mpt::match_what(AllOf(HasSubstr(vm.vm_name), HasSubstr(name))));
}
};
expect_throws();
const mp::VMSpecs specs{};
vm.take_snapshot(specs, "smith", "");
vm.take_snapshot(specs, "johnson", "");
vm.take_snapshot(specs, "jones", "");
expect_throws();
}
TEST_F(BaseVM, throwsOnRepeatedSnapshotName)
{
mock_snapshotting();
const mp::VMSpecs specs{};
auto repeated_given_name = "asdf";
auto repeated_derived_name = "snapshot3";
vm.take_snapshot(specs, repeated_given_name, "");
vm.take_snapshot(specs, repeated_derived_name, "");
MP_ASSERT_THROW_THAT(vm.take_snapshot(specs, repeated_given_name, ""),
mp::SnapshotNameTakenException,
mpt::match_what(HasSubstr(repeated_given_name)));
MP_EXPECT_THROW_THAT(vm.take_snapshot(specs, "", ""), // this would be the third snapshot
mp::SnapshotNameTakenException,
mpt::match_what(HasSubstr(repeated_derived_name)));
}
TEST_F(BaseVM, snapshotDeletionUpdatesParents)
{
mock_snapshotting();
const auto num_snapshots = 3;
const mp::VMSpecs specs{};
for (int i = 0; i < num_snapshots; ++i)
vm.take_snapshot(specs, "", "");
ASSERT_EQ(snapshot_album.size(), num_snapshots);
EXPECT_CALL(*snapshot_album[2], set_parent(Eq(snapshot_album[0]))).Times(1);
vm.delete_snapshot(snapshot_album[1]->get_name());
}
TEST_F(BaseVM, snapshotDeletionThrowsOnMissingSnapshot)
{
const auto name = "missing";
MP_EXPECT_THROW_THAT(vm.delete_snapshot(name),
mp::NoSuchSnapshotException,
mpt::match_what(AllOf(HasSubstr(vm.vm_name), HasSubstr(name))));
}
TEST_F(BaseVM, providesChildrenNames)
{
mock_snapshotting();
const auto name_template = "s{}";
const auto num_snapshots = 5;
const mp::VMSpecs specs{};
for (int i = 0; i < num_snapshots; ++i)
vm.take_snapshot(specs, fmt::format(name_template, i), "");
ASSERT_EQ(snapshot_album.size(), num_snapshots);
std::vector<std::string> expected_children_names{};
for (int i = 1; i < num_snapshots; ++i)
{
EXPECT_CALL(Const(*snapshot_album[i]), get_parent()).WillRepeatedly(Return(snapshot_album[0]));
expected_children_names.push_back(fmt::format(name_template, i));
}
EXPECT_THAT(vm.get_childrens_names(snapshot_album[0].get()), UnorderedElementsAreArray(expected_children_names));
for (int i = 1; i < num_snapshots; ++i)
{
EXPECT_THAT(vm.get_childrens_names(snapshot_album[i].get()), IsEmpty());
}
}
TEST_F(BaseVM, renamesSnapshot)
{
const std::string old_name = "initial";
const std::string new_name = "renamed";
std::string current_name = old_name;
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*snapshot, get_name()).WillRepeatedly(ReturnPointee(¤t_name));
EXPECT_CALL(vm, make_specific_snapshot(_, _, _, _, _)).WillOnce(Return(snapshot));
vm.take_snapshot({}, old_name, "as ;lklkh afa");
EXPECT_CALL(*snapshot, set_name(Eq(new_name))).WillOnce(Assign(¤t_name, new_name));
vm.rename_snapshot(old_name, new_name);
EXPECT_EQ(vm.get_snapshot(new_name), snapshot);
}
TEST_F(BaseVM, skipsSnapshotRenamingWithIdenticalName)
{
mock_snapshotting();
const auto* name = "fixed";
vm.take_snapshot({}, name, "not changing");
ASSERT_EQ(snapshot_album.size(), 1);
EXPECT_CALL(*snapshot_album[0], set_name).Times(0);
EXPECT_NO_THROW(vm.rename_snapshot(name, name));
EXPECT_EQ(vm.get_snapshot(name), snapshot_album[0]);
}
TEST_F(BaseVM, throwsOnRequestToRenameMissingSnapshot)
{
mock_snapshotting();
const auto* good_name = "Mafalda";
const auto* missing_name = "Gui";
vm.take_snapshot({}, good_name, "");
ASSERT_EQ(snapshot_album.size(), 1);
EXPECT_CALL(*snapshot_album[0], set_name).Times(0);
MP_EXPECT_THROW_THAT(vm.rename_snapshot(missing_name, "Filipe"),
mp::NoSuchSnapshotException,
mpt::match_what(AllOf(HasSubstr(vm.vm_name), HasSubstr(missing_name))));
EXPECT_EQ(vm.get_snapshot(good_name), snapshot_album[0]);
}
TEST_F(BaseVM, throwsOnRequestToRenameSnapshotWithRepeatedName)
{
mock_snapshotting();
const auto names = std::array{"Mafalda", "Gui"};
mp::VMSpecs specs{};
vm.take_snapshot(specs, names[0], "");
vm.take_snapshot(specs, names[1], "");
ASSERT_EQ(snapshot_album.size(), 2);
EXPECT_CALL(*snapshot_album[0], set_name).Times(0);
MP_EXPECT_THROW_THAT(vm.rename_snapshot(names[0], names[1]),
mp::SnapshotNameTakenException,
mpt::match_what(AllOf(HasSubstr(vm.vm_name), HasSubstr(names[1]))));
MP_EXPECT_THROW_THAT(vm.rename_snapshot(names[1], names[0]),
mp::SnapshotNameTakenException,
mpt::match_what(AllOf(HasSubstr(vm.vm_name), HasSubstr(names[0]))));
EXPECT_EQ(vm.get_snapshot(names[0]), snapshot_album[0]);
EXPECT_EQ(vm.get_snapshot(names[1]), snapshot_album[1]);
}
TEST_F(BaseVM, restoresSnapshots)
{
mock_snapshotting();
mp::VMMount mount{"src", {}, {}, mp::VMMount::MountType::Classic};
QJsonObject metadata{};
metadata["meta"] = "data";
const mp::VMSpecs original_specs{2,
mp::MemorySize{"3.5G"},
mp::MemorySize{"15G"},
"12:12:12:12:12:12",
{},
"user",
St::off,
{{"dst", mount}},
false,
metadata};
const auto* snapshot_name = "shoot";
vm.take_snapshot(original_specs, snapshot_name, "");
ASSERT_EQ(snapshot_album.size(), 1);
auto& snapshot = *snapshot_album[0];
mp::VMSpecs changed_specs = original_specs;
changed_specs.num_cores = 3;
changed_specs.mem_size = mp::MemorySize{"5G"};
changed_specs.disk_space = mp::MemorySize{"35G"};
changed_specs.state = St::stopped;
changed_specs.mounts.clear();
changed_specs.metadata["data"] = "meta";
changed_specs.metadata["meta"] = "toto";
EXPECT_CALL(snapshot, apply);
EXPECT_CALL(snapshot, get_state).WillRepeatedly(Return(original_specs.state));
EXPECT_CALL(snapshot, get_num_cores).WillRepeatedly(Return(original_specs.num_cores));
EXPECT_CALL(snapshot, get_mem_size).WillRepeatedly(Return(original_specs.mem_size));
EXPECT_CALL(snapshot, get_disk_space).WillRepeatedly(Return(original_specs.disk_space));
EXPECT_CALL(snapshot, get_mounts).WillRepeatedly(ReturnRef(original_specs.mounts));
EXPECT_CALL(snapshot, get_metadata).WillRepeatedly(ReturnRef(original_specs.metadata));
vm.restore_snapshot(snapshot_name, changed_specs);
EXPECT_EQ(original_specs, changed_specs);
}
TEST_F(BaseVM, restoresSnapshotsWithExtraInterfaceDiff)
{
mock_snapshotting();
// default value of VMSpecs::state is off, so restore_snapshot will pass the assert_vm_stopped check, the other
// fields do not matter, and VMSpecs::extra_interfaces is defaulted to be empty, which is we want.
const mp::VMSpecs original_specs{};
const auto* snapshot_name = "snapshot1";
vm.take_snapshot(original_specs, snapshot_name, "");
ASSERT_EQ(snapshot_album.size(), 1);
const auto& snapshot = *snapshot_album[0];
mp::VMSpecs new_specs = original_specs;
new_specs.extra_interfaces =
std::vector<mp::NetworkInterface>{{"id", "52:54:00:56:78:91", true}, {"id", "52:54:00:56:78:92", true}};
// the ref return functions can not use the default mock behavior, so they need to be specified
EXPECT_CALL(snapshot, get_mounts).WillOnce(ReturnRef(original_specs.mounts));
EXPECT_CALL(snapshot, get_metadata).WillOnce(ReturnRef(original_specs.metadata));
// set the behavior of get_extra_interfaces to cause the difference to the new space extra interfaces
EXPECT_CALL(snapshot, get_extra_interfaces).Times(3).WillRepeatedly(Return(original_specs.extra_interfaces));
EXPECT_CALL(*mock_cloud_init_file_ops_injection.first,
update_cloud_init_with_new_extra_interfaces_and_new_id(_, _, _, _))
.Times(1);
vm.restore_snapshot(snapshot_name, new_specs);
EXPECT_EQ(original_specs, new_specs);
}
TEST_F(BaseVM, usesRestoredSnapshotAsParentForNewSnapshots)
{
mock_snapshotting();
mp::VMSpecs specs{};
const std::string root_name{"first"};
vm.take_snapshot(specs, root_name, "");
auto root_snapshot = snapshot_album[0];
ASSERT_EQ(snapshot_album.size(), 1);
EXPECT_EQ(vm.take_snapshot(specs, "second", "")->get_parent(), root_snapshot);
ASSERT_EQ(snapshot_album.size(), 2);
EXPECT_EQ(vm.take_snapshot(specs, "third", "")->get_parent().get(), snapshot_album[1].get());
std::unordered_map<std::string, mp::VMMount> mounts;
EXPECT_CALL(*root_snapshot, get_mounts).WillRepeatedly(ReturnRef(mounts));
QJsonObject metadata{};
EXPECT_CALL(*root_snapshot, get_metadata).WillRepeatedly(ReturnRef(metadata));
vm.restore_snapshot(root_name, specs);
EXPECT_EQ(vm.take_snapshot(specs, "fourth", "")->get_parent(), root_snapshot);
}
TEST_F(BaseVM, loadSnasphotThrowsIfSnapshotsNotImplemented)
{
StubBaseVirtualMachine stub{};
mpt::make_file_with_content(stub.tmp_dir->filePath("0001.snapshot.json"), "whatever-content");
MP_EXPECT_THROW_THAT(stub.load_snapshots(),
mp::NotImplementedOnThisBackendException,
mpt::match_what(HasSubstr("snapshots")));
}
using SpacePadding = std::tuple<std::string, std::string>;
struct TestLoadingOfPaddedGenericSnapshotInfo : public BaseVM, WithParamInterface<SpacePadding>
{
void SetUp() override
{
static const auto space_matcher = MatchesRegex(fmt::format("{}*", space_char_class));
ASSERT_THAT(padding_left, space_matcher);
ASSERT_THAT(padding_right, space_matcher);
}
const std::string& padding_left = std::get<0>(GetParam());
const std::string& padding_right = std::get<1>(GetParam());
};
TEST_P(TestLoadingOfPaddedGenericSnapshotInfo, loadsAndUsesTotalSnapshotCount)
{
mock_snapshotting();
int initial_count = 42;
auto count_text = fmt::format("{}{}{}", padding_left, initial_count, padding_right);
mpt::make_file_with_content(count_path, count_text);
EXPECT_NO_THROW(vm.load_snapshots());
mp::VMSpecs specs{};
for (int i = 1; i <= 5; ++i)
{
int expected_idx = initial_count + i;
vm.take_snapshot(specs, "", "");
EXPECT_EQ(vm.get_snapshot(expected_idx)->get_name(), fmt::format("snapshot{}", expected_idx));
}
}
TEST_P(TestLoadingOfPaddedGenericSnapshotInfo, loadsAndUsesSnapshotHeadIndex)
{
mock_snapshotting();
int head_index = 13;
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(vm, get_snapshot(head_index)).WillOnce(Return(snapshot));
auto head_text = fmt::format("{}{}{}", padding_left, head_index, padding_right);
mpt::make_file_with_content(head_path, head_text);
mpt::make_file_with_content(count_path, "31");
EXPECT_NO_THROW(vm.load_snapshots());
auto name = "julius";
vm.take_snapshot({}, name, "");
EXPECT_EQ(vm.get_snapshot(name)->get_parent(), snapshot);
}
std::vector<std::string> space_paddings = {"", " ", " ", "\n", " \n", "\n\n\n", "\t", "\t\t\t", "\t \n \t "};
INSTANTIATE_TEST_SUITE_P(BaseVM,
TestLoadingOfPaddedGenericSnapshotInfo,
Combine(ValuesIn(space_paddings), ValuesIn(space_paddings)));
TEST_F(BaseVM, loadsSnasphots)
{
static constexpr auto num_snapshots = 5;
static constexpr auto name_prefix = "blankpage";
static constexpr auto generate_snapshot_name = [](int count) { return fmt::format("{}{}", name_prefix, count); };
static const auto index_digits_regex = n_occurrences(digit_char_class, 4);
static const auto file_regex = fmt::format(R"(.*{}\.snapshot\.json)", index_digits_regex);
auto& expectation = EXPECT_CALL(vm, make_specific_snapshot(mpt::match_qstring(MatchesRegex(file_regex))));
using NiceMockSnapshot = NiceMock<mpt::MockSnapshot>;
std::array<std::shared_ptr<NiceMockSnapshot>, num_snapshots> snapshot_bag{};
generate(snapshot_bag.begin(), snapshot_bag.end(), [this, &expectation] {
static int idx = 1;
mpt::make_file_with_content(get_snapshot_file_path(idx), "stub");
auto ret = std::make_shared<NiceMockSnapshot>();
EXPECT_CALL(*ret, get_index).WillRepeatedly(Return(idx));
EXPECT_CALL(*ret, get_name).WillRepeatedly(Return(generate_snapshot_name(idx++)));
expectation.WillOnce(Return(ret));
return ret;
});
mpt::make_file_with_content(head_path, fmt::format("{}", num_snapshots));
mpt::make_file_with_content(count_path, fmt::format("{}", num_snapshots));
EXPECT_NO_THROW(vm.load_snapshots());
for (int i = 0; i < num_snapshots; ++i)
{
const auto idx = i + 1;
EXPECT_EQ(vm.get_snapshot(idx)->get_name(), generate_snapshot_name(idx));
}
}
TEST_F(BaseVM, throwsIfThereAreSnapshotsToLoadButNoGenericInfo)
{
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
const auto name = "snapshot1";
EXPECT_CALL(*snapshot, get_name).WillRepeatedly(Return(name));
EXPECT_CALL(*snapshot, get_index).WillRepeatedly(Return(1));
EXPECT_CALL(vm, make_specific_snapshot(_)).Times(2).WillRepeatedly(Return(snapshot));
mpt::make_file_with_content(get_snapshot_file_path(1), "stub");
MP_EXPECT_THROW_THAT(vm.load_snapshots(), mp::FileOpenFailedException, mpt::match_what(HasSubstr(count_filename)));
vm.delete_snapshot(name);
mpt::make_file_with_content(count_path, "1");
MP_EXPECT_THROW_THAT(vm.load_snapshots(), mp::FileOpenFailedException, mpt::match_what(HasSubstr(head_filename)));
}
TEST_F(BaseVM, throwsIfLoadedSnapshotsNameIsTaken)
{
const auto common_name = "common";
auto snapshot1 = std::make_shared<NiceMock<mpt::MockSnapshot>>();
auto snapshot2 = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*snapshot1, get_name).WillRepeatedly(Return(common_name));
EXPECT_CALL(*snapshot1, get_index).WillRepeatedly(Return(1));
EXPECT_CALL(*snapshot2, get_name).WillRepeatedly(Return(common_name));
EXPECT_CALL(*snapshot2, get_index).WillRepeatedly(Return(2));
EXPECT_CALL(vm, make_specific_snapshot(_)).WillOnce(Return(snapshot1)).WillOnce(Return(snapshot2));
mpt::make_file_with_content(get_snapshot_file_path(1), "stub");
mpt::make_file_with_content(get_snapshot_file_path(2), "stub");
mpt::make_file_with_content(head_path, "1");
mpt::make_file_with_content(count_path, "2");
MP_EXPECT_THROW_THAT(vm.load_snapshots(), mp::SnapshotNameTakenException, mpt::match_what(HasSubstr(common_name)));
}
TEST_F(BaseVM, snapshotDeletionRestoresParentsOnFailure)
{
mock_snapshotting();
const auto num_snapshots = 3;
const mp::VMSpecs specs{};
for (int i = 0; i < num_snapshots; ++i)
vm.take_snapshot(specs, "", "");
ASSERT_EQ(snapshot_album.size(), num_snapshots);
EXPECT_CALL(*snapshot_album[2], set_parent(Eq(snapshot_album[0]))).Times(1);
EXPECT_CALL(*snapshot_album[2], set_parent(Eq(snapshot_album[1]))).Times(1); // rollback
EXPECT_CALL(*snapshot_album[1], erase).WillOnce(Throw(std::runtime_error{"intentional"}));
EXPECT_ANY_THROW(vm.delete_snapshot(snapshot_album[1]->get_name()));
}
TEST_F(BaseVM, snapshotDeletionKeepsHeadOnFailure)
{
mock_snapshotting();
mp::VMSpecs specs{};
vm.take_snapshot(specs, "", "");
vm.take_snapshot(specs, "", "");
ASSERT_EQ(snapshot_album.size(), 2);
EXPECT_CALL(*snapshot_album[1], erase).WillOnce(Throw(std::runtime_error{"intentional"}));
EXPECT_ANY_THROW(vm.delete_snapshot(snapshot_album[1]->get_name()));
EXPECT_EQ(vm.take_snapshot(specs, "", "")->get_parent().get(), snapshot_album[1].get());
}
TEST_F(BaseVM, takeSnapshotRevertsToNullHeadOnFirstFailure)
{
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*snapshot, capture).WillOnce(Throw(std::runtime_error{"intentional"}));
EXPECT_CALL(vm, make_specific_snapshot(_, _, _, _, _)).WillOnce(Return(snapshot)).RetiresOnSaturation();
mp::VMSpecs specs{};
EXPECT_ANY_THROW(vm.take_snapshot(specs, "", ""));
mock_snapshotting();
EXPECT_EQ(vm.take_snapshot(specs, "", "")->get_parent().get(), nullptr);
}
TEST_F(BaseVM, takeSnapshotRevertsHeadAndCount)
{
auto early_snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*early_snapshot, get_name).WillRepeatedly(Return("asdf"));
EXPECT_CALL(*early_snapshot, get_index).WillRepeatedly(Return(1));
EXPECT_CALL(vm, make_specific_snapshot(_)).WillOnce(Return(early_snapshot));
mpt::make_file_with_content(get_snapshot_file_path(1), "stub");
mpt::make_file_with_content(head_path, "1");
mpt::make_file_with_content(count_path, "1");
vm.load_snapshots();
constexpr auto attempted_name = "fdsa";
auto failing_snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*failing_snapshot, get_name).WillRepeatedly(Return(attempted_name));
EXPECT_CALL(*failing_snapshot, get_index).WillRepeatedly(Return(2));
EXPECT_CALL(*failing_snapshot, get_parents_index)
.WillOnce(Throw(std::runtime_error{"intentional"})) // causes persisting to break, after successful capture
.RetiresOnSaturation();
EXPECT_CALL(vm, make_specific_snapshot(_, _, _, _, _)).WillOnce(Return(failing_snapshot)).RetiresOnSaturation();
mp::VMSpecs specs{};
EXPECT_ANY_THROW(vm.take_snapshot(specs, attempted_name, ""));
mock_snapshotting();
auto new_snapshot = vm.take_snapshot(specs, attempted_name, "");
EXPECT_EQ(new_snapshot->get_parent(), early_snapshot);
EXPECT_EQ(new_snapshot->get_index(), 2); // snapshot count not increased by failed snapshot
}
TEST_F(BaseVM, renameFailureIsReverted)
{
std::string current_name = "before";
std::string attempted_name = "after";
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*snapshot, get_name()).WillRepeatedly(Return(current_name));
EXPECT_CALL(vm, make_specific_snapshot(_, _, _, _, _)).WillOnce(Return(snapshot));
vm.take_snapshot({}, current_name, "");
EXPECT_CALL(*snapshot, set_name(Eq(attempted_name))).WillOnce(Throw(std::runtime_error{"intentional"}));
EXPECT_ANY_THROW(vm.rename_snapshot(current_name, attempted_name));
EXPECT_EQ(vm.get_snapshot(current_name), snapshot);
}
TEST_F(BaseVM, persistsGenericSnapshotInfoWhenTakingSnapshot)
{
mock_snapshotting();
ASSERT_EQ(vm.get_snapshot_count(), 0);
ASSERT_FALSE(QFileInfo{head_path}.exists());
ASSERT_FALSE(QFileInfo{count_path}.exists());
mp::VMSpecs specs{};
for (int i = 1; i < 5; ++i)
{
vm.take_snapshot(specs, "", "");
ASSERT_TRUE(QFileInfo{head_path}.exists());
ASSERT_TRUE(QFileInfo{count_path}.exists());
auto regex_matcher = make_index_file_contents_matcher(i);
EXPECT_THAT(mpt::load(head_path).toStdString(), regex_matcher);
EXPECT_THAT(mpt::load(count_path).toStdString(), regex_matcher);
}
}
TEST_F(BaseVM, removesGenericSnapshotInfoFilesOnFirstFailure)
{
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject();
auto& mock_utils = *mock_utils_ptr;
mock_snapshotting();
ASSERT_FALSE(QFileInfo{head_path}.exists());
ASSERT_FALSE(QFileInfo{count_path}.exists());
MP_DELEGATE_MOCK_CALLS_ON_BASE_WITH_MATCHERS(mock_utils,
make_file_with_content,
mp::Utils,
(EndsWith(head_filename), _, Eq(true)));
EXPECT_CALL(mock_utils, make_file_with_content(EndsWith(head_filename), _, Eq(true)));
EXPECT_CALL(mock_utils, make_file_with_content(EndsWith(count_filename), _, Eq(true)))
.WillOnce(Throw(std::runtime_error{"intentional"}));
EXPECT_ANY_THROW(vm.take_snapshot({}, "", ""));
EXPECT_FALSE(QFileInfo{head_path}.exists());
EXPECT_FALSE(QFileInfo{count_path}.exists());
}
TEST_F(BaseVM, restoresGenericSnapshotInfoFileContents)
{
mock_snapshotting();
mp::VMSpecs specs{};
vm.take_snapshot(specs, "", "");
ASSERT_TRUE(QFileInfo{head_path}.exists());
ASSERT_TRUE(QFileInfo{count_path}.exists());
auto regex_matcher = make_index_file_contents_matcher(1);
EXPECT_THAT(mpt::load(head_path).toStdString(), regex_matcher);
EXPECT_THAT(mpt::load(count_path).toStdString(), regex_matcher);
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject<NiceMock>();
auto& mock_utils = *mock_utils_ptr;
MP_DELEGATE_MOCK_CALLS_ON_BASE_WITH_MATCHERS(mock_utils, make_file_with_content, mp::Utils, (_, _, Eq(true)));
EXPECT_CALL(mock_utils, make_file_with_content(EndsWith(head_filename), _, Eq(true))).Times(2);
EXPECT_CALL(mock_utils, make_file_with_content(EndsWith(count_filename), _, Eq(true)))
.WillOnce(Throw(std::runtime_error{"intentional"}))
.WillOnce(DoDefault());
EXPECT_ANY_THROW(vm.take_snapshot({}, "", ""));
EXPECT_TRUE(QFileInfo{head_path}.exists());
EXPECT_TRUE(QFileInfo{count_path}.exists());
EXPECT_THAT(mpt::load(head_path).toStdString(), regex_matcher);
EXPECT_THAT(mpt::load(count_path).toStdString(), regex_matcher);
}
TEST_F(BaseVM, persistsHeadIndexOnRestore)
{
mock_snapshotting();
mp::VMSpecs specs{};
const auto intended_snapshot = "this-one";
vm.take_snapshot(specs, "foo", "");
vm.take_snapshot(specs, intended_snapshot, "");
vm.take_snapshot(specs, "bar", "");
std::unordered_map<std::string, mp::VMMount> mounts;
EXPECT_CALL(*snapshot_album[1], get_mounts).WillRepeatedly(ReturnRef(mounts));
QJsonObject metadata{};
EXPECT_CALL(*snapshot_album[1], get_metadata).WillRepeatedly(ReturnRef(metadata));
vm.restore_snapshot(intended_snapshot, specs);
EXPECT_TRUE(QFileInfo{head_path}.exists());
auto regex_matcher = make_index_file_contents_matcher(snapshot_album[1]->get_index());
EXPECT_THAT(mpt::load(head_path).toStdString(), regex_matcher);
}
TEST_F(BaseVM, rollsbackFailedRestore)
{
mock_snapshotting();
const mp::VMSpecs original_specs{1,
mp::MemorySize{"1.5G"},
mp::MemorySize{"4G"},
"ab:ab:ab:ab:ab:ab",
{},
"me",
St::off,
{},
false,
{}};
vm.take_snapshot(original_specs, "", "");
auto target_snapshot_name = "this one";
vm.take_snapshot(original_specs, target_snapshot_name, "");
vm.take_snapshot(original_specs, "", "");
ASSERT_EQ(snapshot_album.size(), 3);
auto& target_snapshot = *snapshot_album[1];
auto& last_snapshot = *snapshot_album[2];
mp::VMMount mount{"src", {}, {}, mp::VMMount::MountType::Classic};
auto changed_specs = original_specs;
changed_specs.num_cores = 4;
changed_specs.mem_size = mp::MemorySize{"2G"};
changed_specs.state = multipass::VirtualMachine::State::running;
changed_specs.mounts["dst"] = mount;
changed_specs.metadata["blah"] = "this and that";
EXPECT_CALL(target_snapshot, get_state).WillRepeatedly(Return(original_specs.state));
EXPECT_CALL(target_snapshot, get_num_cores).WillRepeatedly(Return(original_specs.num_cores));
EXPECT_CALL(target_snapshot, get_mem_size).WillRepeatedly(Return(original_specs.mem_size));
EXPECT_CALL(target_snapshot, get_disk_space).WillRepeatedly(Return(original_specs.disk_space));
EXPECT_CALL(target_snapshot, get_mounts).WillRepeatedly(ReturnRef(original_specs.mounts));
EXPECT_CALL(target_snapshot, get_metadata).WillRepeatedly(ReturnRef(original_specs.metadata));
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject();
EXPECT_CALL(*mock_utils_ptr, make_file_with_content(_, _, _))
.WillOnce(Throw(std::runtime_error{"intentional"}))
.WillRepeatedly(DoDefault());
auto current_specs = changed_specs;
EXPECT_ANY_THROW(vm.restore_snapshot(target_snapshot_name, current_specs));
EXPECT_EQ(changed_specs, current_specs);
auto regex_matcher = make_index_file_contents_matcher(last_snapshot.get_index());
EXPECT_THAT(mpt::load(head_path).toStdString(), regex_matcher);
EXPECT_EQ(vm.take_snapshot(current_specs, "", "")->get_parent().get(), &last_snapshot);
}
TEST_F(BaseVM, waitForCloudInitNoErrorsAndDoneDoesNotThrow)
{
vm.simulate_cloud_init();
EXPECT_CALL(vm, ensure_vm_is_running()).WillRepeatedly(Return());
EXPECT_CALL(vm, ssh_exec).WillOnce(DoDefault());
std::chrono::milliseconds timeout(1);
EXPECT_NO_THROW(vm.wait_for_cloud_init(timeout));
}
TEST_F(BaseVM, waitForCloudInitErrorTimesOutThrows)
{
vm.simulate_cloud_init();
EXPECT_CALL(vm, ensure_vm_is_running()).WillRepeatedly(Return());
EXPECT_CALL(vm, ssh_exec).WillOnce(Throw(mp::SSHExecFailure{"no worky", 1}));
std::chrono::milliseconds timeout(1);
MP_EXPECT_THROW_THAT(vm.wait_for_cloud_init(timeout),
std::runtime_error,
mpt::match_what(StrEq("timed out waiting for initialization to complete")));
}
TEST_F(BaseVM, waitForSSHUpThrowsOnTimeout)
{
vm.simulate_waiting_for_ssh();
EXPECT_CALL(vm, ssh_hostname(_)).WillOnce(Throw(std::runtime_error{"intentional"}));
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject();
auto& mock_utils = *mock_utils_ptr;
MP_DELEGATE_MOCK_CALLS_ON_BASE(mock_utils, sleep_for, mp::Utils);
MP_EXPECT_THROW_THAT(vm.wait_until_ssh_up(std::chrono::milliseconds{1}),
std::runtime_error,
mpt::match_what(HasSubstr("timed out waiting for response")));
}
using ExceptionParam =
std::variant<std::runtime_error, mp::IPUnavailableException, mp::SSHException, mp::InternalTimeoutException>;
class TestWaitForSSHExceptions : public BaseVM, public WithParamInterface<ExceptionParam>
{
};
TEST_P(TestWaitForSSHExceptions, waitForSSHUpRetriesOnExpectedException)
{
static constexpr auto thrower = [](const auto& e) { throw e; };
vm.simulate_waiting_for_ssh();
EXPECT_CALL(vm, ensure_vm_is_running()).WillRepeatedly(Return());
EXPECT_CALL(vm, update_state()).WillRepeatedly(Return());
auto timeout = std::chrono::milliseconds{100};
EXPECT_CALL(vm, ssh_hostname(_))
.WillOnce(WithoutArgs([]() {
std::visit(thrower, GetParam());
return "neverland";
}))
.WillRepeatedly(Return("underworld"));
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject();
EXPECT_CALL(*mock_utils_ptr, sleep_for(_)).WillRepeatedly(Return());
EXPECT_NO_THROW(vm.wait_until_ssh_up(timeout));
}
INSTANTIATE_TEST_SUITE_P(TestWaitForSSHExceptions,
TestWaitForSSHExceptions,
Values(std::runtime_error{"todo-remove-eventually"},
mp::IPUnavailableException{"noip"},
mp::SSHException{"nossh"},
mp::InternalTimeoutException{"notime", std::chrono::seconds{1}}));
TEST_F(BaseVM, sshExecRefusesToExecuteIfVMIsNotRunning)
{
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject();
EXPECT_CALL(*mock_utils_ptr, is_running).WillRepeatedly(Return(false));
EXPECT_CALL(*mock_utils_ptr, run_in_ssh_session).Times(0);
vm.simulate_ssh_exec();
MP_EXPECT_THROW_THAT(vm.ssh_exec("echo"), mp::SSHException, mpt::match_what(HasSubstr("not running")));
}
TEST_F(BaseVM, sshExecRunsDirectlyIfConnected)
{
static constexpr auto* cmd = ":";
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject();
EXPECT_CALL(*mock_utils_ptr, is_running).WillOnce(Return(true));
EXPECT_CALL(*mock_utils_ptr, run_in_ssh_session(_, cmd, _)).Times(1);
vm.simulate_ssh_exec();
vm.renew_ssh_session();
EXPECT_NO_THROW(vm.ssh_exec(cmd));
}
TEST_F(BaseVM, sshExecReconnectsIfDisconnected)
{
static constexpr auto* cmd = ":";
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject();
EXPECT_CALL(*mock_utils_ptr, is_running).WillOnce(Return(true));
EXPECT_CALL(*mock_utils_ptr, run_in_ssh_session(_, cmd, _)).Times(1);
vm.simulate_ssh_exec();
EXPECT_NO_THROW(vm.ssh_exec(cmd));
}
TEST_F(BaseVM, sshExecTriesToReconnectAfterLateDetectionOfDisconnection)
{
static constexpr auto* cmd = ":";
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject();
EXPECT_CALL(*mock_utils_ptr, is_running).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_utils_ptr, run_in_ssh_session(_, cmd, _))
.WillOnce(Throw(mp::SSHException{"intentional"}))
.WillOnce(DoDefault());
vm.simulate_ssh_exec();
vm.renew_ssh_session();
mock_ssh_test_fixture.is_connected.returnValue(true, false, false);
EXPECT_NO_THROW(vm.ssh_exec(cmd));
}
TEST_F(BaseVM, sshExecRethrowsOtherExceptions)
{
static constexpr auto* cmd = ":";
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject();
EXPECT_CALL(*mock_utils_ptr, is_running).WillOnce(Return(true));
EXPECT_CALL(*mock_utils_ptr, run_in_ssh_session(_, cmd, _)).WillOnce(Throw(std::runtime_error{"intentional"}));
vm.simulate_ssh_exec();
vm.renew_ssh_session();
MP_EXPECT_THROW_THAT(vm.ssh_exec(cmd), std::runtime_error, mpt::match_what(HasSubstr("intentional")));
}
TEST_F(BaseVM, sshExecRethrowsSSHExceptionsWhenConnected)
{
static constexpr auto* cmd = ":";
auto [mock_utils_ptr, guard] = mpt::MockUtils::inject();
EXPECT_CALL(*mock_utils_ptr, is_running).WillOnce(Return(true));
EXPECT_CALL(*mock_utils_ptr, run_in_ssh_session(_, cmd, _)).WillOnce(Throw(mp::SSHException{"intentional"}));
vm.simulate_ssh_exec();
vm.renew_ssh_session();
MP_EXPECT_THROW_THAT(vm.ssh_exec(cmd), mp::SSHException, mpt::match_what(HasSubstr("intentional")));
}
} // namespace
| 49,310
|
C++
|
.cpp
| 1,088
| 38.558824
| 119
| 0.654633
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,572
|
test_utils.cpp
|
canonical_multipass/tests/test_utils.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "file_operations.h"
#include "mock_file_ops.h"
#include "mock_logger.h"
#include "mock_openssl_syscalls.h"
#include "mock_ssh.h"
#include "mock_ssh_process_exit_status.h"
#include "mock_ssh_test_fixture.h"
#include "mock_virtual_machine.h"
#include "stub_ssh_key_provider.h"
#include "temp_dir.h"
#include "temp_file.h"
#include <multipass/format.h>
#include <multipass/utils.h>
#include <multipass/vm_image_vault.h>
#include <QRegularExpression>
#include <gtest/gtest-death-test.h>
#include <sstream>
#include <string>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
namespace mpu = mp::utils;
using namespace testing;
namespace
{
std::string file_contents{"line 1 of file contents\nline 2\n"};
void check_file_contents(QFile& checked_file, const std::string& checked_contents)
{
checked_file.open(QIODevice::ReadOnly | QIODevice::Text);
QString actual_contents;
while (!checked_file.atEnd())
actual_contents += checked_file.readLine();
checked_file.close();
ASSERT_EQ(checked_contents, actual_contents.toStdString());
}
} // namespace
TEST(Utils, hostname_begins_with_letter_is_valid)
{
EXPECT_TRUE(mp::utils::valid_hostname("foo"));
}
TEST(Utils, hostname_single_letter_is_valid)
{
EXPECT_TRUE(mp::utils::valid_hostname("f"));
}
TEST(Utils, hostname_contains_digit_is_valid)
{
EXPECT_TRUE(mp::utils::valid_hostname("foo1"));
}
TEST(Utils, hostname_contains_hyphen_is_valid)
{
EXPECT_TRUE(mp::utils::valid_hostname("foo-bar"));
}
TEST(Utils, hostname_begins_with_digit_is_invalid)
{
EXPECT_FALSE(mp::utils::valid_hostname("1foo"));
}
TEST(Utils, hostname_single_digit_is_invalid)
{
EXPECT_FALSE(mp::utils::valid_hostname("1"));
}
TEST(Utils, hostname_contains_underscore_is_invalid)
{
EXPECT_FALSE(mp::utils::valid_hostname("foo_bar"));
}
TEST(Utils, hostname_contains_special_character_is_invalid)
{
EXPECT_FALSE(mp::utils::valid_hostname("foo!"));
}
TEST(Utils, path_root_invalid)
{
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//")));
}
TEST(Utils, path_root_foo_valid)
{
EXPECT_FALSE(mp::utils::invalid_target_path(QString("/foo")));
EXPECT_FALSE(mp::utils::invalid_target_path(QString("/foo/")));
EXPECT_FALSE(mp::utils::invalid_target_path(QString("//foo")));
}
TEST(Utils, path_dev_invalid)
{
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/dev")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/dev/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//dev/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/dev//")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//dev//")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/dev/foo")));
}
TEST(Utils, path_devpath_valid)
{
EXPECT_FALSE(mp::utils::invalid_target_path(QString("/devpath")));
EXPECT_FALSE(mp::utils::invalid_target_path(QString("/devpath/")));
EXPECT_FALSE(mp::utils::invalid_target_path(QString("/devpath/foo")));
}
TEST(Utils, path_proc_invalid)
{
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/proc")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/proc/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//proc/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/proc//")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//proc//")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/proc/foo")));
}
TEST(Utils, path_sys_invalid)
{
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/sys")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/sys/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//sys/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/sys//")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//sys//")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/sys/foo")));
}
TEST(Utils, path_home_proper_invalid)
{
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/home")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/home/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//home/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/home//")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//home//")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/home/foo/..")));
}
TEST(Utils, path_home_ubuntu_invalid)
{
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/home/ubuntu")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/home/ubuntu/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//home/ubuntu/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/home//ubuntu/")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/home/ubuntu//")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("//home//ubuntu//")));
EXPECT_TRUE(mp::utils::invalid_target_path(QString("/home/ubuntu/foo/..")));
}
TEST(Utils, path_home_foo_valid)
{
EXPECT_FALSE(mp::utils::invalid_target_path(QString("/home/foo")));
EXPECT_FALSE(mp::utils::invalid_target_path(QString("/home/foo/")));
EXPECT_FALSE(mp::utils::invalid_target_path(QString("//home/foo/")));
}
TEST(Utils, path_home_ubuntu_foo_valid)
{
EXPECT_FALSE(mp::utils::invalid_target_path(QString("/home/ubuntu/foo")));
EXPECT_FALSE(mp::utils::invalid_target_path(QString("/home/ubuntu/foo/")));
EXPECT_FALSE(mp::utils::invalid_target_path(QString("//home/ubuntu/foo")));
}
TEST(Utils, create_temp_file_with_path_does_not_throw_when_folder_exists)
{
mpt::TempDir temp_dir;
QString file_template = temp_dir.path() + "/test_temp_file";
EXPECT_NO_THROW(mp::utils::create_temp_file_with_path(file_template));
}
TEST(Utils, create_temp_file_with_path_does_not_throw_when_folder_does_not_exist)
{
mpt::TempDir temp_dir;
QString file_template = temp_dir.path() + "/new_folder/test_temp_file";
EXPECT_NO_THROW(mp::utils::create_temp_file_with_path(file_template));
}
TEST(Utils, create_temp_file_with_path_works_when_folder_exists)
{
mpt::TempDir temp_dir;
QString file_template = temp_dir.path() + "/test_temp_file";
QTemporaryFile file{mp::utils::create_temp_file_with_path(file_template)};
file.open();
EXPECT_THAT(file.fileName().toStdString(), HasSubstr(file_template.toStdString()));
file.close();
}
TEST(Utils, create_temp_file_with_path_works_when_folder_does_not_exist)
{
mpt::TempDir temp_dir;
QString file_template = temp_dir.path() + "/new_folder/test_temp_file";
QTemporaryFile file{mp::utils::create_temp_file_with_path(file_template)};
EXPECT_TRUE(QFileInfo::exists(temp_dir.path() + "/new_folder/"));
file.open();
EXPECT_THAT(file.fileName().toStdString(), HasSubstr(file_template.toStdString()));
file.close();
}
TEST(Utils, create_temp_file_with_path_throws_if_cannot_create_path)
{
mpt::TempDir temp_dir;
QString file_template = temp_dir.path() + "/new_folder/test_temp_file";
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(mp::utils::create_temp_file_with_path(file_template), std::runtime_error,
mpt::match_what(HasSubstr("Could not create path")));
}
TEST(Utils, make_file_with_content_works)
{
mpt::TempDir temp_dir;
QString file_name = temp_dir.path() + "/test-file";
EXPECT_NO_THROW(MP_UTILS.make_file_with_content(file_name.toStdString(), file_contents));
QFile checked_file(file_name);
check_file_contents(checked_file, file_contents);
}
TEST(Utils, make_file_with_content_does_not_overwrite)
{
mpt::TempDir temp_dir;
QString file_name = temp_dir.path() + "/test-file";
EXPECT_NO_THROW(MP_UTILS.make_file_with_content(file_name.toStdString(), file_contents));
QFile checked_file(file_name);
check_file_contents(checked_file, file_contents);
MP_EXPECT_THROW_THAT(MP_UTILS.make_file_with_content(file_name.toStdString(), "other stuff\n"), std::runtime_error,
mpt::match_what(HasSubstr("already exists")));
check_file_contents(checked_file, file_contents);
}
TEST(Utils, make_file_with_content_overwrites_when_asked)
{
mpt::TempDir temp_dir;
QString file_name = temp_dir.path() + "/test-file";
EXPECT_NO_THROW(MP_UTILS.make_file_with_content(file_name.toStdString(), file_contents));
QFile checked_file(file_name);
check_file_contents(checked_file, file_contents);
EXPECT_NO_THROW(MP_UTILS.make_file_with_content(file_name.toStdString(), "other stuff\n", true));
check_file_contents(checked_file, "other stuff\n");
}
TEST(Utils, make_file_with_content_creates_path)
{
mpt::TempDir temp_dir;
QString file_name = temp_dir.path() + "/new_dir/test-file";
EXPECT_NO_THROW(MP_UTILS.make_file_with_content(file_name.toStdString(), file_contents));
QFile checked_file(file_name);
check_file_contents(checked_file, file_contents);
}
TEST(Utils, make_file_with_content_fails_if_path_cannot_be_created)
{
std::string file_name{"some_dir/test-file"};
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, exists(A<const QFile&>())).WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(MP_UTILS.make_file_with_content(file_name, file_contents), std::runtime_error,
mpt::match_what(HasSubstr("failed to create dir")));
}
TEST(Utils, make_file_with_content_fails_if_file_cannot_be_created)
{
std::string file_name{"some_dir/test-file"};
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, exists(A<const QFile&>())).WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(MP_UTILS.make_file_with_content(file_name, file_contents), std::runtime_error,
mpt::match_what(HasSubstr("failed to open file")));
}
TEST(Utils, make_file_with_content_throws_on_write_error)
{
std::string file_name{"some_dir/test-file"};
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, exists(A<const QFile&>())).WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, write(A<QFile&>(), _, _)).WillOnce(Return(747));
MP_EXPECT_THROW_THAT(MP_UTILS.make_file_with_content(file_name, file_contents), std::runtime_error,
mpt::match_what(HasSubstr("failed to write to file")));
}
TEST(Utils, make_file_with_content_throws_on_failure_to_flush)
{
std::string file_name{"some_dir/test-file"};
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, exists(A<const QFile&>())).WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, write(A<QFile&>(), _, _)).WillOnce(Return(file_contents.size()));
EXPECT_CALL(*mock_file_ops, flush(A<QFile&>())).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(MP_UTILS.make_file_with_content(file_name, file_contents),
std::runtime_error,
mpt::match_what(HasSubstr("failed to flush file")));
}
TEST(Utils, expectedScryptHashReturned)
{
const auto passphrase = MP_UTILS.generate_scrypt_hash_for("passphrase");
EXPECT_EQ(passphrase, "f28cb995d91eed8064674766f28e468aae8065b2cf02af556c857dd77de2d2476f3830fd02147f3e35037a1812df"
"0d0d0934fa677be585269fee5358d5c70758");
}
TEST(Utils, generateScryptHashErrorThrows)
{
REPLACE(EVP_PBE_scrypt, [](auto...) { return 0; });
MP_EXPECT_THROW_THAT(MP_UTILS.generate_scrypt_hash_for("passphrase"), std::runtime_error,
mpt::match_what(StrEq("Cannot generate passphrase hash")));
}
TEST(Utils, to_cmd_returns_empty_string_on_empty_input)
{
std::vector<std::string> args{};
auto output = mp::utils::to_cmd(args, mp::utils::QuoteType::quote_every_arg);
EXPECT_THAT(output, ::testing::StrEq(""));
}
TEST(Utils, to_cmd_output_are_not_escaped_with_no_quotes)
{
std::vector<std::string> args{"hello", "world"};
auto output = mp::utils::to_cmd(args, mp::utils::QuoteType::no_quotes);
EXPECT_THAT(output, ::testing::StrEq("hello world"));
}
TEST(Utils, to_cmd_arguments_are_not_escaped_if_not_needed)
{
std::vector<std::string> args{"hello", "world"};
auto output = mp::utils::to_cmd(args, mp::utils::QuoteType::quote_every_arg);
EXPECT_THAT(output, ::testing::StrEq("hello world"));
}
TEST(Utils, to_cmd_arguments_with_single_quotes_are_escaped)
{
std::vector<std::string> args{"it's", "me"};
auto output = mp::utils::to_cmd(args, mp::utils::QuoteType::quote_every_arg);
EXPECT_THAT(output, ::testing::StrEq("it\\'s me"));
}
TEST(Utils, to_cmd_arguments_with_double_quotes_are_escaped)
{
std::vector<std::string> args{"they", "said", "\"please\""};
auto output = mp::utils::to_cmd(args, mp::utils::QuoteType::quote_every_arg);
EXPECT_THAT(output, ::testing::StrEq("they said \\\"please\\\""));
}
struct TestTrimUtilities : public Test
{
std::string s{"\n \f \n \r \t \vI'm a great\n\t string \n \f \n \r \t \v"};
};
TEST_F(TestTrimUtilities, trimEndActuallyTrimsEnd)
{
mp::utils::trim_end(s);
EXPECT_THAT(s, ::testing::StrEq("\n \f \n \r \t \vI'm a great\n\t string"));
}
TEST_F(TestTrimUtilities, trimBeginActuallyTrimsTheBeginning)
{
mp::utils::trim_begin(s);
EXPECT_EQ(s, "I'm a great\n\t string \n \f \n \r \t \v");
}
TEST_F(TestTrimUtilities, trimActuallyTrims)
{
mp::utils::trim(s);
EXPECT_EQ(s, "I'm a great\n\t string");
}
TEST_F(TestTrimUtilities, trimAcceptsCustomFilter)
{
mp::utils::trim(s, [](unsigned char c) { return c == '\n' || c == '\v'; });
EXPECT_EQ(s, " \f \n \r \t \vI'm a great\n\t string \n \f \n \r \t ");
}
TEST(Utils, trim_newline_works)
{
std::string s{"correct\n"};
mp::utils::trim_newline(s);
EXPECT_THAT(s, ::testing::StrEq("correct"));
}
TEST(Utils, trim_newline_assertion_works)
{
std::string s{"wrong"};
ASSERT_DEBUG_DEATH(mp::utils::trim_newline(s), "[Aa]ssert");
}
TEST(Utils, escape_char_actually_escapes)
{
std::string s{"I've got \"quotes\""};
auto res = mp::utils::escape_char(s, '"');
EXPECT_THAT(res, ::testing::StrEq("I've got \\\"quotes\\\""));
}
TEST(Utils, escape_for_shell_actually_escapes)
{
std::string s{"I've got \"quotes\""};
auto res = mp::utils::escape_for_shell(s);
EXPECT_THAT(res, ::testing::StrEq("I\\'ve\\ got\\ \\\"quotes\\\""));
}
TEST(Utils, escape_for_shell_quotes_newlines)
{
std::string s{"I've got\nnewlines"};
auto res = mp::utils::escape_for_shell(s);
EXPECT_THAT(res, ::testing::StrEq("I\\'ve\\ got\"\n\"newlines"));
}
TEST(Utils, escape_for_shell_quotes_empty_string)
{
std::string s{""};
auto res = mp::utils::escape_for_shell(s);
EXPECT_THAT(res, ::testing::StrEq("''"));
}
TEST(Utils, try_action_actually_times_out)
{
bool on_timeout_called{false};
auto on_timeout = [&on_timeout_called] { on_timeout_called = true; };
auto retry_action = [] { return mp::utils::TimeoutAction::retry; };
mp::utils::try_action_for(on_timeout, std::chrono::milliseconds(1), retry_action);
EXPECT_TRUE(on_timeout_called);
}
TEST(Utils, try_action_does_not_timeout)
{
bool on_timeout_called{false};
auto on_timeout = [&on_timeout_called] { on_timeout_called = true; };
bool action_called{false};
auto successful_action = [&action_called] {
action_called = true;
return mp::utils::TimeoutAction::done;
};
mp::utils::try_action_for(on_timeout, std::chrono::seconds(1), successful_action);
EXPECT_FALSE(on_timeout_called);
EXPECT_TRUE(action_called);
}
TEST(Utils, uuid_has_no_curly_brackets)
{
auto uuid = mp::utils::make_uuid();
EXPECT_FALSE(uuid.contains(QRegularExpression("[{}]")));
}
TEST(Utils, contents_of_actually_reads_contents)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
std::string expected_content{"just a bit of test content here"};
mpt::make_file_with_content(file_name, expected_content);
auto content = mp::utils::contents_of(file_name);
EXPECT_THAT(content, StrEq(expected_content));
}
TEST(Utils, contents_of_throws_on_missing_file)
{
EXPECT_THROW(mp::utils::contents_of("this-file-does-not-exist"), std::runtime_error);
}
TEST(Utils, contents_of_empty_contents_on_empty_file)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/empty_test_file";
mpt::make_file_with_content(file_name, "");
auto content = mp::utils::contents_of(file_name);
EXPECT_TRUE(content.empty());
}
TEST(Utils, split_returns_token_list)
{
std::vector<std::string> expected_tokens;
expected_tokens.push_back("Hello");
expected_tokens.push_back("World");
expected_tokens.push_back("Bye!");
const std::string delimiter{":"};
std::stringstream content;
for (const auto& token : expected_tokens)
{
content << token;
content << delimiter;
}
const auto tokens = mp::utils::split(content.str(), delimiter);
EXPECT_THAT(tokens, ContainerEq(expected_tokens));
}
TEST(Utils, split_returns_one_token_if_no_delimiter)
{
const std::string content{"no delimiter here"};
const std::string delimiter{":"};
const auto tokens = mp::utils::split(content, delimiter);
ASSERT_THAT(tokens.size(), Eq(1u));
EXPECT_THAT(tokens[0], StrEq(content));
}
TEST(Utils, valid_mac_address_works)
{
EXPECT_TRUE(mp::utils::valid_mac_address("00:11:22:33:44:55"));
EXPECT_TRUE(mp::utils::valid_mac_address("aa:bb:cc:dd:ee:ff"));
EXPECT_TRUE(mp::utils::valid_mac_address("AA:BB:CC:DD:EE:FF"));
EXPECT_TRUE(mp::utils::valid_mac_address("52:54:00:dd:ee:ff"));
EXPECT_TRUE(mp::utils::valid_mac_address("52:54:00:AB:CD:EF"));
EXPECT_FALSE(mp::utils::valid_mac_address("01:23:45:67:89:AG"));
EXPECT_FALSE(mp::utils::valid_mac_address("012345678901"));
EXPECT_FALSE(mp::utils::valid_mac_address("1:23:45:65:89:ab"));
EXPECT_FALSE(mp::utils::valid_mac_address("aa-bb-cc-dd-ee-ff"));
EXPECT_FALSE(mp::utils::valid_mac_address("aa:bb:cc:dd:ee:ff:"));
EXPECT_FALSE(mp::utils::valid_mac_address(":aa:bb:cc:dd:ee:ff"));
}
TEST(Utils, has_only_digits_works)
{
EXPECT_FALSE(mp::utils::has_only_digits("124ft:,"));
EXPECT_TRUE(mp::utils::has_only_digits("0123456789"));
EXPECT_FALSE(mp::utils::has_only_digits("0123456789:'`'"));
}
TEST(Utils, randomBytesReturnCorrectSize)
{
EXPECT_THAT(MP_UTILS.random_bytes(4), SizeIs(4));
}
TEST(Utils, validate_server_address_throws_on_invalid_address)
{
EXPECT_THROW(mp::utils::validate_server_address("unix"), std::runtime_error);
EXPECT_THROW(mp::utils::validate_server_address("unix:"), std::runtime_error);
EXPECT_THROW(mp::utils::validate_server_address("test:test"), std::runtime_error);
EXPECT_THROW(mp::utils::validate_server_address(""), std::runtime_error);
}
TEST(Utils, validate_server_address_does_not_throw_on_good_address)
{
EXPECT_NO_THROW(mp::utils::validate_server_address("unix:/tmp/a_socket"));
EXPECT_NO_THROW(mp::utils::validate_server_address("test-server.net:123"));
}
TEST(Utils, dir_is_a_dir)
{
mpt::TempDir temp_dir;
EXPECT_TRUE(mp::utils::is_dir(temp_dir.path().toStdString()));
}
TEST(Utils, file_is_not_a_dir)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/empty_test_file";
mpt::make_file_with_content(file_name, "");
EXPECT_FALSE(mp::utils::is_dir(file_name.toStdString()));
}
TEST(Utils, filename_only_is_returned)
{
std::string file_name{"my_file"};
std::string full_path{"/tmp/foo/" + file_name};
EXPECT_THAT(mp::utils::filename_for(full_path), Eq(file_name));
}
TEST(Utils, no_subdirectory_returns_same_path)
{
mp::Path original_path{"/tmp/foo"};
QString empty_subdir{};
EXPECT_THAT(mp::utils::backend_directory_path(original_path, empty_subdir), Eq(original_path));
}
TEST(Utils, subdirectory_returns_new_path)
{
mp::Path original_path{"/tmp/foo"};
QString subdir{"bar"};
EXPECT_THAT(mp::utils::backend_directory_path(original_path, subdir), Eq(mp::Path{"/tmp/foo/bar"}));
}
TEST(Utils, vm_running_returns_true)
{
mp::VirtualMachine::State state = mp::VirtualMachine::State::running;
EXPECT_TRUE(MP_UTILS.is_running(state));
}
TEST(Utils, vm_delayed_shutdown_returns_true)
{
mp::VirtualMachine::State state = mp::VirtualMachine::State::delayed_shutdown;
EXPECT_TRUE(MP_UTILS.is_running(state));
}
TEST(Utils, vm_stopped_returns_false)
{
mp::VirtualMachine::State state = mp::VirtualMachine::State::stopped;
EXPECT_FALSE(MP_UTILS.is_running(state));
}
TEST(Utils, absent_config_file_and_dir_are_created)
{
mpt::TempDir temp_dir;
const QString config_file_path{QString("%1/config_dir/config").arg(temp_dir.path())};
mp::utils::check_and_create_config_file(config_file_path);
EXPECT_TRUE(QFile::exists(config_file_path));
}
TEST(Utils, existing_config_file_is_untouched)
{
mpt::TempFile config_file;
QFileInfo config_file_info{config_file.name()};
auto original_last_modified = config_file_info.lastModified();
mp::utils::check_and_create_config_file(config_file.name());
auto new_last_modified = config_file_info.lastModified();
EXPECT_THAT(new_last_modified, Eq(original_last_modified));
}
TEST(Utils, line_matcher_returns_expected_line)
{
std::string data{"LD_LIBRARY_PATH=/foo/lib\nSNAP=/foo/bin\nDATA=/bar/baz\n"};
std::string matcher{"SNAP="};
auto snap_data = mp::utils::match_line_for(data, matcher);
EXPECT_THAT(snap_data, Eq("SNAP=/foo/bin"));
}
TEST(Utils, line_matcher_no_match_returns_empty_string)
{
std::string data{"LD_LIBRARY_PATH=/foo/lib\nSNAP=/foo/bin\nDATA=/bar/baz\n"};
std::string matcher{"FOO="};
auto snap_data = mp::utils::match_line_for(data, matcher);
EXPECT_TRUE(snap_data.empty());
}
TEST(Utils, make_dir_creates_correct_dir)
{
mpt::TempDir temp_dir;
QString new_dir{"foo"};
auto new_path = MP_UTILS.make_dir(QDir(temp_dir.path()), new_dir);
EXPECT_TRUE(QFile::exists(new_path));
EXPECT_EQ(new_path, temp_dir.path() + "/" + new_dir);
}
TEST(Utils, make_dir_with_no_new_dir)
{
mpt::TempDir temp_dir;
auto new_path = MP_UTILS.make_dir(QDir(temp_dir.path()), "");
EXPECT_TRUE(QFile::exists(new_path));
EXPECT_EQ(new_path, temp_dir.path());
}
TEST(Utils, check_filesystem_bytes_available_returns_non_negative)
{
mpt::TempDir temp_dir;
auto bytes_available = MP_UTILS.filesystem_bytes_available(temp_dir.path());
EXPECT_GE(bytes_available, 0);
}
TEST(VaultUtils, copy_creates_new_file_and_returned_path_exists)
{
mpt::TempDir temp_dir1, temp_dir2;
auto orig_file_path = QDir(temp_dir1.path()).filePath("test_file");
mpt::make_file_with_content(orig_file_path);
auto new_file_path = mp::vault::copy(orig_file_path, temp_dir2.path());
EXPECT_TRUE(QFile::exists(new_file_path));
}
TEST(VaultUtils, copy_returns_empty_path_when_file_name_is_empty)
{
mpt::TempDir temp_dir;
auto path = mp::vault::copy("", temp_dir.path());
EXPECT_TRUE(path.isEmpty());
}
TEST(VaultUtils, copy_throws_when_file_does_not_exist)
{
mpt::TempDir temp_dir;
const QString file_name{"/foo/bar"};
MP_EXPECT_THROW_THAT(mp::vault::copy(file_name, temp_dir.path()), std::runtime_error,
mpt::match_what(StrEq(fmt::format("{} missing", file_name))));
}
| 24,714
|
C++
|
.cpp
| 605
| 37.052893
| 120
| 0.690788
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,573
|
test_memory_size.cpp
|
canonical_multipass/tests/test_memory_size.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <multipass/exceptions/invalid_memory_size_exception.h>
#include <multipass/format.h>
#include <multipass/memory_size.h>
#include <string>
#include <tuple>
#include <vector>
namespace mp = multipass;
using namespace testing;
namespace
{
constexpr auto kilo = 1024LL; // LL: giga times value higher than 4 would overflow if we used only 4bytes here
constexpr auto mega = kilo * kilo;
constexpr auto giga = kilo * mega;
template <typename Num>
std::string to_str(Num val) // alternative to std::to_string that ignores locale
{
return fmt::format("{}", val);
}
struct TestGoodMemorySizeFormats : public TestWithParam<std::tuple<long long, long long, std::string, long long>>
{
struct UnitSpec
{
std::vector<std::string> suffixes;
long long factor;
auto gen_unit_args() const
{
std::vector<std::tuple<std::string, long long>> ret;
for(const auto& suffix : suffixes)
ret.emplace_back(suffix, factor);
return ret;
}
};
static auto generate_unit_args()
{
const UnitSpec byte_unit{{"", "b", "B"}, 1LL};
const UnitSpec kilo_unit{{"k", "kb", "kB", "Kb", "KB", "K", "KiB"}, kilo};
const UnitSpec mega_unit{{"m", "mb", "mB", "Mb", "MB", "M", "MiB"}, mega};
const UnitSpec giga_unit{{"g", "gb", "gB", "Gb", "GB", "G", "GiB"}, giga};
auto args = byte_unit.gen_unit_args();
const auto kilo_args = kilo_unit.gen_unit_args();
const auto mega_args = mega_unit.gen_unit_args();
const auto giga_args = giga_unit.gen_unit_args();
args.insert(std::end(args), std::cbegin(kilo_args), std::cend(kilo_args));
args.insert(std::end(args), std::cbegin(mega_args), std::cend(mega_args));
args.insert(std::end(args), std::cbegin(giga_args), std::cend(giga_args));
return args;
}
static auto generate_args()
{
const auto values = {0LL, 1LL, 42LL, 1023LL, 1024LL, 2048LL, 2049LL};
const auto decimals = {-1LL, 0LL, 25LL, 141562653LL, 999999LL};
const auto unit_args = generate_unit_args();
std::vector<std::tuple<long long, long long, std::string, long long>> ret;
for (const auto& uarg : unit_args)
{
if (get<1>(uarg) > 1)
for (auto val : values)
for (auto dec : decimals)
ret.emplace_back(val, dec, get<0>(uarg), get<1>(uarg));
else
for (auto val : values)
ret.emplace_back(val, -1LL, get<0>(uarg), get<1>(uarg));
}
return ret;
}
};
struct TestBadMemorySizeFormats : public TestWithParam<std::string>
{
};
} // namespace
TEST_P(TestGoodMemorySizeFormats, interpretsValidFormats)
{
auto param = GetParam();
const auto val = get<0>(param);
const auto dec = get<1>(param);
const auto unit = get<2>(param);
const auto factor = get<3>(param);
const auto size =
dec < 0 ? mp::MemorySize{to_str(val) + unit} : mp::MemorySize{to_str(val) + "." + to_str(dec) + unit};
EXPECT_EQ(size.in_bytes(),
dec < 0 ? val * factor : val * factor + (long long)((dec * factor) / pow(10, to_str(dec).size())));
}
TEST_P(TestBadMemorySizeFormats, rejectsBadFormats)
{
EXPECT_THROW(mp::MemorySize{GetParam()}, mp::InvalidMemorySizeException);
}
INSTANTIATE_TEST_SUITE_P(MemorySize, TestGoodMemorySizeFormats, ValuesIn(TestGoodMemorySizeFormats::generate_args()));
INSTANTIATE_TEST_SUITE_P(MemorySize, TestBadMemorySizeFormats,
Values("321BB", "321BK", "1024MM", "1024KM", "1024GK", "K", "", "123.321", "6868i", "555iB",
"486ki", "54Mi", "8i33", "4M2", "-2345", "-5MiB", "K", "4GM", "256.M", "186000.B",
"3.14", ".5g", "4.2B", "42.", "2048.K", " 268. "));
TEST(MemorySize, defaultConstructsToZero)
{
EXPECT_EQ(mp::MemorySize{}.in_bytes(), 0LL);
}
TEST(MemorySize, converts0ToK)
{
EXPECT_EQ(mp::MemorySize{"0"}.in_kilobytes(), 0LL);
}
TEST(MemorySize, converts0ToM)
{
EXPECT_EQ(mp::MemorySize{"0B"}.in_megabytes(), 0LL);
}
TEST(MemorySize, converts0ToG)
{
EXPECT_EQ(mp::MemorySize{"0G"}.in_gigabytes(), 0LL);
}
TEST(MemorySize, converts0DecimalToG)
{
EXPECT_EQ(mp::MemorySize{"0.0m"}.in_gigabytes(), 0LL);
}
TEST(MemorySize, convertsHigherUnitToB)
{
constexpr auto val = 65535;
EXPECT_EQ(mp::MemorySize{to_str(val) + "K"}.in_bytes(), val * kilo);
EXPECT_EQ(mp::MemorySize{to_str(val) + "M"}.in_bytes(), val * mega);
EXPECT_EQ(mp::MemorySize{to_str(val) + "G"}.in_bytes(), val * giga);
}
TEST(MemorySize, convertsHigherUnitToK)
{
constexpr auto val = 694;
EXPECT_EQ(mp::MemorySize{to_str(val) + "M"}.in_kilobytes(), val * kilo);
EXPECT_EQ(mp::MemorySize{to_str(val) + "G"}.in_kilobytes(), val * mega);
}
TEST(MemorySize, convertsHigherUnitToM)
{
constexpr auto val = 653;
EXPECT_EQ(mp::MemorySize{to_str(val) + "G"}.in_megabytes(), val * kilo);
}
TEST(MemorySize, convertsHigherUnitToBWhenDecimal)
{
constexpr auto val = 0.0625;
EXPECT_EQ(mp::MemorySize{to_str(val) + "K"}.in_bytes(), val * kilo);
EXPECT_EQ(mp::MemorySize{to_str(val) + "M"}.in_bytes(), val * mega);
EXPECT_EQ(mp::MemorySize{to_str(val) + "G"}.in_bytes(), val * giga);
}
TEST(MemorySize, convertsHigherUnitToKWhenDecimal)
{
constexpr auto val = 42.125;
EXPECT_EQ(mp::MemorySize{to_str(val) + "M"}.in_kilobytes(), val * kilo);
EXPECT_EQ(mp::MemorySize{to_str(val) + "G"}.in_kilobytes(), val * mega);
}
TEST(MemorySize, convertsHigherUnitToMWhenDecimal)
{
constexpr auto val = 22.75;
EXPECT_EQ(mp::MemorySize(to_str(val) + "G").in_megabytes(), val * kilo);
}
TEST(MemorySize, convertsLowerUnitToKWhenExactMultiple)
{
constexpr auto val = 2;
EXPECT_EQ(mp::MemorySize{to_str(val * kilo)}.in_kilobytes(), val);
}
TEST(MemorySize, convertsLowerUnitToMWhenExactMultiple)
{
constexpr auto val = 456;
EXPECT_EQ(mp::MemorySize{to_str(val * giga)}.in_megabytes(), val * kilo);
}
TEST(MemorySize, convertsLowerUnitToGWhenExactMultiple)
{
constexpr auto val = 99;
EXPECT_EQ(mp::MemorySize{to_str(val * giga)}.in_gigabytes(), val);
}
TEST(MemorySize, convertsLowerUnitToKByFlooringWhenNotMultiple)
{
EXPECT_EQ(mp::MemorySize{"1234B"}.in_kilobytes(), 1);
EXPECT_EQ(mp::MemorySize{"33B"}.in_kilobytes(), 0);
EXPECT_EQ(mp::MemorySize{"42.0K"}.in_kilobytes(), 42);
EXPECT_EQ(mp::MemorySize{"1.2M"}.in_kilobytes(), 1228);
}
TEST(MemorySize, convertsLowerUnitToMByFlooringWhenNotMultiple)
{
EXPECT_EQ(mp::MemorySize{"5555K"}.in_megabytes(), 5);
EXPECT_EQ(mp::MemorySize{"5555B"}.in_megabytes(), 0);
EXPECT_EQ(mp::MemorySize{"5555.5K"}.in_megabytes(), 5);
EXPECT_EQ(mp::MemorySize{"1.5G"}.in_megabytes(), 1536);
}
TEST(MemorySize, convertsLowerUnitToGByFlooringWhenNotMultiple)
{
EXPECT_EQ(mp::MemorySize{"2047M"}.in_gigabytes(), 1);
EXPECT_EQ(mp::MemorySize{"2047K"}.in_gigabytes(), 0);
EXPECT_EQ(mp::MemorySize{"1.4G"}.in_gigabytes(), 1);
EXPECT_EQ(mp::MemorySize{"0.9G"}.in_gigabytes(), 0);
}
TEST(MemorySize, canCompareEqual)
{
mp::MemorySize x{"999"};
EXPECT_EQ(x, x);
EXPECT_EQ(x, mp::MemorySize{x});
EXPECT_EQ(mp::MemorySize{}, mp::MemorySize{"0B"});
EXPECT_EQ(mp::MemorySize{"2048"}, mp::MemorySize{"2k"});
EXPECT_EQ(mp::MemorySize{"2g"}, mp::MemorySize{"2048M"});
EXPECT_EQ(mp::MemorySize{"0m"}, mp::MemorySize{"0k"});
EXPECT_EQ(mp::MemorySize{"1.5G"}, mp::MemorySize{"1536M"});
EXPECT_EQ(mp::MemorySize{"1.0K"}, mp::MemorySize{"1024B"});
EXPECT_EQ(mp::MemorySize{"1.0K"}, mp::MemorySize{"1k"});
EXPECT_EQ(mp::MemorySize{"3.14K"}, mp::MemorySize{"3215"});
EXPECT_EQ(mp::MemorySize{"0.0001G"}, mp::MemorySize{"107374"});
EXPECT_EQ(mp::MemorySize{"0.095367432K"}, mp::MemorySize{"97B"});
}
TEST(MemorySize, canCompareNotEqual)
{
EXPECT_NE(mp::MemorySize{"2048b"}, mp::MemorySize{"2g"});
EXPECT_NE(mp::MemorySize{"42g"}, mp::MemorySize{"42m"});
EXPECT_NE(mp::MemorySize{"123"}, mp::MemorySize{"321"});
EXPECT_NE(mp::MemorySize{"2352346"}, mp::MemorySize{"0"});
EXPECT_NE(mp::MemorySize{"1.5G"}, mp::MemorySize{"1G"});
EXPECT_NE(mp::MemorySize{"1.5G"}, mp::MemorySize{"1535M"});
EXPECT_NE(mp::MemorySize{"1.2K"}, mp::MemorySize{"1229"});
EXPECT_NE(mp::MemorySize{"0.0001G"}, mp::MemorySize{"0"});
EXPECT_NE(mp::MemorySize{"2048.5K"}, mp::MemorySize{"2M"});
}
TEST(MemorySize, canCompareGreater)
{
EXPECT_GT(mp::MemorySize{"2048b"}, mp::MemorySize{"2"});
EXPECT_GT(mp::MemorySize{"42g"}, mp::MemorySize{"42m"});
EXPECT_GT(mp::MemorySize{"1234"}, mp::MemorySize{"321"});
EXPECT_GT(mp::MemorySize{"2352346"}, mp::MemorySize{"0"});
EXPECT_GT(mp::MemorySize{"0.5G"}, mp::MemorySize{"511M"});
EXPECT_GT(mp::MemorySize{"2.2M"}, mp::MemorySize{"2048K"});
EXPECT_GT(mp::MemorySize{"2048.5K"}, mp::MemorySize{"2M"});
EXPECT_GT(mp::MemorySize{"0.51G"}, mp::MemorySize{"0.5G"});
}
TEST(MemorySize, canCompareGreaterEqual)
{
EXPECT_GE(mp::MemorySize{"2048b"}, mp::MemorySize{"2"});
EXPECT_GE(mp::MemorySize{"0m"}, mp::MemorySize{"0k"});
EXPECT_GE(mp::MemorySize{"76"}, mp::MemorySize{"76"});
EXPECT_GE(mp::MemorySize{"7k"}, mp::MemorySize{"6k"});
EXPECT_GE(mp::MemorySize{"1024M"}, mp::MemorySize{"1.0G"});
}
TEST(MemorySize, canCompareLess)
{
EXPECT_LT(mp::MemorySize{"2047b"}, mp::MemorySize{"2k"});
EXPECT_LT(mp::MemorySize{"42g"}, mp::MemorySize{"420g"});
EXPECT_LT(mp::MemorySize{"123"}, mp::MemorySize{"321"});
EXPECT_LT(mp::MemorySize{"2352346"}, mp::MemorySize{"55g"});
EXPECT_LT(mp::MemorySize{"1024K"}, mp::MemorySize{"1.5M"});
EXPECT_LT(mp::MemorySize{"0.5G"}, mp::MemorySize{"0.75G"});
}
TEST(MemorySize, canCompareLessEqual)
{
EXPECT_LE(mp::MemorySize{"2"}, mp::MemorySize{"2048b"});
EXPECT_LE(mp::MemorySize{"0k"}, mp::MemorySize{"0m"});
EXPECT_LE(mp::MemorySize{"76"}, mp::MemorySize{"76"});
EXPECT_LE(mp::MemorySize{"6k"}, mp::MemorySize{"7k"});
EXPECT_GE(mp::MemorySize{"1.0G"}, mp::MemorySize{"1024M"});
}
using mem_repr = std::tuple<std::string, std::string>;
struct TestHumanReadableSizes : public TestWithParam<mem_repr>
{
};
TEST_P(TestHumanReadableSizes, producesProperHumanReadableFormat)
{
const auto& [size, repr] = GetParam();
EXPECT_EQ(mp::MemorySize{size}.human_readable(), repr);
}
INSTANTIATE_TEST_SUITE_P(MemorySize, TestHumanReadableSizes,
Values(mem_repr{"0", "0B"}, mem_repr{"42B", "42B"}, mem_repr{"31", "31B"},
mem_repr{"50B", "50B"}, mem_repr{"999", "999B"}, mem_repr{"1023", "1023B"},
mem_repr{"876b", "876B"}, mem_repr{"9k", "9.0KiB"}, mem_repr{"98kib", "98.0KiB"},
mem_repr{"1024", "1.0KiB"}, mem_repr{"1031", "1.0KiB"}, mem_repr{"999K", "999.0KiB"},
mem_repr{"4096K", "4.0MiB"}, mem_repr{"4546K", "4.4MiB"}, mem_repr{"8653K", "8.5MiB"},
mem_repr{"9999M", "9.8GiB"}, mem_repr{"1234567890", "1.1GiB"},
mem_repr{"123456G", "123456.0GiB"}));
| 11,893
|
C++
|
.cpp
| 281
| 37.074733
| 118
| 0.640516
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,574
|
test_setting_specs.cpp
|
canonical_multipass/tests/test_setting_specs.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <multipass/exceptions/settings_exceptions.h>
#include <multipass/settings/basic_setting_spec.h>
#include <multipass/settings/bool_setting_spec.h>
#include <multipass/settings/custom_setting_spec.h>
namespace mp = multipass;
namespace mpt = mp::test;
using namespace testing;
namespace
{
template <typename T>
struct TestPlainKeyAndDefault : public Test
{
};
using PlainKeyAndDefaultTypes = Types<mp::BasicSettingSpec, mp::BoolSettingSpec, mp::CustomSettingSpec>;
MP_TYPED_TEST_SUITE(TestPlainKeyAndDefault, PlainKeyAndDefaultTypes);
TYPED_TEST(TestPlainKeyAndDefault, basicSettingSpecReturnsProvidedKeyAndDefault)
{
const auto key = "foo", default_ = "true";
const auto setting = [key, default_]() {
if constexpr (std::is_same_v<TypeParam, mp::CustomSettingSpec>)
return TypeParam{key, default_, [](const auto& v) { return v; }};
else
return TypeParam{key, default_};
}();
EXPECT_EQ(setting.get_key(), key);
EXPECT_EQ(setting.get_default(), default_);
}
TEST(TestSettingSpec, basicSettingSpecImplementsInterpretAsIdentity)
{
mp::BasicSettingSpec setting{"a", "b"};
const auto val = "an arbitrary value";
EXPECT_EQ(setting.interpret(val), val);
}
TEST(TestSettingSpec, customSettingSpecCallsGivenInterpreter)
{
bool called = false;
const auto val = "yak";
mp::CustomSettingSpec setting{"a", "b", [&called](QString v) {
called = true;
return v;
}};
EXPECT_EQ(setting.interpret(val), val);
EXPECT_TRUE(called);
}
TEST(TestSettingSpec, customSettingSpecInterpretsGivenDefault)
{
const auto interpreted = "real";
mp::CustomSettingSpec setting{"poiu", "lkjh", [interpreted](auto) { return interpreted; }};
EXPECT_EQ(setting.get_default(), interpreted);
}
struct TestBadBoolSettingSpec : public TestWithParam<const char*>
{
};
TEST_P(TestBadBoolSettingSpec, boolSettingSpecRejectsBadDefaults)
{
const auto key = "asdf";
const auto bad = GetParam();
MP_ASSERT_THROW_THAT((mp::BoolSettingSpec{key, bad}), mp::InvalidSettingException,
mpt::match_what(AllOf(HasSubstr(key), HasSubstr(bad))));
}
TEST_P(TestBadBoolSettingSpec, boolSettingSpecRejectsOtherValues)
{
const auto key = "key";
const auto bad = GetParam();
mp::BoolSettingSpec setting{key, "true"};
MP_ASSERT_THROW_THAT(setting.interpret(bad), mp::InvalidSettingException,
mpt::match_what(AllOf(HasSubstr(key), HasSubstr(bad))));
}
INSTANTIATE_TEST_SUITE_P(TestBadBoolSettingSpec, TestBadBoolSettingSpec,
Values("nonsense", "invalid", "", "bool", "representations", "-", "null", "4"));
using ReprVal = std::tuple<QString, QString>;
struct TestGoodBoolSettingSpec : public TestWithParam<ReprVal>
{
};
TEST_P(TestGoodBoolSettingSpec, interpretsBools)
{
const auto& [repr, val] = GetParam();
mp::BoolSettingSpec setting{"key", "false"};
EXPECT_EQ(setting.interpret(repr), val);
}
INSTANTIATE_TEST_SUITE_P(TestTrueBoolSettingSpec, TestGoodBoolSettingSpec,
Combine(Values("yes", "on", "1", "true"), Values("true")));
INSTANTIATE_TEST_SUITE_P(TestFalseBoolSettingSpec, TestGoodBoolSettingSpec,
Combine(Values("no", "off", "0", "false"), Values("false")));
} // namespace
| 4,069
|
C++
|
.cpp
| 102
| 34.833333
| 105
| 0.701545
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,575
|
test_sshfs_mount_handler.cpp
|
canonical_multipass/tests/test_sshfs_mount_handler.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_ssh_test_fixture.h"
#include "common.h"
#include "mock_environment_helpers.h"
#include "mock_file_ops.h"
#include "mock_logger.h"
#include "mock_process_factory.h"
#include "mock_server_reader_writer.h"
#include "mock_ssh_process_exit_status.h"
#include "mock_virtual_machine.h"
#include "stub_ssh_key_provider.h"
#include "stub_virtual_machine.h"
#include <multipass/exceptions/sshfs_missing_error.h>
#include <multipass/sshfs_mount/sshfs_mount_handler.h>
#include <multipass/vm_mount.h>
#include <thread>
#include <QCoreApplication>
#include <QTimer>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
const multipass::logging::Level default_log_level = multipass::logging::Level::debug;
auto sshfs_server_callback(mpt::MockProcessFactory::Callback callback)
{
return [callback](mpt::MockProcess* process) {
if (process->program().contains("sshfs_server"))
callback(process);
};
}
struct SSHFSMountHandlerTest : public ::Test
{
SSHFSMountHandlerTest()
{
EXPECT_CALL(server, Write(_, _)).WillRepeatedly(Return(true));
EXPECT_CALL(mock_file_ops, status)
.WillOnce(Return(mp::fs::file_status{mp::fs::file_type::directory, mp::fs::perms::all}));
}
void TearDown() override
{
// Deliberately spin the event loop to ensure all deleteLater()'ed QObjects are cleaned up, so
// the mock tests are performed
qApp->processEvents(QEventLoop::AllEvents);
}
auto make_exec_that_fails_for(const std::vector<std::string>& expected_cmds, bool& invoked)
{
return [this, expected_cmds, &invoked](ssh_channel, const char* raw_cmd) {
std::string cmd{raw_cmd};
exit_status_mock.set_exit_status(exit_status_mock.success_status);
for (const auto& expected_cmd : expected_cmds)
{
if (cmd.find(expected_cmd) != std::string::npos)
{
invoked = true;
exit_status_mock.set_exit_status(exit_status_mock.failure_status);
break;
}
}
return SSH_OK;
};
}
mpt::StubSSHKeyProvider key_provider;
std::string source_path{"/my/source/path"}, target_path{"/the/target/path"};
mpt::MockFileOps::GuardedMock mock_file_ops_injection = mpt::MockFileOps::inject();
mpt::MockFileOps& mock_file_ops = *mock_file_ops_injection.first;
mp::id_mappings gid_mappings{{1, 2}, {3, 4}}, uid_mappings{{5, -1}, {6, 10}};
mpt::SetEnvScope env_scope{"DISABLE_APPARMOR", "1"};
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(default_log_level);
mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest> server;
mpt::MockSSHTestFixture mock_ssh_test_fixture;
mpt::ExitStatusMock exit_status_mock;
mpt::StubVirtualMachine vm;
const mp::VMMount mount{source_path, gid_mappings, uid_mappings, mp::VMMount::MountType::Classic};
std::unique_ptr<mpt::MockProcessFactory::Scope> factory = mpt::MockProcessFactory::Inject();
mpt::MockProcessFactory::Callback sshfs_prints_connected = [](mpt::MockProcess* process) {
// Have "sshfs_server" print "Connected" to its stdout after short delay
ON_CALL(*process, read_all_standard_output).WillByDefault(Return("Connected"));
QTimer::singleShot(1, process, [process] { emit process->ready_read_standard_output(); });
// Ensure process_state() does not have an exit code set (i.e. still running)
ON_CALL(*process, process_state).WillByDefault(Return(mp::ProcessState{}));
};
};
TEST_F(SSHFSMountHandlerTest, mount_creates_sshfs_process)
{
factory->register_callback(sshfs_server_callback(sshfs_prints_connected));
mpt::MockVirtualMachine mock_vm{"my_instance"};
EXPECT_CALL(mock_vm, ssh_port()).Times(3);
EXPECT_CALL(mock_vm, ssh_hostname()).Times(3);
EXPECT_CALL(mock_vm, ssh_username()).Times(3);
mp::SSHFSMountHandler sshfs_mount_handler{&mock_vm, &key_provider, target_path, mount};
sshfs_mount_handler.activate(&server);
ASSERT_EQ(factory->process_list().size(), 1u);
auto sshfs_command = factory->process_list()[0];
EXPECT_TRUE(sshfs_command.command.endsWith("sshfs_server"));
ASSERT_EQ(sshfs_command.arguments.size(), 8);
EXPECT_EQ(sshfs_command.arguments[0], "localhost");
EXPECT_EQ(sshfs_command.arguments[1], "42");
EXPECT_EQ(sshfs_command.arguments[2], "ubuntu");
EXPECT_EQ(sshfs_command.arguments[3], "/my/source/path");
EXPECT_EQ(sshfs_command.arguments[4], "/the/target/path");
// Ordering of the next 2 options not guaranteed, hence the or-s.
EXPECT_TRUE(sshfs_command.arguments[5] == "6:10,5:-1," || sshfs_command.arguments[5] == "5:-1,6:10,");
EXPECT_TRUE(sshfs_command.arguments[6] == "3:4,1:2," || sshfs_command.arguments[6] == "1:2,3:4,");
const QString log_level_as_string{QString::number(static_cast<int>(default_log_level))};
EXPECT_EQ(sshfs_command.arguments[7], log_level_as_string);
}
TEST_F(SSHFSMountHandlerTest, sshfs_process_failing_with_return_code_9_causes_exception)
{
factory->register_callback(sshfs_server_callback([](mpt::MockProcess* process) {
mp::ProcessState exit_state;
exit_state.exit_code = 9;
// Have "sshfs_server" die after short delay
QTimer::singleShot(100, process, [process]() { emit process->finished({9, {}}); });
ON_CALL(*process, process_state()).WillByDefault(Return(exit_state));
}));
mp::SSHFSMountHandler sshfs_mount_handler{&vm, &key_provider, target_path, mount};
EXPECT_THROW(sshfs_mount_handler.activate(&server), mp::SSHFSMissingError);
ASSERT_EQ(factory->process_list().size(), 1u);
auto sshfs_command = factory->process_list()[0];
EXPECT_TRUE(sshfs_command.command.endsWith("sshfs_server"));
}
TEST_F(SSHFSMountHandlerTest, sshfs_process_failing_causes_runtime_exception)
{
factory->register_callback(sshfs_server_callback([](mpt::MockProcess* process) {
mp::ProcessState exit_state;
exit_state.exit_code = 1;
// Have "sshfs_server" die after short delay
ON_CALL(*process, read_all_standard_error()).WillByDefault(Return("Whoopsie"));
QTimer::singleShot(100, process, [process, exit_state]() { emit process->finished(exit_state); });
ON_CALL(*process, process_state()).WillByDefault(Return(exit_state));
}));
mp::SSHFSMountHandler sshfs_mount_handler{&vm, &key_provider, target_path, mount};
MP_EXPECT_THROW_THAT(sshfs_mount_handler.activate(&server), std::runtime_error,
mpt::match_what(StrEq("Process returned exit code: 1: Whoopsie")));
}
TEST_F(SSHFSMountHandlerTest, stop_terminates_sshfs_process)
{
factory->register_callback(sshfs_server_callback([this](mpt::MockProcess* process) {
sshfs_prints_connected(process);
EXPECT_CALL(*process, terminate);
EXPECT_CALL(*process, wait_for_finished).WillOnce(Return(true));
}));
mp::SSHFSMountHandler sshfs_mount_handler{&vm, &key_provider, target_path, mount};
sshfs_mount_handler.activate(&server);
sshfs_mount_handler.deactivate();
}
TEST_F(SSHFSMountHandlerTest, throws_install_sshfs_which_snap_fails)
{
auto invoked = false;
REPLACE(ssh_channel_request_exec, make_exec_that_fails_for({"which snap"}, invoked));
mp::SSHFSMountHandler sshfs_mount_handler{&vm, &key_provider, target_path, mount};
EXPECT_THROW(sshfs_mount_handler.activate(&server), std::runtime_error);
EXPECT_TRUE(invoked);
}
TEST_F(SSHFSMountHandlerTest, throws_install_sshfs_no_snap_dir_fails)
{
auto invoked = false;
REPLACE(ssh_channel_request_exec,
make_exec_that_fails_for({"[ -e /snap ]", "sudo snap list multipass-sshfs"}, invoked));
mp::SSHFSMountHandler sshfs_mount_handler{&vm, &key_provider, target_path, mount};
EXPECT_THROW(sshfs_mount_handler.activate(&server), std::runtime_error);
EXPECT_TRUE(invoked);
}
TEST_F(SSHFSMountHandlerTest, throws_install_sshfs_snap_install_fails)
{
auto invoked = false;
REPLACE(ssh_channel_request_exec,
make_exec_that_fails_for({"sudo snap list multipass-sshfs", "sudo snap install multipass-sshfs"}, invoked));
mp::SSHFSMountHandler sshfs_mount_handler{&vm, &key_provider, target_path, mount};
EXPECT_THROW(sshfs_mount_handler.activate(&server), mp::SSHFSMissingError);
EXPECT_TRUE(invoked);
}
TEST_F(SSHFSMountHandlerTest, install_sshfs_timeout_logs_info)
{
ssh_channel_callbacks callbacks{nullptr};
auto sleep = false;
int exit_code;
auto mocked_ssh_channel_request_exec = [&sleep, &exit_code](ssh_channel, const char* raw_cmd) {
std::string cmd{raw_cmd};
exit_code = SSH_OK;
if (cmd == "sudo snap install multipass-sshfs")
sleep = true;
else if (cmd == "sudo snap list multipass-sshfs")
exit_code = SSH_ERROR;
return SSH_OK;
};
REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec);
REPLACE(ssh_add_channel_callbacks, [&callbacks](ssh_channel, ssh_channel_callbacks cb) mutable {
callbacks = cb;
return SSH_OK;
});
auto mocked_ssh_event_dopoll = [&callbacks, &sleep, &exit_code](ssh_event, int timeout) {
if (!callbacks)
return SSH_ERROR;
if (sleep)
std::this_thread::sleep_for(std::chrono::milliseconds(timeout + 1));
else
callbacks->channel_exit_status_function(nullptr, nullptr, exit_code, callbacks->userdata);
return SSH_OK;
};
REPLACE(ssh_event_dopoll, mocked_ssh_event_dopoll);
logger_scope.mock_logger->screen_logs(mpl::Level::error);
EXPECT_CALL(*logger_scope.mock_logger,
log(mpl::Level::error,
mpt::MockLogger::make_cstring_matcher(StrEq("sshfs-mount-handler")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr("Could not install 'multipass-sshfs' in 'stub'"), HasSubstr("timed out")))));
mp::SSHFSMountHandler sshfs_mount_handler{&vm, &key_provider, target_path, mount};
EXPECT_THROW(sshfs_mount_handler.activate(&server, std::chrono::milliseconds(1)), mp::SSHFSMissingError);
}
| 10,962
|
C++
|
.cpp
| 225
| 42.715556
| 120
| 0.689575
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,576
|
test_argparser.cpp
|
canonical_multipass/tests/test_argparser.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "tests/fake_alias_config.h"
#include "tests/stub_terminal.h"
#include <multipass/alias_definition.h>
#include <multipass/cli/argparser.h>
#include <multipass/cli/command.h>
#include <QString>
#include <QStringList>
#include <sstream>
#include <string>
#include <vector>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
typedef std::vector<std::pair<std::string, mp::AliasDefinition>> AliasesVector;
struct TestVerbosity : public TestWithParam<int>
{
};
TEST_P(TestVerbosity, test_various_vs)
{
std::ostringstream oss;
const auto cmds = std::vector<mp::cmd::Command::UPtr>{};
const auto v = GetParam();
auto args = QStringList{"multipass_tests"};
if (v)
{
auto arg = QString{v, 'v'};
arg.prepend('-');
args << arg;
}
auto parser = mp::ArgParser{args, cmds, oss, oss};
parser.parse();
const auto expect = v > 4 ? 4 : v;
EXPECT_EQ(parser.verbosityLevel(), expect);
}
INSTANTIATE_TEST_SUITE_P(ArgParser, TestVerbosity, Range(0, 10));
struct TestAliasArguments : public TestWithParam<std::tuple<QStringList /* pre */, QStringList /* post */>>,
public FakeAliasConfig
{
};
TEST_P(TestAliasArguments, test_alias_arguments)
{
std::ostringstream oss;
std::istringstream cin;
mpt::StubTerminal term(oss, oss, cin);
const auto cmds = std::vector<mp::cmd::Command::UPtr>{};
const auto& [pre, post] = GetParam();
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "map"}}});
mp::AliasDict alias_dict(&term);
auto parser = mp::ArgParser{pre, cmds, oss, oss};
const auto& result = parser.parse(alias_dict);
ASSERT_EQ(result, mp::ParseCode::Ok) << "Failed to parse given arguments";
EXPECT_EQ(parser.allArguments(), post);
}
INSTANTIATE_TEST_SUITE_P(
ArgParser, TestAliasArguments,
Values(std::make_tuple(QStringList{"mp", "an_alias"}, QStringList{"mp", "exec", "an_instance", "a_command"}),
std::make_tuple(QStringList{"mp", "-v", "an_alias"},
QStringList{"mp", "-v", "exec", "an_instance", "a_command"}),
std::make_tuple(QStringList{"mp", "an_alias", "-v"},
QStringList{"mp", "exec", "an_instance", "a_command", "-v"}),
std::make_tuple(QStringList{"mp", "an_alias", "an_argument"},
QStringList{"mp", "exec", "an_instance", "a_command", "an_argument"}),
std::make_tuple(QStringList{"mp", "an_alias", "--", "an_argument"},
QStringList{"mp", "exec", "an_instance", "a_command", "--", "an_argument"}),
std::make_tuple(QStringList{"mp", "an_alias", "--", "--an_option"},
QStringList{"mp", "exec", "an_instance", "a_command", "--", "--an_option"}),
std::make_tuple(QStringList{"mp", "an_alias", "--", "--an_option", "an_argument"},
QStringList{"mp", "exec", "an_instance", "a_command", "--", "--an_option", "an_argument"}),
std::make_tuple(QStringList{"mp", "an_alias", "an_alias", "an_alias"}, // args happen to be called the same
QStringList{"mp", "exec", "an_instance", "a_command", "an_alias", "an_alias"})));
| 3,942
|
C++
|
.cpp
| 87
| 39.149425
| 118
| 0.632334
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,577
|
test_simple_streams_index.cpp
|
canonical_multipass/tests/test_simple_streams_index.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "file_operations.h"
#include <multipass/simple_streams_index.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
TEST(SimpleStreamsIndex, parses_manifest_location)
{
auto json = mpt::load_test_file("good_index.json");
auto index = mp::SimpleStreamsIndex::fromJson(json);
EXPECT_THAT(index.manifest_path, Eq("multiple_versions_manifest.json"));
}
TEST(SimpleStreamsIndex, parses_update_stamp)
{
auto json = mpt::load_test_file("good_index.json");
auto index = mp::SimpleStreamsIndex::fromJson(json);
EXPECT_THAT(index.updated_at, Eq("Thu, 18 May 2017 09:18:01 +0000"));
}
TEST(SimpleStreamsIndex, throws_if_invalid_data_type)
{
auto json = mpt::load_test_file("bad_datatype_index.json");
EXPECT_THROW(mp::SimpleStreamsIndex::fromJson(json), std::runtime_error);
}
TEST(SimpleStreamsIndex, throws_if_missing_index)
{
auto json = mpt::load_test_file("missing_index.json");
EXPECT_THROW(mp::SimpleStreamsIndex::fromJson(json), std::runtime_error);
}
TEST(SimpleStreamsIndex, throws_if_index_is_not_object_type)
{
auto json = mpt::load_test_file("bad_index.json");
EXPECT_THROW(mp::SimpleStreamsIndex::fromJson(json), std::runtime_error);
}
TEST(SimpleStreamsIndex, throws_on_invalid_json)
{
QByteArray json;
EXPECT_THROW(mp::SimpleStreamsIndex::fromJson(json), std::runtime_error);
}
TEST(SimpleStreamsIndex, throws_on_invalid_top_level_type)
{
auto json = mpt::load_test_file("invalid_top_level.json");
EXPECT_THROW(mp::SimpleStreamsIndex::fromJson(json), std::runtime_error);
}
| 2,245
|
C++
|
.cpp
| 59
| 35.491525
| 77
| 0.750115
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,578
|
test_sftpserver.cpp
|
canonical_multipass/tests/test_sftpserver.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "disabling_macros.h"
#include "file_operations.h"
#include "mock_file_ops.h"
#include "mock_logger.h"
#include "mock_platform.h"
#include "mock_recursive_dir_iterator.h"
#include "mock_ssh_process_exit_status.h"
#include "path.h"
#include "sftp_server_test_fixture.h"
#include "stub_ssh_key_provider.h"
#include "temp_dir.h"
#include "temp_file.h"
#include <src/sshfs_mount/sftp_server.h>
#include <multipass/cli/client_platform.h>
#include <multipass/format.h>
#include <multipass/platform.h>
#include <multipass/ssh/ssh_session.h>
#include <queue>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
namespace mcp = multipass::cli::platform;
using namespace testing;
using StringUPtr = std::unique_ptr<ssh_string_struct, void (*)(ssh_string)>;
namespace
{
constexpr uint8_t SFTP_BAD_MESSAGE{255u};
static const int default_uid = mcp::getuid();
static const int default_gid = mcp::getgid();
struct SftpServer : public mp::test::SftpServerTest
{
mp::SftpServer make_sftpserver()
{
return make_sftpserver("");
}
mp::SftpServer make_sftpserver(const std::string& path,
const mp::id_mappings& uid_mappings = {{default_uid, mp::default_id}},
const mp::id_mappings& gid_mappings = {{default_gid, mp::default_id}})
{
mp::SSHSession session{"a", 42, "ubuntu", key_provider};
return {std::move(session), path, path, gid_mappings, uid_mappings, default_uid, default_gid, "sshfs"};
}
auto make_msg(uint8_t type = SFTP_BAD_MESSAGE)
{
auto msg = std::make_unique<sftp_client_message_struct>();
msg->type = type;
messages.push(msg.get());
return msg;
}
auto make_msg_handler()
{
auto msg_handler = [this](auto...) -> sftp_client_message {
if (messages.empty())
return nullptr;
auto msg = messages.front();
messages.pop();
return msg;
};
return msg_handler;
}
auto make_reply_status(sftp_client_message expected_msg, uint32_t expected_status, int& num_calls)
{
auto reply_status = [expected_msg, expected_status, &num_calls](sftp_client_message msg, uint32_t status,
const char*) {
EXPECT_THAT(msg, Eq(expected_msg));
EXPECT_THAT(status, Eq(expected_status));
++num_calls;
return SSH_OK;
};
return reply_status;
}
const mpt::StubSSHKeyProvider key_provider;
mpt::ExitStatusMock exit_status_mock;
std::queue<sftp_client_message> messages;
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
};
struct MessageAndReply
{
MessageAndReply(uint8_t type, uint32_t reply_status) : message_type{type}, reply_status_type{reply_status}
{
}
uint8_t message_type;
uint32_t reply_status_type;
};
struct WhenInvalidMessageReceived : public SftpServer, public ::testing::WithParamInterface<MessageAndReply>
{
};
struct Stat : public SftpServer, public ::testing::WithParamInterface<uint8_t>
{
};
struct WhenInInvalidDir : public SftpServer, public ::testing::WithParamInterface<uint8_t>
{
};
std::string name_for_message(uint8_t message_type)
{
switch (message_type)
{
case SFTP_BAD_MESSAGE:
return "SFTP_BAD_MESSAGE";
case SFTP_CLOSE:
return "SFTP_CLOSE";
case SFTP_READ:
return "SFTP_READ";
case SFTP_FSETSTAT:
return "SFTP_FSETSTAT";
case SFTP_SETSTAT:
return "SFTP_SETSTAT";
case SFTP_FSTAT:
return "SFTP_FSTAT";
case SFTP_READDIR:
return "SFTP_READDIR";
case SFTP_WRITE:
return "SFTP_WRITE";
case SFTP_OPENDIR:
return "SFTP_OPENDIR";
case SFTP_STAT:
return "SFTP_STAT";
case SFTP_LSTAT:
return "SFTP_LSTAT";
case SFTP_READLINK:
return "SFTP_READLINK";
case SFTP_SYMLINK:
return "SFTP_SYMLINK";
case SFTP_RENAME:
return "SFTP_RENAME";
case SFTP_EXTENDED:
return "SFTP_EXTENDED";
case SFTP_MKDIR:
return "SFTP_MKDIR";
case SFTP_RMDIR:
return "SFTP_RMDIR";
case SFTP_OPEN:
return "SFTP_OPEN";
case SFTP_REALPATH:
return "SFTP_REALPATH";
case SFTP_REMOVE:
return "SFTP_REMOVE";
default:
return "Unknown";
}
}
std::string name_for_status(uint32_t status_type)
{
switch (status_type)
{
case SSH_FX_OP_UNSUPPORTED:
return "SSH_FX_OP_UNSUPPORTED";
case SSH_FX_BAD_MESSAGE:
return "SSH_FX_BAD_MESSAGE";
case SSH_FX_NO_SUCH_FILE:
return "SSH_FX_NO_SUCH_FILE";
case SSH_FX_FAILURE:
return "SSH_FX_FAILURE";
default:
return "Unknown";
}
}
std::string string_for_param(const ::testing::TestParamInfo<MessageAndReply>& info)
{
return fmt::format("message_{}_replies_{}", name_for_message(info.param.message_type),
name_for_status(info.param.reply_status_type));
}
std::string string_for_message(const ::testing::TestParamInfo<uint8_t>& info)
{
return fmt::format("message_{}", name_for_message(info.param));
}
auto name_as_char_array(const std::string& name)
{
std::vector<char> out(name.begin(), name.end());
out.push_back('\0');
return out;
}
auto make_data(const std::string& in)
{
StringUPtr out{ssh_string_new(in.size()), ssh_string_free};
ssh_string_fill(out.get(), in.data(), in.size());
return out;
}
bool content_match(const QString& path, const std::string& data)
{
auto content = mpt::load(path);
const int data_size = data.size();
if (content.size() != data_size)
return false;
return std::equal(data.begin(), data.end(), content.begin());
}
enum class Permission
{
Owner,
Group,
Other
};
bool compare_permission(uint32_t ssh_permissions, const QFileInfo& file, Permission perm_type)
{
uint16_t qt_perm_mask{0u}, ssh_perm_mask{0u}, qt_bitshift{0u}, ssh_bitshift{0u};
// Comparing file permissions, sftp uses octal format: (aaabbbccc), QFileInfo uses hex format (aaaa----bbbbcccc)
switch (perm_type)
{
case Permission::Owner:
qt_perm_mask = 0x7000;
qt_bitshift = 12;
ssh_perm_mask = 0700;
ssh_bitshift = 6;
break;
case Permission::Group:
qt_perm_mask = 0x70;
qt_bitshift = 4;
ssh_perm_mask = 070;
ssh_bitshift = 3;
break;
case Permission::Other:
qt_perm_mask = 0x7;
qt_bitshift = 0;
ssh_perm_mask = 07;
ssh_bitshift = 0;
break;
}
return ((ssh_permissions & ssh_perm_mask) >> ssh_bitshift) == ((file.permissions() & qt_perm_mask) >> qt_bitshift);
}
} // namespace
TEST_F(SftpServer, throws_when_failed_to_init)
{
REPLACE(sftp_server_init, [](auto...) { return SSH_ERROR; });
EXPECT_THROW(make_sftpserver(), std::runtime_error);
}
TEST_F(SftpServer, throws_when_sshfs_errors_on_start)
{
bool invoked{false};
auto request_exec = [this, &invoked](ssh_channel, const char* raw_cmd) {
std::string cmd{raw_cmd};
if (cmd.find("sudo sshfs") != std::string::npos)
{
invoked = true;
exit_status_mock.set_exit_status(exit_status_mock.failure_status);
}
return SSH_OK;
};
REPLACE(ssh_channel_request_exec, request_exec);
EXPECT_THROW(make_sftpserver(), std::runtime_error);
EXPECT_TRUE(invoked);
}
TEST_F(SftpServer, throws_on_ssh_failure_read_exit)
{
bool invoked{false};
auto request_exec = [this, &invoked](ssh_channel, const char* raw_cmd) {
std::string cmd{raw_cmd};
if (cmd.find("sudo sshfs") != std::string::npos)
{
invoked = true;
exit_status_mock.set_ssh_rc(SSH_ERROR);
exit_status_mock.set_no_exit();
}
return SSH_OK;
};
REPLACE(ssh_channel_request_exec, request_exec);
EXPECT_THROW(make_sftpserver(), std::runtime_error);
EXPECT_TRUE(invoked);
}
TEST_F(SftpServer, sshfs_restarts_on_timeout)
{
int num_calls{0};
auto request_exec = [this, &num_calls](ssh_channel, const char* raw_cmd) {
std::string cmd{raw_cmd};
if (cmd.find("sudo sshfs") != std::string::npos)
{
if (++num_calls < 3)
{
exit_status_mock.set_ssh_rc(SSH_OK);
exit_status_mock.set_no_exit();
}
}
return SSH_OK;
};
REPLACE(ssh_channel_request_exec, request_exec);
auto sftp = make_sftpserver();
auto get_client_msg = [this, &num_calls](auto...) {
exit_status_mock.set_ssh_rc(SSH_OK);
exit_status_mock.set_exit_status(num_calls == 1 ? exit_status_mock.failure_status
: exit_status_mock.success_status);
return nullptr;
};
REPLACE(sftp_get_client_message, get_client_msg);
sftp.run();
EXPECT_EQ(num_calls, 2);
}
TEST_F(SftpServer, stops_after_a_null_message)
{
auto sftp = make_sftpserver();
REPLACE(sftp_get_client_message, [](auto...) { return nullptr; });
sftp.run();
}
TEST_F(SftpServer, frees_message)
{
auto sftp = make_sftpserver();
auto msg = make_msg(SFTP_BAD_MESSAGE);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
msg_free.expectCalled(1).withValues(msg.get());
}
TEST_F(SftpServer, handles_realpath)
{
mpt::TempFile file;
auto file_name = name_as_char_array(file.name().toStdString());
auto sftp = make_sftpserver(file.name().toStdString());
auto msg = make_msg(SFTP_REALPATH);
msg->filename = file_name.data();
bool invoked{false};
auto reply_name = [&msg, &invoked, &file_name](sftp_client_message cmsg, const char* name, sftp_attributes attr) {
EXPECT_THAT(cmsg, Eq(msg.get()));
EXPECT_THAT(name, StrEq(file_name.data()));
invoked = true;
return SSH_OK;
};
REPLACE(sftp_reply_name, reply_name);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
EXPECT_TRUE(invoked);
}
TEST_F(SftpServer, realpathFailsWhenIdsAreNotMapped)
{
mpt::TempFile file;
auto file_name = name_as_char_array(file.name().toStdString());
auto sftp = make_sftpserver(file.name().toStdString(), {}, {});
auto msg = make_msg(SFTP_REALPATH);
msg->filename = file_name.data();
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
}
TEST_F(SftpServer, handles_opendir)
{
auto dir_name = name_as_char_array(mpt::test_data_path().toStdString());
auto sftp = make_sftpserver(mpt::test_data_path().toStdString());
auto msg = make_msg(SFTP_OPENDIR);
msg->filename = dir_name.data();
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, dir_iterator).WillOnce(Return(std::make_unique<mpt::MockDirIterator>()));
REPLACE(sftp_reply_handle, [](auto...) { return SSH_OK; });
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
}
TEST_F(SftpServer, opendir_not_existing_fails)
{
auto sftp = make_sftpserver(mpt::test_data_path().toStdString());
auto dir_name = name_as_char_array(mpt::test_data_path().toStdString());
const auto msg = make_msg(SFTP_OPENDIR);
msg->filename = dir_name.data();
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, dir_iterator).WillOnce([&](const mp::fs::path&, std::error_code& err) {
err = std::make_error_code(std::errc::no_such_file_or_directory);
return std::make_unique<mpt::MockDirIterator>();
});
REPLACE(sftp_get_client_message, make_msg_handler());
int no_such_file_calls{0};
REPLACE(sftp_reply_status, make_reply_status(msg.get(), SSH_FX_NO_SUCH_FILE, no_such_file_calls));
sftp.run();
EXPECT_EQ(no_such_file_calls, 1);
}
TEST_F(SftpServer, opendir_not_readable_fails)
{
auto sftp = make_sftpserver(mpt::test_data_path().toStdString());
auto dir_name = name_as_char_array(mpt::test_data_path().toStdString());
const auto msg = make_msg(SFTP_OPENDIR);
msg->filename = dir_name.data();
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, dir_iterator).WillOnce([](auto, std::error_code& err) {
err = std::make_error_code(std::errc::permission_denied);
return std::make_unique<mpt::MockDirIterator>();
});
REPLACE(sftp_get_client_message, make_msg_handler());
int perm_denied_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls));
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace),
mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr("Cannot read directory"), HasSubstr(mpt::test_data_path().toStdString())))));
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
}
TEST_F(SftpServer, opendir_no_handle_allocated_fails)
{
auto dir_name = name_as_char_array(mpt::test_data_path().toStdString());
auto sftp = make_sftpserver(mpt::test_data_path().toStdString());
auto msg = make_msg(SFTP_OPENDIR);
msg->filename = dir_name.data();
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, dir_iterator).WillOnce([&](const mp::fs::path&, std::error_code& err) {
err.clear();
return std::make_unique<mpt::MockDirIterator>();
});
EXPECT_CALL(*file_ops, ownerId(_)).WillRepeatedly([](const QFileInfo& file) { return file.ownerId(); });
EXPECT_CALL(*file_ops, groupId(_)).WillRepeatedly([](const QFileInfo& file) { return file.groupId(); });
REPLACE(sftp_handle_alloc, [](auto...) { return nullptr; });
REPLACE(sftp_get_client_message, make_msg_handler());
int failure_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls));
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(StrEq("Cannot allocate handle for opendir()"))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, opendirFailsWhenIdsAreNotMapped)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto open_dir_msg = make_msg(SFTP_OPENDIR);
auto dir_name = name_as_char_array(temp_dir.path().toStdString());
open_dir_msg->filename = dir_name.data();
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(open_dir_msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
}
TEST_F(SftpServer, handles_mkdir)
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
sftp_attributes_struct attr{};
attr.permissions = 0777;
const auto msg = make_msg(SFTP_MKDIR);
msg->filename = new_dir_name.data();
msg->attr = &attr;
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, permissions(A<const mp::fs::path&>(), _, _)).WillOnce([](auto, auto, std::error_code& err) {
err.clear();
});
EXPECT_CALL(*file_ops, ownerId(_)).WillRepeatedly([](const QFileInfo& file) { return file.ownerId(); });
EXPECT_CALL(*file_ops, groupId(_)).WillRepeatedly([](const QFileInfo& file) { return file.groupId(); });
int num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(msg.get(), SSH_FX_OK, num_calls));
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
EXPECT_TRUE(QDir{new_dir_name.data()}.exists());
EXPECT_EQ(num_calls, 1);
}
TEST_F(SftpServer, mkdir_on_existing_dir_fails)
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
QDir dir(new_dir_name.data());
ASSERT_TRUE(dir.mkdir(new_dir_name.data()));
ASSERT_TRUE(dir.exists());
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_MKDIR);
msg->filename = new_dir_name.data();
sftp_attributes_struct attr{};
attr.permissions = 0777;
msg->attr = &attr;
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(AllOf(HasSubstr("mkdir failed for"), HasSubstr(new_dir)))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, mkdir_set_permissions_fails)
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, permissions(_, _, _))
.WillOnce(SetArgReferee<2>(std::make_error_code(std::errc::operation_not_permitted)));
EXPECT_CALL(*file_ops, ownerId(_)).WillRepeatedly([](const QFileInfo& file) { return file.ownerId(); });
EXPECT_CALL(*file_ops, groupId(_)).WillRepeatedly([](const QFileInfo& file) { return file.groupId(); });
auto sftp = make_sftpserver(temp_dir.path().toStdString());
sftp_attributes_struct attr{};
attr.permissions = 0777;
auto msg = make_msg(SFTP_MKDIR);
msg->filename = new_dir_name.data();
msg->attr = &attr;
REPLACE(sftp_get_client_message, make_msg_handler());
int failure_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls));
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(
*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(AllOf(HasSubstr("set permissions failed for"), HasSubstr(new_dir)))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, mkdir_chown_failure_fails)
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
const auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, chown(_, _, _)).WillOnce(Return(-1));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_MKDIR);
msg->filename = new_dir_name.data();
sftp_attributes_struct attr{};
attr.permissions = 0777;
msg->attr = &attr;
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(AllOf(HasSubstr("failed to chown"), HasSubstr(new_dir)))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, mkdirFailsInDirThatsMissingMappedIds)
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
sftp_attributes_struct attr{};
attr.permissions = 0777;
const auto msg = make_msg(SFTP_MKDIR);
msg->filename = new_dir_name.data();
msg->attr = &attr;
int perm_denied_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls));
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
EXPECT_FALSE(QDir{new_dir_name.data()}.exists());
EXPECT_EQ(perm_denied_num_calls, 1);
}
TEST_F(SftpServer, handles_rmdir)
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
QDir dir(new_dir_name.data());
ASSERT_TRUE(dir.mkdir(new_dir_name.data()));
ASSERT_TRUE(dir.exists());
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_RMDIR);
msg->filename = new_dir_name.data();
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_OK, num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
EXPECT_FALSE(dir.exists());
EXPECT_THAT(num_calls, Eq(1));
}
TEST_F(SftpServer, rmdir_non_existing_fails)
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_RMDIR);
msg->filename = new_dir_name.data();
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(AllOf(HasSubstr("rmdir failed for"), HasSubstr(new_dir)))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, rmdir_unable_to_remove_fails)
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
const auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, remove(_, _)).WillOnce(Return(false));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_RMDIR);
msg->filename = new_dir_name.data();
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(AllOf(HasSubstr("rmdir failed for"), HasSubstr(new_dir)))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, rmdirFailsToRemoveDirThatsMissingMappedIds)
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
QDir dir(new_dir_name.data());
ASSERT_TRUE(dir.mkdir(new_dir_name.data()));
ASSERT_TRUE(dir.exists());
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto msg = make_msg(SFTP_RMDIR);
msg->filename = new_dir_name.data();
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
EXPECT_TRUE(dir.exists());
EXPECT_EQ(perm_denied_num_calls, 1);
}
TEST_F(SftpServer, handles_readlink)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto link_name = temp_dir.path() + "/test-link";
mpt::make_file_with_content(file_name);
ASSERT_TRUE(MP_PLATFORM.symlink(file_name.toStdString().c_str(), link_name.toStdString().c_str(),
QFileInfo(file_name).isDir()));
ASSERT_TRUE(QFile::exists(link_name));
ASSERT_TRUE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_READLINK);
auto name = name_as_char_array(link_name.toStdString());
msg->filename = name.data();
int num_calls{0};
auto names_add = [&num_calls, &msg, &file_name](sftp_client_message reply_msg, const char* file, const char*,
sftp_attributes) {
EXPECT_THAT(reply_msg, Eq(msg.get()));
EXPECT_THAT(file, StrEq(file_name.toStdString()));
++num_calls;
return SSH_OK;
};
REPLACE(sftp_reply_names_add, names_add);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_names, [](auto...) { return SSH_OK; });
sftp.run();
EXPECT_THAT(num_calls, Eq(1));
}
TEST_F(SftpServer, readlinkFailsWhenIdsAreNotMapped)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto link_name = temp_dir.path() + "/test-link";
mpt::make_file_with_content(file_name);
ASSERT_TRUE(MP_PLATFORM.symlink(file_name.toStdString().c_str(),
link_name.toStdString().c_str(),
QFileInfo(file_name).isDir()));
ASSERT_TRUE(QFile::exists(link_name));
ASSERT_TRUE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto msg = make_msg(SFTP_READLINK);
auto name = name_as_char_array(link_name.toStdString());
msg->filename = name.data();
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
}
TEST_F(SftpServer, handles_symlink)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto link_name = temp_dir.path() + "/test-link";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_SYMLINK);
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
sftp_attributes_struct attr{};
attr.permissions = 0777;
msg->attr = &attr;
msg->attr->uid = 1000;
msg->attr->gid = 1000;
auto target_name = name_as_char_array(link_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_OK, num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
ASSERT_THAT(num_calls, Eq(1));
QFileInfo info(link_name);
EXPECT_TRUE(QFile::exists(link_name));
EXPECT_TRUE(info.isSymLink());
EXPECT_THAT(info.symLinkTarget(), Eq(file_name));
}
TEST_F(SftpServer, symlink_in_invalid_dir_fails)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_SYMLINK);
auto target = name_as_char_array("bar");
msg->filename = target.data();
auto invalid_link = name_as_char_array("/foo/baz");
REPLACE(sftp_client_message_get_data, [&invalid_link](auto...) { return invalid_link.data(); });
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_THAT(perm_denied_num_calls, Eq(1));
}
TEST_F(SftpServer, broken_symlink_does_not_fail)
{
mpt::TempDir temp_dir;
auto missing_file_name = temp_dir.path() + "/test-file";
auto broken_link_name = temp_dir.path() + "/test-link";
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_SYMLINK);
auto broken_target = name_as_char_array(missing_file_name.toStdString());
msg->filename = broken_target.data();
sftp_attributes_struct attr{};
attr.permissions = 0777;
msg->attr = &attr;
msg->attr->uid = 1000;
msg->attr->gid = 1000;
auto broken_link = name_as_char_array(broken_link_name.toStdString());
REPLACE(sftp_client_message_get_data, [&broken_link](auto...) { return broken_link.data(); });
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_OK, num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
ASSERT_THAT(num_calls, Eq(1));
QFileInfo info(broken_link_name);
EXPECT_TRUE(info.isSymLink());
EXPECT_FALSE(QFile::exists(info.symLinkTarget()));
EXPECT_FALSE(QFile::exists(missing_file_name));
}
TEST_F(SftpServer, symlink_failure_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto link_name = temp_dir.path() + "/test-link";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_SYMLINK);
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(link_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
const auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, symlink(_, _, _)).WillOnce(Return(false));
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(AllOf(HasSubstr("failure creating symlink from"),
HasSubstr(file_name.toStdString()),
HasSubstr(link_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, symlinkFailsWhenMissingMappedIds)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto link_name = temp_dir.path() + "/test-link";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto msg = make_msg(SFTP_SYMLINK);
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
sftp_attributes_struct attr{};
attr.permissions = 0777;
msg->attr = &attr;
msg->attr->uid = 1000;
msg->attr->gid = 1000;
auto target_name = name_as_char_array(link_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
ASSERT_THAT(perm_denied_num_calls, Eq(1));
QFileInfo info(link_name);
EXPECT_FALSE(QFile::exists(link_name));
EXPECT_FALSE(info.isSymLink());
}
TEST_F(SftpServer, handles_rename)
{
mpt::TempDir temp_dir;
auto old_name = temp_dir.path() + "/test-file";
auto new_name = temp_dir.path() + "/test-renamed";
mpt::make_file_with_content(old_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_RENAME);
auto name = name_as_char_array(old_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(new_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_OK, num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
ASSERT_THAT(num_calls, Eq(1));
EXPECT_TRUE(QFile::exists(new_name));
EXPECT_FALSE(QFile::exists(old_name));
}
TEST_F(SftpServer, rename_cannot_remove_target_fails)
{
mpt::TempDir temp_dir;
auto old_name = temp_dir.path() + "/test-file";
auto new_name = temp_dir.path() + "/test-renamed";
mpt::make_file_with_content(old_name);
mpt::make_file_with_content(new_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_RENAME);
auto name = name_as_char_array(old_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(new_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
const auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, remove(_)).WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops, ownerId(_)).WillRepeatedly([](const QFileInfo& file) { return file.ownerId(); });
EXPECT_CALL(*mock_file_ops, groupId(_)).WillRepeatedly([](const QFileInfo& file) { return file.groupId(); });
EXPECT_CALL(*mock_file_ops, exists(A<const QFileInfo&>())).WillRepeatedly([](const QFileInfo& file) {
return file.exists();
});
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(AllOf(
HasSubstr("cannot remove"), HasSubstr(new_name.toStdString()), HasSubstr("for renaming")))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, rename_failure_fails)
{
mpt::TempDir temp_dir;
auto old_name = temp_dir.path() + "/test-file";
auto new_name = temp_dir.path() + "/test-renamed";
mpt::make_file_with_content(old_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_RENAME);
auto name = name_as_char_array(old_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(new_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
const auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, rename(_, _)).WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops, ownerId(_)).WillRepeatedly([](const QFileInfo& file) { return file.ownerId(); });
EXPECT_CALL(*mock_file_ops, groupId(_)).WillRepeatedly([](const QFileInfo& file) { return file.groupId(); });
EXPECT_CALL(*mock_file_ops, exists(A<const QFileInfo&>())).WillRepeatedly([](const QFileInfo& file) {
return file.exists();
});
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(
*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(AllOf(HasSubstr("failed renaming"), HasSubstr(old_name.toStdString()),
HasSubstr(new_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, rename_invalid_target_fails)
{
mpt::TempDir temp_dir;
auto old_name = temp_dir.path() + "/test-file";
auto invalid_target = name_as_char_array("/foo/bar");
mpt::make_file_with_content(old_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_RENAME);
auto name = name_as_char_array(old_name.toStdString());
msg->filename = name.data();
REPLACE(sftp_client_message_get_data, [&invalid_target](auto...) { return invalid_target.data(); });
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_THAT(perm_denied_num_calls, Eq(1));
}
TEST_F(SftpServer, renameFailsWhenSourceFileIdsAreNotMapped)
{
mpt::TempDir temp_dir;
auto old_name = temp_dir.path() + "/test-file";
auto new_name = temp_dir.path() + "/test-renamed";
mpt::make_file_with_content(old_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto msg = make_msg(SFTP_RENAME);
auto name = name_as_char_array(old_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(new_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace),
mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(HasSubstr(old_name.toStdString()))));
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
EXPECT_TRUE(QFile::exists(old_name));
EXPECT_FALSE(QFile::exists(new_name));
}
TEST_F(SftpServer, renameFailsWhenTargetFileIdsAreNotMapped)
{
mpt::TempDir temp_dir;
auto old_name = temp_dir.path() + "/test-file";
auto new_name = temp_dir.path() + "/test-renamed";
mpt::make_file_with_content(old_name);
mpt::make_file_with_content(new_name);
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, ownerId(_))
.WillOnce([](const QFileInfo& file) { return file.ownerId(); })
.WillOnce([](const QFileInfo& file) { return file.ownerId() + 1; });
EXPECT_CALL(*mock_file_ops, groupId(_)).WillOnce([](const QFileInfo& file) { return file.groupId(); });
EXPECT_CALL(*mock_file_ops, exists(A<const QFileInfo&>())).WillRepeatedly([](const QFileInfo& file) {
return file.exists();
});
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_RENAME);
auto name = name_as_char_array(old_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(new_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace),
mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(HasSubstr(new_name.toStdString()))));
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
EXPECT_TRUE(QFile::exists(old_name));
EXPECT_TRUE(QFile::exists(new_name));
}
TEST_F(SftpServer, handles_remove)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
ASSERT_TRUE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_REMOVE);
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_OK, num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
ASSERT_THAT(num_calls, Eq(1));
EXPECT_FALSE(QFile::exists(file_name));
}
TEST_F(SftpServer, remove_non_existing_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
ASSERT_FALSE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_REMOVE);
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr("cannot remove"), HasSubstr(file_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, removeFailsWhenIdsAreNotMapped)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
ASSERT_TRUE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto msg = make_msg(SFTP_REMOVE);
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
EXPECT_TRUE(QFile::exists(file_name));
}
TEST_F(SftpServer, open_in_write_mode_creates_file)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
ASSERT_FALSE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
sftp_attributes_struct attr{};
attr.permissions = 0777;
auto name = name_as_char_array(file_name.toStdString());
auto msg = make_msg(SFTP_OPEN);
msg->flags |= SSH_FXF_WRITE | SSH_FXF_CREAT;
msg->attr = &attr;
msg->filename = name.data();
const auto [platform, mock_platform_guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*platform, chown).WillOnce(Return(0));
bool reply_handle_invoked{false};
auto reply_handle = [&reply_handle_invoked](auto...) {
reply_handle_invoked = true;
return SSH_OK;
};
REPLACE(sftp_reply_handle, reply_handle);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
ASSERT_TRUE(reply_handle_invoked);
EXPECT_TRUE(QFile::exists(file_name));
}
TEST_F(SftpServer, open_in_truncate_mode_truncates_file)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
ASSERT_TRUE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_OPEN);
msg->flags |= SSH_FXF_WRITE | SSH_FXF_TRUNC;
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
bool reply_handle_invoked{false};
auto reply_handle = [&reply_handle_invoked](auto...) {
reply_handle_invoked = true;
return SSH_OK;
};
REPLACE(sftp_reply_handle, reply_handle);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
QFile file(file_name);
ASSERT_TRUE(reply_handle_invoked);
EXPECT_EQ(file.size(), 0);
}
TEST_F(SftpServer, open_unable_to_open_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
ASSERT_TRUE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
sftp_attributes_struct attr{};
attr.permissions = 0777;
auto name = name_as_char_array(file_name.toStdString());
auto msg = make_msg(SFTP_OPEN);
msg->flags |= SSH_FXF_READ | SSH_FXF_WRITE | SSH_FXF_APPEND | SSH_FXF_EXCL;
msg->attr = &attr;
msg->filename = name.data();
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, symlink_status).WillOnce([](auto, std::error_code& err) {
err.clear();
return mp::fs::file_status{mp::fs::file_type::regular};
});
EXPECT_CALL(*file_ops, open_fd).WillOnce([](auto path, auto...) {
errno = EACCES;
return std::make_unique<mp::NamedFd>(path, -1);
});
EXPECT_CALL(*file_ops, ownerId(_)).WillRepeatedly([](const QFileInfo& file) { return file.ownerId(); });
EXPECT_CALL(*file_ops, groupId(_)).WillRepeatedly([](const QFileInfo& file) { return file.groupId(); });
REPLACE(sftp_get_client_message, make_msg_handler());
int failure_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls));
logger_scope.mock_logger->screen_logs(mpl::Level::error);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace),
mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr("Cannot open"), HasSubstr(file_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, open_unable_to_get_status_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
ASSERT_TRUE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
sftp_attributes_struct attr{};
attr.permissions = 0777;
auto name = name_as_char_array(file_name.toStdString());
auto msg = make_msg(SFTP_OPEN);
msg->flags |= SSH_FXF_READ | SSH_FXF_WRITE | SSH_FXF_APPEND | SSH_FXF_EXCL;
msg->attr = &attr;
msg->filename = name.data();
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, symlink_status).WillOnce([](auto, std::error_code& err) {
err = std::make_error_code(std::errc::permission_denied);
return mp::fs::file_status{mp::fs::file_type::unknown};
});
REPLACE(sftp_get_client_message, make_msg_handler());
int failure_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, failure_num_calls));
logger_scope.mock_logger->screen_logs(mpl::Level::error);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace),
mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr("Cannot get status"), HasSubstr(file_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, open_chown_failure_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
const auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, chown(_, _, _)).WillOnce(Return(-1));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_OPEN);
msg->flags |= SSH_FXF_WRITE | SSH_FXF_CREAT;
sftp_attributes_struct attr{};
attr.permissions = 0777;
msg->attr = &attr;
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::error);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr("failed to chown"), HasSubstr(file_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, open_no_handle_allocated_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
ASSERT_FALSE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_OPEN);
msg->flags |= SSH_FXF_WRITE | SSH_FXF_CREAT;
sftp_attributes_struct attr{};
attr.permissions = 0777;
msg->attr = &attr;
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_handle_alloc, [](auto...) { return nullptr; });
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::error);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(StrEq("Cannot allocate handle for open()"))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, openFailsWhenIdsAreNotMapped)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto msg = make_msg(SFTP_OPEN);
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
}
TEST_F(SftpServer, openNonExistingFileFailsWhenDirIdsAreNotMapped)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto msg = make_msg(SFTP_OPEN);
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
QFile file(file_name);
EXPECT_FALSE(file.exists());
}
TEST_F(SftpServer, handles_readdir)
{
mpt::TempDir temp_dir;
QDir dir_entry(temp_dir.path());
auto test_dir = temp_dir.path() + "/test-dir-entry";
ASSERT_TRUE(dir_entry.mkdir(test_dir));
auto test_file = temp_dir.path() + "/test-file";
mpt::make_file_with_content(test_file);
auto test_link = temp_dir.path() + "/test-link";
ASSERT_TRUE(MP_PLATFORM.symlink(test_file.toStdString().c_str(),
test_link.toStdString().c_str(),
QFileInfo(test_file).isDir()));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto readdir_msg = make_msg(SFTP_READDIR);
auto readdir_msg_final = make_msg(SFTP_READDIR);
std::vector<mp::fs::path> expected_entries = {".", "..", "test-dir-entry", "test-file", "test-link"};
auto entries_read = 0ul;
auto directory_entry = mpt::MockDirectoryEntry{};
EXPECT_CALL(directory_entry, path).WillRepeatedly([&]() -> const mp::fs::path& {
return expected_entries[entries_read - 1];
});
EXPECT_CALL(directory_entry, is_symlink()).WillRepeatedly([&]() {
return expected_entries[entries_read - 1] == "test-link";
});
auto dir_iterator = mpt::MockDirIterator{};
EXPECT_CALL(dir_iterator, hasNext).WillRepeatedly([&] { return entries_read != expected_entries.size(); });
EXPECT_CALL(dir_iterator, next).WillRepeatedly(DoAll([&] { entries_read++; }, ReturnRef(directory_entry)));
REPLACE(sftp_handle, [&dir_iterator](auto...) { return &dir_iterator; });
REPLACE(sftp_get_client_message, make_msg_handler());
int eof_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(readdir_msg_final.get(), SSH_FX_EOF, eof_num_calls));
std::vector<mp::fs::path> given_entries;
auto reply_names_add = [&given_entries](auto, const char* file, auto, auto) {
given_entries.push_back(file);
return SSH_OK;
};
REPLACE(sftp_reply_names_add, reply_names_add);
REPLACE(sftp_reply_names, [](auto...) { return SSH_OK; });
sftp.run();
EXPECT_EQ(eof_num_calls, 1);
EXPECT_THAT(given_entries, ContainerEq(expected_entries));
}
TEST_F(SftpServer, handles_readdir_attributes_preserved)
{
mpt::TempDir temp_dir;
QDir dir_entry(temp_dir.path());
const auto test_file_name = "test-file";
auto test_file = temp_dir.path() + "/" + test_file_name;
mpt::make_file_with_content(test_file, "some content for the file to give it non-zero size");
QFileDevice::Permissions expected_permissions =
QFileDevice::WriteOwner | QFileDevice::ExeGroup | QFileDevice::ReadOther;
QFile::setPermissions(test_file, expected_permissions);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto readdir_msg = make_msg(SFTP_READDIR);
auto readdir_msg_final = make_msg(SFTP_READDIR);
const auto temp_dir_path = mp::fs::path{temp_dir.path().toStdString()};
std::vector<mp::fs::path> expected_entries = {temp_dir_path / ".",
temp_dir_path / "..",
temp_dir_path / "test-file"};
auto entries_read = 0ul;
auto directory_entry = mpt::MockDirectoryEntry{};
EXPECT_CALL(directory_entry, path).WillRepeatedly([&]() -> const mp::fs::path& {
return expected_entries[entries_read - 1];
});
auto dir_iterator = mpt::MockDirIterator{};
EXPECT_CALL(dir_iterator, hasNext).WillRepeatedly([&] { return entries_read != expected_entries.size(); });
EXPECT_CALL(dir_iterator, next).WillRepeatedly(DoAll([&] { entries_read++; }, ReturnRef(directory_entry)));
REPLACE(sftp_handle, [&dir_iterator](auto...) { return &dir_iterator; });
REPLACE(sftp_get_client_message, make_msg_handler());
int eof_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(readdir_msg_final.get(), SSH_FX_EOF, eof_num_calls));
sftp_attributes_struct test_file_attrs{};
auto get_test_file_attributes = [&](auto, const char* file, auto, sftp_attributes attr) {
if (strcmp(file, test_file_name) == 0)
{
test_file_attrs = *attr;
}
return SSH_OK;
};
REPLACE(sftp_reply_names_add, get_test_file_attributes);
REPLACE(sftp_reply_names, [](auto...) { return SSH_OK; });
sftp.run();
EXPECT_EQ(eof_num_calls, 1);
QFileInfo test_file_info(test_file);
EXPECT_EQ(test_file_attrs.size, (uint64_t)test_file_info.size());
EXPECT_EQ(test_file_attrs.gid, test_file_info.groupId());
EXPECT_EQ(test_file_attrs.uid, test_file_info.ownerId());
EXPECT_EQ(test_file_attrs.atime,
(uint32_t)test_file_info.lastModified().toSecsSinceEpoch()); // atime64 is zero, expected?
EXPECT_TRUE(compare_permission(test_file_attrs.permissions, test_file_info, Permission::Owner));
EXPECT_TRUE(compare_permission(test_file_attrs.permissions, test_file_info, Permission::Group));
EXPECT_TRUE(compare_permission(test_file_attrs.permissions, test_file_info, Permission::Other));
}
TEST_F(SftpServer, handles_close)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto open_dir_msg = make_msg(SFTP_OPENDIR);
auto dir_name = name_as_char_array(temp_dir.path().toStdString());
open_dir_msg->filename = dir_name.data();
auto close_msg = make_msg(SFTP_CLOSE);
void* id{nullptr};
auto handle_alloc = [&id](sftp_session, void* info) {
id = info;
return ssh_string_new(4);
};
int ok_num_calls{0};
auto reply_status = make_reply_status(close_msg.get(), SSH_FX_OK, ok_num_calls);
REPLACE(sftp_reply_handle, [](auto...) { return SSH_OK; });
REPLACE(sftp_handle_alloc, handle_alloc);
REPLACE(sftp_handle, [&id](auto...) { return id; });
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_reply_names, [](auto...) { return SSH_OK; });
REPLACE(sftp_handle_remove, [](auto...) {});
sftp.run();
EXPECT_THAT(ok_num_calls, Eq(1));
}
TEST_F(SftpServer, handles_fstat)
{
mpt::TempDir temp_dir;
const auto content = std::string{"whatever just some content bla bla"};
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name, content);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto open_msg = make_msg(SFTP_OPEN);
auto name = name_as_char_array(file_name.toStdString());
open_msg->filename = name.data();
open_msg->flags |= SSH_FXF_READ;
auto fstat_msg = make_msg(SFTP_FSTAT);
void* id{nullptr};
auto handle_alloc = [&id](sftp_session, void* info) {
id = info;
return ssh_string_new(4);
};
int num_calls{0};
auto reply_attr = [&num_calls, &fstat_msg, expected_size = content.size()](sftp_client_message reply_msg,
sftp_attributes attr) {
EXPECT_THAT(reply_msg, Eq(fstat_msg.get()));
EXPECT_THAT(attr->size, Eq(expected_size));
++num_calls;
return SSH_OK;
};
REPLACE(sftp_reply_attr, reply_attr);
REPLACE(sftp_reply_handle, [](auto...) { return SSH_OK; });
REPLACE(sftp_handle_alloc, handle_alloc);
REPLACE(sftp_handle, [&id](auto...) { return id; });
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
EXPECT_THAT(num_calls, Eq(1));
}
TEST_F(SftpServer, handles_fsetstat)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto open_msg = make_msg(SFTP_OPEN);
auto name = name_as_char_array(file_name.toStdString());
sftp_attributes_struct attr{};
const int expected_size = 7777;
attr.size = expected_size;
attr.flags = SSH_FILEXFER_ATTR_SIZE;
attr.permissions = 0777;
open_msg->filename = name.data();
open_msg->attr = &attr;
open_msg->flags |= SSH_FXF_WRITE | SSH_FXF_TRUNC | SSH_FXF_CREAT;
auto fsetstat_msg = make_msg(SFTP_FSETSTAT);
fsetstat_msg->attr = &attr;
void* id{nullptr};
auto handle_alloc = [&id](sftp_session, void* info) {
id = info;
return ssh_string_new(4);
};
int num_calls{0};
auto reply_status = make_reply_status(fsetstat_msg.get(), SSH_FX_OK, num_calls);
REPLACE(sftp_reply_handle, [](auto...) { return SSH_OK; });
REPLACE(sftp_handle_alloc, handle_alloc);
REPLACE(sftp_handle, [&id](auto...) { return id; });
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
QFile file(file_name);
ASSERT_THAT(num_calls, Eq(1));
EXPECT_TRUE(file.exists());
EXPECT_THAT(file.size(), Eq(expected_size));
}
TEST_F(SftpServer, handles_setstat)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_SETSTAT);
auto name = name_as_char_array(file_name.toStdString());
sftp_attributes_struct attr{};
const int expected_size = 7777;
attr.size = expected_size;
attr.flags = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS;
attr.permissions = 0777;
msg->filename = name.data();
msg->attr = &attr;
msg->flags = SSH_FXF_WRITE;
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_OK, num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
QFile file(file_name);
ASSERT_THAT(num_calls, Eq(1));
EXPECT_THAT(file.size(), Eq(expected_size));
}
TEST_F(SftpServer, setstat_correctly_modifies_file_timestamp)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
QFileInfo orig_info{file_name};
auto original_time = orig_info.lastModified().toSecsSinceEpoch();
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_SETSTAT);
auto name = name_as_char_array(file_name.toStdString());
sftp_attributes_struct attr{};
attr.mtime = static_cast<uint32_t>(original_time + 1);
attr.flags = SSH_FILEXFER_ATTR_ACMODTIME;
msg->filename = name.data();
msg->attr = &attr;
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_OK, num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
ASSERT_THAT(num_calls, Eq(1));
QFileInfo modified_info{file_name};
auto new_time = modified_info.lastModified().toSecsSinceEpoch();
EXPECT_EQ(new_time, original_time + 1);
}
TEST_F(SftpServer, setstat_resize_failure_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_SETSTAT);
auto name = name_as_char_array(file_name.toStdString());
sftp_attributes_struct attr{};
const int expected_size = 7777;
attr.size = expected_size;
attr.flags = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS;
attr.permissions = 0777;
msg->filename = name.data();
msg->attr = &attr;
msg->flags = SSH_FXF_WRITE;
const auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, resize(_, _)).WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops, ownerId(_)).WillRepeatedly([](const QFileInfo& file) { return file.ownerId(); });
EXPECT_CALL(*mock_file_ops, groupId(_)).WillRepeatedly([](const QFileInfo& file) { return file.groupId(); });
EXPECT_CALL(*mock_file_ops, exists(A<const QFileInfo&>())).WillRepeatedly([](const QFileInfo& file) {
return file.exists();
});
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr("cannot resize"), HasSubstr(file_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, setstat_set_permissions_failure_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto name = name_as_char_array(file_name.toStdString());
sftp_attributes_struct attr{};
attr.size = 7777;
attr.flags = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS;
attr.permissions = 0777;
auto msg = make_msg(SFTP_SETSTAT);
msg->filename = name.data();
msg->attr = &attr;
msg->flags = SSH_FXF_WRITE;
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, resize).WillOnce(Return(true));
EXPECT_CALL(*file_ops, permissions(_, _, _))
.WillOnce(SetArgReferee<2>(std::make_error_code(std::errc::permission_denied)));
EXPECT_CALL(*file_ops, ownerId(_)).WillRepeatedly([](const QFileInfo& file) { return file.ownerId(); });
EXPECT_CALL(*file_ops, groupId(_)).WillRepeatedly([](const QFileInfo& file) { return file.groupId(); });
EXPECT_CALL(*file_ops, exists(A<const QFileInfo&>())).WillRepeatedly([](const QFileInfo& file) {
return file.exists();
});
REPLACE(sftp_get_client_message, make_msg_handler());
int failure_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls));
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr("set permissions failed for"), HasSubstr(file_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, setstat_chown_failure_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString(),
{{default_uid, -1}, {1001, 1001}},
{{default_gid, -1}, {1001, 1001}});
auto msg = make_msg(SFTP_SETSTAT);
auto name = name_as_char_array(file_name.toStdString());
sftp_attributes_struct attr{};
const int expected_size = 7777;
attr.size = expected_size;
attr.flags = SSH_FILEXFER_ATTR_UIDGID;
attr.permissions = 0777;
attr.uid = 1001;
attr.gid = 1001;
msg->filename = name.data();
msg->attr = &attr;
msg->flags = SSH_FXF_WRITE;
const auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, chown(_, _, _)).WillOnce(Return(-1));
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr("cannot set ownership for"), HasSubstr(file_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, setstat_utime_failure_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_SETSTAT);
auto name = name_as_char_array(file_name.toStdString());
sftp_attributes_struct attr{};
const int expected_size = 7777;
attr.size = expected_size;
attr.flags = SSH_FILEXFER_ATTR_ACMODTIME;
attr.permissions = 0777;
msg->filename = name.data();
msg->attr = &attr;
msg->flags = SSH_FXF_WRITE;
const auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, utime(_, _, _)).WillOnce(Return(-1));
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr("cannot set modification date for"), HasSubstr(file_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, setstatFailsWhenMissingMappedIds)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
QFile file(file_name);
auto file_size = file.size();
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto msg = make_msg(SFTP_SETSTAT);
auto name = name_as_char_array(file_name.toStdString());
sftp_attributes_struct attr{};
attr.size = 777;
attr.flags = SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS;
attr.permissions = 0777;
msg->filename = name.data();
msg->attr = &attr;
msg->flags = SSH_FXF_WRITE;
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
EXPECT_EQ(file.size(), file_size);
}
TEST_F(SftpServer, setstatChownFailsWhenNewIdsAreNotMapped)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_SETSTAT);
auto name = name_as_char_array(file_name.toStdString());
sftp_attributes_struct attr{};
attr.flags = SSH_FILEXFER_ATTR_UIDGID;
attr.uid = 1001;
attr.gid = 1001;
msg->filename = name.data();
msg->attr = &attr;
msg->flags = SSH_FXF_WRITE;
auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, chown(_, _, _)).Times(0);
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
}
TEST_F(SftpServer, handles_writes)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto write_msg1 = make_msg(SFTP_WRITE);
auto data1 = make_data("The answer is ");
write_msg1->data = data1.get();
write_msg1->offset = 0;
auto write_msg2 = make_msg(SFTP_WRITE);
auto data2 = make_data("always 42");
write_msg2->data = data2.get();
write_msg2->offset = ssh_string_len(data1.get());
const auto path = mp::fs::path{temp_dir.path().toStdString()} / "test-file";
const auto fd = 123;
const auto named_fd = std::make_pair(path, fd);
std::stringstream stream;
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, lseek).WillRepeatedly(Return(true));
EXPECT_CALL(*file_ops, write(fd, _, _)).WillRepeatedly([&stream](int, const void* buf, size_t nbytes) {
stream.write((const char*)buf, nbytes);
return nbytes;
});
REPLACE(sftp_handle, [&named_fd](auto...) { return (void*)&named_fd; });
REPLACE(sftp_get_client_message, make_msg_handler());
int num_calls{0};
auto reply_status = [&num_calls](auto, uint32_t status, auto) {
EXPECT_TRUE(status == SSH_FX_OK);
++num_calls;
return SSH_OK;
};
REPLACE(sftp_reply_status, reply_status);
sftp.run();
ASSERT_EQ(num_calls, 2);
EXPECT_EQ(stream.str(), "The answer is always 42");
}
TEST_F(SftpServer, write_cannot_seek_fails)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto write_msg = make_msg(SFTP_WRITE);
auto data1 = make_data("The answer is ");
write_msg->data = data1.get();
write_msg->offset = 10;
const auto path = mp::fs::path{temp_dir.path().toStdString()} / "test-file";
const auto fd = 123;
const auto named_fd = std::make_pair(path, fd);
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, lseek(fd, _, _)).WillRepeatedly(Return(-1));
REPLACE(sftp_handle, [&named_fd](auto...) { return (void*)&named_fd; });
REPLACE(sftp_get_client_message, make_msg_handler());
int failure_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(write_msg.get(), SSH_FX_FAILURE, failure_num_calls));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, write_failure_fails)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto write_msg = make_msg(SFTP_WRITE);
auto data1 = make_data("The answer is ");
write_msg->data = data1.get();
write_msg->offset = 10;
const auto path = mp::fs::path{temp_dir.path().toStdString()} / "test-file";
const auto fd = 123;
const auto named_fd = std::make_pair(path, fd);
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, lseek(fd, _, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*file_ops, write(fd, _, _)).WillRepeatedly(Return(-1));
REPLACE(sftp_handle, [&named_fd](auto...) { return (void*)&named_fd; });
REPLACE(sftp_get_client_message, make_msg_handler());
int failure_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(write_msg.get(), SSH_FX_FAILURE, failure_num_calls));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, handles_reads)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
std::string given_data{"some text"};
auto read_msg = make_msg(SFTP_READ);
read_msg->offset = 0;
read_msg->len = given_data.size();
const auto path = mp::fs::path{temp_dir.path().toStdString()} / "test-file";
const auto fd = 123;
const auto named_fd = std::make_pair(path, fd);
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, lseek(fd, _, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*file_ops, read(fd, _, _)).WillRepeatedly([&given_data, r = 0](int, void* buf, size_t count) mutable {
::memcpy(buf, given_data.c_str() + r, count);
r += count;
return count;
});
REPLACE(sftp_handle, [&named_fd](auto...) { return (void*)&named_fd; });
REPLACE(sftp_get_client_message, make_msg_handler());
int num_calls{0};
auto reply_data = [&](sftp_client_message msg, const void* data, int len) {
EXPECT_GT(len, 0);
EXPECT_EQ(msg, read_msg.get());
std::string data_read{reinterpret_cast<const char*>(data), static_cast<std::string::size_type>(len)};
EXPECT_EQ(data_read, given_data);
++num_calls;
return SSH_OK;
};
REPLACE(sftp_reply_data, reply_data);
sftp.run();
ASSERT_EQ(num_calls, 1);
}
TEST_F(SftpServer, read_cannot_seek_fails)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
std::string given_data{"some text"};
const int seek_pos{10};
auto read_msg = make_msg(SFTP_READ);
read_msg->offset = seek_pos;
read_msg->len = given_data.size();
const auto path = mp::fs::path{temp_dir.path().toStdString()} / "test-file";
const auto fd = 123;
const auto named_fd = std::make_pair(path, fd);
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, lseek(fd, _, _)).WillRepeatedly(Return(-1));
REPLACE(sftp_handle, [&named_fd](auto...) { return (void*)&named_fd; });
REPLACE(sftp_get_client_message, make_msg_handler());
int failure_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(read_msg.get(), SSH_FX_FAILURE, failure_num_calls));
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(
*logger_scope.mock_logger,
log(mpl::Level::trace,
mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(
AllOf(HasSubstr(fmt::format("cannot seek to position {} in", seek_pos)), HasSubstr(path.string())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, read_returns_failure_fails)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
std::string given_data{"some text"};
auto read_msg = make_msg(SFTP_READ);
read_msg->offset = 0;
read_msg->len = given_data.size();
const auto path = mp::fs::path{temp_dir.path().toStdString()} / "test-file";
const auto fd = 123;
const auto named_fd = std::make_pair(path, fd);
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, lseek(fd, _, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*file_ops, read(fd, _, _)).WillOnce(Return(-1));
REPLACE(sftp_handle, [&named_fd](auto...) { return (void*)&named_fd; });
REPLACE(sftp_get_client_message, make_msg_handler());
int failure_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(read_msg.get(), SSH_FX_FAILURE, failure_num_calls));
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(
*logger_scope.mock_logger,
log(Eq(mpl::Level::trace),
mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(AllOf(HasSubstr("read failed for"), HasSubstr(path.string())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, read_returns_zero_end_of_file)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto read_msg = make_msg(SFTP_READ);
read_msg->offset = 0;
read_msg->len = 10;
const auto path = mp::fs::path{temp_dir.path().toStdString()} / "test-file";
const auto fd = 123;
const auto named_fd = std::make_pair(path, fd);
const auto [file_ops, mock_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*file_ops, lseek(fd, _, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*file_ops, read(fd, _, _)).WillOnce(Return(0));
REPLACE(sftp_handle, [&named_fd](auto...) { return (void*)&named_fd; });
REPLACE(sftp_get_client_message, make_msg_handler());
int eof_num_calls{0};
REPLACE(sftp_reply_status, make_reply_status(read_msg.get(), SSH_FX_EOF, eof_num_calls));
sftp.run();
EXPECT_EQ(eof_num_calls, 1);
}
TEST_F(SftpServer, handle_extended_link)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto link_name = temp_dir.path() + "/test-link";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_EXTENDED);
auto submessage = name_as_char_array("hardlink@openssh.com");
msg->submessage = submessage.data();
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(link_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_OK, num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
ASSERT_THAT(num_calls, Eq(1));
QFileInfo info(link_name);
EXPECT_TRUE(QFile::exists(link_name));
EXPECT_TRUE(content_match(link_name, "this is a test file"));
}
TEST_F(SftpServer, extended_link_in_invalid_dir_fails)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_EXTENDED);
auto submessage = name_as_char_array("hardlink@openssh.com");
msg->submessage = submessage.data();
auto invalid_path = name_as_char_array("bar");
msg->filename = invalid_path.data();
auto invalid_link = name_as_char_array("/foo/baz");
REPLACE(sftp_client_message_get_data, [&invalid_link](auto...) { return invalid_link.data(); });
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_THAT(perm_denied_num_calls, Eq(1));
}
TEST_F(SftpServer, extended_link_failure_fails)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto link_name = temp_dir.path() + "/test-link";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_EXTENDED);
auto submessage = name_as_char_array("hardlink@openssh.com");
msg->submessage = submessage.data();
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(link_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
const auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, link(_, _)).WillOnce(Return(false));
int failure_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_FAILURE, failure_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::trace), mpt::MockLogger::make_cstring_matcher(StrEq("sftp server")),
mpt::MockLogger::make_cstring_matcher(AllOf(HasSubstr("failed creating link from"),
HasSubstr(file_name.toStdString()),
HasSubstr(link_name.toStdString())))));
sftp.run();
EXPECT_EQ(failure_num_calls, 1);
}
TEST_F(SftpServer, extendedLinkFailureFailsWhenSourceFileIdsAreNotMapped)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto link_name = temp_dir.path() + "/test-link";
mpt::make_file_with_content(file_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto msg = make_msg(SFTP_EXTENDED);
auto submessage = name_as_char_array("hardlink@openssh.com");
msg->submessage = submessage.data();
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(link_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_EQ(perm_denied_num_calls, 1);
QFileInfo info(link_name);
EXPECT_FALSE(QFile::exists(link_name));
}
TEST_F(SftpServer, handle_extended_rename)
{
mpt::TempDir temp_dir;
auto old_name = temp_dir.path() + "/test-file";
auto new_name = temp_dir.path() + "/test-renamed";
mpt::make_file_with_content(old_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_EXTENDED);
auto submessage = name_as_char_array("posix-rename@openssh.com");
msg->submessage = submessage.data();
auto name = name_as_char_array(old_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(new_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_OK, num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
ASSERT_THAT(num_calls, Eq(1));
EXPECT_TRUE(QFile::exists(new_name));
EXPECT_FALSE(QFile::exists(old_name));
}
TEST_F(SftpServer, extendedRenameFailsWhenMissingMappedIds)
{
mpt::TempDir temp_dir;
auto old_name = temp_dir.path() + "/test-file";
auto new_name = temp_dir.path() + "/test-renamed";
mpt::make_file_with_content(old_name);
auto sftp = make_sftpserver(temp_dir.path().toStdString(), {}, {});
auto msg = make_msg(SFTP_EXTENDED);
auto submessage = name_as_char_array("posix-rename@openssh.com");
msg->submessage = submessage.data();
auto name = name_as_char_array(old_name.toStdString());
msg->filename = name.data();
auto target_name = name_as_char_array(new_name.toStdString());
REPLACE(sftp_client_message_get_data, [&target_name](auto...) { return target_name.data(); });
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_reply_status, reply_status);
REPLACE(sftp_get_client_message, make_msg_handler());
sftp.run();
ASSERT_THAT(perm_denied_num_calls, Eq(1));
EXPECT_FALSE(QFile::exists(new_name));
EXPECT_TRUE(QFile::exists(old_name));
}
TEST_F(SftpServer, extended_rename_in_invalid_dir_fails)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_EXTENDED);
auto submessage = name_as_char_array("posix-rename@openssh.com");
msg->submessage = submessage.data();
auto invalid_path = name_as_char_array("/foo/bar");
msg->filename = invalid_path.data();
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_THAT(perm_denied_num_calls, Eq(1));
}
TEST_F(SftpServer, invalid_extended_fails)
{
auto sftp = make_sftpserver();
auto msg = make_msg(SFTP_EXTENDED);
auto submessage = name_as_char_array("invalid submessage");
msg->submessage = submessage.data();
REPLACE(sftp_get_client_message, make_msg_handler());
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_OP_UNSUPPORTED, num_calls);
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_THAT(num_calls, Eq(1));
}
TEST_P(Stat, handles)
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
auto link_name = temp_dir.path() + "/test-link";
mpt::make_file_with_content(file_name);
auto msg_type = GetParam();
ASSERT_TRUE(MP_PLATFORM.symlink(file_name.toStdString().c_str(), link_name.toStdString().c_str(),
QFileInfo(file_name).isDir()));
ASSERT_TRUE(QFile::exists(link_name));
ASSERT_TRUE(QFile::exists(file_name));
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(msg_type);
auto name = name_as_char_array(link_name.toStdString());
msg->filename = name.data();
REPLACE(sftp_get_client_message, make_msg_handler());
int num_calls{0};
QFile file(file_name);
uint64_t expected_size = msg_type == SFTP_LSTAT ? file_name.size() : file.size();
auto reply_attr = [&num_calls, &msg, expected_size](sftp_client_message reply_msg, sftp_attributes attr) {
EXPECT_THAT(reply_msg, Eq(msg.get()));
EXPECT_THAT(attr->size, Eq(expected_size));
++num_calls;
return SSH_OK;
};
REPLACE(sftp_reply_attr, reply_attr);
sftp.run();
EXPECT_THAT(num_calls, Eq(1));
}
TEST_P(WhenInInvalidDir, fails)
{
auto msg_type = GetParam();
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(msg_type);
auto invalid_path = name_as_char_array("/foo/bar");
msg->filename = invalid_path.data();
int perm_denied_num_calls{0};
auto reply_status = make_reply_status(msg.get(), SSH_FX_PERMISSION_DENIED, perm_denied_num_calls);
REPLACE(sftp_get_client_message, make_msg_handler());
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_THAT(perm_denied_num_calls, Eq(1));
}
namespace
{
INSTANTIATE_TEST_SUITE_P(SftpServer, Stat, ::testing::Values(SFTP_LSTAT, SFTP_STAT), string_for_message);
INSTANTIATE_TEST_SUITE_P(SftpServer, WhenInInvalidDir,
::testing::Values(SFTP_MKDIR, SFTP_RMDIR, SFTP_OPEN, SFTP_OPENDIR, SFTP_READLINK,
SFTP_REALPATH, SFTP_REMOVE, SFTP_RENAME, SFTP_SETSTAT, SFTP_STAT),
string_for_message);
TEST_P(WhenInvalidMessageReceived, replies_failure)
{
mpt::TempDir temp_dir;
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto params = GetParam();
auto file_name = name_as_char_array(temp_dir.path().toStdString() + "this.does.not.exist");
EXPECT_FALSE(QFile::exists(file_name.data()));
auto msg = make_msg(params.message_type);
msg->filename = file_name.data();
auto data = name_as_char_array("");
REPLACE(sftp_client_message_get_data, [&data](auto...) { return data.data(); });
REPLACE(sftp_get_client_message, make_msg_handler());
int num_calls{0};
auto reply_status = make_reply_status(msg.get(), params.reply_status_type, num_calls);
REPLACE(sftp_reply_status, reply_status);
sftp.run();
EXPECT_THAT(num_calls, Eq(1));
}
INSTANTIATE_TEST_SUITE_P(
SftpServer, WhenInvalidMessageReceived,
::testing::Values(
MessageAndReply{SFTP_BAD_MESSAGE, SSH_FX_OP_UNSUPPORTED}, MessageAndReply{SFTP_CLOSE, SSH_FX_BAD_MESSAGE},
MessageAndReply{SFTP_READ, SSH_FX_BAD_MESSAGE}, MessageAndReply{SFTP_FSETSTAT, SSH_FX_BAD_MESSAGE},
MessageAndReply{SFTP_FSTAT, SSH_FX_BAD_MESSAGE}, MessageAndReply{SFTP_READDIR, SSH_FX_BAD_MESSAGE},
MessageAndReply{SFTP_WRITE, SSH_FX_BAD_MESSAGE}, MessageAndReply{SFTP_OPENDIR, SSH_FX_NO_SUCH_FILE},
MessageAndReply{SFTP_STAT, SSH_FX_NO_SUCH_FILE}, MessageAndReply{SFTP_LSTAT, SSH_FX_NO_SUCH_FILE},
MessageAndReply{SFTP_READLINK, SSH_FX_NO_SUCH_FILE}, MessageAndReply{SFTP_SYMLINK, SSH_FX_PERMISSION_DENIED},
MessageAndReply{SFTP_RENAME, SSH_FX_NO_SUCH_FILE}, MessageAndReply{SFTP_SETSTAT, SSH_FX_NO_SUCH_FILE},
MessageAndReply{SFTP_EXTENDED, SSH_FX_FAILURE}),
string_for_param);
TEST_F(SftpServer, DISABLE_ON_WINDOWS(mkdir_chown_honors_maps_in_the_host))
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
const auto [mock_platform, guard] = mpt::MockPlatform::inject();
int host_uid = QFileInfo(temp_dir.path()).ownerId();
int host_gid = QFileInfo(temp_dir.path()).groupId();
int sftp_uid = 1008;
int sftp_gid = 1009;
mp::id_mappings uid_mappings{{host_uid, sftp_uid}};
mp::id_mappings gid_mappings{{host_gid, sftp_gid}};
auto sftp = make_sftpserver(temp_dir.path().toStdString(), uid_mappings, gid_mappings);
auto msg = make_msg(SFTP_MKDIR);
msg->filename = new_dir_name.data();
sftp_attributes_struct attr{};
msg->attr = &attr;
msg->attr->uid = sftp_uid;
msg->attr->gid = sftp_gid;
REPLACE(sftp_get_client_message, make_msg_handler());
EXPECT_CALL(*mock_platform, chown(_, host_uid, host_gid)).Times(1);
EXPECT_CALL(*mock_platform, chown(_, sftp_uid, sftp_gid)).Times(0);
sftp.run();
}
TEST_F(SftpServer, DISABLE_ON_WINDOWS(mkdir_chown_works_when_ids_are_not_mapped))
{
mpt::TempDir temp_dir;
auto new_dir = fmt::format("{}/mkdir-test", temp_dir.path().toStdString());
auto new_dir_name = name_as_char_array(new_dir);
const auto [mock_platform, guard] = mpt::MockPlatform::inject();
auto sftp = make_sftpserver(temp_dir.path().toStdString());
auto msg = make_msg(SFTP_MKDIR);
msg->filename = new_dir_name.data();
sftp_attributes_struct attr{};
msg->attr = &attr;
msg->attr->uid = 1003;
msg->attr->gid = 1004;
REPLACE(sftp_get_client_message, make_msg_handler());
QFileInfo parent_dir(temp_dir.path());
EXPECT_CALL(*mock_platform, chown(_, parent_dir.ownerId(), parent_dir.groupId())).Times(1);
sftp.run();
}
TEST_F(SftpServer, DISABLE_ON_WINDOWS(open_chown_honors_maps_in_the_host))
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
const auto [mock_platform, guard] = mpt::MockPlatform::inject();
int host_uid = QFileInfo(temp_dir.path()).ownerId();
int host_gid = QFileInfo(temp_dir.path()).groupId();
int sftp_uid = 1008;
int sftp_gid = 1009;
mp::id_mappings uid_mappings{{host_uid, sftp_uid}};
mp::id_mappings gid_mappings{{host_gid, sftp_gid}};
auto sftp = make_sftpserver(temp_dir.path().toStdString(), uid_mappings, gid_mappings);
auto msg = make_msg(SFTP_OPEN);
msg->flags |= SSH_FXF_WRITE | SSH_FXF_CREAT;
sftp_attributes_struct attr{};
attr.permissions = 0777;
msg->attr = &attr;
auto name = name_as_char_array(file_name.toStdString());
msg->filename = name.data();
msg->attr->uid = sftp_uid;
msg->attr->gid = sftp_gid;
REPLACE(sftp_get_client_message, make_msg_handler());
EXPECT_CALL(*mock_platform, chown(_, host_uid, host_gid)).WillOnce(Return(-1));
EXPECT_CALL(*mock_platform, chown(_, sftp_uid, sftp_gid)).Times(0);
sftp.run();
}
TEST_F(SftpServer, DISABLE_ON_WINDOWS(setstat_chown_honors_maps_in_the_host))
{
mpt::TempDir temp_dir;
auto file_name = temp_dir.path() + "/test-file";
mpt::make_file_with_content(file_name);
int host_uid = QFileInfo(temp_dir.path()).ownerId();
int host_gid = QFileInfo(temp_dir.path()).groupId();
int sftp_uid = 1024;
int sftp_gid = 1025;
mp::id_mappings uid_mappings{{host_uid, sftp_uid}};
mp::id_mappings gid_mappings{{host_gid, sftp_gid}};
auto sftp = make_sftpserver(temp_dir.path().toStdString(), uid_mappings, gid_mappings);
auto msg = make_msg(SFTP_SETSTAT);
auto name = name_as_char_array(file_name.toStdString());
sftp_attributes_struct attr{};
const int expected_size = 7777;
attr.size = expected_size;
attr.flags = SSH_FILEXFER_ATTR_UIDGID;
attr.permissions = 0777;
msg->filename = name.data();
msg->attr = &attr;
msg->flags = SSH_FXF_WRITE;
msg->attr->uid = sftp_uid;
msg->attr->gid = sftp_gid;
REPLACE(sftp_get_client_message, make_msg_handler());
const auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, chown(_, host_uid, host_gid)).Times(1);
EXPECT_CALL(*mock_platform, chown(_, sftp_uid, sftp_gid)).Times(0);
sftp.run();
}
} // namespace
| 98,147
|
C++
|
.cpp
| 2,184
| 39.000916
| 120
| 0.659419
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,579
|
test_daemon_launch.cpp
|
canonical_multipass/tests/test_daemon_launch.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "blueprint_test_lambdas.h"
#include "common.h"
#include "daemon_test_fixture.h"
#include "mock_image_host.h"
#include "mock_platform.h"
#include "mock_server_reader_writer.h"
#include "mock_settings.h"
#include "mock_virtual_machine.h"
#include "mock_vm_blueprint_provider.h"
#include "mock_vm_image_vault.h"
#include "stub_virtual_machine.h"
#include "stub_vm_image_vault.h"
#include <src/daemon/daemon.h>
#include <multipass/constants.h>
#include <multipass/format.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
struct TestDaemonLaunch : public mpt::DaemonTestFixture
{
void SetUp() override
{
EXPECT_CALL(mock_settings, register_handler).WillRepeatedly(Return(nullptr));
EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber());
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillRepeatedly(Return("true"));
}
mpt::MockPlatform::GuardedMock attr{mpt::MockPlatform::inject<NiceMock>()};
mpt::MockPlatform* mock_platform = attr.first;
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject<StrictMock>();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
};
TEST_F(TestDaemonLaunch, blueprintFoundMountsWorkspaceWithNameOverride)
{
const std::string name{"ultimo-blueprint"};
const std::string command_line_name{"name-override"};
static constexpr int num_cores = 4;
const std::string mem_size_str{"4G"};
const auto mem_size = mp::MemorySize(mem_size_str);
const std::string disk_space_str{"25G"};
const auto disk_space = mp::MemorySize(disk_space_str);
const std::string remote{"release"};
const std::string release{"focal"};
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, command_line_name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(
mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, std::nullopt, name));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
mp::LaunchRequest request;
request.set_instance_name(command_line_name);
request.set_image(name);
mp::LaunchReply reply;
StrictMock<mpt::MockServerReaderWriter<mp::LaunchReply, mp::LaunchRequest>> writer{};
EXPECT_CALL(writer, Write(_, _)).WillRepeatedly([&reply](const mp::LaunchReply& written_reply, auto) -> bool {
reply = written_reply;
return true;
});
auto status = call_daemon_slot(daemon, &mp::Daemon::launch, request, writer);
EXPECT_EQ(reply.workspaces_to_be_created_size(), 1);
if (reply.workspaces_to_be_created_size() > 0)
{
EXPECT_EQ(reply.workspaces_to_be_created(0), command_line_name);
}
}
TEST_F(TestDaemonLaunch, v2BlueprintFoundPropagatesSha)
{
const std::string name{"ultimo-blueprint"};
const std::string command_line_name{"name-override"};
static constexpr int num_cores = 4;
const std::string mem_size_str{"4G"};
const auto mem_size = mp::MemorySize(mem_size_str);
const std::string disk_space_str{"25G"};
const auto disk_space = mp::MemorySize(disk_space_str);
const std::string remote{"release"};
const std::string release{"focal"};
const std::string sha256{"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"};
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, command_line_name));
// The expectation of this test is set in fetch_image_lambda().
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _))
.WillOnce(mpt::fetch_image_lambda(release, remote, true));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, std::nullopt,
std::nullopt, sha256));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
mp::LaunchRequest request;
request.set_instance_name(command_line_name);
request.set_image(name);
mp::LaunchReply reply;
StrictMock<mpt::MockServerReaderWriter<mp::LaunchReply, mp::LaunchRequest>> writer{};
EXPECT_CALL(writer, Write(_, _)).WillRepeatedly([&reply](const mp::LaunchReply& written_reply, auto) -> bool {
reply = written_reply;
return true;
});
auto status = call_daemon_slot(daemon, &mp::Daemon::launch, request, writer);
}
| 6,238
|
C++
|
.cpp
| 125
| 45.056
| 120
| 0.713205
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,580
|
test_daemon_start.cpp
|
canonical_multipass/tests/test_daemon_start.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
// The daemon test fixture contains premock code so it must be included first.
#include "daemon_test_fixture.h"
#include "common.h"
#include "mock_image_host.h"
#include "mock_mount_handler.h"
#include "mock_platform.h"
#include "mock_server_reader_writer.h"
#include "mock_settings.h"
#include "mock_virtual_machine.h"
#include "mock_vm_image_vault.h"
#include <src/daemon/daemon.h>
#include <multipass/constants.h>
#include <multipass/format.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
struct TestDaemonStart : public mpt::DaemonTestFixture
{
void SetUp() override
{
EXPECT_CALL(mock_settings, register_handler).WillRepeatedly(Return(nullptr));
EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber());
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillRepeatedly(Return("true"));
}
const std::string mock_instance_name{"real-zebraphant"};
const std::string mac_addr{"52:54:00:73:76:28"};
std::vector<mp::NetworkInterface> extra_interfaces;
mpt::MockPlatform::GuardedMock attr{mpt::MockPlatform::inject<NiceMock>()};
mpt::MockPlatform* mock_platform = attr.first;
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject<StrictMock>();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
};
TEST_F(TestDaemonStart, successfulStartOkStatus)
{
auto mock_factory = use_a_mock_vm_factory();
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
auto instance_ptr = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce([&instance_ptr](auto&&...) {
return std::move(instance_ptr);
});
EXPECT_CALL(*instance_ptr, wait_until_ssh_up).WillRepeatedly(Return());
EXPECT_CALL(*instance_ptr, current_state()).WillRepeatedly(Return(mp::VirtualMachine::State::off));
EXPECT_CALL(*instance_ptr, start()).Times(1);
config_builder.data_directory = temp_dir->path();
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mp::Daemon daemon{config_builder.build()};
mp::StartRequest request;
request.mutable_instance_names()->add_instance_name(mock_instance_name);
StrictMock<mpt::MockServerReaderWriter<mp::StartReply, mp::StartRequest>> mock_server{};
EXPECT_CALL(mock_server, Write(_, _)).Times(1);
auto status = call_daemon_slot(daemon, &mp::Daemon::start, request, std::move(mock_server));
EXPECT_TRUE(status.ok());
}
TEST_F(TestDaemonStart, exitlessSshProcessExceptionDoesNotShowMessage)
{
auto event_dopoll = [](auto...) { return SSH_ERROR; };
REPLACE(ssh_event_dopoll, event_dopoll);
std::vector<mp::NetworkInterface> extra_interfaces{{"eth7", "52:54:00:99:99:99", true}};
auto mock_factory = use_a_mock_vm_factory();
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
auto instance_ptr = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce([&instance_ptr](auto&&...) {
return std::move(instance_ptr);
});
EXPECT_CALL(*instance_ptr, wait_until_ssh_up).WillRepeatedly(Return());
EXPECT_CALL(*instance_ptr, current_state()).WillRepeatedly(Return(mp::VirtualMachine::State::off));
EXPECT_CALL(*instance_ptr, start()).Times(1);
// New networks configuration was moved to the instance settings handler, add_network_interface mustn't be called.
EXPECT_CALL(*instance_ptr, add_network_interface(_, _, _)).Times(0);
config_builder.data_directory = temp_dir->path();
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mp::Daemon daemon{config_builder.build()};
mp::StartRequest request;
request.mutable_instance_names()->add_instance_name(mock_instance_name);
StrictMock<mpt::MockServerReaderWriter<mp::StartReply, mp::StartRequest>> server;
EXPECT_CALL(server, Write(_, _)).Times(1);
auto status = call_daemon_slot(daemon, &mp::Daemon::start, request, std::move(server));
EXPECT_THAT(status.error_message(), StrEq(""));
EXPECT_TRUE(status.ok());
}
TEST_F(TestDaemonStart, unknownStateDoesNotStart)
{
auto mock_factory = use_a_mock_vm_factory();
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
auto instance_ptr = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce([&instance_ptr](auto&&...) {
return std::move(instance_ptr);
});
EXPECT_CALL(*instance_ptr, current_state()).WillRepeatedly(Return(mp::VirtualMachine::State::unknown));
EXPECT_CALL(*instance_ptr, start()).Times(0);
config_builder.data_directory = temp_dir->path();
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mp::Daemon daemon{config_builder.build()};
mp::StartRequest request;
request.mutable_instance_names()->add_instance_name(mock_instance_name);
StrictMock<mpt::MockServerReaderWriter<mp::StartReply, mp::StartRequest>> mock_server;
EXPECT_CALL(mock_server, Write(_, _)).Times(1);
auto status = call_daemon_slot(daemon, &mp::Daemon::start, request, std::move(mock_server));
EXPECT_FALSE(status.ok());
}
TEST_F(TestDaemonStart, suspendingStateDoesNotStartHasError)
{
auto mock_factory = use_a_mock_vm_factory();
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
auto instance_ptr = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce([&instance_ptr](auto&&...) {
return std::move(instance_ptr);
});
EXPECT_CALL(*instance_ptr, current_state()).WillRepeatedly(Return(mp::VirtualMachine::State::suspending));
EXPECT_CALL(*instance_ptr, start()).Times(0);
config_builder.data_directory = temp_dir->path();
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mp::Daemon daemon{config_builder.build()};
mp::StartRequest request;
request.mutable_instance_names()->add_instance_name(mock_instance_name);
StrictMock<mpt::MockServerReaderWriter<mp::StartReply, mp::StartRequest>> mock_server;
EXPECT_CALL(mock_server, Write(_, _)).Times(1);
auto status = call_daemon_slot(daemon, &mp::Daemon::start, request, std::move(mock_server));
EXPECT_FALSE(status.ok());
EXPECT_THAT(status.error_message(),
HasSubstr(fmt::format("Cannot start the instance \'{}\' while suspending", mock_instance_name)));
}
TEST_F(TestDaemonStart, definedMountsInitializedDuringStart)
{
const std::string fake_target_path{"/home/luke/skywalker"}, fake_source_path{"/home/han/solo"};
const mp::id_mappings uid_mappings{{1000, 1001}}, gid_mappings{{1002, 1003}};
const mp::VMMount mount{fake_source_path, gid_mappings, uid_mappings, mp::VMMount::MountType::Native};
std::unordered_map<std::string, mp::VMMount> mounts{{fake_target_path, mount}};
auto mock_factory = use_a_mock_vm_factory();
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces, mounts));
auto mock_mount_handler = std::make_unique<mpt::MockMountHandler>();
EXPECT_CALL(*mock_mount_handler, activate_impl).Times(1);
auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_vm, wait_until_ssh_up).WillRepeatedly(Return());
EXPECT_CALL(*mock_vm, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::off));
EXPECT_CALL(*mock_vm, start).Times(1);
EXPECT_CALL(*mock_vm, make_native_mount_handler).WillOnce(Return(std::move(mock_mount_handler)));
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm)));
config_builder.data_directory = temp_dir->path();
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mp::Daemon daemon{config_builder.build()};
mp::StartRequest request;
request.mutable_instance_names()->add_instance_name(mock_instance_name);
StrictMock<mpt::MockServerReaderWriter<mp::StartReply, mp::StartRequest>> mock_server;
EXPECT_CALL(mock_server, Write(_, _)).Times(1);
auto status = call_daemon_slot(daemon, &mp::Daemon::start, request, std::move(mock_server));
EXPECT_TRUE(status.ok());
}
TEST_F(TestDaemonStart, removingMountOnFailedStart)
{
const std::string fake_target_path{"/home/luke/skywalker"}, fake_source_path{"/home/han/solo"};
const mp::id_mappings uid_mappings{{1000, 1001}}, gid_mappings{{1002, 1003}};
const mp::VMMount mount{fake_source_path, gid_mappings, uid_mappings, mp::VMMount::MountType::Native};
std::unordered_map<std::string, mp::VMMount> mounts{{fake_target_path, mount}};
auto mock_factory = use_a_mock_vm_factory();
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces, mounts));
auto error = "failed to start mount";
auto mock_mount_handler = std::make_unique<mpt::MockMountHandler>();
EXPECT_CALL(*mock_mount_handler, activate_impl).WillOnce(Throw(std::runtime_error{error}));
auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_vm, wait_until_ssh_up).WillRepeatedly(Return());
EXPECT_CALL(*mock_vm, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::off));
EXPECT_CALL(*mock_vm, start).Times(1);
EXPECT_CALL(*mock_vm, make_native_mount_handler).WillOnce(Return(std::move(mock_mount_handler)));
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm)));
auto log = fmt::format("Removing mount \"{}\" from '{}': {}\n", fake_target_path, mock_instance_name, error);
StrictMock<mpt::MockServerReaderWriter<mp::StartReply, mp::StartRequest>> server;
EXPECT_CALL(server, Write(_, _));
EXPECT_CALL(server, Write(Property(&mp::StartReply::log_line, Eq(log)), _));
config_builder.data_directory = temp_dir->path();
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mp::Daemon daemon{config_builder.build()};
mp::StartRequest request;
request.mutable_instance_names()->add_instance_name(mock_instance_name);
auto status = call_daemon_slot(daemon, &mp::Daemon::start, request, std::move(server));
EXPECT_TRUE(status.ok());
}
| 11,295
|
C++
|
.cpp
| 193
| 53.979275
| 118
| 0.723285
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,581
|
main.cpp
|
canonical_multipass/tests/main.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_standard_paths.h"
#include <QCoreApplication>
namespace mp = multipass;
// Normally one would just use libgtest_main but our static library dependencies
// also define main... DAMN THEM!
int main(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
QCoreApplication::setApplicationName("multipass_tests");
::testing::InitGoogleTest(&argc, argv);
mp::test::MockStandardPaths::mockit();
return RUN_ALL_TESTS();
}
| 1,107
|
C++
|
.cpp
| 30
| 34.533333
| 80
| 0.749767
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,582
|
test_daemon_snapshot_restore.cpp
|
canonical_multipass/tests/test_daemon_snapshot_restore.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "daemon_test_fixture.h"
#include "mock_platform.h"
#include "mock_server_reader_writer.h"
#include "mock_settings.h"
#include "mock_snapshot.h"
#include "mock_virtual_machine.h"
#include "mock_vm_image_vault.h"
#include "multipass/exceptions/snapshot_exceptions.h"
#include <multipass/exceptions/not_implemented_on_this_backend_exception.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct TestDaemonSnapshotRestoreBase : public mpt::DaemonTestFixture
{
void SetUp() override
{
EXPECT_CALL(mock_settings, register_handler).WillRepeatedly(Return(nullptr));
EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber());
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
}
auto build_daemon_with_mock_instance()
{
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
auto instance_ptr = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
auto* ret_instance = instance_ptr.get();
EXPECT_CALL(*instance_ptr, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::restarting));
EXPECT_CALL(mock_factory, create_virtual_machine).WillOnce(Return(std::move(instance_ptr)));
config_builder.data_directory = temp_dir->path();
auto daemon = std::make_unique<mp::Daemon>(config_builder.build());
return std::pair{std::move(daemon), ret_instance};
}
mpt::MockPlatform::GuardedMock mock_platform_injection{mpt::MockPlatform::inject<NiceMock>()};
mpt::MockPlatform& mock_platform = *mock_platform_injection.first;
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject<StrictMock>();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
mpt::MockVirtualMachineFactory& mock_factory = *use_a_mock_vm_factory();
std::vector<mp::NetworkInterface> extra_interfaces;
const std::string mac_addr{"52:54:00:73:76:28"};
const std::string mock_instance_name{"real-zebraphant"};
};
struct TestDaemonSnapshot : public TestDaemonSnapshotRestoreBase
{
using TestDaemonSnapshotRestoreBase::SetUp; // It seems this is what signals gtest the type to use for test names
};
struct TestDaemonRestore : public TestDaemonSnapshotRestoreBase
{
using TestDaemonSnapshotRestoreBase::SetUp; // It seems this is what signals gtest the type to use for test names
};
struct SnapshotRPCTypes
{
using Request = mp::SnapshotRequest;
using Reply = mp::SnapshotReply;
inline static constexpr auto daemon_slot_ptr = &mp::Daemon::snapshot;
};
struct RestoreRPCTypes
{
using Request = mp::RestoreRequest;
using Reply = mp::RestoreReply;
inline static constexpr auto daemon_slot_ptr = &mp::Daemon::restore;
};
template <typename RPCTypes>
struct TestDaemonSnapshotRestoreCommon : public TestDaemonSnapshotRestoreBase
{
using TestDaemonSnapshotRestoreBase::SetUp; // It seems this is what signals gtest the type to use for test names
using MockServer = StrictMock<mpt::MockServerReaderWriter<typename RPCTypes::Reply, typename RPCTypes::Request>>;
};
using RPCTypes = Types<SnapshotRPCTypes, RestoreRPCTypes>;
TYPED_TEST_SUITE(TestDaemonSnapshotRestoreCommon, RPCTypes);
TYPED_TEST(TestDaemonSnapshotRestoreCommon, failsOnMissingInstance)
{
static constexpr auto missing_instance = "foo";
typename TypeParam::Request request{};
request.set_instance(missing_instance);
mp::Daemon daemon{this->config_builder.build()};
auto status =
this->call_daemon_slot(daemon, TypeParam::daemon_slot_ptr, request, typename TestFixture::MockServer{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::NOT_FOUND);
EXPECT_EQ(status.error_message(), fmt::format("instance \"{}\" does not exist", missing_instance));
}
TYPED_TEST(TestDaemonSnapshotRestoreCommon, failsOnActiveInstance)
{
typename TypeParam::Request request{};
request.set_instance(this->mock_instance_name);
auto [daemon, instance] = this->build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::restarting));
auto status =
this->call_daemon_slot(*daemon, TypeParam::daemon_slot_ptr, request, typename TestFixture::MockServer{});
EXPECT_EQ(status.error_code(), grpc::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), HasSubstr("stopped"));
}
TEST_F(TestDaemonSnapshot, failsIfBackendDoesNotSupportSnapshots)
{
EXPECT_CALL(mock_factory, require_snapshots_support)
.WillRepeatedly(Throw(mp::NotImplementedOnThisBackendException{"snapshots"}));
mp::Daemon daemon{config_builder.build()};
auto status = call_daemon_slot(daemon,
&mp::Daemon::snapshot,
mp::SnapshotRequest{},
StrictMock<mpt::MockServerReaderWriter<mp::SnapshotReply, mp::SnapshotRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INTERNAL);
EXPECT_THAT(status.error_message(), AllOf(HasSubstr("not implemented"), HasSubstr("snapshots")));
}
TEST_F(TestDaemonSnapshot, failsOnInvalidSnapshotName)
{
mp::SnapshotRequest request{};
request.set_instance(mock_instance_name);
request.set_snapshot("%$@#*& \t\n nope, no.can.do");
auto [daemon, instance] = build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::stopped));
auto status = call_daemon_slot(*daemon,
&mp::Daemon::snapshot,
request,
StrictMock<mpt::MockServerReaderWriter<mp::SnapshotReply, mp::SnapshotRequest>>{});
EXPECT_EQ(status.error_code(), grpc::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), HasSubstr("Invalid snapshot name"));
}
TEST_F(TestDaemonSnapshot, failsOnRepeatedSnapshotName)
{
static constexpr auto* snapshot_name = "Obelix";
mp::SnapshotRequest request{};
request.set_instance(mock_instance_name);
request.set_snapshot(snapshot_name);
auto [daemon, instance] = build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::off));
EXPECT_CALL(*instance, take_snapshot(_, Eq(snapshot_name), _))
.WillOnce(Throw(mp::SnapshotNameTakenException{mock_instance_name, snapshot_name}));
auto status = call_daemon_slot(*daemon,
&mp::Daemon::snapshot,
request,
StrictMock<mpt::MockServerReaderWriter<mp::SnapshotReply, mp::SnapshotRequest>>{});
EXPECT_EQ(status.error_code(), grpc::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), AllOf(HasSubstr(mock_instance_name), HasSubstr(snapshot_name)));
}
TEST_F(TestDaemonSnapshot, usesProvidedSnapshotProperties)
{
static constexpr auto* snapshot_name = "orangutan";
static constexpr auto* snapshot_comment = "not a monkey";
mp::SnapshotRequest request{};
request.set_instance(mock_instance_name);
request.set_snapshot(snapshot_name);
request.set_comment(snapshot_comment);
auto [daemon, instance] = build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::stopped));
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*snapshot, get_name).WillOnce(Return(snapshot_name));
EXPECT_CALL(*instance, take_snapshot(_, Eq(snapshot_name), Eq(snapshot_comment))).WillOnce(Return(snapshot));
auto server = StrictMock<mpt::MockServerReaderWriter<mp::SnapshotReply, mp::SnapshotRequest>>{};
EXPECT_CALL(server, Write(Property(&mp::SnapshotReply::snapshot, Eq(snapshot_name)), _)).WillOnce(Return(true));
auto status = call_daemon_slot(*daemon, &mp::Daemon::snapshot, request, server);
EXPECT_EQ(status.error_code(), grpc::OK);
}
TEST_F(TestDaemonSnapshot, acceptsEmptySnapshotName)
{
static constexpr auto* generated_name = "asdrubal";
mp::SnapshotRequest request{};
request.set_instance(mock_instance_name);
auto [daemon, instance] = build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::off));
auto snapshot = std::make_shared<NiceMock<mpt::MockSnapshot>>();
EXPECT_CALL(*snapshot, get_name).WillOnce(Return(generated_name));
EXPECT_CALL(*instance, take_snapshot(_, IsEmpty(), IsEmpty())).WillOnce(Return(snapshot));
auto server = StrictMock<mpt::MockServerReaderWriter<mp::SnapshotReply, mp::SnapshotRequest>>{};
EXPECT_CALL(server, Write(Property(&mp::SnapshotReply::snapshot, Eq(generated_name)), _)).WillOnce(Return(true));
auto status = call_daemon_slot(*daemon, &mp::Daemon::snapshot, request, server);
EXPECT_EQ(status.error_code(), grpc::OK);
}
TEST_F(TestDaemonRestore, failsIfBackendDoesNotSupportSnapshots)
{
mp::RestoreRequest request{};
request.set_instance(mock_instance_name);
auto [daemon, instance] = build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::stopped));
EXPECT_CALL(*instance, get_snapshot(A<const std::string&>()))
.WillOnce(Throw(mp::NotImplementedOnThisBackendException{"snapshots"}));
auto status = call_daemon_slot(*daemon,
&mp::Daemon::restore,
request,
StrictMock<mpt::MockServerReaderWriter<mp::RestoreReply, mp::RestoreRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INTERNAL);
EXPECT_THAT(status.error_message(), AllOf(HasSubstr("not implemented"), HasSubstr("snapshots")));
}
TEST_F(TestDaemonRestore, failsOnMissingSnapshotName)
{
static constexpr auto* missing_snapshot_name = "albatross";
mp::RestoreRequest request{};
request.set_instance(mock_instance_name);
request.set_snapshot(missing_snapshot_name);
auto [daemon, instance] = build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::stopped));
EXPECT_CALL(*instance, get_snapshot(TypedEq<const std::string&>(missing_snapshot_name)))
.WillOnce(Throw(mp::NoSuchSnapshotException{mock_instance_name, missing_snapshot_name}));
auto status = call_daemon_slot(*daemon,
&mp::Daemon::restore,
request,
StrictMock<mpt::MockServerReaderWriter<mp::RestoreReply, mp::RestoreRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::NOT_FOUND);
EXPECT_THAT(status.error_message(),
AllOf(HasSubstr("No such snapshot"), HasSubstr(mock_instance_name), HasSubstr(missing_snapshot_name)));
}
TEST_F(TestDaemonRestore, restoresSnapshotDirectlyIfDestructive)
{
static constexpr auto* snapshot_name = "dodo";
mp::RestoreRequest request{};
request.set_instance(mock_instance_name);
request.set_snapshot(snapshot_name);
request.set_destructive(true);
auto [daemon, instance] = build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::stopped));
EXPECT_CALL(*instance, restore_snapshot(Eq(snapshot_name), _)).Times(1);
StrictMock<mpt::MockServerReaderWriter<mp::RestoreReply, mp::RestoreRequest>> server{};
EXPECT_CALL(server, Write).Times(2);
auto status = call_daemon_slot(*daemon, &mp::Daemon::restore, request, server);
EXPECT_EQ(status.error_code(), grpc::OK);
}
} // namespace
| 12,492
|
C++
|
.cpp
| 234
| 47.132479
| 119
| 0.716559
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,583
|
common.cpp
|
canonical_multipass/tests/common.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <multipass/network_interface.h>
#include <multipass/network_interface_info.h>
#include <QString>
#include <ostream>
QT_BEGIN_NAMESPACE
void PrintTo(const QString& qstr, std::ostream* os)
{
*os << "QString(\"" << qUtf8Printable(qstr) << "\")";
}
QT_END_NAMESPACE
void multipass::PrintTo(const NetworkInterface& net, std::ostream* os)
{
*os << "NetworkInterface(id=\"" << net.id << "\")";
}
void multipass::PrintTo(const NetworkInterfaceInfo& net, std::ostream* os)
{
*os << "NetworkInterfaceInfo(id=\"" << net.id << "\")";
}
| 1,200
|
C++
|
.cpp
| 35
| 32.314286
| 74
| 0.724525
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,584
|
test_remote_settings_handler.cpp
|
canonical_multipass/tests/test_remote_settings_handler.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_client_rpc.h"
#include "mock_terminal.h"
#include <src/client/cli/cmd/remote_settings_handler.h>
#include <multipass/exceptions/settings_exceptions.h>
#include <sstream>
namespace mp = multipass;
namespace mpt = mp::test;
using namespace testing;
namespace
{
class RemoteSettingsTest : public Test
{
public:
void SetUp() override
{
EXPECT_CALL(mock_term, cout).WillRepeatedly(ReturnRef(fake_cout));
EXPECT_CALL(mock_term, cerr).WillRepeatedly(ReturnRef(fake_cerr));
}
template <typename RequestType, typename ReplyType>
static std::unique_ptr<mpt::MockClientReaderWriter<RequestType, ReplyType>>
make_mock_reader_writer() // just a helper to minimize boilerplate
{
return std::make_unique<mpt::MockClientReaderWriter<RequestType, ReplyType>>();
}
// Create a callable that returns an owning plain pointer (as expected by grpc), but spares ownership until called.
// This is useful in mock actions for grpc functions that return ownership-transferring ptrs.
// Note that we'd better not just `EXPECT_CALL(...).Return(uptr.release())` because that would release the ptr right
// away, to be adopted only if and when the mock was called.
template <typename T>
static auto make_releaser(std::unique_ptr<T>& uptr) // uptr avoids leaking on exceptions until ownership transfer
{
return [&uptr] // we capture by reference - no leaks if uptr is destroyed before lambda called
{
return uptr.release(); /* transfer ownership */
};
}
static auto make_status_matcher(grpc::StatusCode code, const std::string& msg, const std::string& details)
{
return AllOf(Property(&grpc::Status::error_code, Eq(code)), Property(&grpc::Status::error_message, Eq(msg)),
Property(&grpc::Status::error_details, Eq(details)));
}
public:
std::ostringstream fake_cout;
std::ostringstream fake_cerr;
mpt::MockTerminal mock_term;
StrictMock<mpt::MockRpcStub> mock_stub{};
};
TEST_F(RemoteSettingsTest, savesProvidedKeyPrefix)
{
constexpr auto prefix = "my.prefix";
mp::RemoteSettingsHandler handler{prefix, mock_stub, &mock_term, 1};
EXPECT_EQ(handler.get_key_prefix(), prefix);
}
TEST_F(RemoteSettingsTest, savesProvidedVerbosity)
{
constexpr auto verbosity = 42;
mp::RemoteSettingsHandler handler{"prefix", mock_stub, &mock_term, verbosity};
EXPECT_EQ(handler.get_verbosity(), verbosity);
}
TEST_F(RemoteSettingsTest, honorsVerbosityInKeysRequest)
{
constexpr auto verbosity = 5;
auto mock_client = make_mock_reader_writer<mp::KeysRequest, mp::KeysReply>();
EXPECT_CALL(*mock_client, Write(Property(&mp::KeysRequest::verbosity_level, Eq(verbosity)), _))
.WillOnce(Return(true));
EXPECT_CALL(mock_stub, keysRaw).WillOnce(make_releaser(mock_client));
mp::RemoteSettingsHandler handler{"prefix", mock_stub, &mock_term, verbosity};
handler.keys();
}
TEST_F(RemoteSettingsTest, honorsVerbosityInGetRequest)
{
constexpr auto verbosity = 6;
auto mock_client = make_mock_reader_writer<mp::GetRequest, mp::GetReply>();
EXPECT_CALL(*mock_client, Write(Property(&mp::GetRequest::verbosity_level, Eq(verbosity)), _))
.WillOnce(Return(true));
EXPECT_CALL(mock_stub, getRaw).WillOnce(make_releaser(mock_client));
mp::RemoteSettingsHandler handler{"", mock_stub, &mock_term, verbosity};
handler.get("whatever");
}
TEST_F(RemoteSettingsTest, honorsVerbosityInSetRequest)
{
constexpr auto verbosity = 7;
auto mock_client = make_mock_reader_writer<mp::SetRequest, mp::SetReply>();
EXPECT_CALL(*mock_client, Write(Property(&mp::SetRequest::verbosity_level, Eq(verbosity)), _))
.WillOnce(Return(true));
EXPECT_CALL(mock_stub, setRaw).WillOnce(make_releaser(mock_client));
mp::RemoteSettingsHandler handler{"", mock_stub, &mock_term, verbosity};
handler.set("whatever", "works");
}
TEST_F(RemoteSettingsTest, keysEmptyByDefault)
{
auto mock_client = make_mock_reader_writer<mp::KeysRequest, mp::KeysReply>();
EXPECT_CALL(*mock_client, Write).Times(1);
EXPECT_CALL(mock_stub, keysRaw).WillOnce(make_releaser(mock_client));
mp::RemoteSettingsHandler handler{"prefix", mock_stub, &mock_term, 31};
EXPECT_THAT(handler.keys(), IsEmpty());
}
TEST_F(RemoteSettingsTest, keysReturnsRemoteKeys)
{
constexpr auto some_keys = std::array{"a.b", "c.d.e", "f"};
auto mock_client = make_mock_reader_writer<mp::KeysRequest, mp::KeysReply>();
EXPECT_CALL(*mock_client, Write).Times(1);
EXPECT_CALL(*mock_client, Read).WillOnce([&some_keys](mp::KeysReply* reply) {
reply->mutable_settings_keys()->Add(some_keys.begin(), some_keys.end());
return false;
});
EXPECT_CALL(mock_stub, keysRaw).WillOnce(make_releaser(mock_client)); /* grpc code claims ownership of the
ptr that keysRaw() returns */
mp::RemoteSettingsHandler handler{"prefix", mock_stub, &mock_term, 99};
EXPECT_THAT(handler.keys(), UnorderedElementsAreArray(some_keys));
}
TEST_F(RemoteSettingsTest, keysReturnsNoKeysWhenDaemonNotAround)
{
auto mock_client = make_mock_reader_writer<mp::KeysRequest, mp::KeysReply>();
EXPECT_CALL(*mock_client, Write).Times(1);
EXPECT_CALL(*mock_client, Finish).WillOnce(Return(grpc::Status{grpc::StatusCode::NOT_FOUND, "remote not around"}));
EXPECT_CALL(mock_stub, keysRaw).WillOnce(make_releaser(mock_client));
auto prefix = "remote.";
mp::RemoteSettingsHandler handler{prefix, mock_stub, &mock_term, 0};
EXPECT_THAT(handler.keys(), IsEmpty());
}
TEST_F(RemoteSettingsTest, keysThrowsOnOtherErrorFromRemote)
{
constexpr auto error_code = grpc::StatusCode::INTERNAL;
constexpr auto error_msg = "unexpected";
constexpr auto error_details = "details";
auto mock_client = make_mock_reader_writer<mp::KeysRequest, mp::KeysReply>();
EXPECT_CALL(*mock_client, Write).Times(1);
EXPECT_CALL(*mock_client, Finish).WillOnce(Return(grpc::Status{error_code, error_msg, error_details}));
EXPECT_CALL(mock_stub, keysRaw).WillOnce(make_releaser(mock_client));
mp::RemoteSettingsHandler handler{"prefix.", mock_stub, &mock_term, 789};
MP_EXPECT_THROW_THAT(
handler.keys(), mp::RemoteHandlerException,
Property(&mp::RemoteHandlerException::get_status, make_status_matcher(error_code, error_msg, error_details)));
}
TEST_F(RemoteSettingsTest, getRequestsSoughtSetting)
{
constexpr auto prefix = "a.";
const auto key = QString{prefix} + "key";
auto mock_client = make_mock_reader_writer<mp::GetRequest, mp::GetReply>();
EXPECT_CALL(*mock_client, Write(Property(&mp::GetRequest::key, Eq(key.toStdString())), _)).WillOnce(Return(true));
EXPECT_CALL(mock_stub, getRaw).WillOnce(make_releaser(mock_client));
mp::RemoteSettingsHandler handler{prefix, mock_stub, &mock_term, 1};
handler.get(key);
}
TEST_F(RemoteSettingsTest, getReturnsObtainedValue)
{
constexpr auto prefix = "local.", val = "asdf";
auto mock_client = make_mock_reader_writer<mp::GetRequest, mp::GetReply>();
EXPECT_CALL(*mock_client, Write).WillOnce(Return(true));
EXPECT_CALL(*mock_client, Read).WillOnce([val](mp::GetReply* reply) {
reply->set_value(val);
return false;
});
EXPECT_CALL(mock_stub, getRaw).WillOnce(make_releaser(mock_client));
mp::RemoteSettingsHandler handler{prefix, mock_stub, &mock_term, 11};
EXPECT_THAT(handler.get(QString{prefix} + "key"), Eq(val));
}
TEST_F(RemoteSettingsTest, getThrowsOnWrongPrefix)
{
constexpr auto prefix = "local.", key = "client.gui.something";
mp::RemoteSettingsHandler handler{prefix, mock_stub, &mock_term, 2};
MP_EXPECT_THROW_THAT(handler.get(key), mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(key)));
}
TEST_F(RemoteSettingsTest, getThrowsOnOtherErrorFromRemote)
{
constexpr auto error_code = grpc::StatusCode::INVALID_ARGUMENT;
constexpr auto error_msg = "an error";
constexpr auto error_details = "whatever";
auto mock_client = make_mock_reader_writer<mp::GetRequest, mp::GetReply>();
EXPECT_CALL(*mock_client, Write).WillOnce(Return(true));
EXPECT_CALL(*mock_client, Finish).WillOnce(Return(grpc::Status{error_code, error_msg, error_details}));
EXPECT_CALL(mock_stub, getRaw).WillOnce(make_releaser(mock_client));
mp::RemoteSettingsHandler handler{"asdf", mock_stub, &mock_term, 3};
MP_EXPECT_THROW_THAT(
handler.get("asdf.asdf"), mp::RemoteHandlerException,
Property(&mp::RemoteHandlerException::get_status, make_status_matcher(error_code, error_msg, error_details)));
}
TEST_F(RemoteSettingsTest, setRequestsSpecifiedSettingKeyAndValue)
{
constexpr auto prefix = "remote-", val = "setting-value";
const auto key = QString{prefix} + "setting-key";
auto mock_client = make_mock_reader_writer<mp::SetRequest, mp::SetReply>();
EXPECT_CALL(
*mock_client,
Write(AllOf(Property(&mp::SetRequest::key, Eq(key.toStdString())), Property(&mp::SetRequest::val, Eq(val))), _))
.WillOnce(Return(true));
EXPECT_CALL(mock_stub, setRaw).WillOnce(make_releaser(mock_client));
mp::RemoteSettingsHandler handler{prefix, mock_stub, &mock_term, 22};
handler.set(key, val);
}
TEST_F(RemoteSettingsTest, setThrowsOnWrongPrefix)
{
constexpr auto prefix = "local.", key = "client.gui.something";
mp::RemoteSettingsHandler handler{prefix, mock_stub, &mock_term, 2};
MP_EXPECT_THROW_THAT(handler.set(key, "val"), mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(key)));
}
TEST_F(RemoteSettingsTest, setThrowsOnOtherErrorFromRemote)
{
constexpr auto error_code = grpc::StatusCode::FAILED_PRECONDITION;
constexpr auto error_msg = "no worky";
constexpr auto error_details = "because";
auto mock_client = make_mock_reader_writer<mp::SetRequest, mp::SetReply>();
EXPECT_CALL(*mock_client, Write).WillOnce(Return(true));
EXPECT_CALL(*mock_client, Finish).WillOnce(Return(grpc::Status{error_code, error_msg, error_details}));
EXPECT_CALL(mock_stub, setRaw).WillOnce(make_releaser(mock_client));
mp::RemoteSettingsHandler handler{"a", mock_stub, &mock_term, 33};
MP_EXPECT_THROW_THAT(
handler.set("a.ongajgsiffsgu", "dfoinig"), mp::RemoteHandlerException,
Property(&mp::RemoteHandlerException::get_status, make_status_matcher(error_code, error_msg, error_details)));
}
} // namespace
| 11,224
|
C++
|
.cpp
| 229
| 44.183406
| 120
| 0.718
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,585
|
test_mount_handler.cpp
|
canonical_multipass/tests/test_mount_handler.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_file_ops.h"
#include <multipass/mount_handler.h>
#include <multipass/vm_mount.h>
#include <filesystem>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct PublicMountHandler : public mp::MountHandler
{
template <typename... Ts>
PublicMountHandler(Ts&&... params) : mp::MountHandler(std::forward<Ts>(params)...)
{
}
void activate_impl(mp::ServerVariant server, std::chrono::milliseconds timeout) override
{
}
void deactivate_impl(bool force) override
{
}
};
TEST(MountHandler, providesMountSpec)
{
namespace fs = std::filesystem;
mp::VMMount mount{"asdf", {}, {}, multipass::VMMount::MountType::Native};
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, status).WillOnce(Return(fs::file_status{fs::file_type::directory, fs::perms::unknown}));
PublicMountHandler handler{nullptr, nullptr, mount, ""};
EXPECT_EQ(handler.get_mount_spec(), mount);
}
} // namespace
| 1,687
|
C++
|
.cpp
| 49
| 31.55102
| 120
| 0.728615
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,586
|
reset_process_factory.cpp
|
canonical_multipass/tests/reset_process_factory.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "reset_process_factory.h"
namespace mp = multipass;
namespace mpt = multipass::test;
namespace
{
class ResettableProcessFactory : public mp::ProcessFactory
{
public:
static void Reset()
{
mp::ProcessFactory::reset();
}
using mp::ProcessFactory::ProcessFactory;
};
} // namespace
mpt::ResetProcessFactory::ResetProcessFactory()
{
ResettableProcessFactory::Reset();
}
mpt::ResetProcessFactory::~ResetProcessFactory()
{
ResettableProcessFactory::Reset();
}
| 1,129
|
C++
|
.cpp
| 39
| 26.589744
| 72
| 0.755535
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,587
|
test_ubuntu_image_host.cpp
|
canonical_multipass/tests/test_ubuntu_image_host.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "image_host_remote_count.h"
#include "mischievous_url_downloader.h"
#include "mock_platform.h"
#include "mock_settings.h"
#include "path.h"
#include "stub_url_downloader.h"
#include <src/daemon/ubuntu_image_host.h>
#include <multipass/constants.h>
#include <multipass/exceptions/download_exception.h>
#include <multipass/exceptions/unsupported_alias_exception.h>
#include <multipass/exceptions/unsupported_image_exception.h>
#include <multipass/exceptions/unsupported_remote_exception.h>
#include <multipass/query.h>
#include <QUrl>
#include <cstddef>
#include <optional>
#include <unordered_set>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace multipass::platform;
using namespace testing;
using namespace std::literals::chrono_literals;
namespace
{
struct UbuntuImageHost : public testing::Test
{
UbuntuImageHost()
{
EXPECT_CALL(mock_platform, is_remote_supported(_)).WillRepeatedly(Return(true));
EXPECT_CALL(mock_platform, is_alias_supported(_, _)).WillRepeatedly(Return(true));
EXPECT_CALL(mock_settings, get(Eq(mp::driver_key))).WillRepeatedly(Return("emu")); /* TODO parameterize driver
(code branches for lxd) */
EXPECT_CALL(mock_settings, get(Eq(mp::mirror_key))).WillRepeatedly(Return(""));
}
mp::Query make_query(std::string release, std::string remote)
{
return {"", std::move(release), false, std::move(remote), mp::Query::Type::Alias};
}
QString test_host = QUrl::fromLocalFile(mpt::test_data_path()).toString();
QString test_valid_mirror_host = QUrl::fromLocalFile(mpt::test_data_sub_dir_path("valid_image_mirror")).toString();
QString test_valid_outdated_mirror_host =
QUrl::fromLocalFile(mpt::test_data_sub_dir_path("valid_outdated_image_mirror")).toString();
QString test_invalid_mirror_host =
QUrl::fromLocalFile(mpt::test_data_sub_dir_path("invalid_image_mirror")).toString();
std::string mock_image_host = test_host.toStdString();
QString host_url{test_host + "releases/"};
QString daily_url{test_host + "daily/"};
std::pair<std::string, mp::UbuntuVMImageRemote> release_remote_spec = {
"release", mp::UbuntuVMImageRemote{mock_image_host, "releases/"}};
std::pair<std::string, mp::UbuntuVMImageRemote> release_remote_spec_with_mirror_allowed = {
"release", mp::UbuntuVMImageRemote{mock_image_host, "releases/", std::make_optional<QString>(mp::mirror_key)}};
std::pair<std::string, mp::UbuntuVMImageRemote> daily_remote_spec = {
"daily", mp::UbuntuVMImageRemote{mock_image_host, "daily/"}};
std::vector<std::pair<std::string, mp::UbuntuVMImageRemote>> all_remote_specs = {release_remote_spec,
daily_remote_spec};
mpt::MischievousURLDownloader url_downloader{std::chrono::seconds{10}};
QString expected_location{host_url + "newest_image.img"};
QString expected_id{"8842e7a8adb01c7a30cc702b01a5330a1951b12042816e87efd24b61c5e2239f"};
mpt::MockPlatform::GuardedMock mock_platform_injection{mpt::MockPlatform::inject()};
mpt::MockPlatform& mock_platform = *mock_platform_injection.first;
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject<StrictMock>();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
};
} // namespace
TEST_F(UbuntuImageHost, returns_expected_info)
{
mp::UbuntuVMImageHost host{{release_remote_spec}, &url_downloader};
host.update_manifests(false);
auto info = host.info_for(make_query("xenial", release_remote_spec.first));
ASSERT_TRUE(info);
EXPECT_THAT(info->image_location, Eq(expected_location));
EXPECT_THAT(info->id, Eq(expected_id));
}
TEST_F(UbuntuImageHost, returns_expected_mirror_info)
{
EXPECT_CALL(mock_settings, get(Eq(mp::mirror_key))).WillRepeatedly(Return(test_valid_mirror_host));
mp::UbuntuVMImageHost host{{release_remote_spec_with_mirror_allowed}, &url_downloader};
host.update_manifests(false);
auto info = host.info_for(make_query("xenial", release_remote_spec.first));
QString expected_location{test_valid_mirror_host + "releases/" + "newest_image.img"};
ASSERT_TRUE(info);
EXPECT_THAT(info->image_location, Eq(expected_location));
EXPECT_THAT(info->id, Eq(expected_id));
}
TEST_F(UbuntuImageHost, returns_expected_mirror_info_with_most_recent_image)
{
EXPECT_CALL(mock_settings, get(Eq(mp::mirror_key))).WillRepeatedly(Return(test_valid_outdated_mirror_host));
mp::UbuntuVMImageHost host{{release_remote_spec_with_mirror_allowed}, &url_downloader};
host.update_manifests(false);
auto info = host.info_for(make_query("xenial", release_remote_spec.first));
QString expected_location{test_valid_outdated_mirror_host + "releases/" + "test_image.img"};
QString expected_id{"1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac"};
ASSERT_TRUE(info);
EXPECT_THAT(info->image_location, Eq(expected_location));
EXPECT_THAT(info->id, Eq(expected_id));
}
TEST_F(UbuntuImageHost, throw_if_mirror_is_invalid)
{
EXPECT_CALL(mock_settings, get(Eq(mp::mirror_key))).WillRepeatedly(Return(test_invalid_mirror_host));
mp::UbuntuVMImageHost host{{release_remote_spec_with_mirror_allowed}, &url_downloader};
host.update_manifests(false);
EXPECT_THROW(host.info_for(make_query("xenial", release_remote_spec.first)), std::runtime_error);
}
TEST_F(UbuntuImageHost, uses_default_on_unspecified_release)
{
mp::UbuntuVMImageHost host{{release_remote_spec}, &url_downloader};
host.update_manifests(false);
auto info = host.info_for(make_query("", release_remote_spec.first));
ASSERT_TRUE(info);
EXPECT_THAT(info->image_location, Eq(expected_location));
EXPECT_THAT(info->id, Eq(expected_id));
}
TEST_F(UbuntuImageHost, iterates_over_all_entries)
{
mp::UbuntuVMImageHost host{{release_remote_spec}, &url_downloader};
host.update_manifests(false);
std::unordered_set<std::string> ids;
auto action = [&ids](const std::string& remote, const mp::VMImageInfo& info) { ids.insert(info.id.toStdString()); };
host.for_each_entry_do(action);
const size_t expected_entries{5};
EXPECT_THAT(ids.size(), Eq(expected_entries));
EXPECT_THAT(ids.count("1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac"), Eq(1u));
EXPECT_THAT(ids.count("8842e7a8adb01c7a30cc702b01a5330a1951b12042816e87efd24b61c5e2239f"), Eq(1u));
EXPECT_THAT(ids.count("1507bd2b3288ef4bacd3e699fe71b827b7ccf321ec4487e168a30d7089d3c8e4"), Eq(1u));
EXPECT_THAT(ids.count("ab115b83e7a8bebf3d3a02bf55ad0cb75a0ed515fcbc65fb0c9abe76c752921c"), Eq(1u));
EXPECT_THAT(ids.count("520224efaaf49b15a976b49c7ce7f2bd2e5b161470d684b37a838933595c0520"), Eq(1u));
}
TEST_F(UbuntuImageHost, unsupported_alias_iterates_over_expected_entries)
{
mp::UbuntuVMImageHost host{{release_remote_spec}, &url_downloader};
host.update_manifests(false);
std::unordered_set<std::string> ids;
auto action = [&ids](const std::string& remote, const mp::VMImageInfo& info) { ids.insert(info.id.toStdString()); };
EXPECT_CALL(mock_platform, is_alias_supported(AnyOf("zesty", "17.04", "z"), _)).WillRepeatedly(Return(false));
host.for_each_entry_do(action);
const size_t expected_entries{4};
EXPECT_THAT(ids.size(), Eq(expected_entries));
}
TEST_F(UbuntuImageHost, can_query_by_hash)
{
mp::UbuntuVMImageHost host{{release_remote_spec}, &url_downloader};
host.update_manifests(false);
const auto expected_id = "1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac";
auto info = host.info_for(make_query(expected_id, release_remote_spec.first));
ASSERT_TRUE(info);
EXPECT_THAT(info->id, Eq(expected_id));
}
TEST_F(UbuntuImageHost, can_query_by_partial_hash)
{
mp::UbuntuVMImageHost host{{release_remote_spec}, &url_downloader};
host.update_manifests(false);
const auto expected_id = "1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac";
QStringList short_hashes;
short_hashes << "1797"
<< "1797c5"
<< "1797c5c";
for (const auto& hash : short_hashes)
{
auto info = host.info_for(make_query(hash.toStdString(), release_remote_spec.first));
ASSERT_TRUE(info);
EXPECT_THAT(info->id, Eq(expected_id));
}
EXPECT_FALSE(host.info_for(make_query("abcde", release_remote_spec.first)));
}
TEST_F(UbuntuImageHost, supports_multiple_manifests)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
QString daily_expected_location{daily_url + "newest-artful.img"};
QString daily_expected_id{"c09f123b9589c504fe39ec6e9ebe5188c67be7d1fc4fb80c969bf877f5a8333a"};
auto info = host.info_for(make_query("artful", daily_remote_spec.first));
ASSERT_TRUE(info);
EXPECT_THAT(info->image_location, Eq(daily_expected_location));
EXPECT_THAT(info->id, Eq(daily_expected_id));
auto xenial_info = host.info_for(make_query("xenial", release_remote_spec.first));
ASSERT_TRUE(xenial_info);
EXPECT_THAT(xenial_info->image_location, Eq(expected_location));
EXPECT_THAT(xenial_info->id, Eq(expected_id));
}
TEST_F(UbuntuImageHost, looks_for_aliases_before_hashes)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
QString daily_expected_location{daily_url + "newest-artful.img"};
QString daily_expected_id{"c09f123b9589c504fe39ec6e9ebe5188c67be7d1fc4fb80c969bf877f5a8333a"};
auto info = host.info_for(make_query("a", daily_remote_spec.first));
ASSERT_TRUE(info);
EXPECT_THAT(info->image_location, Eq(daily_expected_location));
EXPECT_THAT(info->id, Eq(daily_expected_id));
}
TEST_F(UbuntuImageHost, all_info_release_returns_multiple_hash_matches)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
auto images_info = host.all_info_for(make_query("1", release_remote_spec.first));
const size_t expected_matches{2};
EXPECT_THAT(images_info.size(), Eq(expected_matches));
}
TEST_F(UbuntuImageHost, all_info_daily_no_matches_returns_empty_vector)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
auto images = host.all_info_for(make_query("1", daily_remote_spec.first));
EXPECT_TRUE(images.empty());
}
TEST_F(UbuntuImageHost, all_info_release_returns_one_alias_match)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
auto images_info = host.all_info_for(make_query("xenial", release_remote_spec.first));
const size_t expected_matches{1};
EXPECT_THAT(images_info.size(), Eq(expected_matches));
}
TEST_F(UbuntuImageHost, all_images_for_release_returns_four_matches)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
auto images = host.all_images_for(release_remote_spec.first, false);
const size_t expected_matches{4};
EXPECT_THAT(images.size(), Eq(expected_matches));
}
TEST_F(UbuntuImageHost, all_images_for_release_unsupported_returns_five_matches)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
auto images = host.all_images_for(release_remote_spec.first, true);
const size_t expected_matches{5};
EXPECT_THAT(images.size(), Eq(expected_matches));
}
TEST_F(UbuntuImageHost, all_images_for_daily_returns_all_matches)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
auto images = host.all_images_for(daily_remote_spec.first, false);
const size_t expected_matches{3};
EXPECT_THAT(images.size(), Eq(expected_matches));
}
TEST_F(UbuntuImageHost, all_images_for_release_unsupported_alias_returns_three_matches)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
EXPECT_CALL(mock_platform, is_alias_supported(AnyOf("zesty", "17.04", "z"), _)).WillRepeatedly(Return(false));
auto images = host.all_images_for(release_remote_spec.first, false);
const size_t expected_matches{3};
EXPECT_EQ(images.size(), expected_matches);
}
TEST_F(UbuntuImageHost, supported_remotes_returns_expected_values)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
auto supported_remotes = host.supported_remotes();
const size_t expected_size{2};
EXPECT_THAT(supported_remotes.size(), Eq(expected_size));
EXPECT_TRUE(std::find(supported_remotes.begin(), supported_remotes.end(), release_remote_spec.first) !=
supported_remotes.end());
EXPECT_TRUE(std::find(supported_remotes.begin(), supported_remotes.end(), daily_remote_spec.first) !=
supported_remotes.end());
}
TEST_F(UbuntuImageHost, invalid_remote_throws_error)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
EXPECT_THROW(host.info_for(make_query("xenial", "foo")), std::runtime_error);
}
TEST_F(UbuntuImageHost, handles_and_recovers_from_initial_network_failure)
{
url_downloader.mischiefs = 1000;
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
EXPECT_THROW(host.update_manifests(false), mp::DownloadException);
const auto query = make_query("xenial", release_remote_spec.first);
EXPECT_THROW(host.info_for(query), std::runtime_error);
url_downloader.mischiefs = 0;
host.update_manifests(false);
EXPECT_TRUE(host.info_for(query));
}
TEST_F(UbuntuImageHost, handles_and_recovers_from_later_network_failure)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
const auto query = make_query("xenial", release_remote_spec.first);
host.update_manifests(false);
EXPECT_TRUE(host.info_for(query));
url_downloader.mischiefs = 1000;
EXPECT_THROW(host.update_manifests(false), mp::DownloadException);
EXPECT_THROW(host.info_for(query), std::runtime_error);
url_downloader.mischiefs = 0;
host.update_manifests(false);
EXPECT_TRUE(host.info_for(query));
}
TEST_F(UbuntuImageHost, handles_and_recovers_from_independent_server_failures)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
const auto num_remotes = mpt::count_remotes(host);
EXPECT_GT(num_remotes, 0u);
url_downloader.mischiefs = 0;
EXPECT_EQ(mpt::count_remotes(host), num_remotes);
for (size_t i = 1; i < num_remotes; ++i)
{
url_downloader.mischiefs = i;
EXPECT_THROW(mpt::count_remotes(host), mp::DownloadException);
}
}
TEST_F(UbuntuImageHost, throws_unsupported_image_when_image_not_supported)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
EXPECT_THROW(host.info_for(make_query("artful", release_remote_spec.first)), mp::UnsupportedImageException);
}
TEST_F(UbuntuImageHost, devel_request_with_no_remote_returns_expected_info)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
QString daily_expected_location{daily_url + "newest-artful.img"};
QString daily_expected_id{"c09f123b9589c504fe39ec6e9ebe5188c67be7d1fc4fb80c969bf877f5a8333a"};
auto info = host.info_for(make_query("devel", ""));
ASSERT_TRUE(info);
EXPECT_EQ(info->image_location, daily_expected_location);
EXPECT_EQ(info->id, daily_expected_id);
}
TEST_F(UbuntuImageHost, info_for_too_many_hash_matches_throws)
{
mp::UbuntuVMImageHost host{{release_remote_spec}, &url_downloader};
host.update_manifests(false);
const std::string release{"1"};
MP_EXPECT_THROW_THAT(host.info_for(make_query(release, release_remote_spec.first)), std::runtime_error,
mpt::match_what(StrEq(fmt::format("Too many images matching \"{}\"", release))));
}
TEST_F(UbuntuImageHost, info_for_same_full_hash_in_both_remotes_does_not_throw)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
const auto hash_query{"ab115b83e7a8bebf3d3a02bf55ad0cb75a0ed515fcbc65fb0c9abe76c752921c"};
EXPECT_NO_THROW(host.info_for(make_query(hash_query, "")));
}
TEST_F(UbuntuImageHost, info_for_partial_hash_in_both_remotes_throws)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
const auto hash_query{"ab115"};
MP_EXPECT_THROW_THAT(host.info_for(make_query(hash_query, "")), std::runtime_error,
mpt::match_what(StrEq(fmt::format("Too many images matching \"{}\"", hash_query))));
}
TEST_F(UbuntuImageHost, all_info_for_no_remote_query_defaults_to_release)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
auto images_info = host.all_info_for(make_query("1", ""));
const size_t expected_matches{2};
EXPECT_EQ(images_info.size(), expected_matches);
}
TEST_F(UbuntuImageHost, all_info_for_unsupported_image_throw)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
const std::string release{"artful"};
MP_EXPECT_THROW_THAT(host.all_info_for(make_query(release, release_remote_spec.first)),
mp::UnsupportedImageException,
mpt::match_what(StrEq(fmt::format("The {} release is no longer supported.", release))));
}
TEST_F(UbuntuImageHost, all_info_for_unsupported_alias_throws)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
const std::string unsupported_alias{"daily"};
EXPECT_CALL(mock_platform, is_alias_supported(unsupported_alias, _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(
host.all_info_for(make_query(unsupported_alias, release_remote_spec.first)), mp::UnsupportedAliasException,
mpt::match_what(HasSubstr(fmt::format("\'{}\' is not a supported alias.", unsupported_alias))));
}
TEST_F(UbuntuImageHost, info_for_unsupported_remote_throws)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
const std::string unsupported_remote{"bar"};
EXPECT_CALL(mock_platform, is_remote_supported(unsupported_remote)).WillRepeatedly(Return(false));
MP_EXPECT_THROW_THAT(host.info_for(make_query("xenial", unsupported_remote)), mp::UnsupportedRemoteException,
mpt::match_what(HasSubstr(fmt::format(
"Remote \'{}\' is not a supported remote for this platform.", unsupported_remote))));
}
TEST_F(UbuntuImageHost, info_for_no_remote_first_unsupported_returns_expected_info)
{
mp::UbuntuVMImageHost host{all_remote_specs, &url_downloader};
host.update_manifests(false);
EXPECT_CALL(mock_platform, is_remote_supported("release")).Times(AtLeast(1)).WillRepeatedly(Return(false));
auto info = host.info_for(make_query("artful", ""));
EXPECT_EQ(info->id, "c09f123b9589c504fe39ec6e9ebe5188c67be7d1fc4fb80c969bf877f5a8333a");
}
| 20,023
|
C++
|
.cpp
| 404
| 44.601485
| 120
| 0.727543
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,588
|
test_daemon_clone.cpp
|
canonical_multipass/tests/test_daemon_clone.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "daemon_test_fixture.h"
#include "mock_platform.h"
#include "mock_server_reader_writer.h"
#include "mock_virtual_machine.h"
#include "mock_vm_image_vault.h"
#include <src/daemon/daemon.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
struct TestDaemonClone : public mpt::DaemonTestFixture
{
void SetUp() override
{
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
}
auto build_daemon_with_mock_instance()
{
auto instance_unique_ptr = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_src_instance_name);
auto* instance_raw_ptr = instance_unique_ptr.get();
EXPECT_CALL(mock_factory, create_virtual_machine).WillOnce(Return(std::move(instance_unique_ptr)));
const auto [temp_dir, _] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
config_builder.data_directory = temp_dir->path();
auto daemon = std::make_unique<mp::Daemon>(config_builder.build());
return std::pair{std::move(daemon), instance_raw_ptr};
}
const std::string mock_src_instance_name{"real-zebraphant"};
const std::string mac_addr{"52:54:00:73:76:28"};
std::vector<mp::NetworkInterface> extra_interfaces;
const mpt::MockVirtualMachineFactory& mock_factory = *use_a_mock_vm_factory();
const mpt::MockPlatform::GuardedMock attr{mpt::MockPlatform::inject<NiceMock>()};
const mpt::MockPlatform& mock_platform = *attr.first;
};
TEST_F(TestDaemonClone, missingOnSrcInstance)
{
const std::string src_instance_name = "non_exist_instance";
mp::CloneRequest request{};
request.set_source_name(src_instance_name);
mp::Daemon daemon{config_builder.build()};
const auto status = call_daemon_slot(daemon,
&mp::Daemon::clone,
request,
NiceMock<mpt::MockServerReaderWriter<mp::CloneReply, mp::CloneRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::NOT_FOUND);
EXPECT_EQ(status.error_message(), fmt::format("instance \"{}\" does not exist", src_instance_name));
}
TEST_F(TestDaemonClone, invalidDestVmName)
{
const auto [daemon, instance] = build_daemon_with_mock_instance();
constexpr std::string_view dest_instance_name = "5invalid_vm_name";
mp::CloneRequest request{};
request.set_source_name(mock_src_instance_name);
request.set_destination_name(std::string{dest_instance_name});
const auto status = call_daemon_slot(*daemon,
&mp::Daemon::clone,
request,
NiceMock<mpt::MockServerReaderWriter<mp::CloneReply, mp::CloneRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), HasSubstr("Invalid destination instance name"));
}
TEST_F(TestDaemonClone, alreadyExistDestVmName)
{
const auto [daemon, instance] = build_daemon_with_mock_instance();
mp::CloneRequest request{};
request.set_source_name(mock_src_instance_name);
request.set_destination_name(mock_src_instance_name);
const auto status = call_daemon_slot(*daemon,
&mp::Daemon::clone,
request,
NiceMock<mpt::MockServerReaderWriter<mp::CloneReply, mp::CloneRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), HasSubstr("already exists, please choose a new name."));
}
TEST_F(TestDaemonClone, successfulCloneGenerateDestNameOkStatus)
{
// add this line to cover the update_unique_identifiers_of_metadata all branches
extra_interfaces.emplace_back(mp::NetworkInterface{"eth1", "52:54:00:00:00:00", true});
const auto [daemon, instance] = build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillOnce(Return(mp::VirtualMachine::State::stopped));
mp::CloneRequest request{};
request.set_source_name(mock_src_instance_name);
const auto status = call_daemon_slot(*daemon,
&mp::Daemon::clone,
request,
NiceMock<mpt::MockServerReaderWriter<mp::CloneReply, mp::CloneRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::OK);
}
TEST_F(TestDaemonClone, successfulCloneSpecifyDestNameOkStatus)
{
const auto [daemon, instance] = build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillOnce(Return(mp::VirtualMachine::State::stopped));
mp::CloneRequest request{};
request.set_source_name(mock_src_instance_name);
request.set_destination_name("valid-dest-instance-name");
const auto status = call_daemon_slot(*daemon,
&mp::Daemon::clone,
request,
NiceMock<mpt::MockServerReaderWriter<mp::CloneReply, mp::CloneRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::OK);
}
TEST_F(TestDaemonClone, failsOnCloneOnNonStoppedInstance)
{
const auto [daemon, instance] = build_daemon_with_mock_instance();
EXPECT_CALL(*instance, current_state).WillOnce(Return(mp::VirtualMachine::State::running));
mp::CloneRequest request{};
request.set_source_name(mock_src_instance_name);
const auto status = call_daemon_slot(*daemon,
&mp::Daemon::clone,
request,
NiceMock<mpt::MockServerReaderWriter<mp::CloneReply, mp::CloneRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::FAILED_PRECONDITION);
EXPECT_EQ(status.error_message(),
fmt::format("Please stop instance {} before you clone it.", mock_src_instance_name));
}
| 6,721
|
C++
|
.cpp
| 130
| 42.323077
| 116
| 0.655025
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,589
|
test_cli_client.cpp
|
canonical_multipass/tests/test_cli_client.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_ssh_test_fixture.h"
#include "common.h"
#include "disabling_macros.h"
#include "fake_alias_config.h"
#include "fake_key_data.h"
#include "mock_cert_provider.h"
#include "mock_environment_helpers.h"
#include "mock_file_ops.h"
#include "mock_network.h"
#include "mock_platform.h"
#include "mock_settings.h"
#include "mock_sftp_client.h"
#include "mock_sftp_utils.h"
#include "mock_standard_paths.h"
#include "mock_stdcin.h"
#include "mock_terminal.h"
#include "mock_utils.h"
#include "path.h"
#include "stub_cert_store.h"
#include "stub_console.h"
#include "stub_terminal.h"
#include <src/client/cli/client.h>
#include <src/client/cli/cmd/remote_settings_handler.h>
#include <src/daemon/daemon_rpc.h>
#include <multipass/cli/client_platform.h>
#include <multipass/constants.h>
#include <multipass/exceptions/settings_exceptions.h>
#include <multipass/exceptions/ssh_exception.h>
#include <QStringList>
#include <QTemporaryFile>
#include <QTimer>
#include <QtCore/QTemporaryDir>
#include <QtGlobal>
#include <chrono>
#include <initializer_list>
#include <thread>
#include <utility>
namespace mp = multipass;
namespace mcp = multipass::cli::platform;
namespace mpt = multipass::test;
namespace mpu = multipass::utils;
using namespace testing;
namespace
{
struct MockDaemonRpc : public mp::DaemonRpc
{
using mp::DaemonRpc::DaemonRpc; // ctor
MOCK_METHOD(grpc::Status, create,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::CreateReply, mp::CreateRequest> * server)),
(override)); // here only to ensure not called
MOCK_METHOD(grpc::Status, launch,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::LaunchReply, mp::LaunchRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, purge,
(grpc::ServerContext * context, (grpc::ServerReaderWriter<mp::PurgeReply, mp::PurgeRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, find,
(grpc::ServerContext * context, (grpc::ServerReaderWriter<mp::FindReply, mp::FindRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, info,
(grpc::ServerContext * context, (grpc::ServerReaderWriter<mp::InfoReply, mp::InfoRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, list,
(grpc::ServerContext * context, (grpc::ServerReaderWriter<mp::ListReply, mp::ListRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, mount,
(grpc::ServerContext * context, (grpc::ServerReaderWriter<mp::MountReply, mp::MountRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, recover,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::RecoverReply, mp::RecoverRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, ssh_info,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, start,
(grpc::ServerContext * context, (grpc::ServerReaderWriter<mp::StartReply, mp::StartRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, stop,
(grpc::ServerContext * context, (grpc::ServerReaderWriter<mp::StopReply, mp::StopRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, suspend,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::SuspendReply, mp::SuspendRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, restart,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::RestartReply, mp::RestartRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, delet,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::DeleteReply, mp::DeleteRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, umount,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::UmountReply, mp::UmountRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, version,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::VersionReply, mp::VersionRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, ping,
(grpc::ServerContext * context, const mp::PingRequest* request, mp::PingReply* response), (override));
MOCK_METHOD(grpc::Status, get,
(grpc::ServerContext * context, (grpc::ServerReaderWriter<mp::GetReply, mp::GetRequest> * server)),
(override));
MOCK_METHOD(grpc::Status, authenticate,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::AuthenticateReply, mp::AuthenticateRequest> * server)),
(override));
MOCK_METHOD(grpc::Status,
snapshot,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::SnapshotReply, mp::SnapshotRequest> * server)),
(override));
MOCK_METHOD(grpc::Status,
restore,
(grpc::ServerContext * context,
(grpc::ServerReaderWriter<mp::RestoreReply, mp::RestoreRequest> * server)),
(override));
MOCK_METHOD(grpc::Status,
clone,
(grpc::ServerContext * context, (grpc::ServerReaderWriter<mp::CloneReply, mp::CloneRequest> * server)),
(override));
};
struct Client : public Test
{
void SetUp() override
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(petenv_name));
EXPECT_CALL(mock_settings, get(Eq(mp::winterm_key))).WillRepeatedly(Return("none"));
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillRepeatedly(Return("true"));
EXPECT_CALL(mock_settings, register_handler(_)).WillRepeatedly(Return(nullptr));
EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber());
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), locate(_, _, _))
.Times(AnyNumber()); // needed to allow general calls once we have added the specific expectation below
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(),
locate(_, mpt::match_qstring(EndsWith("settings.json")), _))
.Times(AnyNumber())
.WillRepeatedly(Return("")); /* Avoid writing to Windows Terminal settings. We use an "expectation" so that
it gets reset at the end of each test (by VerifyAndClearExpectations) */
}
void TearDown() override
{
testing::Mock::VerifyAndClearExpectations(&mock_daemon); /* We got away without this before because, being a
strict mock every call to mock_daemon had to be explicitly
"expected". Being the best match for incoming calls, each
expectation took precedence over the previous ones,
preventing them from being saturated inadvertently */
}
int setup_client_and_run(const std::vector<std::string>& command, mp::Terminal& term)
{
mp::ClientConfig client_config{server_address, get_client_cert_provider(), &term};
mp::Client client{client_config};
QStringList args = QStringList() << "multipass_test";
for (const auto& arg : command)
{
args << QString::fromStdString(arg);
}
return client.run(args);
}
int send_command(const std::vector<std::string>& command, std::ostream& cout = trash_stream,
std::ostream& cerr = trash_stream, std::istream& cin = trash_stream)
{
mpt::StubTerminal term(cout, cerr, cin);
return setup_client_and_run(command, term);
}
template <typename Str1, typename Str2>
std::string keyval_arg(Str1&& key, Str2&& val)
{
return fmt::format("{}={}", std::forward<Str1>(key), std::forward<Str2>(val));
}
std::string get_setting(const std::initializer_list<std::string>& args)
{
auto out = std::ostringstream{};
std::vector<std::string> cmd{"get"};
cmd.insert(end(cmd), cbegin(args), cend(args));
EXPECT_THAT(send_command(cmd, out), Eq(mp::ReturnCode::Ok));
auto ret = out.str();
if (!ret.empty())
{
EXPECT_EQ(ret.back(), '\n');
ret.pop_back(); // drop newline
}
return ret;
}
std::string get_setting(const std::string& key)
{
return get_setting({key});
}
static auto make_mount_matcher(const std::string_view fake_source, const std::string_view fake_target,
const std::string_view instance_name)
{
const auto automount_source_matcher = Property(&mp::MountRequest::source_path, StrEq(fake_source));
const auto target_instance_matcher = Property(&mp::TargetPathInfo::instance_name, StrEq(instance_name));
const auto target_path_matcher = Property(&mp::TargetPathInfo::target_path, StrEq(fake_target));
const auto target_info_matcher = AllOf(target_instance_matcher, target_path_matcher);
const auto automount_target_matcher =
Property(&mp::MountRequest::target_paths, AllOf(Contains(target_info_matcher), SizeIs(1)));
return AllOf(automount_source_matcher, automount_target_matcher);
}
static auto make_mount_id_mappings_matcher(const mp::id_mappings& expected_uid_mappings,
const mp::id_mappings& expected_gid_mappings)
{
auto compare_uid_map = [expected_uid_mappings](auto request_uid_mappings) {
auto mappings_size = expected_uid_mappings.size();
if (mappings_size != (decltype(mappings_size))request_uid_mappings.size())
return false;
for (decltype(mappings_size) i = 0; i < mappings_size; ++i)
if (expected_uid_mappings[i].first != request_uid_mappings.at(i).host_id() ||
expected_uid_mappings[i].second != request_uid_mappings.at(i).instance_id())
return false;
return true;
};
const auto uid_map_matcher = Property(&mp::MountRequest::mount_maps,
Property(&mp::MountMaps::uid_mappings, ResultOf(compare_uid_map, true)));
auto compare_gid_map = [expected_gid_mappings](auto request_gid_mappings) {
auto mappings_size = expected_gid_mappings.size();
if (mappings_size != (decltype(mappings_size))request_gid_mappings.size())
return false;
for (decltype(mappings_size) i = 0; i < mappings_size; ++i)
if (expected_gid_mappings[i].first != request_gid_mappings.at(i).host_id() ||
expected_gid_mappings[i].second != request_gid_mappings.at(i).instance_id())
return false;
return true;
};
const auto gid_map_matcher = Property(&mp::MountRequest::mount_maps,
Property(&mp::MountMaps::gid_mappings, ResultOf(compare_gid_map, true)));
return AllOf(uid_map_matcher, gid_map_matcher);
}
auto make_launch_instance_matcher(const std::string& instance_name)
{
return Property(&mp::LaunchRequest::instance_name, StrEq(instance_name));
}
auto make_ssh_info_instance_matcher(const std::string& instance_name)
{
return Property(&mp::SSHInfoRequest::instance_name, ElementsAre(StrEq(instance_name)));
}
template <typename RequestType, typename Matcher>
auto make_instances_matcher(const Matcher& instances_matcher)
{
return Property(&RequestType::instance_names, Property(&mp::InstanceNames::instance_name, instances_matcher));
}
template <typename RequestType, typename Sequence>
auto make_instances_sequence_matcher(const Sequence& seq)
{
return make_instances_matcher<RequestType>(ElementsAreArray(seq));
}
template <typename RequestType, int size>
auto make_instance_in_repeated_field_matcher(const std::string& instance_name)
{
static_assert(size > 0, "size must be positive");
return make_instances_matcher<RequestType>(AllOf(Contains(StrEq(instance_name)), SizeIs(size)));
}
template <typename RequestType>
auto make_request_verbosity_matcher(decltype(std::declval<RequestType>().verbosity_level()) verbosity)
{
return Property(&RequestType::verbosity_level, Eq(verbosity));
}
template <typename RequestType>
auto make_request_timeout_matcher(decltype(std::declval<RequestType>().timeout()) timeout)
{
return Property(&RequestType::timeout, Eq(timeout));
}
void aux_set_cmd_rejects_bad_val(const char* key, const char* val)
{
EXPECT_CALL(mock_settings, set(Eq(key), Eq(val)))
.WillRepeatedly(Throw(mp::InvalidSettingException{key, val, "bad"}));
EXPECT_THAT(send_command({"set", keyval_arg(key, val)}), Eq(mp::ReturnCode::CommandLineError));
}
auto make_fill_listreply(std::vector<mp::InstanceStatus_Status> statuses)
{
return [statuses](Unused, grpc::ServerReaderWriter<mp::ListReply, mp::ListRequest>* response) {
mp::ListReply list_reply;
for (mp::InstanceStatus_Status status : statuses)
{
auto list_entry = list_reply.mutable_instance_list()->add_instances();
list_entry->mutable_instance_status()->set_status(status);
}
response->Write(list_reply);
return grpc::Status{};
};
}
std::string negate_flag_string(const std::string& orig)
{
auto flag = QVariant{QString::fromStdString(orig)}.toBool();
return QVariant::fromValue(!flag).toString().toStdString();
}
template <typename ReplyType, typename RequestType, typename Matcher>
auto check_request_and_return(const Matcher& matcher,
const grpc::Status& status,
const ReplyType& reply = ReplyType{})
{
return [&matcher, &status, reply = std::move(reply)](grpc::ServerReaderWriter<ReplyType, RequestType>* server) {
RequestType request;
server->Read(&request);
EXPECT_THAT(request, matcher);
server->Write(std::move(reply));
return status;
};
}
#ifdef WIN32
std::string server_address{"localhost:50051"};
#else
std::string server_address{"unix:/tmp/test-multipassd.socket"};
#endif
static std::unique_ptr<NiceMock<mpt::MockCertProvider>> get_client_cert_provider()
{
return std::make_unique<NiceMock<mpt::MockCertProvider>>();
};
std::unique_ptr<NiceMock<mpt::MockCertProvider>> daemon_cert_provider{
std::make_unique<NiceMock<mpt::MockCertProvider>>()};
mpt::MockPlatform::GuardedMock attr{mpt::MockPlatform::inject<NiceMock>()};
mpt::MockPlatform* mock_platform = attr.first;
mpt::StubCertStore cert_store;
StrictMock<MockDaemonRpc> mock_daemon{server_address, *daemon_cert_provider,
&cert_store}; // strict to fail on unexpected calls and play well with sharing
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
inline static std::stringstream trash_stream; // this may have contents (that we don't care about)
static constexpr char petenv_name[] = "the-petenv";
const grpc::Status ok{};
mpt::MockSSHTestFixture mock_ssh_test_fixture;
};
struct ClientAlias : public Client, public FakeAliasConfig
{
ClientAlias()
{
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(_))
.WillRepeatedly(Return(fake_alias_dir.path()));
EXPECT_CALL(*mock_platform, create_alias_script(_, _)).WillRepeatedly(Return());
EXPECT_CALL(*mock_platform, remove_alias_script(_)).WillRepeatedly(Return());
}
};
auto make_info_function(const std::string& source_path = "", const std::string& target_path = "")
{
auto info_function = [&source_path, &target_path](
grpc::ServerContext*, grpc::ServerReaderWriter<mp::InfoReply, mp::InfoRequest>* server) {
mp::InfoRequest request;
server->Read(&request);
mp::InfoReply info_reply;
if (request.instance_snapshot_pairs(0).instance_name() == "primary")
{
auto vm_info = info_reply.add_details();
vm_info->set_name("primary");
vm_info->mutable_instance_status()->set_status(mp::InstanceStatus::RUNNING);
if (!source_path.empty() && !target_path.empty())
{
auto mount_info = vm_info->mutable_mount_info();
auto entry = mount_info->add_mount_paths();
entry->set_source_path(source_path);
entry->set_target_path(target_path);
if (source_path.size() > target_path.size())
mount_info->set_longest_path_len(source_path.size());
else
mount_info->set_longest_path_len(target_path.size());
}
server->Write(info_reply);
return grpc::Status{};
}
else
return grpc::Status{grpc::StatusCode::INVALID_ARGUMENT, "msg"};
};
return info_function;
}
typedef std::vector<std::pair<std::string, mp::AliasDefinition>> AliasesVector;
const std::string csv_header{"Alias,Instance,Command,Working directory,Context\n"};
// Tests for no postional args given
TEST_F(Client, no_command_is_error)
{
EXPECT_THAT(send_command({}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, no_command_help_ok)
{
EXPECT_THAT(send_command({"-h"}), Eq(mp::ReturnCode::Ok));
}
// Remote-handler tests
template <typename M>
auto match_uptr_to_remote_settings_handler(M&& matcher)
{
return Pointee(
Address(WhenDynamicCastTo<const mp::RemoteSettingsHandler*>(AllOf(NotNull(), std::forward<M>(matcher)))));
}
struct RemoteHandlerTest : public Client, public WithParamInterface<std::string>
{
inline static const auto cmds = Values("", " ", "help", "get");
};
TEST_P(RemoteHandlerTest, registersRemoteSettingsHandler)
{
EXPECT_CALL(mock_settings, // clang-format don't get it
register_handler(match_uptr_to_remote_settings_handler(
Property(&mp::RemoteSettingsHandler::get_key_prefix, Eq("local.")))))
.Times(1);
send_command({GetParam()});
}
TEST_P(RemoteHandlerTest, unregistersRemoteSettingsHandler)
{
auto handler = reinterpret_cast<mp::SettingsHandler*>(0x123123);
EXPECT_CALL(mock_settings, register_handler(match_uptr_to_remote_settings_handler(_))).WillOnce(Return(handler));
EXPECT_CALL(mock_settings, unregister_handler(handler)).Times(1);
send_command({GetParam()});
}
INSTANTIATE_TEST_SUITE_P(Client, RemoteHandlerTest, RemoteHandlerTest::cmds);
struct RemoteHandlerVerbosity : public Client, WithParamInterface<std::tuple<int, std::string>>
{
};
TEST_P(RemoteHandlerVerbosity, honors_verbosity_in_remote_settings_handler)
{
const auto& [num_vs, cmd] = GetParam();
EXPECT_CALL(mock_settings, // clang-format hands off...
register_handler(match_uptr_to_remote_settings_handler(
Property(&mp::RemoteSettingsHandler::get_verbosity, Eq(num_vs))))) // ... this piece of code
.Times(1);
auto vs = fmt::format("{}{}", num_vs ? "-" : "", std::string(num_vs, 'v'));
send_command({vs, cmd});
}
INSTANTIATE_TEST_SUITE_P(Client, RemoteHandlerVerbosity, Combine(Range(0, 5), RemoteHandlerTest::cmds));
TEST_F(Client, handles_remote_handler_exception)
{
auto cmd = "get";
auto key = "nowhere";
auto msg = "can't";
auto details = "too far";
EXPECT_CALL(mock_settings, get(QString{key}))
.WillOnce(Throw(mp::RemoteHandlerException{grpc::Status{grpc::StatusCode::INVALID_ARGUMENT, msg, details}}));
std::stringstream fake_cerr;
auto got = send_command({cmd, key}, trash_stream, fake_cerr);
EXPECT_THAT(fake_cerr.str(), AllOf(HasSubstr(cmd), HasSubstr(msg), Not(HasSubstr(details))));
EXPECT_EQ(got, mp::CommandFail);
}
// transfer cli tests
TEST_F(Client, transfer_cmd_instance_source_local_target)
{
auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject();
auto mocked_sftp_client = std::make_unique<mpt::MockSFTPClient>();
auto mocked_sftp_client_p = mocked_sftp_client.get();
EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient).WillOnce(Return(std::move(mocked_sftp_client)));
EXPECT_CALL(*mocked_sftp_client_p, pull).WillOnce(Return(true));
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce([](auto, grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
mp::SSHInfoReply reply;
reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}});
server->Write(reply);
return grpc::Status{};
});
EXPECT_EQ(send_command({"transfer", "test-vm:foo", "bar"}), mp::ReturnCode::Ok);
}
TEST_F(Client, transfer_cmd_instance_sources_local_target_not_dir)
{
auto [mocked_file_ops, mocked_file_ops_guard] = mpt::MockFileOps::inject();
auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject();
EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient).WillOnce(Return(std::make_unique<mpt::MockSFTPClient>()));
EXPECT_CALL(*mocked_file_ops, is_directory).WillOnce(Return(false));
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce([](auto, grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
mp::SSHInfoReply reply;
reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}});
server->Write(reply);
return grpc::Status{};
});
std::stringstream err;
EXPECT_EQ(send_command({"transfer", "test-vm:foo", "test-vm:baz", "bar"}, trash_stream, err),
mp::ReturnCode::CommandFail);
EXPECT_THAT(err.str(), HasSubstr("Target \"bar\" is not a directory"));
}
TEST_F(Client, transfer_cmd_instance_sources_local_target_cannot_access)
{
auto [mocked_file_ops, mocked_file_ops_guard] = mpt::MockFileOps::inject();
auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject();
EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient).WillOnce(Return(std::make_unique<mpt::MockSFTPClient>()));
auto err = std::make_error_code(std::errc::permission_denied);
EXPECT_CALL(*mocked_file_ops, is_directory).WillOnce([&](auto, std::error_code& e) {
e = err;
return false;
});
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce([](auto, grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
mp::SSHInfoReply reply;
reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}});
server->Write(reply);
return grpc::Status{};
});
std::stringstream err_sink;
EXPECT_EQ(send_command({"transfer", "test-vm:foo", "test-vm:baz", "bar"}, trash_stream, err_sink),
mp::ReturnCode::CommandFail);
EXPECT_THAT(err_sink.str(), HasSubstr(fmt::format("Cannot access \"bar\": {}", err.message())));
}
TEST_F(Client, transfer_cmd_local_sources_instance_target_not_dir)
{
auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject();
auto mocked_sftp_client = std::make_unique<mpt::MockSFTPClient>();
auto mocked_sftp_client_p = mocked_sftp_client.get();
EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient).WillOnce(Return(std::move(mocked_sftp_client)));
EXPECT_CALL(*mocked_sftp_client_p, is_remote_dir).WillOnce(Return(false));
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce([](auto, grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
mp::SSHInfoReply reply;
reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}});
server->Write(reply);
return grpc::Status{};
});
std::stringstream err;
EXPECT_EQ(send_command({"transfer", "foo", "baz", "test-vm:bar"}, trash_stream, err), mp::ReturnCode::CommandFail);
EXPECT_THAT(err.str(), HasSubstr("Target \"bar\" is not a directory"));
}
TEST_F(Client, transfer_cmd_local_source_instance_target)
{
auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject();
auto mocked_sftp_client = std::make_unique<mpt::MockSFTPClient>();
auto mocked_sftp_client_p = mocked_sftp_client.get();
EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient).WillOnce(Return(std::move(mocked_sftp_client)));
EXPECT_CALL(*mocked_sftp_client_p, push).WillRepeatedly(Return(true));
EXPECT_CALL(*mocked_sftp_client_p, is_remote_dir).WillOnce(Return(true));
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce([](auto, grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
mp::SSHInfoReply reply;
reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}});
server->Write(reply);
return grpc::Status{};
});
EXPECT_EQ(send_command({"transfer", "foo", "C:\\Users\\file", "test-vm:bar"}), mp::ReturnCode::Ok);
}
TEST_F(Client, transfer_cmd_help_ok)
{
EXPECT_THAT(send_command({"transfer", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, transfer_cmd_fails_no_instance)
{
EXPECT_THAT(send_command({"transfer", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, transfer_cmd_fails_instance_both_source_destination)
{
EXPECT_THAT(send_command({"transfer", "test-vm1:foo", "test-vm2:bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, transfer_cmd_fails_too_few_args)
{
EXPECT_THAT(send_command({"transfer", "foo"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, transfer_cmd_local_target_not_all_instance_sources_fails)
{
EXPECT_THAT(send_command({"transfer", "aaa", "test-vm1:foo", "bbb"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, transfer_cmd_stdin_good_destination_ok)
{
auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject();
auto mocked_sftp_client = std::make_unique<mpt::MockSFTPClient>();
auto mocked_sftp_client_p = mocked_sftp_client.get();
EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient).WillOnce(Return(std::move(mocked_sftp_client)));
EXPECT_CALL(*mocked_sftp_client_p, from_cin);
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce([](auto, grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
mp::SSHInfoReply reply;
reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}});
server->Write(reply);
return grpc::Status{};
});
EXPECT_EQ(send_command({"transfer", "-", "test-vm1:foo"}), mp::ReturnCode::Ok);
}
TEST_F(Client, transfer_cmd_stdin_bad_destination_fails)
{
EXPECT_THAT(send_command({"transfer", "-", "foo"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, transfer_cmd_stdout_good_source_ok)
{
auto [mocked_sftp_utils, mocked_sftp_utils_guard] = mpt::MockSFTPUtils::inject();
auto mocked_sftp_client = std::make_unique<mpt::MockSFTPClient>();
auto mocked_sftp_client_p = mocked_sftp_client.get();
EXPECT_CALL(*mocked_sftp_utils, make_SFTPClient).WillOnce(Return(std::move(mocked_sftp_client)));
EXPECT_CALL(*mocked_sftp_client_p, to_cout);
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce([](auto, grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
mp::SSHInfoReply reply;
reply.mutable_ssh_info()->insert({"test-vm", mp::SSHInfo{}});
server->Write(reply);
return grpc::Status{};
});
EXPECT_EQ(send_command({"transfer", "test-vm1:foo", "-"}), mp::ReturnCode::Ok);
}
TEST_F(Client, transfer_cmd_stdout_bad_source_fails)
{
EXPECT_THAT(send_command({"transfer", "foo", "-"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, transfer_cmd_stdout_stdin_only_fails)
{
EXPECT_THAT(send_command({"transfer", "-", "-"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, transfer_cmd_stdout_stdin_declaration_fails)
{
EXPECT_THAT(send_command({"transfer", "test-vm1:foo", "-", "-"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, transfer_cmd_stream_too_many_args)
{
EXPECT_THAT(send_command({"transfer", "test-vm1:foo", "aaaaa", "-"}), Eq(mp::ReturnCode::CommandLineError));
}
// shell cli test
TEST_F(Client, shell_cmd_good_arguments)
{
EXPECT_CALL(mock_daemon, ssh_info(_, _));
EXPECT_THAT(send_command({"shell", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shell_cmd_help_ok)
{
EXPECT_THAT(send_command({"shell", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shell_cmd_no_args_targets_petenv)
{
const auto petenv_matcher = make_ssh_info_instance_matcher(petenv_name);
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"shell"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shell_cmd_considers_configured_petenv)
{
const auto custom_petenv = "jarjar binks";
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(custom_petenv));
const auto petenv_matcher = make_ssh_info_instance_matcher(custom_petenv);
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"shell"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shell_cmd_can_target_petenv_explicitly)
{
const auto petenv_matcher = make_ssh_info_instance_matcher(petenv_name);
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"shell", petenv_name}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shell_cmd_launches_petenv_if_absent)
{
const auto petenv_ssh_info_matcher = make_ssh_info_instance_matcher(petenv_name);
const auto petenv_launch_matcher = Property(&mp::LaunchRequest::instance_name, StrEq(petenv_name));
const grpc::Status notfound{grpc::StatusCode::NOT_FOUND, "msg"};
EXPECT_CALL(mock_daemon, mount).WillRepeatedly(Return(ok)); // 0 or more times
InSequence seq;
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(WithArg<1>(
check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(petenv_ssh_info_matcher, notfound)));
EXPECT_CALL(mock_daemon, launch)
.WillOnce(WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(petenv_launch_matcher, ok)));
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(
WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(petenv_ssh_info_matcher, ok)));
EXPECT_THAT(send_command({"shell", petenv_name}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shell_cmd_automounts_when_launching_petenv)
{
const grpc::Status notfound{grpc::StatusCode::NOT_FOUND, "msg"};
InSequence seq;
EXPECT_CALL(mock_daemon, ssh_info(_, _)).WillOnce(Return(notfound));
EXPECT_CALL(mock_daemon, launch(_, _)).WillOnce(Return(ok));
EXPECT_CALL(mock_daemon, mount(_, _)).WillOnce(Return(ok));
EXPECT_CALL(mock_daemon, ssh_info(_, _)).WillOnce(Return(ok));
EXPECT_THAT(send_command({"shell", petenv_name}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shellCmdSkipsAutomountWhenDisabled)
{
std::stringstream cout_stream;
const grpc::Status notfound{grpc::StatusCode::NOT_FOUND, "msg"};
InSequence seq;
EXPECT_CALL(mock_daemon, ssh_info(_, _)).WillOnce(Return(notfound));
EXPECT_CALL(mock_daemon, launch(_, _)).WillOnce(Return(ok));
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillOnce(Return("false"));
EXPECT_CALL(mock_daemon, mount(_, _)).Times(0);
EXPECT_CALL(mock_daemon, ssh_info(_, _)).WillOnce(Return(ok));
EXPECT_THAT(send_command({"shell", petenv_name}, cout_stream), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(cout_stream.str(), HasSubstr("Skipping mount due to disabled mounts feature\n"));
}
TEST_F(Client, shell_cmd_forwards_verbosity_to_subcommands)
{
const grpc::Status notfound{grpc::StatusCode::NOT_FOUND, "msg"};
const auto verbosity = 3;
const auto ssh_info_verbosity_matcher = make_request_verbosity_matcher<mp::SSHInfoRequest>(verbosity);
const auto launch_verbosity_matcher = make_request_verbosity_matcher<mp::LaunchRequest>(verbosity);
const auto mount_verbosity_matcher = make_request_verbosity_matcher<mp::MountRequest>(verbosity);
InSequence seq;
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(WithArg<1>(
check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(ssh_info_verbosity_matcher, notfound)));
EXPECT_CALL(mock_daemon, launch)
.WillOnce(
WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(launch_verbosity_matcher, ok)));
EXPECT_CALL(mock_daemon, mount)
.WillOnce(WithArg<1>(check_request_and_return<mp::MountReply, mp::MountRequest>(mount_verbosity_matcher, ok)));
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(
WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(ssh_info_verbosity_matcher, ok)));
EXPECT_THAT(send_command({"shell", "-vvv"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shell_cmd_forwards_timeout_to_subcommands)
{
const grpc::Status notfound{grpc::StatusCode::NOT_FOUND, "msg"};
const auto timeout = 123;
const auto launch_timeout_matcher = make_request_timeout_matcher<mp::LaunchRequest>(timeout);
InSequence seq;
EXPECT_CALL(mock_daemon, ssh_info).WillOnce(Return(notfound));
EXPECT_CALL(mock_daemon, launch)
.WillOnce(WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(launch_timeout_matcher, ok)));
EXPECT_CALL(mock_daemon, mount).WillOnce(Return(ok));
EXPECT_CALL(mock_daemon, ssh_info).WillOnce(Return(ok));
EXPECT_THAT(send_command({"shell", "--timeout", std::to_string(timeout)}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shellCmdFailsWhenUnableToRetrieveAutomountSetting)
{
const grpc::Status notfound{grpc::StatusCode::NOT_FOUND, "msg"}, error{grpc::StatusCode::INTERNAL, "oops"};
const auto except = mp::RemoteHandlerException{error};
InSequence seq;
EXPECT_CALL(mock_daemon, ssh_info).WillOnce(Return(notfound));
EXPECT_CALL(mock_daemon, launch).WillOnce(Return(ok));
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillOnce(Throw(except));
EXPECT_CALL(mock_daemon, mount).Times(0);
EXPECT_THAT(send_command({"shell", petenv_name}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, shell_cmd_fails_when_automounting_in_petenv_fails)
{
const auto notfound = grpc::Status{grpc::StatusCode::NOT_FOUND, "msg"};
const auto mount_failure = grpc::Status{grpc::StatusCode::INVALID_ARGUMENT, "msg"};
InSequence seq;
EXPECT_CALL(mock_daemon, ssh_info(_, _)).WillOnce(Return(notfound));
EXPECT_CALL(mock_daemon, launch(_, _)).WillOnce(Return(ok));
EXPECT_CALL(mock_daemon, mount(_, _)).WillOnce(Return(mount_failure));
EXPECT_THAT(send_command({"shell", petenv_name}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, shell_cmd_starts_instance_if_stopped_or_suspended)
{
const auto instance = "ordinary";
const auto ssh_info_matcher = make_ssh_info_instance_matcher(instance);
const auto start_matcher = make_instance_in_repeated_field_matcher<mp::StartRequest, 1>(instance);
const grpc::Status aborted{grpc::StatusCode::ABORTED, "msg"};
InSequence seq;
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(
WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(ssh_info_matcher, aborted)));
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(start_matcher, ok)));
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(ssh_info_matcher, ok)));
EXPECT_THAT(send_command({"shell", instance}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shell_cmd_starts_petenv_if_stopped_or_suspended)
{
const auto ssh_info_matcher = make_ssh_info_instance_matcher(petenv_name);
const auto start_matcher = make_instance_in_repeated_field_matcher<mp::StartRequest, 1>(petenv_name);
const grpc::Status aborted{grpc::StatusCode::ABORTED, "msg"};
InSequence seq;
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(
WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(ssh_info_matcher, aborted)));
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(start_matcher, ok)));
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(ssh_info_matcher, ok)));
EXPECT_THAT(send_command({"shell", petenv_name}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shell_cmd_fails_if_petenv_present_but_deleted)
{
const auto petenv_matcher = make_ssh_info_instance_matcher(petenv_name);
const grpc::Status failed_precond{grpc::StatusCode::FAILED_PRECONDITION, "msg"};
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(
WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(petenv_matcher, failed_precond)));
EXPECT_THAT(send_command({"shell", petenv_name}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, shell_cmd_fails_on_other_absent_instance)
{
const auto instance = "ordinary";
const auto instance_matcher = make_ssh_info_instance_matcher(instance);
const grpc::Status notfound{grpc::StatusCode::NOT_FOUND, "msg"};
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(
WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(instance_matcher, notfound)));
EXPECT_THAT(send_command({"shell", instance}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, shell_cmd_fails_multiple_args)
{
EXPECT_THAT(send_command({"shell", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, shell_cmd_fails_unknown_options)
{
EXPECT_THAT(send_command({"shell", "--not", "foo"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, shell_cmd_disabled_petenv)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, ssh_info(_, _)).Times(0);
EXPECT_THAT(send_command({"shell"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_CALL(mock_daemon, ssh_info(_, _)).Times(2);
EXPECT_THAT(send_command({"shell", "foo"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"shell", "primary"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, shell_cmd_disabled_petenv_help)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, ssh_info(_, _)).Times(0);
EXPECT_THAT(send_command({"shell", "-h"}), Eq(mp::ReturnCode::Ok));
}
// launch cli tests
TEST_F(Client, launch_cmd_good_arguments)
{
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_THAT(send_command({"launch", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, launch_cmd_wrong_mem_arguments)
{
EXPECT_CALL(mock_daemon, launch(_, _)).Times(0);
MP_EXPECT_THROW_THAT(send_command({"launch", "-m", "wrong"}), std::runtime_error,
mpt::match_what(HasSubstr("wrong is not a valid memory size")));
MP_EXPECT_THROW_THAT(send_command({"launch", "--memory", "1.23f"}), std::runtime_error,
mpt::match_what(HasSubstr("1.23f is not a valid memory size")));
MP_EXPECT_THROW_THAT(send_command({"launch", "-memory", "2048M"}), std::runtime_error,
mpt::match_what(HasSubstr("emory is not a valid memory size"))); // note single dash
}
TEST_F(Client, launch_cmd_wrong_disk_arguments)
{
EXPECT_CALL(mock_daemon, launch(_, _)).Times(0);
MP_EXPECT_THROW_THAT(send_command({"launch", "-d", "wrong"}), std::runtime_error,
mpt::match_what(HasSubstr("wrong is not a valid memory size")));
MP_EXPECT_THROW_THAT(send_command({"launch", "--disk", "4.56f"}), std::runtime_error,
mpt::match_what(HasSubstr("4.56f is not a valid memory size")));
MP_EXPECT_THROW_THAT(send_command({"launch", "-disk", "8192M"}), std::runtime_error,
mpt::match_what(HasSubstr("isk is not a valid memory size"))); // note single dash
}
TEST_F(Client, launch_cmd_help_ok)
{
EXPECT_THAT(send_command({"launch", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, launch_cmd_fails_multiple_args)
{
EXPECT_THAT(send_command({"launch", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_fails_unknown_option)
{
EXPECT_THAT(send_command({"launch", "-z", "2"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_name_option_ok)
{
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_THAT(send_command({"launch", "-n", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, launch_cmd_name_option_fails_no_value)
{
EXPECT_THAT(send_command({"launch", "-n"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_memory_option_ok)
{
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_THAT(send_command({"launch", "-m", "1G"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, launch_cmd_memory_option_fails_no_value)
{
EXPECT_THAT(send_command({"launch", "-m"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_memory_fails_duplicate_options)
{
EXPECT_THAT(send_command({"launch", "--memory", "2048M", "--mem", "2048M"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_memory_deprecated_option_warning)
{
std::stringstream cerr_stream;
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_THAT(send_command({"launch", "--mem", "2048M"}, trash_stream, cerr_stream), Eq(mp::ReturnCode::Ok));
EXPECT_NE(std::string::npos, cerr_stream.str().find("Warning: the \"--mem\"")) << "cout has: " << cerr_stream.str();
}
TEST_F(Client, launch_cmd_cpu_option_ok)
{
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_THAT(send_command({"launch", "-c", "2"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, launch_cmd_cpu_option_alpha_numeric_fail)
{
EXPECT_THAT(send_command({"launch", "-c", "w00t"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_cpu_option_alpha_fail)
{
EXPECT_THAT(send_command({"launch", "-c", "many"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_cpu_option_decimal_fail)
{
EXPECT_THAT(send_command({"launch", "-c", "1.608"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_cpu_option_zero_fail)
{
EXPECT_THAT(send_command({"launch", "-c", "0"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_cpu_option_negative_fail)
{
EXPECT_THAT(send_command({"launch", "-c", "-2"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_cpu_option_fails_no_value)
{
EXPECT_THAT(send_command({"launch", "-c"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, DISABLE_ON_MACOS(launch_cmd_custom_image_file_ok))
{
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_THAT(send_command({"launch", "file://foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, DISABLE_ON_MACOS(launch_cmd_custom_image_http_ok))
{
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_THAT(send_command({"launch", "http://foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, launch_cmd_cloudinit_option_with_valid_file_is_ok)
{
QTemporaryFile tmpfile; // file is auto-deleted when this goes out of scope
tmpfile.open();
tmpfile.write("password: passw0rd"); // need some YAML
tmpfile.close();
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_THAT(send_command({"launch", "--cloud-init", qPrintable(tmpfile.fileName())}), Eq(mp::ReturnCode::Ok));
}
struct BadCloudInitFile : public Client, WithParamInterface<std::string>
{
};
TEST_P(BadCloudInitFile, launch_cmd_cloudinit_option_fails_with_missing_file)
{
std::stringstream cerr_stream;
auto missing_file{"/definitely/missing-file"};
EXPECT_THAT(send_command({"launch", "--cloud-init", missing_file}, trash_stream, cerr_stream),
Eq(mp::ReturnCode::CommandLineError));
EXPECT_NE(std::string::npos, cerr_stream.str().find("Could not load")) << "cerr has: " << cerr_stream.str();
EXPECT_NE(std::string::npos, cerr_stream.str().find(missing_file)) << "cerr has: " << cerr_stream.str();
}
INSTANTIATE_TEST_SUITE_P(Client,
BadCloudInitFile,
Values("/definitely/missing-file", "/dev/null", "/home", "/root/.bashrc"));
TEST_F(Client, launch_cmd_cloudinit_option_fails_no_value)
{
EXPECT_THAT(send_command({"launch", "--cloud-init"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, launch_cmd_cloudinit_option_reads_stdin_ok)
{
MockStdCin cin("password: passw0rd"); // no effect since terminal encapsulation of streams
std::stringstream ss;
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_THAT(send_command({"launch", "--cloud-init", "-"}, trash_stream, trash_stream, ss), Eq(mp::ReturnCode::Ok));
}
#ifndef WIN32 // TODO make home mocking work for windows
TEST_F(Client, launch_cmd_automounts_home_in_petenv)
{
const auto fake_home = QTemporaryDir{}; // the client checks the mount source exists
const auto env_scope = mpt::SetEnvScope{"HOME", fake_home.path().toUtf8()};
const auto home_automount_matcher =
make_mount_matcher(fake_home.path().toStdString(), mp::home_automount_dir, petenv_name);
const auto petenv_launch_matcher = make_launch_instance_matcher(petenv_name);
InSequence seq;
EXPECT_CALL(mock_daemon, launch)
.WillOnce(WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(petenv_launch_matcher, ok)));
EXPECT_CALL(mock_daemon, mount)
.WillOnce(WithArg<1>(check_request_and_return<mp::MountReply, mp::MountRequest>(home_automount_matcher, ok)));
EXPECT_THAT(send_command({"launch", "--name", petenv_name}), Eq(mp::ReturnCode::Ok));
}
#endif
TEST_F(Client, launchCmdSkipsAutomountWhenDisabled)
{
std::stringstream cout_stream;
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillOnce(Return("false"));
EXPECT_CALL(mock_daemon, launch).WillOnce(Return(ok));
EXPECT_CALL(mock_daemon, mount).Times(0);
EXPECT_THAT(send_command({"launch", "--name", petenv_name}, cout_stream), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(cout_stream.str(), HasSubstr("Skipping mount due to disabled mounts feature\n"));
}
TEST_F(Client, launchCmdOnlyWarnsMountForPetEnv)
{
const auto invalid_argument = grpc::Status{grpc::StatusCode::INVALID_ARGUMENT, "msg"};
std::stringstream cout_stream;
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillRepeatedly(Return("false"));
EXPECT_CALL(mock_daemon, launch(_, _)).WillOnce(Return(invalid_argument));
EXPECT_THAT(send_command({"launch", "--name", ".asdf"}, cout_stream), Eq(mp::ReturnCode::CommandFail));
EXPECT_THAT(cout_stream.str(), Not(HasSubstr("Skipping mount due to disabled mounts feature\n")));
}
TEST_F(Client, launchCmdFailsWhenUnableToRetrieveAutomountSetting)
{
const auto except = mp::RemoteHandlerException{grpc::Status{grpc::StatusCode::INTERNAL, "oops"}};
InSequence seq;
EXPECT_CALL(mock_daemon, launch).WillOnce(Return(ok));
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillOnce(Throw(except));
EXPECT_CALL(mock_daemon, mount).Times(0);
EXPECT_THAT(send_command({"launch", "--name", petenv_name}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, launch_cmd_fails_when_automounting_in_petenv_fails)
{
const grpc::Status mount_failure{grpc::StatusCode::INVALID_ARGUMENT, "msg"};
InSequence seq;
EXPECT_CALL(mock_daemon, launch(_, _)).WillOnce(Return(ok));
EXPECT_CALL(mock_daemon, mount(_, _)).WillOnce(Return(mount_failure));
EXPECT_THAT(send_command({"launch", "--name", petenv_name}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, launch_cmd_forwards_verbosity_to_subcommands)
{
const auto verbosity = 4;
const auto launch_verbosity_matcher = make_request_verbosity_matcher<mp::LaunchRequest>(verbosity);
const auto mount_verbosity_matcher = make_request_verbosity_matcher<mp::MountRequest>(verbosity);
InSequence seq;
EXPECT_CALL(mock_daemon, launch)
.WillOnce(
WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(launch_verbosity_matcher, ok)));
EXPECT_CALL(mock_daemon, mount)
.WillOnce(WithArg<1>(check_request_and_return<mp::MountReply, mp::MountRequest>(mount_verbosity_matcher, ok)));
EXPECT_THAT(send_command({"launch", "--name", petenv_name, "-vvvv"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, launch_cmd_does_not_automount_in_normal_instances)
{
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_CALL(mock_daemon, mount(_, _)).Times(0); // because we may want to move from a Strict mock in the future
EXPECT_THAT(send_command({"launch"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, launch_cmd_disabled_petenv_passes)
{
const auto custom_petenv = "";
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(custom_petenv));
const auto petenv_matcher = make_launch_instance_matcher("foo");
EXPECT_CALL(mock_daemon, launch)
.WillOnce(WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"launch", "--name", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, launch_cmd_mount_option)
{
const QTemporaryDir fake_directory{};
const auto fake_source = fake_directory.path().toStdString();
const auto fake_target = fake_source;
const auto instance_name = "some_instance";
const auto mount_matcher = make_mount_matcher(fake_source, fake_target, instance_name);
const auto launch_matcher = make_launch_instance_matcher(instance_name);
EXPECT_CALL(mock_daemon, launch)
.WillOnce(WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(launch_matcher, ok)));
EXPECT_CALL(mock_daemon, mount)
.WillOnce(WithArg<1>(check_request_and_return<mp::MountReply, mp::MountRequest>(mount_matcher, ok)));
EXPECT_EQ(send_command({"launch", "--name", instance_name, "--mount", fake_source}), mp::ReturnCode::Ok);
}
TEST_F(Client, launchCmdMountOptionFailsOnInvalidDir)
{
auto [mocked_file_ops, mocked_file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mocked_file_ops, exists(A<const QFileInfo&>())).WillOnce(Return(false)).WillRepeatedly(Return(true));
EXPECT_CALL(*mocked_file_ops, isDir(A<const QFileInfo&>())).WillOnce(Return(false)).WillRepeatedly(Return(true));
EXPECT_CALL(*mocked_file_ops, isReadable(A<const QFileInfo&>()))
.WillOnce(Return(false))
.WillRepeatedly(Return(true));
const auto fake_source = "invalid/dir";
const auto fake_target = fake_source;
const auto instance_name = "some_instance";
std::stringstream err;
EXPECT_EQ(
send_command({"launch", "--name", instance_name, "--mount", fmt::format("{}:{}", fake_source, fake_target)},
trash_stream, err),
mp::ReturnCode::CommandLineError);
EXPECT_THAT(err.str(), HasSubstr(fmt::format("Mount source path \"{}\" does not exist", fake_source)));
err.clear();
EXPECT_EQ(
send_command({"launch", "--name", instance_name, "--mount", fmt::format("{}:{}", fake_source, fake_target)},
trash_stream, err),
mp::ReturnCode::CommandLineError);
EXPECT_THAT(err.str(), HasSubstr(fmt::format("Mount source path \"{}\" is not a directory", fake_source)));
err.clear();
EXPECT_EQ(
send_command({"launch", "--name", instance_name, "--mount", fmt::format("{}:{}", fake_source, fake_target)},
trash_stream, err),
mp::ReturnCode::CommandLineError);
EXPECT_THAT(err.str(), HasSubstr(fmt::format("Mount source path \"{}\" is not readable", fake_source)));
}
TEST_F(Client, launch_cmd_petenv_mount_option_override_home)
{
const QTemporaryDir fake_directory{};
const auto fake_source = fake_directory.path().toStdString();
const auto fake_target = mp::home_automount_dir;
const auto mount_matcher = make_mount_matcher(fake_source, fake_target, petenv_name);
const auto launch_matcher = make_launch_instance_matcher(petenv_name);
EXPECT_CALL(mock_daemon, launch)
.WillOnce(WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(launch_matcher, ok)));
EXPECT_CALL(mock_daemon, mount)
.WillOnce(WithArg<1>(check_request_and_return<mp::MountReply, mp::MountRequest>(mount_matcher, ok)));
EXPECT_EQ(
send_command({"launch", "--name", petenv_name, "--mount", fmt::format("{}:{}", fake_source, fake_target)}),
mp::ReturnCode::Ok);
}
TEST_F(Client, launch_cmd_cloudinit_url)
{
const auto fake_url = QStringLiteral("https://example.com");
const auto fake_downloaded_yaml = QByteArrayLiteral("password: passw0rd");
auto [mock_network_manager_factory, guard] = mpt::MockNetworkManagerFactory::inject();
auto mock_network_access_manager = std::make_unique<NiceMock<mpt::MockQNetworkAccessManager>>();
auto mock_reply = new mpt::MockQNetworkReply();
EXPECT_CALL(*mock_network_manager_factory, make_network_manager).WillOnce([&mock_network_access_manager](auto...) {
return std::move(mock_network_access_manager);
});
EXPECT_CALL(*mock_network_access_manager, createRequest).WillOnce(Return(mock_reply));
EXPECT_CALL(*mock_reply, readData)
.WillOnce([&fake_downloaded_yaml](char* data, auto) {
auto data_size = fake_downloaded_yaml.size();
memcpy(data, fake_downloaded_yaml.constData(), data_size);
return data_size;
})
.WillOnce(Return(0));
QTimer::singleShot(0, [&mock_reply] { mock_reply->finished(); });
EXPECT_CALL(mock_daemon, launch).WillOnce(Return(ok));
EXPECT_EQ(send_command({"launch", "--cloud-init", fake_url.toStdString()}), mp::ReturnCode::Ok);
}
typedef typename std::tuple<mp::id_mappings, mp::id_mappings, mp::id_mappings, mp::id_mappings> id_test_tuples;
struct MountIdMappingsTest : public Client, public WithParamInterface<id_test_tuples>
{
};
TEST_P(MountIdMappingsTest, mount_cmd_id_mappings)
{
const QTemporaryDir fake_directory{};
const auto fake_source = fake_directory.path().toStdString();
const auto fake_target = "instance_name:mounted_folder";
auto [cmdline_uid_mappings, cmdline_gid_mappings, expected_uid_mappings, expected_gid_mappings] = GetParam();
const auto id_mappings_matcher = make_mount_id_mappings_matcher(expected_uid_mappings, expected_gid_mappings);
EXPECT_CALL(mock_daemon, mount)
.WillOnce(WithArg<1>(check_request_and_return<mp::MountReply, mp::MountRequest>(id_mappings_matcher, ok)));
std::vector<std::string> cmdline{"mount", fake_source, fake_target};
for (const auto& uid_element : cmdline_uid_mappings)
{
cmdline.push_back("--uid-map");
cmdline.push_back(std::to_string(uid_element.first) + ":" + std::to_string(uid_element.second));
}
for (const auto& gid_element : cmdline_gid_mappings)
{
cmdline.push_back("--gid-map");
cmdline.push_back(std::to_string(gid_element.first) + ":" + std::to_string(gid_element.second));
}
EXPECT_EQ(send_command(cmdline), mp::ReturnCode::Ok);
}
INSTANTIATE_TEST_SUITE_P(
Client, MountIdMappingsTest,
Values(id_test_tuples{{{500, 600}, {300, 400}}, {{700, 800}}, {{500, 600}, {300, 400}}, {{700, 800}}},
id_test_tuples{{}, {{200, 300}}, {{mcp::getuid(), mp::default_id}}, {{200, 300}}},
id_test_tuples{{{100, 200}}, {}, {{100, 200}}, {{mcp::getgid(), mp::default_id}}},
id_test_tuples{{}, {}, {{mcp::getuid(), mp::default_id}}, {{mcp::getgid(), mp::default_id}}}));
struct TestInvalidNetworkOptions : Client, WithParamInterface<std::vector<std::string>>
{
};
TEST_P(TestInvalidNetworkOptions, launch_cmd_return)
{
auto commands = GetParam();
commands.insert(commands.begin(), std::string{"launch"});
EXPECT_CALL(mock_daemon, launch(_, _)).Times(0);
EXPECT_THAT(send_command(commands), Eq(mp::ReturnCode::CommandLineError));
}
INSTANTIATE_TEST_SUITE_P(Client, TestInvalidNetworkOptions,
Values(std::vector<std::string>{"--network", "invalid=option"},
std::vector<std::string>{"--network"},
std::vector<std::string>{"--network", "mode=manual"},
std::vector<std::string>{"--network", "mode=manual=auto"},
std::vector<std::string>{"--network", "name=eth0,mode=man"},
std::vector<std::string>{"--network", "name=eth1,mac=0a"},
std::vector<std::string>{"--network", "eth2", "--network"}));
struct TestValidNetworkOptions : Client, WithParamInterface<std::vector<std::string>>
{
};
TEST_P(TestValidNetworkOptions, launch_cmd_return)
{
auto commands = GetParam();
commands.insert(commands.begin(), std::string{"launch"});
EXPECT_CALL(mock_daemon, launch(_, _));
EXPECT_THAT(send_command(commands), Eq(mp::ReturnCode::Ok));
}
INSTANTIATE_TEST_SUITE_P(Client, TestValidNetworkOptions,
Values(std::vector<std::string>{"--network", "eth3"},
std::vector<std::string>{"--network", "name=eth4", "--network", "eth5"},
std::vector<std::string>{"--network", "name=eth6,mac=01:23:45:67:89:ab"},
std::vector<std::string>{"--network", "name=eth7,mode=manual"},
std::vector<std::string>{"--network", "name=eth8,mode=auto"},
std::vector<std::string>{"--network", "name=eth9", "--network", "name=eth9"},
std::vector<std::string>{"--network", "bridged"},
std::vector<std::string>{"--network", "name=bridged"},
std::vector<std::string>{"--bridged"}));
// purge cli tests
TEST_F(Client, purge_cmd_ok_no_args)
{
EXPECT_CALL(mock_daemon, purge(_, _));
EXPECT_THAT(send_command({"purge"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, purge_cmd_fails_with_args)
{
EXPECT_THAT(send_command({"purge", "foo"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, purge_cmd_help_ok)
{
EXPECT_THAT(send_command({"purge", "-h"}), Eq(mp::ReturnCode::Ok));
}
// exec cli tests
TEST_F(Client, exec_cmd_double_dash_ok_cmd_arg)
{
EXPECT_CALL(mock_daemon, ssh_info(_, _));
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function());
EXPECT_THAT(send_command({"exec", "foo", "--", "cmd"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, exec_cmd_double_dash_ok_cmd_arg_with_opts)
{
EXPECT_CALL(mock_daemon, ssh_info(_, _));
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function());
EXPECT_THAT(send_command({"exec", "foo", "--", "cmd", "--foo", "--bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, exec_cmd_double_dash_fails_missing_cmd_arg)
{
EXPECT_THAT(send_command({"exec", "foo", "--"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, exec_cmd_no_double_dash_ok_cmd_arg)
{
EXPECT_CALL(mock_daemon, ssh_info(_, _));
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function());
EXPECT_THAT(send_command({"exec", "foo", "cmd"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, exec_cmd_no_double_dash_ok_multiple_args)
{
EXPECT_CALL(mock_daemon, ssh_info(_, _));
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function());
EXPECT_THAT(send_command({"exec", "foo", "cmd", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, exec_cmd_no_double_dash_fails_cmd_arg_with_opts)
{
EXPECT_THAT(send_command({"exec", "foo", "cmd", "--foo"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, exec_cmd_help_ok)
{
EXPECT_THAT(send_command({"exec", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, exec_cmd_no_double_dash_unknown_option_fails_print_suggested_command)
{
std::stringstream cerr_stream;
EXPECT_THAT(send_command({"exec", "foo", "cmd", "--unknownOption"}, trash_stream, cerr_stream),
Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(
cerr_stream.str(),
HasSubstr("Options to the inner command should come after \"--\", like this:\nmultipass exec <instance> -- "
"<command> <arguments>\n"));
}
TEST_F(Client, exec_cmd_double_dash_unknown_option_fails_does_not_print_suggested_command)
{
std::stringstream cerr_stream;
EXPECT_THAT(send_command({"exec", "foo", "--unknownOption", "--", "cmd"}, trash_stream, cerr_stream),
Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(
cerr_stream.str(),
Not(HasSubstr("Options to the inner command should come after \"--\", like this:\nmultipass exec <instance> -- "
"<command> <arguments>\n")));
}
TEST_F(Client, exec_cmd_no_double_dash_no_unknown_option_fails_does_not_print_suggested_command)
{
std::stringstream cerr_stream;
EXPECT_THAT(send_command({"exec", "foo", "cmd", "--help"}, trash_stream, cerr_stream), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(
cerr_stream.str(),
Not(HasSubstr("Options to the inner command should come after \"--\", like this:\nmultipass exec <instance> -- "
"<command> <arguments>\n")));
}
TEST_F(Client, exec_cmd_starts_instance_if_stopped_or_suspended)
{
const auto instance = "ordinary";
const auto ssh_info_matcher = make_ssh_info_instance_matcher(instance);
const auto start_matcher = make_instance_in_repeated_field_matcher<mp::StartRequest, 1>(instance);
const grpc::Status aborted{grpc::StatusCode::ABORTED, "msg"};
InSequence seq;
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(
WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(ssh_info_matcher, aborted)));
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(start_matcher, ok)));
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(ssh_info_matcher, ok)));
EXPECT_THAT(send_command({"exec", instance, "--no-map-working-directory", "--", "command"}),
Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, exec_cmd_fails_on_other_absent_instance)
{
const auto instance = "ordinary";
const auto instance_matcher = make_ssh_info_instance_matcher(instance);
const grpc::Status notfound{grpc::StatusCode::NOT_FOUND, "msg"};
EXPECT_CALL(mock_daemon, ssh_info)
.WillOnce(
WithArg<1>(check_request_and_return<mp::SSHInfoReply, mp::SSHInfoRequest>(instance_matcher, notfound)));
EXPECT_THAT(send_command({"exec", instance, "--no-map-working-directory", "--", "command"}),
Eq(mp::ReturnCode::CommandFail));
}
mp::SSHInfo make_ssh_info(const std::string& host = "222.222.222.222", int port = 22,
const std::string& priv_key = mpt::fake_key_data, const std::string& username = "user")
{
mp::SSHInfo ssh_info;
ssh_info.set_host(host);
ssh_info.set_port(port);
ssh_info.set_priv_key_base64(priv_key);
ssh_info.set_username(username);
return ssh_info;
}
mp::SSHInfoReply make_fake_ssh_info_response(const std::string& instance_name)
{
mp::SSHInfoReply response;
(*response.mutable_ssh_info())[instance_name] = make_ssh_info();
return response;
}
struct SSHClientReturnTest : Client, WithParamInterface<int>
{
};
TEST_P(SSHClientReturnTest, execCmdWithoutDirWorks)
{
const int failure_code{GetParam()};
REPLACE(ssh_channel_get_exit_status, [&failure_code](auto) { return failure_code; });
std::string instance_name{"instance"};
mp::SSHInfoReply response = make_fake_ssh_info_response(instance_name);
EXPECT_CALL(mock_daemon, ssh_info(_, _))
.WillOnce([&response](grpc::ServerContext* context,
grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
server->Write(response);
return grpc::Status{};
});
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function());
EXPECT_EQ(send_command({"exec", instance_name, "--", "cmd"}), failure_code);
}
TEST_P(SSHClientReturnTest, execCmdWithDirWorks)
{
const int failure_code{GetParam()};
REPLACE(ssh_channel_get_exit_status, [&failure_code](auto) { return failure_code; });
std::string instance_name{"instance"};
mp::SSHInfoReply response = make_fake_ssh_info_response(instance_name);
EXPECT_CALL(mock_daemon, ssh_info(_, _))
.WillOnce([&response](grpc::ServerContext* context,
grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
server->Write(response);
return grpc::Status{};
});
EXPECT_EQ(send_command({"exec", instance_name, "--working-directory", "/home/ubuntu/", "--", "cmd"}), failure_code);
}
INSTANTIATE_TEST_SUITE_P(Client, SSHClientReturnTest, Values(0, -1, 1, 127));
TEST_F(Client, execCmdWithDirPrependsCd)
{
std::string dir{"/home/ubuntu/"};
std::string cmd{"pwd"};
REPLACE(ssh_channel_request_exec, ([&dir, &cmd](ssh_channel, const char* raw_cmd) {
EXPECT_THAT(raw_cmd, StartsWith("cd " + dir));
EXPECT_THAT(raw_cmd, HasSubstr("&&"));
EXPECT_THAT(raw_cmd, EndsWith(cmd)); // This will fail if cmd needs to be escaped.
return SSH_OK;
}));
std::string instance_name{"instance"};
mp::SSHInfoReply response = make_fake_ssh_info_response(instance_name);
EXPECT_CALL(mock_daemon, ssh_info(_, _))
.WillOnce([&response](grpc::ServerContext* context,
grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
server->Write(response);
return grpc::Status{};
});
EXPECT_EQ(send_command({"exec", instance_name, "--working-directory", dir, "--", cmd}), mp::ReturnCode::Ok);
}
TEST_F(Client, execCmdWithDirAndSudoUsesSh)
{
std::string dir{"/root/"};
std::vector<std::string> cmds{"sudo", "pwd"};
std::string cmds_string{cmds[0]};
for (size_t i = 1; i < cmds.size(); ++i)
cmds_string += " " + cmds[i];
REPLACE(ssh_channel_request_exec, ([&dir, &cmds_string](ssh_channel, const char* raw_cmd) {
EXPECT_EQ(raw_cmd, "sudo sh -c cd\\ " + dir + "\\ \\&\\&\\ " + mpu::escape_for_shell(cmds_string));
return SSH_OK;
}));
std::string instance_name{"instance"};
mp::SSHInfoReply response = make_fake_ssh_info_response(instance_name);
EXPECT_CALL(mock_daemon, ssh_info(_, _))
.WillOnce([&response](grpc::ServerContext* context,
grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
server->Write(response);
return grpc::Status{};
});
std::vector<std::string> full_cmdline{"exec", instance_name, "--working-directory", dir, "--"};
for (const auto& c : cmds)
full_cmdline.push_back(c);
EXPECT_EQ(send_command(full_cmdline), mp::ReturnCode::Ok);
}
TEST_F(Client, execCmdFailsIfSshExecThrows)
{
std::string dir{"/home/ubuntu/"};
std::string cmd{"pwd"};
REPLACE(ssh_channel_request_exec, ([](ssh_channel, const char* raw_cmd) {
throw mp::SSHException("some exception");
return SSH_OK;
}));
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
std::string instance_name{"instance"};
mp::SSHInfoReply response = make_fake_ssh_info_response(instance_name);
EXPECT_CALL(mock_daemon, ssh_info(_, _))
.WillOnce([&response](grpc::ServerContext* context,
grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
server->Write(response);
return grpc::Status{};
});
std::stringstream cerr_stream;
EXPECT_EQ(send_command({"exec", instance_name, "--", cmd}, trash_stream, cerr_stream), mp::ReturnCode::CommandFail);
EXPECT_THAT(cerr_stream.str(), HasSubstr("exec failed: some exception\n"));
}
TEST_F(Client, execFailsOnArgumentClash)
{
std::stringstream cerr_stream;
EXPECT_THAT(send_command({"exec", "instance", "--working-directory", "/home/ubuntu/", "--no-map-working-directory",
"--", "cmd"},
trash_stream, cerr_stream),
Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(cerr_stream.str(), Eq("Options --working-directory and --no-map-working-directory clash\n"));
}
// help cli tests
TEST_F(Client, help_cmd_ok_with_valid_single_arg)
{
EXPECT_THAT(send_command({"help", "launch"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, help_cmd_ok_no_args)
{
EXPECT_THAT(send_command({"help"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, help_cmd_fails_with_invalid_arg)
{
EXPECT_THAT(send_command({"help", "foo"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, help_cmd_help_ok)
{
EXPECT_THAT(send_command({"help", "-h"}), Eq(mp::ReturnCode::Ok));
}
// info cli tests
TEST_F(Client, infoCmdOkNoArgs)
{
EXPECT_CALL(mock_daemon, info(_, _));
EXPECT_THAT(send_command({"info"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, info_cmd_ok_with_one_arg)
{
EXPECT_CALL(mock_daemon, info(_, _));
EXPECT_THAT(send_command({"info", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, info_cmd_succeeds_with_multiple_args)
{
EXPECT_CALL(mock_daemon, info(_, _));
EXPECT_THAT(send_command({"info", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, info_cmd_help_ok)
{
EXPECT_THAT(send_command({"info", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, info_cmd_succeeds_with_all)
{
EXPECT_CALL(mock_daemon, info(_, _));
EXPECT_THAT(send_command({"info", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, info_cmd_fails_with_names_and_all)
{
EXPECT_THAT(send_command({"info", "--all", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, infoCmdDoesNotDefaultToNoRuntimeInformationAndSucceeds)
{
const auto info_matcher = Property(&mp::InfoRequest::no_runtime_information, IsFalse());
EXPECT_CALL(mock_daemon, info)
.WillOnce(WithArg<1>(check_request_and_return<mp::InfoReply, mp::InfoRequest>(info_matcher, ok)));
EXPECT_THAT(send_command({"info", "name1", "name2"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, infoCmdSucceedsWithInstanceNamesAndNoRuntimeInformation)
{
const auto info_matcher = Property(&mp::InfoRequest::no_runtime_information, IsTrue());
EXPECT_CALL(mock_daemon, info)
.WillOnce(WithArg<1>(check_request_and_return<mp::InfoReply, mp::InfoRequest>(info_matcher, ok)));
EXPECT_THAT(send_command({"info", "name3", "name4", "--no-runtime-information"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, infoCmdSucceedsWithAllAndNoRuntimeInformation)
{
const auto info_matcher = Property(&mp::InfoRequest::no_runtime_information, IsTrue());
EXPECT_CALL(mock_daemon, info)
.WillOnce(WithArg<1>(check_request_and_return<mp::InfoReply, mp::InfoRequest>(info_matcher, ok)));
EXPECT_THAT(send_command({"info", "name5", "--no-runtime-information"}), Eq(mp::ReturnCode::Ok));
}
// list cli tests
TEST_F(Client, list_cmd_ok_no_args)
{
const auto list_matcher = Property(&mp::ListRequest::request_ipv4, IsTrue());
mp::ListReply reply;
reply.mutable_instance_list();
EXPECT_CALL(mock_daemon, list)
.WillOnce(WithArg<1>(check_request_and_return<mp::ListReply, mp::ListRequest>(list_matcher, ok, reply)));
EXPECT_THAT(send_command({"list"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, list_cmd_fails_with_args)
{
EXPECT_THAT(send_command({"list", "foo"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, list_cmd_help_ok)
{
EXPECT_THAT(send_command({"list", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, list_cmd_no_ipv4_ok)
{
const auto list_matcher = Property(&mp::ListRequest::request_ipv4, IsFalse());
mp::ListReply reply;
reply.mutable_instance_list();
EXPECT_CALL(mock_daemon, list)
.WillOnce(WithArg<1>(check_request_and_return<mp::ListReply, mp::ListRequest>(list_matcher, ok, reply)));
EXPECT_THAT(send_command({"list", "--no-ipv4"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, listCmdFailsWithIpv4AndSnapshots)
{
EXPECT_THAT(send_command({"list", "--no-ipv4", "--snapshots"}), Eq(mp::ReturnCode::CommandLineError));
}
// mount cli tests
// Note: mpt::test_data_path() returns an absolute path
TEST_F(Client, mount_cmd_good_absolute_source_path)
{
EXPECT_CALL(mock_daemon, mount(_, _));
EXPECT_THAT(send_command({"mount", mpt::test_data_path().toStdString(), "test-vm:test"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, mount_cmd_good_relative_source_path)
{
EXPECT_CALL(mock_daemon, mount(_, _));
EXPECT_THAT(send_command({"mount", "..", "test-vm:test"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, mount_cmd_fails_invalid_source_path)
{
EXPECT_THAT(send_command({"mount", mpt::test_data_path_for("foo").toStdString(), "test-vm:test"}),
Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, mount_cmd_good_valid_uid_mappings)
{
EXPECT_CALL(mock_daemon, mount(_, _));
EXPECT_THAT(send_command({"mount", mpt::test_data_path().toStdString(), "-u", "1000:501", "test-vm:test"}),
Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, mount_cmd_good_valid_large_uid_mappings)
{
EXPECT_CALL(mock_daemon, mount(_, _));
EXPECT_THAT(send_command({"mount", mpt::test_data_path().toStdString(), "-u", "218038053:0", "test-vm:test"}),
Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, mount_cmd_fails_invalid_string_uid_mappings)
{
EXPECT_THAT(send_command({"mount", mpt::test_data_path().toStdString(), "-u", "foo:bar", "test-vm:test"}),
Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, mount_cmd_fails_invalid_host_int_uid_mappings)
{
EXPECT_THAT(send_command({"mount", mpt::test_data_path().toStdString(), "-u", "5000000000:0", "test-vm:test"}),
Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, mount_cmd_good_valid_gid_mappings)
{
EXPECT_CALL(mock_daemon, mount(_, _));
EXPECT_THAT(send_command({"mount", mpt::test_data_path().toStdString(), "-g", "1000:501", "test-vm:test"}),
Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, mount_cmd_good_valid_large_gid_mappings)
{
EXPECT_CALL(mock_daemon, mount(_, _));
EXPECT_THAT(send_command({"mount", mpt::test_data_path().toStdString(), "-g", "218038053:0", "test-vm:test"}),
Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, mount_cmd_fails_invalid_string_gid_mappings)
{
EXPECT_THAT(send_command({"mount", mpt::test_data_path().toStdString(), "-g", "foo:bar", "test-vm:test"}),
Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, mount_cmd_fails_invalid_host_int_gid_mappings)
{
EXPECT_THAT(send_command({"mount", mpt::test_data_path().toStdString(), "-g", "5000000000:0", "test-vm:test"}),
Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, mountCmdGoodClassicMountType)
{
EXPECT_CALL(mock_daemon, mount(_, _));
EXPECT_EQ(send_command({"mount", "-t", "classic", mpt::test_data_path().toStdString(), "test-vm:test"}),
mp::ReturnCode::Ok);
}
TEST_F(Client, mountCmdGoodNativeMountType)
{
EXPECT_CALL(mock_daemon, mount(_, _));
EXPECT_EQ(send_command({"mount", "-t", "native", mpt::test_data_path().toStdString(), "test-vm:test"}),
mp::ReturnCode::Ok);
}
TEST_F(Client, mountCmdFailsBogusMountType)
{
EXPECT_EQ(send_command({"mount", "-t", "bogus", mpt::test_data_path().toStdString(), "test-vm:test"}),
mp::ReturnCode::CommandLineError);
}
// recover cli tests
TEST_F(Client, recover_cmd_fails_no_args)
{
EXPECT_THAT(send_command({"recover"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, recover_cmd_ok_with_one_arg)
{
EXPECT_CALL(mock_daemon, recover(_, _));
EXPECT_THAT(send_command({"recover", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, recover_cmd_succeeds_with_multiple_args)
{
EXPECT_CALL(mock_daemon, recover(_, _));
EXPECT_THAT(send_command({"recover", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, recover_cmd_help_ok)
{
EXPECT_THAT(send_command({"recover", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, recover_cmd_succeeds_with_all)
{
EXPECT_CALL(mock_daemon, recover(_, _));
EXPECT_THAT(send_command({"recover", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, recover_cmd_fails_with_names_and_all)
{
EXPECT_THAT(send_command({"recover", "--all", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
// start cli tests
TEST_F(Client, start_cmd_ok_with_one_arg)
{
EXPECT_CALL(mock_daemon, start(_, _));
EXPECT_THAT(send_command({"start", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_succeeds_with_multiple_args)
{
EXPECT_CALL(mock_daemon, start(_, _));
EXPECT_THAT(send_command({"start", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_help_ok)
{
EXPECT_THAT(send_command({"start", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_succeeds_with_all)
{
EXPECT_CALL(mock_daemon, start(_, _));
EXPECT_THAT(send_command({"start", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_fails_with_names_and_all)
{
EXPECT_THAT(send_command({"start", "--all", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, start_cmd_no_args_targets_petenv)
{
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::StartRequest, 1>(petenv_name);
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"start"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_considers_configured_petenv)
{
const auto custom_petenv = "jarjar binks";
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(custom_petenv));
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::StartRequest, 1>(custom_petenv);
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"start"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_can_target_petenv_explicitly)
{
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::StartRequest, 1>(petenv_name);
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"start", petenv_name}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_can_target_petenv_among_others)
{
const auto petenv_matcher2 = make_instance_in_repeated_field_matcher<mp::StartRequest, 2>(petenv_name);
const auto petenv_matcher4 = make_instance_in_repeated_field_matcher<mp::StartRequest, 4>(petenv_name);
InSequence s;
EXPECT_CALL(mock_daemon, start(_, _));
EXPECT_CALL(mock_daemon, start)
.Times(2)
.WillRepeatedly(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(petenv_matcher2, ok)));
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(petenv_matcher4, ok)));
EXPECT_THAT(send_command({"start", "primary"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"start", "foo", petenv_name}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"start", petenv_name, "bar"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"start", "foo", petenv_name, "bar", "baz"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_disabled_petenv)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, start(_, _));
EXPECT_THAT(send_command({"start", "foo"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"start"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, start_cmd_disabled_petenv_all)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, start(_, _));
EXPECT_THAT(send_command({"start", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_disabled_petenv_help)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, start(_, _)).Times(0);
EXPECT_THAT(send_command({"start", "-h"}), Eq(mp::ReturnCode::Ok));
}
// version cli tests
TEST_F(Client, version_without_arg)
{
EXPECT_CALL(mock_daemon, version(_, _));
EXPECT_THAT(send_command({"version"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, version_with_positional_format_arg)
{
EXPECT_THAT(send_command({"version", "format"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, version_with_option_format_arg)
{
EXPECT_CALL(mock_daemon, version(_, _)).Times(4);
EXPECT_THAT(send_command({"version", "--format=table"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"version", "--format=yaml"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"version", "--format=json"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"version", "--format=csv"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, version_with_option_format_invalid_arg)
{
EXPECT_THAT(send_command({"version", "--format=default"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"version", "--format=MumboJumbo"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, version_parse_failure)
{
EXPECT_THAT(send_command({"version", "--format"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, version_info_on_failure)
{
const grpc::Status notfound{grpc::StatusCode::NOT_FOUND, "msg"};
EXPECT_CALL(mock_daemon, version(_, _)).WillOnce(Return(notfound));
EXPECT_THAT(send_command({"version", "--format=yaml"}), Eq(mp::ReturnCode::Ok));
}
grpc::Status aborted_start_status(const std::vector<std::string>& absent_instances = {},
const std::vector<std::string>& deleted_instances = {})
{
mp::StartError start_error{};
auto* errors = start_error.mutable_instance_errors();
for (const auto& instance : absent_instances)
errors->insert({instance, mp::StartError::DOES_NOT_EXIST});
for (const auto& instance : deleted_instances)
errors->insert({instance, mp::StartError::INSTANCE_DELETED});
return {grpc::StatusCode::ABORTED, "fakemsg", start_error.SerializeAsString()};
}
std::vector<std::string> concat(const std::vector<std::string>& v1, const std::vector<std::string>& v2)
{
auto ret = v1;
ret.insert(end(ret), cbegin(v2), cend(v2));
return ret;
}
TEST_F(Client, start_cmd_launches_petenv_if_absent)
{
const auto petenv_start_matcher = make_instance_in_repeated_field_matcher<mp::StartRequest, 1>(petenv_name);
const auto petenv_launch_matcher = make_launch_instance_matcher(petenv_name);
const grpc::Status aborted = aborted_start_status({petenv_name});
EXPECT_CALL(mock_daemon, mount).WillRepeatedly(Return(ok)); // 0 or more times
InSequence seq;
EXPECT_CALL(mock_daemon, start)
.WillOnce(
WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(petenv_start_matcher, aborted)));
EXPECT_CALL(mock_daemon, launch)
.WillOnce(WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(petenv_launch_matcher, ok)));
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(petenv_start_matcher, ok)));
EXPECT_THAT(send_command({"start", petenv_name}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_automounts_when_launching_petenv)
{
const grpc::Status aborted = aborted_start_status({petenv_name});
InSequence seq;
EXPECT_CALL(mock_daemon, start(_, _)).WillOnce(Return(aborted));
EXPECT_CALL(mock_daemon, launch(_, _)).WillOnce(Return(ok));
EXPECT_CALL(mock_daemon, mount(_, _)).WillOnce(Return(ok));
EXPECT_CALL(mock_daemon, start(_, _)).WillOnce(Return(ok));
EXPECT_THAT(send_command({"start", petenv_name}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, startCmdSkipsAutomountWhenDisabled)
{
std::stringstream cout_stream;
const grpc::Status aborted = aborted_start_status({petenv_name});
InSequence seq;
EXPECT_CALL(mock_daemon, start(_, _)).WillOnce(Return(aborted));
EXPECT_CALL(mock_daemon, launch(_, _)).WillOnce(Return(ok));
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillOnce(Return("false"));
EXPECT_CALL(mock_daemon, mount(_, _)).Times(0);
EXPECT_CALL(mock_daemon, start(_, _)).WillOnce(Return(ok));
EXPECT_THAT(send_command({"start", petenv_name}, cout_stream), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(cout_stream.str(), HasSubstr("Skipping mount due to disabled mounts feature\n"));
}
TEST_F(Client, start_cmd_forwards_verbosity_to_subcommands)
{
const grpc::Status aborted = aborted_start_status({petenv_name});
const auto verbosity = 2;
const auto start_verbosity_matcher = make_request_verbosity_matcher<mp::StartRequest>(verbosity);
const auto launch_verbosity_matcher = make_request_verbosity_matcher<mp::LaunchRequest>(verbosity);
const auto mount_verbosity_matcher = make_request_verbosity_matcher<mp::MountRequest>(verbosity);
InSequence seq;
EXPECT_CALL(mock_daemon, start)
.WillOnce(
WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(start_verbosity_matcher, aborted)));
EXPECT_CALL(mock_daemon, launch)
.WillOnce(
WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(launch_verbosity_matcher, ok)));
EXPECT_CALL(mock_daemon, mount)
.WillOnce(WithArg<1>(check_request_and_return<mp::MountReply, mp::MountRequest>(mount_verbosity_matcher, ok)));
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(start_verbosity_matcher, ok)));
EXPECT_THAT(send_command({"start", "-vv"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_forwards_timeout_to_subcommands)
{
const grpc::Status aborted = aborted_start_status({petenv_name});
const auto timeout = 123;
const auto start_timeout_matcher = make_request_timeout_matcher<mp::StartRequest>(timeout);
const auto launch_timeout_matcher = make_request_timeout_matcher<mp::LaunchRequest>(timeout);
InSequence seq;
EXPECT_CALL(mock_daemon, start)
.WillOnce(
WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(start_timeout_matcher, aborted)));
EXPECT_CALL(mock_daemon, launch)
.WillOnce(WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(launch_timeout_matcher, ok)));
EXPECT_CALL(mock_daemon, mount).WillOnce(Return(ok));
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(start_timeout_matcher, ok)));
EXPECT_THAT(send_command({"start", "--timeout", std::to_string(timeout)}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, startCmdFailsWhenUnableToRetrieveAutomountSetting)
{
const auto aborted = aborted_start_status({petenv_name});
const auto except = mp::RemoteHandlerException{grpc::Status{grpc::StatusCode::INTERNAL, "oops"}};
InSequence seq;
EXPECT_CALL(mock_daemon, start).WillOnce(Return(aborted));
EXPECT_CALL(mock_daemon, launch).WillOnce(Return(ok));
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillOnce(Throw(except));
EXPECT_CALL(mock_daemon, mount).Times(0);
EXPECT_THAT(send_command({"start", petenv_name}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, start_cmd_fails_when_automounting_in_petenv_fails)
{
const auto aborted = aborted_start_status({petenv_name});
const auto mount_failure = grpc::Status{grpc::StatusCode::INVALID_ARGUMENT, "msg"};
InSequence seq;
EXPECT_CALL(mock_daemon, start(_, _)).WillOnce(Return(aborted));
EXPECT_CALL(mock_daemon, launch(_, _)).WillOnce(Return(ok));
EXPECT_CALL(mock_daemon, mount(_, _)).WillOnce(Return(mount_failure));
EXPECT_THAT(send_command({"start", petenv_name}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, start_cmd_launches_petenv_if_absent_among_others_present)
{
std::vector<std::string> instances{"a", "b", petenv_name, "c"}, cmd = concat({"start"}, instances);
const auto instance_start_matcher = make_instances_sequence_matcher<mp::StartRequest>(instances);
const auto petenv_launch_matcher = make_launch_instance_matcher(petenv_name);
const grpc::Status aborted = aborted_start_status({petenv_name});
EXPECT_CALL(mock_daemon, mount).WillRepeatedly(Return(ok)); // 0 or more times
InSequence seq;
EXPECT_CALL(mock_daemon, start)
.WillOnce(
WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(instance_start_matcher, aborted)));
EXPECT_CALL(mock_daemon, launch)
.WillOnce(WithArg<1>(check_request_and_return<mp::LaunchReply, mp::LaunchRequest>(petenv_launch_matcher, ok)));
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(instance_start_matcher, ok)));
EXPECT_THAT(send_command(cmd), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_fails_if_petenv_if_absent_amount_others_absent)
{
std::vector<std::string> instances{"a", "b", "c", petenv_name, "xyz"}, cmd = concat({"start"}, instances);
const auto instance_start_matcher = make_instances_sequence_matcher<mp::StartRequest>(instances);
const auto aborted = aborted_start_status({std::next(std::cbegin(instances), 2), std::cend(instances)});
EXPECT_CALL(mock_daemon, start)
.WillOnce(
WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(instance_start_matcher, aborted)));
EXPECT_THAT(send_command(cmd), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, start_cmd_fails_if_petenv_if_absent_amount_others_deleted)
{
std::vector<std::string> instances{"nope", petenv_name}, cmd = concat({"start"}, instances);
const auto instance_start_matcher = make_instances_sequence_matcher<mp::StartRequest>(instances);
const auto aborted = aborted_start_status({}, {instances.front()});
EXPECT_CALL(mock_daemon, start)
.WillOnce(
WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(instance_start_matcher, aborted)));
EXPECT_THAT(send_command(cmd), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, start_cmd_fails_if_petenv_present_but_deleted)
{
const auto petenv_start_matcher = make_instance_in_repeated_field_matcher<mp::StartRequest, 1>(petenv_name);
const grpc::Status aborted = aborted_start_status({}, {petenv_name});
InSequence seq;
EXPECT_CALL(mock_daemon, start)
.WillOnce(
WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(petenv_start_matcher, aborted)));
EXPECT_THAT(send_command({"start", petenv_name}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, start_cmd_fails_if_petenv_present_but_deleted_among_others)
{
std::vector<std::string> instances{petenv_name, "other"}, cmd = concat({"start"}, instances);
const auto instance_start_matcher = make_instances_sequence_matcher<mp::StartRequest>(instances);
const auto aborted = aborted_start_status({}, {instances.front()});
EXPECT_CALL(mock_daemon, start)
.WillOnce(
WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(instance_start_matcher, aborted)));
EXPECT_THAT(send_command(cmd), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, start_cmd_fails_on_other_absent_instance)
{
std::vector<std::string> instances{"o-o", "O_o"}, cmd = concat({"start"}, instances);
const auto instance_start_matcher = make_instances_sequence_matcher<mp::StartRequest>(instances);
const auto aborted = aborted_start_status({}, {"O_o"});
EXPECT_CALL(mock_daemon, start)
.WillOnce(
WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(instance_start_matcher, aborted)));
EXPECT_THAT(send_command(cmd), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, start_cmd_fails_on_other_absent_instances_with_petenv)
{
std::vector<std::string> cmd{"start"}, instances{petenv_name, "lala", "zzz"};
cmd.insert(end(cmd), cbegin(instances), cend(instances));
const auto instance_start_matcher = make_instances_sequence_matcher<mp::StartRequest>(instances);
const auto aborted = aborted_start_status({}, {"zzz"});
EXPECT_CALL(mock_daemon, start)
.WillOnce(
WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(instance_start_matcher, aborted)));
EXPECT_THAT(send_command(cmd), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, start_cmd_does_not_add_petenv_to_others)
{
const auto matcher = make_instances_matcher<mp::StartRequest>(ElementsAre(StrEq("foo"), StrEq("bar")));
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(matcher, ok)));
EXPECT_THAT(send_command({"start", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, start_cmd_does_not_add_petenv_to_all)
{
const auto matcher = make_instances_matcher<mp::StartRequest>(IsEmpty());
EXPECT_CALL(mock_daemon, start)
.WillOnce(WithArg<1>(check_request_and_return<mp::StartReply, mp::StartRequest>(matcher, ok)));
EXPECT_THAT(send_command({"start", "--all"}), Eq(mp::ReturnCode::Ok));
}
// stop cli tests
TEST_F(Client, stop_cmd_ok_with_one_arg)
{
EXPECT_CALL(mock_daemon, stop(_, _));
EXPECT_THAT(send_command({"stop", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_succeeds_with_multiple_args)
{
EXPECT_CALL(mock_daemon, stop(_, _));
EXPECT_THAT(send_command({"stop", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_help_ok)
{
EXPECT_THAT(send_command({"stop", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_succeeds_with_all)
{
EXPECT_CALL(mock_daemon, stop(_, _));
EXPECT_THAT(send_command({"stop", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_fails_with_names_and_all)
{
EXPECT_THAT(send_command({"stop", "--all", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, stop_cmd_no_args_targets_petenv)
{
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::StopRequest, 1>(petenv_name);
EXPECT_CALL(mock_daemon, stop)
.WillOnce(WithArg<1>(check_request_and_return<mp::StopReply, mp::StopRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"stop"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_considers_configured_petenv)
{
const auto custom_petenv = "jarjar binks";
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(custom_petenv));
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::StopRequest, 1>(custom_petenv);
EXPECT_CALL(mock_daemon, stop)
.WillOnce(WithArg<1>(check_request_and_return<mp::StopReply, mp::StopRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"stop"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_can_target_petenv_explicitly)
{
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::StopRequest, 1>(petenv_name);
EXPECT_CALL(mock_daemon, stop)
.WillOnce(WithArg<1>(check_request_and_return<mp::StopReply, mp::StopRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"stop", petenv_name}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_can_target_petenv_among_others)
{
const auto petenv_matcher2 = make_instance_in_repeated_field_matcher<mp::StopRequest, 2>(petenv_name);
const auto petenv_matcher4 = make_instance_in_repeated_field_matcher<mp::StopRequest, 4>(petenv_name);
InSequence s;
EXPECT_CALL(mock_daemon, stop(_, _));
EXPECT_CALL(mock_daemon, stop)
.Times(2)
.WillRepeatedly(WithArg<1>(check_request_and_return<mp::StopReply, mp::StopRequest>(petenv_matcher2, ok)));
EXPECT_CALL(mock_daemon, stop)
.WillOnce(WithArg<1>(check_request_and_return<mp::StopReply, mp::StopRequest>(petenv_matcher4, ok)));
EXPECT_THAT(send_command({"stop", "primary"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"stop", "foo", petenv_name}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"stop", petenv_name, "bar"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"stop", "foo", petenv_name, "bar", "baz"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_does_not_add_petenv_to_others)
{
const auto matcher = make_instances_matcher<mp::StopRequest>(ElementsAre(StrEq("foo"), StrEq("bar")));
EXPECT_CALL(mock_daemon, stop)
.WillOnce(WithArg<1>(check_request_and_return<mp::StopReply, mp::StopRequest>(matcher, ok)));
EXPECT_THAT(send_command({"stop", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_does_not_add_petenv_to_all)
{
const auto matcher = make_instances_matcher<mp::StopRequest>(IsEmpty());
EXPECT_CALL(mock_daemon, stop)
.WillOnce(WithArg<1>(check_request_and_return<mp::StopReply, mp::StopRequest>(matcher, ok)));
EXPECT_THAT(send_command({"stop", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_fails_with_time_and_cancel)
{
EXPECT_THAT(send_command({"stop", "--time", "+10", "--cancel", "foo"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, stop_cmd_succeeds_with_plus_time)
{
EXPECT_CALL(mock_daemon, stop(_, _));
EXPECT_THAT(send_command({"stop", "foo", "--time", "+10"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_succeeds_with_no_plus_time)
{
EXPECT_CALL(mock_daemon, stop(_, _));
EXPECT_THAT(send_command({"stop", "foo", "--time", "10"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_fails_with_invalid_time_prefix)
{
EXPECT_THAT(send_command({"stop", "foo", "--time", "-10"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, stop_cmd_fails_with_invalid_time)
{
EXPECT_THAT(send_command({"stop", "foo", "--time", "+bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, stop_cmd_fails_with_time_suffix)
{
EXPECT_THAT(send_command({"stop", "foo", "--time", "+10s"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, stop_cmd_succeeds_with_cancel)
{
EXPECT_CALL(mock_daemon, stop(_, _));
EXPECT_THAT(send_command({"stop", "foo", "--cancel"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_no_args_time_option_delays_petenv_shutdown)
{
const auto delay = 5;
const auto matcher = AllOf(make_instance_in_repeated_field_matcher<mp::StopRequest, 1>(petenv_name),
Property(&mp::StopRequest::time_minutes, delay));
EXPECT_CALL(mock_daemon, stop)
.WillOnce(WithArg<1>(check_request_and_return<mp::StopReply, mp::StopRequest>(matcher, ok)));
EXPECT_THAT(send_command({"stop", "--time", std::to_string(delay)}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_no_args_cancel_option_cancels_delayed_petenv_shutdown)
{
const auto matcher = AllOf(make_instance_in_repeated_field_matcher<mp::StopRequest, 1>(petenv_name),
Property(&mp::StopRequest::cancel_shutdown, true));
EXPECT_CALL(mock_daemon, stop)
.WillOnce(WithArg<1>(check_request_and_return<mp::StopReply, mp::StopRequest>(matcher, ok)));
EXPECT_THAT(send_command({"stop", "--cancel"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_no_args_fails_with_time_and_cancel)
{
EXPECT_THAT(send_command({"stop", "--time", "+10", "--cancel"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, stop_cmd_disabled_petenv)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_THAT(send_command({"stop"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"stop", "--cancel"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"stop", "--time", "10"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, stop_cmd_disabled_petenv_with_instance)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, stop(_, _));
EXPECT_THAT(send_command({"stop"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"stop", "foo"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"stop", "--cancel"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"stop", "--time", "10"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, stop_cmd_disabled_petenv_help)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_THAT(send_command({"stop", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_disabled_petenv_all)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, stop(_, _));
EXPECT_THAT(send_command({"stop", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_force_sends_proper_request)
{
const auto force_set_matcher = Property(&mp::StopRequest::force_stop, IsTrue());
EXPECT_CALL(mock_daemon, stop)
.WillOnce(WithArg<1>(check_request_and_return<mp::StopReply, mp::StopRequest>(force_set_matcher, ok)));
EXPECT_THAT(send_command({"stop", "foo", "--force"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, stop_cmd_force_conflicts_with_time_option)
{
EXPECT_THAT(send_command({"stop", "foo", "--force", "--time", "10"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, stop_cmd_force_conflicts_with_cancel_option)
{
EXPECT_THAT(send_command({"stop", "foo", "--force", "--cancel"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, stopCmdWrongVmState)
{
const auto invalid_vm_state_failure = grpc::Status{grpc::StatusCode::INVALID_ARGUMENT, "msg"};
EXPECT_CALL(mock_daemon, stop(_, _)).WillOnce(Return(invalid_vm_state_failure));
EXPECT_THAT(send_command({"stop", "foo"}), Eq(mp::ReturnCode::CommandFail));
}
// suspend cli tests
TEST_F(Client, suspend_cmd_ok_with_one_arg)
{
EXPECT_CALL(mock_daemon, suspend(_, _)).Times(2);
EXPECT_THAT(send_command({"suspend", "foo"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"suspend", "primary"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_succeeds_with_multiple_args)
{
EXPECT_CALL(mock_daemon, suspend(_, _));
EXPECT_THAT(send_command({"suspend", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_help_ok)
{
EXPECT_THAT(send_command({"suspend", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_succeeds_with_all)
{
EXPECT_CALL(mock_daemon, suspend(_, _));
EXPECT_THAT(send_command({"suspend", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_no_args_targets_petenv)
{
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::SuspendRequest, 1>(petenv_name);
EXPECT_CALL(mock_daemon, suspend)
.WillOnce(WithArg<1>(check_request_and_return<mp::SuspendReply, mp::SuspendRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"suspend"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_considers_configured_petenv)
{
const auto custom_petenv = "jarjar binks";
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(custom_petenv));
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::SuspendRequest, 1>(custom_petenv);
EXPECT_CALL(mock_daemon, suspend)
.WillOnce(WithArg<1>(check_request_and_return<mp::SuspendReply, mp::SuspendRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"suspend"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_can_target_petenv_explicitly)
{
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::SuspendRequest, 1>(petenv_name);
EXPECT_CALL(mock_daemon, suspend)
.WillOnce(WithArg<1>(check_request_and_return<mp::SuspendReply, mp::SuspendRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"suspend", petenv_name}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_can_target_petenv_among_others)
{
const auto petenv_matcher2 = make_instance_in_repeated_field_matcher<mp::SuspendRequest, 2>(petenv_name);
const auto petenv_matcher4 = make_instance_in_repeated_field_matcher<mp::SuspendRequest, 4>(petenv_name);
InSequence s;
EXPECT_CALL(mock_daemon, suspend)
.Times(2)
.WillRepeatedly(
WithArg<1>(check_request_and_return<mp::SuspendReply, mp::SuspendRequest>(petenv_matcher2, ok)));
EXPECT_CALL(mock_daemon, suspend)
.WillOnce(WithArg<1>(check_request_and_return<mp::SuspendReply, mp::SuspendRequest>(petenv_matcher4, ok)));
EXPECT_THAT(send_command({"suspend", "foo", petenv_name}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"suspend", petenv_name, "bar"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"suspend", "foo", petenv_name, "bar", "baz"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_does_not_add_petenv_to_others)
{
const auto matcher = make_instances_matcher<mp::SuspendRequest>(ElementsAre(StrEq("foo"), StrEq("bar")));
EXPECT_CALL(mock_daemon, suspend)
.WillOnce(WithArg<1>(check_request_and_return<mp::SuspendReply, mp::SuspendRequest>(matcher, ok)));
EXPECT_THAT(send_command({"suspend", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_does_not_add_petenv_to_all)
{
const auto matcher = make_instances_matcher<mp::SuspendRequest>(IsEmpty());
EXPECT_CALL(mock_daemon, suspend)
.WillOnce(WithArg<1>(check_request_and_return<mp::SuspendReply, mp::SuspendRequest>(matcher, ok)));
EXPECT_THAT(send_command({"suspend", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_fails_with_names_and_all)
{
EXPECT_THAT(send_command({"suspend", "--all", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, suspend_cmd_disabled_petenv)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, suspend(_, _));
EXPECT_THAT(send_command({"suspend"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"suspend", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_disabled_petenv_help)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_THAT(send_command({"suspend", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, suspend_cmd_disabled_petenv_all)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, suspend(_, _));
EXPECT_THAT(send_command({"suspend", "--all"}), Eq(mp::ReturnCode::Ok));
}
// restart cli tests
TEST_F(Client, restart_cmd_ok_with_one_arg)
{
EXPECT_CALL(mock_daemon, restart(_, _)).Times(2);
EXPECT_THAT(send_command({"restart", "foo"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"restart", "primary"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_succeeds_with_multiple_args)
{
EXPECT_CALL(mock_daemon, restart(_, _));
EXPECT_THAT(send_command({"restart", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_help_ok)
{
EXPECT_THAT(send_command({"restart", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_succeeds_with_all)
{
EXPECT_CALL(mock_daemon, restart(_, _));
EXPECT_THAT(send_command({"restart", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_no_args_targets_petenv)
{
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::RestartRequest, 1>(petenv_name);
EXPECT_CALL(mock_daemon, restart)
.WillOnce(WithArg<1>(check_request_and_return<mp::RestartReply, mp::RestartRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"restart"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_considers_configured_petenv)
{
const auto custom_petenv = "jarjar binks";
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(custom_petenv));
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::RestartRequest, 1>(custom_petenv);
EXPECT_CALL(mock_daemon, restart)
.WillOnce(WithArg<1>(check_request_and_return<mp::RestartReply, mp::RestartRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"restart"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_can_target_petenv_explicitly)
{
const auto petenv_matcher = make_instance_in_repeated_field_matcher<mp::RestartRequest, 1>(petenv_name);
EXPECT_CALL(mock_daemon, restart)
.WillOnce(WithArg<1>(check_request_and_return<mp::RestartReply, mp::RestartRequest>(petenv_matcher, ok)));
EXPECT_THAT(send_command({"restart", petenv_name}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_can_target_petenv_among_others)
{
const auto petenv_matcher2 = make_instance_in_repeated_field_matcher<mp::RestartRequest, 2>(petenv_name);
const auto petenv_matcher4 = make_instance_in_repeated_field_matcher<mp::RestartRequest, 4>(petenv_name);
InSequence s;
EXPECT_CALL(mock_daemon, restart)
.Times(2)
.WillRepeatedly(
WithArg<1>(check_request_and_return<mp::RestartReply, mp::RestartRequest>(petenv_matcher2, ok)));
EXPECT_CALL(mock_daemon, restart)
.WillOnce(WithArg<1>(check_request_and_return<mp::RestartReply, mp::RestartRequest>(petenv_matcher4, ok)));
EXPECT_THAT(send_command({"restart", "foo", petenv_name}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"restart", petenv_name, "bar"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"restart", "foo", petenv_name, "bar", "baz"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_does_not_add_petenv_to_others)
{
const auto matcher = make_instances_matcher<mp::RestartRequest>(ElementsAre(StrEq("foo"), StrEq("bar")));
EXPECT_CALL(mock_daemon, restart)
.WillOnce(WithArg<1>(check_request_and_return<mp::RestartReply, mp::RestartRequest>(matcher, ok)));
EXPECT_THAT(send_command({"restart", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_does_not_add_petenv_to_all)
{
const auto matcher = make_instances_matcher<mp::RestartRequest>(IsEmpty());
EXPECT_CALL(mock_daemon, restart)
.WillOnce(WithArg<1>(check_request_and_return<mp::RestartReply, mp::RestartRequest>(matcher, ok)));
EXPECT_THAT(send_command({"restart", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_fails_with_names_and_all)
{
EXPECT_THAT(send_command({"restart", "--all", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, restart_cmd_fails_with_unknown_options)
{
EXPECT_THAT(send_command({"restart", "-x", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"restart", "-wrong", "--all"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"restart", "-h", "--nope", "not"}), Eq(mp::ReturnCode::CommandLineError));
// Options that would be accepted by stop
EXPECT_THAT(send_command({"restart", "-t", "foo"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"restart", "-t0", "bar"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"restart", "--time", "42", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"restart", "-c", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"restart", "--cancel", "foo"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, restart_cmd_fails_if_petenv_nonexistent)
{
const auto petenv_start_matcher = make_instance_in_repeated_field_matcher<mp::RestartRequest, 1>(petenv_name);
const grpc::Status aborted = aborted_start_status({}, {petenv_name});
InSequence seq;
EXPECT_CALL(mock_daemon, restart)
.WillOnce(
WithArg<1>(check_request_and_return<mp::RestartReply, mp::RestartRequest>(petenv_start_matcher, aborted)));
EXPECT_THAT(send_command({"restart"}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, restart_cmd_disabled_petenv)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, restart(_, _));
EXPECT_THAT(send_command({"restart"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"restart", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_disabled_petenv_help)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_THAT(send_command({"restart", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, restart_cmd_disabled_petenv_all)
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(""));
EXPECT_CALL(mock_daemon, restart(_, _));
EXPECT_THAT(send_command({"restart", "--all"}), Eq(mp::ReturnCode::Ok));
}
// delete cli tests
TEST_F(Client, delete_cmd_fails_no_args)
{
EXPECT_THAT(send_command({"delete"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, delete_cmd_ok_with_one_arg)
{
EXPECT_CALL(mock_daemon, delet(_, _));
EXPECT_THAT(send_command({"delete", "foo"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, delete_cmd_succeeds_with_multiple_args)
{
EXPECT_CALL(mock_daemon, delet(_, _));
EXPECT_THAT(send_command({"delete", "foo", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, delete_cmd_help_ok)
{
EXPECT_THAT(send_command({"delete", "-h"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, delete_cmd_succeeds_with_all)
{
EXPECT_CALL(mock_daemon, delet(_, _));
EXPECT_THAT(send_command({"delete", "--all"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, delete_cmd_fails_with_names_and_all)
{
EXPECT_THAT(send_command({"delete", "--all", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, delete_cmd_accepts_purge_option)
{
EXPECT_CALL(mock_daemon, delet(_, _)).Times(2);
EXPECT_THAT(send_command({"delete", "--purge", "foo"}), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(send_command({"delete", "-p", "bar"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, deleteCmdWrongVmState)
{
const auto invalid_vm_state_failure = grpc::Status{grpc::StatusCode::INVALID_ARGUMENT, "msg"};
EXPECT_CALL(mock_daemon, delet(_, _)).WillOnce(Return(invalid_vm_state_failure));
EXPECT_THAT(send_command({"delete", "foo"}), Eq(mp::ReturnCode::CommandFail));
}
// find cli tests
TEST_F(Client, findCmdUnsupportedOptionOk)
{
EXPECT_CALL(mock_daemon, find(_, _));
EXPECT_THAT(send_command({"find", "--show-unsupported"}), Eq(mp::ReturnCode::Ok));
}
TEST_F(Client, findCmdForceUpdateOk)
{
EXPECT_CALL(mock_daemon, find(_, _));
EXPECT_EQ(send_command({"find", "--force-update"}), mp::ReturnCode::Ok);
}
TEST_F(Client, findCmdForceUpdateAndOnlyImagesOk)
{
EXPECT_CALL(mock_daemon, find(_, _));
EXPECT_EQ(send_command({"find", "--force-update", "--only-images"}), mp::ReturnCode::Ok);
}
TEST_F(Client, findCmdForceUpdateAndOnlyBlueprintsError)
{
EXPECT_EQ(send_command({"find", "--force-update", "--only-blueprints"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, findCmdForceUpdateWithRemoteOk)
{
EXPECT_CALL(mock_daemon, find(_, _));
EXPECT_EQ(send_command({"find", "foo:", "--force-update"}), mp::ReturnCode::Ok);
}
TEST_F(Client, findCmdForceUpdateWithRemoteAndSearchNameOk)
{
EXPECT_CALL(mock_daemon, find(_, _));
EXPECT_EQ(send_command({"find", "foo:bar", "--force-update"}), mp::ReturnCode::Ok);
}
TEST_F(Client, findCmdFailsOnMultipleConditions)
{
EXPECT_THAT(send_command({"find"
"--only-blueprints",
"--only-images"}),
Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, findCmdTooManyArgsFails)
{
EXPECT_THAT(send_command({"find", "foo", "bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, findCmdMultipleColonsFails)
{
EXPECT_THAT(send_command({"find", "foo::bar"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, findCmdHelpOk)
{
EXPECT_THAT(send_command({"find", "-h"}), Eq(mp::ReturnCode::Ok));
}
// get/set cli tests
struct TestGetSetHelp : Client, WithParamInterface<std::string>
{
};
TEST_P(TestGetSetHelp, helpIncludesKeyExamplesAndHowToGetFullList)
{
std::ostringstream cout;
EXPECT_THAT(send_command({GetParam(), "--help"}, cout), Eq(mp::ReturnCode::Ok));
EXPECT_THAT(cout.str(), AllOf(HasSubstr("local."), HasSubstr("client."), HasSubstr("get --keys")));
}
INSTANTIATE_TEST_SUITE_P(Client, TestGetSetHelp, Values("get", "set"));
struct TestBasicGetSetOptions : Client, WithParamInterface<const char*>
{
};
TEST_P(TestBasicGetSetOptions, get_can_read_settings)
{
const auto& key = GetParam();
const auto value = "a value";
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Return(value));
EXPECT_THAT(get_setting(key), Eq(value));
}
TEST_P(TestBasicGetSetOptions, set_can_write_settings)
{
const auto& key = GetParam();
const auto val = "blah";
EXPECT_CALL(mock_settings, set(Eq(key), Eq(val)));
EXPECT_THAT(send_command({"set", keyval_arg(key, val)}), Eq(mp::ReturnCode::Ok));
}
TEST_P(TestBasicGetSetOptions, set_cmd_allows_empty_val)
{
const auto& key = GetParam();
const auto val = "";
EXPECT_CALL(mock_settings, set(Eq(key), Eq(val)));
EXPECT_THAT(send_command({"set", keyval_arg(key, val)}), Eq(mp::ReturnCode::Ok));
}
TEST_P(TestBasicGetSetOptions, InteractiveSetWritesSettings)
{
const auto& key = GetParam();
const auto val = "blah";
std::istringstream cin{fmt::format("{}\n", val)};
EXPECT_CALL(mock_settings, set(Eq(key), Eq(val)));
EXPECT_THAT(send_command({"set", key}, trash_stream, trash_stream, cin), Eq(mp::ReturnCode::Ok));
}
INSTANTIATE_TEST_SUITE_P(
Client,
TestBasicGetSetOptions,
Values(mp::petenv_key, mp::driver_key, mp::bridged_interface_key, mp::mounts_key, "anything.else.really"));
TEST_F(Client, get_returns_setting)
{
const auto key = "sigur", val = "ros";
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Return(val));
EXPECT_THAT(get_setting(key), Eq(val));
}
TEST_F(Client, get_cmd_fails_with_no_arguments)
{
EXPECT_THAT(send_command({"get"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, set_cmd_fails_with_no_arguments)
{
EXPECT_CALL(mock_settings, set(_, _)).Times(0);
EXPECT_THAT(send_command({"set"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, get_cmd_fails_with_multiple_arguments)
{
EXPECT_THAT(send_command({"get", mp::petenv_key, mp::driver_key}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, set_cmd_fails_with_multiple_arguments)
{
EXPECT_CALL(mock_settings, set(_, _)).Times(0);
EXPECT_THAT(send_command({"set", keyval_arg(mp::petenv_key, "asdf"), keyval_arg(mp::driver_key, "qemu")}),
Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, set_cmd_fails_with_bad_key_val_format)
{
EXPECT_CALL(mock_settings, set(_, _)).Times(0); // this is not where the rejection is here
EXPECT_THAT(send_command({"set", "="}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"set", "=abc"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"set", "foo=bar="}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"set", "=foo=bar"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"set", "=foo=bar="}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"set", "foo=bar=="}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"set", "==foo=bar"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"set", "foo==bar"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"set", "foo===bar"}), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(send_command({"set", "x=x=x"}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, InteractiveSetFailsWithEOF)
{
std::ostringstream cerr;
std::istringstream cin;
EXPECT_THAT(send_command({"set", mp::petenv_key}, trash_stream, cerr, cin), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(cerr.str(), HasSubstr("Failed to read value"));
}
TEST_F(Client, get_cmd_fails_with_unknown_key)
{
const auto key = "wrong.key";
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Throw(mp::UnrecognizedSettingException{key}));
EXPECT_THAT(send_command({"get", key}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, set_cmd_fails_with_unknown_key)
{
const auto key = "wrong.key";
const auto val = "blah";
EXPECT_CALL(mock_settings, set(Eq(key), Eq(val))).WillOnce(Throw(mp::UnrecognizedSettingException{key}));
EXPECT_THAT(send_command({"set", keyval_arg(key, val)}), Eq(mp::ReturnCode::CommandLineError));
}
TEST_F(Client, InteractiveSetFailsWithUnknownKey)
{
const auto key = "wrong.key";
const auto val = "blah";
std::ostringstream cerr;
std::istringstream cin{fmt::format("{}\n", val)};
EXPECT_CALL(mock_settings, set(Eq(key), Eq(val))).WillOnce(Throw(mp::UnrecognizedSettingException{key}));
EXPECT_THAT(send_command({"set", key}, trash_stream, cerr, cin), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(cerr.str(), HasSubstr("Unrecognized settings key: 'wrong.key'"));
}
TEST_F(Client, get_handles_persistent_settings_errors)
{
const auto key = mp::petenv_key;
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Throw(mp::PersistentSettingsException{"op", "test"}));
EXPECT_THAT(send_command({"get", key}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, get_returns_special_representation_of_empty_value_by_default)
{
const auto key = mp::petenv_key;
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Return(QStringLiteral("")));
EXPECT_THAT(get_setting(key), Eq("<empty>"));
}
TEST_F(Client, get_returns_empty_string_on_empty_value_with_raw_option)
{
const auto key = mp::petenv_key;
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Return(QStringLiteral("")));
EXPECT_THAT(get_setting({key, "--raw"}), IsEmpty());
}
TEST_F(Client, get_keeps_other_values_untouched_with_raw_option)
{
std::vector<std::pair<const char*, QString>> keyvals{{mp::petenv_key, QStringLiteral("a-pet-nAmE")}};
for (const auto& [key, val] : keyvals)
{
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Return(val));
EXPECT_THAT(get_setting({key, "--raw"}), Eq(val.toStdString()));
}
}
TEST_F(Client, getKeysNoArgReturnsAllSettingsKeys)
{
const auto key_set = std::set<QString>{"asdf", "sdfg", "dfgh"};
EXPECT_CALL(mock_settings, keys).WillOnce(Return(key_set));
auto got_keys = QString::fromStdString(get_setting("--keys")).split('\n');
EXPECT_THAT(got_keys, UnorderedElementsAreArray(key_set));
}
TEST_F(Client, getKeysWithValidKeyReturnsThatKey)
{
constexpr auto key = "foo";
const auto key_set = std::set<QString>{"asdf", "sdfg", "dfgh", key};
EXPECT_CALL(mock_settings, keys).WillOnce(Return(key_set));
EXPECT_THAT(get_setting({"--keys", key}), StrEq(key));
}
TEST_F(Client, getKeysWithUnrecognizedKeyFails)
{
constexpr auto wildcard = "*not*yet*";
const auto key_set = std::set<QString>{"asdf", "sdfg", "dfgh"};
EXPECT_CALL(mock_settings, keys).WillOnce(Return(key_set));
std::ostringstream cout, cerr;
EXPECT_THAT(send_command({"get", "--keys", wildcard}, cout, cerr), Eq(mp::ReturnCode::CommandLineError));
EXPECT_THAT(cerr.str(), AllOf(HasSubstr("Unrecognized"), HasSubstr(wildcard)));
EXPECT_THAT(cout.str(), IsEmpty());
}
TEST_F(Client, set_handles_persistent_settings_errors)
{
const auto key = mp::petenv_key;
const auto val = "asdasdasd";
EXPECT_CALL(mock_settings, set(Eq(key), Eq(val))).WillOnce(Throw(mp::PersistentSettingsException{"op", "test"}));
EXPECT_THAT(send_command({"set", keyval_arg(key, val)}), Eq(mp::ReturnCode::CommandFail));
}
TEST_F(Client, set_cmd_rejects_bad_values)
{
const auto key = "hip", val = "hop", why = "don't like it";
EXPECT_CALL(mock_settings, set(Eq(key), Eq(val))).WillOnce(Throw(mp::InvalidSettingException{key, val, why}));
EXPECT_THAT(send_command({"set", keyval_arg(key, val)}), Eq(mp::ReturnCode::CommandLineError));
}
#ifdef MULTIPASS_PLATFORM_LINUX // These tests concern linux-specific behavior for qemu<->libvirt switching
TEST_F(Client, set_cmd_toggle_petenv)
{
EXPECT_CALL(mock_settings, set(Eq(mp::petenv_key), Eq("")));
EXPECT_THAT(send_command({"set", keyval_arg(mp::petenv_key, "")}), Eq(mp::ReturnCode::Ok));
EXPECT_CALL(mock_settings, set(Eq(mp::petenv_key), Eq("some primary")));
EXPECT_THAT(send_command({"set", keyval_arg(mp::petenv_key, "some primary")}), Eq(mp::ReturnCode::Ok));
}
#endif // MULTIPASS_PLATFORM_LINUX
// general help tests
TEST_F(Client, help_returns_ok_return_code)
{
EXPECT_THAT(send_command({"--help"}), Eq(mp::ReturnCode::Ok));
}
struct HelpTestsuite : public ClientAlias, public WithParamInterface<std::pair<std::string, std::string>>
{
};
TEST_P(HelpTestsuite, answers_correctly)
{
auto [command, expected_text] = GetParam();
std::stringstream cout_stream;
EXPECT_EQ(send_command({"help", command}, cout_stream), mp::ReturnCode::Ok);
EXPECT_THAT(cout_stream.str(), HasSubstr(expected_text));
cout_stream.str(std::string());
EXPECT_EQ(send_command({command, "-h"}, cout_stream), mp::ReturnCode::Ok);
EXPECT_THAT(cout_stream.str(), HasSubstr(expected_text));
}
INSTANTIATE_TEST_SUITE_P(
Client, HelpTestsuite,
Values(std::make_pair(std::string{"alias"}, "Create an alias to be executed on a given instance.\n"),
std::make_pair(std::string{"aliases"}, "List available aliases\n"),
std::make_pair(std::string{"unalias"}, "Remove aliases\n"),
std::make_pair(std::string{"prefer"},
"Switch the current alias context. If it does not exist, create it before switching.")));
TEST_F(Client, command_help_is_different_than_general_help)
{
std::stringstream general_help_output;
send_command({"--help"}, general_help_output);
std::stringstream command_output;
send_command({"list", "--help"}, command_output);
EXPECT_THAT(general_help_output.str(), Ne(command_output.str()));
}
TEST_F(Client, help_cmd_launch_same_launch_cmd_help)
{
std::stringstream help_cmd_launch;
send_command({"help", "launch"}, help_cmd_launch);
std::stringstream launch_cmd_help;
send_command({"launch", "-h"}, launch_cmd_help);
EXPECT_THAT(help_cmd_launch.str(), Ne(""));
EXPECT_THAT(help_cmd_launch.str(), Eq(launch_cmd_help.str()));
}
// clone cli tests
TEST_F(Client, cloneCmdWithTooManyArgsFails)
{
EXPECT_EQ(send_command({"clone", "vm1", "vm2"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, cloneCmdWithTooLessArgsFails)
{
EXPECT_EQ(send_command({"clone"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, cloneCmdInvalidOptionFails)
{
EXPECT_EQ(send_command({"clone", "--invalid_option"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, cloneCmdHelpOk)
{
EXPECT_EQ(send_command({"clone", "--help"}), mp::ReturnCode::Ok);
}
TEST_F(Client, cloneCmdWithSrcVMNameOnly)
{
EXPECT_CALL(mock_daemon, clone).Times(1);
EXPECT_EQ(send_command({"clone", "vm1"}), mp::ReturnCode::Ok);
}
TEST_F(Client, cloneCmdWithDestName)
{
EXPECT_CALL(mock_daemon, clone).Times(2);
EXPECT_EQ(send_command({"clone", "vm1", "-n", "vm2"}), mp::ReturnCode::Ok);
EXPECT_EQ(send_command({"clone", "vm1", "--name", "vm2"}), mp::ReturnCode::Ok);
}
TEST_F(Client, cloneCmdFailedFromDaemon)
{
const grpc::Status clone_failure{grpc::StatusCode::FAILED_PRECONDITION, "dummy_msg"};
EXPECT_CALL(mock_daemon, clone).Times(1).WillOnce(Return(clone_failure));
EXPECT_EQ(send_command({"clone", "vm1"}), mp::ReturnCode::CommandFail);
}
// snapshot cli tests
TEST_F(Client, snapshotCmdHelpOk)
{
EXPECT_EQ(send_command({"snapshot", "--help"}), mp::ReturnCode::Ok);
}
TEST_F(Client, snapshotCmdNoOptionsOk)
{
EXPECT_CALL(mock_daemon, snapshot);
EXPECT_EQ(send_command({"snapshot", "foo"}), mp::ReturnCode::Ok);
}
TEST_F(Client, snapshotCmdNameAlternativesOk)
{
EXPECT_CALL(mock_daemon, snapshot).Times(2);
EXPECT_EQ(send_command({"snapshot", "-n", "bar", "foo"}), mp::ReturnCode::Ok);
EXPECT_EQ(send_command({"snapshot", "--name", "bar", "foo"}), mp::ReturnCode::Ok);
}
TEST_F(Client, snapshotCmdNameConsumesArg)
{
EXPECT_CALL(mock_daemon, snapshot).Times(0);
EXPECT_EQ(send_command({"snapshot", "--name", "foo"}), mp::ReturnCode::CommandLineError);
EXPECT_EQ(send_command({"snapshot", "-n", "foo"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, snapshotCmdCommentOptionAlternativesOk)
{
EXPECT_CALL(mock_daemon, snapshot).Times(3);
EXPECT_EQ(send_command({"snapshot", "--comment", "a comment", "foo"}), mp::ReturnCode::Ok);
EXPECT_EQ(send_command({"snapshot", "-c", "a comment", "foo"}), mp::ReturnCode::Ok);
EXPECT_EQ(send_command({"snapshot", "-m", "a comment", "foo"}), mp::ReturnCode::Ok);
}
TEST_F(Client, snapshotCmdCommentConsumesArg)
{
EXPECT_CALL(mock_daemon, snapshot).Times(0);
EXPECT_EQ(send_command({"snapshot", "--comment", "foo"}), mp::ReturnCode::CommandLineError);
EXPECT_EQ(send_command({"snapshot", "-c", "foo"}), mp::ReturnCode::CommandLineError);
EXPECT_EQ(send_command({"snapshot", "-m", "foo"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, snapshotCmdTooFewArgsFails)
{
EXPECT_EQ(send_command({"snapshot", "-m", "Who controls the past controls the future"}),
mp::ReturnCode::CommandLineError);
}
TEST_F(Client, snapshotCmdTooManyArgsFails)
{
EXPECT_EQ(send_command({"snapshot", "foo", "bar"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, snapshotCmdInvalidOptionFails)
{
EXPECT_EQ(send_command({"snapshot", "--snap"}), mp::ReturnCode::CommandLineError);
}
// restore cli tests
TEST_F(Client, restoreCmdHelpOk)
{
EXPECT_EQ(send_command({"restore", "--help"}), mp::ReturnCode::Ok);
}
TEST_F(Client, restoreCmdGoodArgsOk)
{
EXPECT_CALL(mock_daemon, restore);
EXPECT_EQ(send_command({"restore", "foo.snapshot1", "--destructive"}), mp::ReturnCode::Ok);
}
TEST_F(Client, restoreCmdTooFewArgsFails)
{
EXPECT_EQ(send_command({"restore", "--destructive"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, restoreCmdTooManyArgsFails)
{
EXPECT_EQ(send_command({"restore", "foo.snapshot1", "bar.snapshot2"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, restoreCmdMissingInstanceFails)
{
EXPECT_EQ(send_command({"restore", ".snapshot1"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, restoreCmdMissingSnapshotFails)
{
EXPECT_EQ(send_command({"restore", "foo."}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, restoreCmdInvalidOptionFails)
{
EXPECT_EQ(send_command({"restore", "--foo"}), mp::ReturnCode::CommandLineError);
}
struct RestoreCommandClient : public Client
{
RestoreCommandClient()
{
EXPECT_CALL(mock_terminal, cout).WillRepeatedly(ReturnRef(cout));
EXPECT_CALL(mock_terminal, cerr).WillRepeatedly(ReturnRef(cerr));
EXPECT_CALL(mock_terminal, cin).WillRepeatedly(ReturnRef(cin));
}
std::ostringstream cerr, cout;
std::istringstream cin;
mpt::MockTerminal mock_terminal;
};
TEST_F(RestoreCommandClient, restoreCmdConfirmsDesruction)
{
cin.str("invalid input\nyes\n");
EXPECT_CALL(mock_terminal, cin_is_live()).WillOnce(Return(true));
EXPECT_CALL(mock_terminal, cout_is_live()).WillOnce(Return(true));
EXPECT_CALL(mock_daemon, restore(_, _)).WillOnce([](auto, auto* server) {
mp::RestoreRequest request;
server->Read(&request);
EXPECT_FALSE(request.destructive());
mp::RestoreReply reply;
reply.set_confirm_destructive(true);
server->Write(reply);
return grpc::Status{};
});
EXPECT_EQ(setup_client_and_run({"restore", "foo.snapshot1"}, mock_terminal), mp::ReturnCode::Ok);
EXPECT_TRUE(cout.str().find("Please answer yes/no"));
}
TEST_F(RestoreCommandClient, restoreCmdNotDestructiveNotLiveTermFails)
{
EXPECT_CALL(mock_terminal, cin_is_live()).WillOnce(Return(false));
EXPECT_CALL(mock_daemon, restore(_, _)).WillOnce([](auto, auto* server) {
mp::RestoreReply reply;
reply.set_confirm_destructive(true);
server->Write(reply);
return grpc::Status{};
});
EXPECT_THROW(setup_client_and_run({"restore", "foo.snapshot1"}, mock_terminal), std::runtime_error);
}
// authenticate cli tests
TEST_F(Client, authenticateCmdGoodPassphraseOk)
{
EXPECT_CALL(mock_daemon, authenticate);
EXPECT_EQ(send_command({"authenticate", "foo"}), mp::ReturnCode::Ok);
}
TEST_F(Client, authenticateCmdInvalidOptionFails)
{
EXPECT_EQ(send_command({"authenticate", "--foo"}), mp::ReturnCode::CommandLineError);
}
TEST_F(Client, authenticateCmdHelpOk)
{
EXPECT_EQ(send_command({"authenticate", "--help"}), mp::ReturnCode::Ok);
}
TEST_F(Client, authenticateCmdTooManyArgsFails)
{
EXPECT_EQ(send_command({"authenticate", "foo", "bar"}), mp::ReturnCode::CommandLineError);
}
struct AuthenticateCommandClient : public Client
{
AuthenticateCommandClient()
{
EXPECT_CALL(mock_terminal, cout).WillRepeatedly(ReturnRef(cout));
EXPECT_CALL(mock_terminal, cerr).WillRepeatedly(ReturnRef(cerr));
EXPECT_CALL(mock_terminal, cin).WillRepeatedly(ReturnRef(cin));
{
InSequence s;
EXPECT_CALL(mock_terminal, set_cin_echo(false)).Times(1);
EXPECT_CALL(mock_terminal, set_cin_echo(true)).Times(1);
}
}
std::ostringstream cerr, cout;
std::istringstream cin;
mpt::MockTerminal mock_terminal;
};
TEST_F(AuthenticateCommandClient, authenticateCmdAcceptsEnteredPassphrase)
{
const std::string passphrase{"foo"};
cin.str(passphrase + "\n");
EXPECT_CALL(mock_daemon, authenticate(_, _)).WillOnce([&passphrase](auto, auto* server) {
mp::AuthenticateRequest request;
server->Read(&request);
EXPECT_EQ(request.passphrase(), passphrase);
return grpc::Status{};
});
EXPECT_EQ(setup_client_and_run({"authenticate"}, mock_terminal), mp::ReturnCode::Ok);
}
TEST_F(AuthenticateCommandClient, authenticateCmdNoPassphraseEnteredReturnsError)
{
cin.str("\n");
EXPECT_EQ(setup_client_and_run({"authenticate"}, mock_terminal), mp::ReturnCode::CommandLineError);
EXPECT_EQ(cerr.str(), "No passphrase given\n");
}
TEST_F(AuthenticateCommandClient, authenticateCmdNoPassphrasePrompterFailsReturnsError)
{
cin.clear();
EXPECT_EQ(setup_client_and_run({"authenticate"}, mock_terminal), mp::ReturnCode::CommandLineError);
EXPECT_EQ(cerr.str(), "Failed to read value\n");
}
const std::vector<std::string> timeout_commands{"launch", "start", "restart", "shell"};
const std::vector<std::string> valid_timeouts{"120", "1234567"};
const std::vector<std::string> invalid_timeouts{"-1", "0", "a", "3min", "15.51", ""};
struct TimeoutCorrectSuite : Client, WithParamInterface<std::tuple<std::string, std::string>>
{
};
TEST_P(TimeoutCorrectSuite, cmds_with_timeout_ok)
{
const auto& [command, timeout] = GetParam();
EXPECT_CALL(mock_daemon, launch).Times(AtMost(1));
EXPECT_CALL(mock_daemon, start).Times(AtMost(1));
EXPECT_CALL(mock_daemon, restart).Times(AtMost(1));
EXPECT_CALL(mock_daemon, ssh_info).Times(AtMost(1));
EXPECT_THAT(send_command({command, "--timeout", timeout}), Eq(mp::ReturnCode::Ok));
}
INSTANTIATE_TEST_SUITE_P(Client, TimeoutCorrectSuite, Combine(ValuesIn(timeout_commands), ValuesIn(valid_timeouts)));
struct TimeoutNullSuite : Client, WithParamInterface<std::string>
{
};
TEST_P(TimeoutNullSuite, cmds_with_timeout_null_bad)
{
EXPECT_THAT(send_command({GetParam(), "--timeout"}), Eq(mp::ReturnCode::CommandLineError));
}
INSTANTIATE_TEST_SUITE_P(Client, TimeoutNullSuite, ValuesIn(timeout_commands));
struct TimeoutInvalidSuite : Client, WithParamInterface<std::tuple<std::string, std::string>>
{
};
TEST_P(TimeoutInvalidSuite, cmds_with_invalid_timeout_bad)
{
std::stringstream cerr_stream;
const auto& [command, timeout] = GetParam();
EXPECT_THAT(send_command({command, "--timeout", timeout}, trash_stream, cerr_stream),
Eq(mp::ReturnCode::CommandLineError));
EXPECT_EQ(cerr_stream.str(), "error: --timeout value has to be a positive integer\n");
}
INSTANTIATE_TEST_SUITE_P(Client, TimeoutInvalidSuite, Combine(ValuesIn(timeout_commands), ValuesIn(invalid_timeouts)));
struct TimeoutSuite : Client, WithParamInterface<std::string>
{
void SetUp() override
{
Client::SetUp();
ON_CALL(mock_daemon, launch).WillByDefault(request_sleeper<mp::LaunchRequest, mp::LaunchReply>);
ON_CALL(mock_daemon, start).WillByDefault(request_sleeper<mp::StartRequest, mp::StartReply>);
ON_CALL(mock_daemon, restart).WillByDefault(request_sleeper<mp::RestartRequest, mp::RestartReply>);
ON_CALL(mock_daemon, ssh_info).WillByDefault(request_sleeper<mp::SSHInfoRequest, mp::SSHInfoReply>);
}
template <typename RequestType, typename ReplyType>
static grpc::Status request_sleeper(grpc::ServerContext* context,
grpc::ServerReaderWriter<ReplyType, RequestType>* response)
{
std::this_thread::sleep_for(std::chrono::seconds(2));
return grpc::Status::OK;
}
};
TEST_P(TimeoutSuite, command_exits_on_timeout)
{
auto [mock_utils, guard] = mpt::MockUtils::inject();
EXPECT_CALL(mock_daemon, launch).Times(AtMost(1));
EXPECT_CALL(mock_daemon, start).Times(AtMost(1));
EXPECT_CALL(mock_daemon, restart).Times(AtMost(1));
EXPECT_CALL(mock_daemon, ssh_info).Times(AtMost(1));
EXPECT_CALL(*mock_utils, exit(mp::timeout_exit_code));
send_command({GetParam(), "--timeout", "1"});
}
TEST_P(TimeoutSuite, command_completes_without_timeout)
{
EXPECT_CALL(mock_daemon, launch).Times(AtMost(1));
EXPECT_CALL(mock_daemon, start).Times(AtMost(1));
EXPECT_CALL(mock_daemon, restart).Times(AtMost(1));
EXPECT_CALL(mock_daemon, ssh_info).Times(AtMost(1));
EXPECT_EQ(send_command({GetParam(), "--timeout", "5"}), mp::ReturnCode::Ok);
}
INSTANTIATE_TEST_SUITE_P(Client, TimeoutSuite, ValuesIn(timeout_commands));
struct ClientLogMessageSuite : Client, WithParamInterface<std::vector<std::string>>
{
void SetUp() override
{
Client::SetUp();
ON_CALL(mock_daemon, launch).WillByDefault(reply_log_message<mp::LaunchReply, mp::LaunchRequest>);
ON_CALL(mock_daemon, mount).WillByDefault(reply_log_message<mp::MountReply, mp::MountRequest>);
ON_CALL(mock_daemon, start).WillByDefault(reply_log_message<mp::StartReply, mp::StartRequest>);
ON_CALL(mock_daemon, restart).WillByDefault(reply_log_message<mp::RestartReply, mp::RestartRequest>);
ON_CALL(mock_daemon, version).WillByDefault(reply_log_message<mp::VersionReply, mp::VersionRequest>);
}
template <typename ReplyType, typename RequestType>
static grpc::Status reply_log_message(Unused, grpc::ServerReaderWriter<ReplyType, RequestType>* response)
{
ReplyType reply;
reply.set_log_line(log_message);
response->Write(reply);
return grpc::Status{};
}
static constexpr auto log_message = "This is a fake log message";
};
TEST_P(ClientLogMessageSuite, clientPrintsOutExpectedLogMessage)
{
EXPECT_CALL(mock_daemon, launch).Times(AtMost(1));
EXPECT_CALL(mock_daemon, mount).Times(AtMost(1));
EXPECT_CALL(mock_daemon, start).Times(AtMost(1));
EXPECT_CALL(mock_daemon, version).Times(AtMost(1));
EXPECT_CALL(mock_daemon, restart).Times(AtMost(1));
std::stringstream cerr_stream;
send_command(GetParam(), trash_stream, cerr_stream);
EXPECT_EQ(cerr_stream.str(), log_message);
}
INSTANTIATE_TEST_SUITE_P(Client, ClientLogMessageSuite,
Values(std::vector<std::string>{"launch"},
std::vector<std::string>{"mount", "..", "test-vm:test"},
std::vector<std::string>{"start"}, std::vector<std::string>{"version"},
std::vector<std::string>{"restart"}, std::vector<std::string>{"version"}));
TEST_F(ClientAlias, alias_creates_alias)
{
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "map"}}});
EXPECT_EQ(send_command({"alias", "primary:another_command", "another_alias", "--no-map-working-directory"}),
mp::ReturnCode::Ok);
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(), csv_header + "an_alias,an_instance,a_command,map,default*\n"
"another_alias,primary,another_command,default,default*\n");
}
struct ClientAliasNameSuite : public ClientAlias,
public WithParamInterface<std::tuple<std::string /* command */, std::string /* path */>>
{
};
TEST_P(ClientAliasNameSuite, creates_correct_default_alias_name)
{
const auto& [command, path] = GetParam();
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
std::vector<std::string> arguments{"alias"};
arguments.push_back(fmt::format("primary:{}{}", path, command));
arguments.push_back("--no-map-working-directory");
EXPECT_EQ(send_command(arguments), mp::ReturnCode::Ok);
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(),
fmt::format(csv_header + "{},primary,{}{},default,default*\n", command, path, command));
}
INSTANTIATE_TEST_SUITE_P(ClientAlias, ClientAliasNameSuite,
Combine(Values("command", "com.mand", "com.ma.nd"),
Values("", "/", "./", "./relative/", "/absolute/", "../more/relative/")));
TEST_F(ClientAlias, failsIfCannotWriteFullyQualifiedScript)
{
EXPECT_CALL(*mock_platform, create_alias_script(_, _)).Times(1).WillRepeatedly(Throw(std::runtime_error("aaa")));
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
std::stringstream cerr_stream;
EXPECT_EQ(send_command({"alias", "primary:command"}, trash_stream, cerr_stream), mp::ReturnCode::CommandLineError);
EXPECT_EQ(cerr_stream.str(), "Error when creating script for alias: aaa\n");
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(), csv_header);
}
TEST_F(ClientAlias, failsIfCannotWriteNonFullyQualifiedScript)
{
EXPECT_CALL(*mock_platform, create_alias_script(_, _))
.WillOnce(Return())
.WillOnce(Throw(std::runtime_error("bbb")));
EXPECT_CALL(*mock_platform, remove_alias_script(_)).WillOnce(Return());
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
std::stringstream cerr_stream;
EXPECT_EQ(send_command({"alias", "primary:command"}, trash_stream, cerr_stream), mp::ReturnCode::CommandLineError);
EXPECT_EQ(cerr_stream.str(), "Error when creating script for alias: bbb\n");
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(), csv_header);
}
TEST_F(ClientAlias, alias_does_not_overwrite_alias)
{
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "map"}}});
std::stringstream cerr_stream;
EXPECT_EQ(send_command({"alias", "primary:another_command", "an_alias"}, trash_stream, cerr_stream),
mp::ReturnCode::CommandLineError);
EXPECT_EQ(cerr_stream.str(), "Alias 'an_alias' already exists in current context\n");
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(), csv_header + "an_alias,an_instance,a_command,map,default*\n");
}
struct ArgumentCheckTestsuite
: public ClientAlias,
public WithParamInterface<std::tuple<std::vector<std::string>, mp::ReturnCode, std::string, std::string>>
{
};
TEST_P(ArgumentCheckTestsuite, answers_correctly)
{
auto [arguments, expected_return_code, expected_cout, expected_cerr] = GetParam();
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
std::stringstream cout_stream, cerr_stream;
EXPECT_EQ(send_command(arguments, cout_stream, cerr_stream), expected_return_code);
EXPECT_THAT(cout_stream.str(), HasSubstr(expected_cout));
EXPECT_EQ(cerr_stream.str(), expected_cerr);
}
INSTANTIATE_TEST_SUITE_P(
Client, ArgumentCheckTestsuite,
Values(std::make_tuple(std::vector<std::string>{"alias"}, mp::ReturnCode::CommandLineError, "",
"Wrong number of arguments given\n"),
std::make_tuple(std::vector<std::string>{"alias", "instance", "command", "alias_name"},
mp::ReturnCode::CommandLineError, "", "Wrong number of arguments given\n"),
std::make_tuple(std::vector<std::string>{"alias", "instance", "alias_name"},
mp::ReturnCode::CommandLineError, "", "No command given\n"),
std::make_tuple(std::vector<std::string>{"alias", "primary:command", "alias_name"}, mp::ReturnCode::Ok,
"You'll need to add", ""),
std::make_tuple(std::vector<std::string>{"alias", "primary:command"}, mp::ReturnCode::Ok,
"You'll need to add", ""),
std::make_tuple(std::vector<std::string>{"alias", ":command"}, mp::ReturnCode::CommandLineError, "",
"No instance name given\n"),
std::make_tuple(std::vector<std::string>{"alias", ":command", "alias_name"},
mp::ReturnCode::CommandLineError, "", "No instance name given\n"),
std::make_tuple(std::vector<std::string>{"alias", "primary:command", "relative/alias_name"},
mp::ReturnCode::CommandLineError, "", "Alias has to be a valid filename\n"),
std::make_tuple(std::vector<std::string>{"alias", "primary:command", "/absolute/alias_name"},
mp::ReturnCode::CommandLineError, "", "Alias has to be a valid filename\n"),
std::make_tuple(std::vector<std::string>{"alias", "primary:command", "weird alias_name"}, mp::ReturnCode::Ok,
"You'll need to add", ""),
std::make_tuple(std::vector<std::string>{"alias", "primary:command", "com.mand"}, mp::ReturnCode::Ok,
"You'll need to add", ""),
std::make_tuple(std::vector<std::string>{"alias", "primary:command", "com.ma.nd"}, mp::ReturnCode::Ok,
"You'll need to add", "")));
TEST_F(ClientAlias, empty_aliases)
{
std::stringstream cout_stream;
send_command({"aliases"}, cout_stream);
EXPECT_THAT(cout_stream.str(), "No aliases defined.\n");
}
TEST_F(ClientAlias, bad_aliases_format)
{
std::stringstream cerr_stream;
send_command({"aliases", "--format", "wrong"}, trash_stream, cerr_stream);
EXPECT_EQ(cerr_stream.str(), "Invalid format type given.\n");
}
TEST_F(ClientAlias, too_many_aliases_arguments)
{
std::stringstream cerr_stream;
send_command({"aliases", "bad_argument"}, trash_stream, cerr_stream);
EXPECT_EQ(cerr_stream.str(), "This command takes no arguments\n");
}
TEST_F(ClientAlias, execute_existing_alias)
{
populate_db_file(AliasesVector{{"some_alias", {"some_instance", "some_command", "map"}}});
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function());
EXPECT_CALL(mock_daemon, ssh_info(_, _));
EXPECT_EQ(send_command({"some_alias"}), mp::ReturnCode::Ok);
}
TEST_F(ClientAlias, execute_nonexistent_alias)
{
populate_db_file(AliasesVector{{"some_alias", {"some_instance", "some_command", "map"}}});
EXPECT_CALL(mock_daemon, ssh_info(_, _)).Times(0);
std::stringstream cout_stream;
EXPECT_EQ(send_command({"other_undefined_alias"}, cout_stream), mp::ReturnCode::CommandLineError);
EXPECT_THAT(cout_stream.str(), HasSubstr("Unknown command or alias"));
}
TEST_F(ClientAlias, execute_alias_with_arguments)
{
populate_db_file(AliasesVector{{"some_alias", {"some_instance", "some_command", "map"}}});
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function());
EXPECT_CALL(mock_daemon, ssh_info(_, _));
EXPECT_EQ(send_command({"some_alias", "some_argument"}), mp::ReturnCode::Ok);
}
TEST_F(ClientAlias, fails_executing_alias_without_separator)
{
populate_db_file(AliasesVector{{"some_alias", {"some_instance", "some_command", "map"}}});
EXPECT_CALL(mock_daemon, ssh_info(_, _)).Times(0);
std::stringstream cerr_stream;
EXPECT_EQ(send_command({"some_alias", "--some-option"}, trash_stream, cerr_stream),
mp::ReturnCode::CommandLineError);
EXPECT_THAT(cerr_stream.str(), HasSubstr("Options to the alias should come after \"--\", like this:\n"
"multipass <alias> -- <arguments>\n"));
}
TEST_F(ClientAlias, alias_refuses_creation_nonexistent_instance)
{
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "map"}}});
std::stringstream cout_stream, cerr_stream;
send_command({"alias", "foo:another_command", "another_alias"}, cout_stream, cerr_stream);
EXPECT_EQ(cout_stream.str(), "");
EXPECT_EQ(cerr_stream.str(), "Instance 'foo' does not exist\n");
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(), csv_header + "an_alias,an_instance,a_command,map,default*\n");
}
TEST_F(ClientAlias, alias_refuses_creation_rpc_error)
{
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(Return(grpc::Status{grpc::StatusCode::NOT_FOUND, "msg"}));
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "map"}}});
std::stringstream cout_stream, cerr_stream;
send_command({"alias", "foo:another_command", "another_alias"}, cout_stream, cerr_stream);
EXPECT_EQ(cout_stream.str(), "");
EXPECT_EQ(cerr_stream.str(), "Error retrieving list of instances\n");
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(), csv_header + "an_alias,an_instance,a_command,map,default*\n");
}
TEST_F(ClientAlias, aliasRefusesCreateDuplicateAlias)
{
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
populate_db_file(AliasesVector{{"an_alias", {"primary", "a_command", "map"}}});
std::stringstream cout_stream, cerr_stream;
send_command({"alias", "primary:another_command", "an_alias"}, cout_stream, cerr_stream);
EXPECT_EQ(cout_stream.str(), "");
EXPECT_EQ(cerr_stream.str(), "Alias 'an_alias' already exists in current context\n");
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(), csv_header + "an_alias,primary,a_command,map,default*\n");
}
TEST_F(ClientAlias, aliasCreatesAliasThatExistsInAnotherContext)
{
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
populate_db_file(AliasesVector{{"an_alias", {"primary", "a_command", "map"}}});
EXPECT_EQ(send_command({"prefer", "new_context"}), mp::ReturnCode::Ok);
std::stringstream cout_stream, cerr_stream;
EXPECT_EQ(send_command({"alias", "primary:another_command", "an_alias"}, cout_stream, cerr_stream),
mp::ReturnCode::Ok);
EXPECT_EQ(cout_stream.str(), "");
EXPECT_EQ(cerr_stream.str(), "");
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(),
csv_header +
"an_alias,primary,a_command,map,default\nan_alias,primary,another_command,map,new_context*\n");
}
TEST_F(ClientAlias, unalias_removes_existing_alias)
{
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "default"}},
{"another_alias", {"another_instance", "another_command", "map"}}});
EXPECT_EQ(send_command({"unalias", "another_alias"}), mp::ReturnCode::Ok);
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(), csv_header + "an_alias,an_instance,a_command,default,default*\n");
}
TEST_F(ClientAlias, unalias_succeeds_even_if_script_cannot_be_removed)
{
EXPECT_CALL(*mock_platform, remove_alias_script(_)).Times(1).WillRepeatedly(Throw(std::runtime_error("bbb")));
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "map"}},
{"another_alias", {"another_instance", "another_command", "default"}}});
std::stringstream cerr_stream;
EXPECT_EQ(send_command({"unalias", "another_alias"}, trash_stream, cerr_stream), mp::ReturnCode::Ok);
EXPECT_THAT(cerr_stream.str(), Eq("Warning: 'bbb' when removing alias script for default.another_alias\n"));
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_THAT(cout_stream.str(), csv_header + "an_alias,an_instance,a_command,map,default*\n");
}
TEST_F(ClientAlias, unaliasDoesNotRemoveNonexistentAlias)
{
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "map"}},
{"another_alias", {"another_instance", "another_command", "default"}}});
std::stringstream cerr_stream;
EXPECT_EQ(send_command({"unalias", "nonexistent_alias"}, trash_stream, cerr_stream),
mp::ReturnCode::CommandLineError);
EXPECT_EQ(cerr_stream.str(), "Nonexistent alias: nonexistent_alias.\n");
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_EQ(cout_stream.str(), csv_header + "an_alias,an_instance,a_command,map,default*\n"
"another_alias,another_instance,another_command,default,default*\n");
}
TEST_F(ClientAlias, unaliasDoesNotRemoveNonexistentAliases)
{
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "default"}},
{"another_alias", {"another_instance", "another_command", "map"}}});
std::stringstream cerr_stream;
EXPECT_EQ(send_command({"unalias", "nonexistent_alias", "another_nonexistent_alias"}, trash_stream, cerr_stream),
mp::ReturnCode::CommandLineError);
// Since the container for bad aliases is unordered, we cannot expect an ordered output.
EXPECT_THAT(cerr_stream.str(), HasSubstr("Nonexistent aliases: "));
EXPECT_THAT(cerr_stream.str(), HasSubstr("nonexistent_alias"));
EXPECT_THAT(cerr_stream.str(), HasSubstr(", "));
EXPECT_THAT(cerr_stream.str(), HasSubstr("another_nonexistent_alias"));
EXPECT_THAT(cerr_stream.str(), HasSubstr(".\n"));
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_EQ(cout_stream.str(), csv_header + "an_alias,an_instance,a_command,default,default*\n"
"another_alias,another_instance,another_command,map,default*\n");
}
TEST_F(ClientAlias, unaliasDashDashAllWorks)
{
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "map"}},
{"another_alias", {"another_instance", "another_command", "default"}}});
std::stringstream cerr_stream;
EXPECT_EQ(send_command({"unalias", "--all"}, trash_stream, cerr_stream), mp::ReturnCode::Ok);
EXPECT_EQ(cerr_stream.str(), "");
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_EQ(cout_stream.str(), csv_header);
}
TEST_F(ClientAlias, unaliasDashDashAllClashesWithOtherArguments)
{
populate_db_file(AliasesVector{{"an_alias", {"an_instance", "a_command", "map"}},
{"another_alias", {"another_instance", "another_command", "default"}}});
std::stringstream cerr_stream;
EXPECT_EQ(send_command({"unalias", "arg", "--all"}, trash_stream, cerr_stream), mp::ReturnCode::CommandLineError);
EXPECT_EQ(cerr_stream.str(), "Cannot specify name when --all option set\n");
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
EXPECT_EQ(cout_stream.str(), csv_header + "an_alias,an_instance,a_command,map,default*\n"
"another_alias,another_instance,another_command,default,default*\n");
}
TEST_F(ClientAlias, fails_if_unable_to_create_directory)
{
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, exists(A<const QFile&>())).WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(false));
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
std::stringstream cerr_stream;
send_command({"alias", "primary:command", "alias_name"}, trash_stream, cerr_stream);
ASSERT_THAT(cerr_stream.str(), HasSubstr("Could not create path"));
}
TEST_F(ClientAlias, creating_first_alias_displays_message)
{
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function());
std::stringstream cout_stream;
EXPECT_EQ(send_command({"alias", "primary:a_command", "an_alias"}, cout_stream), mp::ReturnCode::Ok);
EXPECT_THAT(cout_stream.str(), HasSubstr("You'll need to add "));
}
TEST_F(ClientAlias, creating_first_alias_does_not_display_message_if_path_is_set)
{
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function());
auto path = qgetenv("PATH");
#ifdef MULTIPASS_PLATFORM_WINDOWS
path += ';';
#else
path += ':';
#endif
path += MP_PLATFORM.get_alias_scripts_folder().path().toUtf8();
const auto env_scope = mpt::SetEnvScope{"PATH", path};
std::stringstream cout_stream;
EXPECT_EQ(send_command({"alias", "primary:a_command", "an_alias"}, cout_stream), mp::ReturnCode::Ok);
EXPECT_THAT(cout_stream.str(), Eq(""));
}
TEST_F(ClientAlias, fails_when_name_clashes_with_command_alias)
{
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
std::stringstream cerr_stream;
send_command({"alias", "primary:command", "ls"}, trash_stream, cerr_stream);
ASSERT_THAT(cerr_stream.str(), Eq("Alias name 'ls' clashes with a command name\n"));
}
TEST_F(ClientAlias, fails_when_name_clashes_with_command_name)
{
EXPECT_CALL(mock_daemon, info(_, _)).Times(AtMost(1)).WillRepeatedly(make_info_function());
std::stringstream cerr_stream;
send_command({"alias", "primary:command", "list"}, trash_stream, cerr_stream);
ASSERT_THAT(cerr_stream.str(), Eq("Alias name 'list' clashes with a command name\n"));
}
TEST_F(ClientAlias, execAliasRewritesMountedDir)
{
std::string alias_name{"an_alias"};
std::string instance_name{"primary"};
std::string cmd{"pwd"};
QDir current_dir{QDir::current()};
std::string source_dir{(current_dir.canonicalPath()).toStdString()};
std::string target_dir{"/home/ubuntu/dir"};
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function(source_dir, target_dir));
populate_db_file(AliasesVector{{alias_name, {instance_name, cmd, "map"}}});
REPLACE(ssh_channel_request_exec, ([&target_dir, &cmd](ssh_channel, const char* raw_cmd) {
EXPECT_THAT(raw_cmd, StartsWith("cd " + target_dir + "/"));
EXPECT_THAT(raw_cmd, HasSubstr("&&"));
EXPECT_THAT(raw_cmd, EndsWith(cmd)); // assuming that cmd does not have escaped characters!
return SSH_OK;
}));
mp::SSHInfoReply ssh_info_response = make_fake_ssh_info_response(instance_name);
EXPECT_CALL(mock_daemon, ssh_info(_, _))
.WillOnce([&ssh_info_response](grpc::ServerContext* context,
grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
server->Write(ssh_info_response);
return grpc::Status{};
});
EXPECT_EQ(send_command({alias_name}), mp::ReturnCode::Ok);
}
struct NotDirRewriteTestsuite : public ClientAlias, public WithParamInterface<std::pair<bool, QString>>
{
};
TEST_P(NotDirRewriteTestsuite, execAliasDoesNotRewriteMountedDir)
{
auto [map_dir, source_qdir] = GetParam();
std::string alias_name{"an_alias"};
std::string instance_name{"primary"};
std::string cmd{"pwd"};
QDir current_dir{QDir::current()};
std::string source_dir{source_qdir.toStdString()};
std::string target_dir{"/home/ubuntu/dir"};
if (map_dir)
EXPECT_CALL(mock_daemon, info(_, _)).WillOnce(make_info_function(source_dir, target_dir));
else
EXPECT_CALL(mock_daemon, info(_, _)).Times(0);
populate_db_file(AliasesVector{{alias_name, {instance_name, cmd, map_dir ? "map" : "default"}}});
REPLACE(ssh_channel_request_exec, ([&cmd](ssh_channel, const char* raw_cmd) {
EXPECT_THAT(raw_cmd, Not(StartsWith("cd ")));
EXPECT_THAT(raw_cmd, Not(HasSubstr("&&")));
EXPECT_THAT(raw_cmd, EndsWith(cmd)); // again, assuming that cmd does not have escaped characters
return SSH_OK;
}));
mp::SSHInfoReply ssh_info_response = make_fake_ssh_info_response(instance_name);
EXPECT_CALL(mock_daemon, ssh_info(_, _))
.WillOnce([&ssh_info_response](grpc::ServerContext* context,
grpc::ServerReaderWriter<mp::SSHInfoReply, mp::SSHInfoRequest>* server) {
server->Write(ssh_info_response);
return grpc::Status{};
});
std::vector<std::string> arguments{alias_name};
EXPECT_EQ(send_command(arguments), mp::ReturnCode::Ok);
}
QString current_cdup()
{
QDir cur{QDir::current()};
cur.cdUp();
return cur.canonicalPath();
}
INSTANTIATE_TEST_SUITE_P(ClientAlias, NotDirRewriteTestsuite,
Values(std::make_pair(false, QDir{QDir::current()}.canonicalPath()),
std::make_pair(true, QDir{QDir::current()}.canonicalPath() + "/0/1/2/3/4/5/6/7/8/9"),
std::make_pair(true, current_cdup() + "/different_name")));
TEST_F(ClientAliasNameSuite, preferWithNoArgumentFails)
{
EXPECT_EQ(send_command({"prefer"}), mp::ReturnCode::CommandLineError);
}
TEST_F(ClientAliasNameSuite, preferWithManyArgumentsFails)
{
EXPECT_EQ(send_command({"prefer", "arg", "arg"}), mp::ReturnCode::CommandLineError);
}
TEST_F(ClientAliasNameSuite, preferWorks)
{
std::stringstream cout_stream;
send_command({"aliases", "--format=yaml"}, cout_stream);
EXPECT_THAT(cout_stream.str(), HasSubstr("active_context: default\n"));
EXPECT_EQ(send_command({"prefer", "new_context"}), mp::ReturnCode::Ok);
cout_stream.str(std::string());
send_command({"aliases", "--format=yaml"}, cout_stream);
EXPECT_THAT(cout_stream.str(), HasSubstr("active_context: new_context\n"));
}
} // namespace
| 166,476
|
C++
|
.cpp
| 3,386
| 43.545481
| 120
| 0.673913
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,590
|
mock_process_factory.cpp
|
canonical_multipass/tests/mock_process_factory.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_process_factory.h"
#include <QProcess>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace ::testing;
std::unique_ptr<mp::Process> mpt::MockProcessFactory::create_process(std::unique_ptr<mp::ProcessSpec>&& spec) const
{
auto process = std::make_unique<NiceMock<mpt::MockProcess>>(std::move(spec),
const_cast<std::vector<ProcessInfo>&>(process_list));
if (callback)
(*callback)(process.get());
return process;
}
mpt::MockProcess::MockProcess(std::unique_ptr<mp::ProcessSpec>&& spec,
std::vector<mpt::MockProcessFactory::ProcessInfo>& process_list)
: spec{std::move(spec)}
{
success_exit_state.exit_code = 0;
ON_CALL(*this, start()).WillByDefault(Invoke([this] { emit started(); }));
ON_CALL(*this, kill()).WillByDefault(Invoke([this] {
mp::ProcessState exit_state;
exit_state.exit_code = 0;
emit finished(exit_state);
}));
ON_CALL(*this, running()).WillByDefault(Return(true));
ON_CALL(*this, process_state()).WillByDefault(Return(success_exit_state));
ON_CALL(*this, execute(_)).WillByDefault(Return(success_exit_state));
ON_CALL(*this, wait_for_started(_)).WillByDefault(Return(true));
mpt::MockProcessFactory::ProcessInfo p{program(), arguments()};
process_list.emplace_back(p);
}
void mpt::MockProcessFactory::register_callback(const mpt::MockProcessFactory::Callback& cb)
{
callback = cb;
}
std::unique_ptr<mp::test::MockProcessFactory::Scope> mp::test::MockProcessFactory::Inject()
{
ProcessFactory::reset();
ProcessFactory::mock<MockProcessFactory>();
return std::make_unique<mp::test::MockProcessFactory::Scope>();
}
mpt::MockProcessFactory::Scope::~Scope()
{
ProcessFactory::reset();
}
std::vector<mpt::MockProcessFactory::ProcessInfo> mpt::MockProcessFactory::Scope::process_list()
{
return mock_instance().process_list;
}
mpt::MockProcessFactory& mpt::MockProcessFactory::mock_instance()
{
try
{
return dynamic_cast<mpt::MockProcessFactory&>(instance());
}
catch (std::bad_cast&)
{
throw std::runtime_error("ProcessFactory::instance() called before MockProcessFactory::Inject()");
}
}
void mpt::MockProcessFactory::Scope::register_callback(const mpt::MockProcessFactory::Callback& cb)
{
mock_instance().register_callback(cb);
}
// MockProcess implementation
QString mpt::MockProcess::program() const
{
return spec->program();
}
QStringList mpt::MockProcess::arguments() const
{
return spec->arguments();
}
QString mpt::MockProcess::working_directory() const
{
return spec->working_directory();
}
QProcessEnvironment mpt::MockProcess::process_environment() const
{
return spec->environment();
}
bool mpt::MockProcess::wait_for_ready_read(int)
{
return true;
}
void mpt::MockProcess::close_write_channel()
{
}
void mpt::MockProcess::set_process_channel_mode(QProcess::ProcessChannelMode)
{
}
void mpt::MockProcess::setup_child_process()
{
}
| 3,704
|
C++
|
.cpp
| 110
| 29.909091
| 117
| 0.711329
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,591
|
test_top_catch_all.cpp
|
canonical_multipass/tests/test_top_catch_all.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_logger.h"
#include <multipass/logging/log.h>
#include <multipass/top_catch_all.h>
#include <stdexcept>
#include <string>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct TopCatchAll : public Test
{
void SetUp() override
{
logger_scope.mock_logger->screen_logs();
}
auto make_category_matcher()
{
return mpt::MockLogger::make_cstring_matcher(StrEq(category.c_str()));
}
const std::string category = "testing";
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
};
struct CustomExceptionForTesting : public std::exception
{
public:
CustomExceptionForTesting() = default;
const char* what() const noexcept override
{
return msg;
}
inline static constexpr const auto msg = "custom";
};
} // namespace
TEST_F(TopCatchAll, calls_function_with_no_args)
{
int ret = 123, got = 0;
EXPECT_NO_THROW(got = mp::top_catch_all("", EXIT_FAILURE, [ret] { return ret; }););
EXPECT_EQ(got, ret);
}
TEST_F(TopCatchAll, calls_function_with_other_return)
{
std::string ret{"abc"}, got;
EXPECT_NO_THROW(got = mp::top_catch_all("", "unused", [&ret] { return ret; }););
EXPECT_EQ(got, ret);
}
TEST_F(TopCatchAll, calls_function_with_args)
{
int a = 5, b = 7, got = 0;
EXPECT_NO_THROW(got = mp::top_catch_all("", EXIT_FAILURE, std::plus<int>{}, a, b););
EXPECT_EQ(got, a + b);
}
TEST_F(TopCatchAll, handles_unknown_error)
{
int got = 0;
EXPECT_CALL(*logger_scope.mock_logger, log(Eq(mpl::Level::error), make_category_matcher(),
mpt::MockLogger::make_cstring_matcher(HasSubstr("unknown"))));
EXPECT_NO_THROW(got = mp::top_catch_all(category, EXIT_FAILURE, [] {
throw 123;
return 0;
}););
EXPECT_EQ(got, EXIT_FAILURE);
}
TEST_F(TopCatchAll, handles_standard_exception)
{
int got = 0;
const std::string emsg = "some error";
const auto msg_matcher = AllOf(HasSubstr("exception"), HasSubstr(emsg.c_str()));
EXPECT_CALL(*logger_scope.mock_logger, log(Eq(mpl::Level::error), make_category_matcher(),
mpt::MockLogger::make_cstring_matcher(msg_matcher)));
EXPECT_NO_THROW(got = mp::top_catch_all(category, EXIT_FAILURE, [&emsg] {
throw std::runtime_error{emsg};
return 0;
}););
EXPECT_EQ(got, EXIT_FAILURE);
}
TEST_F(TopCatchAll, handles_custom_exception)
{
int got = 0;
const auto msg_matcher = AllOf(HasSubstr("exception"), HasSubstr(CustomExceptionForTesting::msg));
EXPECT_CALL(*logger_scope.mock_logger, log(Eq(mpl::Level::error), make_category_matcher(),
mpt::MockLogger::make_cstring_matcher(msg_matcher)));
EXPECT_NO_THROW(got = mp::top_catch_all(category, EXIT_FAILURE, [] {
throw CustomExceptionForTesting{};
return 42;
}));
EXPECT_EQ(got, EXIT_FAILURE);
}
TEST_F(TopCatchAll, uses_fallback_object_of_other_types_on_exception)
{
std::string fallback{"default"}, got;
EXPECT_CALL(*logger_scope.mock_logger, log(Eq(mpl::Level::error), _, _)).Times(1);
EXPECT_NO_THROW(got = mp::top_catch_all(category, fallback, []() -> std::string { throw 31; }));
EXPECT_EQ(got, fallback);
}
TEST_F(TopCatchAll, calls_void_callable)
{
auto ran = false;
EXPECT_NO_THROW(mp::top_catch_all("", [&ran] { ran = true; }));
EXPECT_TRUE(ran);
}
TEST_F(TopCatchAll, handles_unknown_error_in_void_callable)
{
EXPECT_CALL(*logger_scope.mock_logger, log(Eq(mpl::Level::error), make_category_matcher(),
mpt::MockLogger::make_cstring_matcher(HasSubstr("unknown"))));
EXPECT_NO_THROW(mp::top_catch_all(category, [] { throw 123; }));
}
TEST_F(TopCatchAll, handles_exception_in_void_callable)
{
EXPECT_CALL(*logger_scope.mock_logger, log(Eq(mpl::Level::error), make_category_matcher(),
mpt::MockLogger::make_cstring_matcher(HasSubstr("exception"))));
EXPECT_NO_THROW(mp::top_catch_all(category, [] { throw std::exception{}; }));
}
| 5,017
|
C++
|
.cpp
| 131
| 32.007634
| 111
| 0.638289
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,592
|
test_custom_image_host.cpp
|
canonical_multipass/tests/test_custom_image_host.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "image_host_remote_count.h"
#include "mock_platform.h"
#include "mock_url_downloader.h"
#include "path.h"
#include <src/daemon/custom_image_host.h>
#include <multipass/exceptions/download_exception.h>
#include <multipass/exceptions/unsupported_alias_exception.h>
#include <multipass/exceptions/unsupported_remote_exception.h>
#include <multipass/format.h>
#include <multipass/query.h>
#include <QUrl>
#include <cstddef>
#include <unordered_set>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace multipass::platform;
using namespace testing;
using namespace std::literals::chrono_literals;
namespace
{
constexpr auto sha256_sums =
"934d52e4251537ee3bd8c500f212ae4c34992447e7d40d94f00bc7c21f72ceb7 *ubuntu-core-16-amd64.img.xz\n"
"1ffea8a9caf5a4dcba4f73f9144cb4afe1e4fc1987f4ab43bed4c02fad9f087f *ubuntu-core-18-amd64.img.xz\n"
"52a4606b0b3b28e4cb64e2c2595ef8fdbb4170bfd3596f4e0b84f4d84511b614 *ubuntu-core-20-amd64.img.xz\n"
"6378b1fa3db76cdf18c905c8282ebc97401951a9338722486f653dbf16eb7915 *ubuntu-core-22-amd64.img.xz\n"
"192c40c8f3361f4f9da2757d87e409ac5abb2df393145983d3696e21f486b552 *ubuntu-core-24-amd64.img.xz\n";
struct CustomImageHost : public Test
{
CustomImageHost()
{
EXPECT_CALL(*mock_platform, is_remote_supported(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_platform, is_alias_supported(_, _)).WillRepeatedly(Return(true));
ON_CALL(mock_url_downloader, last_modified(_)).WillByDefault(Return(QDateTime::currentDateTime()));
ON_CALL(mock_url_downloader, download(_)).WillByDefault(Return(sha256_sums));
ON_CALL(mock_url_downloader, download(_, _)).WillByDefault(Return(sha256_sums));
}
mp::Query make_query(std::string release, std::string remote)
{
return {"", std::move(release), false, std::move(remote), mp::Query::Type::Alias};
}
NiceMock<mpt::MockURLDownloader> mock_url_downloader;
mpt::MockPlatform::GuardedMock attr{mpt::MockPlatform::inject()};
mpt::MockPlatform* mock_platform = attr.first;
};
} // namespace
typedef std::tuple<std::vector<std::string> /* aliases */, std::string /* remote */, QUrl /* url */, QString /* id */,
QString /* release */, QString /* release_title */>
CustomData;
struct ExpectedDataSuite : CustomImageHost, WithParamInterface<CustomData>
{
};
TEST_P(ExpectedDataSuite, returns_expected_data)
{
const auto [aliases, remote, url, id, release, release_title] = GetParam();
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
for (const auto& alias : aliases)
{
auto info = host.info_for(make_query(alias, remote));
ASSERT_TRUE(info);
EXPECT_EQ(info->image_location, url.toDisplayString());
EXPECT_EQ(info->id, id);
EXPECT_EQ(info->release, release);
EXPECT_EQ(info->release_title, release_title);
EXPECT_TRUE(info->supported);
EXPECT_EQ(info->version, QLocale::c().toString(QDateTime::currentDateTime(), "yyyyMMdd"));
}
}
INSTANTIATE_TEST_SUITE_P(
CustomImageHost, ExpectedDataSuite,
Values(CustomData{std::vector<std::string>{"core", "core16"}, "",
"https://cdimage.ubuntu.com/ubuntu-core/16/stable/current/ubuntu-core-16-amd64.img.xz",
"934d52e4251537ee3bd8c500f212ae4c34992447e7d40d94f00bc7c21f72ceb7", "core-16", "Core 16"},
CustomData{std::vector<std::string>{"core18"}, "",
"https://cdimage.ubuntu.com/ubuntu-core/18/stable/current/ubuntu-core-18-amd64.img.xz",
"1ffea8a9caf5a4dcba4f73f9144cb4afe1e4fc1987f4ab43bed4c02fad9f087f", "core-18", "Core 18"}));
TEST_F(CustomImageHost, iterates_over_all_entries)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
std::unordered_set<std::string> ids;
auto action = [&ids](const std::string& remote, const mp::VMImageInfo& info) { ids.insert(info.id.toStdString()); };
host.for_each_entry_do(action);
EXPECT_THAT(ids,
UnorderedElementsAre("934d52e4251537ee3bd8c500f212ae4c34992447e7d40d94f00bc7c21f72ceb7",
"1ffea8a9caf5a4dcba4f73f9144cb4afe1e4fc1987f4ab43bed4c02fad9f087f",
"52a4606b0b3b28e4cb64e2c2595ef8fdbb4170bfd3596f4e0b84f4d84511b614",
"6378b1fa3db76cdf18c905c8282ebc97401951a9338722486f653dbf16eb7915",
"192c40c8f3361f4f9da2757d87e409ac5abb2df393145983d3696e21f486b552"));
}
TEST_F(CustomImageHost, unsupported_alias_iterates_over_expected_entries)
{
std::unordered_set<std::string> ids;
EXPECT_CALL(*mock_platform, is_alias_supported("core18", _)).WillRepeatedly(Return(false));
auto action = [&ids](const std::string& remote, const mp::VMImageInfo& info) { ids.insert(info.id.toStdString()); };
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
host.for_each_entry_do(action);
const size_t expected_entries{4};
EXPECT_EQ(ids.size(), expected_entries);
}
TEST_F(CustomImageHost, unsupported_remote_iterates_over_expected_entries)
{
const std::string unsupported_remote{""};
EXPECT_CALL(*mock_platform, is_remote_supported(unsupported_remote)).WillRepeatedly(Return(false));
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
std::unordered_set<std::string> ids;
auto action = [&ids](const std::string& remote, const mp::VMImageInfo& info) { ids.insert(info.id.toStdString()); };
host.for_each_entry_do(action);
const size_t expected_entries{0};
EXPECT_EQ(ids.size(), expected_entries);
}
TEST_F(CustomImageHost, all_images_for_no_remote_returns_appropriate_matches)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
auto images = host.all_images_for("", false);
const size_t expected_matches{5};
EXPECT_THAT(images.size(), Eq(expected_matches));
}
TEST_F(CustomImageHost, all_images_for_no_remote_unsupported_alias_returns_appropriate_matches)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
const std::string unsupported_alias{"core18"};
EXPECT_CALL(*mock_platform, is_alias_supported(unsupported_alias, _)).WillOnce(Return(false));
auto images = host.all_images_for("", false);
const size_t expected_matches{4};
EXPECT_EQ(images.size(), expected_matches);
}
TEST_F(CustomImageHost, all_info_for_no_remote_returns_one_alias_match)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
auto images_info = host.all_info_for(make_query("core20", ""));
const size_t expected_matches{1};
EXPECT_THAT(images_info.size(), Eq(expected_matches));
}
TEST_F(CustomImageHost, all_info_for_unsupported_alias_throws)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
const std::string unsupported_alias{"core20"};
EXPECT_CALL(*mock_platform, is_alias_supported(unsupported_alias, _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(
host.all_info_for(make_query(unsupported_alias, "")), mp::UnsupportedAliasException,
mpt::match_what(HasSubstr(fmt::format("\'{}\' is not a supported alias.", unsupported_alias))));
}
TEST_F(CustomImageHost, supported_remotes_returns_expected_values)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
auto supported_remotes = host.supported_remotes();
const size_t expected_size{1};
EXPECT_THAT(supported_remotes.size(), Eq(expected_size));
EXPECT_TRUE(std::find(supported_remotes.begin(), supported_remotes.end(), "") != supported_remotes.end());
}
TEST_F(CustomImageHost, invalid_image_returns_false)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
EXPECT_FALSE(host.info_for(make_query("foo", "")));
}
TEST_F(CustomImageHost, invalid_remote_throws_error)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
EXPECT_THROW(host.info_for(make_query("core", "foo")), std::runtime_error);
}
TEST_F(CustomImageHost, handles_and_recovers_from_initial_network_failure)
{
EXPECT_CALL(mock_url_downloader, last_modified(_))
.WillOnce(Throw(mp::DownloadException{"", ""}))
.WillRepeatedly(DoDefault());
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
const auto query = make_query("core20", "");
EXPECT_THROW(host.update_manifests(false), mp::DownloadException);
EXPECT_THROW(host.info_for(query), std::runtime_error);
host.update_manifests(false);
EXPECT_TRUE(host.info_for(query));
}
TEST_F(CustomImageHost, handles_and_recovers_from_later_network_failure)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
const auto query = make_query("core20", "");
host.update_manifests(false);
EXPECT_TRUE(host.info_for(query));
EXPECT_CALL(mock_url_downloader, last_modified(_))
.WillOnce(Throw(mp::DownloadException{"", ""}))
.WillRepeatedly(DoDefault());
EXPECT_THROW(host.update_manifests(false), mp::DownloadException);
EXPECT_THROW(host.info_for(query), std::runtime_error);
host.update_manifests(false);
EXPECT_TRUE(host.info_for(query));
}
TEST_F(CustomImageHost, handles_and_recovers_from_independent_server_failures)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
const auto num_remotes = mpt::count_remotes(host);
EXPECT_GT(num_remotes, 0u);
for (size_t i = 0; i < num_remotes; ++i)
{
Sequence seq;
if (i > 0)
{
EXPECT_CALL(mock_url_downloader, last_modified(_))
.Times(i)
.InSequence(seq)
.WillRepeatedly(Throw(mp::DownloadException{"", ""}));
}
EXPECT_CALL(mock_url_downloader, last_modified(_)).Times(AnyNumber()).InSequence(seq);
EXPECT_EQ(mpt::count_remotes(host), num_remotes - i);
EXPECT_TRUE(Mock::VerifyAndClearExpectations(&mock_url_downloader));
}
}
TEST_F(CustomImageHost, info_for_unsupported_remote_throws)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
const std::string unsupported_remote{"foo"};
EXPECT_CALL(*mock_platform, is_remote_supported(unsupported_remote)).WillRepeatedly(Return(false));
MP_EXPECT_THROW_THAT(host.info_for(make_query("xenial", unsupported_remote)), mp::UnsupportedRemoteException,
mpt::match_what(HasSubstr(fmt::format(
"Remote \'{}\' is not a supported remote for this platform.", unsupported_remote))));
}
TEST_F(CustomImageHost, info_for_full_hash_returns_empty_image_info)
{
mp::CustomVMImageHost host{"x86_64", &mock_url_downloader};
host.update_manifests(false);
const auto info = host.info_for_full_hash("934d52e4251537ee3bd8c500f212ae4c34992447e7d40d94f00bc7c21f72ceb7");
EXPECT_EQ(info, mp::VMImageInfo{});
}
struct EmptyArchSuite : CustomImageHost, WithParamInterface<QString>
{
};
TEST_P(EmptyArchSuite, empty_for_other_arches)
{
auto arch = GetParam();
mp::CustomVMImageHost host{arch, &mock_url_downloader};
host.update_manifests(false);
EXPECT_CALL(mock_url_downloader, last_modified(_)).Times(0);
EXPECT_CALL(mock_url_downloader, download(_)).Times(0);
std::unordered_set<std::string> ids;
host.for_each_entry_do(
[&ids](const std::string& remote, const mp::VMImageInfo& info) { ids.insert(info.id.toStdString()); });
const size_t expected_entries{0};
EXPECT_THAT(ids.size(), Eq(expected_entries));
}
INSTANTIATE_TEST_SUITE_P(CustomImageHost, EmptyArchSuite, Values("arm", "arm64", "i386", "power", "power64", "s390x"));
| 12,726
|
C++
|
.cpp
| 268
| 42.037313
| 120
| 0.71086
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,593
|
mock_process.cpp
|
canonical_multipass/tests/mock_process.cpp
|
#include <cstdlib>
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
if (argc == 1)
{
// deliberately will crash if argument 1 missing
abort();
}
// Exit immediately if only 1 argument
else if (argc == 2)
{
return atoi(argv[1]);
}
// If more than 1 argument, run until get EOF from input
std::string s;
std::getline(std::cin, s, '\0');
// Crash on demand
if (s == "crash")
{
abort();
}
// Print out what was supplied by stdin
std::cout << s;
std::cerr << s;
return atoi(argv[1]);
}
| 614
|
C++
|
.cpp
| 28
| 17.035714
| 60
| 0.564544
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,594
|
temp_file.cpp
|
canonical_multipass/tests/temp_file.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Alberto Aguirre <alberto.aguirre@canonical.com>
*
*/
#include "temp_file.h"
#include <stdexcept>
namespace mpt = multipass::test;
mpt::TempFile::TempFile()
{
if (file.open())
{
the_name = file.fileName();
the_url = QUrl::fromLocalFile(the_name).toString();
}
else
{
throw std::runtime_error("test failed to create temporary file");
}
}
| 1,030
|
C++
|
.cpp
| 33
| 28.121212
| 73
| 0.713998
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,595
|
test_petname.cpp
|
canonical_multipass/tests/test_petname.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Alberto Aguirre <alberto.aguirre@canonical.com>
*
*/
#include "common.h"
#include <src/petname/petname.h>
#include <regex>
#include <string>
#include <unordered_set>
#include <vector>
namespace mp = multipass;
using namespace testing;
namespace
{
std::vector<std::string> split(const std::string& string, const std::string& delimiter)
{
std::regex regex(delimiter);
return {std::sregex_token_iterator{string.begin(), string.end(), regex, -1}, std::sregex_token_iterator{}};
}
}
TEST(Petname, generates_the_requested_num_words)
{
std::string separator{"-"};
mp::Petname gen1{mp::Petname::NumWords::ONE, separator};
mp::Petname gen2{mp::Petname::NumWords::TWO, separator};
mp::Petname gen3{mp::Petname::NumWords::THREE, separator};
auto one_word_name = gen1.make_name();
auto tokens = split(one_word_name, separator);
EXPECT_THAT(tokens.size(), Eq(1u));
auto two_word_name = gen2.make_name();
tokens = split(two_word_name, separator);
EXPECT_THAT(tokens.size(), Eq(2u));
auto three_word_name = gen3.make_name();
tokens = split(three_word_name, separator);
EXPECT_THAT(tokens.size(), Eq(3u));
}
TEST(Petname, uses_default_separator)
{
std::string expected_separator{"-"};
mp::Petname name_generator{mp::Petname::NumWords::THREE};
auto name = name_generator.make_name();
auto tokens = split(name, expected_separator);
EXPECT_THAT(tokens.size(), Eq(3u));
}
TEST(Petname, generates_two_tokens_by_default)
{
std::string separator{"-"};
mp::Petname name_generator{separator};
auto name = name_generator.make_name();
auto tokens = split(name, separator);
EXPECT_THAT(tokens.size(), Eq(2u));
// Each token should be unique
std::unordered_set<std::string> set(tokens.begin(), tokens.end());
EXPECT_THAT(set.size(), Eq(tokens.size()));
}
TEST(Petname, can_generate_at_least_hundred_unique_names)
{
std::string separator{"-"};
mp::Petname name_generator{mp::Petname::NumWords::THREE, separator};
std::unordered_set<std::string> name_set;
const std::size_t expected_num_unique_names{100};
//TODO: fixme, randomness is involved in name generation hence there's a non-zero probability
// we will fail to generate the number of expected unique names.
for (std::size_t i = 0; i < 10*expected_num_unique_names; i++)
{
name_set.insert(name_generator.make_name());
}
EXPECT_THAT(name_set.size(), Ge(expected_num_unique_names));
}
| 3,126
|
C++
|
.cpp
| 83
| 34.349398
| 111
| 0.709379
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,596
|
test_output_formatter.cpp
|
canonical_multipass/tests/test_output_formatter.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_format_utils.h"
#include "mock_settings.h"
#include <multipass/cli/csv_formatter.h>
#include <multipass/cli/json_formatter.h>
#include <multipass/cli/table_formatter.h>
#include <multipass/cli/yaml_formatter.h>
#include <multipass/constants.h>
#include <multipass/format.h>
#include <multipass/rpc/multipass.grpc.pb.h>
#include <multipass/settings/settings.h>
#include <locale>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
auto petenv_name()
{
return MP_SETTINGS.get(mp::petenv_key).toStdString();
}
auto construct_empty_list_reply()
{
mp::ListReply list_reply;
list_reply.mutable_instance_list();
return list_reply;
}
auto construct_empty_list_snapshot_reply()
{
mp::ListReply list_reply;
list_reply.mutable_snapshot_list();
return list_reply;
}
auto construct_single_instance_list_reply()
{
mp::ListReply list_reply;
auto list_entry = list_reply.mutable_instance_list()->add_instances();
list_entry->set_name("foo");
list_entry->mutable_instance_status()->set_status(mp::InstanceStatus::RUNNING);
list_entry->set_current_release("16.04 LTS");
list_entry->add_ipv4("10.168.32.2");
list_entry->add_ipv4("200.3.123.30");
list_entry->add_ipv6("fdde:2681:7a2::4ca");
list_entry->add_ipv6("fe80::1c3c:b703:d561:a00");
return list_reply;
}
auto construct_multiple_instances_list_reply()
{
mp::ListReply list_reply;
auto list_entry = list_reply.mutable_instance_list()->add_instances();
list_entry->set_name("bogus-instance");
list_entry->mutable_instance_status()->set_status(mp::InstanceStatus::RUNNING);
list_entry->set_current_release("16.04 LTS");
list_entry->add_ipv4("10.21.124.56");
list_entry = list_reply.mutable_instance_list()->add_instances();
list_entry->set_name("bombastic");
list_entry->mutable_instance_status()->set_status(mp::InstanceStatus::STOPPED);
list_entry->set_current_release("18.04 LTS");
return list_reply;
}
auto construct_unsorted_list_reply()
{
mp::ListReply list_reply;
auto list_entry = list_reply.mutable_instance_list()->add_instances();
list_entry->set_name("trusty-190611-1542");
list_entry->mutable_instance_status()->set_status(mp::InstanceStatus::RUNNING);
list_entry->set_current_release("N/A");
list_entry = list_reply.mutable_instance_list()->add_instances();
list_entry->set_name("trusty-190611-1535");
list_entry->mutable_instance_status()->set_status(mp::InstanceStatus::STOPPED);
list_entry->set_current_release("N/A");
list_entry = list_reply.mutable_instance_list()->add_instances();
list_entry->set_name("trusty-190611-1539");
list_entry->mutable_instance_status()->set_status(mp::InstanceStatus::SUSPENDED);
list_entry->set_current_release("");
list_entry = list_reply.mutable_instance_list()->add_instances();
list_entry->set_name("trusty-190611-1529");
list_entry->mutable_instance_status()->set_status(mp::InstanceStatus::DELETED);
list_entry->set_current_release("");
return list_reply;
}
auto construct_single_snapshot_list_reply()
{
mp::ListReply list_reply;
auto list_entry = list_reply.mutable_snapshot_list()->add_snapshots();
list_entry->set_name("foo");
auto fundamentals = list_entry->mutable_fundamentals();
fundamentals->set_snapshot_name("snapshot1");
fundamentals->set_comment("This is a sample comment");
google::protobuf::Timestamp timestamp;
timestamp.set_seconds(time(nullptr));
timestamp.set_nanos(0);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
return list_reply;
}
auto construct_multiple_snapshots_list_reply()
{
mp::ListReply list_reply;
auto list_entry = list_reply.mutable_snapshot_list()->add_snapshots();
auto fundamentals = list_entry->mutable_fundamentals();
google::protobuf::Timestamp timestamp;
list_entry->set_name("prosperous-spadefish");
fundamentals->set_snapshot_name("snapshot10");
fundamentals->set_parent("snapshot2");
timestamp.set_seconds(1672531200);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
list_entry = list_reply.mutable_snapshot_list()->add_snapshots();
fundamentals = list_entry->mutable_fundamentals();
list_entry->set_name("hale-roller");
fundamentals->set_snapshot_name("rolling");
fundamentals->set_parent("pristine");
fundamentals->set_comment("Loaded with stuff");
timestamp.set_seconds(25425952800);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
list_entry = list_reply.mutable_snapshot_list()->add_snapshots();
fundamentals = list_entry->mutable_fundamentals();
list_entry->set_name("hale-roller");
fundamentals->set_snapshot_name("rocking");
fundamentals->set_parent("pristine");
fundamentals->set_comment("A very long comment that should be truncated by the table formatter");
timestamp.set_seconds(2209234259);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
list_entry = list_reply.mutable_snapshot_list()->add_snapshots();
fundamentals = list_entry->mutable_fundamentals();
list_entry->set_name("hale-roller");
fundamentals->set_snapshot_name("pristine");
fundamentals->set_comment("A first snapshot");
timestamp.set_seconds(409298914);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
list_entry = list_reply.mutable_snapshot_list()->add_snapshots();
fundamentals = list_entry->mutable_fundamentals();
list_entry->set_name("prosperous-spadefish");
fundamentals->set_snapshot_name("snapshot2");
fundamentals->set_comment("Before restoring snap1\nContains a newline that\r\nshould be truncated");
timestamp.set_seconds(1671840000);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
return list_reply;
}
auto add_petenv_to_reply(mp::ListReply& reply)
{
if (reply.has_instance_list())
{
auto instance = reply.mutable_instance_list()->add_instances();
instance->set_name(petenv_name());
instance->mutable_instance_status()->set_status(mp::InstanceStatus::DELETED);
instance->set_current_release("Not Available");
}
else
{
auto snapshot = reply.mutable_snapshot_list()->add_snapshots();
snapshot->set_name(petenv_name());
snapshot->mutable_fundamentals()->set_snapshot_name("snapshot1");
snapshot->mutable_fundamentals()->set_comment("An exemplary comment");
}
}
auto construct_one_short_line_networks_reply()
{
mp::NetworksReply networks_reply;
// This reply will have strings shorter than the column headers, to test formatting.
auto networks_entry = networks_reply.add_interfaces();
networks_entry->set_name("en0");
networks_entry->set_type("eth");
networks_entry->set_description("Ether");
return networks_reply;
}
auto construct_one_long_line_networks_reply()
{
mp::NetworksReply networks_reply;
// This reply will have strings shorter than the column headers, to test formatting.
auto networks_entry = networks_reply.add_interfaces();
networks_entry->set_name("enp3s0");
networks_entry->set_type("ethernet");
networks_entry->set_description("Amazingly fast and robust ethernet adapter");
return networks_reply;
}
auto construct_multiple_lines_networks_reply()
{
mp::NetworksReply networks_reply = construct_one_short_line_networks_reply();
// This reply will have strings shorter than the column headers, to test formatting.
auto networks_entry = networks_reply.add_interfaces();
networks_entry->set_name("wlx0123456789ab");
networks_entry->set_type("wifi");
networks_entry->set_description("Wireless");
return networks_reply;
}
auto construct_empty_info_snapshot_reply()
{
mp::InfoReply info_reply;
info_reply.set_snapshots(true);
return info_reply;
}
auto construct_single_instance_info_reply()
{
mp::InfoReply info_reply;
auto info_entry = info_reply.add_details();
info_entry->set_name("foo");
info_entry->mutable_instance_status()->set_status(mp::InstanceStatus::RUNNING);
info_entry->mutable_instance_info()->set_image_release("16.04 LTS");
info_entry->mutable_instance_info()->set_id("1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac");
auto mount_info = info_entry->mutable_mount_info();
mount_info->set_longest_path_len(19);
auto mount_entry = mount_info->add_mount_paths();
mount_entry->set_source_path("/home/user/foo");
mount_entry->set_target_path("foo");
auto uid_map_pair = mount_entry->mutable_mount_maps()->add_uid_mappings();
uid_map_pair->set_host_id(1000);
uid_map_pair->set_instance_id(1000);
auto gid_map_pair = mount_entry->mutable_mount_maps()->add_gid_mappings();
gid_map_pair->set_host_id(1000);
gid_map_pair->set_instance_id(1000);
mount_entry = mount_info->add_mount_paths();
mount_entry->set_source_path("/home/user/test_dir");
mount_entry->set_target_path("test_dir");
uid_map_pair = mount_entry->mutable_mount_maps()->add_uid_mappings();
uid_map_pair->set_host_id(1000);
uid_map_pair->set_instance_id(1000);
gid_map_pair = mount_entry->mutable_mount_maps()->add_gid_mappings();
gid_map_pair->set_host_id(1000);
gid_map_pair->set_instance_id(1000);
info_entry->set_cpu_count("1");
info_entry->mutable_instance_info()->set_load("0.45 0.51 0.15");
info_entry->mutable_instance_info()->set_memory_usage("60817408");
info_entry->set_memory_total("1503238554");
info_entry->mutable_instance_info()->set_disk_usage("1288490188");
info_entry->set_disk_total("5153960756");
info_entry->mutable_instance_info()->set_current_release("Ubuntu 16.04.3 LTS");
info_entry->mutable_instance_info()->add_ipv4("10.168.32.2");
info_entry->mutable_instance_info()->add_ipv4("200.3.123.29");
info_entry->mutable_instance_info()->add_ipv6("2001:67c:1562:8007::aac:423a");
info_entry->mutable_instance_info()->add_ipv6("fd52:2ccf:f758:0:a342:79b5:e2ba:e05e");
info_entry->mutable_instance_info()->set_num_snapshots(0);
return info_reply;
}
auto construct_multiple_instances_info_reply()
{
mp::InfoReply info_reply;
auto info_entry = info_reply.add_details();
info_entry->set_name("bogus-instance");
info_entry->mutable_instance_status()->set_status(mp::InstanceStatus::RUNNING);
info_entry->mutable_instance_info()->set_image_release("16.04 LTS");
info_entry->mutable_instance_info()->set_id("1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac");
auto mount_info = info_entry->mutable_mount_info();
mount_info->set_longest_path_len(17);
auto mount_entry = mount_info->add_mount_paths();
mount_entry->set_source_path("/home/user/source");
mount_entry->set_target_path("source");
auto uid_map_pair = mount_entry->mutable_mount_maps()->add_uid_mappings();
uid_map_pair->set_host_id(1000);
uid_map_pair->set_instance_id(501);
auto gid_map_pair = mount_entry->mutable_mount_maps()->add_gid_mappings();
gid_map_pair->set_host_id(1000);
gid_map_pair->set_instance_id(501);
info_entry->set_cpu_count("4");
info_entry->mutable_instance_info()->set_load("0.03 0.10 0.15");
info_entry->mutable_instance_info()->set_memory_usage("38797312");
info_entry->set_memory_total("1610612736");
info_entry->mutable_instance_info()->set_disk_usage("1932735284");
info_entry->set_disk_total("6764573492");
info_entry->mutable_instance_info()->set_current_release("Ubuntu 16.04.3 LTS");
info_entry->mutable_instance_info()->add_ipv4("10.21.124.56");
info_entry->mutable_instance_info()->set_num_snapshots(1);
info_entry = info_reply.add_details();
info_entry->set_name("bombastic");
info_entry->mutable_instance_status()->set_status(mp::InstanceStatus::STOPPED);
info_entry->mutable_instance_info()->set_image_release("18.04 LTS");
info_entry->mutable_instance_info()->set_id("ab5191cc172564e7cc0eafd397312a32598823e645279c820f0935393aead509");
info_entry->mutable_instance_info()->set_num_snapshots(3);
return info_reply;
}
auto construct_single_snapshot_info_reply()
{
mp::InfoReply info_reply;
auto info_entry = info_reply.add_details();
auto fundamentals = info_entry->mutable_snapshot_info()->mutable_fundamentals();
info_entry->set_name("bogus-instance");
info_entry->set_cpu_count("2");
info_entry->set_disk_total("4.9GiB");
info_entry->set_memory_total("0.9GiB");
fundamentals->set_snapshot_name("snapshot2");
fundamentals->set_parent("snapshot1");
fundamentals->set_comment("This is a comment with some\nnew\r\nlines.");
info_entry->mutable_snapshot_info()->set_size("128MiB");
info_entry->mutable_snapshot_info()->add_children("snapshot3");
info_entry->mutable_snapshot_info()->add_children("snapshot4");
auto mount_entry = info_entry->mutable_mount_info()->add_mount_paths();
mount_entry->set_source_path("/home/user/source");
mount_entry->set_target_path("source");
mount_entry = info_entry->mutable_mount_info()->add_mount_paths();
mount_entry->set_source_path("/home/user");
mount_entry->set_target_path("Home");
google::protobuf::Timestamp timestamp;
timestamp.set_seconds(63108020);
timestamp.set_nanos(21000000);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
return info_reply;
}
auto construct_multiple_snapshots_info_reply()
{
mp::InfoReply info_reply;
auto info_entry = info_reply.add_details();
auto fundamentals = info_entry->mutable_snapshot_info()->mutable_fundamentals();
info_entry->set_name("messier-87");
info_entry->set_cpu_count("1");
info_entry->set_disk_total("1024GiB");
info_entry->set_memory_total("128GiB");
fundamentals->set_snapshot_name("black-hole");
fundamentals->set_comment("Captured by EHT");
google::protobuf::Timestamp timestamp;
timestamp.set_seconds(1554897599);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
info_entry = info_reply.add_details();
fundamentals = info_entry->mutable_snapshot_info()->mutable_fundamentals();
info_entry->set_name("bogus-instance");
info_entry->set_cpu_count("2");
info_entry->set_disk_total("4.9GiB");
info_entry->set_memory_total("0.9GiB");
fundamentals->set_snapshot_name("snapshot2");
fundamentals->set_parent("snapshot1");
info_entry->mutable_snapshot_info()->add_children("snapshot3");
info_entry->mutable_snapshot_info()->add_children("snapshot4");
auto mount_entry = info_entry->mutable_mount_info()->add_mount_paths();
mount_entry->set_source_path("/home/user/source");
mount_entry->set_target_path("source");
mount_entry = info_entry->mutable_mount_info()->add_mount_paths();
mount_entry->set_source_path("/home/user");
mount_entry->set_target_path("Home");
timestamp.set_seconds(63108020);
timestamp.set_nanos(21000000);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
return info_reply;
}
auto construct_mixed_instance_and_snapshot_info_reply()
{
mp::InfoReply info_reply;
auto info_entry = info_reply.add_details();
auto fundamentals = info_entry->mutable_snapshot_info()->mutable_fundamentals();
info_entry->set_name("bogus-instance");
info_entry->set_cpu_count("2");
info_entry->set_disk_total("4.9GiB");
info_entry->set_memory_total("0.9GiB");
fundamentals->set_snapshot_name("snapshot2");
fundamentals->set_parent("snapshot1");
info_entry->mutable_snapshot_info()->add_children("snapshot3");
info_entry->mutable_snapshot_info()->add_children("snapshot4");
auto mount_entry = info_entry->mutable_mount_info()->add_mount_paths();
mount_entry->set_source_path("/home/user/source");
mount_entry->set_target_path("source");
mount_entry = info_entry->mutable_mount_info()->add_mount_paths();
mount_entry->set_source_path("/home/user");
mount_entry->set_target_path("Home");
google::protobuf::Timestamp timestamp;
timestamp.set_seconds(63108020);
timestamp.set_nanos(21000000);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
info_entry = info_reply.add_details();
info_entry->set_name("bombastic");
info_entry->mutable_instance_status()->set_status(mp::InstanceStatus::STOPPED);
info_entry->mutable_instance_info()->set_image_release("18.04 LTS");
info_entry->mutable_instance_info()->set_id("ab5191cc172564e7cc0eafd397312a32598823e645279c820f0935393aead509");
info_entry->mutable_instance_info()->set_num_snapshots(3);
return info_reply;
}
auto construct_multiple_mixed_instances_and_snapshots_info_reply()
{
mp::InfoReply info_reply;
auto info_entry = info_reply.add_details();
info_entry->set_name("bogus-instance");
info_entry->mutable_instance_status()->set_status(mp::InstanceStatus::RUNNING);
info_entry->mutable_instance_info()->set_image_release("16.04 LTS");
info_entry->mutable_instance_info()->set_id("1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac");
auto mount_info = info_entry->mutable_mount_info();
mount_info->set_longest_path_len(17);
auto mount_entry = mount_info->add_mount_paths();
mount_entry->set_source_path("/home/user/source");
mount_entry->set_target_path("source");
auto uid_map_pair = mount_entry->mutable_mount_maps()->add_uid_mappings();
uid_map_pair->set_host_id(1000);
uid_map_pair->set_instance_id(501);
auto gid_map_pair = mount_entry->mutable_mount_maps()->add_gid_mappings();
gid_map_pair->set_host_id(1000);
gid_map_pair->set_instance_id(501);
info_entry->set_cpu_count("4");
info_entry->mutable_instance_info()->set_load("0.03 0.10 0.15");
info_entry->mutable_instance_info()->set_memory_usage("38797312");
info_entry->set_memory_total("1610612736");
info_entry->mutable_instance_info()->set_disk_usage("1932735284");
info_entry->set_disk_total("6764573492");
info_entry->mutable_instance_info()->set_current_release("Ubuntu 16.04.3 LTS");
info_entry->mutable_instance_info()->add_ipv4("10.21.124.56");
info_entry->mutable_instance_info()->set_num_snapshots(2);
info_entry = info_reply.add_details();
auto fundamentals = info_entry->mutable_snapshot_info()->mutable_fundamentals();
info_entry->set_name("bogus-instance");
info_entry->set_cpu_count("2");
info_entry->set_disk_total("4.9GiB");
info_entry->set_memory_total("0.9GiB");
fundamentals->set_snapshot_name("snapshot2");
fundamentals->set_parent("snapshot1");
info_entry->mutable_snapshot_info()->add_children("snapshot3");
info_entry->mutable_snapshot_info()->add_children("snapshot4");
mount_entry = info_entry->mutable_mount_info()->add_mount_paths();
mount_entry->set_source_path("/home/user/source");
mount_entry->set_target_path("source");
mount_entry = info_entry->mutable_mount_info()->add_mount_paths();
mount_entry->set_source_path("/home/user");
mount_entry->set_target_path("Home");
google::protobuf::Timestamp timestamp;
timestamp.set_seconds(63108020);
timestamp.set_nanos(21000000);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
info_entry = info_reply.add_details();
fundamentals = info_entry->mutable_snapshot_info()->mutable_fundamentals();
info_entry->set_name("bogus-instance");
info_entry->set_cpu_count("2");
info_entry->set_disk_total("4.9GiB");
info_entry->set_memory_total("0.9GiB");
fundamentals->set_snapshot_name("snapshot1");
timestamp.set_seconds(63107999);
timestamp.set_nanos(21000000);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
info_entry = info_reply.add_details();
info_entry->set_name("bombastic");
info_entry->mutable_instance_status()->set_status(mp::InstanceStatus::STOPPED);
info_entry->mutable_instance_info()->set_image_release("18.04 LTS");
info_entry->mutable_instance_info()->set_id("ab5191cc172564e7cc0eafd397312a32598823e645279c820f0935393aead509");
info_entry->mutable_instance_info()->set_num_snapshots(3);
info_entry = info_reply.add_details();
fundamentals = info_entry->mutable_snapshot_info()->mutable_fundamentals();
info_entry->set_name("messier-87");
info_entry->set_cpu_count("1");
info_entry->set_disk_total("1024GiB");
info_entry->set_memory_total("128GiB");
fundamentals->set_snapshot_name("black-hole");
fundamentals->set_comment("Captured by EHT");
timestamp.set_seconds(1554897599);
timestamp.set_nanos(0);
fundamentals->mutable_creation_timestamp()->CopyFrom(timestamp);
return info_reply;
}
auto add_petenv_to_reply(mp::InfoReply& reply, bool csv_format, bool snapshots)
{
if ((csv_format && !snapshots) || !csv_format)
{
auto entry = reply.add_details();
entry->set_name(petenv_name());
entry->mutable_instance_status()->set_status(mp::InstanceStatus::SUSPENDED);
entry->mutable_instance_info()->set_image_release("18.10");
entry->mutable_instance_info()->set_id("1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd");
}
if ((csv_format && snapshots) || !csv_format)
{
auto entry = reply.add_details();
entry->set_name(petenv_name());
entry->mutable_snapshot_info()->mutable_fundamentals()->set_snapshot_name("snapshot1");
}
}
auto construct_empty_reply()
{
auto reply = mp::FindReply();
reply.set_show_blueprints(true);
reply.set_show_images(true);
return reply;
}
auto construct_empty_reply_only_images()
{
auto reply = mp::FindReply();
reply.set_show_images(true);
return reply;
}
auto construct_empty_reply_only_blueprints()
{
auto reply = mp::FindReply();
reply.set_show_blueprints(true);
return reply;
}
auto construct_find_one_reply()
{
auto reply = mp::FindReply();
reply.set_show_images(true);
auto image_entry = reply.add_images_info();
image_entry->set_os("Ubuntu");
image_entry->set_release("18.04 LTS");
image_entry->set_version("20190516");
auto alias_entry = image_entry->add_aliases_info();
alias_entry->set_alias("ubuntu");
return reply;
}
auto construct_find_one_blueprint_reply()
{
auto reply = mp::FindReply();
reply.set_show_blueprints(true);
reply.set_show_images(true);
auto blueprint_entry = reply.add_blueprints_info();
blueprint_entry->set_release("Anbox Cloud Appliance");
blueprint_entry->set_version("latest");
auto alias_entry = blueprint_entry->add_aliases_info();
alias_entry->set_alias("anbox-cloud-appliance");
return reply;
}
auto construct_find_one_reply_no_os()
{
auto reply = mp::FindReply();
reply.set_show_blueprints(true);
reply.set_show_images(true);
auto image_entry = reply.add_images_info();
image_entry->set_release("Snapcraft builder for core18");
image_entry->set_version("20190520");
auto alias_entry = image_entry->add_aliases_info();
alias_entry->set_alias("core18");
alias_entry->set_remote_name("snapcraft");
return reply;
}
auto construct_find_multiple_reply()
{
auto reply = mp::FindReply();
reply.set_show_blueprints(true);
reply.set_show_images(true);
auto blueprint_entry = reply.add_blueprints_info();
blueprint_entry->set_release("Anbox Cloud Appliance");
blueprint_entry->set_version("latest");
auto alias_entry = blueprint_entry->add_aliases_info();
alias_entry->set_alias("anbox-cloud-appliance");
auto image_entry = reply.add_images_info();
image_entry->set_os("Ubuntu");
image_entry->set_release("18.04 LTS");
image_entry->set_version("20190516");
alias_entry = image_entry->add_aliases_info();
alias_entry->set_alias("ubuntu");
alias_entry = image_entry->add_aliases_info();
alias_entry->set_alias("lts");
image_entry = reply.add_images_info();
image_entry->set_os("Ubuntu");
image_entry->set_release("19.10");
image_entry->set_version("20190516");
alias_entry = image_entry->add_aliases_info();
alias_entry->set_alias("19.10");
alias_entry->set_remote_name("daily");
alias_entry = image_entry->add_aliases_info();
alias_entry->set_alias("eoan");
alias_entry->set_remote_name("daily");
alias_entry = image_entry->add_aliases_info();
alias_entry->set_alias("devel");
alias_entry->set_remote_name("daily");
return reply;
}
auto construct_find_multiple_reply_duplicate_image()
{
auto reply = mp::FindReply();
reply.set_show_blueprints(true);
reply.set_show_images(true);
auto image_entry = reply.add_images_info();
image_entry->set_os("Ubuntu");
image_entry->set_release("Core 18");
image_entry->set_version("20190520");
auto alias_entry = image_entry->add_aliases_info();
alias_entry->set_alias("core18");
image_entry = reply.add_images_info();
image_entry->set_release("Snapcraft builder for core18");
image_entry->set_version("20190520");
alias_entry = image_entry->add_aliases_info();
alias_entry->set_alias("core18");
alias_entry->set_remote_name("snapcraft");
return reply;
}
auto construct_version_info_multipassd_update_available()
{
auto reply = mp::VersionReply();
reply.set_version("Daemon version");
reply.mutable_update_info()->set_version("update version number");
reply.mutable_update_info()->set_title("update title information");
reply.mutable_update_info()->set_description("update description information");
reply.mutable_update_info()->set_url("http://multipass.web");
return reply;
}
auto construct_version_info_multipassd_up_to_date()
{
auto reply = mp::VersionReply();
reply.set_version("Daemon version");
return reply;
}
class BaseFormatterSuite : public testing::Test
{
public:
BaseFormatterSuite() : saved_locale{std::locale()}
{
// The tests expected output are for the default C locale
std::locale::global(std::locale("C"));
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return("pet"));
// Timestamps in tests need to be in a consistent locale
EXPECT_CALL(mock_format_utils, convert_to_user_locale(_)).WillRepeatedly([](const auto timestamp) {
return google::protobuf::util::TimeUtil::ToString(timestamp);
});
}
~BaseFormatterSuite()
{
std::locale::global(saved_locale);
}
protected:
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject<StrictMock>();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
mpt::MockFormatUtils::GuardedMock mock_format_utils_injection = mpt::MockFormatUtils::inject<NiceMock>();
mpt::MockFormatUtils& mock_format_utils = *mock_format_utils_injection.first;
private:
std::locale saved_locale;
};
typedef std::tuple<const mp::Formatter*, const ::google::protobuf::Message*, std::string /* output */,
std::string /* test name */>
FormatterParamType;
struct FormatterSuite : public BaseFormatterSuite, public WithParamInterface<FormatterParamType>
{
};
auto print_param_name(const testing::TestParamInfo<FormatterSuite::ParamType>& info)
{
return std::get<3>(info.param);
}
struct PetenvFormatterSuite : public BaseFormatterSuite,
public WithParamInterface<std::tuple<QString, bool, FormatterParamType>>
{
};
auto print_petenv_param_name(const testing::TestParamInfo<PetenvFormatterSuite::ParamType>& info)
{
const auto param_name = std::get<3>(std::get<2>(info.param));
const auto petenv_name = std::get<0>(info.param);
const auto prepend = std::get<1>(info.param);
return fmt::format("{}_{}_{}", param_name, petenv_name.isEmpty() ? "default" : petenv_name,
prepend ? "prepend" : "append");
}
const mp::TableFormatter table_formatter;
const mp::JsonFormatter json_formatter;
const mp::CSVFormatter csv_formatter;
const mp::YamlFormatter yaml_formatter;
const auto empty_list_reply = construct_empty_list_reply();
const auto empty_list_snapshot_reply = construct_empty_list_snapshot_reply();
const auto single_instance_list_reply = construct_single_instance_list_reply();
const auto multiple_instances_list_reply = construct_multiple_instances_list_reply();
const auto unsorted_list_reply = construct_unsorted_list_reply();
const auto single_snapshot_list_reply = construct_single_snapshot_list_reply();
const auto multiple_snapshots_list_reply = construct_multiple_snapshots_list_reply();
const auto empty_networks_reply = mp::NetworksReply();
const auto one_short_line_networks_reply = construct_one_short_line_networks_reply();
const auto one_long_line_networks_reply = construct_one_long_line_networks_reply();
const auto multiple_lines_networks_reply = construct_multiple_lines_networks_reply();
const auto empty_info_reply = mp::InfoReply();
const auto empty_info_snapshot_reply = construct_empty_info_snapshot_reply();
const auto single_instance_info_reply = construct_single_instance_info_reply();
const auto multiple_instances_info_reply = construct_multiple_instances_info_reply();
const auto single_snapshot_info_reply = construct_single_snapshot_info_reply();
const auto multiple_snapshots_info_reply = construct_multiple_snapshots_info_reply();
const auto mixed_instance_and_snapshot_info_reply = construct_mixed_instance_and_snapshot_info_reply();
const auto multiple_mixed_instances_and_snapshots_info_reply =
construct_multiple_mixed_instances_and_snapshots_info_reply();
const std::vector<FormatterParamType> orderable_list_info_formatter_outputs{
{&table_formatter, &empty_list_reply, "No instances found.\n", "table_list_empty"},
{&table_formatter, &empty_list_snapshot_reply, "No snapshots found.\n", "table_list_snapshot_empty"},
{&table_formatter,
&single_instance_list_reply,
"Name State IPv4 Image\n"
"foo Running 10.168.32.2 Ubuntu 16.04 LTS\n"
" 200.3.123.30\n",
"table_list_single"},
{&table_formatter,
&multiple_instances_list_reply,
"Name State IPv4 Image\n"
"bogus-instance Running 10.21.124.56 Ubuntu 16.04 LTS\n"
"bombastic Stopped -- Ubuntu 18.04 LTS\n",
"table_list_multiple"},
{&table_formatter,
&unsorted_list_reply,
"Name State IPv4 Image\n"
"trusty-190611-1529 Deleted -- Not Available\n"
"trusty-190611-1535 Stopped -- Ubuntu N/A\n"
"trusty-190611-1539 Suspended -- Not Available\n"
"trusty-190611-1542 Running -- Ubuntu N/A\n",
"table_list_unsorted"},
{&table_formatter,
&single_snapshot_list_reply,
"Instance Snapshot Parent Comment\n"
"foo snapshot1 -- This is a sample comment\n",
"table_list_single_snapshot"},
{&table_formatter,
&multiple_snapshots_list_reply,
"Instance Snapshot Parent Comment\n"
"hale-roller pristine -- A first snapshot\n"
"hale-roller rocking pristine A very long comment that should be truncated by t…\n"
"hale-roller rolling pristine Loaded with stuff\n"
"prosperous-spadefish snapshot2 -- Before restoring snap1…\n"
"prosperous-spadefish snapshot10 snapshot2 --\n",
"table_list_multiple_snapshots"},
{&table_formatter, &empty_info_reply, "No instances found.\n", "table_info_empty"},
{&table_formatter, &empty_info_snapshot_reply, "No snapshots found.\n", "table_info_snapshot_empty"},
{&table_formatter,
&single_instance_info_reply,
"Name: foo\n"
"State: Running\n"
"Snapshots: 0\n"
"IPv4: 10.168.32.2\n"
" 200.3.123.29\n"
"IPv6: 2001:67c:1562:8007::aac:423a\n"
" fd52:2ccf:f758:0:a342:79b5:e2ba:e05e\n"
"Release: Ubuntu 16.04.3 LTS\n"
"Image hash: 1797c5c82016 (Ubuntu 16.04 LTS)\n"
"CPU(s): 1\n"
"Load: 0.45 0.51 0.15\n"
"Disk usage: 1.2GiB out of 4.8GiB\n"
"Memory usage: 58.0MiB out of 1.4GiB\n"
"Mounts: /home/user/foo => foo\n"
" UID map: 1000:1000\n"
" GID map: 1000:1000\n"
" /home/user/test_dir => test_dir\n"
" UID map: 1000:1000\n"
" GID map: 1000:1000\n",
"table_info_single_instance"},
{&table_formatter,
&multiple_instances_info_reply,
"Name: bogus-instance\n"
"State: Running\n"
"Snapshots: 1\n"
"IPv4: 10.21.124.56\n"
"Release: Ubuntu 16.04.3 LTS\n"
"Image hash: 1797c5c82016 (Ubuntu 16.04 LTS)\n"
"CPU(s): 4\n"
"Load: 0.03 0.10 0.15\n"
"Disk usage: 1.8GiB out of 6.3GiB\n"
"Memory usage: 37.0MiB out of 1.5GiB\n"
"Mounts: /home/user/source => source\n"
" UID map: 1000:501\n"
" GID map: 1000:501\n\n"
"Name: bombastic\n"
"State: Stopped\n"
"Snapshots: 3\n"
"IPv4: --\n"
"Release: --\n"
"Image hash: ab5191cc1725 (Ubuntu 18.04 LTS)\n"
"CPU(s): --\n"
"Load: --\n"
"Disk usage: --\n"
"Memory usage: --\n"
"Mounts: --\n",
"table_info_multiple_instances"},
{&table_formatter,
&single_snapshot_info_reply,
"Snapshot: snapshot2\n"
"Instance: bogus-instance\n"
"Size: 128MiB\n"
"CPU(s): 2\n"
"Disk space: 4.9GiB\n"
"Memory size: 0.9GiB\n"
"Mounts: /home/user/source => source\n"
" /home/user => Home\n"
"Created: 1972-01-01T10:00:20.021Z\n"
"Parent: snapshot1\n"
"Children: snapshot3\n"
" snapshot4\n"
"Comment: This is a comment with some\n"
" new\r\n"
" lines.\n",
"table_info_single_snapshot"},
{&table_formatter,
&multiple_snapshots_info_reply,
"Snapshot: snapshot2\n"
"Instance: bogus-instance\n"
"CPU(s): 2\n"
"Disk space: 4.9GiB\n"
"Memory size: 0.9GiB\n"
"Mounts: /home/user/source => source\n"
" /home/user => Home\n"
"Created: 1972-01-01T10:00:20.021Z\n"
"Parent: snapshot1\n"
"Children: snapshot3\n"
" snapshot4\n"
"Comment: --\n\n"
"Snapshot: black-hole\n"
"Instance: messier-87\n"
"CPU(s): 1\n"
"Disk space: 1024GiB\n"
"Memory size: 128GiB\n"
"Mounts: --\n"
"Created: 2019-04-10T11:59:59Z\n"
"Parent: --\n"
"Children: --\n"
"Comment: Captured by EHT\n",
"table_info_multiple_snapshots"},
{&table_formatter,
&mixed_instance_and_snapshot_info_reply,
"Name: bombastic\n"
"State: Stopped\n"
"Snapshots: 3\n"
"IPv4: --\n"
"Release: --\n"
"Image hash: ab5191cc1725 (Ubuntu 18.04 LTS)\n"
"CPU(s): --\n"
"Load: --\n"
"Disk usage: --\n"
"Memory usage: --\n"
"Mounts: --\n\n"
"Snapshot: snapshot2\n"
"Instance: bogus-instance\n"
"CPU(s): 2\n"
"Disk space: 4.9GiB\n"
"Memory size: 0.9GiB\n"
"Mounts: /home/user/source => source\n"
" /home/user => Home\n"
"Created: 1972-01-01T10:00:20.021Z\n"
"Parent: snapshot1\n"
"Children: snapshot3\n"
" snapshot4\n"
"Comment: --\n",
"table_info_mixed_instance_and_snapshot"},
{&table_formatter,
&multiple_mixed_instances_and_snapshots_info_reply,
"Name: bogus-instance\n"
"State: Running\n"
"Snapshots: 2\n"
"IPv4: 10.21.124.56\n"
"Release: Ubuntu 16.04.3 LTS\n"
"Image hash: 1797c5c82016 (Ubuntu 16.04 LTS)\n"
"CPU(s): 4\n"
"Load: 0.03 0.10 0.15\n"
"Disk usage: 1.8GiB out of 6.3GiB\n"
"Memory usage: 37.0MiB out of 1.5GiB\n"
"Mounts: /home/user/source => source\n"
" UID map: 1000:501\n"
" GID map: 1000:501\n\n"
"Name: bombastic\n"
"State: Stopped\n"
"Snapshots: 3\n"
"IPv4: --\n"
"Release: --\n"
"Image hash: ab5191cc1725 (Ubuntu 18.04 LTS)\n"
"CPU(s): --\n"
"Load: --\n"
"Disk usage: --\n"
"Memory usage: --\n"
"Mounts: --\n\n"
"Snapshot: snapshot1\n"
"Instance: bogus-instance\n"
"CPU(s): 2\n"
"Disk space: 4.9GiB\n"
"Memory size: 0.9GiB\n"
"Mounts: --\n"
"Created: 1972-01-01T09:59:59.021Z\n"
"Parent: --\n"
"Children: --\n"
"Comment: --\n\n"
"Snapshot: snapshot2\n"
"Instance: bogus-instance\n"
"CPU(s): 2\n"
"Disk space: 4.9GiB\n"
"Memory size: 0.9GiB\n"
"Mounts: /home/user/source => source\n"
" /home/user => Home\n"
"Created: 1972-01-01T10:00:20.021Z\n"
"Parent: snapshot1\n"
"Children: snapshot3\n"
" snapshot4\n"
"Comment: --\n\n"
"Snapshot: black-hole\n"
"Instance: messier-87\n"
"CPU(s): 1\n"
"Disk space: 1024GiB\n"
"Memory size: 128GiB\n"
"Mounts: --\n"
"Created: 2019-04-10T11:59:59Z\n"
"Parent: --\n"
"Children: --\n"
"Comment: Captured by EHT\n",
"table_info_multiple_mixed_instances_and_snapshots"},
{&csv_formatter, &empty_list_reply, "Name,State,IPv4,IPv6,Release,AllIPv4\n", "csv_list_empty"},
{&csv_formatter,
&single_instance_list_reply,
"Name,State,IPv4,IPv6,Release,AllIPv4\n"
"foo,Running,10.168.32.2,fdde:2681:7a2::4ca,Ubuntu 16.04 LTS,\"10.168.32.2,200.3.123.30\"\n",
"csv_list_single"},
{&csv_formatter,
&multiple_instances_list_reply,
"Name,State,IPv4,IPv6,Release,AllIPv4\n"
"bogus-instance,Running,10.21.124.56,,Ubuntu 16.04 LTS,\"10.21.124.56\"\n"
"bombastic,Stopped,,,Ubuntu 18.04 LTS,\"\"\n",
"csv_list_multiple"},
{&csv_formatter,
&unsorted_list_reply,
"Name,State,IPv4,IPv6,Release,AllIPv4\n"
"trusty-190611-1529,Deleted,,,Not Available,\"\"\n"
"trusty-190611-1535,Stopped,,,Ubuntu N/A,\"\"\n"
"trusty-190611-1539,Suspended,,,Not Available,\"\"\n"
"trusty-190611-1542,Running,,,Ubuntu N/A,\"\"\n",
"csv_list_unsorted"},
{&csv_formatter, &empty_list_snapshot_reply, "Instance,Snapshot,Parent,Comment\n", "csv_list_snapshot_empty"},
{&csv_formatter,
&single_snapshot_list_reply,
"Instance,Snapshot,Parent,Comment\nfoo,snapshot1,,\"This is a sample comment\"\n",
"csv_list_single_snapshot"},
{&csv_formatter,
&multiple_snapshots_list_reply,
"Instance,Snapshot,Parent,Comment\nhale-roller,pristine,,\"A first "
"snapshot\"\nhale-roller,rocking,pristine,\"A very long comment that should be truncated by the table "
"formatter\"\nhale-roller,rolling,pristine,\"Loaded with stuff\"\nprosperous-spadefish,snapshot2,,\"Before "
"restoring snap1\nContains a newline that\r\nshould be "
"truncated\"\nprosperous-spadefish,snapshot10,snapshot2,\"\"\n",
"csv_list_multiple_snapshots"},
{&csv_formatter, &empty_info_reply, "", "csv_info_empty"},
{&csv_formatter,
&single_instance_info_reply,
"Name,State,Ipv4,Ipv6,Release,Image hash,Image release,Load,Disk usage,Disk total,Memory "
"usage,Memory total,Mounts,AllIPv4,CPU(s),Snapshots\nfoo,Running,10.168.32.2,2001:67c:1562:8007::aac:423a,Ubuntu "
"16.04.3 "
"LTS,1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac,16.04 LTS,0.45 0.51 "
"0.15,1288490188,5153960756,60817408,1503238554,/home/user/foo => foo;/home/user/test_dir "
"=> test_dir,10.168.32.2;200.3.123.29,1,0\n",
"csv_info_single_instance"},
{&csv_formatter,
&single_snapshot_info_reply,
"Snapshot,Instance,CPU(s),Disk space,Memory "
"size,Mounts,Created,Parent,Children,Comment\nsnapshot2,bogus-instance,2,4.9GiB,0.9GiB,/home/user/source "
"=> "
"source;/home/user => Home,1972-01-01T10:00:20.021Z,snapshot1,snapshot3;snapshot4,\"This is a comment with "
"some\nnew\r\nlines.\"\n",
"csv_info_single_snapshot_info_reply"},
{&csv_formatter,
&multiple_snapshots_info_reply,
"Snapshot,Instance,CPU(s),Disk space,Memory "
"size,Mounts,Created,Parent,Children,Comment\nsnapshot2,bogus-instance,2,4.9GiB,0.9GiB,/home/user/source => "
"source;/home/user => "
"Home,1972-01-01T10:00:20.021Z,snapshot1,snapshot3;snapshot4,\"\"\nblack-hole,messier-87,1,1024GiB,128GiB,,"
"2019-04-10T11:59:59Z,,,\"Captured by EHT\"\n",
"csv_info_multiple_snapshot_info_reply"},
{&csv_formatter,
&multiple_instances_info_reply,
"Name,State,Ipv4,Ipv6,Release,Image hash,Image release,Load,Disk usage,Disk total,Memory "
"usage,Memory total,Mounts,AllIPv4,CPU(s),Snapshots\nbogus-instance,Running,10.21.124.56,,Ubuntu 16.04.3 "
"LTS,1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac,16.04 LTS,0.03 0.10 "
"0.15,1932735284,6764573492,38797312,1610612736,/home/user/source => "
"source,10.21.124.56,4,1\nbombastic,Stopped,,,,"
"ab5191cc172564e7cc0eafd397312a32598823e645279c820f0935393aead509,18.04 LTS,,,,,,,,,3\n",
"csv_info_multiple_instances"},
{&yaml_formatter, &empty_list_reply, "\n", "yaml_list_empty"},
{&yaml_formatter,
&single_instance_list_reply,
"foo:\n"
" - state: Running\n"
" ipv4:\n"
" - 10.168.32.2\n"
" - 200.3.123.30\n"
" release: Ubuntu 16.04 LTS\n",
"yaml_list_single"},
{&yaml_formatter,
&multiple_instances_list_reply,
"bogus-instance:\n"
" - state: Running\n"
" ipv4:\n"
" - 10.21.124.56\n"
" release: Ubuntu 16.04 LTS\n"
"bombastic:\n"
" - state: Stopped\n"
" ipv4:\n"
" []\n"
" release: Ubuntu 18.04 LTS\n",
"yaml_list_multiple"},
{&yaml_formatter,
&unsorted_list_reply,
"trusty-190611-1529:\n"
" - state: Deleted\n"
" ipv4:\n"
" []\n"
" release: Not Available\n"
"trusty-190611-1535:\n"
" - state: Stopped\n"
" ipv4:\n"
" []\n"
" release: Ubuntu N/A\n"
"trusty-190611-1539:\n"
" - state: Suspended\n"
" ipv4:\n"
" []\n"
" release: Not Available\n"
"trusty-190611-1542:\n"
" - state: Running\n"
" ipv4:\n"
" []\n"
" release: Ubuntu N/A\n",
"yaml_list_unsorted"},
{&yaml_formatter, &empty_list_snapshot_reply, "\n", "yaml_list_snapshot_empty"},
{&yaml_formatter,
&single_snapshot_list_reply,
"foo:\n"
" - snapshot1:\n"
" - parent: ~\n"
" comment: This is a sample comment\n",
"yaml_list_single_snapshot"},
{&yaml_formatter,
&multiple_snapshots_list_reply,
"hale-roller:\n"
" - pristine:\n"
" - parent: ~\n"
" comment: A first snapshot\n"
" - rocking:\n"
" - parent: pristine\n"
" comment: A very long comment that should be truncated by the table formatter\n"
" - rolling:\n"
" - parent: pristine\n"
" comment: Loaded with stuff\n"
"prosperous-spadefish:\n"
" - snapshot2:\n"
" - parent: ~\n"
" comment: \"Before restoring snap1\\nContains a newline that\\r\\nshould be truncated\"\n"
" - snapshot10:\n"
" - parent: snapshot2\n"
" comment: ~\n",
"yaml_list_multiple_snapshots"},
{&yaml_formatter, &empty_info_reply, "errors:\n - ~\n", "yaml_info_empty"},
{&yaml_formatter,
&single_instance_info_reply,
"errors:\n"
" - ~\n"
"foo:\n"
" - state: Running\n"
" snapshot_count: 0\n"
" image_hash: 1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac\n"
" image_release: 16.04 LTS\n"
" release: Ubuntu 16.04.3 LTS\n"
" cpu_count: 1\n"
" load:\n"
" - 0.45\n"
" - 0.51\n"
" - 0.15\n"
" disks:\n"
" - sda1:\n"
" used: 1288490188\n"
" total: 5153960756\n"
" memory:\n"
" usage: 60817408\n"
" total: 1503238554\n"
" ipv4:\n"
" - 10.168.32.2\n"
" - 200.3.123.29\n"
" mounts:\n"
" foo:\n"
" uid_mappings:\n"
" - \"1000:1000\"\n"
" gid_mappings:\n"
" - \"1000:1000\"\n"
" source_path: /home/user/foo\n"
" test_dir:\n"
" uid_mappings:\n"
" - \"1000:1000\"\n"
" gid_mappings:\n"
" - \"1000:1000\"\n"
" source_path: /home/user/test_dir\n",
"yaml_info_single_instance"},
{&yaml_formatter,
&multiple_instances_info_reply,
"errors:\n"
" - ~\n"
"bogus-instance:\n"
" - state: Running\n"
" snapshot_count: 1\n"
" image_hash: 1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac\n"
" image_release: 16.04 LTS\n"
" release: Ubuntu 16.04.3 LTS\n"
" cpu_count: 4\n"
" load:\n"
" - 0.03\n"
" - 0.10\n"
" - 0.15\n"
" disks:\n"
" - sda1:\n"
" used: 1932735284\n"
" total: 6764573492\n"
" memory:\n"
" usage: 38797312\n"
" total: 1610612736\n"
" ipv4:\n"
" - 10.21.124.56\n"
" mounts:\n"
" source:\n"
" uid_mappings:\n"
" - \"1000:501\"\n"
" gid_mappings:\n"
" - \"1000:501\"\n"
" source_path: /home/user/source\n"
"bombastic:\n"
" - state: Stopped\n"
" snapshot_count: 3\n"
" image_hash: ab5191cc172564e7cc0eafd397312a32598823e645279c820f0935393aead509\n"
" image_release: 18.04 LTS\n"
" release: ~\n"
" cpu_count: ~\n"
" disks:\n"
" - sda1:\n"
" used: ~\n"
" total: ~\n"
" memory:\n"
" usage: ~\n"
" total: ~\n"
" ipv4:\n"
" []\n"
" mounts: ~\n",
"yaml_info_multiple_instances"},
{&yaml_formatter,
&single_snapshot_info_reply,
"errors:\n"
" - ~\n"
"bogus-instance:\n"
" - snapshots:\n"
" - snapshot2:\n"
" size: 128MiB\n"
" cpu_count: 2\n"
" disk_space: 4.9GiB\n"
" memory_size: 0.9GiB\n"
" mounts:\n"
" source:\n"
" source_path: /home/user/source\n"
" Home:\n"
" source_path: /home/user\n"
" created: \"1972-01-01T10:00:20.021Z\"\n"
" parent: snapshot1\n"
" children:\n"
" - snapshot3\n"
" - snapshot4\n"
" comment: \"This is a comment with some\\nnew\\r\\nlines.\"\n",
"yaml_info_single_snapshot_info_reply"},
{&yaml_formatter,
&multiple_snapshots_info_reply,
"errors:\n"
" - ~\n"
"bogus-instance:\n"
" - snapshots:\n"
" - snapshot2:\n"
" size: ~\n"
" cpu_count: 2\n"
" disk_space: 4.9GiB\n"
" memory_size: 0.9GiB\n"
" mounts:\n"
" source:\n"
" source_path: /home/user/source\n"
" Home:\n"
" source_path: /home/user\n"
" created: \"1972-01-01T10:00:20.021Z\"\n"
" parent: snapshot1\n"
" children:\n"
" - snapshot3\n"
" - snapshot4\n"
" comment: ~\n"
"messier-87:\n"
" - snapshots:\n"
" - black-hole:\n"
" size: ~\n"
" cpu_count: 1\n"
" disk_space: 1024GiB\n"
" memory_size: 128GiB\n"
" mounts: ~\n"
" created: \"2019-04-10T11:59:59Z\"\n"
" parent: ~\n"
" children:\n"
" []\n"
" comment: Captured by EHT\n",
"yaml_info_multiple_snapshots_info_reply"},
{&yaml_formatter,
&mixed_instance_and_snapshot_info_reply,
"errors:\n"
" - ~\n"
"bombastic:\n"
" - state: Stopped\n"
" snapshot_count: 3\n"
" image_hash: ab5191cc172564e7cc0eafd397312a32598823e645279c820f0935393aead509\n"
" image_release: 18.04 LTS\n"
" release: ~\n"
" cpu_count: ~\n"
" disks:\n"
" - sda1:\n"
" used: ~\n"
" total: ~\n"
" memory:\n"
" usage: ~\n"
" total: ~\n"
" ipv4:\n"
" []\n"
" mounts: ~\n"
"bogus-instance:\n"
" - snapshots:\n"
" - snapshot2:\n"
" size: ~\n"
" cpu_count: 2\n"
" disk_space: 4.9GiB\n"
" memory_size: 0.9GiB\n"
" mounts:\n"
" source:\n"
" source_path: /home/user/source\n"
" Home:\n"
" source_path: /home/user\n"
" created: \"1972-01-01T10:00:20.021Z\"\n"
" parent: snapshot1\n"
" children:\n"
" - snapshot3\n"
" - snapshot4\n"
" comment: ~\n",
"yaml_info_mixed_instance_and_snapshot_info_reply"},
{&yaml_formatter,
&multiple_mixed_instances_and_snapshots_info_reply,
"errors:\n"
" - ~\n"
"bogus-instance:\n"
" - state: Running\n"
" snapshot_count: 2\n"
" image_hash: 1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac\n"
" image_release: 16.04 LTS\n"
" release: Ubuntu 16.04.3 LTS\n"
" cpu_count: 4\n"
" load:\n"
" - 0.03\n"
" - 0.10\n"
" - 0.15\n"
" disks:\n"
" - sda1:\n"
" used: 1932735284\n"
" total: 6764573492\n"
" memory:\n"
" usage: 38797312\n"
" total: 1610612736\n"
" ipv4:\n"
" - 10.21.124.56\n"
" mounts:\n"
" source:\n"
" uid_mappings:\n"
" - \"1000:501\"\n"
" gid_mappings:\n"
" - \"1000:501\"\n"
" source_path: /home/user/source\n"
" snapshots:\n"
" - snapshot1:\n"
" size: ~\n"
" cpu_count: 2\n"
" disk_space: 4.9GiB\n"
" memory_size: 0.9GiB\n"
" mounts: ~\n"
" created: \"1972-01-01T09:59:59.021Z\"\n"
" parent: ~\n"
" children:\n"
" []\n"
" comment: ~\n"
" - snapshot2:\n"
" size: ~\n"
" cpu_count: 2\n"
" disk_space: 4.9GiB\n"
" memory_size: 0.9GiB\n"
" mounts:\n"
" source:\n"
" source_path: /home/user/source\n"
" Home:\n"
" source_path: /home/user\n"
" created: \"1972-01-01T10:00:20.021Z\"\n"
" parent: snapshot1\n"
" children:\n"
" - snapshot3\n"
" - snapshot4\n"
" comment: ~\n"
"bombastic:\n"
" - state: Stopped\n"
" snapshot_count: 3\n"
" image_hash: ab5191cc172564e7cc0eafd397312a32598823e645279c820f0935393aead509\n"
" image_release: 18.04 LTS\n"
" release: ~\n"
" cpu_count: ~\n"
" disks:\n"
" - sda1:\n"
" used: ~\n"
" total: ~\n"
" memory:\n"
" usage: ~\n"
" total: ~\n"
" ipv4:\n"
" []\n"
" mounts: ~\n"
"messier-87:\n"
" - snapshots:\n"
" - black-hole:\n"
" size: ~\n"
" cpu_count: 1\n"
" disk_space: 1024GiB\n"
" memory_size: 128GiB\n"
" mounts: ~\n"
" created: \"2019-04-10T11:59:59Z\"\n"
" parent: ~\n"
" children:\n"
" []\n"
" comment: Captured by EHT\n",
"yaml_info_multiple_mixed_instances_and_snapshots"}};
const std::vector<FormatterParamType> non_orderable_list_info_formatter_outputs{
{&json_formatter,
&empty_list_reply,
"{\n"
" \"list\": [\n"
" ]\n"
"}\n",
"json_list_empty"},
{&json_formatter,
&single_instance_list_reply,
"{\n"
" \"list\": [\n"
" {\n"
" \"ipv4\": [\n"
" \"10.168.32.2\",\n"
" \"200.3.123.30\"\n"
" ],\n"
" \"name\": \"foo\",\n"
" \"release\": \"Ubuntu 16.04 LTS\",\n"
" \"state\": \"Running\"\n"
" }\n"
" ]\n"
"}\n",
"json_list_single"},
{&json_formatter,
&multiple_instances_list_reply,
"{\n"
" \"list\": [\n"
" {\n"
" \"ipv4\": [\n"
" \"10.21.124.56\"\n"
" ],\n"
" \"name\": \"bogus-instance\",\n"
" \"release\": \"Ubuntu 16.04 LTS\",\n"
" \"state\": \"Running\"\n"
" },\n"
" {\n"
" \"ipv4\": [\n"
" ],\n"
" \"name\": \"bombastic\",\n"
" \"release\": \"Ubuntu 18.04 LTS\",\n"
" \"state\": \"Stopped\"\n"
" }\n"
" ]\n"
"}\n",
"json_list_multiple"},
{&json_formatter,
&single_snapshot_list_reply,
"{\n"
" \"errors\": [\n"
" ],\n"
" \"info\": {\n"
" \"foo\": {\n"
" \"snapshot1\": {\n"
" \"comment\": \"This is a sample comment\",\n"
" \"parent\": \"\"\n"
" }\n"
" }\n"
" }\n"
"}\n",
"json_list_single_snapshot"},
{&json_formatter,
&multiple_snapshots_list_reply,
"{\n"
" \"errors\": [\n"
" ],\n"
" \"info\": {\n"
" \"hale-roller\": {\n"
" \"pristine\": {\n"
" \"comment\": \"A first snapshot\",\n"
" \"parent\": \"\"\n"
" },\n"
" \"rocking\": {\n"
" \"comment\": \"A very long comment that should be truncated by the table formatter\",\n"
" \"parent\": \"pristine\"\n"
" },\n"
" \"rolling\": {\n"
" \"comment\": \"Loaded with stuff\",\n"
" \"parent\": \"pristine\"\n"
" }\n"
" },\n"
" \"prosperous-spadefish\": {\n"
" \"snapshot10\": {\n"
" \"comment\": \"\",\n"
" \"parent\": \"snapshot2\"\n"
" },\n"
" \"snapshot2\": {\n"
" \"comment\": \"Before restoring snap1\\nContains a newline that\\r\\nshould be truncated\",\n"
" \"parent\": \"\"\n"
" }\n"
" }\n"
" }\n"
"}\n",
"json_list_multiple_snapshots"},
{&json_formatter,
&empty_info_reply,
"{\n"
" \"errors\": [\n"
" ],\n"
" \"info\": {\n"
" }\n"
"}\n",
"json_info_empty"},
{&json_formatter,
&single_instance_info_reply,
"{\n"
" \"errors\": [\n"
" ],\n"
" \"info\": {\n"
" \"foo\": {\n"
" \"cpu_count\": \"1\",\n"
" \"disks\": {\n"
" \"sda1\": {\n"
" \"total\": \"5153960756\",\n"
" \"used\": \"1288490188\"\n"
" }\n"
" },\n"
" \"image_hash\": \"1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac\",\n"
" \"image_release\": \"16.04 LTS\",\n"
" \"ipv4\": [\n"
" \"10.168.32.2\",\n"
" \"200.3.123.29\"\n"
" ],\n"
" \"load\": [\n"
" 0.45,\n"
" 0.51,\n"
" 0.15\n"
" ],\n"
" \"memory\": {\n"
" \"total\": 1503238554,\n"
" \"used\": 60817408\n"
" },\n"
" \"mounts\": {\n"
" \"foo\": {\n"
" \"gid_mappings\": [\n"
" \"1000:1000\"\n"
" ],\n"
" \"source_path\": \"/home/user/foo\",\n"
" \"uid_mappings\": [\n"
" \"1000:1000\"\n"
" ]\n"
" },\n"
" \"test_dir\": {\n"
" \"gid_mappings\": [\n"
" \"1000:1000\"\n"
" ],\n"
" \"source_path\": \"/home/user/test_dir\",\n"
" \"uid_mappings\": [\n"
" \"1000:1000\"\n"
" ]\n"
" }\n"
" },\n"
" \"release\": \"Ubuntu 16.04.3 LTS\",\n"
" \"snapshot_count\": \"0\",\n"
" \"state\": \"Running\"\n"
" }\n"
" }\n"
"}\n",
"json_info_single_instance"},
{&json_formatter,
&multiple_instances_info_reply,
"{\n"
" \"errors\": [\n"
" ],\n"
" \"info\": {\n"
" \"bogus-instance\": {\n"
" \"cpu_count\": \"4\",\n"
" \"disks\": {\n"
" \"sda1\": {\n"
" \"total\": \"6764573492\",\n"
" \"used\": \"1932735284\"\n"
" }\n"
" },\n"
" \"image_hash\": \"1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac\",\n"
" \"image_release\": \"16.04 LTS\",\n"
" \"ipv4\": [\n"
" \"10.21.124.56\"\n"
" ],\n"
" \"load\": [\n"
" 0.03,\n"
" 0.1,\n"
" 0.15\n"
" ],\n"
" \"memory\": {\n"
" \"total\": 1610612736,\n"
" \"used\": 38797312\n"
" },\n"
" \"mounts\": {\n"
" \"source\": {\n"
" \"gid_mappings\": [\n"
" \"1000:501\"\n"
" ],\n"
" \"source_path\": \"/home/user/source\",\n"
" \"uid_mappings\": [\n"
" \"1000:501\"\n"
" ]\n"
" }\n"
" },\n"
" \"release\": \"Ubuntu 16.04.3 LTS\",\n"
" \"snapshot_count\": \"1\",\n"
" \"state\": \"Running\"\n"
" },\n"
" \"bombastic\": {\n"
" \"cpu_count\": \"\",\n"
" \"disks\": {\n"
" \"sda1\": {\n"
" }\n"
" },\n"
" \"image_hash\": \"ab5191cc172564e7cc0eafd397312a32598823e645279c820f0935393aead509\",\n"
" \"image_release\": \"18.04 LTS\",\n"
" \"ipv4\": [\n"
" ],\n"
" \"load\": [\n"
" ],\n"
" \"memory\": {\n"
" },\n"
" \"mounts\": {\n"
" },\n"
" \"release\": \"\",\n"
" \"snapshot_count\": \"3\",\n"
" \"state\": \"Stopped\"\n"
" }\n"
" }\n"
"}\n",
"json_info_multiple_instances"},
{&json_formatter,
&single_snapshot_info_reply,
"{\n"
" \"errors\": [\n"
" ],\n"
" \"info\": {\n"
" \"bogus-instance\": {\n"
" \"snapshots\": {\n"
" \"snapshot2\": {\n"
" \"children\": [\n"
" \"snapshot3\",\n"
" \"snapshot4\"\n"
" ],\n"
" \"comment\": \"This is a comment with some\\nnew\\r\\nlines.\",\n"
" \"cpu_count\": \"2\",\n"
" \"created\": \"1972-01-01T10:00:20.021Z\",\n"
" \"disk_space\": \"4.9GiB\",\n"
" \"memory_size\": \"0.9GiB\",\n"
" \"mounts\": {\n"
" \"Home\": {\n"
" \"source_path\": \"/home/user\"\n"
" },\n"
" \"source\": {\n"
" \"source_path\": \"/home/user/source\"\n"
" }\n"
" },\n"
" \"parent\": \"snapshot1\",\n"
" \"size\": \"128MiB\"\n"
" }\n"
" }\n"
" }\n"
" }\n"
"}\n",
"json_info_single_snapshot_info_reply"},
{&json_formatter,
&multiple_snapshots_info_reply,
"{\n"
" \"errors\": [\n"
" ],\n"
" \"info\": {\n"
" \"bogus-instance\": {\n"
" \"snapshots\": {\n"
" \"snapshot2\": {\n"
" \"children\": [\n"
" \"snapshot3\",\n"
" \"snapshot4\"\n"
" ],\n"
" \"comment\": \"\",\n"
" \"cpu_count\": \"2\",\n"
" \"created\": \"1972-01-01T10:00:20.021Z\",\n"
" \"disk_space\": \"4.9GiB\",\n"
" \"memory_size\": \"0.9GiB\",\n"
" \"mounts\": {\n"
" \"Home\": {\n"
" \"source_path\": \"/home/user\"\n"
" },\n"
" \"source\": {\n"
" \"source_path\": \"/home/user/source\"\n"
" }\n"
" },\n"
" \"parent\": \"snapshot1\",\n"
" \"size\": \"\"\n"
" }\n"
" }\n"
" },\n"
" \"messier-87\": {\n"
" \"snapshots\": {\n"
" \"black-hole\": {\n"
" \"children\": [\n"
" ],\n"
" \"comment\": \"Captured by EHT\",\n"
" \"cpu_count\": \"1\",\n"
" \"created\": \"2019-04-10T11:59:59Z\",\n"
" \"disk_space\": \"1024GiB\",\n"
" \"memory_size\": \"128GiB\",\n"
" \"mounts\": {\n"
" },\n"
" \"parent\": \"\",\n"
" \"size\": \"\"\n"
" }\n"
" }\n"
" }\n"
" }\n"
"}\n",
"json_info_multiple_snapshots_info_reply"},
{&json_formatter,
&mixed_instance_and_snapshot_info_reply,
"{\n"
" \"errors\": [\n"
" ],\n"
" \"info\": {\n"
" \"bogus-instance\": {\n"
" \"snapshots\": {\n"
" \"snapshot2\": {\n"
" \"children\": [\n"
" \"snapshot3\",\n"
" \"snapshot4\"\n"
" ],\n"
" \"comment\": \"\",\n"
" \"cpu_count\": \"2\",\n"
" \"created\": \"1972-01-01T10:00:20.021Z\",\n"
" \"disk_space\": \"4.9GiB\",\n"
" \"memory_size\": \"0.9GiB\",\n"
" \"mounts\": {\n"
" \"Home\": {\n"
" \"source_path\": \"/home/user\"\n"
" },\n"
" \"source\": {\n"
" \"source_path\": \"/home/user/source\"\n"
" }\n"
" },\n"
" \"parent\": \"snapshot1\",\n"
" \"size\": \"\"\n"
" }\n"
" }\n"
" },\n"
" \"bombastic\": {\n"
" \"cpu_count\": \"\",\n"
" \"disks\": {\n"
" \"sda1\": {\n"
" }\n"
" },\n"
" \"image_hash\": \"ab5191cc172564e7cc0eafd397312a32598823e645279c820f0935393aead509\",\n"
" \"image_release\": \"18.04 LTS\",\n"
" \"ipv4\": [\n"
" ],\n"
" \"load\": [\n"
" ],\n"
" \"memory\": {\n"
" },\n"
" \"mounts\": {\n"
" },\n"
" \"release\": \"\",\n"
" \"snapshot_count\": \"3\",\n"
" \"state\": \"Stopped\"\n"
" }\n"
" }\n"
"}\n",
"json_info_mixed_instance_and_snapshot_info_reply"},
{&json_formatter,
&multiple_mixed_instances_and_snapshots_info_reply,
"{\n"
" \"errors\": [\n"
" ],\n"
" \"info\": {\n"
" \"bogus-instance\": {\n"
" \"cpu_count\": \"4\",\n"
" \"disks\": {\n"
" \"sda1\": {\n"
" \"total\": \"6764573492\",\n"
" \"used\": \"1932735284\"\n"
" }\n"
" },\n"
" \"image_hash\": \"1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac\",\n"
" \"image_release\": \"16.04 LTS\",\n"
" \"ipv4\": [\n"
" \"10.21.124.56\"\n"
" ],\n"
" \"load\": [\n"
" 0.03,\n"
" 0.1,\n"
" 0.15\n"
" ],\n"
" \"memory\": {\n"
" \"total\": 1610612736,\n"
" \"used\": 38797312\n"
" },\n"
" \"mounts\": {\n"
" \"source\": {\n"
" \"gid_mappings\": [\n"
" \"1000:501\"\n"
" ],\n"
" \"source_path\": \"/home/user/source\",\n"
" \"uid_mappings\": [\n"
" \"1000:501\"\n"
" ]\n"
" }\n"
" },\n"
" \"release\": \"Ubuntu 16.04.3 LTS\",\n"
" \"snapshot_count\": \"2\",\n"
" \"snapshots\": {\n"
" \"snapshot1\": {\n"
" \"children\": [\n"
" ],\n"
" \"comment\": \"\",\n"
" \"cpu_count\": \"2\",\n"
" \"created\": \"1972-01-01T09:59:59.021Z\",\n"
" \"disk_space\": \"4.9GiB\",\n"
" \"memory_size\": \"0.9GiB\",\n"
" \"mounts\": {\n"
" },\n"
" \"parent\": \"\",\n"
" \"size\": \"\"\n"
" },\n"
" \"snapshot2\": {\n"
" \"children\": [\n"
" \"snapshot3\",\n"
" \"snapshot4\"\n"
" ],\n"
" \"comment\": \"\",\n"
" \"cpu_count\": \"2\",\n"
" \"created\": \"1972-01-01T10:00:20.021Z\",\n"
" \"disk_space\": \"4.9GiB\",\n"
" \"memory_size\": \"0.9GiB\",\n"
" \"mounts\": {\n"
" \"Home\": {\n"
" \"source_path\": \"/home/user\"\n"
" },\n"
" \"source\": {\n"
" \"source_path\": \"/home/user/source\"\n"
" }\n"
" },\n"
" \"parent\": \"snapshot1\",\n"
" \"size\": \"\"\n"
" }\n"
" },\n"
" \"state\": \"Running\"\n"
" },\n"
" \"bombastic\": {\n"
" \"cpu_count\": \"\",\n"
" \"disks\": {\n"
" \"sda1\": {\n"
" }\n"
" },\n"
" \"image_hash\": \"ab5191cc172564e7cc0eafd397312a32598823e645279c820f0935393aead509\",\n"
" \"image_release\": \"18.04 LTS\",\n"
" \"ipv4\": [\n"
" ],\n"
" \"load\": [\n"
" ],\n"
" \"memory\": {\n"
" },\n"
" \"mounts\": {\n"
" },\n"
" \"release\": \"\",\n"
" \"snapshot_count\": \"3\",\n"
" \"state\": \"Stopped\"\n"
" },\n"
" \"messier-87\": {\n"
" \"snapshots\": {\n"
" \"black-hole\": {\n"
" \"children\": [\n"
" ],\n"
" \"comment\": \"Captured by EHT\",\n"
" \"cpu_count\": \"1\",\n"
" \"created\": \"2019-04-10T11:59:59Z\",\n"
" \"disk_space\": \"1024GiB\",\n"
" \"memory_size\": \"128GiB\",\n"
" \"mounts\": {\n"
" },\n"
" \"parent\": \"\",\n"
" \"size\": \"\"\n"
" }\n"
" }\n"
" }\n"
" }\n"
"}\n",
"json_info_multiple_mixed_instances_and_snapshots"}};
const std::vector<FormatterParamType> non_orderable_networks_formatter_outputs{
{&table_formatter, &empty_networks_reply, "No network interfaces found.\n", "table_networks_empty"},
{&table_formatter,
&one_short_line_networks_reply,
"Name Type Description\n"
"en0 eth Ether\n",
"table_networks_one_short_line"},
{&table_formatter,
&one_long_line_networks_reply,
"Name Type Description\n"
"enp3s0 ethernet Amazingly fast and robust ethernet adapter\n",
"table_networks_one_long_line"},
{&table_formatter,
&multiple_lines_networks_reply,
"Name Type Description\n"
"en0 eth Ether\n"
"wlx0123456789ab wifi Wireless\n",
"table_networks_multiple_lines"},
{&csv_formatter, &empty_networks_reply, "Name,Type,Description\n", "csv_networks_empty"},
{&csv_formatter,
&one_short_line_networks_reply,
"Name,Type,Description\n"
"en0,eth,\"Ether\"\n",
"csv_networks_one_short_line"},
{&csv_formatter,
&one_long_line_networks_reply,
"Name,Type,Description\n"
"enp3s0,ethernet,\"Amazingly fast and robust ethernet adapter\"\n",
"csv_networks_one_long_line"},
{&csv_formatter,
&multiple_lines_networks_reply,
"Name,Type,Description\n"
"en0,eth,\"Ether\"\n"
"wlx0123456789ab,wifi,\"Wireless\"\n",
"csv_networks_multiple_lines"},
{&yaml_formatter, &empty_networks_reply, "\n", "yaml_networks_empty"},
{&yaml_formatter,
&one_short_line_networks_reply,
"en0:\n"
" - type: eth\n"
" description: Ether\n",
"yaml_networks_one_short_line"},
{&yaml_formatter,
&one_long_line_networks_reply,
"enp3s0:\n"
" - type: ethernet\n"
" description: Amazingly fast and robust ethernet adapter\n",
"yaml_networks_one_long_line"},
{&yaml_formatter,
&multiple_lines_networks_reply,
"en0:\n"
" - type: eth\n"
" description: Ether\n"
"wlx0123456789ab:\n"
" - type: wifi\n"
" description: Wireless\n",
"yaml_networks_multiple_lines"},
{&json_formatter,
&empty_networks_reply,
"{\n"
" \"list\": [\n"
" ]\n"
"}\n",
"json_networks_empty"},
{&json_formatter,
&one_short_line_networks_reply,
"{\n"
" \"list\": [\n"
" {\n"
" \"description\": \"Ether\",\n"
" \"name\": \"en0\",\n"
" \"type\": \"eth\"\n"
" }\n"
" ]\n"
"}\n",
"json_networks_one_short_line"},
{&json_formatter,
&one_long_line_networks_reply,
"{\n"
" \"list\": [\n"
" {\n"
" \"description\": \"Amazingly fast and robust ethernet adapter\",\n"
" \"name\": \"enp3s0\",\n"
" \"type\": \"ethernet\"\n"
" }\n"
" ]\n"
"}\n",
"json_networks_one_long_line"},
{&json_formatter,
&multiple_lines_networks_reply,
"{\n"
" \"list\": [\n"
" {\n"
" \"description\": \"Ether\",\n"
" \"name\": \"en0\",\n"
" \"type\": \"eth\"\n"
" },\n"
" {\n"
" \"description\": \"Wireless\",\n"
" \"name\": \"wlx0123456789ab\",\n"
" \"type\": \"wifi\"\n"
" }\n"
" ]\n"
"}\n",
"json_networks_multiple_lines"}};
const auto empty_find_reply = construct_empty_reply();
const auto empty_find_reply_only_images = construct_empty_reply_only_images();
const auto empty_find_reply_only_blueprints = construct_empty_reply_only_blueprints();
const auto find_one_reply = construct_find_one_reply();
const auto find_one_blueprint_reply = construct_find_one_blueprint_reply();
const auto find_multiple_reply = construct_find_multiple_reply();
const auto find_one_reply_no_os = construct_find_one_reply_no_os();
const auto find_multiple_reply_duplicate_image = construct_find_multiple_reply_duplicate_image();
const auto json_empty_find_reply = "{\n"
" \"blueprints\": {\n"
" },\n"
" \"errors\": [\n"
" ],\n"
" \"images\": {\n"
" }\n"
"}\n";
const auto csv_empty_find_reply = "Image,Remote,Aliases,OS,Release,Version,Type\n";
const auto yaml_empty_find_reply = "errors:\n"
" []\n"
"blueprints:\n"
" {}\n"
"images:\n"
" {}\n";
const std::vector<FormatterParamType> find_formatter_outputs{
{&table_formatter, &empty_find_reply, "No images or blueprints found.\n", "table_find_empty"},
{&table_formatter, &empty_find_reply_only_images, "No images found.\n", "table_find_empty_only_images"},
{&table_formatter, &empty_find_reply_only_blueprints, "No blueprints found.\n", "table_find_empty_only_blueprints"},
{&table_formatter, &find_one_reply,
"Image Aliases Version Description\n"
"ubuntu 20190516 Ubuntu 18.04 LTS\n"
"\n",
"table_find_one_image"},
{&table_formatter, &find_one_blueprint_reply,
"Blueprint Aliases Version Description\n"
"anbox-cloud-appliance latest Anbox Cloud Appliance\n"
"\n",
"table_find_one_blueprint"},
{&table_formatter, &find_multiple_reply,
"Image Aliases Version Description\n"
"lts 20190516 Ubuntu 18.04 LTS\n"
"daily:19.10 eoan,devel 20190516 Ubuntu 19.10\n"
"\n"
"Blueprint Aliases Version Description\n"
"anbox-cloud-appliance latest Anbox Cloud Appliance\n"
"\n",
"table_find_multiple"},
{&table_formatter, &find_one_reply_no_os,
"Image Aliases Version Description\n"
"snapcraft:core18 20190520 Snapcraft builder for core18\n"
"\n",
"table_find_no_os"},
{&table_formatter, &find_multiple_reply_duplicate_image,
"Image Aliases Version Description\n"
"core18 20190520 Ubuntu Core 18\n"
"snapcraft:core18 20190520 Snapcraft builder for core18\n"
"\n",
"table_find_multiple_duplicate_image"},
{&json_formatter, &empty_find_reply, json_empty_find_reply, "json_find_empty"},
{&json_formatter, &empty_find_reply_only_images, json_empty_find_reply, "json_find_empty_only_images"},
{&json_formatter, &empty_find_reply_only_blueprints, json_empty_find_reply, "json_find_empty_only_blueprints"},
{&json_formatter, &find_one_reply,
"{\n"
" \"blueprints\": {\n"
" },\n"
" \"errors\": [\n"
" ],\n"
" \"images\": {\n"
" \"ubuntu\": {\n"
" \"aliases\": [\n"
" ],\n"
" \"os\": \"Ubuntu\",\n"
" \"release\": \"18.04 LTS\",\n"
" \"remote\": \"\",\n"
" \"version\": \"20190516\"\n"
" }\n"
" }\n"
"}\n",
"json_find_one"},
{&json_formatter, &find_one_blueprint_reply,
"{\n"
" \"blueprints\": {\n"
" \"anbox-cloud-appliance\": {\n"
" \"aliases\": [\n"
" ],\n"
" \"os\": \"\",\n"
" \"release\": \"Anbox Cloud Appliance\",\n"
" \"remote\": \"\",\n"
" \"version\": \"latest\"\n"
" }\n"
" },\n"
" \"errors\": [\n"
" ],\n"
" \"images\": {\n"
" }\n"
"}\n",
"json_find_one_blueprint"},
{&json_formatter, &find_multiple_reply,
"{\n"
" \"blueprints\": {\n"
" \"anbox-cloud-appliance\": {\n"
" \"aliases\": [\n"
" ],\n"
" \"os\": \"\",\n"
" \"release\": \"Anbox Cloud Appliance\",\n"
" \"remote\": \"\",\n"
" \"version\": \"latest\"\n"
" }\n"
" },\n"
" \"errors\": [\n"
" ],\n"
" \"images\": {\n"
" \"daily:19.10\": {\n"
" \"aliases\": [\n"
" \"eoan\",\n"
" \"devel\"\n"
" ],\n"
" \"os\": \"Ubuntu\",\n"
" \"release\": \"19.10\",\n"
" \"remote\": \"daily\",\n"
" \"version\": \"20190516\"\n"
" },\n"
" \"lts\": {\n"
" \"aliases\": [\n"
" ],\n"
" \"os\": \"Ubuntu\",\n"
" \"release\": \"18.04 LTS\",\n"
" \"remote\": \"\",\n"
" \"version\": \"20190516\"\n"
" }\n"
" }\n"
"}\n",
"json_find_multiple"},
{&json_formatter, &find_multiple_reply_duplicate_image,
"{\n"
" \"blueprints\": {\n"
" },\n"
" \"errors\": [\n"
" ],\n"
" \"images\": {\n"
" \"core18\": {\n"
" \"aliases\": [\n"
" ],\n"
" \"os\": \"Ubuntu\",\n"
" \"release\": \"Core 18\",\n"
" \"remote\": \"\",\n"
" \"version\": \"20190520\"\n"
" },\n"
" \"snapcraft:core18\": {\n"
" \"aliases\": [\n"
" ],\n"
" \"os\": \"\",\n"
" \"release\": \"Snapcraft builder for core18\",\n"
" \"remote\": \"snapcraft\",\n"
" \"version\": \"20190520\"\n"
" }\n"
" }\n"
"}\n",
"json_find_multiple_duplicate_image"},
{&csv_formatter, &empty_find_reply, csv_empty_find_reply, "csv_find_empty"},
{&csv_formatter, &empty_find_reply_only_images, csv_empty_find_reply, "csv_find_empty_only_images"},
{&csv_formatter, &empty_find_reply_only_blueprints, csv_empty_find_reply, "csv_find_empty_only_blueprints"},
{&csv_formatter, &find_one_reply,
"Image,Remote,Aliases,OS,Release,Version,Type\n"
"ubuntu,,,Ubuntu,18.04 LTS,20190516,Cloud Image\n",
"csv_find_one"},
{&csv_formatter, &find_one_blueprint_reply,
"Image,Remote,Aliases,OS,Release,Version,Type\n"
"anbox-cloud-appliance,,,,Anbox Cloud Appliance,latest,Blueprint\n",
"csv_find_one_blueprint"},
{&csv_formatter, &find_multiple_reply,
"Image,Remote,Aliases,OS,Release,Version,Type\n"
"lts,,,Ubuntu,18.04 LTS,20190516,Cloud Image\n"
"daily:19.10,daily,eoan;devel,Ubuntu,19.10,20190516,Cloud Image\n"
"anbox-cloud-appliance,,,,Anbox Cloud Appliance,latest,Blueprint\n",
"csv_find_multiple"},
{&csv_formatter, &find_multiple_reply_duplicate_image,
"Image,Remote,Aliases,OS,Release,Version,Type\n"
"core18,,,Ubuntu,Core 18,20190520,Cloud Image\n"
"snapcraft:core18,snapcraft,,,Snapcraft builder for core18,20190520,Cloud Image\n",
"csv_find_multiple_duplicate_image"},
{&yaml_formatter, &empty_find_reply, yaml_empty_find_reply, "yaml_find_empty"},
{&yaml_formatter, &empty_find_reply_only_images, yaml_empty_find_reply, "yaml_find_empty_only_images"},
{&yaml_formatter, &empty_find_reply_only_blueprints, yaml_empty_find_reply, "yaml_find_empty_only_blueprints"},
{&yaml_formatter, &find_one_reply,
"errors:\n"
" []\n"
"blueprints:\n"
" {}\n"
"images:\n"
" ubuntu:\n"
" aliases:\n"
" []\n"
" os: Ubuntu\n"
" release: 18.04 LTS\n"
" version: 20190516\n"
" remote: \"\"\n",
"yaml_find_one"},
{&yaml_formatter, &find_one_blueprint_reply,
"errors:\n"
" []\n"
"blueprints:\n"
" anbox-cloud-appliance:\n"
" aliases:\n"
" []\n"
" os: \"\"\n"
" release: Anbox Cloud Appliance\n"
" version: latest\n"
" remote: \"\"\n"
"images:\n"
" {}\n",
"yaml_find_one_blueprint"},
{&yaml_formatter, &find_multiple_reply,
"errors:\n"
" []\n"
"blueprints:\n"
" anbox-cloud-appliance:\n"
" aliases:\n"
" []\n"
" os: \"\"\n"
" release: Anbox Cloud Appliance\n"
" version: latest\n"
" remote: \"\"\n"
"images:\n"
" \"daily:19.10\":\n"
" aliases:\n"
" - eoan\n"
" - devel\n"
" os: Ubuntu\n"
" release: 19.10\n"
" version: 20190516\n"
" remote: daily\n"
" lts:\n"
" aliases:\n"
" []\n"
" os: Ubuntu\n"
" release: 18.04 LTS\n"
" version: 20190516\n"
" remote: \"\"\n",
"yaml_find_multiple"},
{&yaml_formatter, &find_multiple_reply_duplicate_image,
"errors:\n"
" []\n"
"blueprints:\n"
" {}\n"
"images:\n"
" core18:\n"
" aliases:\n"
" []\n"
" os: Ubuntu\n"
" release: Core 18\n"
" version: 20190520\n"
" remote: \"\"\n"
" \"snapcraft:core18\":\n"
" aliases:\n"
" []\n"
" os: \"\"\n"
" release: Snapcraft builder for core18\n"
" version: 20190520\n"
" remote: snapcraft\n",
"yaml_find_multiple_duplicate_image"}};
const auto version_client_reply = mp::VersionReply();
const auto version_daemon_no_update_reply = construct_version_info_multipassd_up_to_date();
const auto version_daemon_update_reply = construct_version_info_multipassd_update_available();
const std::vector<FormatterParamType> version_formatter_outputs{
{&table_formatter, &version_client_reply, "multipass Client version\n", "table_version_client"},
{&table_formatter, &version_daemon_no_update_reply,
"multipass Client version\n"
"multipassd Daemon version\n",
"table_version_daemon_no_updates"},
{&table_formatter, &version_daemon_update_reply,
"multipass Client version\n"
"multipassd Daemon version\n"
"\n##################################################\n"
"update title information\n"
"update description information\n"
"\nGo here for more information: http://multipass.web\n"
"##################################################\n",
"table_version_daemon_updates"},
{&json_formatter, &version_client_reply,
"{\n"
" \"multipass\": \"Client version\"\n"
"}\n",
"json_version_client"},
{&json_formatter, &version_daemon_no_update_reply,
"{\n"
" \"multipass\": \"Client version\",\n"
" \"multipassd\": \"Daemon version\"\n"
"}\n",
"json_version_daemon_no_updates"},
{&json_formatter, &version_daemon_update_reply,
"{\n"
" \"multipass\": \"Client version\",\n"
" \"multipassd\": \"Daemon version\",\n"
" \"update\": {\n"
" \"description\": \"update description information\",\n"
" \"title\": \"update title information\",\n"
" \"url\": \"http://multipass.web\"\n"
" }\n"
"}\n",
"json_version_daemon_updates"},
{&csv_formatter, &version_client_reply,
"Multipass,Multipassd,Title,Description,URL\n"
"Client version,,,,\n",
"csv_version_client"},
{&csv_formatter, &version_daemon_no_update_reply,
"Multipass,Multipassd,Title,Description,URL\n"
"Client version,Daemon version,,,\n",
"csv_version_daemon_no_updates"},
{&csv_formatter, &version_daemon_update_reply,
"Multipass,Multipassd,Title,Description,URL\n"
"Client version,Daemon version,update title information,update description information,http://multipass.web\n",
"csv_version_daemon_updates"},
{&yaml_formatter, &version_client_reply, "multipass: Client version\n", "yaml_version_client"},
{&yaml_formatter, &version_daemon_no_update_reply,
"multipass: Client version\n"
"multipassd: Daemon version\n",
"yaml_version_daemon_no_updates"},
{&yaml_formatter, &version_daemon_update_reply,
"multipass: Client version\n"
"multipassd: Daemon version\n"
"update:\n title: update title information\n"
" description: update description information\n"
" url: \"http://multipass.web\"\n",
"yaml_version_daemon_updates"}};
} // namespace
TEST_P(FormatterSuite, properly_formats_output)
{
const auto& [formatter, reply, expected_output, test_name] = GetParam();
Q_UNUSED(test_name); // gcc 7.4 can't do [[maybe_unused]] for structured bindings
std::string output;
if (auto input = dynamic_cast<const mp::ListReply*>(reply))
output = formatter->format(*input);
else if (auto input = dynamic_cast<const mp::NetworksReply*>(reply))
output = formatter->format(*input);
else if (auto input = dynamic_cast<const mp::InfoReply*>(reply))
output = formatter->format(*input);
else if (auto input = dynamic_cast<const mp::FindReply*>(reply))
output = formatter->format(*input);
else if (auto input = dynamic_cast<const mp::VersionReply*>(reply))
output = formatter->format(*input, "Client version");
else
FAIL() << "Not a supported reply type.";
EXPECT_EQ(output, expected_output);
}
INSTANTIATE_TEST_SUITE_P(OrderableListInfoOutputFormatter, FormatterSuite,
ValuesIn(orderable_list_info_formatter_outputs), print_param_name);
INSTANTIATE_TEST_SUITE_P(NonOrderableListInfoOutputFormatter, FormatterSuite,
ValuesIn(non_orderable_list_info_formatter_outputs), print_param_name);
INSTANTIATE_TEST_SUITE_P(FindOutputFormatter, FormatterSuite, ValuesIn(find_formatter_outputs), print_param_name);
INSTANTIATE_TEST_SUITE_P(NonOrderableNetworksOutputFormatter, FormatterSuite,
ValuesIn(non_orderable_networks_formatter_outputs), print_param_name);
INSTANTIATE_TEST_SUITE_P(VersionInfoOutputFormatter, FormatterSuite, ValuesIn(version_formatter_outputs),
print_param_name);
#if GTEST_HAS_POSIX_RE
TEST_P(PetenvFormatterSuite, pet_env_first_in_output)
{
const auto& [petenv_nname, prepend, param] = GetParam();
const auto& [formatter, reply, expected_output, test_name] = param;
Q_UNUSED(expected_output);
Q_UNUSED(test_name); // gcc 7.4 can't do [[maybe_unused]] for structured bindings
if (!petenv_nname.isEmpty())
{
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return(petenv_nname));
}
std::string output, regex;
if (auto input = dynamic_cast<const mp::ListReply*>(reply))
{
mp::ListReply reply_copy;
if (input->has_instance_list())
reply_copy.mutable_instance_list();
else
reply_copy.mutable_snapshot_list();
if (prepend)
{
add_petenv_to_reply(reply_copy);
reply_copy.MergeFrom(*input);
}
else
{
reply_copy.CopyFrom(*input);
add_petenv_to_reply(reply_copy);
}
output = formatter->format(reply_copy);
if (dynamic_cast<const mp::TableFormatter*>(formatter))
regex = fmt::format("((Name|Instance)[[:print:]]*\n{0}[[:space:]]+.*)", petenv_name());
else if (dynamic_cast<const mp::CSVFormatter*>(formatter))
regex = fmt::format("(Name|Instance)[[:print:]]*\n{},.*", petenv_name());
else if (dynamic_cast<const mp::YamlFormatter*>(formatter))
regex = fmt::format("{}:.*", petenv_name());
else
FAIL() << "Not a supported formatter.";
}
else if (auto input = dynamic_cast<const mp::InfoReply*>(reply))
{
mp::InfoReply reply_copy;
if (prepend)
{
add_petenv_to_reply(reply_copy,
dynamic_cast<const mp::CSVFormatter*>(formatter),
test_name.find("snapshot") != std::string::npos);
reply_copy.MergeFrom(*input);
}
else
{
reply_copy.CopyFrom(*input);
add_petenv_to_reply(reply_copy,
dynamic_cast<const mp::CSVFormatter*>(formatter),
test_name.find("snapshot") != std::string::npos);
}
output = formatter->format(reply_copy);
if (dynamic_cast<const mp::TableFormatter*>(formatter))
regex = fmt::format("(Name:[[:space:]]+{0}.+)"
"(Snapshot:[[:print:]]*\nInstance:[[:space:]]+{0}.+)",
petenv_name());
else if (dynamic_cast<const mp::CSVFormatter*>(formatter))
regex = fmt::format("(Name[[:print:]]*\n{0},.*)|"
"(Snapshot[[:print:]]*\n[[:print:]]*,{0},.*)",
petenv_name());
else if (dynamic_cast<const mp::YamlFormatter*>(formatter))
regex = fmt::format("(errors:[[:space:]]+-[[:space:]]+~[[:space:]]+)?{}:.*", petenv_name());
else
FAIL() << "Not a supported formatter.";
}
else
FAIL() << "Not a supported reply type.";
EXPECT_THAT(output, MatchesRegex(regex));
}
INSTANTIATE_TEST_SUITE_P(PetenvOutputFormatter, PetenvFormatterSuite,
Combine(Values(QStringLiteral(), QStringLiteral("aaa"),
QStringLiteral("zzz")) /* primary name */,
Bool() /* prepend or append */, ValuesIn(orderable_list_info_formatter_outputs)),
print_petenv_param_name);
#endif
| 94,701
|
C++
|
.cpp
| 2,324
| 34.866179
| 120
| 0.529291
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,597
|
test_image_vault.cpp
|
canonical_multipass/tests/test_image_vault.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "disabling_macros.h"
#include "file_operations.h"
#include "mock_image_host.h"
#include "mock_json_utils.h"
#include "mock_logger.h"
#include "mock_process_factory.h"
#include "path.h"
#include "stub_url_downloader.h"
#include "temp_dir.h"
#include "temp_file.h"
#include "tracking_url_downloader.h"
#include <src/daemon/default_vm_image_vault.h>
#include <multipass/exceptions/aborted_download_exception.h>
#include <multipass/exceptions/create_image_exception.h>
#include <multipass/exceptions/image_vault_exceptions.h>
#include <multipass/exceptions/unsupported_image_exception.h>
#include <multipass/format.h>
#include <multipass/query.h>
#include <multipass/url_downloader.h>
#include <multipass/utils.h>
#include <QDateTime>
#include <QThread>
#include <QUrl>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
const QDateTime default_last_modified{QDate(2019, 6, 25), QTime(13, 15, 0)};
struct BadURLDownloader : public mp::URLDownloader
{
BadURLDownloader() : mp::URLDownloader{std::chrono::seconds(10)}
{
}
void download_to(const QUrl& url, const QString& file_name, int64_t size, const int download_type,
const mp::ProgressMonitor&) override
{
mpt::make_file_with_content(file_name, "Bad hash");
}
QByteArray download(const QUrl& url) override
{
return {};
}
};
struct HttpURLDownloader : public mp::URLDownloader
{
HttpURLDownloader() : mp::URLDownloader{std::chrono::seconds(10)}
{
}
void download_to(const QUrl& url, const QString& file_name, int64_t size, const int download_type,
const mp::ProgressMonitor&) override
{
mpt::make_file_with_content(file_name, "");
downloaded_urls << url.toString();
downloaded_files << file_name;
}
QByteArray download(const QUrl& url) override
{
return {};
}
QDateTime last_modified(const QUrl& url) override
{
return default_last_modified;
}
QStringList downloaded_files;
QStringList downloaded_urls;
};
struct RunningURLDownloader : public mp::URLDownloader
{
RunningURLDownloader() : mp::URLDownloader{std::chrono::seconds(10)}
{
}
void download_to(const QUrl& url, const QString& file_name, int64_t size, const int download_type,
const mp::ProgressMonitor&) override
{
while (!abort_downloads)
QThread::yieldCurrentThread();
throw mp::AbortedDownloadException("Aborted!");
}
QByteArray download(const QUrl& url) override
{
return {};
}
};
struct ImageVault : public testing::Test
{
void SetUp()
{
hosts.push_back(&host);
}
QByteArray fake_img_info(const mp::MemorySize& size)
{
return QByteArray::fromStdString(
fmt::format("some\nother\ninfo\nfirst\nvirtual size: {} ({} bytes)\nmore\ninfo\nafter\n",
size.in_gigabytes(), size.in_bytes()));
}
void simulate_qemuimg_info(const mpt::MockProcess* process, const mp::ProcessState& produce_result,
const QByteArray& produce_output = {})
{
ASSERT_EQ(process->program().toStdString(), "qemu-img");
const auto args = process->arguments();
ASSERT_EQ(args.size(), 2);
EXPECT_EQ(args.constFirst(), "info");
EXPECT_CALL(*process, execute).WillOnce(Return(produce_result));
if (produce_result.completed_successfully())
EXPECT_CALL(*process, read_all_standard_output).WillOnce(Return(produce_output));
else if (produce_result.exit_code)
EXPECT_CALL(*process, read_all_standard_error).WillOnce(Return(produce_output));
else
ON_CALL(*process, read_all_standard_error).WillByDefault(Return(produce_output));
}
std::unique_ptr<mp::test::MockProcessFactory::Scope>
inject_fake_qemuimg_callback(const mp::ProcessState& qemuimg_exit_status, const QByteArray& qemuimg_output)
{
std::unique_ptr<mp::test::MockProcessFactory::Scope> mock_factory_scope = mpt::MockProcessFactory::Inject();
mock_factory_scope->register_callback(
[&](mpt::MockProcess* process) { simulate_qemuimg_info(process, qemuimg_exit_status, qemuimg_output); });
return mock_factory_scope;
}
QString host_url{QUrl::fromLocalFile(mpt::test_data_path()).toString()};
mpt::TrackingURLDownloader url_downloader;
std::vector<mp::VMImageHost*> hosts;
NiceMock<mpt::MockImageHost> host;
mpt::MockJsonUtils::GuardedMock mock_json_utils_injection = mpt::MockJsonUtils::inject<NiceMock>();
mpt::MockJsonUtils& mock_json_utils = *mock_json_utils_injection.first;
mp::ProgressMonitor stub_monitor{[](int, int) { return true; }};
mp::VMImageVault::PrepareAction stub_prepare{
[](const mp::VMImage& source_image) -> mp::VMImage { return source_image; }};
mpt::TempDir cache_dir;
mpt::TempDir data_dir;
mpt::TempDir save_dir;
std::string instance_name{"valley-pied-piper"};
QString instance_dir = save_dir.filePath(QString::fromStdString(instance_name));
mp::Query default_query{instance_name, "xenial", false, "", mp::Query::Type::Alias};
};
} // namespace
TEST_F(ImageVault, downloads_image)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
EXPECT_THAT(url_downloader.downloaded_files.size(), Eq(1));
EXPECT_TRUE(url_downloader.downloaded_urls.contains(host.image.url()));
}
TEST_F(ImageVault, returned_image_contains_instance_name)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
EXPECT_TRUE(vm_image.image_path.contains(QString::fromStdString(instance_name)));
}
TEST_F(ImageVault, imageCloneSuccess)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
const std::string dest_name = instance_name + "clone";
EXPECT_NO_THROW(vault.clone(instance_name, dest_name));
EXPECT_TRUE(vault.has_record_for(dest_name));
}
TEST_F(ImageVault, imageCloneFailOnNonExistSrcImage)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
EXPECT_THROW(vault.clone("non_exist_src_image_name", "dummy_dest_name"), std::runtime_error);
}
TEST_F(ImageVault, imageCloneFailOnAlreadyExistDestImage)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
const std::string dest_name = "valley-pied-piper-clone";
const mp::Query second_query{dest_name, "xenial", false, "", mp::Query::Type::Alias};
vault.fetch_image(mp::FetchType::ImageOnly,
second_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
save_dir.filePath(QString::fromStdString(second_query.name)));
// valley-pied-piper-clone is already added, so it will throw
EXPECT_THROW(vault.clone(instance_name, dest_name), std::runtime_error);
}
TEST_F(ImageVault, calls_prepare)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
bool prepare_called{false};
auto prepare = [&prepare_called](const mp::VMImage& source_image) -> mp::VMImage {
prepare_called = true;
return source_image;
};
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
EXPECT_TRUE(prepare_called);
}
TEST_F(ImageVault, records_instanced_images)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
int prepare_called_count{0};
auto prepare = [&prepare_called_count](const mp::VMImage& source_image) -> mp::VMImage {
++prepare_called_count;
return source_image;
};
auto vm_image1 = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
auto vm_image2 = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
EXPECT_THAT(url_downloader.downloaded_files.size(), Eq(1));
EXPECT_THAT(prepare_called_count, Eq(1));
EXPECT_THAT(vm_image1.image_path, Eq(vm_image2.image_path));
EXPECT_THAT(vm_image1.id, Eq(vm_image2.id));
}
TEST_F(ImageVault, caches_prepared_images)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
int prepare_called_count{0};
auto prepare = [&prepare_called_count](const mp::VMImage& source_image) -> mp::VMImage {
++prepare_called_count;
return source_image;
};
auto vm_image1 = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
auto another_query = default_query;
another_query.name = "valley-pied-piper-chat";
auto vm_image2 = vault.fetch_image(mp::FetchType::ImageOnly,
another_query,
prepare,
stub_monitor,
false,
std::nullopt,
save_dir.filePath(QString::fromStdString(another_query.name)));
EXPECT_THAT(url_downloader.downloaded_files.size(), Eq(1));
EXPECT_THAT(prepare_called_count, Eq(1));
EXPECT_THAT(vm_image1.image_path, Ne(vm_image2.image_path));
EXPECT_THAT(vm_image1.id, Eq(vm_image2.id));
}
TEST_F(ImageVault, remembers_instance_images)
{
int prepare_called_count{0};
auto prepare = [&prepare_called_count](const mp::VMImage& source_image) -> mp::VMImage {
++prepare_called_count;
return source_image;
};
EXPECT_CALL(mock_json_utils, write_json).WillRepeatedly([this](auto&&... args) {
return mock_json_utils.JsonUtils::write_json(std::forward<decltype(args)>(args)...); // call the real thing
});
mp::DefaultVMImageVault first_vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image1 = first_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
mp::DefaultVMImageVault another_vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image2 = another_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
EXPECT_THAT(url_downloader.downloaded_files.size(), Eq(1));
EXPECT_THAT(prepare_called_count, Eq(1));
EXPECT_THAT(vm_image1.image_path, Eq(vm_image2.image_path));
}
TEST_F(ImageVault, remembers_prepared_images)
{
int prepare_called_count{0};
auto prepare = [&prepare_called_count](const mp::VMImage& source_image) -> mp::VMImage {
++prepare_called_count;
return source_image;
};
EXPECT_CALL(mock_json_utils, write_json).WillRepeatedly([this](auto&&... args) {
return mock_json_utils.JsonUtils::write_json(std::forward<decltype(args)>(args)...); // call the real thing
});
mp::DefaultVMImageVault first_vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image1 = first_vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
auto another_query = default_query;
another_query.name = "valley-pied-piper-chat";
mp::DefaultVMImageVault another_vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image2 = another_vault.fetch_image(mp::FetchType::ImageOnly,
another_query,
prepare,
stub_monitor,
false,
std::nullopt,
save_dir.filePath(QString::fromStdString(another_query.name)));
EXPECT_THAT(url_downloader.downloaded_files.size(), Eq(1));
EXPECT_THAT(prepare_called_count, Eq(1));
EXPECT_THAT(vm_image1.image_path, Ne(vm_image2.image_path));
EXPECT_THAT(vm_image1.id, Eq(vm_image2.id));
}
TEST_F(ImageVault, uses_image_from_prepare)
{
constexpr auto expected_data = "12345-pied-piper-rats";
QDir dir{cache_dir.path()};
auto file_name = dir.filePath("prepared-image");
mpt::make_file_with_content(file_name, expected_data);
auto prepare = [&file_name](const mp::VMImage& source_image) -> mp::VMImage {
return {file_name, source_image.id, "", "", "", {}};
};
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
const auto image_data = mp::utils::contents_of(vm_image.image_path);
EXPECT_THAT(image_data, StrEq(expected_data));
EXPECT_THAT(vm_image.id, Eq(mpt::default_id));
}
TEST_F(ImageVault, image_purged_expired)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
QDir images_dir{MP_UTILS.make_dir(cache_dir.path(), "images")};
auto file_name = images_dir.filePath("mock_image.img");
auto prepare = [&file_name](const mp::VMImage& source_image) -> mp::VMImage {
mpt::make_file_with_content(file_name);
return {file_name, source_image.id, "", "", "", {}};
};
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
EXPECT_TRUE(QFileInfo::exists(file_name));
vault.prune_expired_images();
EXPECT_FALSE(QFileInfo::exists(file_name));
}
TEST_F(ImageVault, image_exists_not_expired)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}};
QDir images_dir{MP_UTILS.make_dir(cache_dir.path(), "images")};
auto file_name = images_dir.filePath("mock_image.img");
auto prepare = [&file_name](const mp::VMImage& source_image) -> mp::VMImage {
mpt::make_file_with_content(file_name);
return {file_name, source_image.id, "", "", "", {}};
};
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
EXPECT_TRUE(QFileInfo::exists(file_name));
vault.prune_expired_images();
EXPECT_TRUE(QFileInfo::exists(file_name));
}
TEST_F(ImageVault, invalid_image_dir_is_removed)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}};
QDir invalid_image_dir(MP_UTILS.make_dir(cache_dir.path(), "vault/images/invalid_image"));
auto file_name = invalid_image_dir.filePath("mock_image.img");
mpt::make_file_with_content(file_name);
EXPECT_TRUE(QFileInfo::exists(file_name));
vault.prune_expired_images();
EXPECT_FALSE(QFileInfo::exists(file_name));
EXPECT_FALSE(QFileInfo::exists(invalid_image_dir.absolutePath()));
}
TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(file_based_fetch_copies_image_and_returns_expected_info))
{
mpt::TempFile file;
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto query = default_query;
query.release = file.url().toStdString();
query.query_type = mp::Query::Type::LocalFile;
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
EXPECT_TRUE(QFileInfo::exists(vm_image.image_path));
EXPECT_EQ(vm_image.id, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
}
TEST_F(ImageVault, invalid_custom_image_file_throws)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto query = default_query;
query.release = "file://foo";
query.query_type = mp::Query::Type::LocalFile;
EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir),
std::runtime_error);
}
TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(custom_image_url_downloads))
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto query = default_query;
query.release = "http://www.foo.com/fake.img";
query.query_type = mp::Query::Type::HttpDownload;
vault.fetch_image(mp::FetchType::ImageOnly, query, stub_prepare, stub_monitor, false, std::nullopt, instance_dir);
EXPECT_THAT(url_downloader.downloaded_files.size(), Eq(1));
EXPECT_TRUE(url_downloader.downloaded_urls.contains(QString::fromStdString(query.release)));
}
TEST_F(ImageVault, missing_downloaded_image_throws)
{
mpt::StubURLDownloader stub_url_downloader;
mp::DefaultVMImageVault vault{hosts, &stub_url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir),
mp::CreateImageException);
}
TEST_F(ImageVault, hash_mismatch_throws)
{
BadURLDownloader bad_url_downloader;
mp::DefaultVMImageVault vault{hosts, &bad_url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir),
mp::CreateImageException);
}
TEST_F(ImageVault, invalid_remote_throws)
{
mpt::StubURLDownloader stub_url_downloader;
mp::DefaultVMImageVault vault{hosts, &stub_url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto query = default_query;
query.remote_name = "foo";
EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir),
std::runtime_error);
}
TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(invalid_image_alias_throw))
{
mpt::StubURLDownloader stub_url_downloader;
mp::DefaultVMImageVault vault{hosts, &stub_url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto query = default_query;
query.release = "foo";
EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir),
mp::CreateImageException);
}
TEST_F(ImageVault, valid_remote_and_alias_returns_valid_image_info)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto query = default_query;
query.release = "default";
query.remote_name = "release";
mp::VMImage image;
EXPECT_NO_THROW(image = vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir));
EXPECT_THAT(image.original_release, Eq("18.04 LTS"));
EXPECT_THAT(image.id, Eq("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"));
}
TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(http_download_returns_expected_image_info))
{
HttpURLDownloader http_url_downloader;
mp::DefaultVMImageVault vault{hosts, &http_url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto image_url{"http://www.foo.com/images/foo.img"};
mp::Query query{instance_name, image_url, false, "", mp::Query::Type::HttpDownload};
mp::VMImage image;
EXPECT_NO_THROW(image = vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir));
// Hash is based on image url
EXPECT_THAT(image.id, Eq("7404f51c9b4f40312fa048a0ad36e07b74b718a2d3a5a08e8cca906c69059ddf"));
EXPECT_THAT(image.release_date, Eq(default_last_modified.toString().toStdString()));
}
TEST_F(ImageVault, image_update_creates_new_dir_and_removes_old)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}};
vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
auto original_file{url_downloader.downloaded_files[0]};
auto original_absolute_path{QFileInfo(original_file).absolutePath()};
EXPECT_TRUE(QFileInfo::exists(original_file));
EXPECT_TRUE(original_absolute_path.contains(mpt::default_version));
// Mock an update to the image and don't verify because of hash mismatch
const QString new_date_string{"20180825"};
host.mock_bionic_image_info.id = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b856";
host.mock_bionic_image_info.version = new_date_string;
host.mock_bionic_image_info.verify = false;
vault.update_images(mp::FetchType::ImageOnly, stub_prepare, stub_monitor);
auto updated_file{url_downloader.downloaded_files[1]};
EXPECT_TRUE(QFileInfo::exists(updated_file));
EXPECT_TRUE(QFileInfo(updated_file).absolutePath().contains(new_date_string));
// Old image and directory should be removed
EXPECT_FALSE(QFileInfo::exists(original_file));
EXPECT_FALSE(QFileInfo::exists(original_absolute_path));
}
TEST_F(ImageVault, aborted_download_throws)
{
RunningURLDownloader running_url_downloader;
mp::DefaultVMImageVault vault{hosts, &running_url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
running_url_downloader.abort_all_downloads();
EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir),
mp::AbortedDownloadException);
}
TEST_F(ImageVault, minimum_image_size_returns_expected_size)
{
const mp::MemorySize image_size{"1048576"};
const mp::ProcessState qemuimg_exit_status{0, std::nullopt};
const QByteArray qemuimg_output(fake_img_info(image_size));
auto mock_factory_scope = inject_fake_qemuimg_callback(qemuimg_exit_status, qemuimg_output);
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
const auto size = vault.minimum_image_size_for(vm_image.id);
EXPECT_EQ(image_size, size);
}
TEST_F(ImageVault, DISABLE_ON_WINDOWS_AND_MACOS(file_based_minimum_size_returns_expected_size))
{
const mp::MemorySize image_size{"2097152"};
const mp::ProcessState qemuimg_exit_status{0, std::nullopt};
const QByteArray qemuimg_output(fake_img_info(image_size));
auto mock_factory_scope = inject_fake_qemuimg_callback(qemuimg_exit_status, qemuimg_output);
mpt::TempFile file;
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto query = default_query;
query.release = file.url().toStdString();
query.query_type = mp::Query::Type::LocalFile;
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
const auto size = vault.minimum_image_size_for(vm_image.id);
EXPECT_EQ(image_size, size);
}
TEST_F(ImageVault, minimum_image_size_throws_when_not_cached)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}};
const std::string id{"12345"};
MP_EXPECT_THROW_THAT(vault.minimum_image_size_for(id), std::runtime_error,
mpt::match_what(StrEq(fmt::format("Cannot determine minimum image size for id \'{}\'", id))));
}
TEST_F(ImageVault, minimum_image_size_throws_when_qemuimg_info_crashes)
{
const mp::ProcessState qemuimg_exit_status{std::nullopt, mp::ProcessState::Error{QProcess::Crashed, "core dumped"}};
const QByteArray qemuimg_output("about to crash");
auto mock_factory_scope = inject_fake_qemuimg_callback(qemuimg_exit_status, qemuimg_output);
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
MP_EXPECT_THROW_THAT(vault.minimum_image_size_for(vm_image.id), std::runtime_error,
mpt::match_what(AllOf(HasSubstr("qemu-img failed"), HasSubstr("with output"))));
}
TEST_F(ImageVault, minimum_image_size_throws_when_qemuimg_info_cannot_find_the_image)
{
const mp::ProcessState qemuimg_exit_status{1, std::nullopt};
const QByteArray qemuimg_output("Could not find");
auto mock_factory_scope = inject_fake_qemuimg_callback(qemuimg_exit_status, qemuimg_output);
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
MP_EXPECT_THROW_THAT(vault.minimum_image_size_for(vm_image.id), std::runtime_error,
mpt::match_what(AllOf(HasSubstr("qemu-img failed"), HasSubstr("Could not find"))));
}
TEST_F(ImageVault, minimum_image_size_throws_when_qemuimg_info_does_not_understand_the_image_size)
{
const mp::ProcessState qemuimg_exit_status{0, std::nullopt};
const QByteArray qemuimg_output("virtual size: an unintelligible string");
auto mock_factory_scope = inject_fake_qemuimg_callback(qemuimg_exit_status, qemuimg_output);
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
auto vm_image = vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
MP_EXPECT_THROW_THAT(vault.minimum_image_size_for(vm_image.id), std::runtime_error,
mpt::match_what(HasSubstr("Could not obtain image's virtual size")));
}
TEST_F(ImageVault, all_info_for_no_remote_given_returns_expected_data)
{
mpt::StubURLDownloader stub_url_downloader;
mp::DefaultVMImageVault vault{hosts, &stub_url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
const std::string remote_name{"release"};
EXPECT_CALL(host, all_info_for(_))
.WillOnce(Return(std::vector<std::pair<std::string, mp::VMImageInfo>>{
{remote_name, host.mock_bionic_image_info}, {remote_name, host.mock_another_image_info}}));
auto images = vault.all_info_for({"", "e3", false, "", mp::Query::Type::Alias, true});
EXPECT_EQ(images.size(), 2u);
const auto& [first_image_remote, first_image_info] = images[0];
EXPECT_EQ(first_image_remote, remote_name);
EXPECT_EQ(first_image_info.id.toStdString(), mpt::default_id);
EXPECT_EQ(first_image_info.version.toStdString(), mpt::default_version);
const auto& [second_image_remote, second_image_info] = images[1];
EXPECT_EQ(second_image_remote, remote_name);
EXPECT_EQ(second_image_info.id.toStdString(), mpt::another_image_id);
EXPECT_EQ(second_image_info.version.toStdString(), mpt::another_image_version);
}
TEST_F(ImageVault, all_info_for_remote_given_returns_expected_data)
{
mpt::StubURLDownloader stub_url_downloader;
mp::DefaultVMImageVault vault{hosts, &stub_url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
const std::string remote_name{"release"};
EXPECT_CALL(host, all_info_for(_))
.WillOnce(Return(std::vector<std::pair<std::string, mp::VMImageInfo>>{
{remote_name, host.mock_bionic_image_info}, {remote_name, host.mock_another_image_info}}));
auto images = vault.all_info_for({"", "e3", false, remote_name, mp::Query::Type::Alias, true});
EXPECT_EQ(images.size(), 2u);
const auto& [first_image_remote, first_image_info] = images[0];
EXPECT_EQ(first_image_remote, remote_name);
EXPECT_EQ(first_image_info.id.toStdString(), mpt::default_id);
EXPECT_EQ(first_image_info.version.toStdString(), mpt::default_version);
const auto& [second_image_remote, second_image_info] = images[1];
EXPECT_EQ(second_image_remote, remote_name);
EXPECT_EQ(second_image_info.id.toStdString(), mpt::another_image_id);
EXPECT_EQ(second_image_info.version.toStdString(), mpt::another_image_version);
}
TEST_F(ImageVault, allInfoForNoImagesReturnsEmpty)
{
mpt::StubURLDownloader stub_url_downloader;
mp::DefaultVMImageVault vault{hosts, &stub_url_downloader, cache_dir.path(), data_dir.path(), mp::days{0}};
const std::string name{"foo"};
EXPECT_CALL(host, all_info_for(_)).WillOnce(Return(std::vector<std::pair<std::string, mp::VMImageInfo>>{}));
EXPECT_TRUE(vault.all_info_for({"", name, false, "", mp::Query::Type::Alias, true}).empty());
}
TEST_F(ImageVault, updateImagesLogsWarningOnUnsupportedImage)
{
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(mpl::Level::warning);
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}};
vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
EXPECT_CALL(host, info_for(_)).WillOnce(Throw(mp::UnsupportedImageException(default_query.release)));
logger_scope.mock_logger->screen_logs(mpl::Level::warning);
EXPECT_CALL(*logger_scope.mock_logger,
log(mpl::Level::warning, mpt::MockLogger::make_cstring_matcher(StrEq("image vault")),
mpt::MockLogger::make_cstring_matcher(StrEq(fmt::format(
"Skipping update: The {} release is no longer supported.", default_query.release)))));
EXPECT_NO_THROW(vault.update_images(mp::FetchType::ImageOnly, stub_prepare, stub_monitor));
}
TEST_F(ImageVault, updateImagesLogsWarningOnEmptyVault)
{
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(mpl::Level::warning);
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}};
vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir);
EXPECT_CALL(host, info_for(_)).WillOnce(Return(std::nullopt));
logger_scope.mock_logger->screen_logs(mpl::Level::warning);
EXPECT_CALL(*logger_scope.mock_logger,
log(mpl::Level::warning, mpt::MockLogger::make_cstring_matcher(StrEq("image vault")),
mpt::MockLogger::make_cstring_matcher(
StrEq(fmt::format("Skipping update: Unable to find an image matching \"{}\" in remote \"{}\".",
default_query.release, default_query.remote_name)))));
EXPECT_NO_THROW(vault.update_images(mp::FetchType::ImageOnly, stub_prepare, stub_monitor));
}
TEST_F(ImageVault, fetchLocalImageThrowsOnEmptyVault)
{
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}};
EXPECT_CALL(host, info_for(_)).WillOnce(Return(std::nullopt));
EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly,
default_query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir),
mp::ImageNotFoundException);
}
TEST_F(ImageVault, fetchRemoteImageThrowsOnMissingKernel)
{
mp::Query query{instance_name, "xenial", false, "", mp::Query::Type::Alias};
mp::DefaultVMImageVault vault{hosts, &url_downloader, cache_dir.path(), data_dir.path(), mp::days{1}};
EXPECT_CALL(host, info_for(_)).WillOnce(Return(std::nullopt));
EXPECT_THROW(vault.fetch_image(mp::FetchType::ImageOnly,
query,
stub_prepare,
stub_monitor,
false,
std::nullopt,
instance_dir),
mp::ImageNotFoundException);
}
| 40,510
|
C++
|
.cpp
| 807
| 36.429988
| 120
| 0.574055
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,598
|
test_cli_prompters.cpp
|
canonical_multipass/tests/test_cli_prompters.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_terminal.h"
#include "stub_terminal.h"
#include <multipass/cli/prompters.h>
#include <multipass/exceptions/cli_exceptions.h>
#include <sstream>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
struct CLIPrompters : Test
{
std::ostringstream cerr, cout;
std::istringstream cin;
mpt::StubTerminal term{cout, cerr, cin};
};
struct TestPassphrasePrompters : Test
{
TestPassphrasePrompters()
{
EXPECT_CALL(mock_terminal, cout()).WillRepeatedly(ReturnRef(cout));
}
std::ostringstream cerr, cout;
std::istringstream cin;
mpt::MockTerminal mock_terminal;
};
TEST_F(CLIPrompters, PlainPromptsText)
{
auto prompt = mp::PlainPrompter{&term};
cin.str("\n");
prompt.prompt("foo");
EXPECT_EQ(cout.str(), "foo: ");
}
TEST_F(CLIPrompters, PlainReturnsText)
{
auto prompt = mp::PlainPrompter{&term};
cin.str("value\n");
EXPECT_EQ(prompt.prompt(""), "value");
}
// Note that the following test does not actually test if the terminal echos or not-
// that is specific to platform terminal types.
TEST_F(TestPassphrasePrompters, passphraseCallsEchoAndReturnsExpectedPassphrase)
{
const std::string expected_output{"Please enter passphrase: \n"};
const std::string passphrase{"foo"};
cin.str(passphrase + "\n");
{
InSequence s;
EXPECT_CALL(mock_terminal, set_cin_echo(false)).Times(1);
EXPECT_CALL(mock_terminal, set_cin_echo(true)).Times(1);
}
EXPECT_CALL(mock_terminal, cin()).WillOnce(ReturnRef(cin));
mp::PassphrasePrompter prompter{&mock_terminal};
auto input = prompter.prompt();
EXPECT_EQ(cout.str(), expected_output);
EXPECT_EQ(input, passphrase);
}
TEST_F(TestPassphrasePrompters, newPassPhraseCallsEchoAndReturnsExpectedPassphrase)
{
const std::string expected_output{"Please enter passphrase: \nPlease re-enter passphrase: \n"};
const std::string passphrase{"foo"};
{
InSequence s;
EXPECT_CALL(mock_terminal, set_cin_echo(false)).Times(1);
EXPECT_CALL(mock_terminal, set_cin_echo(true)).Times(1);
EXPECT_CALL(mock_terminal, set_cin_echo(false)).Times(1);
EXPECT_CALL(mock_terminal, set_cin_echo(true)).Times(1);
}
EXPECT_CALL(mock_terminal, cin()).Times(2).WillRepeatedly([this, &passphrase]() -> std::istream& {
cin.str(passphrase + "\n");
return cin;
});
mp::NewPassphrasePrompter prompter{&mock_terminal};
auto input = prompter.prompt();
EXPECT_EQ(cout.str(), expected_output);
EXPECT_EQ(input, passphrase);
}
TEST_F(TestPassphrasePrompters, newPassPhraseWrongPassphraseThrows)
{
const std::string expected_output{"Please enter passphrase: \nPlease re-enter passphrase: \n"};
const std::string passphrase{"foo"}, wrong_passphrase{"bar"};
{
InSequence s;
EXPECT_CALL(mock_terminal, set_cin_echo(false)).Times(1);
EXPECT_CALL(mock_terminal, set_cin_echo(true)).Times(1);
EXPECT_CALL(mock_terminal, set_cin_echo(false)).Times(1);
EXPECT_CALL(mock_terminal, set_cin_echo(true)).Times(1);
}
auto good_passphrase = [this, &passphrase]() -> std::istream& {
cin.str(passphrase + "\n");
return cin;
};
auto bad_passphrase = [this, &wrong_passphrase]() -> std::istream& {
cin.str(wrong_passphrase + "\n");
return cin;
};
EXPECT_CALL(mock_terminal, cin()).WillOnce(Invoke(good_passphrase)).WillOnce(Invoke(bad_passphrase));
mp::NewPassphrasePrompter prompter{&mock_terminal};
MP_EXPECT_THROW_THAT(prompter.prompt(), mp::PromptException, mpt::match_what(StrEq("Passphrases do not match")));
EXPECT_EQ(cout.str(), expected_output);
}
class CLIPromptersBadCinState : public CLIPrompters, public WithParamInterface<std::ios_base::iostate>
{
};
TEST_P(CLIPromptersBadCinState, PlainThrows)
{
auto prompt = mp::PlainPrompter{&term};
cin.clear(GetParam());
MP_EXPECT_THROW_THAT(prompt.prompt(""), mp::PromptException, mpt::match_what(HasSubstr("Failed to read value")));
}
INSTANTIATE_TEST_SUITE_P(CLIPrompters, CLIPromptersBadCinState,
Values(std::ios::eofbit, std::ios::failbit, std::ios::badbit));
class BridgePrompterTests : public CLIPrompters,
public WithParamInterface<std::tuple<std::vector<std::string>, std::string, bool>>
{
};
TEST_F(CLIPrompters, failsIfNoNetworks)
{
std::vector<std::string> nets{};
mpt::MockTerminal mock_terminal;
mp::BridgePrompter prompter{&mock_terminal};
EXPECT_CALL(mock_terminal, cin_is_live()).WillRepeatedly(Return(false));
EXPECT_CALL(mock_terminal, cout_is_live()).WillRepeatedly(Return(false));
ASSERT_DEBUG_DEATH(prompter.bridge_prompt(nets), "[Aa]ssert");
}
TEST_P(BridgePrompterTests, correctlyReturns)
{
auto [nets, answer, ret] = GetParam();
mpt::MockTerminal mock_terminal;
EXPECT_CALL(mock_terminal, cout()).WillRepeatedly(ReturnRef(cout));
EXPECT_CALL(mock_terminal, cout_is_live()).WillOnce(Return(true));
EXPECT_CALL(mock_terminal, cin()).WillOnce(ReturnRef(cin));
EXPECT_CALL(mock_terminal, cin_is_live()).WillOnce(Return(true));
cin.str(answer + "\n");
mp::BridgePrompter prompter{&mock_terminal};
EXPECT_EQ(prompter.bridge_prompt(nets), ret);
}
INSTANTIATE_TEST_SUITE_P(CLIPrompters,
BridgePrompterTests,
Values(std::make_tuple(std::vector<std::string>{"eth1"}, "yes", true),
std::make_tuple(std::vector<std::string>{"eth1", "eth3"}, "y", true),
std::make_tuple(std::vector<std::string>{"eth1", "eth3"}, "no", false),
std::make_tuple(std::vector<std::string>{"eth1"}, "n", false)));
TEST_F(CLIPrompters, handlesWrongAnswer)
{
mpt::MockTerminal mock_terminal;
EXPECT_CALL(mock_terminal, cout()).WillRepeatedly(ReturnRef(cout));
EXPECT_CALL(mock_terminal, cout_is_live()).WillOnce(Return(true));
EXPECT_CALL(mock_terminal, cin()).WillRepeatedly(ReturnRef(cin));
EXPECT_CALL(mock_terminal, cin_is_live()).WillOnce(Return(true));
cin.str("qqq\nyes\n");
mp::BridgePrompter prompter{&mock_terminal};
std::vector<std::string> nets{"eth2"};
EXPECT_EQ(prompter.bridge_prompt(nets), true);
}
TEST_F(CLIPrompters, falseOnNonLiveTerminal)
{
mpt::MockTerminal mock_terminal;
EXPECT_CALL(mock_terminal, cin_is_live()).WillOnce(Return(false));
mp::BridgePrompter prompter{&mock_terminal};
std::vector<std::string> nets{"eth2"};
EXPECT_EQ(prompter.bridge_prompt(nets), false);
}
| 7,331
|
C++
|
.cpp
| 178
| 35.949438
| 117
| 0.692937
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,599
|
test_new_release_monitor.cpp
|
canonical_multipass/tests/test_new_release_monitor.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <src/platform/update/new_release_monitor.h>
#include <QEventLoop>
#include <QTemporaryFile>
#include <QTimer>
#include <QUrl>
#include <chrono>
namespace mp = multipass;
using namespace testing;
namespace
{
const auto timeout = std::chrono::milliseconds{250};
const QString json_template = R"END({
"prefix_field": "foo",
"release_url": "%1",
"infix_field": "bar",
"version": "%2",
"suffix_field": "baz"
}
)END";
class StubUpdateJson
{
public:
StubUpdateJson(QString version, QString url)
{
json_file.open();
json_file.write(json_template.arg(url).arg(version).toUtf8());
json_file.close();
}
QByteArray url() const
{
return QUrl::fromLocalFile(json_file.fileName()).toEncoded();
}
private:
QTemporaryFile json_file;
};
auto check_for_new_release(QString currentVersion, QString newVersion, QString newVersionUrl = "")
{
QEventLoop e;
StubUpdateJson json(newVersion, newVersionUrl);
mp::NewReleaseMonitor monitor(currentVersion, std::chrono::hours(1), json.url());
QTimer::singleShot(timeout, &e, &QEventLoop::quit); // TODO replace with a thread sync mechanism (e.g. condition)
e.exec();
return monitor.get_new_release();
}
} // namespace
TEST(NewReleaseMonitor, checks_new_release)
{
auto new_release = check_for_new_release("0.1.0", "0.2.0", "https://something_unique.com");
ASSERT_TRUE(new_release);
EXPECT_EQ("0.2.0", new_release->version.toStdString());
EXPECT_EQ("https://something_unique.com", new_release->url.toString().toStdString());
}
TEST(NewReleaseMonitor, checks_new_release_when_nothing_new)
{
auto new_release = check_for_new_release("0.2.1", "0.2.1");
EXPECT_FALSE(new_release);
}
TEST(NewReleaseMonitor, checks_new_release_when_newer_than_available)
{
auto new_release = check_for_new_release("0.3.0", "0.2.0");
EXPECT_FALSE(new_release);
}
TEST(NewReleaseMonitor, checks_new_release_when_download_fails)
{
QEventLoop e;
StubUpdateJson json("0.2.0", "https://something_unique.com");
mp::NewReleaseMonitor monitor("0.1.0", std::chrono::hours(1), "file:///does/not/exist");
QTimer::singleShot(timeout, &e, &QEventLoop::quit);
e.exec();
auto new_release = monitor.get_new_release();
EXPECT_FALSE(new_release);
}
// Just double-checking that the SemVer library applies the ordering we expect for prerelease strings.
TEST(NewReleaseMonitor, dev_prerelease_ordering_correct)
{
auto new_release = check_for_new_release("0.6.0", "0.6.0-dev.238+g5c642f4");
EXPECT_FALSE(new_release);
}
TEST(NewReleaseMonitor, dev_prerelease_ordering_correct1)
{
auto new_release = check_for_new_release("0.6.0-dev.238+g5c642f4", "0.6.0");
ASSERT_TRUE(new_release);
EXPECT_EQ("0.6.0", new_release->version.toStdString());
}
TEST(NewReleaseMonitor, rc_prerelease_ordering_correct)
{
auto new_release = check_for_new_release("0.6.0", "0.6.0-rc.238+g5c642f4");
EXPECT_FALSE(new_release);
}
TEST(NewReleaseMonitor, rc_prerelease_ordering_correct1)
{
auto new_release = check_for_new_release("0.6.0-rc.238+g5c642f4", "0.6.0");
EXPECT_TRUE(new_release);
}
TEST(NewReleaseMonitor, dev_rc_release_ordering_correct)
{
auto new_release = check_for_new_release("0.6.0-rc.238+g3245235.win", "0.6.0-dev.238+g5c642f4");
EXPECT_FALSE(new_release);
}
TEST(NewReleaseMonitor, dev_rc_release_ordering_correct1)
{
auto new_release = check_for_new_release("0.6.0-dev.238+g3245235.win", "0.6.0-rc.238+g5c642f4");
EXPECT_TRUE(new_release);
}
| 4,211
|
C++
|
.cpp
| 121
| 31.68595
| 117
| 0.719359
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,600
|
test_global_settings_handlers.cpp
|
canonical_multipass/tests/test_global_settings_handlers.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_platform.h"
#include "mock_qsettings.h"
#include "mock_settings.h"
#include "mock_standard_paths.h"
#include "mock_utils.h"
#include <multipass/cli/client_common.h>
#include <multipass/constants.h>
#include <multipass/settings/basic_setting_spec.h>
#include <multipass/settings/persistent_settings_handler.h>
#include <src/daemon/daemon_init_settings.h>
#include <QDir>
namespace mp = multipass;
namespace mpt = mp::test;
using namespace testing;
namespace
{
struct TestGlobalSettingsHandlers : public Test
{
void SetUp() override
{
ON_CALL(mock_platform, default_privileged_mounts).WillByDefault(Return("true"));
ON_CALL(mock_platform, is_backend_supported).WillByDefault(Return(true));
EXPECT_CALL(mock_settings,
register_handler(Pointer(WhenDynamicCastTo<const mp::PersistentSettingsHandler*>(NotNull()))))
.WillOnce([this](auto uptr) {
handler = std::move(uptr);
return handler.get();
});
}
void inject_mock_qsettings() // moves the mock, so call once only, after setting expectations
{
EXPECT_CALL(*mock_qsettings, fileName)
.WillRepeatedly(Return(QDir::temp().absoluteFilePath("missing_file.conf")));
EXPECT_CALL(*mock_qsettings_provider, make_wrapped_qsettings(_, Eq(QSettings::IniFormat)))
.WillOnce(Return(ByMove(std::move(mock_qsettings))));
}
void inject_default_returning_mock_qsettings()
{
EXPECT_CALL(*mock_qsettings_provider, make_wrapped_qsettings)
.WillRepeatedly(WithArg<0>(Invoke(make_default_returning_mock_qsettings)));
}
void expect_setting_values(const std::map<QString, QString>& setting_values)
{
for (const auto& [k, v] : setting_values)
{
EXPECT_EQ(handler->get(k), v);
}
}
template <typename... Ts>
void assert_unrecognized_keys(Ts... keys)
{
for (const char* key : {keys...})
{
MP_ASSERT_THROW_THAT(handler->get(key), mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(key)));
}
}
static std::unique_ptr<multipass::WrappedQSettings> make_default_returning_mock_qsettings(const QString& filename)
{
auto mock_qsettings = std::make_unique<NiceMock<mpt::MockQSettings>>();
EXPECT_CALL(*mock_qsettings, value_impl).WillRepeatedly(ReturnArg<1>());
EXPECT_CALL(*mock_qsettings, fileName).WillRepeatedly(Return(filename));
return mock_qsettings;
}
static mp::SettingSpec::Set to_setting_set(const std::map<QString, QString>& setting_defaults)
{
mp::SettingSpec::Set ret;
for (const auto& [k, v] : setting_defaults)
ret.insert(std::make_unique<mp::BasicSettingSpec>(k, v));
return ret;
}
public:
mpt::MockQSettingsProvider::GuardedMock mock_qsettings_injection =
mpt::MockQSettingsProvider::inject<StrictMock>(); /* strict to ensure that, other than explicitly injected, no
QSettings are used */
mpt::MockQSettingsProvider* mock_qsettings_provider = mock_qsettings_injection.first;
std::unique_ptr<NiceMock<mpt::MockQSettings>> mock_qsettings = std::make_unique<NiceMock<mpt::MockQSettings>>();
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject<StrictMock>();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
mpt::MockPlatform::GuardedMock mock_platform_injection = mpt::MockPlatform::inject<NiceMock>();
mpt::MockPlatform& mock_platform = *mock_platform_injection.first;
std::unique_ptr<mp::SettingsHandler> handler = nullptr;
};
TEST_F(TestGlobalSettingsHandlers, clientsRegisterPersistentHandlerWithClientFilename)
{
auto config_location = QStringLiteral("/a/b/c");
auto expected_filename = config_location + "/multipass/multipass.conf";
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::GenericConfigLocation))
.WillOnce(Return(config_location));
mp::client::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings_provider, make_wrapped_qsettings(Eq(expected_filename), _))
.WillOnce(WithArg<0>(Invoke(make_default_returning_mock_qsettings)));
handler->set(mp::petenv_key, "goo");
}
TEST_F(TestGlobalSettingsHandlers, clientsRegisterPersistentHandlerForClientSettings)
{
mp::client::register_global_settings_handlers();
inject_default_returning_mock_qsettings();
expect_setting_values({{mp::petenv_key, "primary"}});
}
TEST_F(TestGlobalSettingsHandlers, clientsRegisterPersistentHandlerWithOverridingPlatformSettings)
{
const auto platform_defaults = std::map<QString, QString>{{"client.a.setting", "a reasonably long value for this"},
{mp::petenv_key, "secondary"},
{"client.empty.setting", ""},
{"client.an.int", "-12345"},
{"client.a.float.with.a.long_key", "3.14"}};
EXPECT_CALL(mock_platform, extra_client_settings).WillOnce(Return(ByMove(to_setting_set(platform_defaults))));
mp::client::register_global_settings_handlers();
inject_default_returning_mock_qsettings();
expect_setting_values(platform_defaults);
}
TEST_F(TestGlobalSettingsHandlers, clientsDoNotRegisterPersistentHandlerForDaemonSettings)
{
mp::client::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings_provider, make_wrapped_qsettings(_, _)).Times(0);
assert_unrecognized_keys(mp::driver_key, mp::bridged_interface_key, mp::mounts_key, mp::passphrase_key);
}
struct TestGoodPetEnvSetting : public TestGlobalSettingsHandlers, WithParamInterface<const char*>
{
};
TEST_P(TestGoodPetEnvSetting, clientsRegisterHandlerThatAcceptsValidPetenv)
{
auto key = mp::petenv_key, val = GetParam();
mp::client::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings, setValue(Eq(key), Eq(val)));
inject_mock_qsettings();
ASSERT_NO_THROW(handler->set(key, val));
}
INSTANTIATE_TEST_SUITE_P(TestGoodPetEnvSetting, TestGoodPetEnvSetting, Values("valid-primary", ""));
struct TestBadPetEnvSetting : public TestGlobalSettingsHandlers, WithParamInterface<const char*>
{
};
TEST_P(TestBadPetEnvSetting, clientsRegisterHandlerThatRejectsInvalidPetenv)
{
auto key = mp::petenv_key, val = GetParam();
mp::client::register_global_settings_handlers();
MP_ASSERT_THROW_THAT(handler->set(key, val),
mp::InvalidSettingException,
mpt::match_what(AllOf(HasSubstr(key), HasSubstr(val))));
}
INSTANTIATE_TEST_SUITE_P(TestBadPetEnvSetting, TestBadPetEnvSetting, Values("-", "-a-b-", "_asd", "_1", "1-2-3"));
TEST_F(TestGlobalSettingsHandlers, daemonRegistersPersistentHandlerWithDaemonFilename)
{
auto config_location = QStringLiteral("/a/b/c");
auto expected_filename = config_location + "/multipassd.conf";
EXPECT_CALL(mock_platform, daemon_config_home).WillOnce(Return(config_location));
mp::daemon::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings_provider, make_wrapped_qsettings(Eq(expected_filename), _))
.WillOnce(WithArg<0>(Invoke(make_default_returning_mock_qsettings)));
handler->set(mp::bridged_interface_key, "bridge");
}
TEST_F(TestGlobalSettingsHandlers, daemonRegistersPersistentHandlerForDaemonSettings)
{
const auto driver = "conductor";
const auto mount = "false";
EXPECT_CALL(mock_platform, default_driver).WillOnce(Return(driver));
EXPECT_CALL(mock_platform, default_privileged_mounts).WillOnce(Return(mount));
mp::daemon::register_global_settings_handlers();
inject_default_returning_mock_qsettings();
expect_setting_values({{mp::driver_key, driver}, {mp::bridged_interface_key, ""}, {mp::mounts_key, mount}});
}
TEST_F(TestGlobalSettingsHandlers, daemonRegistersPersistentHandlerForDaemonPlatformSettings)
{
const auto platform_defaults = std::map<QString, QString>{{"local.blah", "blargh"},
{mp::driver_key, "platform-hypervisor"},
{"local.a.bool", "false"},
{mp::bridged_interface_key, "platform-bridge"},
{"local.foo", "barrrr"},
{mp::mounts_key, "false"},
{"local.a.long.number", "1234567890"}};
EXPECT_CALL(mock_platform, default_driver).WillOnce(Return("unused"));
EXPECT_CALL(mock_platform, default_privileged_mounts).WillOnce(Return("true"));
EXPECT_CALL(mock_platform, extra_daemon_settings).WillOnce(Return(ByMove(to_setting_set(platform_defaults))));
mp::daemon::register_global_settings_handlers();
inject_default_returning_mock_qsettings();
expect_setting_values(platform_defaults);
}
TEST_F(TestGlobalSettingsHandlers, daemonDoesNotRegisterPersistentHandlerForClientSettings)
{
mp::daemon::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings_provider, make_wrapped_qsettings(_, _)).Times(0);
assert_unrecognized_keys(mp::petenv_key, mp::winterm_key);
}
TEST_F(TestGlobalSettingsHandlers, daemonRegistersHandlerThatAcceptsValidBackend)
{
auto key = mp::driver_key, val = "good driver";
mp::daemon::register_global_settings_handlers();
EXPECT_CALL(mock_platform, is_backend_supported(Eq(val))).WillOnce(Return(true));
EXPECT_CALL(*mock_qsettings, setValue(Eq(key), Eq(val)));
inject_mock_qsettings();
ASSERT_NO_THROW(handler->set(key, val));
}
TEST_F(TestGlobalSettingsHandlers, daemonRegistersHandlerThatTransformsHyperVDriver)
{
const auto key = mp::driver_key;
const auto val = "hyper-v";
const auto transformed_val = "hyperv";
mp::daemon::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings, setValue(Eq(key), Eq(transformed_val))).Times(1);
inject_mock_qsettings();
ASSERT_NO_THROW(handler->set(key, val));
}
TEST_F(TestGlobalSettingsHandlers, daemonRegistersHandlerThatTransformsVBoxDriver)
{
const auto key = mp::driver_key;
const auto val = "vbox";
const auto transformed_val = "virtualbox";
mp::daemon::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings, setValue(Eq(key), Eq(transformed_val))).Times(1);
inject_mock_qsettings();
ASSERT_NO_THROW(handler->set(key, val));
}
TEST_F(TestGlobalSettingsHandlers, daemonRegistersHandlerThatRejectsInvalidBackend)
{
auto key = mp::driver_key, val = "bad driver";
mp::daemon::register_global_settings_handlers();
EXPECT_CALL(mock_platform, is_backend_supported(Eq(val))).WillOnce(Return(false));
MP_ASSERT_THROW_THAT(handler->set(key, val),
mp::InvalidSettingException,
mpt::match_what(AllOf(HasSubstr(key), HasSubstr(val))));
}
TEST_F(TestGlobalSettingsHandlers, daemonRegistersHandlerThatAcceptsBoolMounts)
{
mp::daemon::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings, setValue(Eq(mp::mounts_key), Eq("true")));
inject_mock_qsettings();
ASSERT_NO_THROW(handler->set(mp::mounts_key, "1"));
}
TEST_F(TestGlobalSettingsHandlers, daemonRegistersHandlerThatAcceptsBrigedInterface)
{
const auto val = "bridge";
mp::daemon::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings, setValue(Eq(mp::bridged_interface_key), Eq(val)));
inject_mock_qsettings();
ASSERT_NO_THROW(handler->set(mp::bridged_interface_key, val));
}
TEST_F(TestGlobalSettingsHandlers, daemonRegistersHandlerThatHashesNonEmptyPassword)
{
const auto val = "correct horse battery staple";
const auto hash = "xkcd";
auto [mock_utils, guard] = mpt::MockUtils::inject<StrictMock>();
EXPECT_CALL(*mock_utils, generate_scrypt_hash_for(Eq(val))).WillOnce(Return(hash));
mp::daemon::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings, setValue(Eq(mp::passphrase_key), Eq(hash)));
inject_mock_qsettings();
ASSERT_NO_THROW(handler->set(mp::passphrase_key, val));
}
TEST_F(TestGlobalSettingsHandlers, daemonRegistersHandlerThatResetsHashWhenPasswordIsEmpty)
{
const auto val = "";
mp::daemon::register_global_settings_handlers();
EXPECT_CALL(*mock_qsettings, setValue(Eq(mp::passphrase_key), Eq(val)));
inject_mock_qsettings();
ASSERT_NO_THROW(handler->set(mp::passphrase_key, val));
}
} // namespace
| 13,855
|
C++
|
.cpp
| 273
| 42.157509
| 120
| 0.677756
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,601
|
test_delayed_shutdown.cpp
|
canonical_multipass/tests/test_delayed_shutdown.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_ssh_test_fixture.h"
#include "mock_virtual_machine.h"
#include "signal.h"
#include "stub_virtual_machine.h"
#include <multipass/delayed_shutdown_timer.h>
#include <multipass/exceptions/ssh_exception.h>
#include <QEventLoop>
#include <chrono>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
struct DelayedShutdown : public Test
{
DelayedShutdown()
{
vm = std::make_unique<mpt::StubVirtualMachine>();
vm->state = mp::VirtualMachine::State::running;
}
mpt::MockSSHTestFixture mock_ssh_test_fixture;
mp::VirtualMachine::UPtr vm;
QEventLoop loop;
ssh_channel_callbacks callbacks{nullptr};
};
TEST_F(DelayedShutdown, emits_finished_after_timer_expires)
{
mpt::Signal finished;
mp::DelayedShutdownTimer delayed_shutdown_timer{vm.get(), [](const std::string&) {}};
QObject::connect(&delayed_shutdown_timer, &mp::DelayedShutdownTimer::finished, [this, &finished] {
loop.quit();
finished.signal();
});
delayed_shutdown_timer.start(std::chrono::milliseconds(1));
loop.exec();
auto finish_invoked = finished.wait_for(std::chrono::seconds(1));
EXPECT_TRUE(finish_invoked);
}
TEST_F(DelayedShutdown, wallsImpendingShutdown)
{
static constexpr auto msg_upcoming = "The system is going down for poweroff in 0 minutes";
static constexpr auto msg_now = "The system is going down for poweroff now";
static const auto upcoming_cmd_matcher = AllOf(HasSubstr("wall"), HasSubstr(msg_upcoming));
static const auto now_cmd_matcher = AllOf(HasSubstr("wall"), HasSubstr(msg_now));
mpt::MockVirtualMachine vm{mp::VirtualMachine::State::running, "mock"};
mp::DelayedShutdownTimer delayed_shutdown_timer{&vm, [](const std::string&) {}};
EXPECT_CALL(vm, ssh_exec(upcoming_cmd_matcher, _)).Times(1); // as we start
EXPECT_CALL(vm, ssh_exec(now_cmd_matcher, _)).Times(1); // as we finish
QObject::connect(&delayed_shutdown_timer, &mp::DelayedShutdownTimer::finished, [this] { loop.quit(); });
delayed_shutdown_timer.start(std::chrono::milliseconds(1));
loop.exec();
}
TEST_F(DelayedShutdown, handlesExceptionWhenAttemptingToWall)
{
mpt::MockVirtualMachine vm{mp::VirtualMachine::State::running, "mock"};
mp::DelayedShutdownTimer delayed_shutdown_timer{&vm, [](const std::string&) {}};
EXPECT_CALL(vm, ssh_exec(HasSubstr("wall"), _)).Times(2).WillRepeatedly(Throw(mp::SSHException("nope")));
mpt::Signal finished;
QObject::connect(&delayed_shutdown_timer, &mp::DelayedShutdownTimer::finished, [this, &finished] {
loop.quit();
finished.signal();
});
delayed_shutdown_timer.start(std::chrono::milliseconds(1));
loop.exec();
EXPECT_TRUE(finished.wait_for(std::chrono::milliseconds(1)));
}
TEST_F(DelayedShutdown, emits_finished_with_no_timer)
{
mpt::Signal finished;
mp::DelayedShutdownTimer delayed_shutdown_timer{vm.get(), [](const std::string&) {}};
QObject::connect(&delayed_shutdown_timer, &mp::DelayedShutdownTimer::finished, [&finished] { finished.signal(); });
delayed_shutdown_timer.start(std::chrono::milliseconds::zero());
auto finish_invoked = finished.wait_for(std::chrono::seconds(1));
EXPECT_TRUE(finish_invoked);
}
TEST_F(DelayedShutdown, vm_state_delayed_shutdown_when_timer_running)
{
auto add_channel_cbs = [this](ssh_channel, ssh_channel_callbacks cb) {
callbacks = cb;
return SSH_OK;
};
REPLACE(ssh_add_channel_callbacks, add_channel_cbs);
auto event_dopoll = [this](auto...) {
if (!callbacks)
return SSH_ERROR;
callbacks->channel_exit_status_function(nullptr, nullptr, 0, callbacks->userdata);
return SSH_OK;
};
REPLACE(ssh_event_dopoll, event_dopoll);
EXPECT_TRUE(vm->state == mp::VirtualMachine::State::running);
mp::DelayedShutdownTimer delayed_shutdown_timer{vm.get(), [](const std::string&) {}};
delayed_shutdown_timer.start(std::chrono::milliseconds(1));
EXPECT_TRUE(vm->state == mp::VirtualMachine::State::delayed_shutdown);
}
TEST_F(DelayedShutdown, vm_state_running_after_cancel)
{
auto add_channel_cbs = [this](ssh_channel, ssh_channel_callbacks cb) {
callbacks = cb;
return SSH_OK;
};
REPLACE(ssh_add_channel_callbacks, add_channel_cbs);
auto event_dopoll = [this](auto...) {
if (!callbacks)
return SSH_ERROR;
callbacks->channel_exit_status_function(nullptr, nullptr, 0, callbacks->userdata);
return SSH_OK;
};
REPLACE(ssh_event_dopoll, event_dopoll);
{
mp::DelayedShutdownTimer delayed_shutdown_timer{vm.get(), [](const std::string&) {}};
delayed_shutdown_timer.start(std::chrono::milliseconds(1));
EXPECT_TRUE(vm->state == mp::VirtualMachine::State::delayed_shutdown);
}
EXPECT_TRUE(vm->state == mp::VirtualMachine::State::running);
}
| 5,586
|
C++
|
.cpp
| 130
| 38.4
| 119
| 0.704223
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,602
|
test_file_ops.cpp
|
canonical_multipass/tests/test_file_ops.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <multipass/file_ops.h>
#include <fcntl.h>
using namespace testing;
namespace fs = multipass::fs;
struct FileOps : public Test
{
fs::path temp_dir = fs::temp_directory_path() / "multipass_fileops_test";
fs::path temp_file = temp_dir / "file.txt";
std::error_code err;
std::string file_content = "content";
FileOps()
{
fs::create_directory(temp_dir);
std::ofstream stream{temp_file};
stream << file_content;
}
~FileOps()
{
fs::remove_all(temp_dir);
}
};
TEST_F(FileOps, open_write)
{
auto file = MP_FILEOPS.open_write(temp_file);
EXPECT_NE(dynamic_cast<std::ofstream*>(file.get()), nullptr);
}
TEST_F(FileOps, open_read)
{
auto file = MP_FILEOPS.open_read(temp_file);
EXPECT_NE(dynamic_cast<std::ifstream*>(file.get()), nullptr);
}
TEST_F(FileOps, exists)
{
EXPECT_TRUE(MP_FILEOPS.exists(temp_dir, err));
EXPECT_FALSE(err);
EXPECT_FALSE(MP_FILEOPS.exists(temp_dir / "nonexistent", err));
EXPECT_FALSE(err);
}
TEST_F(FileOps, copy)
{
const fs::path src_dir = temp_dir / "sub_src_dir";
const fs::path dest_dir = temp_dir / "sub_dest_dir";
MP_FILEOPS.create_directory(src_dir, err);
EXPECT_NO_THROW(MP_FILEOPS.copy(src_dir, dest_dir, std::filesystem::copy_options::recursive));
EXPECT_TRUE(MP_FILEOPS.exists(dest_dir, err));
}
TEST_F(FileOps, is_directory)
{
EXPECT_TRUE(MP_FILEOPS.is_directory(temp_dir, err));
EXPECT_FALSE(err);
EXPECT_FALSE(MP_FILEOPS.is_directory(temp_file, err));
EXPECT_FALSE(err);
}
TEST_F(FileOps, create_directory)
{
EXPECT_TRUE(MP_FILEOPS.create_directory(temp_dir / "subdir", err));
EXPECT_FALSE(err);
EXPECT_FALSE(MP_FILEOPS.create_directory(temp_dir / "subdir", err));
EXPECT_FALSE(err);
}
TEST_F(FileOps, remove)
{
EXPECT_TRUE(MP_FILEOPS.remove(temp_file, err));
EXPECT_FALSE(err);
EXPECT_FALSE(MP_FILEOPS.remove(temp_file, err));
EXPECT_FALSE(err);
}
TEST_F(FileOps, symlink)
{
MP_FILEOPS.create_symlink(temp_file, temp_dir / "symlink", err);
EXPECT_FALSE(err);
MP_FILEOPS.create_symlink(temp_file, temp_dir / "symlink", err);
EXPECT_TRUE(err);
EXPECT_EQ(MP_FILEOPS.read_symlink(temp_dir / "symlink", err), temp_file);
EXPECT_FALSE(err);
}
TEST_F(FileOps, permissions)
{
MP_FILEOPS.permissions(temp_file, fs::perms::all, err);
EXPECT_FALSE(err);
MP_FILEOPS.permissions(temp_dir / "nonexistent", fs::perms::all, err);
EXPECT_TRUE(err);
}
TEST_F(FileOps, status)
{
auto dir_status = MP_FILEOPS.status(temp_dir, err);
EXPECT_NE(dir_status.permissions(), fs::perms::unknown);
EXPECT_EQ(dir_status.type(), fs::file_type::directory);
EXPECT_FALSE(err);
}
TEST_F(FileOps, recurisve_dir_iter)
{
auto iter = MP_FILEOPS.recursive_dir_iterator(temp_dir, err);
EXPECT_FALSE(err);
EXPECT_TRUE(iter->hasNext());
EXPECT_EQ(iter->next().path(), temp_file);
MP_FILEOPS.recursive_dir_iterator(temp_file, err);
EXPECT_TRUE(err);
}
TEST_F(FileOps, create_directories)
{
EXPECT_TRUE(MP_FILEOPS.create_directories(temp_dir / "subdir/nested", err));
EXPECT_FALSE(err);
EXPECT_FALSE(MP_FILEOPS.create_directories(temp_dir / "subdir/nested", err));
EXPECT_FALSE(err);
}
TEST_F(FileOps, dir_iter)
{
auto iter = MP_FILEOPS.dir_iterator(temp_dir, err);
EXPECT_FALSE(err);
EXPECT_TRUE(iter->hasNext());
EXPECT_EQ(iter->next().path(), temp_dir / ".");
EXPECT_EQ(iter->next().path(), temp_dir / "..");
EXPECT_EQ(iter->next().path(), temp_file);
MP_FILEOPS.recursive_dir_iterator(temp_file, err);
EXPECT_TRUE(err);
}
TEST_F(FileOps, posix_open)
{
const auto named_fd1 = MP_FILEOPS.open_fd(temp_file, O_RDWR, 0);
EXPECT_NE(named_fd1->fd, -1);
const auto named_fd2 = MP_FILEOPS.open_fd(temp_dir, O_RDWR, 0);
EXPECT_EQ(named_fd2->fd, -1);
}
TEST_F(FileOps, posix_read)
{
const auto named_fd = MP_FILEOPS.open_fd(temp_file, O_RDWR, 0);
std::array<char, 100> buffer{};
const auto r = MP_FILEOPS.read(named_fd->fd, buffer.data(), buffer.size());
EXPECT_EQ(r, file_content.size());
EXPECT_EQ(buffer.data(), file_content);
}
TEST_F(FileOps, posix_write)
{
const auto named_fd = MP_FILEOPS.open_fd(temp_file, O_RDWR, 0);
const char data[] = "abcdef";
const auto r = MP_FILEOPS.write(named_fd->fd, data, sizeof(data));
EXPECT_EQ(r, sizeof(data));
std::ifstream stream{temp_file};
std::string string{std::istreambuf_iterator{stream}, {}};
EXPECT_STREQ(string.c_str(), data);
}
TEST_F(FileOps, posix_lseek)
{
const auto named_fd = MP_FILEOPS.open_fd(temp_file, O_RDWR, 0);
const auto seek = 3;
MP_FILEOPS.lseek(named_fd->fd, seek, SEEK_SET);
std::array<char, 100> buffer{};
const auto r = MP_FILEOPS.read(named_fd->fd, buffer.data(), buffer.size());
EXPECT_EQ(r, file_content.size() - seek);
EXPECT_STREQ(buffer.data(), file_content.c_str() + seek);
}
| 5,609
|
C++
|
.cpp
| 169
| 29.633136
| 98
| 0.681256
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,603
|
mock_openssl_syscalls.cpp
|
canonical_multipass/tests/mock_openssl_syscalls.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_openssl_syscalls.h"
extern "C" IMPL_MOCK_DEFAULT(10, EVP_PBE_scrypt);
| 715
|
C++
|
.cpp
| 18
| 37.777778
| 72
| 0.753957
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,604
|
test_settings.cpp
|
canonical_multipass/tests/test_settings.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_settings.h"
#include <multipass/settings/settings_handler.h>
#include <QString>
#include <algorithm>
#include <array>
#include <memory>
#include <variant>
namespace mp = multipass;
namespace mpt = mp::test;
using namespace testing;
namespace
{
class TestSettings : public Test
{
public:
class SettingsResetter : public mp::Settings
{
public:
static void reset()
{
mp::Settings::reset();
}
};
void TearDown() override
{
SettingsResetter::reset(); // expectations on MockHandlers verified here (unless manually unregistered earlier)
}
std::pair<QString, QString> make_setting(unsigned index)
{
return std::pair(QString("k%1").arg(index), QString("v%1").arg(index));
};
std::pair<unsigned, bool> half_and_is_odd(unsigned i)
{
auto half_i_div = std::div(i, 2); // can't use structured bindings directly: quot/rem order unspecified
return std::pair(static_cast<unsigned>(half_i_div.quot), static_cast<bool>(half_i_div.rem));
}
};
class MockSettingsHandler : public mp::SettingsHandler
{
public:
using SettingsHandler::SettingsHandler;
MOCK_METHOD(std::set<QString>, keys, (), (const, override));
MOCK_METHOD(QString, get, (const QString&), (const, override));
MOCK_METHOD(void, set, (const QString& key, const QString& val), (override));
};
TEST_F(TestSettings, keysReturnsNoKeysWhenNoHandler)
{
EXPECT_THAT(MP_SETTINGS.keys(), IsEmpty());
}
TEST_F(TestSettings, keysReturnsKeysFromSingleHandler)
{
auto some_keys = {QStringLiteral("a.b"), QStringLiteral("c.d.e"), QStringLiteral("f")};
auto mock_handler = std::make_unique<MockSettingsHandler>();
EXPECT_CALL(*mock_handler, keys).WillOnce(Return(some_keys));
MP_SETTINGS.register_handler(std::move(mock_handler));
EXPECT_THAT(MP_SETTINGS.keys(), UnorderedElementsAreArray(some_keys));
}
TEST_F(TestSettings, keysReturnsKeysFromMultipleHandlers)
{
auto some_keychains =
std::array{std::set({QStringLiteral("asdf.fdsa"), QStringLiteral("blah.bleh")}),
std::set({QStringLiteral("qwerty.ytrewq"), QStringLiteral("foo"), QStringLiteral("bar")}),
std::set({QStringLiteral("a.b.c.d")})};
for (auto i = 0u; i < some_keychains.size(); ++i)
{
auto mock_handler = std::make_unique<MockSettingsHandler>();
EXPECT_CALL(*mock_handler, keys).WillOnce(Return(some_keychains[i])); // copies, so ok to modify below
MP_SETTINGS.register_handler(std::move(mock_handler));
}
auto all_keys = std::reduce(std::begin(some_keychains), std::end(some_keychains), // hands-off clang-format
std::set<QString>{}, [](auto&& a, auto&& b) {
a.merge(std::forward<decltype(b)>(b));
return std::forward<decltype(a)>(a);
});
EXPECT_THAT(MP_SETTINGS.keys(), UnorderedElementsAreArray(all_keys));
}
TEST_F(TestSettings, getThrowsUnrecognizedWhenNoHandler)
{
auto key = "qwer";
MP_EXPECT_THROW_THAT(MP_SETTINGS.get(key), mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(key)));
}
TEST_F(TestSettings, getThrowsUnrecognizedFromSingleHandler)
{
auto key = "asdf";
auto mock_handler = std::make_unique<MockSettingsHandler>();
EXPECT_CALL(*mock_handler, get(Eq(key))).WillOnce(Throw(mp::UnrecognizedSettingException{key}));
MP_SETTINGS.register_handler(std::move(mock_handler));
MP_EXPECT_THROW_THAT(MP_SETTINGS.get(key), mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(key)));
}
TEST_F(TestSettings, getThrowsUnrecognizedAfterTryingAllHandlers)
{
auto key = "zxcv";
for (auto i = 0; i < 10; ++i)
{
auto mock_handler = std::make_unique<MockSettingsHandler>();
EXPECT_CALL(*mock_handler, get(Eq(key))).WillOnce(Throw(mp::UnrecognizedSettingException{key}));
MP_SETTINGS.register_handler(std::move(mock_handler));
}
MP_EXPECT_THROW_THAT(MP_SETTINGS.get(key), mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(key)));
}
TEST_F(TestSettings, getReturnsSettingFromSingleHandler)
{
auto key = "asdf", val = "vvv";
auto mock_handler = std::make_unique<MockSettingsHandler>();
EXPECT_CALL(*mock_handler, get(Eq(key))).WillOnce(Return(val));
MP_SETTINGS.register_handler(std::move(mock_handler));
EXPECT_EQ(MP_SETTINGS.get(key), val);
}
using NumHandlersAndHitIndex = std::tuple<unsigned, unsigned>;
class TestSettingsGetMultipleHandlers : public TestSettings, public WithParamInterface<NumHandlersAndHitIndex>
{
};
TEST_P(TestSettingsGetMultipleHandlers, getReturnsSettingFromFirstHandlerHit)
{
constexpr auto key = "τ", val = "2π";
auto [num_handlers, hit_index] = GetParam();
ASSERT_GT(num_handlers, 0u);
ASSERT_GT(num_handlers, hit_index);
for (auto i = 0u; i < num_handlers; ++i)
{
auto mock_handler = std::make_unique<MockSettingsHandler>();
if (i < hit_index)
{
EXPECT_CALL(*mock_handler, get(Eq(key))).WillOnce(Throw(mp::UnrecognizedSettingException{key}));
}
else if (i == hit_index)
{
EXPECT_CALL(*mock_handler, get(Eq(key))).WillOnce(Return(val));
}
else
{
EXPECT_CALL(*mock_handler, get).Times(0);
}
MP_SETTINGS.register_handler(std::move(mock_handler));
}
EXPECT_EQ(MP_SETTINGS.get(key), val);
}
INSTANTIATE_TEST_SUITE_P(TestSettings, TestSettingsGetMultipleHandlers, Combine(Values(30u), Range(0u, 30u, 3u)));
TEST_F(TestSettings, getReturnsSettingsFromDifferentHandlers)
{
constexpr auto num_settings = 3u;
constexpr auto num_handlers = num_settings * 2u;
constexpr auto unknown_key = "?";
for (auto i = 0u; i < num_handlers; ++i)
{
auto mock_handler = std::make_unique<MockSettingsHandler>();
auto [half_i, odd_i] = half_and_is_odd(i);
for (auto j = 0u; j < num_settings; ++j)
{
auto [key, val] = make_setting(j);
auto& expectation = EXPECT_CALL(*mock_handler, get(Eq(key)));
if (j == half_i && !odd_i)
expectation.WillOnce(Return(val));
else if (j <= half_i)
expectation.Times(0);
else
expectation.WillOnce(Throw(mp::UnrecognizedSettingException{key}));
}
EXPECT_CALL(*mock_handler, get(Eq(unknown_key))).WillOnce(Throw(mp::UnrecognizedSettingException{unknown_key}));
MP_SETTINGS.register_handler(std::move(mock_handler));
}
for (auto i = 0u; i < num_settings; ++i)
{
auto [key, val] = make_setting(i);
EXPECT_EQ(MP_SETTINGS.get(key), val);
}
MP_EXPECT_THROW_THAT(MP_SETTINGS.get(unknown_key), mp::UnrecognizedSettingException,
mpt::match_what(HasSubstr(unknown_key)));
}
TEST_F(TestSettings, setThrowsUnrecognizedWhenNoHandler)
{
auto key = "poiu";
MP_EXPECT_THROW_THAT(MP_SETTINGS.set(key, "qwer"), mp::UnrecognizedSettingException,
mpt::match_what(HasSubstr(key)));
}
TEST_F(TestSettings, setThrowsUnrecognizedFromSingleHandler)
{
auto key = "lkjh", val = "asdf";
auto mock_handler = std::make_unique<MockSettingsHandler>();
EXPECT_CALL(*mock_handler, set(Eq(key), Eq(val))).WillOnce(Throw(mp::UnrecognizedSettingException{key}));
MP_SETTINGS.register_handler(std::move(mock_handler));
MP_EXPECT_THROW_THAT(MP_SETTINGS.set(key, val), mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(key)));
}
TEST_F(TestSettings, setThrowsUnrecognizedAfterTryingAllHandlers)
{
auto key = "mnbv", val = "zxcv";
for (auto i = 0u; i < 10; ++i)
{
auto mock_handler = std::make_unique<MockSettingsHandler>();
EXPECT_CALL(*mock_handler, set(Eq(key), Eq(val))).WillRepeatedly(Throw(mp::UnrecognizedSettingException{key}));
MP_SETTINGS.register_handler(std::move(mock_handler));
}
MP_EXPECT_THROW_THAT(MP_SETTINGS.set(key, val), mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(key)));
}
TEST_F(TestSettings, setDelegatesOnSingleHandler)
{
auto key = "xyz", val = "zyx";
auto mock_handler = std::make_unique<MockSettingsHandler>();
EXPECT_CALL(*mock_handler, set(Eq(key), Eq(val)));
MP_SETTINGS.register_handler(std::move(mock_handler));
EXPECT_NO_THROW(MP_SETTINGS.set(key, val));
}
TEST_F(TestSettings, setDelegatesOnAllHandlers)
{
auto key = "boo", val = "far";
for (auto i = 0; i < 5; ++i)
{
auto mock_handler = std::make_unique<MockSettingsHandler>();
EXPECT_CALL(*mock_handler, set(Eq(key), Eq(val)));
MP_SETTINGS.register_handler(std::move(mock_handler));
}
EXPECT_NO_THROW(MP_SETTINGS.set(key, val));
}
using Indices = std::initializer_list<unsigned>;
using NumHandlersAndHitIndices = std::tuple<unsigned, Indices>;
class TestSettingsSetMultipleHandlers : public TestSettings, public WithParamInterface<NumHandlersAndHitIndices>
{
};
TEST_P(TestSettingsSetMultipleHandlers, setDelegatesOnMultipleHandlers)
{
auto key = "boo", val = "far";
auto [num_handlers, hit_indices] = GetParam();
ASSERT_GT(num_handlers, 0u);
ASSERT_GT(hit_indices.size(), 0u);
ASSERT_THAT(hit_indices, Each(Lt(num_handlers)));
for (auto i = 0u; i < num_handlers; ++i)
{
auto mock_handler = std::make_unique<MockSettingsHandler>();
auto& expectation = EXPECT_CALL(*mock_handler, set(Eq(key), Eq(val)));
if (std::find(hit_indices.begin(), hit_indices.end(), i) == hit_indices.end())
expectation.WillOnce(Throw(mp::UnrecognizedSettingException{key}));
MP_SETTINGS.register_handler(std::move(mock_handler));
}
EXPECT_NO_THROW(MP_SETTINGS.set(key, val));
}
const auto test_indices = std::initializer_list<Indices>{{0u},
{9u},
{7u},
{0u, 4u},
{0u, 4u, 9u},
{1u, 2u, 3u},
{5u, 6u, 7u, 8u},
{1u, 3u, 5u, 7u},
{0u, 1u, 2u, 3u, 4u, 5u, 6u, 7u, 8u, 9u}};
INSTANTIATE_TEST_SUITE_P(TestSettings, TestSettingsSetMultipleHandlers, Combine(Values(10u), ValuesIn(test_indices)));
TEST_F(TestSettings, setDelegatesOnDifferentHandlers)
{
constexpr auto num_settings = 5u;
constexpr auto num_handlers = num_settings * 2u;
constexpr auto unknown_key = "hhhh";
for (auto i = 0u; i < num_handlers; ++i)
{
auto mock_handler = std::make_unique<MockSettingsHandler>();
auto [half_i, odd_i] = half_and_is_odd(i);
for (auto j = 0u; j < num_settings; ++j)
{
auto [key, val] = make_setting(j);
auto& expectation = EXPECT_CALL(*mock_handler, set(Eq(key), Eq(val)));
if (j < half_i || odd_i)
{
expectation.WillOnce(Throw(mp::UnrecognizedSettingException{key}));
}
}
EXPECT_CALL(*mock_handler, set(Eq(unknown_key), _))
.WillOnce(Throw(mp::UnrecognizedSettingException{unknown_key}));
MP_SETTINGS.register_handler(std::move(mock_handler));
}
for (auto i = 0u; i < num_settings; ++i)
{
auto [key, val] = make_setting(i);
EXPECT_NO_THROW(MP_SETTINGS.set(key, val));
}
MP_EXPECT_THROW_THAT(MP_SETTINGS.set(unknown_key, "asdf"), mp::UnrecognizedSettingException,
mpt::match_what(HasSubstr(unknown_key)));
}
using SetException = std::variant<mp::UnrecognizedSettingException, mp::InvalidSettingException, std::runtime_error>; /*
We need to throw an exception of the ultimate type whose handling we're trying to test (to avoid slicing and enter the
right catch block). Therefore, we can't just use a base exception type. Parameterized and typed tests don't mix in
gtest, so we use a variant parameter. */
using SetExceptNumHandlersAndThrowerIdx = std::tuple<SetException, unsigned, unsigned>;
class TestSettingSetOtherExceptions : public TestSettings, public WithParamInterface<SetExceptNumHandlersAndThrowerIdx>
{
};
TEST_P(TestSettingSetOtherExceptions, setThrowsOtherExceptionsFromAnyHandler)
{
constexpr auto key = "F", val = "X";
constexpr auto thrower = [](const auto& e) { throw e; };
auto [except, num_handlers, thrower_idx] = GetParam();
ASSERT_GT(num_handlers, 0u);
ASSERT_GT(num_handlers, thrower_idx);
for (auto i = 0u; i < num_handlers; ++i)
{
auto mock_handler = std::make_unique<MockSettingsHandler>();
auto& expectation = EXPECT_CALL(*mock_handler, set(Eq(key), Eq(val)));
if (i == thrower_idx)
expectation.WillOnce(WithoutArgs([&thrower, e = &except] { std::visit(thrower, *e); })); /* lambda capture
with initializer works around forbidden capture of structured binding */
else if (i > thrower_idx)
expectation.Times(0);
MP_SETTINGS.register_handler(std::move(mock_handler));
}
auto get_what = [](const auto& e) { return e.what(); };
MP_EXPECT_THROW_THAT(MP_SETTINGS.set(key, val), std::exception,
mpt::match_what(StrEq(std::visit(get_what, except))));
}
INSTANTIATE_TEST_SUITE_P(TestSettings, TestSettingSetOtherExceptions,
Combine(Values(mp::InvalidSettingException{"foo", "bar", "err"},
std::runtime_error{"something else"}),
Values(8u), Range(0u, 8u, 2u)));
struct TestSettingsGetAs : public Test
{
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
};
template <typename T>
struct SettingValueRepresentation
{
T val;
QStringList reprs;
};
template <typename T>
std::vector<SettingValueRepresentation<T>> setting_val_reprs();
template <>
std::vector<SettingValueRepresentation<bool>> setting_val_reprs()
{
return {{false, {"False", "false", "0", ""}}, {true, {"True", "true", "1", "no", "off", "anything else"}}};
}
template <>
std::vector<SettingValueRepresentation<int>> setting_val_reprs()
{
return {{0, {"0", "+0", "-0000"}}, {42, {"42", "+42"}}, {-2, {"-2"}}, {23, {"023"}}}; // no hex or octal
}
template <typename T>
struct TestSuccessfulSettingsGetAs : public TestSettingsGetAs
{
};
using GetAsTestTypes = ::testing::Types<bool, int>; // to add more, specialize setting_val_reprs above
MP_TYPED_TEST_SUITE(TestSuccessfulSettingsGetAs, GetAsTestTypes);
TYPED_TEST(TestSuccessfulSettingsGetAs, getAsConvertsValues)
{
InSequence seq;
const auto key = "whatever";
for (const auto& [val, reprs] : setting_val_reprs<TypeParam>())
{
for (const auto& repr : reprs)
{
EXPECT_CALL(this->mock_settings, get(Eq(key))).WillOnce(Return(repr)); // needs `this` ¯\_(ツ)_/¯
EXPECT_EQ(MP_SETTINGS.get_as<TypeParam>(key), val);
}
}
}
TEST_F(TestSettingsGetAs, getAsThrowsOnUnsupportedTypeConversion)
{
const auto key = "the.key";
const auto bad_repr = "#$%!@";
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Return(bad_repr));
MP_ASSERT_THROW_THAT(MP_SETTINGS.get_as<QVariant>(key), mp::UnsupportedSettingValueType<QVariant>,
mpt::match_what(HasSubstr(key)));
}
TEST_F(TestSettingsGetAs, getAsReturnsDefaultOnBadValue)
{
const auto key = "a.key";
const auto bad_int = "ceci n'est pas une int";
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Return(bad_int));
EXPECT_EQ(MP_SETTINGS.get_as<int>(key), 0);
}
} // namespace
| 16,707
|
C++
|
.cpp
| 384
| 36.427083
| 120
| 0.649711
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,605
|
test_singleton.cpp
|
canonical_multipass/tests/test_singleton.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <multipass/singleton.h>
#include <string>
namespace mp = multipass;
using namespace testing;
namespace
{
class TestSingleton : public mp::Singleton<TestSingleton>
{
public:
using Singleton<TestSingleton>::Singleton; // ctor
virtual std::string foo() const
{
return "Hi from singleton";
}
};
class MockTestSingleton : public TestSingleton
{
public:
using TestSingleton::TestSingleton; // ctor
static void mock()
{
TestSingleton::mock<MockTestSingleton>();
}
static void reset() // not thread-safe, make sure no other threads using this singleton
{
TestSingleton::reset();
}
std::string foo() const override
{
return "Hi from mock";
}
};
TEST(Singleton, singleton_can_be_mocked_and_reset)
{
const auto mock_matcher = HasSubstr("mock");
ASSERT_THAT(TestSingleton::instance().foo(), Not(mock_matcher));
MockTestSingleton::reset();
MockTestSingleton::mock();
ASSERT_THAT(TestSingleton::instance().foo(), mock_matcher);
MockTestSingleton::reset();
ASSERT_THAT(TestSingleton::instance().foo(), Not(mock_matcher));
}
// safety demo
class TryMultipleton : public mp::Singleton<TryMultipleton>
{
public:
// TryMultipleton() = default; // compilation fails when called
// TryMultipleton()
// : Singleton<TryMultipleton>{Singleton<TryMultipleton>::pass} // error: private
// {}
struct lockpick
{
} pick{};
// TryMultipleton()
// : Singleton<TryMultipleton>{reinterpret_cast<Singleton<TryMultipleton>::PrivatePass>(pick)} // bad cast
// : Singleton<TryMultipleton>{(Singleton<TryMultipleton>::PrivatePass)(pick)} // no way to convert
// {}
};
} // namespace
| 2,391
|
C++
|
.cpp
| 76
| 27.934211
| 114
| 0.708442
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,606
|
test_instance_settings_handler.cpp
|
canonical_multipass/tests/test_instance_settings_handler.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_virtual_machine.h"
#include <multipass/constants.h>
#include <multipass/utils.h>
#include <multipass/virtual_machine.h>
#include <multipass/vm_specs.h>
#include <src/daemon/instance_settings_handler.h>
#include <QString>
#include <memory>
#include <string>
#include <tuple>
#include <unordered_map>
namespace mp = multipass;
namespace mpt = mp::test;
namespace mpu = mp::utils;
using namespace testing;
namespace
{
enum class SpecialInstanceState
{
none,
preparing,
deleted
};
using InstanceName = const char*;
struct TestInstanceSettingsHandler : public Test
{
mp::InstanceSettingsHandler make_handler()
{
return mp::InstanceSettingsHandler{specs,
vms,
deleted_vms,
preparing_vms,
make_fake_persister(),
make_fake_is_bridged(),
make_fake_add()};
}
void fake_instance_state(const char* name, SpecialInstanceState special_state)
{
if (special_state == SpecialInstanceState::preparing)
preparing_vms.emplace(name);
else if (special_state == SpecialInstanceState::deleted)
deleted_vms[name];
}
std::function<void()> make_fake_persister()
{
return [this] { fake_persister_called = true; };
}
std::function<std::string()> make_fake_bridged_interface()
{
return [this] { return bridged_interface; };
}
std::function<std::string()> make_fake_bridge_name()
{
return [] { return "br-eth8"; };
}
std::function<std::vector<mp::NetworkInterfaceInfo>()> make_fake_host_networks()
{
std::vector<mp::NetworkInterfaceInfo> ret;
ret.push_back(mp::NetworkInterfaceInfo{"eth8", "ethernet", "Ethernet device", {}, true});
ret.push_back(mp::NetworkInterfaceInfo{"virbr0", "bridge", "Network bridge", {}, false});
return [ret] { return ret; };
}
std::function<bool()> make_fake_authorization()
{
return [this]() { return user_authorized; };
}
std::function<bool(const std::string&)> make_fake_is_bridged()
{
return [this](const std::string& n) {
const std::string br_interface{"eth8"};
const std::string br_name{"br-" + br_interface};
const auto& spec = specs[n];
return std::any_of(spec.extra_interfaces.cbegin(),
spec.extra_interfaces.cend(),
[&br_interface, &br_name](const auto& network) -> bool {
return network.id == br_interface || network.id == br_name;
});
};
}
std::function<void(const std::string&)> make_fake_add()
{
return [this](const std::string& n) {
if (!make_fake_is_bridged()(n))
specs[n].extra_interfaces.push_back(mp::NetworkInterface{"eth8", mpu::generate_mac_address(), true});
};
}
template <template <typename /*MockClass*/> typename MockCharacter = ::testing::NiceMock>
mpt::MockVirtualMachine& mock_vm(const std::string& name, bool deleted = false)
{
auto ret = std::make_shared<MockCharacter<mpt::MockVirtualMachine>>(name);
auto& vm_collection = deleted ? deleted_vms : vms;
vm_collection.emplace(name, ret);
return *ret;
}
// empty components to fill before creating handler
std::unordered_map<std::string, mp::VMSpecs> specs;
std::unordered_map<std::string, mp::VirtualMachine::ShPtr> vms;
std::unordered_map<std::string, mp::VirtualMachine::ShPtr> deleted_vms;
std::unordered_set<std::string> preparing_vms;
std::string bridged_interface{"eth8"};
bool fake_persister_called = false;
bool user_authorized = true;
inline static constexpr std::array numeric_properties{"cpus", "disk", "memory"};
inline static constexpr std::array boolean_properties{"bridged"};
inline static constexpr std::array properties{"cpus", "disk", "memory", "bridged"};
};
QString make_key(const QString& instance_name, const QString& property)
{
return QString("%1.%2.%3").arg(mp::daemon_settings_root, instance_name, property);
}
using Instance = std::tuple<InstanceName, SpecialInstanceState>;
using Instances = std::vector<Instance>;
using InstanceLists = std::vector<Instances>;
struct TestInstanceSettingsKeys : public TestInstanceSettingsHandler, public WithParamInterface<Instances>
{
};
TEST_P(TestInstanceSettingsKeys, keysCoversAllPropertiesForAllInstances)
{
const auto intended_instances = GetParam();
auto expected_keys = std::vector<QString>{};
for (const auto& [name, special_state] : intended_instances)
{
specs[name];
fake_instance_state(name, special_state);
for (const auto& prop : properties)
expected_keys.push_back(make_key(name, prop));
}
EXPECT_THAT(make_handler().keys(), UnorderedElementsAreArray(expected_keys));
}
INSTANTIATE_TEST_SUITE_P(TestInstanceSettingsKeysEmpty, TestInstanceSettingsKeys, Values(Instances{}));
INSTANTIATE_TEST_SUITE_P(TestInstanceSettingsKeysSingle, TestInstanceSettingsKeys,
Values(Instances{{"morning-light-mountain", SpecialInstanceState::none}},
Instances{{"morning-light-mountain", SpecialInstanceState::deleted}},
Instances{{"morning-light-mountain", SpecialInstanceState::preparing}}));
INSTANTIATE_TEST_SUITE_P(TestInstanceSettingsKeysMultiple, TestInstanceSettingsKeys,
ValuesIn(InstanceLists{{{"foo", SpecialInstanceState::none},
{"bar", SpecialInstanceState::none},
{"baz", SpecialInstanceState::none}},
{{"foo", SpecialInstanceState::deleted},
{"bar", SpecialInstanceState::preparing},
{"baz", SpecialInstanceState::preparing}},
{{"foo", SpecialInstanceState::deleted},
{"bar", SpecialInstanceState::none},
{"baz", SpecialInstanceState::deleted}},
{{"foo", SpecialInstanceState::preparing},
{"bar", SpecialInstanceState::preparing},
{"baz", SpecialInstanceState::none}},
{{"foo", SpecialInstanceState::none},
{"bar", SpecialInstanceState::none},
{"baz", SpecialInstanceState::preparing}}}));
TEST_F(TestInstanceSettingsHandler, keysDoesNotPersistInstances)
{
specs.insert({{"abc", {}}, {"xyz", {}}, {"blah", {}}});
deleted_vms["blah"];
preparing_vms.emplace("xyz");
make_handler().keys();
EXPECT_FALSE(fake_persister_called);
}
TEST_F(TestInstanceSettingsHandler, getFetchesInstanceCPUs)
{
constexpr auto target_instance_name = "foo";
specs.insert({{target_instance_name, {}}, {"bar", {}}, {"baz", {}}});
specs[target_instance_name].num_cores = 78;
auto got = make_handler().get(make_key(target_instance_name, "cpus"));
EXPECT_EQ(got, QString::number(specs[target_instance_name].num_cores));
}
TEST_F(TestInstanceSettingsHandler, getFetchesInstanceMemory)
{
constexpr auto target_instance_name = "elsa";
specs.insert({{"hugo", {}}, {target_instance_name, {}}, {"flint", {}}});
specs[target_instance_name].mem_size = mp::MemorySize{"789MiB"};
auto got = make_handler().get(make_key(target_instance_name, "memory"));
got.remove(".0"); // TODO drop decimal removal once MemorySize accepts it as input
EXPECT_EQ(mp::MemorySize{got.toStdString()}, specs[target_instance_name].mem_size); /* note that this doesn't work
for all values, because the value is returned in human readable format, which approximates (unless and until --raw
is used/implemented) */
}
TEST_F(TestInstanceSettingsHandler, getFetchesInstanceDisk)
{
constexpr auto target_instance_name = "blue";
specs.insert({{"rhapsody", {}}, {"in", {}}, {target_instance_name, {}}});
specs[target_instance_name].disk_space = mp::MemorySize{"123G"};
auto got = make_handler().get(make_key(target_instance_name, "disk"));
got.remove(".0"); // TODO idem
EXPECT_EQ(mp::MemorySize{got.toStdString()}, specs[target_instance_name].disk_space); // idem
}
TEST_F(TestInstanceSettingsHandler, getReturnsMemorySizesInHumanReadableFormat)
{
constexpr auto target_instance_name = "tinkerbell-hates-goatees";
specs[target_instance_name].disk_space = mp::MemorySize{"12345KiB"};
specs[target_instance_name].mem_size = mp::MemorySize{"345678"};
const auto handler = make_handler();
EXPECT_EQ(handler.get(make_key(target_instance_name, "disk")), "12.1MiB");
EXPECT_EQ(handler.get(make_key(target_instance_name, "memory")), "337.6KiB");
}
struct TestBridgedInstanceSettings : public TestInstanceSettingsHandler,
public WithParamInterface<std::pair<std::string, bool>>
{
};
// Since the instance handler calls functions from the daemon, which were replaced here by other ones, this test just
// checks that the correct functions are called from the handler.
TEST_P(TestBridgedInstanceSettings, getFetchesBridged)
{
const auto [br_interface, bridged] = GetParam();
constexpr auto target_instance_name = "lemmy";
specs.insert({{"mikkey", {}}, {"phil", {}}, {target_instance_name, {}}});
specs[target_instance_name].extra_interfaces = {{br_interface, "52:54:00:12:34:56", true}};
const auto got = make_handler().get(make_key(target_instance_name, "bridged"));
EXPECT_EQ(got, bridged ? "true" : "false");
}
INSTANTIATE_TEST_SUITE_P(getFetchesBridged,
TestBridgedInstanceSettings,
Values(std::make_pair("eth8", true),
std::make_pair("br-eth8", true),
std::make_pair("eth9", false),
std::make_pair("br-eth9", false)));
TEST_F(TestInstanceSettingsHandler, getFetchesPropertiesOfInstanceInSpecialState)
{
constexpr auto preparing_instance = "nouvelle", deleted_instance = "vague";
specs[preparing_instance];
specs[deleted_instance];
fake_instance_state(preparing_instance, SpecialInstanceState::preparing);
fake_instance_state(deleted_instance, SpecialInstanceState::deleted);
const auto handler = make_handler();
for (const auto* instance : {preparing_instance, deleted_instance})
{
for (const auto& property : properties)
{
EXPECT_NO_THROW(handler.get(make_key(instance, property)));
}
}
}
TEST_F(TestInstanceSettingsHandler, getDoesNotPersistInstances)
{
constexpr auto ready_instance = "asdf", preparing_instance = "sdfg", deleted_instance = "dfgh";
constexpr auto instances = std::array{ready_instance, preparing_instance, deleted_instance};
for (const auto& instance : instances)
specs[instance];
fake_instance_state(preparing_instance, SpecialInstanceState::preparing);
fake_instance_state(deleted_instance, SpecialInstanceState::deleted);
const auto handler = make_handler();
auto property_it = std::begin(properties);
for (const auto& instance : instances)
{
assert(property_it != std::end(properties));
handler.get(make_key(instance, *property_it++));
}
EXPECT_FALSE(fake_persister_called);
}
TEST_F(TestInstanceSettingsHandler, constOperationsDoNotModifyInstances) /* note that `const` on the respective methods
isn't enough for the compiler to catch changes to vms and specs, which live outside the handler (only references held
there) */
{
constexpr auto make_mem_size = [](int gigs) { return mp::MemorySize{fmt::format("{}GiB", gigs)}; };
auto gigs = 1;
mp::VMSpecs spec;
spec.num_cores = 3;
spec.mem_size = make_mem_size(gigs);
spec.ssh_username = "hugo";
spec.default_mac_address = "+++++";
for (const auto* name : {"toto", "tata", "fuzz"})
{
vms[name];
specs.emplace(name, spec);
spec.mem_size = make_mem_size(++gigs);
++spec.num_cores;
}
auto specs_copy = specs;
auto vms_copy = vms;
auto handler = make_handler();
for (const auto& key : handler.keys())
handler.get(key);
EXPECT_EQ(specs, specs_copy);
EXPECT_EQ(vms, vms_copy);
}
TEST_F(TestInstanceSettingsHandler, getThrowsOnWrongProperty)
{
constexpr auto target_instance_name = "asdf";
constexpr auto wrong_property = "wrong";
specs[target_instance_name];
MP_EXPECT_THROW_THAT(make_handler().get(make_key(target_instance_name, wrong_property)),
mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(wrong_property)));
}
TEST_F(TestInstanceSettingsHandler, setIncreasesInstanceCPUs)
{
constexpr auto target_instance_name = "foo";
constexpr auto more_cpus = 6;
specs.insert({{"bar", {}}, {target_instance_name, {}}});
const auto& actual_cpus = specs[target_instance_name].num_cores = 4;
EXPECT_CALL(mock_vm(target_instance_name), update_cpus(more_cpus)).Times(1);
make_handler().set(make_key(target_instance_name, "cpus"), QString::number(more_cpus));
EXPECT_EQ(actual_cpus, more_cpus);
}
TEST_F(TestInstanceSettingsHandler, setMaintainsInstanceCPUsUntouchedIfSameButSucceeds)
{
constexpr auto target_instance_name = "asdf";
constexpr auto same_cpus = 42;
const auto& actual_cpus = specs[target_instance_name].num_cores = same_cpus;
EXPECT_CALL(mock_vm(target_instance_name), update_cpus).Times(0);
EXPECT_NO_THROW(make_handler().set(make_key(target_instance_name, "cpus"), QString::number(same_cpus)));
EXPECT_EQ(actual_cpus, same_cpus);
}
TEST_F(TestInstanceSettingsHandler, setAllowsDecreaseInstanceCPUs)
{
constexpr auto target_instance_name = "sdfg";
constexpr auto less_cpus = 2;
const auto& actual_cpus = specs[target_instance_name].num_cores = 3;
EXPECT_CALL(mock_vm(target_instance_name), update_cpus).Times(1);
EXPECT_NO_THROW(make_handler().set(make_key(target_instance_name, "cpus"), QString::number(less_cpus)));
EXPECT_EQ(actual_cpus, less_cpus);
}
TEST_F(TestInstanceSettingsHandler, setExpandsInstanceMemory)
{
constexpr auto target_instance_name = "desmond";
constexpr auto more_mem_str = "64G";
const auto more_mem = mp::MemorySize{more_mem_str};
const auto& actual_mem = specs[target_instance_name].mem_size = mp::MemorySize{"512M"};
EXPECT_CALL(mock_vm(target_instance_name), resize_memory(Eq(more_mem))).Times(1);
make_handler().set(make_key(target_instance_name, "memory"), more_mem_str);
EXPECT_EQ(actual_mem, more_mem);
}
TEST_F(TestInstanceSettingsHandler, setMaintainsInstanceMemoryUntouchedIfSameButSucceeds)
{
constexpr auto target_instance_name = "Liszt";
constexpr auto same_mem_str = "1234567890";
const auto same_mem = mp::MemorySize{same_mem_str};
const auto& actual_mem = specs[target_instance_name].mem_size = same_mem;
EXPECT_CALL(mock_vm(target_instance_name), resize_memory).Times(0);
EXPECT_NO_THROW(make_handler().set(make_key(target_instance_name, "memory"), same_mem_str));
EXPECT_EQ(actual_mem, same_mem);
}
TEST_F(TestInstanceSettingsHandler, setAllowsDecreaseInstanceMemory)
{
constexpr auto target_instance_name = "Dvořák";
constexpr auto less_mem_str = "256MiB";
const auto less_mem = mp::MemorySize{less_mem_str};
const auto& actual_mem = specs[target_instance_name].mem_size = mp::MemorySize{"1024MiB"};
EXPECT_CALL(mock_vm(target_instance_name), resize_memory).Times(1);
EXPECT_NO_THROW(make_handler().set(make_key(target_instance_name, "memory"), less_mem_str));
EXPECT_EQ(actual_mem, less_mem);
}
TEST_F(TestInstanceSettingsHandler, setRefusesDecreaseBelowMinimumMemory)
{
constexpr auto target_instance_name = "Ravel";
constexpr auto mem_str = "96MiB";
const auto& actual_mem = specs[target_instance_name].mem_size = mp::MemorySize{"1024MiB"};
const auto original_mem = actual_mem;
EXPECT_CALL(mock_vm(target_instance_name), resize_memory).Times(0);
MP_EXPECT_THROW_THAT(make_handler().set(make_key(target_instance_name, "memory"), mem_str),
mp::InvalidSettingException, mpt::match_what(HasSubstr("minimum not allowed")));
EXPECT_EQ(actual_mem, original_mem);
}
TEST_F(TestInstanceSettingsHandler, setExpandsInstanceDisk)
{
constexpr auto target_instance_name = "Rimsky-Korsakov";
constexpr auto more_disk_str = "20G";
const auto more_disk = mp::MemorySize{more_disk_str};
const auto& actual_disk = specs[target_instance_name].disk_space = mp::MemorySize{"5G"};
EXPECT_CALL(mock_vm(target_instance_name), resize_disk(Eq(more_disk))).Times(1);
make_handler().set(make_key(target_instance_name, "disk"), more_disk_str);
EXPECT_EQ(actual_disk, more_disk);
}
TEST_F(TestInstanceSettingsHandler, setMaintainsInstanceDiskUntouchedIfSameButSucceeds)
{
constexpr auto target_instance_name = "Gershwin";
constexpr auto same_disk_str = "888999777K";
const auto same_disk = mp::MemorySize{same_disk_str};
const auto& actual_disk = specs[target_instance_name].disk_space = same_disk;
EXPECT_CALL(mock_vm(target_instance_name), resize_disk).Times(0);
EXPECT_NO_THROW(make_handler().set(make_key(target_instance_name, "disk"), same_disk_str));
EXPECT_EQ(actual_disk, same_disk);
}
TEST_F(TestInstanceSettingsHandler, setResusesToShrinkInstanceDisk)
{
constexpr auto target_instance_name = "Chopin";
constexpr auto less_disk_str = "7Mb";
const auto& actual_disk = specs[target_instance_name].disk_space = mp::MemorySize{"2Gb"};
const auto original_disk = actual_disk;
EXPECT_CALL(mock_vm(target_instance_name), resize_disk).Times(0);
MP_EXPECT_THROW_THAT(make_handler().set(make_key(target_instance_name, "disk"), less_disk_str),
mp::InvalidSettingException, mpt::match_what(HasSubstr("can only be expanded")));
EXPECT_EQ(actual_disk, original_disk);
}
TEST_F(TestInstanceSettingsHandler, setRefusesWrongProperty)
{
constexpr auto target_instance_name = "desmond";
constexpr auto wrong_property = "nuts";
const auto original_specs = specs[target_instance_name];
EXPECT_CALL(mock_vm(target_instance_name), update_cpus).Times(0);
MP_EXPECT_THROW_THAT(make_handler().set(make_key(target_instance_name, wrong_property), "1"),
mp::UnrecognizedSettingException, mpt::match_what(HasSubstr(wrong_property)));
EXPECT_EQ(original_specs, specs[target_instance_name]);
}
TEST_F(TestInstanceSettingsHandler, setRefusesToUnbridge)
{
constexpr auto target_instance_name = "hendrix";
specs.insert({{"voodoo", {}}, {"chile", {}}, {target_instance_name, {}}});
specs[target_instance_name].extra_interfaces = {{"eth8", "52:54:00:78:90:12", true}};
mock_vm(target_instance_name); // TODO: make this an expectation.
MP_EXPECT_THROW_THAT(make_handler().set(make_key(target_instance_name, "bridged"), "false"),
mp::InvalidSettingException,
mpt::match_what(HasSubstr("not supported")));
}
TEST_F(TestInstanceSettingsHandler, setAddsInterface)
{
constexpr auto target_instance_name = "pappo";
specs.insert({{"blues", {}}, {"local", {}}, {target_instance_name, {}}});
specs[target_instance_name].extra_interfaces = {{"id", "52:54:00:45:67:89", true}};
mock_vm(target_instance_name); // TODO: make this an expectation.
make_handler().set(make_key(target_instance_name, "bridged"), "true");
EXPECT_EQ(specs[target_instance_name].extra_interfaces.size(), 2u);
EXPECT_TRUE(mpu::valid_mac_address(specs[target_instance_name].extra_interfaces[1].mac_address));
}
TEST_F(TestInstanceSettingsHandler, setDoesNotAddTwoInterfaces)
{
constexpr auto target_instance_name = "vitico";
specs.insert({{"viticus", {}}, {"super", {}}, {target_instance_name, {}}});
specs[target_instance_name].extra_interfaces = {{"br-eth8", "52:54:00:45:67:90", true}};
mock_vm(target_instance_name); // TODO: make this an expectation.
auto got = make_handler().get(make_key(target_instance_name, "bridged"));
EXPECT_EQ(got, "true");
make_handler().set(make_key(target_instance_name, "bridged"), "true");
EXPECT_EQ(specs[target_instance_name].extra_interfaces.size(), 1u);
}
using VMSt = mp::VirtualMachine::State;
using Property = const char*;
using PropertyAndState = std::tuple<Property, VMSt>; // no subliminal political msg intended :)
struct TestInstanceModOnNonStoppedInstance : public TestInstanceSettingsHandler,
public WithParamInterface<PropertyAndState>
{
};
TEST_P(TestInstanceModOnNonStoppedInstance, setRefusesToModifyNonStoppedInstances)
{
constexpr auto target_instance_name = "Mozart";
const auto [property, state] = GetParam();
const auto original_specs = specs[target_instance_name];
auto& target_instance = mock_vm<StrictMock>(target_instance_name);
EXPECT_CALL(target_instance, current_state).WillOnce(Return(state));
MP_EXPECT_THROW_THAT(make_handler().set(make_key(target_instance_name, property), "123"),
mp::InstanceSettingsException,
mpt::match_what(AllOf(HasSubstr("Cannot update"), HasSubstr("Instance must be stopped"))));
EXPECT_EQ(original_specs, specs[target_instance_name]);
}
INSTANTIATE_TEST_SUITE_P(TestInstanceSettingsHandler, TestInstanceModOnNonStoppedInstance,
Combine(ValuesIn(TestInstanceSettingsHandler::properties),
Values(VMSt::running, VMSt::restarting, VMSt::starting, VMSt::delayed_shutdown,
VMSt::suspended, VMSt::suspending, VMSt::unknown)));
struct TestInstanceModOnStoppedInstance : public TestInstanceSettingsHandler,
public WithParamInterface<PropertyAndState>
{
};
TEST_P(TestInstanceModOnStoppedInstance, setWorksOnOtherStates)
{
constexpr auto target_instance_name = "Beethoven";
constexpr auto val = "134217728"; // To work with the 128M minimum allowed for memory
const auto [property, state] = GetParam();
const auto& target_specs = specs[target_instance_name];
EXPECT_CALL(mock_vm(target_instance_name), current_state).WillOnce(Return(state));
EXPECT_NO_THROW(make_handler().set(make_key(target_instance_name, property), val));
const auto props = {static_cast<long long>(target_specs.num_cores), target_specs.mem_size.in_bytes(),
target_specs.disk_space.in_bytes()};
EXPECT_THAT(props, Contains(QString{val}.toLongLong()));
}
INSTANTIATE_TEST_SUITE_P(TestInstanceSettingsHandler,
TestInstanceModOnStoppedInstance,
Combine(ValuesIn(TestInstanceSettingsHandler::numeric_properties),
Values(VMSt::off, VMSt::stopped)));
struct TestInstanceModPersists : public TestInstanceSettingsHandler, public WithParamInterface<Property>
{
};
TEST_P(TestInstanceModPersists, setPersistsInstances)
{
constexpr auto target_instance_name = "Tchaikovsky";
constexpr auto val = "134217728"; // To work with the 128M minimum allowed for memory
const auto property = GetParam();
specs[target_instance_name];
mock_vm(target_instance_name);
make_handler().set(make_key(target_instance_name, property), val);
EXPECT_TRUE(fake_persister_called);
}
INSTANTIATE_TEST_SUITE_P(TestInstanceSettingsHandler,
TestInstanceModPersists,
ValuesIn(TestInstanceSettingsHandler::numeric_properties));
TEST_F(TestInstanceSettingsHandler, setRefusesToModifyInstancesInSpecialState)
{
constexpr auto preparing_instance_name = "Yann", deleted_instance_name = "Tiersen";
specs[preparing_instance_name];
specs[deleted_instance_name];
const auto original_specs = specs;
fake_instance_state(preparing_instance_name, SpecialInstanceState::preparing);
auto& preparing_instance = mock_vm(preparing_instance_name);
auto& deleted_instance = mock_vm(deleted_instance_name, /*deleted=*/true);
auto handler = make_handler();
for (const auto& [instance, instance_name, special_state] :
{std::tuple{&preparing_instance, preparing_instance_name, "prepared"},
std::tuple{&deleted_instance, deleted_instance_name, "deleted"}})
{
EXPECT_CALL(*instance, update_cpus).Times(0);
EXPECT_CALL(*instance, resize_memory).Times(0);
EXPECT_CALL(*instance, resize_disk).Times(0);
for (const auto& property : properties)
{
MP_EXPECT_THROW_THAT(handler.set(make_key(instance_name, property), "234"), mp::InstanceSettingsException,
mpt::match_what(AllOf(HasSubstr("Cannot update"), HasSubstr(special_state))));
}
}
EXPECT_EQ(specs, original_specs);
}
TEST_F(TestInstanceSettingsHandler, getAndSetThrowOnMissingInstance)
{
constexpr auto instance = "missing-instance";
auto handler = make_handler();
for (const auto& prop : properties)
{
MP_EXPECT_THROW_THAT(handler.get(make_key(instance, prop)), mp::InstanceSettingsException,
mpt::match_what(AllOf(HasSubstr(instance), HasSubstr("No such instance"))));
MP_EXPECT_THROW_THAT(handler.set(make_key(instance, prop), "1"), mp::InstanceSettingsException,
mpt::match_what(AllOf(HasSubstr(instance), HasSubstr("No such instance"))));
}
}
TEST_F(TestInstanceSettingsHandler, getAndSetThrowOnBadKey)
{
constexpr auto bad_key = ".#^&nonsense-.-$-$";
MP_EXPECT_THROW_THAT(make_handler().get(bad_key), mp::UnrecognizedSettingException,
mpt::match_what(HasSubstr(bad_key)));
MP_EXPECT_THROW_THAT(make_handler().set(bad_key, "1"), mp::UnrecognizedSettingException,
mpt::match_what(HasSubstr(bad_key)));
}
using PlainValue = const char*;
using PropertyValue = std::tuple<Property, PlainValue>;
struct TestInstanceSettingsHandlerBadNumericValues : public TestInstanceSettingsHandler,
public WithParamInterface<PropertyValue>
{
};
TEST_P(TestInstanceSettingsHandlerBadNumericValues, setRefusesBadNumericValues)
{
constexpr auto target_instance_name = "xanana";
const auto& [property, bad_val] = GetParam();
const auto original_specs = specs[target_instance_name];
EXPECT_CALL(mock_vm(target_instance_name), update_cpus).Times(0);
MP_EXPECT_THROW_THAT(
make_handler().set(make_key(target_instance_name, property), bad_val), mp::InvalidSettingException,
mpt::match_what(AllOf(HasSubstr(bad_val), AnyOf(HasSubstr("positive"), HasSubstr("non-negative")))));
EXPECT_EQ(original_specs, specs[target_instance_name]);
}
INSTANTIATE_TEST_SUITE_P(TestInstanceSettingsHandler,
TestInstanceSettingsHandlerBadNumericValues,
Combine(ValuesIn(TestInstanceSettingsHandler::numeric_properties),
Values("0",
"2u",
"1.5f",
"2.0",
"0xa",
"0x8",
"-4",
"-1",
"rubbish",
" 123nonsense ",
"¤9",
"\n",
"\t",
"^",
"")));
struct TestInstanceSettingsHandlerBadBooleanValues : public TestInstanceSettingsHandler,
public WithParamInterface<PropertyValue>
{
};
TEST_P(TestInstanceSettingsHandlerBadBooleanValues, setRefusesBadBooleanValues)
{
constexpr auto target_instance_name = "zappa";
const auto& [property, bad_val] = GetParam();
const auto original_specs = specs[target_instance_name];
mock_vm(target_instance_name); // TODO: make this an expectation.
MP_EXPECT_THROW_THAT(make_handler().set(make_key(target_instance_name, property), bad_val),
mp::InvalidSettingException,
mpt::match_what(AllOf(HasSubstr(bad_val), HasSubstr("try \"true\" or \"false\""))));
EXPECT_EQ(original_specs, specs[target_instance_name]);
}
INSTANTIATE_TEST_SUITE_P(TestInstanceSettingsHandler,
TestInstanceSettingsHandlerBadBooleanValues,
Combine(ValuesIn(TestInstanceSettingsHandler::boolean_properties),
Values("apostrophe", "(')", "1974")));
} // namespace
| 30,380
|
C++
|
.cpp
| 600
| 41.795
| 119
| 0.65519
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,607
|
daemon_test_fixture.cpp
|
canonical_multipass/tests/daemon_test_fixture.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
// This header contains premock code so it must be included first.
#include "daemon_test_fixture.h"
#include "common.h"
#include "file_operations.h"
#include "mock_cert_provider.h"
#include "mock_server_reader_writer.h"
#include "mock_standard_paths.h"
#include "stub_cert_store.h"
#include "stub_image_host.h"
#include "stub_logger.h"
#include "stub_ssh_key_provider.h"
#include "stub_terminal.h"
#include "stub_virtual_machine_factory.h"
#include "stub_vm_blueprint_provider.h"
#include "stub_vm_image_vault.h"
#include <src/client/cli/client.h>
#include <src/platform/update/disabled_update_prompt.h>
#include <multipass/auto_join_thread.h>
#include <multipass/cli/argparser.h>
#include <multipass/cli/client_common.h>
#include <multipass/cli/command.h>
#include <chrono>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
class TestCreate final : public multipass::cmd::Command
{
public:
using Command::Command;
multipass::ReturnCode run(multipass::ArgParser* parser) override
{
auto on_success = [](multipass::CreateReply& /*reply*/) { return multipass::ReturnCode::Ok; };
auto on_failure = [this](grpc::Status& status) {
multipass::CreateError create_error;
create_error.ParseFromString(status.error_details());
const auto errors = create_error.error_codes();
cerr << "failed: " << status.error_message();
if (errors.size() == 1)
{
const auto& error = errors[0];
if (error == multipass::CreateError::INVALID_DISK_SIZE)
cerr << "disk";
else if (error == multipass::CreateError::INVALID_MEM_SIZE)
cerr << "memory";
else
cerr << "?";
}
return multipass::ReturnCode::CommandFail;
};
auto streaming_callback =
[this](mp::CreateReply& reply,
grpc::ClientReaderWriterInterface<mp::CreateRequest, mp::CreateReply>* client) {
cout << reply.create_message() << std::endl;
};
auto ret = parse_args(parser);
return ret == multipass::ParseCode::Ok
? dispatch(&mp::Rpc::StubInterface::create, request, on_success, on_failure, streaming_callback)
: parser->returnCodeFrom(ret);
}
std::string name() const override
{
return "test_create";
}
QString short_help() const override
{
return {};
}
QString description() const override
{
return {};
}
private:
multipass::ParseCode parse_args(multipass::ArgParser* parser)
{
parser->addPositionalArgument("image", "", "");
QCommandLineOption diskOption("disk", "", "disk", "");
QCommandLineOption memOption("memory", "", "memory", "");
parser->addOptions({diskOption, memOption});
auto status = parser->commandParse(this);
if (status == multipass::ParseCode::Ok)
{
if (!parser->positionalArguments().isEmpty())
request.set_image(parser->positionalArguments().first().toStdString());
if (parser->isSet(memOption))
request.set_mem_size(parser->value(memOption).toStdString());
if (parser->isSet(diskOption))
request.set_disk_space(parser->value(diskOption).toStdString());
}
return status;
}
multipass::CreateRequest request;
};
class TestGet final : public mp::cmd::Command
{
public:
using Command::Command;
mp::ReturnCode run(mp::ArgParser* parser) override
{
std::string val;
auto on_success = [&val](mp::GetReply& reply) {
val = reply.value();
return mp::ReturnCode::Ok;
};
auto on_failure = [this](grpc::Status& status) {
return mp::cmd::standard_failure_handler_for(name(), cerr, status);
};
if (auto parse_result = parse_args(parser); parse_result == mp::ParseCode::Ok)
{
auto ret = dispatch(&mp::Rpc::StubInterface::get, request, on_success, on_failure);
cout << fmt::format("{}={}", request.key(), val);
return ret;
}
else
return parser->returnCodeFrom(parse_result);
}
std::string name() const override
{
return "test_get";
}
QString short_help() const override
{
return {};
}
QString description() const override
{
return {};
}
private:
mp::ParseCode parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("key", "key of the setting to get");
auto status = parser->commandParse(this);
if (status == multipass::ParseCode::Ok)
{
const auto args = parser->positionalArguments();
if (args.count() == 1)
request.set_key(args.at(0).toStdString());
else
status = mp::ParseCode::CommandLineError;
}
return status;
}
mp::GetRequest request;
};
class TestSet final : public mp::cmd::Command
{
public:
using Command::Command;
mp::ReturnCode run(mp::ArgParser* parser) override
{
auto on_success = [](mp::SetReply&) { return mp::ReturnCode::Ok; };
auto on_failure = [this](grpc::Status& status) {
return mp::cmd::standard_failure_handler_for(name(), cerr, status);
};
if (auto parse_result = parse_args(parser); parse_result == mp::ParseCode::Ok)
return dispatch(&mp::Rpc::StubInterface::set, request, on_success, on_failure);
else
return parser->returnCodeFrom(parse_result);
}
std::string name() const override
{
return "test_set";
}
QString short_help() const override
{
return {};
}
QString description() const override
{
return {};
}
private:
mp::ParseCode parse_args(mp::ArgParser* parser)
{
parser->addPositionalArgument("key", "setting key");
parser->addPositionalArgument("val", "setting value");
auto status = parser->commandParse(this);
if (status == mp::ParseCode::Ok)
{
const auto& args = parser->positionalArguments();
if (args.count() == 2)
{
request.set_key(args.at(0).toStdString());
request.set_val(args.at(1).toStdString());
}
else
status = mp::ParseCode::CommandLineError;
}
return status;
}
mp::SetRequest request;
};
class TestKeys final : public mp::cmd::Command
{
public:
using Command::Command;
mp::ReturnCode run(mp::ArgParser* parser) override
{
auto on_success = [](mp::KeysReply&) { return mp::ReturnCode::Ok; };
auto on_failure = [this](grpc::Status& status) {
return mp::cmd::standard_failure_handler_for(name(), cerr, status);
};
if (auto parse_result = parse_args(parser); parse_result == mp::ParseCode::Ok)
return dispatch(&mp::Rpc::StubInterface::keys, request, on_success, on_failure);
else
return parser->returnCodeFrom(parse_result);
}
std::string name() const override
{
return "test_keys";
}
QString short_help() const override
{
return {};
}
QString description() const override
{
return {};
}
private:
mp::ParseCode parse_args(mp::ArgParser* parser)
{
return parser->commandParse(this) == mp::ParseCode::Ok ? mp::ParseCode::Ok : mp::ParseCode::CommandLineError;
}
mp::KeysRequest request;
};
class TestClient : public multipass::Client
{
public:
explicit TestClient(multipass::ClientConfig& context) : multipass::Client{context}
{
add_command<TestCreate>();
add_command<TestKeys>();
add_command<TestGet>();
add_command<TestSet>();
sort_commands();
}
};
} // namespace
mpt::DaemonTestFixture::DaemonTestFixture()
{
config_builder.server_address = server_address;
config_builder.cache_directory = cache_dir.path();
config_builder.data_directory = data_dir.path();
config_builder.vault = std::make_unique<StubVMImageVault>();
config_builder.factory = std::make_unique<StubVirtualMachineFactory>();
config_builder.image_hosts.push_back(std::make_unique<StubVMImageHost>());
config_builder.ssh_key_provider = std::make_unique<StubSSHKeyProvider>();
config_builder.cert_provider = std::make_unique<NiceMock<MockCertProvider>>();
config_builder.client_cert_store = std::make_unique<StubCertStore>();
config_builder.logger = std::make_unique<StubLogger>();
config_builder.update_prompt = std::make_unique<DisabledUpdatePrompt>();
config_builder.blueprint_provider = std::make_unique<StubVMBlueprintProvider>();
}
void mpt::DaemonTestFixture::SetUp()
{
EXPECT_CALL(MockStandardPaths::mock_instance(), locate(_, _, _))
.Times(AnyNumber()); // needed to allow general calls once we have added the specific expectation below
EXPECT_CALL(MockStandardPaths::mock_instance(), locate(_, match_qstring(EndsWith("settings.json")), _))
.Times(AnyNumber())
.WillRepeatedly(Return("")); /* Avoid writing to Windows Terminal settings. We use an "expectation" so that
it gets reset at the end of each test (by VerifyAndClearExpectations) */
}
mpt::MockVirtualMachineFactory* mpt::DaemonTestFixture::use_a_mock_vm_factory()
{
auto mock_factory = std::make_unique<NiceMock<MockVirtualMachineFactory>>();
auto mock_factory_ptr = mock_factory.get();
ON_CALL(*mock_factory_ptr, fetch_type()).WillByDefault(Return(FetchType::ImageOnly));
ON_CALL(*mock_factory_ptr, create_virtual_machine).WillByDefault([](auto&&...) {
return std::make_unique<StubVirtualMachine>();
});
ON_CALL(*mock_factory_ptr, prepare_source_image(_)).WillByDefault(ReturnArg<0>());
ON_CALL(*mock_factory_ptr, get_backend_version_string()).WillByDefault(Return("mock-1234"));
ON_CALL(*mock_factory_ptr, networks())
.WillByDefault(Return(std::vector<NetworkInterfaceInfo>{{"eth0", "ethernet", "wired adapter"},
{"wlan0", "wi-fi", "wireless adapter"}}));
config_builder.factory = std::move(mock_factory);
return mock_factory_ptr;
}
void mpt::DaemonTestFixture::send_command(const std::vector<std::string>& command, std::ostream& cout,
std::ostream& cerr, std::istream& cin)
{
send_commands({command}, cout, cerr, cin);
}
// "commands" is a vector of commands that includes necessary positional arguments, ie,
// "start foo"
void mpt::DaemonTestFixture::send_commands(std::vector<std::vector<std::string>> commands, std::ostream& cout,
std::ostream& cerr, std::istream& cin)
{
// Commands need to be sent from a thread different from that the QEventLoop is on.
// Event loop is started/stopped to ensure all signals are delivered
AutoJoinThread t([this, &commands, &cout, &cerr, &cin] {
StubTerminal term(cout, cerr, cin);
std::unique_ptr<CertProvider> cert_provider;
cert_provider = std::make_unique<NiceMock<MockCertProvider>>();
ClientConfig client_config{server_address, std::move(cert_provider), &term};
TestClient client{client_config};
for (const auto& command : commands)
{
QStringList args = QStringList() << "multipass_test";
for (const auto& arg : command)
{
args << QString::fromStdString(arg);
}
client.run(args);
}
// Commands not using RPC do not block in the "t" thread. This means that there will be a deadlock if
// loop.exec() is called after loop.quit(). The following check avoids this scenario, by making the
// thread sleep until the loop is running.
while (!loop.isRunning())
std::this_thread::sleep_for(std::chrono::milliseconds(10));
loop.quit();
});
loop.exec();
}
int mpt::DaemonTestFixture::total_lines_of_output(std::stringstream& output)
{
int count{0};
std::string line;
while (std::getline(output, line))
{
count++;
}
return count;
}
std::string mpt::DaemonTestFixture::fake_json_contents(const std::string& default_mac,
const std::vector<mp::NetworkInterface>& extra_ifaces,
const std::unordered_map<std::string, mp::VMMount>& mounts)
{
QString contents("{\n"
" \"real-zebraphant\": {\n"
" \"deleted\": false,\n"
" \"disk_space\": \"5368709120\",\n"
" \"extra_interfaces\": [\n");
QStringList array_elements;
for (auto extra_interface : extra_ifaces)
{
array_elements += QString::fromStdString(fmt::format(" {{\n"
" \"auto_mode\": {},\n"
" \"id\": \"{}\",\n"
" \"mac_address\": \"{}\"\n"
" }}\n",
extra_interface.auto_mode, extra_interface.id,
extra_interface.mac_address));
}
contents += array_elements.join(',');
contents += QString::fromStdString(fmt::format(" ],\n"
" \"mac_addr\": \"{}\",\n"
" \"mem_size\": \"1073741824\",\n"
" \"metadata\": {{\n"
" \"arguments\": [\n"
" \"many\",\n"
" \"arguments\"\n"
" ],\n"
" \"machine_type\": \"dmc-de-lorean\"\n"
" }},\n"
" \"mounts\": [\n",
default_mac));
QStringList mount_array_elements;
for (const auto& mount_pair : mounts)
{
const auto& mountpoint = mount_pair.first;
const auto& mount = mount_pair.second;
QString mount_element;
mount_element += QString::fromStdString(fmt::format(" {{\n"
" \"gid_mappings\": ["));
QStringList gid_array_elements;
for (const auto& gid_pair : mount.get_gid_mappings())
{
gid_array_elements += QString::fromStdString(fmt::format("\n {{\n"
" \"host_gid\": {},\n"
" \"instance_gid\": {}\n"
" }}",
gid_pair.first, gid_pair.second));
}
mount_element += gid_array_elements.join(',');
mount_element += QString::fromStdString(fmt::format("\n ],\n"
" \"source_path\": \"{}\",\n"
" \"target_path\": \"{}\",\n",
mount.get_source_path(),
mountpoint));
mount_element += QString::fromStdString(fmt::format(" \"mount_type\": {},\n"
" \"uid_mappings\": [",
mount.get_mount_type()));
QStringList uid_array_elements;
for (const auto& uid_pair : mount.get_uid_mappings())
{
uid_array_elements += QString::fromStdString(fmt::format("\n {{\n"
" \"host_uid\": {},\n"
" \"instance_uid\": {}\n"
" }}",
uid_pair.first, uid_pair.second));
}
mount_element += uid_array_elements.join(',');
mount_element += QString::fromStdString(fmt::format("\n ]\n"
" }}"));
mount_array_elements += mount_element;
}
contents += mount_array_elements.join(",\n");
contents += QString::fromStdString(fmt::format("\n ],\n"
" \"num_cores\": 1,\n"
" \"ssh_username\": \"ubuntu\",\n"
" \"state\": 2\n"
" }}\n"
"}}"));
return contents.toStdString();
}
std::pair<std::unique_ptr<mpt::TempDir>, QString>
mpt::DaemonTestFixture::plant_instance_json(const std::string& contents)
{
auto temp_dir = std::make_unique<TempDir>();
QString filename(temp_dir->path() + "/multipassd-vm-instances.json");
make_file_with_content(filename, contents);
return {std::move(temp_dir), filename};
}
template <typename R>
bool mpt::DaemonTestFixture::is_ready(std::future<R> const& f)
{
// 5 seconds should be plenty of time for the work to be complete
return f.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
}
template <typename DaemonSlotPtr, typename Request, typename Server>
grpc::Status mpt::DaemonTestFixture::call_daemon_slot(Daemon& daemon,
DaemonSlotPtr slot,
const Request& request,
Server&& server)
{
std::promise<grpc::Status> status_promise;
auto status_future = status_promise.get_future();
auto thread = QThread::create([&daemon, slot, &request, &server, &status_promise] {
QEventLoop inner_loop;
(daemon.*slot)(&request, &server, &status_promise);
inner_loop.exec();
});
thread->start();
EXPECT_TRUE(is_ready(status_future));
thread->quit();
thread->wait();
return status_future.get();
}
template bool mpt::DaemonTestFixture::is_ready(std::future<grpc::Status> const&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::AuthenticateRequest*,
grpc::ServerReaderWriterInterface<mp::AuthenticateReply, mp::AuthenticateRequest>*,
std::promise<grpc::Status>*),
const mp::AuthenticateRequest&,
StrictMock<mpt::MockServerReaderWriter<mp::AuthenticateReply, mp::AuthenticateRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::VersionRequest const*,
grpc::ServerReaderWriterInterface<mp::VersionReply, mp::VersionRequest>*,
std::promise<grpc::Status>*),
mp::VersionRequest const&, StrictMock<mpt::MockServerReaderWriter<mp::VersionReply, mp::VersionRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::ListRequest*, grpc::ServerReaderWriterInterface<mp::ListReply, mp::ListRequest>*,
std::promise<grpc::Status>*),
mp::ListRequest const&, StrictMock<mpt::MockServerReaderWriter<mp::ListReply, mp::ListRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::KeysRequest const*, grpc::ServerReaderWriterInterface<mp::KeysReply, mp::KeysRequest>*,
std::promise<grpc::Status>*),
mp::KeysRequest const&, StrictMock<mpt::MockServerReaderWriter<mp::KeysReply, mp::KeysRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::KeysRequest const*, grpc::ServerReaderWriterInterface<mp::KeysReply, mp::KeysRequest>*,
std::promise<grpc::Status>*),
mp::KeysRequest const&, StrictMock<mpt::MockServerReaderWriter<mp::KeysReply, mp::KeysRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::GetRequest const*, grpc::ServerReaderWriterInterface<mp::GetReply, mp::GetRequest>*,
std::promise<grpc::Status>*),
mp::GetRequest const&, StrictMock<mpt::MockServerReaderWriter<mp::GetReply, mp::GetRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::GetRequest const*, grpc::ServerReaderWriterInterface<mp::GetReply, mp::GetRequest>*,
std::promise<grpc::Status>*),
mp::GetRequest const&, StrictMock<mpt::MockServerReaderWriter<mp::GetReply, mp::GetRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::SetRequest const*, grpc::ServerReaderWriterInterface<mp::SetReply, mp::SetRequest>*,
std::promise<grpc::Status>*),
mp::SetRequest const&, StrictMock<mpt::MockServerReaderWriter<mp::SetReply, mp::SetRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::SetRequest const*, grpc::ServerReaderWriterInterface<mp::SetReply, mp::SetRequest>*,
std::promise<grpc::Status>*),
mp::SetRequest const&, StrictMock<mpt::MockServerReaderWriter<mp::SetReply, mp::SetRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::NetworksRequest const*,
grpc::ServerReaderWriterInterface<mp::NetworksReply, mp::NetworksRequest>*,
std::promise<grpc::Status>*),
mp::NetworksRequest const&, StrictMock<mpt::MockServerReaderWriter<mp::NetworksReply, mp::NetworksRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::NetworksRequest const*,
grpc::ServerReaderWriterInterface<mp::NetworksReply, mp::NetworksRequest>*,
std::promise<grpc::Status>*),
mp::NetworksRequest const&, NiceMock<mpt::MockServerReaderWriter<mp::NetworksReply, mp::NetworksRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::PurgeRequest const*, grpc::ServerReaderWriterInterface<mp::PurgeReply, mp::PurgeRequest>*,
std::promise<grpc::Status>*),
mp::PurgeRequest const&, NiceMock<mpt::MockServerReaderWriter<mp::PurgeReply, mp::PurgeRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::MountRequest*, grpc::ServerReaderWriterInterface<mp::MountReply, mp::MountRequest>*,
std::promise<grpc::Status>*),
const mp::MountRequest&, StrictMock<mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::UmountRequest*,
grpc::ServerReaderWriterInterface<mp::UmountReply, mp::UmountRequest>*,
std::promise<grpc::Status>*),
const mp::UmountRequest&, StrictMock<mpt::MockServerReaderWriter<mp::UmountReply, mp::UmountRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(mp::LaunchRequest const*,
grpc::ServerReaderWriterInterface<mp::LaunchReply, mp::LaunchRequest>*,
std::promise<grpc::Status>*),
mp::LaunchRequest const&, StrictMock<mpt::MockServerReaderWriter<mp::LaunchReply, mp::LaunchRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::StartRequest*, grpc::ServerReaderWriterInterface<mp::StartReply, mp::StartRequest>*,
std::promise<grpc::Status>*),
const mp::StartRequest&, StrictMock<mpt::MockServerReaderWriter<mp::StartReply, mp::StartRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::InfoRequest*, grpc::ServerReaderWriterInterface<mp::InfoReply, mp::InfoRequest>*,
std::promise<grpc::Status>*),
const mp::InfoRequest&, StrictMock<mpt::MockServerReaderWriter<mp::InfoReply, mp::InfoRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::SuspendRequest*,
grpc::ServerReaderWriterInterface<mp::SuspendReply, mp::SuspendRequest>*,
std::promise<grpc::Status>*),
const mp::SuspendRequest&,
StrictMock<mpt::MockServerReaderWriter<mp::SuspendReply, mp::SuspendRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::SnapshotRequest*,
grpc::ServerReaderWriterInterface<mp::SnapshotReply, mp::SnapshotRequest>*,
std::promise<grpc::Status>*),
const mp::SnapshotRequest&,
StrictMock<mpt::MockServerReaderWriter<mp::SnapshotReply, mp::SnapshotRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::SnapshotRequest*,
grpc::ServerReaderWriterInterface<mp::SnapshotReply, mp::SnapshotRequest>*,
std::promise<grpc::Status>*),
const mp::SnapshotRequest&,
testing::StrictMock<mpt::MockServerReaderWriter<mp::SnapshotReply, mp::SnapshotRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::RestoreRequest*,
grpc::ServerReaderWriterInterface<mp::RestoreReply, mp::RestoreRequest>*,
std::promise<grpc::Status>*),
const mp::RestoreRequest&,
testing::StrictMock<mpt::MockServerReaderWriter<mp::RestoreReply, mp::RestoreRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::RestoreRequest*,
grpc::ServerReaderWriterInterface<mp::RestoreReply, mp::RestoreRequest>*,
std::promise<grpc::Status>*),
const mp::RestoreRequest&,
StrictMock<mpt::MockServerReaderWriter<mp::RestoreReply, mp::RestoreRequest>>&&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::CloneRequest*,
grpc::ServerReaderWriterInterface<mp::CloneReply, mp::CloneRequest>*,
std::promise<grpc::Status>*),
const mp::CloneRequest&,
NiceMock<mpt::MockServerReaderWriter<mp::CloneReply, mp::CloneRequest>>&);
template grpc::Status mpt::DaemonTestFixture::call_daemon_slot(
mp::Daemon&,
void (mp::Daemon::*)(const mp::CloneRequest*,
grpc::ServerReaderWriterInterface<mp::CloneReply, mp::CloneRequest>*,
std::promise<grpc::Status>*),
const mp::CloneRequest&,
NiceMock<mpt::MockServerReaderWriter<mp::CloneReply, mp::CloneRequest>>&&);
| 29,427
|
C++
|
.cpp
| 600
| 37.458333
| 119
| 0.575511
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,608
|
test_json_utils.cpp
|
canonical_multipass/tests/test_json_utils.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_file_ops.h"
#include <multipass/json_utils.h>
#include <QFileDevice>
#include <QJsonDocument>
#include <QJsonObject>
#include <QString>
#include <stdexcept>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct TestJsonUtils : public Test
{
mpt::MockFileOps::GuardedMock guarded_mock_file_ops = mpt::MockFileOps::inject();
mpt::MockFileOps& mock_file_ops = *guarded_mock_file_ops.first;
inline static const QString dir = QStringLiteral("a/b/c");
inline static const QString file_name = QStringLiteral("asd.blag");
inline static const QString file_path = QStringLiteral("%1/%2").arg(dir, file_name);
inline static const char* json_text = R"({"a": [1,2,3]})";
inline static const QJsonObject json = QJsonDocument::fromJson(json_text).object();
template <typename T>
static Matcher<T&> file_matcher() // not using static template var to workaround bad init order in AppleClang
{
static const auto ret = Property(&T::fileName, Eq(file_path));
return ret;
}
};
TEST_F(TestJsonUtils, writesJsonTransactionally)
{
auto json_matcher =
ResultOf([](auto&& text) { return QJsonDocument::fromJson(std::forward<decltype(text)>(text), nullptr); },
Property(&QJsonDocument::object, Eq(json)));
EXPECT_CALL(mock_file_ops, mkpath(Eq(dir), Eq("."))).WillOnce(Return(true));
EXPECT_CALL(mock_file_ops, open(file_matcher<QFileDevice>(), _)).WillOnce(Return(true));
EXPECT_CALL(mock_file_ops, write(file_matcher<QFileDevice>(), json_matcher)).WillOnce(Return(14));
EXPECT_CALL(mock_file_ops, commit(file_matcher<QSaveFile>())).WillOnce(Return(true));
EXPECT_NO_THROW(MP_JSONUTILS.write_json(json, file_path));
}
TEST_F(TestJsonUtils, writeJsonThrowsOnFailureToCreateDirectory)
{
EXPECT_CALL(mock_file_ops, mkpath).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(MP_JSONUTILS.write_json(json, file_path),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr("Could not create"), HasSubstr(dir.toStdString()))));
}
TEST_F(TestJsonUtils, writeJsonThrowsOnFailureToOpenFile)
{
EXPECT_CALL(mock_file_ops, mkpath).WillOnce(Return(true));
EXPECT_CALL(mock_file_ops, open(_, _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(MP_JSONUTILS.write_json(json, file_path),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr("Could not open"), HasSubstr(file_path.toStdString()))));
}
TEST_F(TestJsonUtils, writeJsonThrowsOnFailureToWriteFile)
{
EXPECT_CALL(mock_file_ops, mkpath).WillOnce(Return(true));
EXPECT_CALL(mock_file_ops, open(_, _)).WillOnce(Return(true));
EXPECT_CALL(mock_file_ops, write(_, _)).WillOnce(Return(-1));
MP_EXPECT_THROW_THAT(MP_JSONUTILS.write_json(json, file_path),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr("Could not write"), HasSubstr(file_path.toStdString()))));
}
TEST_F(TestJsonUtils, writeJsonThrowsOnFailureToCommit)
{
EXPECT_CALL(mock_file_ops, mkpath).WillOnce(Return(true));
EXPECT_CALL(mock_file_ops, open(_, _)).WillOnce(Return(true));
EXPECT_CALL(mock_file_ops, write(_, _)).WillOnce(Return(1234));
EXPECT_CALL(mock_file_ops, commit).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(MP_JSONUTILS.write_json(json, file_path),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr("Could not commit"), HasSubstr(file_path.toStdString()))));
}
struct ExtraInterfacesRead : public TestJsonUtils, public WithParamInterface<std::vector<mp::NetworkInterface>>
{
};
TEST_P(ExtraInterfacesRead, write_and_read_extra_interfaces)
{
std::vector<mp::NetworkInterface> extra_ifaces = GetParam();
auto written_ifaces = MP_JSONUTILS.extra_interfaces_to_json_array(extra_ifaces);
QJsonObject doc;
doc.insert("extra_interfaces", written_ifaces);
auto read_ifaces = MP_JSONUTILS.read_extra_interfaces(doc);
ASSERT_EQ(read_ifaces, extra_ifaces);
}
INSTANTIATE_TEST_SUITE_P(TestJsonUtils,
ExtraInterfacesRead,
Values(std::vector<mp::NetworkInterface>{{"eth1", "52:54:00:00:00:01", true},
{"eth2", "52:54:00:00:00:02", false}},
std::vector<mp::NetworkInterface>{}));
TEST_F(TestJsonUtils, gives_nullopt_on_empty_extra_interfaces)
{
QJsonObject doc;
doc.insert("some_data", "nothing to see here");
ASSERT_FALSE(MP_JSONUTILS.read_extra_interfaces(doc).has_value());
}
TEST_F(TestJsonUtils, throws_on_wrong_mac)
{
std::vector<mp::NetworkInterface> extra_ifaces{mp::NetworkInterface{"eth3", "52:54:00:00:00:0x", true}};
auto written_ifaces = MP_JSONUTILS.extra_interfaces_to_json_array(extra_ifaces);
QJsonObject doc;
doc.insert("extra_interfaces", written_ifaces);
MP_ASSERT_THROW_THAT(MP_JSONUTILS.read_extra_interfaces(doc),
std::runtime_error,
mpt::match_what(StrEq("Invalid MAC address 52:54:00:00:00:0x")));
}
TEST_F(TestJsonUtils, updateCloudInitInstanceIdSucceed)
{
EXPECT_EQ(MP_JSONUTILS.update_cloud_init_instance_id(QJsonValue{"vm1_e_e_e"}, "vm1", "vm2"),
QJsonValue{"vm2_e_e_e"});
}
} // namespace
| 6,067
|
C++
|
.cpp
| 129
| 40.775194
| 116
| 0.685047
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,609
|
mock_logger.cpp
|
canonical_multipass/tests/mock_logger.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_logger.h"
#include <type_traits>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
static_assert(!std::is_copy_assignable_v<mpt::MockLogger>);
static_assert(!std::is_copy_constructible_v<mpt::MockLogger>);
mpt::MockLogger::MockLogger(const PrivatePass&, const mpl::Level logging_level) : Logger{logging_level}
{
}
auto mpt::MockLogger::inject(const mpl::Level logging_level) -> Scope
{
return Scope{logging_level};
}
mpt::MockLogger::Scope::Scope(const mpl::Level logging_level)
: mock_logger{std::make_shared<testing::NiceMock<MockLogger>>(pass, logging_level)}
{
mpl::set_logger(mock_logger);
}
mpt::MockLogger::Scope::~Scope()
{
if (mpl::get_logger() == mock_logger.get() && mock_logger.use_count() == 2)
mpl::set_logger(nullptr); // only reset if we are the last scope with the registered logger
}
void mpt::MockLogger::expect_log(mpl::Level lvl, const std::string& substr, const Cardinality& times)
{
EXPECT_CALL(*this, log(lvl, _, make_cstring_matcher(HasSubstr(substr)))).Times(times);
}
void mpt::MockLogger::screen_logs(mpl::Level lvl)
{
for (auto i = 0; i <= mpl::enum_type(mpl::Level::trace); ++i)
{
auto times = i <= mpl::enum_type(lvl) ? Exactly(0) : AnyNumber();
EXPECT_CALL(*this, log(mpl::level_from(i), _, _)).Times(times);
}
}
| 2,024
|
C++
|
.cpp
| 53
| 35.660377
| 103
| 0.718511
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,610
|
test_yaml_node_utils.cpp
|
canonical_multipass/tests/test_yaml_node_utils.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/network_interface.h>
#include <multipass/yaml_node_utils.h>
#include <gtest/gtest.h>
namespace mp = multipass;
namespace mpu = mp::utils;
TEST(UtilsTests, makeCloudInitMetaConfig)
{
const YAML::Node meta_data_node = mpu::make_cloud_init_meta_config("vm1");
EXPECT_EQ(meta_data_node["instance-id"].as<std::string>(), "vm1");
EXPECT_EQ(meta_data_node["local-hostname"].as<std::string>(), "vm1");
EXPECT_EQ(meta_data_node["cloud-name"].as<std::string>(), "multipass");
}
TEST(UtilsTests, makeCloudInitMetaConfigWithYAMLStr)
{
constexpr std::string_view meta_data_content = R"(#cloud-config
instance-id: vm2_e_e
local-hostname: vm2
cloud-name: multipass)";
const YAML::Node meta_data_node = mpu::make_cloud_init_meta_config("vm1", std::string{meta_data_content});
EXPECT_EQ(meta_data_node["instance-id"].as<std::string>(), "vm1_e_e");
EXPECT_EQ(meta_data_node["local-hostname"].as<std::string>(), "vm1");
EXPECT_EQ(meta_data_node["cloud-name"].as<std::string>(), "multipass");
}
TEST(UtilsTests, addOneExtraInterfaceNonEmptyNetworkFileContent)
{
constexpr std::string_view original_network_config_file_content = R"(#cloud-config
version: 2
ethernets:
default:
match:
macaddress: "52:54:00:51:84:0c"
dhcp4: true
dhcp-identifier: mac
extra0:
match:
macaddress: "52:54:00:d8:12:9b"
dhcp4: true
dhcp-identifier: mac
dhcp4-overrides:
route-metric: 200
optional: true)";
constexpr std::string_view expected_new_network_config_file_content = R"(#cloud-config
version: 2
ethernets:
default:
match:
macaddress: "52:54:00:51:84:0c"
dhcp4: true
dhcp-identifier: mac
extra0:
match:
macaddress: "52:54:00:d8:12:9b"
dhcp4: true
dhcp-identifier: mac
dhcp4-overrides:
route-metric: 200
optional: true
extra1:
match:
macaddress: "52:54:00:d8:12:9c"
dhcp4: true
dhcp-identifier: mac
dhcp4-overrides:
route-metric: 200
optional: true
)";
const mp::NetworkInterface extra_interface{"id", "52:54:00:d8:12:9c", true};
const std::string default_mac_addr = "52:54:00:56:78:90";
const auto new_network_node =
mpu::add_extra_interface_to_network_config(default_mac_addr,
extra_interface,
std::string(original_network_config_file_content));
EXPECT_EQ(mpu::emit_cloud_config(new_network_node), expected_new_network_config_file_content);
}
TEST(UtilsTests, addOneExtraInterfaceEmptyNetworkFileContent)
{
constexpr std::string_view expected_new_network_config_file_content = R"(#cloud-config
version: 2
ethernets:
default:
match:
macaddress: "52:54:00:56:78:90"
dhcp4: true
dhcp-identifier: mac
extra0:
match:
macaddress: "52:54:00:d8:12:9c"
dhcp4: true
dhcp-identifier: mac
dhcp4-overrides:
route-metric: 200
optional: true
)";
const mp::NetworkInterface extra_interface{"id", "52:54:00:d8:12:9c", true};
const std::string default_mac_addr = "52:54:00:56:78:90";
const auto new_network_node = mpu::add_extra_interface_to_network_config(default_mac_addr, extra_interface, "");
EXPECT_EQ(mpu::emit_cloud_config(new_network_node), expected_new_network_config_file_content);
}
TEST(UtilsTests, addOneExtraInterfaceFalseExtraInterface)
{
const mp::NetworkInterface extra_interface{"id", "52:54:00:d8:12:9c", false};
const auto new_network_node = mpu::add_extra_interface_to_network_config("", extra_interface, "");
EXPECT_TRUE(new_network_node.IsNull());
}
TEST(UtilsTests, makeCloudInitMetaConfigWithIdTweakGeneratedId)
{
constexpr std::string_view meta_data_content = R"(#cloud-config
instance-id: vm1
local-hostname: vm1
cloud-name: multipass)";
const YAML::Node meta_data_node = mpu::make_cloud_init_meta_config_with_id_tweak(std::string{meta_data_content});
EXPECT_EQ(meta_data_node["instance-id"].as<std::string>(), "vm1_e");
EXPECT_EQ(meta_data_node["local-hostname"].as<std::string>(), "vm1");
EXPECT_EQ(meta_data_node["cloud-name"].as<std::string>(), "multipass");
}
TEST(UtilsTests, makeCloudInitMetaConfigWithIdTweakNewId)
{
constexpr std::string_view meta_data_content = R"(#cloud-config
instance-id: vm1
local-hostname: vm1
cloud-name: multipass)";
const YAML::Node meta_data_node =
mpu::make_cloud_init_meta_config_with_id_tweak(std::string{meta_data_content}, "vm2");
EXPECT_EQ(meta_data_node["instance-id"].as<std::string>(), "vm2");
EXPECT_EQ(meta_data_node["local-hostname"].as<std::string>(), "vm1");
EXPECT_EQ(meta_data_node["cloud-name"].as<std::string>(), "multipass");
}
| 5,369
|
C++
|
.cpp
| 143
| 33.188811
| 117
| 0.700979
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,611
|
test_client_common.cpp
|
canonical_multipass/tests/test_client_common.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "daemon_test_fixture.h"
#include "file_operations.h"
#include "mock_cert_provider.h"
#include "mock_cert_store.h"
#include "mock_client_rpc.h"
#include "mock_daemon.h"
#include "mock_standard_paths.h"
#include "mock_utils.h"
#include "stub_terminal.h"
#include "temp_dir.h"
#include <multipass/cli/client_common.h>
#include <multipass/utils.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct TestClientCommon : public mpt::DaemonTestFixture
{
TestClientCommon()
{
ON_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::GenericDataLocation))
.WillByDefault(Return(temp_dir.path()));
}
mpt::MockDaemon make_secure_server()
{
EXPECT_CALL(*mock_cert_provider, PEM_certificate()).WillOnce(Return(mpt::daemon_cert));
EXPECT_CALL(*mock_cert_provider, PEM_signing_key()).WillOnce(Return(mpt::daemon_key));
config_builder.server_address = server_address;
config_builder.cert_provider = std::move(mock_cert_provider);
return mpt::MockDaemon(config_builder.build());
}
std::unique_ptr<NiceMock<mpt::MockCertProvider>> mock_cert_provider{
std::make_unique<NiceMock<mpt::MockCertProvider>>()};
std::unique_ptr<mpt::MockCertStore> mock_cert_store{std::make_unique<mpt::MockCertStore>()};
const std::string server_address{"localhost:50052"};
mpt::TempDir temp_dir;
};
} // namespace
TEST_F(TestClientCommon, usesCommonCertWhenItExists)
{
const auto common_cert_dir = MP_UTILS.make_dir(temp_dir.path(), QString(mp::common_client_cert_dir).remove(0, 1));
const auto common_client_cert_file = common_cert_dir + "/" + mp::client_cert_file;
const auto common_client_key_file = common_cert_dir + "/" + mp::client_key_file;
mpt::make_file_with_content(common_client_cert_file, mpt::client_cert);
mpt::make_file_with_content(common_client_key_file, mpt::client_key);
EXPECT_TRUE(mp::client::make_channel(server_address, *mp::client::get_cert_provider()));
}
TEST_F(TestClientCommon, noValidCertsCreatesNewCommonCert)
{
const auto common_cert_dir = temp_dir.path() + mp::common_client_cert_dir;
EXPECT_CALL(*mock_cert_store, empty).WillOnce(Return(false));
config_builder.client_cert_store = std::move(mock_cert_store);
mpt::MockDaemon daemon{make_secure_server()};
EXPECT_TRUE(mp::client::make_channel(server_address, *mp::client::get_cert_provider()));
EXPECT_TRUE(QFile::exists(common_cert_dir + "/" + mp::client_cert_file));
EXPECT_TRUE(QFile::exists(common_cert_dir + "/" + mp::client_key_file));
}
TEST(TestClientHandleUserPassword, defaultHasNoPassword)
{
auto client = std::make_unique<mpt::MockClientReaderWriter<mp::MountRequest, mp::MountReply>>();
std::stringstream trash_stream;
mpt::StubTerminal term(trash_stream, trash_stream, trash_stream);
EXPECT_CALL(*client, Write(Property(&mp::MountRequest::password, IsEmpty()), _)).Times(1);
mp::cmd::handle_password(client.get(), &term);
}
| 3,716
|
C++
|
.cpp
| 83
| 41.180723
| 118
| 0.72765
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,612
|
test_alias_dict.cpp
|
canonical_multipass/tests/test_alias_dict.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/cli/alias_dict.h>
#include <multipass/cli/csv_formatter.h>
#include <multipass/cli/json_formatter.h>
#include <multipass/cli/table_formatter.h>
#include <multipass/cli/yaml_formatter.h>
#include <multipass/constants.h>
#include "common.h"
#include "daemon_test_fixture.h"
#include "fake_alias_config.h"
#include "file_operations.h"
#include "json_test_utils.h"
#include "mock_file_ops.h"
#include "mock_platform.h"
#include "mock_settings.h"
#include "mock_vm_image_vault.h"
#include "stub_terminal.h"
#include "src/daemon/daemon.h"
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct AliasDictionary : public FakeAliasConfig, public Test
{
};
TEST_F(AliasDictionary, works_with_empty_file)
{
QFile db(QString::fromStdString(db_filename()));
db.open(QIODevice::ReadWrite); // Create the database file.
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.get_active_context().size(), 0u);
}
TEST_F(AliasDictionary, works_with_empty_database)
{
mpt::make_file_with_content(QString::fromStdString(db_filename()), "{\n}\n");
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.get_active_context().size(), 0u);
}
TEST_F(AliasDictionary, works_with_unexisting_file)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.get_active_context().size(), 0u);
}
TEST_F(AliasDictionary, works_with_broken_file)
{
mpt::make_file_with_content(QString::fromStdString(db_filename()), "broken file {]");
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.get_active_context().size(), 0u);
}
TEST_F(AliasDictionary, SkipsCorrectlyBrokenEntriesOldFormat)
{
std::string file_contents{"{\n"
" \"alias1\": {\n"
" \"command\": \"first_command\",\n"
" \"instance\": \"first_instance\",\n"
" \"working-directory\": \"map\"\n"
" },\n"
" \"empty_entry\": {\n"
" },\n"
" \"alias2\": {\n"
" \"command\": \"second_command\",\n"
" \"instance\": \"second_instance\",\n"
" \"working-directory\": \"default\"\n"
" }\n"
"}\n"};
mpt::make_file_with_content(QString::fromStdString(db_filename()), file_contents);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.active_context_name(), "default");
ASSERT_EQ(dict.get_active_context().size(), 2u);
auto a1 = dict.get_alias("alias1");
ASSERT_TRUE(a1);
ASSERT_EQ(a1->instance, "first_instance");
ASSERT_EQ(a1->command, "first_command");
ASSERT_EQ(a1->working_directory, "map");
auto a2 = dict.get_alias("alias2");
ASSERT_TRUE(a2);
ASSERT_EQ(a2->instance, "second_instance");
ASSERT_EQ(a2->command, "second_command");
ASSERT_EQ(a2->working_directory, "default");
}
TEST_F(AliasDictionary, SkipsCorrectlyBrokenEntries)
{
std::string file_contents{"{\n"
" \"active-context\": \"default\",\n"
" \"contexts\": {\n"
" \"default\": {\n"
" \"alias1\": {\n"
" \"command\": \"first_command\",\n"
" \"instance\": \"first_instance\",\n"
" \"working-directory\": \"map\"\n"
" },\n"
" \"empty_entry\": {\n"
" },\n"
" \"alias2\": {\n"
" \"command\": \"second_command\",\n"
" \"instance\": \"second_instance\",\n"
" \"working-directory\": \"default\"\n"
" }\n"
" }\n"
" }\n"
"}\n"};
mpt::make_file_with_content(QString::fromStdString(db_filename()), file_contents);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.active_context_name(), "default");
ASSERT_EQ(dict.get_active_context().size(), 2u);
auto a1 = dict.get_alias("alias1");
ASSERT_TRUE(a1);
ASSERT_EQ(a1->instance, "first_instance");
ASSERT_EQ(a1->command, "first_command");
ASSERT_EQ(a1->working_directory, "map");
auto a2 = dict.get_alias("alias2");
ASSERT_TRUE(a2);
ASSERT_EQ(a2->instance, "second_instance");
ASSERT_EQ(a2->command, "second_command");
ASSERT_EQ(a2->working_directory, "default");
}
// In old versions, the file did not contain the `working-directory` flag in the JSON, because the
// `--no-working-directory` flag were not yet introduced. In case the file was generated by an old version,
// the flag must be `false`, in order to maintain backwards compatibility.
TEST_F(AliasDictionary, mapDirMissingTranslatesToDefault)
{
std::string file_contents{"{\n"
" \"alias3\": {\n"
" \"command\": \"third_command\",\n"
" \"instance\": \"third_instance\"\n"
" }\n"
"}\n"};
mpt::make_file_with_content(QString::fromStdString(db_filename()), file_contents);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
auto a3 = dict.get_alias("alias3");
ASSERT_TRUE(a3);
ASSERT_EQ(a3->instance, "third_instance");
ASSERT_EQ(a3->command, "third_command");
ASSERT_EQ(a3->working_directory, "default");
}
TEST_F(AliasDictionary, mapDirEmptyStringTranslatesToDefault)
{
std::string file_contents{"{\n"
" \"alias4\": {\n"
" \"command\": \"fourth_command\",\n"
" \"instance\": \"fourth_instance\",\n"
" \"working-directory\": \"\"\n"
" }\n"
"}\n"};
mpt::make_file_with_content(QString::fromStdString(db_filename()), file_contents);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
auto a4 = dict.get_alias("alias4");
ASSERT_TRUE(a4);
ASSERT_EQ(a4->instance, "fourth_instance");
ASSERT_EQ(a4->command, "fourth_command");
ASSERT_EQ(a4->working_directory, "default");
}
TEST_F(AliasDictionary, mapDirWrongThrows)
{
std::string file_contents{"{\n"
" \"alias5\": {\n"
" \"command\": \"fifth_command\",\n"
" \"instance\": \"fifth_instance\",\n"
" \"working-directory\": \"wrong string\"\n"
" }\n"
"}\n"};
mpt::make_file_with_content(QString::fromStdString(db_filename()), file_contents);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
MP_ASSERT_THROW_THAT(mp::AliasDict dict(&trash_term), std::runtime_error,
mpt::match_what(HasSubstr("invalid working_directory string \"wrong string\"")));
}
typedef std::vector<std::pair<std::string, mp::AliasDefinition>> AliasesVector;
struct WriteReadTestsuite : public AliasDictionary, public WithParamInterface<AliasesVector>
{
};
TEST_P(WriteReadTestsuite, writes_and_reads_files)
{
auto aliases_vector = GetParam();
populate_db_file(aliases_vector);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict reader(&trash_term);
for (const auto& alias : aliases_vector)
{
auto read_value = reader.get_alias(alias.first);
ASSERT_TRUE(read_value);
ASSERT_EQ((*read_value).instance, alias.second.instance);
ASSERT_EQ((*read_value).command, alias.second.command);
}
// We test with this const/non-const iterators and size().
ASSERT_EQ((size_t)std::distance(reader.get_active_context().cbegin(), reader.get_active_context().cend()),
(size_t)aliases_vector.size());
ASSERT_EQ((size_t)std::distance(reader.get_active_context().begin(), reader.get_active_context().end()),
(size_t)aliases_vector.size());
ASSERT_EQ(reader.get_active_context().size(), aliases_vector.size());
}
INSTANTIATE_TEST_SUITE_P(AliasDictionary, WriteReadTestsuite,
Values(AliasesVector{}, AliasesVector{{"w", {"fake", "w", "map"}}},
AliasesVector{{"ipf", {"instance", "ip", "map"}}},
AliasesVector{{"lsp", {"primary", "ls", "map"}}, {"llp", {"primary", "ls", "map"}}}));
TEST_F(AliasDictionary, addAliasWorks)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_TRUE(dict.add_alias("repeated", mp::AliasDefinition{"instance-1", "command-1", "map"}));
ASSERT_FALSE(dict.add_alias("repeated", mp::AliasDefinition{"instance-2", "command-2", "map"}));
ASSERT_EQ(*dict.get_alias("repeated"), (mp::AliasDefinition{"instance-1", "command-1", "map"}));
}
TEST_F(AliasDictionary, existsAliasWorksWithExistingAlias)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.add_alias("existing", mp::AliasDefinition{"instance", "command", "map"});
ASSERT_TRUE(dict.exists_alias("existing"));
}
TEST_F(AliasDictionary, existsAliasWorksWithUnexistingAlias)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_FALSE(dict.exists_alias("unexisting"));
}
TEST_F(AliasDictionary, correctly_removes_alias)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.active_context_name(), "default");
dict.add_alias("alias", mp::AliasDefinition{"instance", "command", "map"});
ASSERT_FALSE(dict.empty());
ASSERT_TRUE(dict.remove_alias("alias"));
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.get_active_context().size(), 0u);
}
TEST_F(AliasDictionary, works_when_removing_unexisting_alias)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.add_alias("alias", mp::AliasDefinition{"instance", "command", "map"});
ASSERT_EQ(dict.size(), 1u);
ASSERT_FALSE(dict.get_active_context().empty());
ASSERT_FALSE(dict.remove_alias("unexisting"));
ASSERT_EQ(dict.size(), 1u);
ASSERT_FALSE(dict.get_active_context().empty());
}
TEST_F(AliasDictionary, clearWorks)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.add_alias("first", mp::AliasDefinition{"instance", "command", "default"});
dict.add_alias("second", mp::AliasDefinition{"other_instance", "other_command", "map"});
dict.clear();
ASSERT_TRUE(dict.empty());
}
TEST_F(AliasDictionary, correctlyGetsAliasInDefaultContext)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
std::string alias_name{"alias"};
mp::AliasDefinition alias_def{"instance", "command", "map"};
dict.add_alias(alias_name, alias_def);
ASSERT_FALSE(dict.empty());
auto result = dict.get_alias(alias_name);
ASSERT_EQ(result, alias_def);
ASSERT_FALSE(dict.empty());
}
TEST_F(AliasDictionary, correctlyGetsUniqueAliasInAnotherContext)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
std::string alias_name{"alias"};
mp::AliasDefinition alias_def{"instance", "command", "map"};
dict.add_alias(alias_name, alias_def);
dict.set_active_context("new_context");
auto result = dict.get_alias(alias_name);
ASSERT_EQ(result, alias_def);
ASSERT_FALSE(dict.empty());
}
TEST_F(AliasDictionary, correctlyGetsAliasInNonDefaultContext)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
std::string context{"non-default"};
std::string alias_name{"alias"};
mp::AliasDefinition alias_def{"instance", "command", "map"};
dict.set_active_context(context);
dict.add_alias(alias_name, alias_def);
dict.set_active_context("default");
auto result = dict.get_alias(context + '.' + alias_name);
ASSERT_EQ(result, alias_def);
ASSERT_FALSE(dict.empty());
}
TEST_F(AliasDictionary, get_unexisting_alias_returns_nullopt)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.get_alias("unexisting"), std::nullopt);
}
TEST_F(AliasDictionary, throws_when_open_alias_file_fails)
{
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, exists(A<const QFile&>())).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(false));
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
MP_ASSERT_THROW_THAT(mp::AliasDict dict(&trash_term), std::runtime_error,
mpt::match_what(HasSubstr("Error opening file '")));
}
struct FormatterTestsuite
: public AliasDictionary,
public WithParamInterface<
std::tuple<std::string, AliasesVector, std::string, std::string, std::string, std::string>>
{
};
TEST_P(FormatterTestsuite, table)
{
auto [context, aliases, csv_output, json_output, table_output, yaml_output] = GetParam();
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.set_active_context(context);
for (const auto& alias : aliases)
dict.add_alias(alias.first, alias.second);
dict.set_active_context("default");
ASSERT_EQ(mp::CSVFormatter().format(dict), csv_output);
ASSERT_EQ(mp::JsonFormatter().format(dict), json_output);
ASSERT_EQ(mp::TableFormatter().format(dict), table_output);
ASSERT_EQ(mp::YamlFormatter().format(dict), yaml_output);
}
const std::string csv_head{"Alias,Instance,Command,Working directory,Context\n"};
INSTANTIATE_TEST_SUITE_P(
AliasDictionary,
FormatterTestsuite,
Values(std::make_tuple("default",
AliasesVector{},
csv_head,
"{\n"
" \"active-context\": \"default\",\n"
" \"contexts\": {\n"
" \"default\": {\n"
" }\n"
" }\n"
"}\n",
"No aliases defined.\n",
"active_context: default\n"
"aliases:\n"
" default: ~\n"),
std::make_tuple("default",
AliasesVector{{"lsp", {"primary", "ls", "map"}}, {"llp", {"primary", "ls", "map"}}},
csv_head + "llp,primary,ls,map,default*\n"
"lsp,primary,ls,map,default*\n",
"{\n"
" \"active-context\": \"default\",\n"
" \"contexts\": {\n"
" \"default\": {\n"
" \"llp\": {\n"
" \"command\": \"ls\",\n"
" \"instance\": \"primary\",\n"
" \"working-directory\": \"map\"\n"
" },\n"
" \"lsp\": {\n"
" \"command\": \"ls\",\n"
" \"instance\": \"primary\",\n"
" \"working-directory\": \"map\"\n"
" }\n"
" }\n"
" }\n"
"}\n",
"Alias Instance Command Context Working directory\n"
"llp primary ls default* map\n"
"lsp primary ls default* map\n",
"active_context: default\n"
"aliases:\n"
" default:\n"
" - alias: llp\n"
" command: ls\n"
" instance: primary\n"
" working-directory: map\n"
" - alias: lsp\n"
" command: ls\n"
" instance: primary\n"
" working-directory: map\n"),
std::make_tuple("docker",
AliasesVector{{"docker", {"docker", "docker", "map"}},
{"docker-compose", {"docker", "docker-compose", "map"}}},
csv_head + "docker,docker,docker,map,docker\n"
"docker-compose,docker,docker-compose,map,docker\n",
"{\n"
" \"active-context\": \"default\",\n"
" \"contexts\": {\n"
" \"default\": {\n"
" },\n"
" \"docker\": {\n"
" \"docker\": {\n"
" \"command\": \"docker\",\n"
" \"instance\": \"docker\",\n"
" \"working-directory\": \"map\"\n"
" },\n"
" \"docker-compose\": {\n"
" \"command\": \"docker-compose\",\n"
" \"instance\": \"docker\",\n"
" \"working-directory\": \"map\"\n"
" }\n"
" }\n"
" }\n"
"}\n",
"Alias Instance Command Context Working directory\n"
"docker docker docker docker map\n"
"docker-compose docker docker-compose docker map\n",
"active_context: default\n"
"aliases:\n"
" default: ~\n"
" docker:\n"
" - alias: docker\n"
" command: docker\n"
" instance: docker\n"
" working-directory: map\n"
" - alias: docker-compose\n"
" command: docker-compose\n"
" instance: docker\n"
" working-directory: map\n")));
struct RemoveInstanceTestsuite : public AliasDictionary,
public WithParamInterface<std::pair<AliasesVector, std::vector<std::string>>>
{
};
TEST_P(RemoveInstanceTestsuite, removes_instance_aliases)
{
auto [original_aliases, remaining_aliases] = GetParam();
populate_db_file(original_aliases);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.remove_aliases_for_instance("instance_to_remove");
ASSERT_EQ(dict.get_active_context().size(), remaining_aliases.size());
for (auto remaining_alias : remaining_aliases)
ASSERT_TRUE(dict.get_alias(remaining_alias));
}
INSTANTIATE_TEST_SUITE_P(
AliasDictionary, RemoveInstanceTestsuite,
Values(std::make_pair(AliasesVector{{"some_alias", {"instance_to_remove", "some_command", "map"}},
{"other_alias", {"other_instance", "other_command", "map"}},
{"another_alias", {"instance_to_remove", "another_command", "map"}},
{"yet_another_alias", {"yet_another_instance", "yet_another_command", "map"}}},
std::vector<std::string>{"other_alias", "yet_another_alias"}),
std::make_pair(AliasesVector{{"alias", {"instance", "command", "map"}}}, std::vector<std::string>{"alias"}),
std::make_pair(AliasesVector{{"alias", {"instance_to_remove", "command", "map"}}},
std::vector<std::string>{})));
typedef std::vector<std::vector<std::string>> CmdList;
struct DaemonAliasTestsuite
: public mpt::DaemonTestFixture,
public FakeAliasConfig,
public WithParamInterface<std::tuple<CmdList, std::string, std::vector<std::string> /* removed aliases */,
std::vector<std::string> /* failed removal aliases */>>
{
void SetUp() override
{
EXPECT_CALL(mock_settings, register_handler).WillRepeatedly(Return(nullptr));
EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber());
EXPECT_CALL(mock_settings, get(Eq(mp::winterm_key))).WillRepeatedly(Return("none"));
}
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject<StrictMock>();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
};
TEST_P(DaemonAliasTestsuite, purge_removes_purged_instance_aliases_and_scripts)
{
auto [commands, expected_output, expected_removed_aliases, expected_failed_removal] = GetParam();
auto mock_image_vault = std::make_unique<NaggyMock<mpt::MockVMImageVault>>();
EXPECT_CALL(*mock_image_vault, remove(_)).WillRepeatedly(Return());
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillRepeatedly(Return(mp::VMImage{}));
EXPECT_CALL(*mock_image_vault, prune_expired_images()).WillRepeatedly(Return());
EXPECT_CALL(*mock_image_vault, has_record_for(_)).WillRepeatedly(Return(true));
config_builder.vault = std::move(mock_image_vault);
auto mock_factory = use_a_mock_vm_factory();
EXPECT_CALL(*mock_factory, remove_resources_for(_)).WillRepeatedly(Return());
std::string json_contents = make_instance_json(std::nullopt, {}, {"primary"});
AliasesVector fake_aliases{{"lsp", {"primary", "ls", "map"}}, {"lsz", {"real-zebraphant", "ls", "map"}}};
populate_db_file(fake_aliases);
mpt::MockPlatform::GuardedMock attr{mpt::MockPlatform::inject<NiceMock>()};
mpt::MockPlatform* mock_platform = attr.first;
ON_CALL(*mock_platform, create_alias_script(_, _)).WillByDefault(Return());
for (const auto& removed_alias : expected_removed_aliases)
{
EXPECT_CALL(*mock_platform, remove_alias_script("default." + removed_alias)).Times(1);
EXPECT_CALL(*mock_platform, remove_alias_script(removed_alias)).Times(1);
}
for (const auto& removed_alias : expected_failed_removal)
{
EXPECT_CALL(*mock_platform, remove_alias_script("default." + removed_alias))
.WillOnce(Throw(std::runtime_error("foo")));
}
mpt::TempDir temp_dir;
QString filename(temp_dir.path() + "/multipassd-vm-instances.json");
mpt::make_file_with_content(filename, json_contents);
// Make the daemon look for the JSON on our temporary directory. It will read the contents of the file.
config_builder.data_directory = temp_dir.path();
mp::Daemon daemon{config_builder.build()};
std::stringstream cout, cerr;
for (const auto& command : commands)
send_command(command, cout, cerr);
for (const auto& removed_alias : expected_failed_removal)
EXPECT_THAT(cerr.str(), HasSubstr(fmt::format("Warning: 'foo' when removing alias script for default.{}\n",
removed_alias)));
send_command({"aliases", "--format", "csv"}, cout);
EXPECT_EQ(cout.str(), expected_output);
}
INSTANTIATE_TEST_SUITE_P(
AliasDictionary, DaemonAliasTestsuite,
Values(
std::make_tuple(CmdList{{"delete", "real-zebraphant"}, {"purge"}}, csv_head + "lsp,primary,ls,map,default*\n",
std::vector<std::string>{"lsz"}, std::vector<std::string>{}),
std::make_tuple(CmdList{{"delete", "--purge", "real-zebraphant"}}, csv_head + "lsp,primary,ls,map,default*\n",
std::vector<std::string>{"lsz"}, std::vector<std::string>{}),
std::make_tuple(CmdList{{"delete", "primary"}, {"delete", "primary", "real-zebraphant", "--purge"}}, csv_head,
std::vector<std::string>{"lsp", "lsz"}, std::vector<std::string>{}),
std::make_tuple(CmdList{{"delete", "primary"}, {"delete", "primary", "real-zebraphant", "--purge"}}, csv_head,
std::vector<std::string>{}, std::vector<std::string>{"lsp", "lsz"}),
std::make_tuple(CmdList{{"delete", "primary"}, {"delete", "primary", "real-zebraphant", "--purge"}}, csv_head,
std::vector<std::string>{"lsp"}, std::vector<std::string>{"lsz"}),
std::make_tuple(CmdList{{"delete", "real-zebraphant"}, {"purge"}}, csv_head + "lsp,primary,ls,map,default*\n",
std::vector<std::string>{}, std::vector<std::string>{"lsz"}),
std::make_tuple(CmdList{{"delete", "real-zebraphant", "primary"}, {"purge"}}, csv_head,
std::vector<std::string>{}, std::vector<std::string>{"lsz", "lsp"})));
TEST_F(AliasDictionary, unexistingActiveContextThrows)
{
std::string file_contents{"{\n"
" \"active-context\": \"inconsistent\",\n"
" \"contexts\": {\n"
" \"default\": {\n"
" }\n"
" }\n"
"}\n"};
mpt::make_file_with_content(QString::fromStdString(db_filename()), file_contents);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.active_context_name(), "inconsistent");
MP_ASSERT_THROW_THAT(dict.get_active_context(), std::runtime_error,
mpt::match_what(HasSubstr("active context \"inconsistent\" does not exist in dictionary")));
}
TEST_F(AliasDictionary, removeContextWorks)
{
std::string file_contents{"{\n"
" \"active-context\": \"default\",\n"
" \"contexts\": {\n"
" \"default\": {\n"
" \"alias1\": {\n"
" \"command\": \"first_command\",\n"
" \"instance\": \"first_instance\",\n"
" \"working-directory\": \"map\"\n"
" }\n"
" },\n"
" \"another\": {\n"
" \"alias2\": {\n"
" \"command\": \"second_command\",\n"
" \"instance\": \"second_instance\",\n"
" \"working-directory\": \"default\"\n"
" }\n"
" }\n"
" }\n"
"}\n"};
mpt::make_file_with_content(QString::fromStdString(db_filename()), file_contents);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.size(), 2u);
ASSERT_EQ(dict.active_context_name(), "default");
ASSERT_EQ(dict.get_active_context().size(), 1u);
dict.set_active_context("another");
ASSERT_EQ(dict.active_context_name(), "another");
ASSERT_EQ(dict.get_active_context().size(), 1u);
auto a2 = dict.get_alias("alias2");
ASSERT_TRUE(a2);
dict.remove_context("another");
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.active_context_name(), "default");
dict.set_active_context("another");
ASSERT_EQ(dict.get_active_context().size(), 0u);
}
TEST_F(AliasDictionary, removeDefaultContextWorks)
{
std::string file_contents{"{\n"
" \"active-context\": \"default\",\n"
" \"contexts\": {\n"
" \"default\": {\n"
" \"alias1\": {\n"
" \"command\": \"first_command\",\n"
" \"instance\": \"first_instance\",\n"
" \"working-directory\": \"map\"\n"
" }\n"
" },\n"
" \"another\": {\n"
" \"alias2\": {\n"
" \"command\": \"second_command\",\n"
" \"instance\": \"second_instance\",\n"
" \"working-directory\": \"default\"\n"
" }\n"
" }\n"
" }\n"
"}\n"};
mpt::make_file_with_content(QString::fromStdString(db_filename()), file_contents);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.size(), 2u);
ASSERT_EQ(dict.active_context_name(), "default");
ASSERT_EQ(dict.get_active_context().size(), 1u);
dict.set_active_context("another");
ASSERT_EQ(dict.active_context_name(), "another");
ASSERT_EQ(dict.get_active_context().size(), 1u);
auto a2 = dict.get_alias("alias2");
ASSERT_TRUE(a2);
dict.set_active_context("default");
ASSERT_EQ(dict.size(), 2u);
ASSERT_EQ(dict.active_context_name(), "default");
ASSERT_EQ(dict.get_active_context().size(), 1u);
dict.remove_context("default");
// Removing the default context just empties it.
ASSERT_EQ(dict.size(), 2u);
ASSERT_EQ(dict.get_active_context().size(), 0u);
dict.set_active_context("another");
ASSERT_EQ(dict.get_active_context().size(), 1u);
}
TEST_F(AliasDictionary, removingUnexistingContextDoesNothing)
{
std::string file_contents{"{\n"
" \"active-context\": \"default\",\n"
" \"contexts\": {\n"
" \"default\": {\n"
" \"alias1\": {\n"
" \"command\": \"first_command\",\n"
" \"instance\": \"first_instance\",\n"
" \"working-directory\": \"map\"\n"
" }\n"
" }\n"
" }\n"
"}\n"};
mpt::make_file_with_content(QString::fromStdString(db_filename()), file_contents);
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.active_context_name(), "default");
ASSERT_EQ(dict.get_active_context().size(), 1u);
dict.remove_context("unexisting");
ASSERT_EQ(dict.size(), 1u);
ASSERT_EQ(dict.active_context_name(), "default");
ASSERT_EQ(dict.get_active_context().size(), 1u);
}
TEST_F(AliasDictionary, unqualifiedGetContextAndAliasWorksIfInDifferentContext)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.add_alias("first_alias", mp::AliasDefinition{"instance-1", "command-1", "map"});
dict.set_active_context("new_context");
ASSERT_EQ(dict.get_context_and_alias("first_alias"), std::nullopt);
}
TEST_F(AliasDictionary, unqualifiedGetContextAndAliasWorksIfInCurrentContext)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.add_alias("first_alias", mp::AliasDefinition{"instance-1", "command-1", "map"});
auto context_and_alias = dict.get_context_and_alias("first_alias");
ASSERT_EQ(context_and_alias->first, "default");
ASSERT_EQ(context_and_alias->second, "first_alias");
}
TEST_F(AliasDictionary, unqualifiedGetContextAndAliasWorksWithEquallyNamesAliasesInDifferentContext)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.add_alias("first_alias", mp::AliasDefinition{"instance-1", "command-1", "map"});
dict.set_active_context("new_context");
dict.add_alias("first_alias", mp::AliasDefinition{"instance-2", "command-2", "map"});
auto context_and_alias = dict.get_context_and_alias("first_alias");
ASSERT_EQ(context_and_alias->first, "new_context");
ASSERT_EQ(context_and_alias->second, "first_alias");
}
TEST_F(AliasDictionary, qualifiedGetContextAndAliasWorksIfAliasAndContextExist)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.add_alias("first_alias", mp::AliasDefinition{"instance-1", "command-1", "map"});
dict.set_active_context("new_context");
dict.add_alias("second_alias", mp::AliasDefinition{"instance-2", "command-2", "map"});
auto context_and_alias = dict.get_context_and_alias("default.first_alias");
ASSERT_EQ(context_and_alias->first, "default");
ASSERT_EQ(context_and_alias->second, "first_alias");
}
TEST_F(AliasDictionary, qualifiedGetContextAndAliasWorksIfContextDoesNotExist)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.add_alias("first_alias", mp::AliasDefinition{"instance-1", "command-1", "map"});
ASSERT_EQ(dict.get_context_and_alias("nonexistent_context.first_alias"), std::nullopt);
}
TEST_F(AliasDictionary, qualifiedGetContextAndAliasWorksIfAliasDoesNotExist)
{
std::stringstream trash_stream;
mpt::StubTerminal trash_term(trash_stream, trash_stream, trash_stream);
mp::AliasDict dict(&trash_term);
dict.add_alias("first_alias", mp::AliasDefinition{"instance-1", "command-1", "map"});
ASSERT_EQ(dict.get_context_and_alias("default.nonexistent_alias"), std::nullopt);
}
} // namespace
| 38,113
|
C++
|
.cpp
| 751
| 39.310253
| 119
| 0.551887
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,613
|
test_sshfs_server_process_spec.cpp
|
canonical_multipass/tests/test_sshfs_server_process_spec.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_environment_helpers.h"
#include "temp_dir.h"
#include <src/platform/backends/shared/sshfs_server_process_spec.h>
#include <multipass/sshfs_server_config.h>
#include <QCoreApplication>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
struct TestSSHFSServerProcessSpec : public Test
{
mp::SSHFSServerConfig config{"host",
42,
"username",
"instance",
"private_key",
"source_path",
"target_path",
{{1, 2}, {3, 4}},
{{5, -1}, {6, 10}}};
};
TEST_F(TestSSHFSServerProcessSpec, program_correct)
{
mp::SSHFSServerProcessSpec spec(config);
EXPECT_TRUE(spec.program().endsWith("sshfs_server"));
}
TEST_F(TestSSHFSServerProcessSpec, arguments_correct)
{
mp::SSHFSServerProcessSpec spec(config);
ASSERT_EQ(spec.arguments().size(), 8);
EXPECT_EQ(spec.arguments()[0], "host");
EXPECT_EQ(spec.arguments()[1], "42");
EXPECT_EQ(spec.arguments()[2], "username");
EXPECT_EQ(spec.arguments()[3], "source_path");
EXPECT_EQ(spec.arguments()[4], "target_path");
// Ordering of the next 2 options not guaranteed, hence the or-s.
EXPECT_TRUE(spec.arguments()[5] == "6:10,5:-1," || spec.arguments()[5] == "5:-1,6:10,");
EXPECT_TRUE(spec.arguments()[6] == "3:4,1:2," || spec.arguments()[6] == "1:2,3:4,");
EXPECT_EQ(spec.arguments()[7], "0");
}
TEST_F(TestSSHFSServerProcessSpec, environment_correct)
{
mp::SSHFSServerProcessSpec spec(config);
ASSERT_TRUE(spec.environment().contains("KEY"));
EXPECT_EQ(spec.environment().value("KEY"), "private_key");
}
TEST_F(TestSSHFSServerProcessSpec, snap_confined_apparmor_profile_returns_expected_data)
{
mpt::TempDir bin_dir;
const QByteArray snap_name{"multipass"};
mpt::SetEnvScope env_scope("SNAP", bin_dir.path().toUtf8());
mpt::SetEnvScope env_scope2("SNAP_NAME", snap_name);
mp::SSHFSServerProcessSpec spec(config);
const auto apparmor_profile = spec.apparmor_profile();
EXPECT_TRUE(apparmor_profile.contains(bin_dir.path() + "/bin/sshfs_server"));
EXPECT_TRUE(apparmor_profile.contains(bin_dir.path() + "/{usr/,}lib/**"));
EXPECT_TRUE(apparmor_profile.contains("signal (receive) peer=snap.multipass.multipassd"));
}
TEST_F(TestSSHFSServerProcessSpec, unconfined_apparmor_profile_returns_expected_data)
{
const QByteArray snap_name{"multipass"};
mpt::UnsetEnvScope env_scope("SNAP");
mpt::SetEnvScope env_scope2("SNAP_NAME", snap_name);
mp::SSHFSServerProcessSpec spec(config);
QDir current_dir(QCoreApplication::applicationDirPath());
const auto apparmor_profile = spec.apparmor_profile();
current_dir.cdUp();
EXPECT_TRUE(apparmor_profile.contains(current_dir.absolutePath() + "/bin/sshfs_server"));
EXPECT_TRUE(apparmor_profile.contains(current_dir.absolutePath() + "/{usr/,}lib/**"));
EXPECT_TRUE(apparmor_profile.contains("signal (receive) peer=unconfined"));
}
| 3,809
|
C++
|
.cpp
| 87
| 37.712644
| 94
| 0.671436
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,614
|
mischievous_url_downloader.cpp
|
canonical_multipass/tests/mischievous_url_downloader.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mischievous_url_downloader.h"
namespace mp = multipass;
namespace mpt = multipass::test;
mpt::MischievousURLDownloader::MischievousURLDownloader(std::chrono::milliseconds timeout) : URLDownloader(timeout)
{
}
void mpt::MischievousURLDownloader::download_to(const QUrl& url, const QString& file_name, int64_t size,
const int download_type, const mp::ProgressMonitor& monitor)
{
URLDownloader::download_to(choose_url(url), file_name, size, download_type, monitor);
}
QByteArray mpt::MischievousURLDownloader::download(const QUrl& url)
{
return URLDownloader::download(choose_url(url));
}
QByteArray mpt::MischievousURLDownloader::download(const QUrl& url, const bool is_force_update_from_network)
{
return URLDownloader::download(choose_url(url), is_force_update_from_network);
}
QDateTime mpt::MischievousURLDownloader::last_modified(const QUrl& url)
{
return URLDownloader::last_modified(choose_url(url));
}
const QUrl& mpt::MischievousURLDownloader::choose_url(const QUrl& url)
{
return mischiefs-- > 0 ? empty_url : url;
}
| 1,739
|
C++
|
.cpp
| 43
| 37.325581
| 115
| 0.752962
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,615
|
test_qemuimg_process_spec.cpp
|
canonical_multipass/tests/test_qemuimg_process_spec.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "disabling_macros.h"
#include "mock_environment_helpers.h"
#include <multipass/process/qemuimg_process_spec.h>
#include <QFile>
#include <QTemporaryDir>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
TEST(TestQemuImgProcessSpec, program_correct)
{
mp::QemuImgProcessSpec spec({}, "");
EXPECT_EQ(spec.program(), "qemu-img");
}
TEST(TestQemuImgProcessSpec, default_arguments_correct)
{
mp::QemuImgProcessSpec spec({}, "");
EXPECT_EQ(spec.arguments(), QStringList());
}
TEST(TestQemuImgProcessSpec, arguments_set_correctly)
{
QStringList args{"-one", "--two"};
mp::QemuImgProcessSpec spec(args, "");
EXPECT_EQ(spec.arguments(), args);
}
TEST(TestQemuImgProcessSpec, apparmor_profile_has_correct_name)
{
mp::QemuImgProcessSpec spec({}, "");
EXPECT_TRUE(spec.apparmor_profile().contains("profile multipass.qemu-img"));
}
TEST(TestQemuImgProcessSpec, no_apparmor_profile_identifier)
{
mp::QemuImgProcessSpec spec({}, "");
EXPECT_EQ(spec.identifier(), "");
}
TEST(TestQemuImgProcessSpec, apparmor_profile_running_as_snap_correct)
{
const QByteArray snap_name{"multipass"};
QTemporaryDir snap_dir;
QString source_image{"/source/image/file"};
mpt::SetEnvScope e("SNAP", snap_dir.path().toUtf8());
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::QemuImgProcessSpec spec({}, source_image);
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1/usr/bin/qemu-img ixr,").arg(snap_dir.path())));
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1 rwk,").arg(source_image)));
}
TEST(TestQemuImgProcessSpec, apparmor_profile_running_as_snap_with_target_correct)
{
const QByteArray snap_name{"multipass"};
QTemporaryDir snap_dir;
QString source_image{"/source/image/file"}, target_image{"/target/image/file"};
mpt::SetEnvScope e("SNAP", snap_dir.path().toUtf8());
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::QemuImgProcessSpec spec({}, source_image, target_image);
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1/usr/bin/qemu-img ixr,").arg(snap_dir.path())));
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1 rwk,").arg(source_image)));
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1 rwk,").arg(target_image)));
}
TEST(TestQemuImgProcessSpec, apparmor_profile_running_as_snap_with_only_target_correct)
{
const QByteArray snap_name{"multipass"};
QTemporaryDir snap_dir;
QString target_image{"/target/image/file"};
mpt::SetEnvScope e("SNAP", snap_dir.path().toUtf8());
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::QemuImgProcessSpec spec({}, "", target_image);
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1/usr/bin/qemu-img ixr,").arg(snap_dir.path())));
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1 rwk,").arg(target_image)));
}
TEST(TestQemuImgProcessSpec,
DISABLE_ON_WINDOWS(apparmor_profile_running_as_symlinked_snap_correct)) // TODO tests involving apparmor should
// probably be moved elsewhere
{
const QByteArray snap_name{"multipass"};
QTemporaryDir snap_dir, snap_link_dir, common_dir, common_link_dir;
QString source_image{"/source/image/file"};
snap_link_dir.remove();
common_link_dir.remove();
QFile::link(snap_dir.path(), snap_link_dir.path());
QFile::link(common_dir.path(), common_link_dir.path());
mpt::SetEnvScope e("SNAP", snap_link_dir.path().toUtf8());
mpt::SetEnvScope e3("SNAP_NAME", snap_name);
mp::QemuImgProcessSpec spec({}, source_image);
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1/usr/bin/qemu-img ixr,").arg(snap_dir.path())));
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1 rwk,").arg(source_image)));
}
TEST(TestQemuImgProcessSpec, apparmor_profile_not_running_as_snap_correct)
{
const QByteArray snap_name{"multipass"};
mpt::UnsetEnvScope e("SNAP");
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::QemuImgProcessSpec spec({}, "");
EXPECT_TRUE(spec.apparmor_profile().contains("capability dac_read_search,"));
EXPECT_TRUE(spec.apparmor_profile().contains(" /usr/bin/qemu-img ixr,")); // space wanted
}
| 4,930
|
C++
|
.cpp
| 111
| 40.324324
| 116
| 0.712884
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,616
|
test_cloud_init_iso.cpp
|
canonical_multipass/tests/test_cloud_init_iso.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_file_ops.h"
#include "temp_dir.h"
#include <multipass/cloud_init_iso.h>
#include <multipass/network_interface.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
constexpr auto* meta_data_content = R"(#cloud-config
instance-id: vm1
local-hostname: vm1
cloud-name: multipass)";
auto read_returns_failed_ifstream = [](std::ifstream& file, char*, std::streamsize) -> std::ifstream& {
file.setstate(std::ios::failbit);
return file;
};
// Since we can have a valid file to read from and FileOps::read is a cheap function, falls back to the original
// implementation would be an easy way to implement EXPECT_CALL multiple times instead of mocking multiple single calls
// with the correct output
auto original_implementation_of_read = [](std::ifstream& file, char* buffer, std::streamsize pos) -> std::ifstream& {
return MP_FILEOPS.FileOps::read(file, buffer, pos);
};
} // namespace
struct CloudInitIso : public Test
{
CloudInitIso()
{
iso_path = QDir{temp_dir.path()}.filePath("test.iso");
}
mpt::TempDir temp_dir;
QString iso_path;
};
TEST_F(CloudInitIso, check_contains_false)
{
mp::CloudInitIso iso;
EXPECT_FALSE(iso.contains("non_exist_file"));
}
TEST_F(CloudInitIso, check_contains_true)
{
mp::CloudInitIso iso;
iso.add_file("test", "test data");
EXPECT_TRUE(iso.contains("test"));
}
TEST_F(CloudInitIso, check_erase_false)
{
mp::CloudInitIso iso;
EXPECT_FALSE(iso.erase("non_exist_file"));
}
TEST_F(CloudInitIso, check_erase_true)
{
mp::CloudInitIso iso;
iso.add_file("test", "test data");
EXPECT_TRUE(iso.contains("test"));
EXPECT_TRUE(iso.erase("test"));
EXPECT_FALSE(iso.contains("test"));
}
TEST_F(CloudInitIso, check_at_operator_throw)
{
mp::CloudInitIso iso;
MP_EXPECT_THROW_THAT(
iso.at("non_exist_file"),
std::runtime_error,
mpt::match_what(StrEq("Did not find the target file non_exist_file in the CloudInitIso instance.")));
}
TEST_F(CloudInitIso, check_at_operator_found_key)
{
mp::CloudInitIso iso;
iso.add_file("test", "test data");
EXPECT_EQ(iso.at("test"), "test data");
}
TEST_F(CloudInitIso, check_index_operator_not_exist_default_return)
{
mp::CloudInitIso iso;
EXPECT_EQ(iso["test"], std::string());
}
TEST_F(CloudInitIso, check_index_operator_found_key)
{
mp::CloudInitIso iso;
iso.add_file("test", "test data");
EXPECT_EQ(iso["test"], "test data");
}
TEST_F(CloudInitIso, creates_iso_file)
{
mp::CloudInitIso iso;
iso.add_file("test", "test data");
iso.write_to(iso_path);
QFile file{iso_path};
EXPECT_TRUE(file.exists());
EXPECT_THAT(file.size(), Ge(0));
}
TEST_F(CloudInitIso, reads_iso_file_failed_to_open_file)
{
mp::CloudInitIso original_iso;
original_iso.write_to(iso_path);
const auto [mock_file_ops, _] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, is_open(An<const std::ifstream&>())).WillOnce(Return(false));
mp::CloudInitIso new_iso;
MP_EXPECT_THROW_THAT(new_iso.read_from(std::filesystem::path(iso_path.toStdString())),
std::runtime_error,
mpt::match_what(HasSubstr("Failed to open file")));
}
TEST_F(CloudInitIso, reads_iso_file_failed_to_read_single_bytes)
{
mp::CloudInitIso original_iso;
original_iso.write_to(iso_path);
const auto [mock_file_ops, _] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, is_open(An<const std::ifstream&>())).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.WillOnce(read_returns_failed_ifstream);
// failed on the first read_single_byte call
mp::CloudInitIso new_iso;
MP_EXPECT_THROW_THAT(new_iso.read_from(std::filesystem::path(iso_path.toStdString())),
std::runtime_error,
mpt::match_what(HasSubstr("Can not read the next byte data from file at")));
}
TEST_F(CloudInitIso, reads_iso_file_failed_to_check_it_has_Joliet_volume_descriptor)
{
mp::CloudInitIso original_iso;
original_iso.write_to(iso_path);
const auto [mock_file_ops, _] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, is_open(An<const std::ifstream&>())).WillOnce(Return(true));
// value 2_u8 is for Joliet volume descriptor
auto read_returns_one_byte_value_one = [](std::ifstream& file, char* one_byte, std::streamsize) -> std::ifstream& {
const int non_joliet_volume_des_num{1U};
*one_byte = static_cast<std::uint8_t>(non_joliet_volume_des_num);
return file;
};
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.WillOnce(read_returns_one_byte_value_one);
mp::CloudInitIso new_iso;
MP_EXPECT_THROW_THAT(new_iso.read_from(std::filesystem::path(iso_path.toStdString())),
std::runtime_error,
mpt::match_what(StrEq("The Joliet volume descriptor is not in place.")));
}
TEST_F(CloudInitIso, reads_iso_file_Joliet_volume_descriptor_malformed)
{
mp::CloudInitIso original_iso;
original_iso.write_to(iso_path);
const auto [mock_file_ops, _] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, is_open(An<const std::ifstream&>())).WillOnce(Return(true));
const InSequence seq;
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.WillOnce(original_implementation_of_read);
auto read_returns_five_bytes_string = [](std::ifstream& file, char* buffer, std::streamsize) -> std::ifstream& {
std::strcpy(buffer, "NonJo");
return file;
};
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.WillOnce(read_returns_five_bytes_string);
mp::CloudInitIso new_iso;
MP_EXPECT_THROW_THAT(new_iso.read_from(std::filesystem::path(iso_path.toStdString())),
std::runtime_error,
mpt::match_what(StrEq("The Joliet descriptor is malformed.")));
}
TEST_F(CloudInitIso, reads_iso_file_failed_to_read_array)
{
mp::CloudInitIso original_iso;
original_iso.write_to(iso_path);
const auto [mock_file_ops, _] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, is_open(An<const std::ifstream&>())).WillOnce(Return(true));
const InSequence seq;
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.WillOnce(original_implementation_of_read);
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.WillOnce(read_returns_failed_ifstream);
mp::CloudInitIso new_iso;
MP_EXPECT_THROW_THAT(new_iso.read_from(std::filesystem::path(iso_path.toStdString())),
std::runtime_error,
mpt::match_what(HasSubstr("bytes data from file at")));
}
TEST_F(CloudInitIso, reads_iso_file_failed_to_check_root_dir_record_data)
{
mp::CloudInitIso original_iso;
original_iso.write_to(iso_path);
const auto [mock_file_ops, _] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, is_open(An<const std::ifstream&>())).WillOnce(Return(true));
const InSequence seq;
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.Times(2)
.WillRepeatedly(original_implementation_of_read);
// default buffer values makes the buffer[0] not 34_u8 which causes root directory record data checking fail
auto read_return_default_buffer = [](std::ifstream& file, char* buffer, std::streamsize) -> std::ifstream& {
return file;
};
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.WillOnce(read_return_default_buffer);
mp::CloudInitIso new_iso;
MP_EXPECT_THROW_THAT(new_iso.read_from(std::filesystem::path(iso_path.toStdString())),
std::runtime_error,
mpt::match_what(StrEq("The root directory record data is malformed.")));
}
TEST_F(CloudInitIso, reads_iso_file_failed_to_read_vec)
{
mp::CloudInitIso original_iso;
// At least one actual file entry is need to reach the read_bytes_to_vec call
original_iso.add_file("test1", "test data1");
original_iso.write_to(iso_path);
const auto [mock_file_ops, _] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, is_open(An<const std::ifstream&>())).WillOnce(Return(true));
// The first read_bytes_to_vec call invoke the 7th call of MP_FILEOPS.read
const InSequence seq;
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.Times(6)
.WillRepeatedly(original_implementation_of_read);
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.WillOnce(read_returns_failed_ifstream);
mp::CloudInitIso new_iso;
MP_EXPECT_THROW_THAT(new_iso.read_from(std::filesystem::path(iso_path.toStdString())),
std::runtime_error,
mpt::match_what(HasSubstr("bytes data from file at")));
}
TEST_F(CloudInitIso, reads_iso_file_encoded_file_name_is_not_even_length)
{
mp::CloudInitIso original_iso;
// At least one actual file entry is need to reach the convert_u16_name_back call
original_iso.add_file("test1", "test data1");
original_iso.write_to(iso_path);
const auto [mock_file_ops, _] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, is_open(An<const std::ifstream&>())).WillOnce(Return(true));
const InSequence seq;
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.Times(7)
.WillRepeatedly(original_implementation_of_read);
auto read_returns_one_byte_value_three =
[](std::ifstream& file, char* one_byte, std::streamsize) -> std::ifstream& {
const int encoded_file_name_length{3U}; // any odd number will do it
*one_byte = static_cast<std::uint8_t>(encoded_file_name_length);
return file;
};
// read_single_byte encoded_file_name_length odd number
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.WillOnce(read_returns_one_byte_value_three);
EXPECT_CALL(*mock_file_ops, read(An<std::ifstream&>(), A<char*>(), A<std::streamsize>()))
.WillOnce(original_implementation_of_read);
mp::CloudInitIso new_iso;
MP_EXPECT_THROW_THAT(new_iso.read_from(std::filesystem::path(iso_path.toStdString())),
std::runtime_error,
mpt::match_what(HasSubstr("is not even, which does not conform to u16 name format")));
}
TEST_F(CloudInitIso, reads_iso_file_with_random_string_data)
{
mp::CloudInitIso original_iso;
original_iso.add_file("test1", "test data1");
original_iso.add_file("test test 2", "test some data2");
original_iso.add_file("test_random_name_3", "more \r test \n \n data3");
original_iso.add_file("test-title_4", "random_test_data: \n - path: /etc/pollinate/add-user-agent");
original_iso.add_file("t5", "");
original_iso.write_to(iso_path);
mp::CloudInitIso new_iso;
new_iso.read_from(iso_path.toStdString());
EXPECT_EQ(original_iso, new_iso);
}
TEST_F(CloudInitIso, reads_iso_file_with_mocked_real_file_data)
{
constexpr auto* user_data_content = R"(#cloud-config
{})";
constexpr auto* vendor_data_content = R"(#cloud-config
growpart:
mode: auto
devices: [/]
ignore_growroot_disabled: false
users:
- default
manage_etc_hosts: true
ssh_authorized_keys:
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQChYxmeUq14WG5KW+PQ9QvlytbZqMC2wIUxHyRzKbieOge2INvi7cG6NhoZ/KUp9RxVMkC1lll38VfHW3xupqxKj1ECDrMNAjuqOB+i8iS+XB3CTzlCs/3I7sW4nbG0fVwXTN6wUpQ9c9PZe09fmB/Va06gtyEb88lBzUq0Q932ZAqOYN+e/0r9TcIrNdzNlGDviiwykC94kzRJ8IapngxJkPzv3ohiOX3rpWCB1I0l2fLc0ZlZulLYxWphDFticoPl6l1mRlhM/1vRJzyjJXmHoFEmabIUe6nkjDy3JAo1btJ5L6CuN0yBsSLshk8XS/ACSNGvS8VvmLGXT0nbTyDH ubuntu@localhost
timezone: Europe/Amsterdam
system_info:
default_user:
name: ubuntu
write_files:
- path: /etc/pollinate/add-user-agent
content: "multipass/version/1.14.0-dev.1209+g5b2c7f7d # written by Multipass\nmultipass/driver/qemu-8.0.4 # written by Multipass\nmultipass/host/ubuntu-23.10 # written by Multipass\nmultipass/alias/default # written by Multipass\n"
)";
mp::CloudInitIso original_iso;
original_iso.add_file("meta-data", meta_data_content);
original_iso.add_file("vendor_data_content", vendor_data_content);
original_iso.add_file("user-data", user_data_content);
original_iso.add_file("network-config", "some random network-data");
original_iso.write_to(iso_path);
mp::CloudInitIso new_iso;
new_iso.read_from(iso_path.toStdString());
EXPECT_EQ(original_iso, new_iso);
}
TEST_F(CloudInitIso, updateCloudInitWithNewNonEmptyExtraInterfaces)
{
mp::CloudInitIso original_iso;
original_iso.add_file("meta-data", meta_data_content);
original_iso.add_file("network-config", "dummy_data");
original_iso.write_to(iso_path);
const std::string default_mac_addr = "52:54:00:56:78:90";
const std::vector<mp::NetworkInterface> extra_interfaces = {{"id", "52:54:00:56:78:91", true}};
EXPECT_NO_THROW(
MP_CLOUD_INIT_FILE_OPS.update_cloud_init_with_new_extra_interfaces_and_new_id(default_mac_addr,
extra_interfaces,
"vm2",
iso_path.toStdString()));
constexpr auto* expected_modified_meta_data_content = R"(#cloud-config
instance-id: vm2
local-hostname: vm1
cloud-name: multipass
)";
constexpr auto* expected_generated_network_config_data_content = R"(#cloud-config
version: 2
ethernets:
default:
match:
macaddress: "52:54:00:56:78:90"
dhcp4: true
dhcp-identifier: mac
extra0:
match:
macaddress: "52:54:00:56:78:91"
dhcp4: true
dhcp-identifier: mac
dhcp4-overrides:
route-metric: 200
optional: true
)";
mp::CloudInitIso new_iso;
new_iso.read_from(iso_path.toStdString());
EXPECT_EQ(new_iso.at("meta-data"), expected_modified_meta_data_content);
EXPECT_EQ(new_iso.at("network-config"), expected_generated_network_config_data_content);
}
TEST_F(CloudInitIso, updateCloudInitWithNewEmptyExtraInterfaces)
{
mp::CloudInitIso original_iso;
original_iso.add_file("meta-data", meta_data_content);
original_iso.add_file("network-config", "dummy_data");
original_iso.write_to(iso_path);
const std::string& default_mac_addr = "52:54:00:56:78:90";
const std::vector<mp::NetworkInterface> empty_extra_interfaces{};
EXPECT_NO_THROW(
MP_CLOUD_INIT_FILE_OPS.update_cloud_init_with_new_extra_interfaces_and_new_id(default_mac_addr,
empty_extra_interfaces,
std::string(),
iso_path.toStdString()));
mp::CloudInitIso new_iso;
new_iso.read_from(iso_path.toStdString());
EXPECT_TRUE(new_iso.contains("network-config"));
}
TEST_F(CloudInitIso, updateCloneCloudInitSrcFileWithExtraInterfaces)
{
constexpr auto* src_meta_data_content = R"(#cloud-config
instance-id: vm1_e_e
local-hostname: vm1
cloud-name: multipass)";
constexpr auto* src_network_config_data_content = R"(#cloud-config
version: 2
ethernets:
default:
match:
macaddress: "00:00:00:00:00:00"
dhcp4: true
dhcp-identifier: mac
extra0:
match:
macaddress: "00:00:00:00:00:01"
dhcp4: true
dhcp-identifier: mac
dhcp4-overrides:
route-metric: 200
optional: true
)";
mp::CloudInitIso original_iso;
original_iso.add_file("meta-data", src_meta_data_content);
original_iso.add_file("network-config", src_network_config_data_content);
original_iso.write_to(iso_path);
const std::string default_mac_addr = "52:54:00:56:78:90";
const std::vector<mp::NetworkInterface> extra_interfaces = {{"id", "52:54:00:56:78:91", true}};
EXPECT_NO_THROW(MP_CLOUD_INIT_FILE_OPS.update_cloned_cloud_init_unique_identifiers(default_mac_addr,
extra_interfaces,
"vm1-clone1",
iso_path.toStdString()));
constexpr auto* expected_modified_meta_data_content = R"(#cloud-config
instance-id: vm1-clone1_e_e
local-hostname: vm1-clone1
cloud-name: multipass
)";
constexpr auto* expected_generated_network_config_data_content = R"(#cloud-config
version: 2
ethernets:
default:
match:
macaddress: "52:54:00:56:78:90"
dhcp4: true
dhcp-identifier: mac
extra0:
match:
macaddress: "52:54:00:56:78:91"
dhcp4: true
dhcp-identifier: mac
dhcp4-overrides:
route-metric: 200
optional: true
)";
mp::CloudInitIso new_iso;
new_iso.read_from(iso_path.toStdString());
EXPECT_EQ(new_iso.at("meta-data"), expected_modified_meta_data_content);
EXPECT_EQ(new_iso.at("network-config"), expected_generated_network_config_data_content);
}
TEST_F(CloudInitIso, addExtraInterfaceToCloudInit)
{
mp::CloudInitIso original_iso;
original_iso.add_file("meta-data", meta_data_content);
original_iso.write_to(iso_path);
const mp::NetworkInterface dummy_extra_interface{};
EXPECT_NO_THROW(
MP_CLOUD_INIT_FILE_OPS.add_extra_interface_to_cloud_init("", dummy_extra_interface, iso_path.toStdString()));
}
TEST_F(CloudInitIso, getInstanceIdFromCloudInit)
{
mp::CloudInitIso original_iso;
original_iso.add_file("meta-data", meta_data_content);
original_iso.write_to(iso_path);
EXPECT_EQ(MP_CLOUD_INIT_FILE_OPS.get_instance_id_from_cloud_init(iso_path.toStdString()), "vm1");
}
| 19,048
|
C++
|
.cpp
| 435
| 37.124138
| 401
| 0.664671
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,617
|
mock_ssh.cpp
|
canonical_multipass/tests/mock_ssh.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_ssh.h"
extern "C"
{
IMPL_MOCK_DEFAULT(0, ssh_new);
IMPL_MOCK_DEFAULT(1, ssh_connect);
IMPL_MOCK_DEFAULT(1, ssh_is_connected);
IMPL_MOCK_DEFAULT(3, ssh_options_set);
IMPL_MOCK_DEFAULT(3, ssh_userauth_publickey);
IMPL_MOCK_DEFAULT(1, ssh_channel_is_eof);
IMPL_MOCK_DEFAULT(1, ssh_channel_is_closed);
IMPL_MOCK_DEFAULT(1, ssh_channel_is_open);
IMPL_MOCK_DEFAULT(1, ssh_channel_new);
IMPL_MOCK_DEFAULT(1, ssh_channel_open_session);
IMPL_MOCK_DEFAULT(2, ssh_channel_request_exec);
IMPL_MOCK_DEFAULT(5, ssh_channel_read_timeout);
IMPL_MOCK_DEFAULT(1, ssh_channel_get_exit_status);
IMPL_MOCK_DEFAULT(2, ssh_event_dopoll);
IMPL_MOCK_DEFAULT(2, ssh_add_channel_callbacks);
IMPL_MOCK_DEFAULT(1, ssh_get_error);
}
| 1,411
|
C++
|
.cpp
| 36
| 35.972222
| 72
| 0.725619
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,618
|
test_recursive_dir_iter.cpp
|
canonical_multipass/tests/test_recursive_dir_iter.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <chrono>
#include <fstream>
#include <multipass/recursive_dir_iterator.h>
namespace mp = multipass;
namespace fs = mp::fs;
using namespace testing;
struct RecursiveDirIterator : public Test
{
fs::path temp_dir = fs::temp_directory_path() / "multipass_recursive_dir_iter_test";
fs::path temp_file = temp_dir / "file.txt";
std::error_code err;
mp::DirectoryEntry entry;
RecursiveDirIterator()
{
fs::create_directory(temp_dir);
std::ofstream{temp_file};
}
~RecursiveDirIterator()
{
fs::remove_all(temp_dir);
}
};
TEST_F(RecursiveDirIterator, assign)
{
EXPECT_NO_THROW(entry.assign(temp_dir));
entry.assign(temp_dir, err);
EXPECT_FALSE(err);
EXPECT_EQ(entry.path(), temp_dir);
}
TEST_F(RecursiveDirIterator, replace_filename)
{
entry.assign(temp_dir / "filename");
EXPECT_NO_THROW(entry.replace_filename(temp_file.filename()));
entry.replace_filename(temp_file.filename(), err);
EXPECT_FALSE(err);
EXPECT_EQ(entry.path().filename(), temp_file.filename());
}
TEST_F(RecursiveDirIterator, refresh)
{
entry.assign(temp_dir);
EXPECT_NO_THROW(entry.refresh());
entry.refresh(err);
EXPECT_FALSE(err);
}
TEST_F(RecursiveDirIterator, exists)
{
entry.assign(temp_dir);
EXPECT_NO_THROW(entry.exists());
EXPECT_TRUE(entry.exists());
EXPECT_TRUE(entry.exists(err));
EXPECT_FALSE(err);
entry.assign(temp_dir / "nonexistent");
EXPECT_NO_THROW(entry.exists());
EXPECT_FALSE(entry.exists());
EXPECT_FALSE(entry.exists(err));
}
TEST_F(RecursiveDirIterator, is_type)
{
entry.assign(temp_file);
EXPECT_NO_THROW(entry.is_regular_file());
EXPECT_TRUE(entry.is_regular_file());
EXPECT_TRUE(entry.is_regular_file(err));
EXPECT_FALSE(err);
#define IS_NOT_TYPE(type) \
EXPECT_NO_THROW(entry.is_##type()); \
EXPECT_FALSE(entry.is_##type()); \
EXPECT_FALSE(entry.is_##type(err)); \
EXPECT_FALSE(err);
IS_NOT_TYPE(block_file);
IS_NOT_TYPE(character_file);
IS_NOT_TYPE(directory);
IS_NOT_TYPE(fifo);
IS_NOT_TYPE(other);
IS_NOT_TYPE(socket);
IS_NOT_TYPE(symlink);
}
TEST_F(RecursiveDirIterator, file_size)
{
entry.assign(temp_file);
EXPECT_NO_THROW(entry.file_size());
EXPECT_EQ(entry.file_size(), 0);
EXPECT_EQ(entry.file_size(err), 0);
EXPECT_FALSE(err);
}
TEST_F(RecursiveDirIterator, hard_link_count)
{
entry.assign(temp_file);
EXPECT_NO_THROW(entry.file_size());
EXPECT_EQ(entry.hard_link_count(), 1);
EXPECT_EQ(entry.hard_link_count(err), 1);
EXPECT_FALSE(err);
}
TEST_F(RecursiveDirIterator, last_write_time)
{
entry.assign(temp_file);
auto file_date = entry.last_write_time();
entry.assign(temp_dir);
auto dir_date = entry.last_write_time(err);
EXPECT_LE(file_date, dir_date);
EXPECT_FALSE(err);
}
TEST_F(RecursiveDirIterator, status)
{
entry.assign(temp_dir);
EXPECT_NO_THROW(entry.status());
EXPECT_NO_THROW(entry.symlink_status());
auto s = entry.status(err);
EXPECT_FALSE(err);
auto ss = entry.symlink_status(err);
EXPECT_FALSE(err);
EXPECT_EQ(s.type(), fs::file_type::directory);
EXPECT_EQ(ss.type(), fs::file_type::directory);
EXPECT_NE(s.permissions(), fs::perms::unknown);
EXPECT_NE(ss.permissions(), fs::perms::unknown);
}
TEST_F(RecursiveDirIterator, equal)
{
mp::DirectoryEntry dir_entry{};
dir_entry.assign(temp_dir);
mp::DirectoryEntry file_entry{};
dir_entry.assign(temp_file);
EXPECT_FALSE(dir_entry == file_entry);
}
TEST_F(RecursiveDirIterator, hasNext)
{
mp::RecursiveDirIterator iter{temp_dir, err};
EXPECT_FALSE(err);
EXPECT_TRUE(iter.hasNext());
}
TEST_F(RecursiveDirIterator, next)
{
mp::RecursiveDirIterator iter{temp_dir, err};
EXPECT_FALSE(err);
EXPECT_EQ(fs::canonical(iter.next().path()), fs::canonical(temp_file));
}
| 4,904
|
C++
|
.cpp
| 152
| 28.565789
| 120
| 0.647196
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,619
|
test_daemon.cpp
|
canonical_multipass/tests/test_daemon.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "blueprint_test_lambdas.h"
#include "common.h"
#include "daemon_test_fixture.h"
#include "dummy_ssh_key_provider.h"
#include "fake_alias_config.h"
#include "json_test_utils.h"
#include "mock_daemon.h"
#include "mock_environment_helpers.h"
#include "mock_file_ops.h"
#include "mock_image_host.h"
#include "mock_json_utils.h"
#include "mock_logger.h"
#include "mock_platform.h"
#include "mock_server_reader_writer.h"
#include "mock_settings.h"
#include "mock_standard_paths.h"
#include "mock_utils.h"
#include "mock_virtual_machine.h"
#include "mock_vm_blueprint_provider.h"
#include "mock_vm_image_vault.h"
#include "path.h"
#include "stub_virtual_machine.h"
#include "stub_vm_image_vault.h"
#include "tracking_url_downloader.h"
#include <src/daemon/default_vm_image_vault.h>
#include <src/daemon/instance_settings_handler.h>
#include <multipass/constants.h>
#include <multipass/default_vm_blueprint_provider.h>
#include <multipass/exceptions/blueprint_exceptions.h>
#include <multipass/logging/log.h>
#include <multipass/name_generator.h>
#include <multipass/version.h>
#include <multipass/virtual_machine_factory.h>
#include <multipass/vm_image_host.h>
#include <yaml-cpp/yaml.h>
#include <scope_guard.hpp>
#include <QJsonArray>
#include <QJsonDocument>
#include <QNetworkProxyFactory>
#include <QStorageInfo>
#include <QString>
#include <QSysInfo>
#include <memory>
#include <ostream>
#include <stdexcept>
#include <string>
#include <variant>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
using namespace multipass::utils;
namespace YAML
{
void PrintTo(const YAML::Node& node, ::std::ostream* os)
{
YAML::Emitter emitter;
emitter.SetIndent(4);
emitter << node;
*os << "\n" << emitter.c_str();
}
} // namespace YAML
namespace
{
const qint64 default_total_bytes{16'106'127'360}; // 15G
const std::string csv_header{"Alias,Instance,Command,Working directory,Context\n"};
struct StubNameGenerator : public mp::NameGenerator
{
explicit StubNameGenerator(std::string name) : name{std::move(name)}
{
}
std::string make_name() override
{
return name;
}
std::string name;
};
} // namespace
struct Daemon : public mpt::DaemonTestFixture
{
Daemon()
{
ON_CALL(mock_utils, filesystem_bytes_available(_)).WillByDefault([this](const QString& data_directory) {
return mock_utils.Utils::filesystem_bytes_available(data_directory);
});
EXPECT_CALL(mock_platform, get_blueprints_url_override()).WillRepeatedly([] { return QString{}; });
EXPECT_CALL(mock_platform, multipass_storage_location()).Times(AnyNumber()).WillRepeatedly(Return(QString()));
EXPECT_CALL(mock_platform, create_alias_script(_, _)).WillRepeatedly(Return());
EXPECT_CALL(mock_platform, remove_alias_script(_)).WillRepeatedly(Return());
}
void SetUp() override
{
EXPECT_CALL(mock_settings, register_handler).WillRepeatedly(Return(nullptr));
EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber());
EXPECT_CALL(mock_settings, get(Eq(mp::petenv_key))).WillRepeatedly(Return("pet-instance"));
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillRepeatedly(Return("true")); /* TODO should probably add
a few more tests for `false`, since there are different portions of code depending on it */
EXPECT_CALL(mock_settings, get(Eq(mp::winterm_key))).WillRepeatedly(Return("none"));
EXPECT_CALL(mock_settings, get(Eq(mp::bridged_interface_key))).WillRepeatedly(Return("eth8"));
}
mpt::MockUtils::GuardedMock mock_utils_injection{mpt::MockUtils::inject<NiceMock>()};
mpt::MockUtils& mock_utils = *mock_utils_injection.first;
mpt::MockPlatform::GuardedMock mock_platform_injection{mpt::MockPlatform::inject()};
mpt::MockPlatform& mock_platform = *mock_platform_injection.first;
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject<StrictMock>();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
};
TEST_F(Daemon, receives_commands_and_calls_corresponding_slot)
{
mpt::MockDaemon daemon{config_builder.build()};
EXPECT_CALL(daemon, keys)
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::KeysRequest, mp::KeysReply>));
EXPECT_CALL(daemon, get)
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::GetRequest, mp::GetReply>));
EXPECT_CALL(daemon, set)
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::SetRequest, mp::SetReply>));
EXPECT_CALL(daemon, create(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::CreateRequest, mp::CreateReply>));
EXPECT_CALL(daemon, launch(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::LaunchRequest, mp::LaunchReply>));
EXPECT_CALL(daemon, purge(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::PurgeRequest, mp::PurgeReply>));
EXPECT_CALL(daemon, find(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::FindRequest, mp::FindReply>));
EXPECT_CALL(daemon, ssh_info(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::SSHInfoRequest, mp::SSHInfoReply>));
EXPECT_CALL(daemon, info(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::InfoRequest, mp::InfoReply>));
EXPECT_CALL(daemon, list(_, _, _)).WillOnce([](auto, auto server, auto status_promise) {
mp::ListReply reply;
reply.mutable_instance_list();
server->Write(reply);
status_promise->set_value(grpc::Status::OK);
return grpc::Status{};
});
EXPECT_CALL(daemon, recover(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::RecoverRequest, mp::RecoverReply>));
EXPECT_CALL(daemon, start(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::StartRequest, mp::StartReply>));
EXPECT_CALL(daemon, stop(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::StopRequest, mp::StopReply>));
EXPECT_CALL(daemon, suspend(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::SuspendRequest, mp::SuspendReply>));
EXPECT_CALL(daemon, restart(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::RestartRequest, mp::RestartReply>));
EXPECT_CALL(daemon, delet(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::DeleteRequest, mp::DeleteReply>));
EXPECT_CALL(daemon, version(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::VersionRequest, mp::VersionReply>));
EXPECT_CALL(daemon, mount(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::MountRequest, mp::MountReply>));
EXPECT_CALL(daemon, umount(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::UmountRequest, mp::UmountReply>));
EXPECT_CALL(daemon, networks(_, _, _))
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::NetworksRequest, mp::NetworksReply>));
EXPECT_CALL(daemon, snapshot)
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::SnapshotRequest, mp::SnapshotReply>));
EXPECT_CALL(daemon, restore)
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::RestoreRequest, mp::RestoreReply>));
EXPECT_CALL(daemon, clone)
.WillOnce(Invoke(&daemon, &mpt::MockDaemon::set_promise_value<mp::CloneRequest, mp::CloneReply>));
EXPECT_CALL(mock_settings, get(Eq("foo"))).WillRepeatedly(Return("bar"));
send_commands({{"test_keys"},
{"test_get", "foo"},
{"test_set", "foo", "bar"},
{"test_create", "foo"},
{"launch", "foo"},
{"delete", "foo"},
{"exec", "foo", "--no-map-working-directory", "--", "cmd"},
{"info", "foo"},
{"list"},
{"purge"},
{"recover", "foo"},
{"snapshot", "foo"},
{"start", "foo"},
{"stop", "foo"},
{"suspend", "foo"},
{"restart", "foo"},
{"restore", "foo.bar"},
{"version"},
{"find", "something"},
{"mount", ".", "target"},
{"umount", "instance"},
{"networks"},
{"clone", "foo"}});
}
TEST_F(Daemon, provides_version)
{
mp::Daemon daemon{config_builder.build()};
StrictMock<mpt::MockServerReaderWriter<mp::VersionReply, mp::VersionRequest>> mock_server;
EXPECT_CALL(mock_server, Write(Property(&mp::VersionReply::version, StrEq(mp::version_string)), _))
.WillOnce(Return(true));
EXPECT_TRUE(call_daemon_slot(daemon, &mp::Daemon::version, mp::VersionRequest{}, mock_server).ok());
}
TEST_F(Daemon, failed_restart_command_returns_fulfilled_promise)
{
mp::Daemon daemon{config_builder.build()};
auto nonexistent_instance = new mp::InstanceNames; // on heap as *Request takes ownership
nonexistent_instance->add_instance_name("nonexistent");
mp::RestartRequest request;
request.set_allocated_instance_names(nonexistent_instance);
std::promise<grpc::Status> status_promise;
daemon.restart(&request, nullptr, &status_promise);
EXPECT_TRUE(is_ready(status_promise.get_future()));
}
TEST_F(Daemon, proxy_contains_valid_info)
{
auto guard = sg::make_scope_guard([]() noexcept { // std::terminate ok if this throws
QNetworkProxyFactory::setUseSystemConfiguration(true); // Resets proxy back to what the system is configured for
});
QString username{"username"};
QString password{"password"};
QString hostname{"192.168.1.1"};
qint16 port{3128};
QString proxy = QString("%1:%2@%3:%4").arg(username).arg(password).arg(hostname).arg(port);
mpt::SetEnvScope env("http_proxy", proxy.toUtf8());
auto config = config_builder.build();
EXPECT_THAT(config->network_proxy->user(), username);
EXPECT_THAT(config->network_proxy->password(), password);
EXPECT_THAT(config->network_proxy->hostName(), hostname);
EXPECT_THAT(config->network_proxy->port(), port);
}
TEST_F(Daemon, daemonAppliesPermissionsToStorageDirectory)
{
QTemporaryDir storage_dir;
mpt::SetEnvScope storage(mp::multipass_storage_env_var, storage_dir.path().toUtf8());
EXPECT_CALL(mock_platform, multipass_storage_location()).WillOnce(Return(mp::utils::get_multipass_storage()));
EXPECT_CALL(mock_utils, make_dir(_, QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner));
auto config = config_builder.build();
}
TEST_F(Daemon, data_path_valid)
{
QTemporaryDir data_dir, cache_dir;
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::CacheLocation))
.WillOnce(Return(cache_dir.path()));
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::AppDataLocation))
.WillOnce(Return(data_dir.path()));
EXPECT_CALL(mock_platform, multipass_storage_location()).WillOnce(Return(QString()));
config_builder.data_directory = "";
config_builder.cache_directory = "";
auto config = config_builder.build();
EXPECT_EQ(config->data_directory, data_dir.path());
EXPECT_EQ(config->cache_directory, cache_dir.path());
}
TEST_F(Daemon, data_path_with_storage_valid)
{
QTemporaryDir storage_dir;
mpt::SetEnvScope storage(mp::multipass_storage_env_var, storage_dir.path().toUtf8());
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(_)).Times(0);
EXPECT_CALL(mock_platform, multipass_storage_location()).WillOnce(Return(mp::utils::get_multipass_storage()));
ON_CALL(mock_utils, make_dir(_, _, _))
.WillByDefault([this](const QDir& a_dir, const QString& name, QFileDevice::Permissions permissions) {
return mock_utils.Utils::make_dir(a_dir, name, permissions);
});
config_builder.data_directory = "";
config_builder.cache_directory = "";
auto config = config_builder.build();
EXPECT_EQ(config->data_directory, storage_dir.filePath("data"));
EXPECT_EQ(config->cache_directory, storage_dir.filePath("cache"));
}
TEST_F(Daemon, blueprintsDownloadsFromCorrectURL)
{
mpt::TempDir cache_dir;
auto url_downloader = std::make_unique<mpt::TrackingURLDownloader>();
config_builder.cache_directory = cache_dir.path();
config_builder.url_downloader = std::move(url_downloader);
config_builder.blueprint_provider.reset();
auto config = config_builder.build();
mpt::TrackingURLDownloader* downloader = static_cast<mpt::TrackingURLDownloader*>(config->url_downloader.get());
EXPECT_EQ(downloader->downloaded_urls.size(), 1);
EXPECT_EQ(downloader->downloaded_urls.front(), mp::default_blueprint_url);
}
TEST_F(Daemon, blueprintsURLOverrideIsCorrect)
{
mpt::TempDir cache_dir;
auto url_downloader = std::make_unique<mpt::TrackingURLDownloader>();
const QString test_blueprints_zip{mpt::test_data_path() + "test-blueprints.zip"};
EXPECT_CALL(mock_platform, get_blueprints_url_override()).WillOnce([&test_blueprints_zip] {
return QUrl::fromLocalFile(test_blueprints_zip).toEncoded();
});
config_builder.cache_directory = cache_dir.path();
config_builder.url_downloader = std::move(url_downloader);
config_builder.blueprint_provider.reset();
auto config = config_builder.build();
mpt::TrackingURLDownloader* downloader = static_cast<mpt::TrackingURLDownloader*>(config->url_downloader.get());
EXPECT_EQ(downloader->downloaded_urls.size(), 1);
EXPECT_EQ(downloader->downloaded_urls.front(), QUrl::fromLocalFile(test_blueprints_zip).toString());
}
namespace
{
struct DaemonCreateLaunchTestSuite : public Daemon, public WithParamInterface<std::string>
{
};
struct DaemonCreateLaunchPollinateDataTestSuite : public Daemon,
public WithParamInterface<std::tuple<std::string, std::string>>
{
};
struct DaemonCreateLaunchAliasTestSuite : public Daemon, public FakeAliasConfig, public WithParamInterface<std::string>
{
DaemonCreateLaunchAliasTestSuite()
{
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(_))
.WillRepeatedly(Return(fake_alias_dir.path()));
}
};
struct MinSpaceRespectedSuite : public Daemon,
public WithParamInterface<std::tuple<std::string, std::string, std::string>>
{
};
struct MinSpaceViolatedSuite : public Daemon,
public WithParamInterface<std::tuple<std::string, std::string, std::string>>
{
};
struct LaunchImgSizeSuite : public Daemon,
public WithParamInterface<std::tuple<std::string, std::vector<std::string>, std::string>>
{
};
struct LaunchStorageCheckSuite : public Daemon, public WithParamInterface<std::string>
{
};
struct LaunchWithBridges
: public Daemon,
public WithParamInterface<
std::pair<std::vector<std::tuple<std::string, std::string, std::string>>, std::vector<std::string>>>
{
};
struct LaunchWithNoExtraNetworkCloudInit : public Daemon, public WithParamInterface<std::vector<std::string>>
{
};
struct RefuseBridging : public Daemon, public WithParamInterface<std::tuple<std::string, std::string>>
{
};
struct ListIP : public Daemon,
public WithParamInterface<
std::tuple<mp::VirtualMachine::State, std::vector<std::string>, std::vector<std::string>>>
{
};
struct DaemonLaunchTimeoutValueTestSuite : public Daemon, public WithParamInterface<std::tuple<int, int, int>>
{
};
TEST_P(DaemonCreateLaunchTestSuite, creates_virtual_machines)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, create_virtual_machine);
send_command({GetParam()});
}
TEST_P(DaemonCreateLaunchTestSuite, on_creation_hooks_up_platform_prepare_source_image)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, prepare_source_image(_));
send_command({GetParam()});
}
TEST_P(DaemonCreateLaunchTestSuite, on_creation_hooks_up_platform_prepare_instance_image)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, prepare_instance_image(_, _));
send_command({GetParam()});
}
TEST_P(DaemonCreateLaunchTestSuite, on_creation_handles_instance_image_preparation_failure)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
std::string cause = "motive";
EXPECT_CALL(*mock_factory, prepare_instance_image(_, _)).WillOnce(Throw(std::runtime_error{cause}));
EXPECT_CALL(*mock_factory, remove_resources_for(_));
std::stringstream err_stream;
send_command({GetParam()}, trash_stream, err_stream);
EXPECT_THAT(err_stream.str(), AllOf(HasSubstr("failed"), HasSubstr(cause)));
}
TEST_P(DaemonCreateLaunchTestSuite, generates_name_on_creation_when_client_does_not_provide_one)
{
const std::string expected_name{"pied-piper-valley"};
config_builder.name_generator = std::make_unique<StubNameGenerator>(expected_name);
mp::Daemon daemon{config_builder.build()};
std::stringstream stream;
send_command({GetParam()}, stream);
EXPECT_THAT(stream.str(), HasSubstr(expected_name));
}
MATCHER_P2(YAMLNodeContainsString, key, val, "")
{
if (!arg.IsMap())
{
return false;
}
if (!arg[key])
{
return false;
}
if (!arg[key].IsScalar())
{
return false;
}
return arg[key].Scalar() == val;
}
MATCHER_P2(YAMLNodeContainsStringStartingWith, key, val, "")
{
if (!arg.IsMap())
{
return false;
}
if (!arg[key])
{
return false;
}
if (!arg[key].IsScalar())
{
return false;
}
return arg[key].Scalar().find(val) == 0;
}
MATCHER_P(YAMLNodeContainsSubString, val, "")
{
if (!arg.IsSequence())
{
return false;
}
return arg[0].Scalar().find(val) != std::string::npos;
}
MATCHER_P2(YAMLNodeContainsStringArray, key, values, "")
{
if (!arg.IsMap())
{
return false;
}
if (!arg[key])
{
return false;
}
if (!arg[key].IsSequence())
{
return false;
}
if (arg[key].size() != values.size())
{
return false;
}
for (auto i = 0u; i < values.size(); ++i)
{
if (arg[key][i].template as<std::string>() != values[i])
{
return false;
}
}
return true;
}
MATCHER_P(YAMLNodeContainsMap, key, "")
{
if (!arg.IsMap())
{
return false;
}
if (!arg[key])
{
return false;
}
return arg[key].IsMap();
}
MATCHER_P(YAMLNodeContainsSequence, key, "")
{
if (!arg.IsMap())
{
return false;
}
if (!arg[key])
{
return false;
}
return arg[key].IsSequence();
}
MATCHER_P(YAMLSequenceContainsStringMap, values, "")
{
if (!arg.IsSequence())
{
return false;
}
for (const auto& node : arg)
{
if (node.size() != values.size())
continue;
for (auto it = values.cbegin();; ++it)
{
if (it == values.cend())
return true;
else if (node[it->first].template as<std::string>() != it->second)
break;
}
}
return false;
}
TEST_P(DaemonCreateLaunchTestSuite, default_cloud_init_grows_root_fs)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, prepare_instance_image(_, _))
.WillOnce(Invoke([](const multipass::VMImage&, const mp::VirtualMachineDescription& desc) {
EXPECT_THAT(desc.vendor_data_config, YAMLNodeContainsMap("growpart"));
if (desc.vendor_data_config["growpart"])
{
auto const& growpart_stanza = desc.vendor_data_config["growpart"];
EXPECT_THAT(growpart_stanza, YAMLNodeContainsString("mode", "auto"));
EXPECT_THAT(growpart_stanza, YAMLNodeContainsStringArray("devices", std::vector<std::string>({"/"})));
EXPECT_THAT(growpart_stanza, YAMLNodeContainsString("ignore_growroot_disabled", "false"));
}
}));
send_command({GetParam()});
}
TEST_P(DaemonCreateLaunchTestSuite, adds_ssh_keys_to_cloud_init_config)
{
auto mock_factory = use_a_mock_vm_factory();
std::string expected_key{"thisitnotansshkeyactually"};
config_builder.ssh_key_provider = std::make_unique<mpt::DummyKeyProvider>(expected_key);
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, prepare_instance_image(_, _))
.WillOnce(Invoke([&expected_key](const multipass::VMImage&, const mp::VirtualMachineDescription& desc) {
ASSERT_THAT(desc.vendor_data_config, YAMLNodeContainsSequence("ssh_authorized_keys"));
auto const& ssh_keys_stanza = desc.vendor_data_config["ssh_authorized_keys"];
EXPECT_THAT(ssh_keys_stanza, YAMLNodeContainsSubString(expected_key));
}));
send_command({GetParam()});
}
TEST_P(DaemonCreateLaunchPollinateDataTestSuite, adds_pollinate_user_agent_to_cloud_init_config)
{
const auto [command, alias] = GetParam();
auto mock_factory = use_a_mock_vm_factory();
std::vector<std::pair<std::string, std::string>> const& expected_pollinate_map{
{"path", "/etc/pollinate/add-user-agent"},
{"content", fmt::format("multipass/version/{} # written by Multipass\n"
"multipass/driver/mock-1234 # written by Multipass\n"
"multipass/host/{}-{} # written by Multipass\n"
"multipass/alias/{} # written by Multipass\n",
multipass::version_string, QSysInfo::productType(), QSysInfo::productVersion(),
alias.empty() ? "default" : alias)}};
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, prepare_instance_image(_, _))
.WillOnce(
Invoke([&expected_pollinate_map](const multipass::VMImage&, const mp::VirtualMachineDescription& desc) {
EXPECT_THAT(desc.vendor_data_config, YAMLNodeContainsSequence("write_files"));
if (desc.vendor_data_config["write_files"])
{
auto const& write_stanza = desc.vendor_data_config["write_files"];
EXPECT_THAT(write_stanza, YAMLSequenceContainsStringMap(expected_pollinate_map));
}
}));
send_command({command, alias});
}
TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundPassesExpectedAliases)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr int num_cores = 4;
const mp::MemorySize mem_size{"4G"};
const mp::MemorySize disk_space{"25G"};
const std::string release{"focal"};
const std::string remote{"release"};
const std::string name{"ultimo-blueprint"};
const std::string alias_name{"aliasname"};
const std::string alias_command{"aliascommand"};
const std::string alias_wdir{"map"};
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
auto alias = std::make_optional(std::make_pair(alias_name, mp::AliasDefinition{name, alias_command, alias_wdir}));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, alias));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
send_command({"launch"});
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
auto expected_csv_string =
csv_header + alias_name + "," + name + "," + alias_command + "," + alias_wdir + "," + name + "\n";
EXPECT_EQ(cout_stream.str(), expected_csv_string);
}
TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundMountsWorkspace)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr int num_cores = 4;
const mp::MemorySize mem_size{"4G"};
const mp::MemorySize disk_space{"25G"};
const std::string release{"focal"};
const std::string remote{"release"};
const std::string name{"ultimo-blueprint"};
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(
mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, std::nullopt, name));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
std::stringstream cout_stream;
send_command({"launch"}, cout_stream);
EXPECT_THAT(cout_stream.str(),
AllOf(HasSubstr("Mounted '"), HasSubstr(name + "' into '" + name + ":" + name + "'")));
}
TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundMountsWorkspaceConfined)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr int num_cores = 4;
const mp::MemorySize mem_size{"4G"};
const mp::MemorySize disk_space{"25G"};
const std::string release{"focal"};
const std::string remote{"release"};
const std::string name{"ultimo-blueprint"};
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(
mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, std::nullopt, name));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
mpt::TempDir temp_dir;
mpt::SetEnvScope env_scope1("SNAP_NAME", "multipass");
mpt::SetEnvScope env_scope2("SNAP_REAL_HOME", temp_dir.path().toUtf8());
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
std::stringstream cout_stream;
send_command({"launch"}, cout_stream);
EXPECT_THAT(cout_stream.str(),
AllOf(HasSubstr("Mounted '"), HasSubstr(name + "' into '" + name + ":" + name + "'")));
}
TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundMountsWorkspaceInExistingDir)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr int num_cores = 4;
const mp::MemorySize mem_size{"4G"};
const mp::MemorySize disk_space{"25G"};
const std::string release{"focal"};
const std::string remote{"release"};
const std::string name{"ultimo-blueprint"};
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(
mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, std::nullopt, name));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
mpt::TempDir temp_dir;
auto workspace_path = temp_dir.path() + "/multipass/" + QString::fromStdString(name);
QDir().mkpath(workspace_path);
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::HomeLocation))
.WillOnce(Return(temp_dir.path()));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
std::stringstream cout_stream, cerr_stream;
send_command({"launch"}, cout_stream, cerr_stream);
EXPECT_THAT(cerr_stream.str(), HasSubstr(fmt::format("Folder \"{}\" already exists.", workspace_path)));
EXPECT_THAT(cout_stream.str(),
AllOf(HasSubstr("Mounted '"), HasSubstr(name + "' into '" + name + ":" + name + "'")));
}
TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundDoesNotMountUnwrittableWorkspace)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr int num_cores = 4;
const mp::MemorySize mem_size{"4G"};
const mp::MemorySize disk_space{"25G"};
const std::string release{"focal"};
const std::string remote{"release"};
const std::string name{"ultimo-blueprint"};
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(
mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, std::nullopt, name));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
mpt::TempDir temp_dir;
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::HomeLocation))
.WillOnce(Return(temp_dir.path()));
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, open(_, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, write(_, _)).WillRepeatedly(Return(1234));
EXPECT_CALL(*mock_file_ops, commit(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(true)).WillOnce(Return(true)).WillOnce(Return(false));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
std::stringstream cout_stream, cerr_stream;
send_command({"launch"}, cout_stream, cerr_stream);
EXPECT_THAT(cerr_stream.str(), HasSubstr(fmt::format("Error creating folder {}/multipass/{}. Not mounting.\n",
temp_dir.path(), name)));
EXPECT_THAT(cout_stream.str(), Not(HasSubstr("Mounted")));
}
TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundButCannotMount)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr int num_cores = 4;
const mp::MemorySize mem_size{"4G"};
const mp::MemorySize disk_space{"25G"};
const std::string release{"focal"};
const std::string remote{"release"};
const std::string name{"ultimo-blueprint"};
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(
mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, std::nullopt, name));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
mpt::TempDir temp_dir;
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::HomeLocation))
.WillOnce(Return(temp_dir.path()));
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, open(_, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, write(_, _)).WillRepeatedly(Return(1234));
EXPECT_CALL(*mock_file_ops, commit(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(true)).WillOnce(Return(true)).WillOnce(Return(true));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
std::stringstream cout_stream, cerr_stream;
send_command({"launch"}, cout_stream, cerr_stream);
EXPECT_THAT(cerr_stream.str(),
HasSubstr(fmt::format("Source path \"{}/multipass/{}\" does not exist", temp_dir.path(), name)));
EXPECT_THAT(cout_stream.str(), Not(HasSubstr("Mounted")));
}
TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundPassesExpectedAliasesWithNameOverride)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr int num_cores = 4;
const mp::MemorySize mem_size{"4G"};
const mp::MemorySize disk_space{"25G"};
const std::string release{"focal"};
const std::string remote{"release"};
const std::string name{"ultimo-blueprint"};
const std::string command_line_name{"name-override"};
const std::string alias_name{"aliasname"};
const std::string alias_command{"aliascommand"};
const std::string alias_wdir{"map"};
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, command_line_name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
auto alias = std::make_optional(std::make_pair(alias_name, mp::AliasDefinition{name, alias_command, alias_wdir}));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, alias));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(command_line_name));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
send_command({"launch", name, "-n", command_line_name});
std::stringstream cout_stream;
send_command({"aliases", "--format=csv"}, cout_stream);
auto expected_csv_string = csv_header + alias_name + "," + command_line_name + "," + alias_command + "," +
alias_wdir + "," + command_line_name + "\n";
EXPECT_EQ(cout_stream.str(), expected_csv_string);
}
TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundDoesNotOverwriteAliases)
{
typedef std::vector<std::pair<std::string, mp::AliasDefinition>> AliasesVector;
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr int num_cores = 4;
const mp::MemorySize mem_size{"4G"};
const mp::MemorySize disk_space{"25G"};
const std::string release{"focal"};
const std::string remote{"release"};
const std::string name{"ultimo-blueprint"};
const std::string alias_name{"aliasname"};
const std::string alias_command{"aliascommand"};
const std::string alias_wdir{"map"};
// This makes the alias be defined in the default context. Launching an instance will define it in another context.
populate_db_file(AliasesVector{{alias_name, {"original_instance", "a_command", "map"}}});
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
auto alias = std::make_optional(std::make_pair(alias_name, mp::AliasDefinition{name, alias_command, alias_wdir}));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, alias));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
std::stringstream cout_stream;
send_command({"launch", name}, cout_stream);
cout_stream.str("");
send_command({"aliases", "--format=csv"}, cout_stream);
auto expected_csv_string = csv_header + alias_name + ",original_instance,a_command,map,default*\n" + alias_name +
"," + name + "," + alias_command + "," + alias_wdir + "," + name + "\n";
EXPECT_EQ(cout_stream.str(), expected_csv_string);
}
TEST_F(DaemonCreateLaunchAliasTestSuite, blueprintFoundDoesNotOverwriteAliasesIfClashing)
{
typedef std::vector<std::pair<std::string, mp::AliasDefinition>> AliasesVector;
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr int num_cores = 4;
const mp::MemorySize mem_size{"4G"};
const mp::MemorySize disk_space{"25G"};
const std::string release{"focal"};
const std::string remote{"release"};
const std::string alias_name{"aliasname"};
const std::string alias_command{"aliascommand"};
const std::string alias_wdir{"map"};
// The easiest way of creating a clash is to name the instance like the default alias context.
const std::string name{"default"};
populate_db_file(AliasesVector{{alias_name, {"original_instance", "a_command", "map"}}});
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
auto alias = std::make_optional(std::make_pair(alias_name, mp::AliasDefinition{name, alias_command, alias_wdir}));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote, alias));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
std::stringstream cout_stream, cerr_stream;
send_command({"launch", name}, cout_stream, cerr_stream);
EXPECT_THAT(cerr_stream.str(), HasSubstr("Warning: unable to create alias " + alias_name));
cout_stream.str("");
send_command({"aliases", "--format=csv"}, cout_stream);
auto expected_csv_string = csv_header + alias_name + ",original_instance,a_command,map,default*\n";
EXPECT_EQ(cout_stream.str(), expected_csv_string);
}
TEST_P(DaemonCreateLaunchTestSuite, blueprint_found_passes_expected_data)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr int num_cores = 4;
const mp::MemorySize mem_size{"4G"};
const mp::MemorySize disk_space{"25G"};
const std::string release{"focal"};
const std::string remote{"release"};
const std::string name{"ultimo-blueprint"};
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, name));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, remote));
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _))
.WillOnce(mpt::fetch_blueprint_for_lambda(num_cores, mem_size, disk_space, release, remote));
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
send_command({GetParam()});
}
TEST_P(DaemonCreateLaunchTestSuite, blueprint_not_found_passes_expected_data)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
static constexpr int num_cores = 1;
const mp::MemorySize mem_size{"1G"};
const mp::MemorySize disk_space{"5G"};
const std::string empty{};
const std::string release{"default"};
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(mpt::create_virtual_machine_lambda(num_cores, mem_size, disk_space, empty));
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).WillOnce(mpt::fetch_image_lambda(release, empty));
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
send_command({GetParam()});
}
TEST_P(LaunchWithNoExtraNetworkCloudInit, no_extra_network_cloud_init)
{
mpt::MockVirtualMachineFactory* mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
const auto launch_args = GetParam();
EXPECT_CALL(*mock_factory, prepare_instance_image(_, _))
.WillOnce([](const multipass::VMImage&, const mp::VirtualMachineDescription& desc) {
EXPECT_FALSE(desc.network_data_config["ethernets"]["default"].IsNull());
EXPECT_FALSE(desc.network_data_config["ethernets"]["extra0"].IsDefined());
});
send_command(launch_args);
}
std::vector<std::string> make_args(const std::vector<std::string>& args)
{
std::vector<std::string> all_args{"launch"};
for (const auto& a : args)
all_args.push_back(a);
return all_args;
}
INSTANTIATE_TEST_SUITE_P(Daemon,
LaunchWithNoExtraNetworkCloudInit,
Values(make_args({}),
make_args({"xenial"}),
make_args({"xenial", "--network", "name=eth0,mode=manual"}),
make_args({"groovy"}),
make_args({"groovy", "--network", "name=eth0,mode=manual"}),
make_args({"--network", "name=eth0,mode=manual"}),
make_args({"devel"}),
make_args({"hirsute", "--network", "name=eth0,mode=manual"}),
make_args({"daily:21.04"}),
make_args({"daily:21.04", "--network", "name=eth0,mode=manual"}),
make_args({"appliance:openhab", "--network", "name=eth0,mode=manual"}),
make_args({"appliance:nextcloud"}),
make_args({"snapcraft:core18", "--network", "name=eth0,mode=manual"}),
make_args({"snapcraft:core20"})));
TEST_P(LaunchWithBridges, creates_network_cloud_init_iso)
{
mpt::MockVirtualMachineFactory* mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
const auto test_params = GetParam();
const auto args = test_params.first;
const auto forbidden_names = test_params.second;
EXPECT_CALL(*mock_factory, prepare_instance_image(_, _))
.WillOnce(Invoke([&args, &forbidden_names](const multipass::VMImage&,
const mp::VirtualMachineDescription& desc) {
EXPECT_THAT(desc.network_data_config, YAMLNodeContainsMap("ethernets"));
EXPECT_THAT(desc.network_data_config["ethernets"], YAMLNodeContainsMap("default"));
auto const& default_network_stanza = desc.network_data_config["ethernets"]["default"];
EXPECT_THAT(default_network_stanza, YAMLNodeContainsMap("match"));
EXPECT_THAT(default_network_stanza["match"], YAMLNodeContainsStringStartingWith("macaddress", "52:54:00:"));
EXPECT_THAT(default_network_stanza, YAMLNodeContainsString("dhcp4", "true"));
for (const auto& arg : args)
{
std::string name = std::get<1>(arg);
if (!name.empty())
{
EXPECT_THAT(desc.network_data_config["ethernets"], YAMLNodeContainsMap(name));
auto const& extra_stanza = desc.network_data_config["ethernets"][name];
EXPECT_THAT(extra_stanza, YAMLNodeContainsMap("match"));
std::string mac = std::get<2>(arg);
if (mac.size() == 17)
EXPECT_THAT(extra_stanza["match"], YAMLNodeContainsString("macaddress", mac));
else
EXPECT_THAT(extra_stanza["match"], YAMLNodeContainsStringStartingWith("macaddress", mac));
EXPECT_THAT(extra_stanza, YAMLNodeContainsString("dhcp4", "true"));
EXPECT_THAT(extra_stanza, YAMLNodeContainsMap("dhcp4-overrides"));
EXPECT_THAT(extra_stanza["dhcp4-overrides"], YAMLNodeContainsString("route-metric", "200"));
EXPECT_THAT(extra_stanza, YAMLNodeContainsString("optional", "true"));
}
}
for (const auto& forbidden : forbidden_names)
{
EXPECT_THAT(desc.network_data_config["ethernets"], Not(YAMLNodeContainsMap(forbidden)));
}
}));
std::vector<std::string> command(1, "launch");
for (const auto& arg : args)
{
command.push_back("--network");
command.push_back(std::get<0>(arg));
}
send_command(command);
}
typedef typename std::pair<std::vector<std::tuple<std::string, std::string, std::string>>, std::vector<std::string>>
BridgeTestArgType;
INSTANTIATE_TEST_SUITE_P(
Daemon, LaunchWithBridges,
Values(BridgeTestArgType({{"eth0", "extra0", "52:54:00:"}}, {"extra1"}),
BridgeTestArgType({{"name=eth0,mac=01:23:45:ab:cd:ef,mode=auto", "extra0", "01:23:45:ab:cd:ef"},
{"wlan0", "extra1", "52:54:00:"}},
{"extra2"}),
BridgeTestArgType({{"name=eth0,mode=manual", "", ""}, {"name=wlan0", "extra1", "52:54:00:"}},
{"extra0", "extra2"})));
TEST_P(MinSpaceRespectedSuite, accepts_launch_with_enough_explicit_memory)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
const auto param = GetParam();
const auto& cmd = std::get<0>(param);
const auto& opt_name = std::get<1>(param);
const auto& opt_value = std::get<2>(param);
EXPECT_CALL(*mock_factory, create_virtual_machine);
send_command({cmd, opt_name, opt_value});
}
TEST_P(MinSpaceViolatedSuite, refuses_launch_with_memory_below_threshold)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
std::stringstream stream;
const auto param = GetParam();
const auto& cmd = std::get<0>(param);
const auto& opt_name = std::get<1>(param);
const auto& opt_value = std::get<2>(param);
EXPECT_CALL(*mock_factory, create_virtual_machine).Times(0); // expect *no* call
send_command({cmd, opt_name, opt_value}, trash_stream, stream);
EXPECT_THAT(stream.str(), AllOf(HasSubstr("fail"), AnyOf(HasSubstr("memory"), HasSubstr("disk"))));
}
TEST_P(LaunchImgSizeSuite, launches_with_correct_disk_size)
{
auto mock_factory = use_a_mock_vm_factory();
const auto param = GetParam();
const auto& first_command_line_parameter = std::get<0>(param);
const auto& other_command_line_parameters = std::get<1>(param);
const auto& img_size_str = std::get<2>(param);
const auto img_size = mp::MemorySize(img_size_str);
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
ON_CALL(*mock_image_vault.get(), minimum_image_size_for(_)).WillByDefault([&img_size_str](auto...) {
return mp::MemorySize{img_size_str};
});
EXPECT_CALL(mock_utils, filesystem_bytes_available(_)).WillRepeatedly(Return(default_total_bytes));
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
std::vector<std::string> all_parameters{first_command_line_parameter};
for (const auto& p : other_command_line_parameters)
all_parameters.push_back(p);
if (other_command_line_parameters.size() > 0 && mp::MemorySize(other_command_line_parameters[1]) < img_size)
{
std::stringstream stream;
EXPECT_CALL(*mock_factory, create_virtual_machine).Times(0);
send_command(all_parameters, trash_stream, stream);
EXPECT_THAT(stream.str(), AllOf(HasSubstr("Requested disk"), HasSubstr("below minimum for this image")));
}
else
{
EXPECT_CALL(*mock_factory, create_virtual_machine);
send_command(all_parameters);
}
}
TEST_P(LaunchStorageCheckSuite, launch_warns_when_overcommitting_disk)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(mock_utils, filesystem_bytes_available(_)).WillRepeatedly(Return(0));
auto logger_scope = mpt::MockLogger::inject();
logger_scope.mock_logger->screen_logs(mpl::Level::error);
logger_scope.mock_logger->expect_log(mpl::Level::error, "autostart prerequisites", AtMost(1));
logger_scope.mock_logger->expect_log(mpl::Level::warning,
fmt::format("Reserving more disk space ({} bytes) than available (0 bytes)",
mp::MemorySize{mp::default_disk_size}.in_bytes()));
EXPECT_CALL(*mock_factory, create_virtual_machine);
send_command({GetParam()});
}
TEST_P(LaunchStorageCheckSuite, launch_fails_when_space_less_than_image)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
ON_CALL(*mock_image_vault.get(), minimum_image_size_for(_)).WillByDefault([](auto...) {
return mp::MemorySize{"1"};
});
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(mock_utils, filesystem_bytes_available(_)).WillRepeatedly(Return(0));
std::stringstream stream;
EXPECT_CALL(*mock_factory, create_virtual_machine).Times(0);
send_command({GetParam()}, trash_stream, stream);
EXPECT_THAT(stream.str(), HasSubstr("Available disk (0 bytes) below minimum for this image (1 bytes)"));
}
TEST_P(LaunchStorageCheckSuite, launch_fails_with_invalid_data_directory)
{
auto mock_factory = use_a_mock_vm_factory();
config_builder.data_directory = QString("invalid_data_directory");
mp::Daemon daemon{config_builder.build()};
auto [mock_json_utils, guard] = mpt::MockJsonUtils::inject<StrictMock>();
EXPECT_CALL(*mock_json_utils, write_json).Times(1); // avoid creating directory
std::stringstream stream;
EXPECT_CALL(*mock_factory, create_virtual_machine).Times(0);
send_command({GetParam()}, trash_stream, stream);
EXPECT_THAT(stream.str(), HasSubstr("Failed to determine information about the volume containing"));
}
INSTANTIATE_TEST_SUITE_P(Daemon, DaemonCreateLaunchTestSuite, Values("launch", "test_create"));
INSTANTIATE_TEST_SUITE_P(Daemon, DaemonCreateLaunchPollinateDataTestSuite,
Combine(Values("launch", "test_create"), Values("foo", "")));
INSTANTIATE_TEST_SUITE_P(Daemon, MinSpaceRespectedSuite,
Combine(Values("test_create", "launch"), Values("--memory", "--disk"),
Values("1024m", "2Gb", "987654321")));
INSTANTIATE_TEST_SUITE_P(Daemon, MinSpaceViolatedSuite,
Combine(Values("test_create", "launch"), Values("--memory", "--disk"),
Values("0", "0B", "0GB", "123B", "42kb", "100")));
INSTANTIATE_TEST_SUITE_P(Daemon, LaunchImgSizeSuite,
Combine(Values("test_create", "launch"),
Values(std::vector<std::string>{}, std::vector<std::string>{"--disk", "4G"}),
Values("1G", mp::default_disk_size, "10G")));
INSTANTIATE_TEST_SUITE_P(Daemon, LaunchStorageCheckSuite, Values("test_create", "launch"));
TEST_F(DaemonCreateLaunchTestSuite, blueprintFromFileCallsCorrectFunction)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
const std::string name{"ultimo-blueprint"};
EXPECT_CALL(*mock_factory, create_virtual_machine).Times(1);
EXPECT_CALL(*mock_image_vault, fetch_image(_, _, _, _, _, _, _)).Times(1);
EXPECT_CALL(*mock_blueprint_provider, fetch_blueprint_for(_, _, _)).Times(0);
EXPECT_CALL(*mock_blueprint_provider, blueprint_from_file(_, _, _, _)).Times(1);
EXPECT_CALL(*mock_blueprint_provider, name_from_blueprint(_)).WillOnce(Return(name));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
send_command({"launch", "file://blah.yaml"});
}
void check_maps_in_json(const QString& file, const mp::id_mappings& expected_gid_mappings,
const mp::id_mappings& expected_uid_mappings)
{
QByteArray json = mpt::load(file);
QJsonParseError parse_error;
const auto doc = QJsonDocument::fromJson(json, &parse_error);
EXPECT_FALSE(doc.isNull());
EXPECT_TRUE(doc.isObject());
const auto doc_object = doc.object();
const auto instance_object = doc_object["real-zebraphant"].toObject();
const auto mounts = instance_object["mounts"].toArray();
ASSERT_EQ(mounts.size(), 1);
auto mount = mounts.first().toObject(); // There is at most one mount in our JSON.
auto gid_mappings = mount["gid_mappings"].toArray();
ASSERT_EQ((unsigned)gid_mappings.size(), expected_gid_mappings.size());
for (unsigned i = 0; i < expected_gid_mappings.size(); ++i)
{
ASSERT_EQ(gid_mappings[i].toObject()["host_gid"], expected_gid_mappings[i].first);
ASSERT_EQ(gid_mappings[i].toObject()["instance_gid"], expected_gid_mappings[i].second);
}
auto uid_mappings = mount["uid_mappings"].toArray();
ASSERT_EQ((unsigned)uid_mappings.size(), expected_uid_mappings.size());
for (unsigned i = 0; i < expected_uid_mappings.size(); ++i)
{
ASSERT_EQ(uid_mappings[i].toObject()["host_uid"], expected_uid_mappings[i].first);
ASSERT_EQ(uid_mappings[i].toObject()["instance_uid"], expected_uid_mappings[i].second);
}
}
TEST_F(Daemon, reads_mac_addresses_from_json)
{
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
std::string mac_addr("52:54:00:73:76:28");
std::vector<mp::NetworkInterface> extra_interfaces{
mp::NetworkInterface{"wlx60e3270f55fe", "52:54:00:bd:19:41", true},
mp::NetworkInterface{"enp3s0", "01:23:45:67:89:ab", false}};
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
EXPECT_CALL(*use_a_mock_vm_factory(), create_virtual_machine).WillRepeatedly(WithArg<0>([](const auto& desc) {
return std::make_unique<mpt::StubVirtualMachine>(desc.vm_name);
}));
// Make the daemon look for the JSON on our temporary directory. It will read the contents of the file.
config_builder.data_directory = temp_dir->path();
mp::Daemon daemon{config_builder.build()};
// Check that the instance was indeed read and there were no errors.
{
StrictMock<mpt::MockServerReaderWriter<mp::ListReply, mp::ListRequest>> mock_server;
mp::ListReply list_reply;
auto instance_matcher = UnorderedElementsAre(Property(&mp::ListVMInstance::name, "real-zebraphant"));
EXPECT_CALL(mock_server, Write(_, _)).WillOnce(DoAll(SaveArg<0>(&list_reply), Return(true)));
EXPECT_TRUE(call_daemon_slot(daemon, &mp::Daemon::list, mp::ListRequest{}, mock_server).ok());
EXPECT_THAT(list_reply.instance_list().instances(), instance_matcher);
}
// Removing the JSON is possible now because data was already read. This step is not necessary, but doing it we
// make sure that the file was indeed rewritten after the next step.
QFile::remove(filename);
daemon.persist_instances();
// Finally, check the contents of the file. If they match with what we read, we are done.
check_interfaces_in_json(filename, mac_addr, extra_interfaces);
}
TEST_F(Daemon, writesAndReadsMountsInJson)
{
ON_CALL(mock_utils, make_dir(_, _, _))
.WillByDefault([this](const QDir& a_dir, const QString& name, QFileDevice::Permissions permissions) {
return mock_utils.Utils::make_dir(a_dir, name, permissions);
});
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
std::string mac_addr("52:54:00:23:11:97");
std::vector<mp::NetworkInterface> extra_interfaces{};
// Create a temp folder containing three subfolders, and create mount points for all of them.
auto temp_mount_dir = QDir(mpt::TempDir().path());
auto temp_mount_1 = MP_UTILS.make_dir(temp_mount_dir, QString("a"), QFileDevice::Permissions{}).toStdString();
auto temp_mount_2 = MP_UTILS.make_dir(temp_mount_dir, QString("b"), QFileDevice::Permissions{}).toStdString();
auto temp_mount_3 = MP_UTILS.make_dir(temp_mount_dir, QString("c"), QFileDevice::Permissions{}).toStdString();
mp::id_mappings uid_mappings_1{{123, 321}};
mp::id_mappings gid_mappings_1{{456, 654}};
mp::id_mappings uid_mappings_2{{234, 432}};
mp::id_mappings gid_mappings_2{{567, 765}};
mp::id_mappings uid_mappings_3{{345, 543}};
mp::id_mappings gid_mappings_3{{678, 876}};
std::unordered_map<std::string, mp::VMMount> mounts;
mounts.emplace("target_1",
mp::VMMount{temp_mount_1, uid_mappings_1, gid_mappings_1, mp::VMMount::MountType::Classic});
mounts.emplace("target_2",
mp::VMMount{temp_mount_2, uid_mappings_2, gid_mappings_2, mp::VMMount::MountType::Classic});
mounts.emplace("target_3",
mp::VMMount{temp_mount_3, uid_mappings_3, gid_mappings_3, mp::VMMount::MountType::Classic});
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces, mounts));
EXPECT_CALL(*use_a_mock_vm_factory(), create_virtual_machine).WillRepeatedly(WithArg<0>([](const auto& desc) {
return std::make_unique<mpt::StubVirtualMachine>(desc.vm_name);
}));
// Make the daemon look for the JSON on our temporary directory. It will read the contents of the file.
config_builder.data_directory = temp_dir->path();
mp::Daemon daemon{config_builder.build()};
// Check that the instance was indeed read and there were no errors.
{
StrictMock<mpt::MockServerReaderWriter<mp::ListReply, mp::ListRequest>> mock_server;
mp::ListReply list_reply;
auto instance_matcher = UnorderedElementsAre(Property(&mp::ListVMInstance::name, "real-zebraphant"));
EXPECT_CALL(mock_server, Write(_, _)).WillOnce(DoAll(SaveArg<0>(&list_reply), Return(true)));
EXPECT_TRUE(call_daemon_slot(daemon, &mp::Daemon::list, mp::ListRequest{}, mock_server).ok());
EXPECT_THAT(list_reply.instance_list().instances(), instance_matcher);
}
QFile::remove(filename); // Remove the JSON.
daemon.persist_instances(); // Write it again to disk.
check_mounts_in_json(filename, mounts);
}
TEST_F(Daemon, writes_and_reads_ordered_maps_in_json)
{
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mp::id_mappings uid_mappings{{1002, 0}, {1001, 1}};
mp::id_mappings gid_mappings{{1002, 0}, {1000, 2}};
std::unordered_map<std::string, mp::VMMount> mounts;
mpt::TempDir dir;
mounts.emplace("Home",
mp::VMMount{dir.path().toStdString(), uid_mappings, gid_mappings, mp::VMMount::MountType::Classic});
const auto [temp_dir, filename] =
plant_instance_json(fake_json_contents("52:54:00:73:76:29", std::vector<mp::NetworkInterface>{}, mounts));
EXPECT_CALL(*use_a_mock_vm_factory(), create_virtual_machine).WillRepeatedly(WithArg<0>([](const auto& desc) {
return std::make_unique<mpt::StubVirtualMachine>(desc.vm_name);
}));
config_builder.data_directory = temp_dir->path();
mp::Daemon daemon{config_builder.build()};
std::stringstream stream;
send_command({"list"}, stream);
EXPECT_THAT(stream.str(), HasSubstr("real-zebraphant"));
QFile::remove(filename);
send_command({"purge"});
check_maps_in_json(filename, uid_mappings, gid_mappings);
}
TEST_F(Daemon, launches_with_valid_network_interface)
{
mpt::MockVirtualMachineFactory* mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, networks());
ASSERT_NO_THROW(send_command({"launch", "--network", "eth0"}));
}
TEST_F(Daemon, refuses_launch_with_invalid_network_interface)
{
mpt::MockVirtualMachineFactory* mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, networks());
std::stringstream err_stream;
send_command({"launch", "--network", "eth2"}, trash_stream, err_stream);
EXPECT_THAT(err_stream.str(), HasSubstr("Invalid network options supplied"));
}
TEST_F(Daemon, refuses_launch_because_bridging_is_not_implemented)
{
// Use the stub factory, which throws when networks() is called.
mp::Daemon daemon{config_builder.build()};
std::stringstream err_stream;
send_command({"launch", "--network", "eth0"}, trash_stream, err_stream);
EXPECT_THAT(err_stream.str(), HasSubstr("The networks feature is not implemented on this backend"));
}
TEST_P(RefuseBridging, old_image)
{
const auto [remote, image] = GetParam();
std::string full_image_name = remote.empty() ? image : remote + ":" + image;
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, networks());
std::stringstream err_stream;
send_command({"launch", full_image_name, "--network", "eth0"}, trash_stream, err_stream);
EXPECT_THAT(err_stream.str(), HasSubstr("Automatic network configuration not available for"));
}
std::vector<std::string> old_releases{"10.04", "lucid", "11.10", "oneiric", "12.04", "precise", "12.10",
"quantal", "13.04", "raring", "13.10", "saucy", "14.04", "trusty",
"14.10", "utopic", "15.04", "vivid", "15.10", "wily", "16.04",
"xenial", "16.10", "yakkety", "17.04", "zesty"};
std::vector<std::string> old_remoteless_rels{"core", "core16"};
INSTANTIATE_TEST_SUITE_P(DaemonRefuseRelease, RefuseBridging,
Combine(Values("release", "daily", ""), ValuesIn(old_releases)));
INSTANTIATE_TEST_SUITE_P(DaemonRefuseRemoteless, RefuseBridging, Combine(Values(""), ValuesIn(old_remoteless_rels)));
TEST_F(Daemon, fails_with_image_not_found_also_if_image_is_also_non_bridgeable)
{
auto mock_image_host = std::make_unique<NiceMock<mpt::MockImageHost>>();
auto mock_image_host_ptr = mock_image_host.get();
std::vector<mp::VMImageHost*> hosts;
hosts.push_back(mock_image_host_ptr);
mp::URLDownloader downloader(std::chrono::milliseconds(1));
mp::DefaultVMImageVault default_vault(hosts, &downloader, mp::Path("/"), mp::Path("/"), mp::days(1));
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_image_vault_ptr = mock_image_vault.get();
EXPECT_CALL(*mock_image_vault_ptr, all_info_for(_)).WillOnce([&default_vault](const mp::Query& query) {
return default_vault.all_info_for(query);
});
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
EXPECT_CALL(*mock_blueprint_provider, info_for(_)).WillOnce(Return(std::nullopt));
config_builder.vault = std::move(mock_image_vault);
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
mp::Daemon daemon{config_builder.build()};
std::stringstream err_stream;
send_command({"launch", "release:xenial", "--network", "eth0"}, trash_stream, err_stream);
EXPECT_THAT(err_stream.str(), HasSubstr("Unable to find an image matching \"xenial\""));
}
constexpr auto ghost_template = R"(
"{}": {{
"deleted": false,
"disk_space": "0",
"mac_addr": "",
"mem_size": "0",
"metadata": {{}},
"mounts": [],
"num_cores": 0,
"ssh_username": "",
"state": 0
}})";
constexpr auto valid_template = R"(
"{}": {{
"deleted": false,
"disk_space": "3232323232",
"mac_addr": "ab:cd:ef:12:34:{}",
"mem_size": "2323232323",
"metadata": {{}},
"mounts": [],
"num_cores": 4,
"ssh_username": "ubuntu",
"state": 1
}})";
constexpr auto deleted_template = R"(
"{}": {{
"deleted": true,
"disk_space": "3232323232",
"mac_addr": "ab:cd:ef:12:34:{}",
"mem_size": "2323232323",
"metadata": {{}},
"mounts": [],
"num_cores": 4,
"ssh_username": "ubuntu",
"state": 1
}})";
TEST_F(Daemon, skips_over_instance_ghosts_in_db) // which will have been sometimes written for purged instances
{
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
const auto id1 = "valid1";
const auto id2 = "valid2";
auto ghost1 = fmt::format(ghost_template, "ghost1");
auto ghost2 = fmt::format(ghost_template, "ghost2");
auto valid1 = fmt::format(valid_template, id1, "56");
auto valid2 = fmt::format(valid_template, id2, "78");
const auto [temp_dir, filename] = plant_instance_json(fmt::format(
"{{\n{},\n{},\n{},\n{}\n}}", std::move(ghost1), std::move(ghost2), std::move(valid1), std::move(valid2)));
config_builder.data_directory = temp_dir->path();
auto mock_factory = use_a_mock_vm_factory();
EXPECT_CALL(*mock_factory, create_virtual_machine).Times(0);
EXPECT_CALL(*mock_factory, create_virtual_machine(Field(&mp::VirtualMachineDescription::vm_name, id1), _, _))
.Times(1);
EXPECT_CALL(*mock_factory, create_virtual_machine(Field(&mp::VirtualMachineDescription::vm_name, id2), _, _))
.Times(1);
mp::Daemon daemon{config_builder.build()};
}
TEST_F(Daemon, ctor_lets_exceptions_arising_from_vm_creation_through)
{
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents("ab:ab:ab:ab:ab:ab", {}));
config_builder.data_directory = temp_dir->path();
const std::string msg = "asdf";
auto mock_factory = use_a_mock_vm_factory();
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Throw(std::runtime_error{msg}));
MP_EXPECT_THROW_THAT(mp::Daemon{config_builder.build()}, std::runtime_error, mpt::match_what(msg));
}
TEST_F(Daemon, ctor_drops_removed_instances)
{
const std::string stayed{"foo"}, gone{"fighters"};
auto stayed_json = fmt::format(valid_template, stayed, "12");
auto gone_json = fmt::format(valid_template, gone, "34");
const auto [temp_dir, filename] =
plant_instance_json(fmt::format("{{\n{},\n{}\n}}", std::move(stayed_json), std::move(gone_json)));
config_builder.data_directory = temp_dir->path();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
EXPECT_CALL(*mock_image_vault, fetch_image(_, Field(&mp::Query::name, stayed), _, _, _, _, _))
.WillRepeatedly(DoDefault()); // returns an image that can be verified to exist for this instance
EXPECT_CALL(*mock_image_vault, fetch_image(_, Field(&mp::Query::name, gone), _, _, _, _, _))
.WillOnce(Return(mp::VMImage{"/path/to/nowhere", "", "", "", "", {}})); // an image that can't be verified to
// exist for this instance
config_builder.vault = std::move(mock_image_vault);
auto mock_factory = use_a_mock_vm_factory();
EXPECT_CALL(*mock_factory, create_virtual_machine(Field(&mp::VirtualMachineDescription::vm_name, stayed), _, _))
.Times(1)
.WillRepeatedly(
WithArg<0>([](const auto& desc) { return std::make_unique<mpt::StubVirtualMachine>(desc.vm_name); }));
EXPECT_CALL(*mock_factory, create_virtual_machine(Field(&mp::VirtualMachineDescription::vm_name, gone), _, _))
.Times(0);
mp::Daemon daemon{config_builder.build()};
StrictMock<mpt::MockServerReaderWriter<mp::ListReply, mp::ListRequest>> mock_server;
mp::ListReply list_reply;
auto stayed_matcher = UnorderedElementsAre(Property(&mp::ListVMInstance::name, stayed));
EXPECT_CALL(mock_server, Write(_, _)).WillOnce(DoAll(SaveArg<0>(&list_reply), Return(true)));
EXPECT_TRUE(call_daemon_slot(daemon, &mp::Daemon::list, mp::ListRequest{}, mock_server).ok());
EXPECT_THAT(list_reply.instance_list().instances(), stayed_matcher);
auto updated_json = mpt::load(filename);
EXPECT_THAT(updated_json.toStdString(), AllOf(HasSubstr(stayed), Not(HasSubstr(gone))));
}
TEST_P(ListIP, lists_with_ip)
{
auto mock_factory = use_a_mock_vm_factory();
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mp::Daemon daemon{config_builder.build()};
auto instance_ptr = std::make_unique<NiceMock<mpt::MockVirtualMachine>>("mock");
EXPECT_CALL(*mock_factory, create_virtual_machine).WillRepeatedly([&instance_ptr](auto&&...) {
return std::move(instance_ptr);
});
auto [state, cmd, strs] = GetParam();
EXPECT_CALL(*instance_ptr, current_state()).WillRepeatedly(Return(state));
EXPECT_CALL(*instance_ptr, ensure_vm_is_running()).WillRepeatedly(Throw(std::runtime_error("Not running")));
MP_DELEGATE_MOCK_CALLS_ON_BASE(mock_utils, is_running, mp::Utils);
send_command({"launch"});
std::stringstream stream;
send_command(cmd, stream);
for (const auto& s : strs)
EXPECT_THAT(stream.str(), HasSubstr(s));
}
INSTANTIATE_TEST_SUITE_P(
Daemon, ListIP,
Values(std::make_tuple(mp::VirtualMachine::State::running, std::vector<std::string>{"list"},
std::vector<std::string>{"Running", "192.168.2.123"}),
std::make_tuple(mp::VirtualMachine::State::running, std::vector<std::string>{"list", "--no-ipv4"},
std::vector<std::string>{"Running", "--"}),
std::make_tuple(mp::VirtualMachine::State::off, std::vector<std::string>{"list"},
std::vector<std::string>{"Stopped", "--"}),
std::make_tuple(mp::VirtualMachine::State::off, std::vector<std::string>{"list", "--no-ipv4"},
std::vector<std::string>{"Stopped", "--"})));
TEST_F(Daemon, prevents_repetition_of_loaded_mac_addresses)
{
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
std::string repeated_mac{"52:54:00:bd:19:41"};
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(repeated_mac, {}));
config_builder.data_directory = temp_dir->path();
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
std::stringstream stream;
EXPECT_CALL(*mock_factory, create_virtual_machine).Times(0); // expect *no* call
send_command({"launch", "--network", fmt::format("name=eth0,mac={}", repeated_mac)}, trash_stream, stream);
EXPECT_THAT(stream.str(), AllOf(HasSubstr("fail"), HasSubstr("Repeated MAC"), HasSubstr(repeated_mac)));
}
TEST_F(Daemon, does_not_hold_on_to_repeated_mac_addresses_when_loading)
{
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
std::string mac_addr("52:54:00:73:76:28");
std::vector<mp::NetworkInterface> extra_interfaces{mp::NetworkInterface{"eth0", mac_addr, true}};
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
config_builder.data_directory = temp_dir->path();
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, create_virtual_machine);
send_command({"launch", "--network", fmt::format("name=eth0,mac={}", mac_addr)});
}
TEST_F(Daemon, does_not_hold_on_to_macs_when_loading_fails)
{
std::string mac1{"52:54:00:73:76:28"}, mac2{"52:54:00:bd:19:41"};
std::vector<mp::NetworkInterface> extra_interfaces{mp::NetworkInterface{"eth0", mac2, true}};
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac1, extra_interfaces));
config_builder.data_directory = temp_dir->path();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
EXPECT_CALL(*mock_image_vault, fetch_image)
.WillOnce(Return(mp::VMImage{"/path/to/nowhere", "", "", "", "", {}})) // cause the Daemon's ctor to fail
// verifying that the img exists
.WillRepeatedly(DoDefault());
config_builder.vault = std::move(mock_image_vault);
auto mock_factory = use_a_mock_vm_factory();
EXPECT_CALL(*mock_factory, create_virtual_machine).Times(2); // no launch in ctor, two launch commands
mp::Daemon daemon{config_builder.build()};
for (const auto* mac : {&mac1, &mac2})
send_command({"launch", "--network", fmt::format("name=eth0,mac={}", *mac)});
}
TEST_F(Daemon, does_not_hold_on_to_macs_when_image_preparation_fails)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
// fail the first prepare call, succeed the second one
InSequence seq;
EXPECT_CALL(*mock_factory, prepare_instance_image).WillOnce(Throw(std::exception{})).WillOnce(DoDefault());
EXPECT_CALL(*mock_factory, create_virtual_machine).Times(1);
auto cmd = std::vector<std::string>{"launch", "--network", "mac=52:54:00:73:76:28,name=wlan0"};
send_command(cmd); // we cause this one to fail
send_command(cmd); // and confirm we can repeat the same mac
}
TEST_F(Daemon, releases_macs_when_launch_fails)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Throw(std::exception{})).WillOnce(DoDefault());
auto cmd = std::vector<std::string>{"launch", "--network", "mac=52:54:00:73:76:28,name=wlan0"};
send_command(cmd); // we cause this one to fail
send_command(cmd); // and confirm we can repeat the same mac
}
TEST_F(Daemon, releases_macs_of_purged_instances_but_keeps_the_rest)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
auto mac1 = "52:54:00:73:76:28", mac2 = "52:54:00:bd:19:41", mac3 = "01:23:45:67:89:ab";
auto mac_matcher = [](const auto& mac) {
return Field(&mp::VirtualMachineDescription::extra_interfaces,
Contains(Field(&mp::NetworkInterface::mac_address, mac)));
};
EXPECT_CALL(*mock_factory, create_virtual_machine(mac_matcher(mac1), _, _)).Times(1);
EXPECT_CALL(*mock_factory, create_virtual_machine(mac_matcher(mac2), _, _)).Times(1);
EXPECT_CALL(*mock_factory, create_virtual_machine(mac_matcher(mac3), _, _)).Times(2); // this one gets reused
send_command({"launch", "--network", fmt::format("name=eth0,mac={}", mac1), "--name", "vm1"});
send_command({"launch", "--network", fmt::format("name=eth0,mac={}", mac2), "--name", "vm2"});
send_command({"launch", "--network", fmt::format("name=eth0,mac={}", mac3), "--name", "vm3"});
send_command({"delete", "vm1"});
send_command({"delete", "--purge", "vm3"}); // so that mac3 can be reused
send_command({"launch", "--network", fmt::format("name=eth0,mac={}", mac1)}); // repeated mac is rejected
send_command({"launch", "--network", fmt::format("name=eth0,mac={}", mac2)}); // idem
send_command(
{"launch", "--network", fmt::format("name=eth0,mac={}", mac3)}); // mac is free after purge, so accepted
}
TEST_P(DaemonLaunchTimeoutValueTestSuite, uses_correct_launch_timeout)
{
auto mock_factory = use_a_mock_vm_factory();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
auto instance_ptr = std::make_unique<NiceMock<mpt::MockVirtualMachine>>("mock");
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce([&instance_ptr](auto&&...) {
return std::move(instance_ptr);
});
// Timeouts are given in seconds
const auto [client_timeout, blueprint_timeout, expected_timeout] = GetParam();
EXPECT_CALL(*mock_blueprint_provider, blueprint_timeout(_)).WillOnce(Return(blueprint_timeout));
EXPECT_CALL(*instance_ptr,
wait_until_ssh_up(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(expected_timeout))))
.WillRepeatedly(Return());
EXPECT_CALL(*instance_ptr,
wait_for_cloud_init(
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(expected_timeout))))
.WillRepeatedly(Return());
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
mp::Daemon daemon{config_builder.build()};
std::vector<std::string> command{"launch"};
if (client_timeout > 0)
{
command.push_back("--timeout");
command.push_back(std::to_string(client_timeout));
}
send_command(command);
}
INSTANTIATE_TEST_SUITE_P(Daemon, DaemonLaunchTimeoutValueTestSuite,
Values(std::make_tuple(0, 600, 600), // client_timeout, blueprint_timeout, expected_timeout
std::make_tuple(1000, 600, 1000), std::make_tuple(1000, 0, 1000),
std::make_tuple(0, 0, 300)));
TEST_F(Daemon, launches_with_bridged)
{
mpt::MockVirtualMachineFactory* mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, networks());
EXPECT_CALL(mock_settings, get(Eq(mp::bridged_interface_key))).WillRepeatedly(Return("eth0"));
ASSERT_NO_THROW(send_command({"launch", "--network", "bridged"}));
}
TEST_F(Daemon, refuses_launch_bridged_without_setting)
{
mpt::MockVirtualMachineFactory* mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(mock_settings, get(Eq(mp::bridged_interface_key))).WillOnce(Return(""));
EXPECT_CALL(*mock_factory, networks()).Times(0);
std::stringstream err_stream;
send_command({"launch", "--network", "bridged"}, trash_stream, err_stream);
EXPECT_THAT(err_stream.str(),
HasSubstr("You have to `multipass set local.bridged-network=<name>` to use the \"bridged\" shortcut."));
}
TEST_F(Daemon, refuses_launch_with_invalid_bridged_interface)
{
mpt::MockVirtualMachineFactory* mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, networks());
EXPECT_CALL(mock_settings, get(Eq(mp::bridged_interface_key))).WillRepeatedly(Return("invalid"));
std::stringstream err_stream;
send_command({"launch", "--network", "bridged"}, trash_stream, err_stream);
EXPECT_THAT(err_stream.str(),
HasSubstr("Invalid network 'invalid' set as bridged interface, use `multipass set "
"local.bridged-network=<name>` to correct. See `multipass networks` for valid names."));
}
TEST_F(Daemon, keysReturnsSettingsKeys)
{
mp::Daemon daemon{config_builder.build()};
const auto keys = std::set{"some", "config.keys", "of.various.kinds"};
EXPECT_CALL(mock_settings, keys).WillOnce(Return(std::set<QString>{keys.begin(), keys.end()}));
StrictMock<mpt::MockServerReaderWriter<mp::KeysReply, mp::KeysRequest>> mock_server;
EXPECT_CALL(mock_server, Write(Property(&mp::KeysReply::settings_keys, UnorderedElementsAreArray(keys)), _))
.WillOnce(Return(true));
auto status = call_daemon_slot(daemon, &mp::Daemon::keys, mp::KeysRequest{}, mock_server);
EXPECT_TRUE(status.ok());
}
TEST_F(Daemon, keysReportsException)
{
mp::Daemon daemon{config_builder.build()};
const auto e = std::runtime_error{"some error"};
EXPECT_CALL(mock_settings, keys).WillOnce(Throw(e));
auto status = call_daemon_slot(daemon, &mp::Daemon::keys, mp::KeysRequest{},
StrictMock<mpt::MockServerReaderWriter<mp::KeysReply, mp::KeysRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INTERNAL);
EXPECT_THAT(status.error_message(), HasSubstr(e.what()));
}
TEST_F(Daemon, getReturnsSetting)
{
mp::Daemon daemon{config_builder.build()};
const auto key = "foo";
const auto val = "bar";
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Return(val));
StrictMock<mpt::MockServerReaderWriter<mp::GetReply, mp::GetRequest>> mock_server;
EXPECT_CALL(mock_server, Write(Property(&mp::GetReply::value, Eq(val)), _)).WillOnce(Return(true));
mp::GetRequest request;
request.set_key(key);
auto status = call_daemon_slot(daemon, &mp::Daemon::get, request, mock_server);
EXPECT_TRUE(status.ok());
}
TEST_F(Daemon, getHandlesEmptyKey)
{
mp::Daemon daemon{config_builder.build()};
const auto key = "";
mp::GetRequest request;
request.set_key(key);
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Throw(mp::UnrecognizedSettingException{key}));
auto status = call_daemon_slot(daemon, &mp::Daemon::get, request,
StrictMock<mpt::MockServerReaderWriter<mp::GetReply, mp::GetRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), AllOf(HasSubstr("Unrecognized"), HasSubstr("''")));
}
TEST_F(Daemon, getHandlesInvalidKey)
{
mp::Daemon daemon{config_builder.build()};
const auto key = "bad";
mp::GetRequest request;
request.set_key(key);
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Throw(mp::UnrecognizedSettingException{key}));
auto status = call_daemon_slot(daemon, &mp::Daemon::get, request,
StrictMock<mpt::MockServerReaderWriter<mp::GetReply, mp::GetRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), AllOf(HasSubstr("Unrecognized"), HasSubstr(request.key())));
}
TEST_F(Daemon, getReportsException)
{
mp::Daemon daemon{config_builder.build()};
const auto key = "foo";
mp::GetRequest request;
request.set_key(key);
EXPECT_CALL(mock_settings, get(Eq(key))).WillOnce(Throw(std::runtime_error{"exception"}));
auto status = call_daemon_slot(daemon, &mp::Daemon::get, request,
StrictMock<mpt::MockServerReaderWriter<mp::GetReply, mp::GetRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INTERNAL);
EXPECT_THAT(status.error_message(), HasSubstr("exception"));
}
TEST_F(Daemon, setSetsSetting)
{
mp::Daemon daemon{config_builder.build()};
const auto key = "foo";
const auto val = "bar";
mp::SetRequest request;
request.set_key(key);
request.set_val(val);
EXPECT_CALL(mock_settings, set(Eq(key), Eq(val))).Times(1);
auto mock_server = StrictMock<mpt::MockServerReaderWriter<mp::SetReply, mp::SetRequest>>{};
EXPECT_TRUE(call_daemon_slot(daemon, &mp::Daemon::set, request, mock_server).ok());
}
using SetException = std::variant<mp::UnrecognizedSettingException, mp::InvalidSettingException, std::runtime_error>; /*
We need to throw an exception of the ultimate type whose handling we're trying to test (to avoid slicing and enter the
right catch block). Therefore, we can't just use a base exception type. Parameterized and typed tests don't mix in
gtest, so we use a variant parameter. */
using SetExceptCodeAndMsgMatcher = std::tuple<SetException, grpc::StatusCode, Matcher<std::string>>;
class DaemonSetExceptions : public Daemon, public WithParamInterface<SetExceptCodeAndMsgMatcher>
{
};
TEST_P(DaemonSetExceptions, setHandlesSettingsException)
{
mp::Daemon daemon{config_builder.build()};
const auto& [exception, expected_code, msg_matcher] = GetParam();
auto thrower = [](const auto& e) { throw e; };
EXPECT_CALL(mock_settings, set).WillOnce(WithoutArgs([&thrower, e = &exception] { std::visit(thrower, *e); })); /*
lambda capture with initializer works around forbidden capture of structured binding */
auto status = call_daemon_slot(daemon, &mp::Daemon::set, mp::SetRequest{},
StrictMock<mpt::MockServerReaderWriter<mp::SetReply, mp::SetRequest>>{});
EXPECT_EQ(status.error_code(), expected_code);
EXPECT_THAT(status.error_message(), msg_matcher);
}
INSTANTIATE_TEST_SUITE_P(
Daemon,
DaemonSetExceptions,
Values(std::tuple{mp::NonAuthorizedBridgeSettingsException{"reason", "instance", "eth8"},
grpc::StatusCode::INTERNAL,
HasSubstr("Need user authorization to bridge eth8")},
std::tuple{mp::BridgeFailureException{"reason", "instance", "eth8"},
grpc::StatusCode::INTERNAL,
HasSubstr("Failure to bridge eth8")},
std::tuple{mp::UnrecognizedSettingException{"foo"},
grpc::StatusCode::INVALID_ARGUMENT,
AllOf(HasSubstr("Unrecognized"), HasSubstr("foo"))},
std::tuple{mp::InvalidSettingException{"foo", "bar", "err"},
grpc::StatusCode::INVALID_ARGUMENT,
AllOf(HasSubstr("Invalid"), HasSubstr("foo"), HasSubstr("bar"), HasSubstr("err"))},
std::tuple{std::runtime_error{"Other"}, grpc::StatusCode::INTERNAL, HasSubstr("Other")}));
TEST_F(Daemon, setWorksIfUserAuthorizes)
{
const std::string key{"local.instance.bridged"}, value{"true"};
mp::Daemon daemon{config_builder.build()};
auto logger_scope = mpt::MockLogger::inject();
logger_scope.mock_logger->screen_logs(mpl::Level::debug);
logger_scope.mock_logger->expect_log(mpl::Level::debug,
fmt::format("Asking for user authorization to set {}={}", key, value));
logger_scope.mock_logger->expect_log(mpl::Level::debug, fmt::format("Succeeded setting {}={}", key, value));
mp::SetRequest request;
request.set_key(key);
request.set_val(value);
const auto& exception = mp::NonAuthorizedBridgeSettingsException{"reason", "instance", "eth8"};
EXPECT_CALL(mock_settings, set).WillOnce(Throw(exception)).WillOnce(Return());
auto mock_server = StrictMock<mpt::MockServerReaderWriter<mp::SetReply, mp::SetRequest>>{};
EXPECT_CALL(mock_server, Write(_, _)).WillOnce([](mp::SetReply reply, auto) {
EXPECT_TRUE(reply.needs_authorization());
return true;
});
EXPECT_CALL(mock_server, Read(_)).WillOnce([](mp::SetRequest* request) {
request->set_authorized(true);
return true;
});
EXPECT_TRUE(call_daemon_slot(daemon, &mp::Daemon::set, request, mock_server).ok());
}
TEST_F(Daemon, set_works_if_bridged_interface_is_empty)
{
const auto key = "local.instance.cpus";
const auto value = "8";
mp::Daemon daemon{config_builder.build()};
auto logger_scope = mpt::MockLogger::inject();
logger_scope.mock_logger->screen_logs(mpl::Level::debug);
logger_scope.mock_logger->expect_log(mpl::Level::debug, fmt::format("Succeeded setting {}={}", key, value));
mp::SetRequest request;
request.set_key(key);
request.set_val(value);
request.set_authorized(true);
EXPECT_CALL(mock_settings, get(Eq(mp::bridged_interface_key))).WillOnce(Return(""));
EXPECT_CALL(mock_settings, set(Eq(key), Eq(value))).Times(1);
auto mock_server = StrictMock<mpt::MockServerReaderWriter<mp::SetReply, mp::SetRequest>>{};
EXPECT_TRUE(call_daemon_slot(daemon, &mp::Daemon::set, request, mock_server).ok());
}
TEST_F(Daemon, setDoesNotSetIfUserDeniesAuthorization)
{
const std::string key{"local.instance.bridged"}, value{"true"};
mp::Daemon daemon{config_builder.build()};
auto logger_scope = mpt::MockLogger::inject();
logger_scope.mock_logger->screen_logs(mpl::Level::debug);
logger_scope.mock_logger->expect_log(mpl::Level::debug,
fmt::format("Asking for user authorization to set {}={}", key, value));
logger_scope.mock_logger->expect_log(mpl::Level::debug, "User did not authorize, cancelling");
mp::SetRequest request;
request.set_key(key);
request.set_val(value);
const auto& exception = mp::NonAuthorizedBridgeSettingsException{"reason", "instance", "eth8"};
EXPECT_CALL(mock_settings, set).WillOnce(Throw(exception));
auto mock_server = StrictMock<mpt::MockServerReaderWriter<mp::SetReply, mp::SetRequest>>{};
EXPECT_CALL(mock_server, Write(_, _)).WillOnce([](mp::SetReply reply, auto) {
EXPECT_TRUE(reply.needs_authorization());
return true;
});
EXPECT_CALL(mock_server, Read(_)).WillOnce([](mp::SetRequest* request) {
request->set_authorized(false);
return true;
});
EXPECT_FALSE(call_daemon_slot(daemon, &mp::Daemon::set, request, mock_server).ok());
}
TEST_F(Daemon, add_bridged_interface_works)
{
std::string instance_name{"willy"};
auto mock_factory = use_a_mock_vm_factory();
mpt::MockDaemon daemon{config_builder.build()};
auto instance_ptr = std::make_shared<NiceMock<mpt::MockVirtualMachine>>(instance_name);
auto logger_scope = mpt::MockLogger::inject();
logger_scope.mock_logger->screen_logs(mpl::Level::debug);
logger_scope.mock_logger->expect_log(mpl::Level::debug, "New interface {\"eth8\", ");
std::vector<mp::NetworkInterfaceInfo> net_info{{"eth8", "Ethernet", "A network adapter", {}, false}};
EXPECT_CALL(*mock_factory, networks).WillOnce(Return(net_info));
EXPECT_CALL(*mock_factory, prepare_networking).Times(1);
EXPECT_CALL(*instance_ptr, add_network_interface(0, _, _)).Times(1);
EXPECT_NO_THROW(daemon.test_add_bridged_interface(instance_name, instance_ptr));
}
TEST_F(Daemon, add_bridged_interface_warns_and_noop_if_already_bridged)
{
std::string instance_name{"foo"};
std::string if_name{"eth8"};
mp::VMSpecs specs{};
specs.extra_interfaces.push_back({if_name, "ab:ab:ab:ab:ab:ab", true});
auto mock_factory = use_a_mock_vm_factory();
mpt::MockDaemon daemon{config_builder.build()};
auto instance_ptr = std::make_shared<NiceMock<mpt::MockVirtualMachine>>(instance_name);
auto logger_scope = mpt::MockLogger::inject();
logger_scope.mock_logger->screen_logs(mpl::Level::warning);
logger_scope.mock_logger->expect_log(mpl::Level::warning, "already bridged");
EXPECT_CALL(*mock_factory, networks).Times(1);
EXPECT_CALL(*mock_factory, prepare_networking).Times(0);
EXPECT_CALL(*instance_ptr, add_network_interface).Times(0);
EXPECT_NO_THROW(daemon.test_add_bridged_interface(instance_name, instance_ptr, specs));
}
TEST_F(Daemon, add_bridged_interface_honors_prepared_bridge)
{
std::string instance_name{"asdf"};
std::string if_name{"eth8"};
std::string br_name{"br-eth8"};
mp::NetworkInterface br_net{br_name, "ab:ab:ab:ab:ab:ab", true};
auto mock_factory = use_a_mock_vm_factory();
mpt::MockDaemon daemon{config_builder.build()};
auto instance_ptr = std::make_shared<NiceMock<mpt::MockVirtualMachine>>(instance_name);
std::vector<mp::NetworkInterfaceInfo> net_info{{if_name, "Ethernet", "A regular adapter", {}, false}};
EXPECT_CALL(*mock_factory, networks).WillOnce(Return(net_info));
EXPECT_CALL(*mock_factory, prepare_networking(Contains(Field(&mp::NetworkInterface::id, StrEq("eth8")))))
.WillOnce(SetArgReferee<0>(std::vector{br_net}));
EXPECT_CALL(*instance_ptr, add_network_interface(0, _, Eq(br_net))).Times(1);
EXPECT_NO_THROW(daemon.test_add_bridged_interface(instance_name, instance_ptr));
}
TEST_F(Daemon, add_bridged_interface_throws_if_backend_throws)
{
std::string instance_name{"wonka"};
auto mock_factory = use_a_mock_vm_factory();
mpt::MockDaemon daemon{config_builder.build()};
auto instance_ptr = std::make_shared<NiceMock<mpt::MockVirtualMachine>>(instance_name);
auto logger_scope = mpt::MockLogger::inject();
logger_scope.mock_logger->screen_logs(mpl::Level::debug);
logger_scope.mock_logger->expect_log(mpl::Level::debug, "New interface {\"eth8\", ");
logger_scope.mock_logger->expect_log(mpl::Level::debug, "Failure adding interface to instance, rolling back");
std::vector<mp::NetworkInterfaceInfo> net_info{{"eth8", "Ethernet", "A network adapter", {}, false}};
EXPECT_CALL(*mock_factory, networks).WillOnce(Return(net_info));
EXPECT_CALL(*mock_factory, prepare_networking).Times(1);
EXPECT_CALL(*instance_ptr, add_network_interface(0, _, _)).WillOnce(Throw(std::runtime_error("something bad")));
std::string msg{"Cannot update instance settings; instance: " + instance_name + "; reason: Failure to bridge eth8"};
MP_EXPECT_THROW_THAT(daemon.test_add_bridged_interface(instance_name, instance_ptr),
std::runtime_error,
mpt::match_what(msg));
}
TEST_F(Daemon, add_bridged_interface_throws_on_bad_bridged_network_setting)
{
std::string instance_name{"bucket"};
auto mock_factory = use_a_mock_vm_factory();
mpt::MockDaemon daemon{config_builder.build()};
auto instance_ptr = std::make_shared<NiceMock<mpt::MockVirtualMachine>>(instance_name);
std::vector<mp::NetworkInterfaceInfo> net_info{{"eth9", "Ethernet", "An invalid network adapter", {}, false}};
EXPECT_CALL(*mock_factory, networks).WillOnce(Return(net_info));
EXPECT_CALL(*mock_factory, prepare_networking).Times(0);
EXPECT_CALL(*instance_ptr, add_network_interface(_, _, _)).Times(0);
std::string msg{"Invalid network 'eth8' set as bridged interface, use `multipass set local.bridged-network=<name>` "
"to correct. See `multipass networks` for valid names."};
MP_EXPECT_THROW_THAT(daemon.test_add_bridged_interface(instance_name, instance_ptr),
std::runtime_error,
mpt::match_what(msg));
}
TEST_F(Daemon, add_bridged_interface_throws_if_needs_authorization)
{
std::string instance_name{"glass-elevator"};
auto mock_factory = use_a_mock_vm_factory();
mpt::MockDaemon daemon{config_builder.build()};
auto instance_ptr = std::make_shared<NiceMock<mpt::MockVirtualMachine>>(instance_name);
std::vector<mp::NetworkInterfaceInfo> net_info{{"eth8", "Ethernet", "A network adapter", {}, true}};
EXPECT_CALL(*mock_factory, networks).WillOnce(Return(net_info));
EXPECT_CALL(*mock_factory, prepare_networking).Times(0);
EXPECT_CALL(*instance_ptr, add_network_interface(_, _, _)).Times(0);
std::string msg{
"Cannot update instance settings; instance: glass-elevator; reason: Need user authorization to bridge eth8"};
MP_EXPECT_THROW_THAT(daemon.test_add_bridged_interface(instance_name, instance_ptr),
mp::NonAuthorizedBridgeSettingsException,
mpt::match_what(msg));
}
struct DaemonIsBridged : public Daemon,
public WithParamInterface<
std::tuple<std::vector<mp::NetworkInterfaceInfo>, std::vector<mp::NetworkInterface>, bool>>
{
};
TEST_P(DaemonIsBridged, is_bridged_works)
{
const auto [host_nets, extra_interfaces, result] = GetParam();
std::string instance_name{"charlie"};
mp::VMSpecs specs{};
specs.extra_interfaces = extra_interfaces;
auto [mock_platform, platform_guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, bridge_nomenclature).WillRepeatedly(Return("generic"));
auto mock_factory = use_a_mock_vm_factory();
EXPECT_CALL(*mock_factory, networks).WillOnce(Return(host_nets));
mpt::MockDaemon daemon{config_builder.build()};
auto instance_ptr = std::make_shared<NiceMock<mpt::MockVirtualMachine>>(instance_name);
EXPECT_EQ(daemon.test_is_bridged(instance_name, specs), result);
}
INSTANTIATE_TEST_SUITE_P(
Daemon,
DaemonIsBridged,
Values(std::make_tuple(std::vector<mp::NetworkInterfaceInfo>{},
std::vector<mp::NetworkInterface>{{"eth8", "52:54:00:09:10:11", true}},
true),
std::make_tuple(std::vector<mp::NetworkInterfaceInfo>{{"somebr", "generic", "some bridge", {"eth8"}, false}},
std::vector<mp::NetworkInterface>{{"somebr", "52:54:00:12:13:14", true}},
true),
std::make_tuple(std::vector<mp::NetworkInterfaceInfo>{},
std::vector<mp::NetworkInterface>{{"eth9", "52:54:00:15:16:17", true}},
false),
std::make_tuple(std::vector<mp::NetworkInterfaceInfo>{{"somebr", "generic", "some bridge", {"eth9"}, false}},
std::vector<mp::NetworkInterface>{{"somebr", "52:54:00:18:19:20", true}},
false)));
TEST_F(Daemon, requests_networks)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
std::vector<mp::NetworkInterfaceInfo> net_infos{{"net_a", "type_a", "description_a"},
{"net_b", "type_b", "description_b"}};
EXPECT_CALL(*mock_factory, networks).WillOnce(Return(net_infos));
StrictMock<mpt::MockServerReaderWriter<mp::NetworksReply, mp::NetworksRequest>> mock_server;
auto are_same_net = [](const mp::NetInterface& proto_net, const mp::NetworkInterfaceInfo& net_info) {
return std::tie(proto_net.name(), proto_net.type(), proto_net.description()) ==
std::tie(net_info.id, net_info.type, net_info.description);
};
auto same_net_matcher = Truly(mpt::with_arg_tuple(are_same_net)); // matches pairs (2-tuples) of equivalent nets
EXPECT_CALL(mock_server,
Write(Property(&mp::NetworksReply::interfaces, UnorderedPointwise(same_net_matcher, net_infos)), _))
.WillOnce(Return(true));
EXPECT_TRUE(call_daemon_slot(daemon, &mp::Daemon::networks, mp::NetworksRequest{}, mock_server).ok());
}
TEST_F(Daemon, performs_health_check_on_networks)
{
auto mock_factory = use_a_mock_vm_factory();
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(*mock_factory, hypervisor_health_check);
call_daemon_slot(daemon, &mp::Daemon::networks, mp::NetworksRequest{},
NiceMock<mpt::MockServerReaderWriter<mp::NetworksReply, mp::NetworksRequest>>{});
}
TEST_F(Daemon, purgePersistsInstances)
{
const std::string name1{"world-of-goo"}, name2{"small-beauty-goo"};
auto instance_json1 = fmt::format(valid_template, name1, "10");
auto instance_json2 = fmt::format(valid_template, name2, "11");
auto json_contents = fmt::format("{{{}, {}}}", instance_json1, instance_json2);
const auto [temp_dir, filename] = plant_instance_json(json_contents);
config_builder.data_directory = temp_dir->path();
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mp::Daemon daemon{config_builder.build()};
QFile::remove(filename);
call_daemon_slot(daemon, &mp::Daemon::purge, mp::PurgeRequest{},
NiceMock<mpt::MockServerReaderWriter<mp::PurgeReply, mp::PurgeRequest>>{});
auto updated_json = mpt::load(filename);
EXPECT_THAT(updated_json.toStdString(), AllOf(HasSubstr(name1), HasSubstr(name2)));
}
TEST_F(Daemon, launch_fails_with_incompatible_blueprint)
{
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
EXPECT_CALL(*mock_blueprint_provider, info_for(_)).WillOnce(Throw(mp::IncompatibleBlueprintException("")));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
mp::Daemon daemon{config_builder.build()};
std::stringstream err_stream;
send_command({"launch", "foo"}, trash_stream, err_stream);
EXPECT_THAT(err_stream.str(), HasSubstr("The \"foo\" Blueprint is not compatible with this host."));
}
TEST_F(Daemon, info_all_returns_all_instances)
{
const std::string good_instance_name{"good-instance"}, deleted_instance_name{"deleted-instance"};
const auto good_instance_json = fmt::format(valid_template, good_instance_name, "10");
const auto deleted_instance_json = fmt::format(deleted_template, deleted_instance_name, "11");
const auto instances_json = fmt::format("{{{}, {}}}", good_instance_json, deleted_instance_json);
const auto [temp_dir, __] = plant_instance_json(instances_json);
config_builder.data_directory = temp_dir->path();
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
EXPECT_CALL(*use_a_mock_vm_factory(), create_virtual_machine).WillRepeatedly(WithArg<0>([](const auto& desc) {
return std::make_unique<mpt::StubVirtualMachine>(desc.vm_name);
}));
const auto names_matcher = UnorderedElementsAre(Property(&mp::DetailedInfoItem::name, good_instance_name),
Property(&mp::DetailedInfoItem::name, deleted_instance_name));
StrictMock<mpt::MockServerReaderWriter<mp::InfoReply, mp::InfoRequest>> mock_server{};
EXPECT_CALL(mock_server, Write(Property(&mp::InfoReply::details, names_matcher), _)).WillOnce(Return(true));
mp::Daemon daemon{config_builder.build()};
call_daemon_slot(daemon, &mp::Daemon::info, mp::InfoRequest{}, mock_server);
}
} // namespace
| 105,519
|
C++
|
.cpp
| 1,971
| 46.7448
| 120
| 0.669589
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,620
|
test_base_virtual_machine_factory.cpp
|
canonical_multipass/tests/test_base_virtual_machine_factory.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_logger.h"
#include "mock_platform.h"
#include "stub_ssh_key_provider.h"
#include "stub_url_downloader.h"
#include "temp_dir.h"
#include <shared/base_virtual_machine_factory.h>
#include <multipass/network_interface_info.h>
#include <multipass/virtual_machine_description.h>
#include <multipass/vm_status_monitor.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct MockBaseFactory : mp::BaseVirtualMachineFactory
{
MockBaseFactory() : MockBaseFactory{std::make_unique<mp::test::TempDir>()}
{
}
MockBaseFactory(std::unique_ptr<mp::test::TempDir>&& tmp_dir)
: mp::BaseVirtualMachineFactory{tmp_dir->path()}, tmp_dir{std::move(tmp_dir)}
{
}
MOCK_METHOD(mp::VirtualMachine::UPtr,
create_virtual_machine,
(const mp::VirtualMachineDescription&, const mp::SSHKeyProvider&, mp::VMStatusMonitor&),
(override));
MOCK_METHOD(mp::VirtualMachine::UPtr,
create_vm_and_clone_instance_dir_data,
(const mp::VMSpecs&,
const mp::VMSpecs&,
const std::string&,
const std::string&,
const mp::VMImage&,
const mp::SSHKeyProvider&,
mp::VMStatusMonitor&),
(override));
MOCK_METHOD(mp::VMImage, prepare_source_image, (const mp::VMImage&), (override));
MOCK_METHOD(void, prepare_instance_image, (const mp::VMImage&, const mp::VirtualMachineDescription&), (override));
MOCK_METHOD(void, hypervisor_health_check, (), (override));
MOCK_METHOD(QString, get_backend_version_string, (), (const, override));
MOCK_METHOD(void, prepare_networking, (std::vector<mp::NetworkInterface>&), (override));
MOCK_METHOD(std::vector<mp::NetworkInterfaceInfo>, networks, (), (const, override));
MOCK_METHOD(std::string, create_bridge_with, (const mp::NetworkInterfaceInfo&), (override));
MOCK_METHOD(void,
prepare_interface,
(mp::NetworkInterface & net, std::vector<mp::NetworkInterfaceInfo>& host_nets),
(override));
MOCK_METHOD(void, remove_resources_for_impl, (const std::string&), (override));
std::string base_create_bridge_with(const mp::NetworkInterfaceInfo& interface)
{
return mp::BaseVirtualMachineFactory::create_bridge_with(interface); // protected
}
void base_prepare_interface(mp::NetworkInterface& net, std::vector<mp::NetworkInterfaceInfo>& host_nets)
{
return mp::BaseVirtualMachineFactory::prepare_interface(net, host_nets); // protected
}
std::unique_ptr<mp::test::TempDir> tmp_dir;
};
struct BaseFactory : public Test
{
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
};
TEST_F(BaseFactory, returns_image_only_fetch_type)
{
MockBaseFactory factory;
EXPECT_EQ(factory.fetch_type(), mp::FetchType::ImageOnly);
}
TEST_F(BaseFactory, dir_name_returns_empty_string)
{
MockBaseFactory factory;
const auto dir_name = factory.get_backend_directory_name();
EXPECT_TRUE(dir_name.isEmpty());
}
TEST_F(BaseFactory, create_image_vault_returns_default_vault)
{
mpt::StubURLDownloader stub_downloader;
mpt::TempDir cache_dir;
mpt::TempDir data_dir;
std::vector<mp::VMImageHost*> hosts;
MockBaseFactory factory;
auto vault = factory.create_image_vault(hosts, &stub_downloader, cache_dir.path(), data_dir.path(), mp::days{0});
EXPECT_TRUE(dynamic_cast<mp::DefaultVMImageVault*>(vault.get()));
}
TEST_F(BaseFactory, networks_throws)
{
StrictMock<MockBaseFactory> factory;
ASSERT_THROW(factory.mp::BaseVirtualMachineFactory::networks(), mp::NotImplementedOnThisBackendException);
}
// Ideally, we'd define some unique YAML for each node and test the contents of the ISO image,
// but we'd need a cross-platform library to read files in an ISO image and that is beyond scope
// at this time. Instead, just make sure an ISO image is created and has the expected path.
TEST_F(BaseFactory, creates_cloud_init_iso_image)
{
MockBaseFactory factory;
const std::string name{"foo"};
const YAML::Node metadata{YAML::Load({fmt::format("name: {}", name)})}, vendor_data{metadata}, user_data{metadata},
network_data{metadata};
mp::VMImage image;
image.image_path = QString("%1/%2").arg(factory.tmp_dir->path()).arg(QString::fromStdString(name));
mp::VirtualMachineDescription vm_desc{2,
mp::MemorySize{"3M"},
mp::MemorySize{}, // not used
name,
"00:16:3e:fe:f2:b9",
{},
"yoda",
image,
"",
metadata,
user_data,
vendor_data,
network_data};
factory.configure(vm_desc);
EXPECT_EQ(vm_desc.cloud_init_iso, QString("%1/cloud-init-config.iso").arg(factory.tmp_dir->path()));
EXPECT_TRUE(QFile::exists(vm_desc.cloud_init_iso));
}
TEST_F(BaseFactory, create_bridge_not_implemented)
{
StrictMock<MockBaseFactory> factory;
MP_EXPECT_THROW_THAT(factory.base_create_bridge_with({}), mp::NotImplementedOnThisBackendException,
mpt::match_what(HasSubstr("bridge creation")));
}
TEST_F(BaseFactory, prepareNetworkingHasNoObviousEffectByDefault)
{
MockBaseFactory factory;
EXPECT_CALL(factory, prepare_networking).WillOnce(Invoke([&factory](auto& nets) {
factory.mp::BaseVirtualMachineFactory::prepare_networking(nets);
}));
std::vector<mp::NetworkInterface> nets{{"asdf", "qwer", true}};
const auto nets_copy = nets;
factory.prepare_networking(nets);
EXPECT_EQ(nets, nets_copy);
}
TEST_F(BaseFactory, prepareInterfaceLeavesUnrecognizedNetworkAlone)
{
StrictMock<MockBaseFactory> factory;
auto host_nets = std::vector<mp::NetworkInterfaceInfo>{{"eth0", "ethernet", "asd"}, {"wlan0", "wifi", "asd"}};
auto extra_net = mp::NetworkInterface{"eth1", "fa:se:ma:c0:12:23", false};
const auto host_copy = host_nets;
const auto extra_copy = extra_net;
factory.base_prepare_interface(extra_net, host_nets);
EXPECT_EQ(host_nets, host_copy);
EXPECT_EQ(extra_net, extra_copy);
}
TEST_F(BaseFactory, prepareInterfaceLeavesExistingBridgeAlone)
{
StrictMock<MockBaseFactory> factory;
constexpr auto bridge_type = "arbitrary";
auto [mock_platform, platform_guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, bridge_nomenclature).WillRepeatedly(Return(bridge_type));
auto host_nets = std::vector<mp::NetworkInterfaceInfo>{{"br0", bridge_type, "foo"}, {"xyz", bridge_type, "bar"}};
auto extra_net = mp::NetworkInterface{"xyz", "fake mac", true};
const auto host_copy = host_nets;
const auto extra_copy = extra_net;
factory.base_prepare_interface(extra_net, host_nets);
EXPECT_EQ(host_nets, host_copy);
EXPECT_EQ(extra_net, extra_copy);
}
TEST_F(BaseFactory, prepareInterfaceReplacesBridgedNetworkWithCorrespondingBridge)
{
StrictMock<MockBaseFactory> factory;
constexpr auto bridge_type = "tunnel";
constexpr auto bridge = "br";
auto [mock_platform, platform_guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, bridge_nomenclature).WillRepeatedly(Return(bridge_type));
auto host_nets = std::vector<mp::NetworkInterfaceInfo>{{"eth", "ethernet", "already bridged"},
{"wlan", "wifi", "something else"},
{bridge, bridge_type, "bridge to eth", {"eth"}},
{"different", bridge_type, "uninteresting", {"wlan"}}};
auto extra_net = mp::NetworkInterface{"eth", "fake mac", false};
const auto host_copy = host_nets;
auto extra_check = extra_net;
extra_check.id = bridge;
factory.base_prepare_interface(extra_net, host_nets);
EXPECT_EQ(host_nets, host_copy);
EXPECT_EQ(extra_net, extra_check);
}
TEST_F(BaseFactory, prepareInterfaceCreatesBridgeForUnbridgedNetwork)
{
StrictMock<MockBaseFactory> factory;
constexpr auto bridge_type = "gagah";
constexpr auto bridge = "newbr";
auto [mock_platform, platform_guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, bridge_nomenclature).WillRepeatedly(Return(bridge_type));
auto host_nets = std::vector<mp::NetworkInterfaceInfo>{{"eth", "ethernet", "already bridged"},
{"wlan", "wifi", "something else"},
{"br0", bridge_type, "bridge to wlan", {"wlan"}}};
const auto host_copy = host_nets;
auto extra_id = "eth";
auto extra_net = mp::NetworkInterface{extra_id, "maccc", true};
auto extra_check = extra_net;
extra_check.id = bridge;
EXPECT_CALL(factory, create_bridge_with(Field(&mp::NetworkInterfaceInfo::id, Eq(extra_net.id))))
.WillOnce(Return(bridge));
factory.base_prepare_interface(extra_net, host_nets);
EXPECT_EQ(extra_net, extra_check);
const auto [host_diff, ignore] =
std::mismatch(host_nets.cbegin(), host_nets.cend(), host_copy.cbegin(), host_copy.cend());
ASSERT_NE(host_diff, host_nets.cend());
EXPECT_EQ(host_diff->id, bridge);
EXPECT_EQ(host_diff->type, bridge_type);
EXPECT_THAT(host_diff->links, ElementsAre(extra_id));
host_nets.erase(host_diff);
EXPECT_EQ(host_nets, host_copy);
}
TEST_F(BaseFactory, prepareNetworkingWithNoExtraNetsHasNoObviousEffect)
{
MockBaseFactory factory;
MP_DELEGATE_MOCK_CALLS_ON_BASE(factory, prepare_networking, mp::BaseVirtualMachineFactory);
std::vector<mp::NetworkInterface> empty;
factory.prepare_networking(empty);
EXPECT_THAT(empty, IsEmpty());
}
TEST_F(BaseFactory, prepareNetworkingPreparesEachRequestedNetwork)
{
constexpr auto bridge_type = "bridge";
auto [mock_platform, platform_guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, bridge_nomenclature).WillRepeatedly(Return(bridge_type));
const auto host_nets = std::vector<mp::NetworkInterfaceInfo>{{"simple", "bridge", "this and that"}};
const auto tag = mp::NetworkInterface{"updated", "tag", false};
auto extra_nets = std::vector<mp::NetworkInterface>{
{"aaa", "alpha", true}, {"bbb", "beta", false}, {"br", "bridge", true}, {"brr", "bridge", false}};
const auto num_nets = extra_nets.size();
MockBaseFactory factory;
EXPECT_CALL(factory, networks).WillOnce(Return(host_nets));
MP_DELEGATE_MOCK_CALLS_ON_BASE(factory, prepare_networking, mp::BaseVirtualMachineFactory);
for (auto& net : extra_nets)
EXPECT_CALL(factory, prepare_interface(Ref(net), Eq(host_nets))).WillOnce(SetArgReferee<0>(tag));
factory.prepare_networking(extra_nets);
EXPECT_EQ(extra_nets.size(), num_nets);
EXPECT_THAT(extra_nets, Each(Eq(tag)));
}
TEST_F(BaseFactory, factoryHasDefaultSuspendSupport)
{
MockBaseFactory factory;
EXPECT_NO_THROW(factory.mp::BaseVirtualMachineFactory::require_suspend_support());
}
} // namespace
| 12,199
|
C++
|
.cpp
| 257
| 39.684825
| 119
| 0.6617
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,621
|
test_disabled_copy_move.cpp
|
canonical_multipass/tests/test_disabled_copy_move.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/disabled_copy_move.h>
#include <type_traits>
namespace mp = multipass;
namespace
{
class Foo : private multipass::DisabledCopyMove
{
public:
virtual ~Foo()
{
}
};
class Bar : public Foo
{
};
class Baz : public Bar
{
public:
Baz() = default;
};
template <class T>
class Buz : public Baz
{
};
template <typename T>
void check_traits()
{
static_assert(!std::is_copy_constructible_v<T>);
static_assert(!std::is_copy_assignable_v<T>);
static_assert(!std::is_move_constructible_v<T>);
static_assert(!std::is_move_assignable_v<T>);
static_assert(std::is_nothrow_default_constructible_v<T>);
static_assert(std::is_nothrow_destructible_v<T>);
}
[[maybe_unused]] void check_all_traits()
{
check_traits<Foo>();
check_traits<Bar>();
check_traits<Baz>();
check_traits<Buz<int>>();
}
} // namespace
| 1,499
|
C++
|
.cpp
| 58
| 23.448276
| 72
| 0.718379
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,622
|
path.cpp
|
canonical_multipass/tests/path.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authored by: Alberto Aguirre <alberto.aguirre@canonical.com>
*
*/
#include "path.h"
#include <multipass/format.h>
#include <QCoreApplication>
#include <QDir>
namespace mpt = multipass::test;
QString mpt::test_data_path()
{
QDir dir{QCoreApplication::applicationDirPath()};
const auto test_data_dir_exists = dir.cd("test_data");
if (!test_data_dir_exists)
throw std::runtime_error("could not find test_data directory");
return QDir::toNativeSeparators(dir.path()) + QDir::separator();
}
QString mpt::test_data_path_for(const char* file_name)
{
QDir dir{test_data_path()};
return dir.filePath(file_name);
}
QString mpt::test_data_sub_dir_path(const char* dir_name)
{
QDir dir{test_data_path()};
if (!dir.cd(dir_name))
throw std::runtime_error(fmt::format("could not find sub dir '{}' under test_data directory", dir_name));
return QDir::toNativeSeparators(dir.path()) + QDir::separator();
}
std::string mpt::mock_bin_path()
{
QDir dir{QCoreApplication::applicationDirPath()};
const auto mocks_dir_exists = dir.cd("mocks");
if (!mocks_dir_exists)
throw std::runtime_error("could not find mock binaries directory");
return QDir::toNativeSeparators(dir.path()).toStdString();
}
| 1,885
|
C++
|
.cpp
| 51
| 34
| 113
| 0.723591
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,623
|
test_mock_standard_paths.cpp
|
canonical_multipass/tests/test_mock_standard_paths.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_standard_paths.h"
#include <multipass/standard_paths.h>
#include <QStandardPaths>
#include <QTemporaryDir>
namespace mp = multipass;
namespace mpt = mp::test;
using namespace testing;
namespace
{
TEST(StandardPaths, provides_regular_locate_by_default)
{
const auto location_type = mp::StandardPaths::TempLocation;
const auto find = QStringLiteral("o_o");
const auto locate_options = mp::StandardPaths::LocateOptions{mp::StandardPaths::LocateDirectory};
// Create a subdir in the standard temp dir, for locate to find
QDir aux{QStandardPaths::writableLocation(location_type)};
ASSERT_TRUE(aux.exists());
aux.mkdir(find);
ASSERT_TRUE(aux.exists(find));
// Confirm the subdir is properly located
const auto proof = QStandardPaths::locate(location_type, find, locate_options);
ASSERT_TRUE(proof.endsWith(find));
ASSERT_EQ(MP_STDPATHS.locate(location_type, find, locate_options), proof);
}
TEST(StandardPaths, can_have_locate_mocked)
{
const auto location_type = mp::StandardPaths::HomeLocation;
const auto locate_options = mp::StandardPaths::LocateOptions{mp::StandardPaths::LocateFile};
const auto find = QStringLiteral("abc");
const auto proof = QStringLiteral("xyz");
auto& mock = mpt::MockStandardPaths::mock_instance();
EXPECT_CALL(mock, locate(location_type, find, locate_options)).WillOnce(Return(proof));
ASSERT_EQ(MP_STDPATHS.locate(location_type, find, locate_options), proof);
}
TEST(StandardPaths, provides_regular_standard_locations_by_default)
{
const auto& test = mp::StandardPaths::MusicLocation;
ASSERT_EQ(MP_STDPATHS.standardLocations(test), QStandardPaths::standardLocations(test));
}
TEST(StandardPaths, can_have_standard_locations_mocked)
{
const auto test = mp::StandardPaths::AppConfigLocation;
const auto proof = QStringList{QStringLiteral("abc"), QStringLiteral("xyz")};
auto& mock = mpt::MockStandardPaths::mock_instance();
EXPECT_CALL(mock, standardLocations(test)).WillOnce(Return(proof));
ASSERT_EQ(MP_STDPATHS.standardLocations(test), proof);
}
TEST(StandardPaths, provides_regular_writable_location_by_default)
{
const auto test = mp::StandardPaths::MoviesLocation;
ASSERT_EQ(MP_STDPATHS.writableLocation(test), QStandardPaths::writableLocation(test));
}
TEST(StandardPaths, can_have_writable_location_mocked)
{
const auto test = mp::StandardPaths::ConfigLocation;
const auto proof = QStringLiteral("xyz");
auto& mock = mpt::MockStandardPaths::mock_instance();
EXPECT_CALL(mock, writableLocation(test)).WillOnce(Return(proof));
ASSERT_EQ(MP_STDPATHS.writableLocation(test), proof);
}
} // namespace
| 3,337
|
C++
|
.cpp
| 78
| 39.692308
| 101
| 0.75794
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,624
|
test_ssl_cert_provider.cpp
|
canonical_multipass/tests/test_ssl_cert_provider.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "file_operations.h"
#include "temp_dir.h"
#include <multipass/ssl_cert_provider.h>
#include <multipass/utils.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
struct SSLCertProvider : public testing::Test
{
SSLCertProvider()
{
cert_dir = MP_UTILS.make_dir(temp_dir.path(), "test-cert");
}
mpt::TempDir temp_dir;
mp::Path cert_dir;
};
TEST_F(SSLCertProvider, creates_cert_and_key)
{
mp::SSLCertProvider cert_provider{cert_dir};
auto pem_cert = cert_provider.PEM_certificate();
auto pem_key = cert_provider.PEM_signing_key();
EXPECT_THAT(pem_cert, StrNe(""));
EXPECT_THAT(pem_key, StrNe(""));
}
TEST_F(SSLCertProvider, imports_existing_cert_and_key)
{
constexpr auto key_data = "-----BEGIN PRIVATE KEY-----\n"
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgsSAz5ggzrLjai0I/\n"
"F0hYg5oG/shpXJiBQtJdBCG3lUShRANCAAQAFGNAqq7c5IMDeQ/cV4+Emogmkfpb\n"
"TLSPfXgXVLHRsvL04xUAkqGpL+eyGFVE6dqaJ7sAPJJwlVj1xD0r5DX5\n"
"-----END PRIVATE KEY-----\n";
constexpr auto cert_data = "-----BEGIN CERTIFICATE-----\n"
"MIIBUjCB+AIBKjAKBggqhkjOPQQDAjA1MQswCQYDVQQGEwJDQTESMBAGA1UECgwJ\n"
"Q2Fub25pY2FsMRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMTgwNjIxMTM0MjI5WhcN\n"
"MTkwNjIxMTM0MjI5WjA1MQswCQYDVQQGEwJDQTESMBAGA1UECgwJQ2Fub25pY2Fs\n"
"MRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQA\n"
"FGNAqq7c5IMDeQ/cV4+EmogmkfpbTLSPfXgXVLHRsvL04xUAkqGpL+eyGFVE6dqa\n"
"J7sAPJJwlVj1xD0r5DX5MAoGCCqGSM49BAMCA0kAMEYCIQCvI0PYv9f201fbe4LP\n"
"BowTeYWSqMQtLNjvZgd++AAGhgIhALNPW+NRSKCXwadiIFgpbjPInLPqXPskLWSc\n"
"aXByaQyt\n"
"-----END CERTIFICATE-----\n";
const QDir dir{cert_dir};
const auto key_path = dir.filePath("multipass_cert_key.pem");
const auto cert_path = dir.filePath("multipass_cert.pem");
mpt::make_file_with_content(key_path, key_data);
mpt::make_file_with_content(cert_path, cert_data);
mp::SSLCertProvider cert_provider{cert_dir};
EXPECT_THAT(cert_provider.PEM_signing_key(), StrEq(key_data));
EXPECT_THAT(cert_provider.PEM_certificate(), StrEq(cert_data));
}
TEST_F(SSLCertProvider, persists_cert_and_key)
{
QDir dir{cert_dir};
auto key_file = dir.filePath("multipass_cert_key.pem");
auto cert_file = dir.filePath("multipass_cert.pem");
EXPECT_FALSE(QFile::exists(key_file));
EXPECT_FALSE(QFile::exists(cert_file));
mp::SSLCertProvider cert_provider{cert_dir};
EXPECT_TRUE(QFile::exists(key_file));
EXPECT_TRUE(QFile::exists(cert_file));
}
TEST_F(SSLCertProvider, creates_different_certs_per_server_name)
{
mp::SSLCertProvider cert_provider1{cert_dir, "test_server1"};
mp::SSLCertProvider cert_provider2{cert_dir, "test_server2"};
auto pem_cert1 = cert_provider1.PEM_certificate();
auto pem_key1 = cert_provider1.PEM_signing_key();
auto pem_cert2 = cert_provider2.PEM_certificate();
auto pem_key2 = cert_provider2.PEM_signing_key();
EXPECT_THAT(pem_cert1, StrNe(pem_cert2));
EXPECT_THAT(pem_key1, StrNe(pem_key2));
}
| 4,067
|
C++
|
.cpp
| 89
| 38.123596
| 99
| 0.679717
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,625
|
test_basic_process.cpp
|
canonical_multipass/tests/test_basic_process.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "test_with_mocked_bin_path.h"
#include <multipass/process/basic_process.h>
#include <multipass/process/simple_process_spec.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
struct BasicProcessTest : public mpt::TestWithMockedBinPath
{
};
TEST_F(BasicProcessTest, execute_missing_command)
{
mp::BasicProcess process(mp::simple_process_spec("a_missing_command"));
auto process_state = process.execute();
EXPECT_FALSE(process_state.completed_successfully());
EXPECT_FALSE(process_state.exit_code);
EXPECT_TRUE(process_state.error);
EXPECT_EQ(QProcess::ProcessError::FailedToStart, process_state.error->state);
}
TEST_F(BasicProcessTest, execute_crashing_command)
{
mp::BasicProcess process(mp::simple_process_spec("mock_process"));
auto process_state = process.execute();
EXPECT_FALSE(process_state.completed_successfully());
EXPECT_FALSE(process_state.exit_code);
EXPECT_TRUE(process_state.error);
EXPECT_EQ(QProcess::ProcessError::Crashed, process_state.error->state);
}
TEST_F(BasicProcessTest, execute_good_command_with_positive_exit_code)
{
const int exit_code = 7;
mp::BasicProcess process(mp::simple_process_spec("mock_process", {QString::number(exit_code)}));
auto process_state = process.execute();
EXPECT_FALSE(process_state.completed_successfully());
ASSERT_TRUE(process_state.exit_code);
EXPECT_EQ(exit_code, *process_state.exit_code);
EXPECT_EQ("Process returned exit code: 7", process_state.failure_message());
EXPECT_FALSE(process_state.error);
}
TEST_F(BasicProcessTest, execute_good_command_with_zero_exit_code)
{
const int exit_code = 0;
mp::BasicProcess process(mp::simple_process_spec("mock_process", {QString::number(exit_code)}));
auto process_state = process.execute();
EXPECT_TRUE(process_state.completed_successfully());
ASSERT_TRUE(process_state.exit_code);
EXPECT_EQ(exit_code, *process_state.exit_code);
EXPECT_EQ(QString(), process_state.failure_message());
EXPECT_FALSE(process_state.error);
}
TEST_F(BasicProcessTest, process_state_when_runs_and_stops_ok)
{
const int exit_code = 7;
mp::BasicProcess process(mp::simple_process_spec("mock_process", {QString::number(exit_code), "stay-alive"}));
process.start();
EXPECT_TRUE(process.wait_for_started());
auto process_state = process.process_state();
EXPECT_FALSE(process_state.exit_code);
EXPECT_FALSE(process_state.error);
process.write(QByteArray(1, '\0')); // will make mock_process quit
EXPECT_TRUE(process.wait_for_finished());
process_state = process.process_state();
ASSERT_TRUE(process_state.exit_code);
EXPECT_EQ(exit_code, *process_state.exit_code);
EXPECT_FALSE(process_state.error);
}
TEST_F(BasicProcessTest, process_state_when_runs_but_fails_to_stop)
{
const int exit_code = 2;
mp::BasicProcess process(mp::simple_process_spec("mock_process", {QString::number(exit_code), "stay-alive"}));
process.start();
EXPECT_TRUE(process.wait_for_started());
auto process_state = process.process_state();
EXPECT_FALSE(process_state.exit_code);
EXPECT_FALSE(process_state.error);
EXPECT_FALSE(process.wait_for_finished(100)); // will hit timeout
process_state = process.process_state();
EXPECT_FALSE(process_state.exit_code);
EXPECT_TRUE(process_state.error);
EXPECT_EQ(QProcess::Timedout, process_state.error->state);
}
TEST_F(BasicProcessTest, process_state_when_crashes_on_start)
{
mp::BasicProcess process(mp::simple_process_spec("mock_process")); // will crash immediately
process.start();
// EXPECT_TRUE(process.wait_for_started()); // on start too soon, app hasn't crashed yet!
EXPECT_TRUE(process.wait_for_finished());
auto process_state = process.process_state();
EXPECT_FALSE(process_state.exit_code);
EXPECT_TRUE(process_state.error);
EXPECT_EQ(QProcess::Crashed, process_state.error->state);
}
TEST_F(BasicProcessTest, process_state_when_crashes_while_running)
{
mp::BasicProcess process(mp::simple_process_spec("mock_process", {QString::number(0), "stay-alive"}));
process.start();
process.write("crash"); // will make mock_process crash
process.write(QByteArray(1, '\0'));
EXPECT_TRUE(process.wait_for_finished());
auto process_state = process.process_state();
EXPECT_FALSE(process_state.exit_code);
EXPECT_TRUE(process_state.error);
EXPECT_EQ(QProcess::Crashed, process_state.error->state);
}
TEST_F(BasicProcessTest, process_state_when_failed_to_start)
{
mp::BasicProcess process(mp::simple_process_spec("a_missing_process"));
process.start();
EXPECT_FALSE(process.wait_for_started());
auto process_state = process.process_state();
EXPECT_FALSE(process_state.exit_code);
EXPECT_TRUE(process_state.error);
EXPECT_EQ(QProcess::FailedToStart, process_state.error->state);
}
TEST_F(BasicProcessTest, process_state_when_runs_and_stops_immediately)
{
const int exit_code = 7;
mp::BasicProcess process(mp::simple_process_spec("mock_process", {QString::number(exit_code)}));
process.start();
EXPECT_TRUE(process.wait_for_started());
auto process_state = process.process_state();
EXPECT_FALSE(process_state.exit_code);
EXPECT_FALSE(process_state.error);
EXPECT_TRUE(process.wait_for_finished());
process_state = process.process_state();
ASSERT_TRUE(process_state.exit_code);
EXPECT_EQ(exit_code, *process_state.exit_code);
EXPECT_FALSE(process_state.error);
}
TEST_F(BasicProcessTest, error_string_when_not_run)
{
const auto program = "foo";
mp::BasicProcess process{mp::simple_process_spec(program)};
EXPECT_THAT(process.error_string().toStdString(), HasSubstr(program));
EXPECT_THAT(process.error_string().toStdString(), HasSubstr("Unknown"));
}
TEST_F(BasicProcessTest, error_string_when_completing_successfully)
{
const auto program = "mock_process";
mp::BasicProcess process{mp::simple_process_spec(program, {"0"})};
EXPECT_TRUE(process.execute().completed_successfully());
EXPECT_THAT(process.error_string().toStdString(), HasSubstr(program));
EXPECT_THAT(process.error_string().toStdString(), HasSubstr("Unknown"));
}
TEST_F(BasicProcessTest, error_string_when_crashing)
{
const auto program = "mock_process";
mp::BasicProcess process(mp::simple_process_spec(program));
EXPECT_FALSE(process.execute().completed_successfully());
EXPECT_THAT(process.error_string().toStdString(), HasSubstr(program));
}
TEST_F(BasicProcessTest, error_string_when_missing_command)
{
const auto program = "no_bin_named_like_this";
mp::BasicProcess process{mp::simple_process_spec(program)};
EXPECT_FALSE(process.execute().completed_successfully());
EXPECT_THAT(process.error_string().toStdString(), HasSubstr(program));
}
TEST_F(BasicProcessTest, reports_pid_0_until_started)
{
const auto program = "mock_process";
mp::BasicProcess process{mp::simple_process_spec(program)};
ASSERT_EQ(process.process_id(), 0);
}
TEST_F(BasicProcessTest, reports_positive_pid_after_started)
{
const auto program = "mock_process";
auto ran = false;
mp::BasicProcess process{mp::simple_process_spec(program)};
QObject::connect(&process, &mp::Process::started, [&process, &ran] {
EXPECT_GT(process.process_id(), 0);
ran = true;
});
process.start();
EXPECT_TRUE(process.wait_for_finished());
EXPECT_TRUE(ran);
}
TEST_F(BasicProcessTest, reports_previous_pid_after_finished)
{
const auto program = "mock_process";
auto pid = 0ll;
mp::BasicProcess process{mp::simple_process_spec(program)};
QObject::connect(&process, &mp::Process::started, [&process, &pid] { pid = process.process_id(); });
process.start();
EXPECT_TRUE(process.wait_for_finished());
ASSERT_GT(pid, 0);
EXPECT_EQ(process.process_id(), pid);
}
TEST_F(BasicProcessTest, reads_expected_data_from_stdout_and_stderr)
{
const QByteArray data{"Some data the mock process will return"};
mp::BasicProcess process(mp::simple_process_spec("mock_process", {"0", "stay-alive"}));
QObject::connect(&process, &mp::Process::ready_read_standard_output, [&process, &data] {
auto stdout_data = process.read_all_standard_output();
EXPECT_EQ(data, stdout_data);
});
QObject::connect(&process, &mp::Process::ready_read_standard_error, [&process, &data] {
auto stderr_data = process.read_all_standard_error();
EXPECT_EQ(data, stderr_data);
});
EXPECT_TRUE(process.working_directory().isEmpty());
process.start();
process.write(data);
process.write(QByteArray(1, '\0'));
EXPECT_TRUE(process.wait_for_finished());
}
| 9,457
|
C++
|
.cpp
| 222
| 38.567568
| 114
| 0.72527
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,626
|
test_ssh_session.cpp
|
canonical_multipass/tests/test_ssh_session.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_ssh.h"
#include "stub_ssh_key_provider.h"
#include <multipass/ssh/ssh_session.h>
namespace mp = multipass;
using namespace testing;
namespace
{
struct SSHSession : public Test
{
mp::SSHSession make_ssh_session()
{
return mp::SSHSession("theanswertoeverything", 42, "ubuntu", key_provider);
}
mp::test::StubSSHKeyProvider key_provider;
};
} // namespace
TEST_F(SSHSession, throws_when_unable_to_allocate_session)
{
REPLACE(ssh_new, []() { return nullptr; });
EXPECT_THROW(make_ssh_session(), std::runtime_error);
}
TEST_F(SSHSession, throws_when_unable_to_set_option)
{
REPLACE(ssh_options_set, [](auto...) { return SSH_ERROR; });
EXPECT_THROW(make_ssh_session(), std::runtime_error);
}
TEST_F(SSHSession, throws_when_unable_to_connect)
{
REPLACE(ssh_connect, [](auto...) { return SSH_ERROR; });
EXPECT_THROW(make_ssh_session(), std::runtime_error);
}
TEST_F(SSHSession, throws_when_unable_to_auth)
{
REPLACE(ssh_connect, [](auto...) { return SSH_OK; });
REPLACE(ssh_userauth_publickey, [](auto...) { return SSH_AUTH_ERROR; });
EXPECT_THROW(make_ssh_session(), std::runtime_error);
}
TEST_F(SSHSession, exec_throws_on_a_dead_session)
{
REPLACE(ssh_connect, [](auto...) { return SSH_OK; });
REPLACE(ssh_userauth_publickey, [](auto...) { return SSH_AUTH_SUCCESS; });
mp::SSHSession session = make_ssh_session();
REPLACE(ssh_is_connected, [](auto...) { return false; });
EXPECT_THROW(session.exec("dummy"), std::runtime_error);
}
TEST_F(SSHSession, exec_throws_if_ssh_is_dead)
{
REPLACE(ssh_connect, [](auto...) { return SSH_OK; });
REPLACE(ssh_userauth_publickey, [](auto...) { return SSH_AUTH_SUCCESS; });
mp::SSHSession session = make_ssh_session();
REPLACE(ssh_is_connected, [](auto...) { return false; });
EXPECT_THROW(session.exec("dummy"), std::runtime_error);
}
TEST_F(SSHSession, exec_throws_when_unable_to_open_a_channel_session)
{
REPLACE(ssh_connect, [](auto...) { return SSH_OK; });
REPLACE(ssh_userauth_publickey, [](auto...) { return SSH_AUTH_SUCCESS; });
mp::SSHSession session = make_ssh_session();
REPLACE(ssh_is_connected, [](auto...) { return true; });
REPLACE(ssh_channel_open_session, [](auto...) { return SSH_ERROR; });
EXPECT_THROW(session.exec("dummy"), std::runtime_error);
}
TEST_F(SSHSession, exec_throws_when_unable_to_request_channel_exec)
{
REPLACE(ssh_connect, [](auto...) { return SSH_OK; });
REPLACE(ssh_userauth_publickey, [](auto...) { return SSH_AUTH_SUCCESS; });
mp::SSHSession session = make_ssh_session();
REPLACE(ssh_is_connected, [](auto...) { return true; });
REPLACE(ssh_channel_open_session, [](auto...) { return SSH_OK; });
REPLACE(ssh_channel_request_exec, [](auto...) { return SSH_ERROR; });
EXPECT_THROW(session.exec("dummy"), std::runtime_error);
}
TEST_F(SSHSession, exec_succeeds)
{
REPLACE(ssh_connect, [](auto...) { return SSH_OK; });
REPLACE(ssh_userauth_publickey, [](auto...) { return SSH_AUTH_SUCCESS; });
mp::SSHSession session = make_ssh_session();
REPLACE(ssh_is_connected, [](auto...) { return true; });
REPLACE(ssh_channel_open_session, [](auto...) { return SSH_OK; });
REPLACE(ssh_channel_request_exec, [](auto...) { return SSH_OK; });
EXPECT_NO_THROW(session.exec("dummy"));
}
TEST_F(SSHSession, moveAssigns)
{
REPLACE(ssh_connect, [](auto...) { return SSH_OK; });
REPLACE(ssh_userauth_publickey, [](auto...) { return SSH_AUTH_SUCCESS; });
mp::SSHSession session1 = make_ssh_session();
mp::SSHSession session2 = make_ssh_session();
ssh_session ssh_session2 = session2;
session1 = std::move(session2);
EXPECT_EQ(ssh_session{session1}, ssh_session2);
EXPECT_EQ(ssh_session{session2}, nullptr);
}
| 4,452
|
C++
|
.cpp
| 110
| 37.209091
| 83
| 0.681481
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,627
|
test_daemon_mount.cpp
|
canonical_multipass/tests/test_daemon_mount.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "daemon_test_fixture.h"
#include "mock_logger.h"
#include "mock_mount_handler.h"
#include "mock_platform.h"
#include "mock_server_reader_writer.h"
#include "mock_settings.h"
#include "mock_virtual_machine.h"
#include "mock_vm_image_vault.h"
#include "stub_mount_handler.h"
#include "temp_dir.h"
#include "temp_file.h"
#include <multipass/constants.h>
#include <multipass/exceptions/not_implemented_on_this_backend_exception.h>
#include <multipass/exceptions/sshfs_missing_error.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct TestDaemonMount : public mpt::DaemonTestFixture
{
void SetUp() override
{
EXPECT_CALL(mock_settings, register_handler(_)).WillRepeatedly(Return(nullptr));
EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber());
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillRepeatedly(Return("true"));
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mock_factory = use_a_mock_vm_factory();
}
std::unique_ptr<mpt::MockMountHandler> mock_mount_handler{std::make_unique<mpt::MockMountHandler>()};
mpt::MockVirtualMachineFactory* mock_factory;
const std::string mock_instance_name{"real-zebraphant"};
const std::string mac_addr{"52:54:00:73:76:28"};
const std::string fake_target_path{"/home/ubuntu/foo"};
std::vector<mp::NetworkInterface> extra_interfaces;
mpt::TempDir mount_dir;
mpt::MockPlatform::GuardedMock platform_attr{mpt::MockPlatform::inject<NiceMock>()};
mpt::MockPlatform* mock_platform = platform_attr.first;
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
};
} // namespace
TEST_F(TestDaemonMount, refusesDisabledMount)
{
mp::Daemon daemon{config_builder.build()};
EXPECT_CALL(mock_settings, get(Eq(mp::mounts_key))).WillRepeatedly(Return("false"));
std::stringstream err_stream;
auto status = call_daemon_slot(daemon, &mp::Daemon::mount, mp::MountRequest{},
StrictMock<mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::FAILED_PRECONDITION);
EXPECT_THAT(status.error_message(), HasSubstr("Mounts are disabled on this installation of Multipass."));
}
TEST_F(TestDaemonMount, missingInstanceFails)
{
const std::string& fake_instance{"fake"};
mp::Daemon daemon{config_builder.build()};
mp::MountRequest request;
request.set_source_path(mount_dir.path().toStdString());
auto entry = request.add_target_paths();
entry->set_instance_name(fake_instance);
auto status = call_daemon_slot(daemon, &mp::Daemon::mount, request,
StrictMock<mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), HasSubstr(fmt::format("instance '{}' does not exist", fake_instance)));
}
TEST_F(TestDaemonMount, invalidTargetPathFails)
{
const auto [temp_dir, _] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
config_builder.data_directory = temp_dir->path();
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(Return(std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name)));
mp::Daemon daemon{config_builder.build()};
const std::string invalid_path{"/dev/foo"};
mp::MountRequest request;
request.set_source_path(mount_dir.path().toStdString());
auto entry = request.add_target_paths();
entry->set_instance_name(mock_instance_name);
entry->set_target_path(invalid_path);
auto status = call_daemon_slot(daemon, &mp::Daemon::mount, request,
StrictMock<mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), HasSubstr(fmt::format("unable to mount to \"{}\"", invalid_path)));
}
TEST_F(TestDaemonMount, mountIgnoresTrailingSlash)
{
const auto [temp_dir, _] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
config_builder.data_directory = temp_dir->path();
auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_vm, make_native_mount_handler).WillOnce(Return(std::make_unique<mpt::StubMountHandler>()));
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm)));
mp::Daemon daemon{config_builder.build()};
mp::MountRequest request;
request.set_source_path(mount_dir.path().toStdString());
request.set_mount_type(mp::MountRequest::NATIVE);
auto entry1 = request.add_target_paths();
entry1->set_instance_name(mock_instance_name);
entry1->set_target_path(fake_target_path);
auto entry2 = request.add_target_paths();
entry2->set_instance_name(mock_instance_name);
entry2->set_target_path(fake_target_path + "/");
auto status = call_daemon_slot(daemon, &mp::Daemon::mount, request,
StrictMock<mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(),
HasSubstr(fmt::format("\"{}\" is already mounted in '{}'", fake_target_path, mock_instance_name)));
}
TEST_F(TestDaemonMount, skipStartMountIfInstanceIsNotRunning)
{
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
config_builder.data_directory = temp_dir->path();
EXPECT_CALL(*mock_mount_handler, activate_impl).Times(0);
auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_vm, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::stopped));
EXPECT_CALL(*mock_vm, make_native_mount_handler).WillOnce(Return(std::move(mock_mount_handler)));
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm)));
mp::Daemon daemon{config_builder.build()};
mp::MountRequest request;
request.set_source_path(mount_dir.path().toStdString());
request.set_mount_type(mp::MountRequest::NATIVE);
auto entry = request.add_target_paths();
entry->set_instance_name(mock_instance_name);
entry->set_target_path(fake_target_path);
auto status = call_daemon_slot(daemon, &mp::Daemon::mount, request,
StrictMock<mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest>>{});
EXPECT_TRUE(status.ok());
}
TEST_F(TestDaemonMount, startsMountIfInstanceRunning)
{
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
config_builder.data_directory = temp_dir->path();
EXPECT_CALL(*mock_mount_handler, activate_impl).Times(1);
auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_vm, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::running));
EXPECT_CALL(*mock_vm, make_native_mount_handler).WillOnce(Return(std::move(mock_mount_handler)));
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm)));
mp::Daemon daemon{config_builder.build()};
mp::MountRequest request;
request.set_source_path(mount_dir.path().toStdString());
request.set_mount_type(mp::MountRequest::NATIVE);
auto entry = request.add_target_paths();
entry->set_instance_name(mock_instance_name);
entry->set_target_path(fake_target_path);
auto status = call_daemon_slot(daemon, &mp::Daemon::mount, request,
StrictMock<mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest>>{});
EXPECT_TRUE(status.ok());
}
TEST_F(TestDaemonMount, mountFailsErrorMounting)
{
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
config_builder.data_directory = temp_dir->path();
auto error = "permission denied";
EXPECT_CALL(*mock_mount_handler, activate_impl).WillOnce(Throw(std::runtime_error(error)));
auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_vm, current_state).WillRepeatedly(Return(mp::VirtualMachine::State::running));
EXPECT_CALL(*mock_vm, make_native_mount_handler).WillOnce(Return(std::move(mock_mount_handler)));
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm)));
mp::Daemon daemon{config_builder.build()};
mp::MountRequest request;
request.set_source_path(mount_dir.path().toStdString());
request.set_mount_type(mp::MountRequest::NATIVE);
auto entry = request.add_target_paths();
entry->set_instance_name(mock_instance_name);
entry->set_target_path(fake_target_path);
auto status = call_daemon_slot(daemon, &mp::Daemon::mount, request,
StrictMock<mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), HasSubstr(fmt::format("error mounting \"{}\": {}", fake_target_path, error)));
}
TEST_F(TestDaemonMount, performanceMountsNotImplementedHasErrorFails)
{
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
config_builder.data_directory = temp_dir->path();
auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_vm, make_native_mount_handler)
.WillOnce(Throw(mp::NotImplementedOnThisBackendException("native mounts")));
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm)));
mp::Daemon daemon{config_builder.build()};
mp::MountRequest request;
request.set_source_path(mount_dir.path().toStdString());
request.set_mount_type(mp::MountRequest::NATIVE);
auto entry = request.add_target_paths();
entry->set_instance_name(mock_instance_name);
entry->set_target_path(fake_target_path);
auto status = call_daemon_slot(daemon, &mp::Daemon::mount, request,
StrictMock<mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::FAILED_PRECONDITION);
EXPECT_THAT(status.error_message(), StrEq("The native mounts feature is not implemented on this backend."));
}
| 11,424
|
C++
|
.cpp
| 205
| 50.185366
| 118
| 0.717167
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,628
|
test_private_pass_provider.cpp
|
canonical_multipass/tests/test_private_pass_provider.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <multipass/private_pass_provider.h>
#include <string>
namespace mp = multipass;
namespace
{
struct FriendExample;
struct PassExample : public mp::PrivatePassProvider<PassExample>
{
public:
static std::string speak_friend_and_enter(const PrivatePass&, const std::string& ret)
{
return ret;
}
private:
static constexpr const PrivatePass& mellon = pass;
friend struct FriendExample;
};
struct FriendExample
{
public:
std::string enter(const std::string& ret) const
{
return PassExample::speak_friend_and_enter(PassExample::mellon, ret);
}
};
TEST(PrivatePass, friend_can_call_function_requiring_pass)
{
const auto str = "proof";
const FriendExample fex{};
EXPECT_EQ(fex.enter(str), str);
}
// safety demo
struct TryBreakInExample : public mp::PrivatePassProvider<TryBreakInExample>,
public mp::PrivatePassProvider<PassExample>
{
static void trybreakin()
{
// PassExample::speak_friend_and_enter(pass, "asdf"); // error: which one?
// PassExample::speak_friend_and_enter(PrivatePassProvider<TryBreakInExample>::pass, "fdsa"); // error: wrong
// type PassExample::speak_friend_and_enter(PrivatePassProvider<PassExample>::pass, "x"); // error: not friends
}
};
} // namespace
| 1,961
|
C++
|
.cpp
| 60
| 29.2
| 119
| 0.725397
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,629
|
test_daemon_find.cpp
|
canonical_multipass/tests/test_daemon_find.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "daemon_test_fixture.h"
#include "mock_image_host.h"
#include "mock_platform.h"
#include "mock_settings.h"
#include "mock_vm_blueprint_provider.h"
#include "mock_vm_image_vault.h"
#include <src/daemon/daemon.h>
#include <multipass/constants.h>
#include <multipass/exceptions/download_exception.h>
#include <multipass/format.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
auto blueprint_description_for(const std::string& blueprint_name)
{
return fmt::format("This is the {} blueprint", blueprint_name);
}
} // namespace
struct DaemonFind : public mpt::DaemonTestFixture
{
void SetUp() override
{
EXPECT_CALL(mock_settings, register_handler).WillRepeatedly(Return(nullptr));
EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber());
EXPECT_CALL(mock_settings, get(Eq(mp::winterm_key))).WillRepeatedly(Return("none"));
}
mpt::MockPlatform::GuardedMock attr{mpt::MockPlatform::inject<NiceMock>()};
mpt::MockPlatform* mock_platform = attr.first;
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject<StrictMock>();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
};
TEST_F(DaemonFind, blankQueryReturnsAllData)
{
auto mock_image_host = std::make_unique<NiceMock<mpt::MockImageHost>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr auto blueprint1_name = "foo";
static constexpr auto blueprint2_name = "bar";
EXPECT_CALL(*mock_blueprint_provider, all_blueprints()).WillOnce([] {
std::vector<mp::VMImageInfo> blueprint_info;
mp::VMImageInfo info1, info2;
info1.aliases.append(blueprint1_name);
info1.release_title = QString::fromStdString(blueprint_description_for(blueprint1_name));
blueprint_info.push_back(info1);
info2.aliases.append(blueprint2_name);
info2.release_title = QString::fromStdString(blueprint_description_for(blueprint2_name));
blueprint_info.push_back(info2);
return blueprint_info;
});
config_builder.image_hosts.clear();
config_builder.image_hosts.push_back(std::move(mock_image_host));
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
mp::Daemon daemon{config_builder.build()};
std::stringstream stream;
send_command({"find"}, stream);
EXPECT_THAT(stream.str(), AllOf(HasSubstr(mpt::default_alias), HasSubstr(mpt::default_release_info),
HasSubstr(mpt::another_alias), HasSubstr(mpt::another_release_info),
HasSubstr(fmt::format("{}:{}", mpt::custom_remote, mpt::custom_alias)),
HasSubstr(mpt::custom_release_info), HasSubstr(blueprint1_name),
HasSubstr(blueprint_description_for(blueprint1_name)), HasSubstr(blueprint2_name),
HasSubstr(blueprint_description_for(blueprint2_name))));
EXPECT_THAT(stream.str(),
Not(AllOf(HasSubstr(fmt::format("{}:{}", mpt::snapcraft_remote, mpt::snapcraft_alias)),
HasSubstr(mpt::snapcraft_release_info))));
EXPECT_EQ(total_lines_of_output(stream), 9);
}
TEST_F(DaemonFind, queryForDefaultReturnsExpectedData)
{
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
EXPECT_CALL(*mock_image_vault, all_info_for(_)).WillOnce([](const mp::Query& query) {
mpt::MockImageHost mock_image_host;
std::vector<std::pair<std::string, mp::VMImageInfo>> info;
info.push_back(std::make_pair(mpt::release_remote, mock_image_host.mock_bionic_image_info));
return info;
});
config_builder.vault = std::move(mock_image_vault);
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
mp::Daemon daemon{config_builder.build()};
std::stringstream stream;
send_command({"find", "default", "--only-images"}, stream);
EXPECT_THAT(stream.str(), AllOf(HasSubstr(mpt::default_alias), HasSubstr(mpt::default_release_info)));
EXPECT_THAT(stream.str(), Not(HasSubstr("No blueprints found.")));
EXPECT_EQ(total_lines_of_output(stream), 3);
}
TEST_F(DaemonFind, queryForBlueprintReturnsExpectedData)
{
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
static constexpr auto blueprint_name = "foo";
config_builder.vault = std::move(mock_image_vault);
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
mp::Daemon daemon{config_builder.build()};
std::stringstream stream;
send_command({"find", blueprint_name, "--only-blueprints"}, stream);
EXPECT_THAT(stream.str(), AllOf(HasSubstr(blueprint_name), HasSubstr(blueprint_description_for(blueprint_name))));
EXPECT_THAT(stream.str(), Not(HasSubstr("No images found.")));
EXPECT_EQ(total_lines_of_output(stream), 3);
}
TEST_F(DaemonFind, unknownQueryReturnsEmpty)
{
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
auto mock_blueprint_provider = std::make_unique<NiceMock<mpt::MockVMBlueprintProvider>>();
EXPECT_CALL(*mock_image_vault, all_info_for(_)).WillOnce(Throw(std::runtime_error("")));
EXPECT_CALL(*mock_blueprint_provider, info_for(_)).WillOnce(Return(std::nullopt));
config_builder.vault = std::move(mock_image_vault);
config_builder.blueprint_provider = std::move(mock_blueprint_provider);
mp::Daemon daemon{config_builder.build()};
constexpr auto phony_name = "phony";
std::stringstream stream;
send_command({"find", phony_name}, stream);
EXPECT_THAT(stream.str(), HasSubstr("No images or blueprints found."));
}
TEST_F(DaemonFind, forByRemoteReturnsExpectedData)
{
NiceMock<mpt::MockImageHost> mock_image_host;
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
EXPECT_CALL(*mock_image_vault, image_host_for(_)).WillOnce([&mock_image_host](auto...) {
return &mock_image_host;
});
EXPECT_CALL(mock_image_host, all_images_for(_, _)).WillOnce([&mock_image_host](auto...) {
std::vector<mp::VMImageInfo> images_info;
images_info.push_back(mock_image_host.mock_bionic_image_info);
images_info.push_back(mock_image_host.mock_another_image_info);
return images_info;
});
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
constexpr auto remote_name = "release:";
std::stringstream stream;
send_command({"find", remote_name}, stream);
EXPECT_THAT(stream.str(), AllOf(HasSubstr(fmt::format("{}{}", remote_name, mpt::default_alias)),
HasSubstr(mpt::default_release_info),
HasSubstr(fmt::format("{}{}", remote_name, mpt::another_alias)),
HasSubstr(mpt::another_release_info)));
EXPECT_EQ(total_lines_of_output(stream), 4);
}
TEST_F(DaemonFind, invalidRemoteNameAndEmptySearchString)
{
auto mock_image_vault = std::make_unique<NiceMock<const mpt::MockVMImageVault>>();
constexpr std::string_view remote_name = "nonsense";
const std::string error_msg = fmt::format(
"Remote \'{}\' is not found. Please use `multipass find` for supported remotes and images.", remote_name);
EXPECT_CALL(*mock_image_vault, image_host_for(_)).Times(1).WillOnce([&error_msg]() {
throw std::runtime_error(error_msg);
return nullptr;
});
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
const std::string full_name = std::string(remote_name) + ":";
std::stringstream cerr_Stream;
// std::cout is the place holder here.
send_command({"find", full_name}, std::cout, cerr_Stream);
EXPECT_THAT(cerr_Stream.str(), HasSubstr(error_msg));
EXPECT_EQ(total_lines_of_output(cerr_Stream), 1);
}
TEST_F(DaemonFind, invalidRemoteNameAndNonEmptySearchString)
{
auto mock_image_vault = std::make_unique<NiceMock<const mpt::MockVMImageVault>>();
constexpr std::string_view remote_name = "nonsense";
const std::string error_msg = fmt::format(
"Remote \'{}\' is not found. Please use `multipass find` for supported remotes and images.", remote_name);
EXPECT_CALL(*mock_image_vault, image_host_for(_)).Times(1).WillOnce([&error_msg]() {
throw std::runtime_error(error_msg);
return nullptr;
});
config_builder.vault = std::move(mock_image_vault);
mp::Daemon daemon{config_builder.build()};
constexpr std::string_view search_string = "default";
const std::string full_name = std::string(remote_name) + ":" + std::string(search_string);
std::stringstream cerr_Stream;
// std::cout is the place holder here.
send_command({"find", full_name}, std::cout, cerr_Stream);
EXPECT_THAT(cerr_Stream.str(), HasSubstr(error_msg));
EXPECT_EQ(total_lines_of_output(cerr_Stream), 1);
}
TEST_F(DaemonFind, findWithoutForceUpdateCheckUpdateManifestsCall)
{
auto mock_image_host = std::make_unique<NiceMock<mpt::MockImageHost>>();
// only the daemon constructor invoke it once
EXPECT_CALL(*mock_image_host, update_manifests(false)).Times(1);
// overwrite the default emplaced StubVMImageHost
config_builder.image_hosts[0] = std::move(mock_image_host);
const mp::Daemon daemon{config_builder.build()};
send_command({"find"});
}
TEST_F(DaemonFind, UpdateManifestsThrowTriggersTheFailedCaseEventHandlerOfAsyncPeriodicDownloadTask)
{
auto mock_image_host = std::make_unique<NiceMock<mpt::MockImageHost>>();
// daemon constructor which constructs update_manifests_all_task calls this.
EXPECT_CALL(*mock_image_host, update_manifests(false)).Times(1).WillOnce([]() {
throw mp::DownloadException{"dummy_url", "dummy_cause"};
});
// overwrite the default emplaced StubVMImageHost
config_builder.image_hosts[0] = std::move(mock_image_host);
const mp::Daemon daemon{config_builder.build()};
// need it because mp::Daemon destructor which destructs qfuture and qfuturewatcher does not wait the async task to
// finish. As a consequence, the event handler is not guaranteed to be called without send_command({"find"});
send_command({"find"});
}
TEST_F(DaemonFind, findForceUpdateCheckUpdateManifestsCalls)
{
auto mock_image_host = std::make_unique<NiceMock<mpt::MockImageHost>>();
// daemon constructor invoke it first and find --force-update invoke it with force flag true after
const testing::InSequence sequence; // Force the following expectations to occur in order
EXPECT_CALL(*mock_image_host, update_manifests(false)).Times(1);
EXPECT_CALL(*mock_image_host, update_manifests(true)).Times(1);
config_builder.image_hosts[0] = std::move(mock_image_host);
const mp::Daemon daemon{config_builder.build()};
send_command({"find", "--force-update"});
}
TEST_F(DaemonFind, findForceUpdateRemoteCheckUpdateManifestsCalls)
{
// this unit test requires and mock image_host_for of vault, so
// auto image_host = config->vault->image_host_for(remote);
// can have a legal value in image_host variable and avoid seg fault in the next
// line
auto mock_image_host = std::make_unique<NiceMock<mpt::MockImageHost>>();
auto mock_image_vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
EXPECT_CALL(*mock_image_vault, image_host_for(_)).WillOnce([image_host_ptr = mock_image_host.get()](auto...) {
return image_host_ptr;
});
const testing::InSequence sequence;
EXPECT_CALL(*mock_image_host, update_manifests(false)).Times(1);
EXPECT_CALL(*mock_image_host, update_manifests(true)).Times(1);
config_builder.vault = std::move(mock_image_vault);
config_builder.image_hosts[0] = std::move(mock_image_host);
const mp::Daemon daemon{config_builder.build()};
send_command({"find", "release:", "--force-update"});
}
TEST_F(DaemonFind, findForceUpdateRemoteSearchNameCheckUpdateManifestsCalls)
{
auto mock_image_host = std::make_unique<NiceMock<mpt::MockImageHost>>();
const testing::InSequence sequence;
EXPECT_CALL(*mock_image_host, update_manifests(false)).Times(1);
EXPECT_CALL(*mock_image_host, update_manifests(true)).Times(1);
config_builder.image_hosts[0] = std::move(mock_image_host);
const mp::Daemon daemon{config_builder.build()};
send_command({"find", "release:22.04", "--force-update"});
}
| 13,459
|
C++
|
.cpp
| 258
| 46.391473
| 119
| 0.702561
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,630
|
json_test_utils.cpp
|
canonical_multipass/tests/json_test_utils.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <multipass/utils.h>
#include "common.h"
#include "file_operations.h"
#include "json_test_utils.h"
#include <fmt/format.h>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
namespace mpu = multipass::utils;
std::string make_instance_json(const std::optional<std::string>& default_mac,
const std::vector<mp::NetworkInterface>& extra_ifaces,
const std::vector<std::string>& extra_instances)
{
QString contents("{\n"
" \"real-zebraphant\": {\n"
" \"deleted\": false,\n"
" \"disk_space\": \"5368709120\",\n"
" \"extra_interfaces\": [\n");
QStringList extra_json;
for (auto extra_interface : extra_ifaces)
{
extra_json += QString::fromStdString(fmt::format(" {{\n"
" \"auto_mode\": {},\n"
" \"id\": \"{}\",\n"
" \"mac_address\": \"{}\"\n"
" }}\n",
extra_interface.auto_mode, extra_interface.id,
extra_interface.mac_address));
}
contents += extra_json.join(',');
contents += QString::fromStdString(fmt::format(" ],\n"
" \"mac_addr\": \"{}\",\n"
" \"mem_size\": \"1073741824\",\n"
" \"metadata\": {{\n"
" \"arguments\": [\n"
" \"many\",\n"
" \"arguments\"\n"
" ],\n"
" \"machine_type\": \"dmc-de-lorean\"\n"
" }},\n"
" \"mounts\": [\n"
" ],\n"
" \"num_cores\": 1,\n"
" \"ssh_username\": \"ubuntu\",\n"
" \"state\": 2\n"
" }}\n",
default_mac ? *default_mac : mpu::generate_mac_address()));
for (const auto& instance : extra_instances)
{
contents += QString::fromStdString(fmt::format(",\n"
" \"{}\": {{\n"
" \"deleted\": false,\n"
" \"disk_space\": \"5368709120\",\n"
" \"extra_interfaces\": [\n"
" ],\n"
" \"mac_addr\": \"{}\",\n"
" \"mem_size\": \"1073741824\",\n"
" \"metadata\": {{\n"
" \"arguments\": [\n"
" \"many\",\n"
" \"arguments\"\n"
" ],\n"
" \"machine_type\": \"dmc-de-lorean\"\n"
" }},\n"
" \"mounts\": [\n"
" ],\n"
" \"num_cores\": 1,\n"
" \"ssh_username\": \"ubuntu\",\n"
" \"state\": 2\n"
" }}",
instance, mpu::generate_mac_address()));
}
contents += "}";
return contents.toStdString();
}
std::unique_ptr<mpt::TempDir> plant_instance_json(const std::string& contents)
{
auto temp_dir = std::make_unique<mpt::TempDir>();
QString filename(temp_dir->path() + "/multipassd-vm-instances.json");
mpt::make_file_with_content(filename, contents);
return temp_dir;
}
void check_interfaces_in_json(const QString& file, const std::string& mac,
const std::vector<mp::NetworkInterface>& extra_ifaces)
{
QByteArray json = mpt::load(file);
QJsonParseError parse_error;
const auto doc = QJsonDocument::fromJson(json, &parse_error);
EXPECT_FALSE(doc.isNull());
EXPECT_TRUE(doc.isObject());
const auto doc_object = doc.object();
const auto instance_object = doc_object["real-zebraphant"].toObject();
const auto default_mac = instance_object["mac_addr"].toString().toStdString();
ASSERT_EQ(default_mac, mac);
const auto extra = instance_object["extra_interfaces"].toArray();
ASSERT_EQ((unsigned)extra.size(), extra_ifaces.size());
auto it = extra_ifaces.cbegin();
for (const auto& extra_i : extra)
{
const auto interface = extra_i.toObject();
ASSERT_EQ(interface["mac_address"].toString().toStdString(), it->mac_address);
ASSERT_EQ(interface["id"].toString().toStdString(), it->id);
ASSERT_EQ(interface["auto_mode"].toBool(), it->auto_mode);
++it;
}
}
void check_mounts_in_json(const QString& file, std::unordered_map<std::string, mp::VMMount>& mounts)
{
QByteArray json = mpt::load(file);
QJsonParseError parse_error;
const auto doc = QJsonDocument::fromJson(json, &parse_error);
EXPECT_FALSE(doc.isNull());
EXPECT_TRUE(doc.isObject());
const auto doc_object = doc.object();
const auto instance_object = doc_object["real-zebraphant"].toObject();
const auto json_mounts = instance_object["mounts"].toArray();
ASSERT_EQ(json_mounts.count(), mounts.size());
for (const QJsonValue& json_mount : json_mounts)
{
const auto& json_target_path = json_mount["target_path"].toString().toStdString();
const auto& json_source_path = json_mount["source_path"].toString().toStdString();
const auto& json_uid_mapping = json_mount["uid_mappings"].toArray();
const auto& json_gid_mapping = json_mount["gid_mappings"].toArray();
ASSERT_EQ(mounts.count(json_target_path), 1);
const auto& original_mount = mounts[json_target_path];
ASSERT_EQ(original_mount.get_source_path(), json_source_path);
ASSERT_EQ(json_uid_mapping.count(), original_mount.get_uid_mappings().size());
for (auto i = 0; i < json_uid_mapping.count(); ++i)
{
ASSERT_EQ(json_uid_mapping[i]["host_uid"], original_mount.get_uid_mappings()[i].first);
ASSERT_EQ(json_uid_mapping[i]["instance_uid"], original_mount.get_uid_mappings()[i].second);
}
ASSERT_EQ(json_gid_mapping.count(), original_mount.get_gid_mappings().size());
for (auto i = 0; i < json_gid_mapping.count(); ++i)
{
ASSERT_EQ(json_gid_mapping[i]["host_gid"], original_mount.get_gid_mappings()[i].first);
ASSERT_EQ(json_gid_mapping[i]["instance_gid"], original_mount.get_gid_mappings()[i].second);
}
}
}
| 8,756
|
C++
|
.cpp
| 156
| 36.365385
| 110
| 0.429255
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,631
|
test_id_mappings.cpp
|
canonical_multipass/tests/test_id_mappings.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <multipass/id_mappings.h>
namespace mp = multipass;
using namespace testing;
struct UniqueIdMappingsTestSuite : public Test, public WithParamInterface<std::pair<mp::id_mappings, mp::id_mappings>>
{
};
TEST_P(UniqueIdMappingsTestSuite, UniqueIdMappingsWorks)
{
auto [input_mappings, expected_mappings] = GetParam();
mp::unique_id_mappings(input_mappings);
ASSERT_EQ(input_mappings, expected_mappings);
}
INSTANTIATE_TEST_SUITE_P(IdMappings,
UniqueIdMappingsTestSuite,
Values(std::make_pair(mp::id_mappings{{1, 1}, {2, 1}, {1, 1}, {1, 2}},
mp::id_mappings{{1, 1}}),
std::make_pair(mp::id_mappings{{3, 4}}, mp::id_mappings{{3, 4}}),
std::make_pair(mp::id_mappings{}, mp::id_mappings{})));
| 1,524
|
C++
|
.cpp
| 35
| 36.942857
| 118
| 0.661715
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,632
|
mock_standard_paths.cpp
|
canonical_multipass/tests/mock_standard_paths.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_standard_paths.h"
namespace mpt = multipass::test;
using namespace testing;
void mpt::MockStandardPaths::mockit()
{
mpt::MockSingletonHelper<MockStandardPaths, NiceMock>::mockit();
}
auto mpt::MockStandardPaths::mock_instance() -> MockStandardPaths&
{
return dynamic_cast<MockStandardPaths&>(instance());
}
void mpt::MockStandardPaths::setup_mock_defaults()
{
// see https://github.com/google/googletest/issues/2794
ON_CALL(*this, locate(_, _, _)).WillByDefault([this](const auto& a, const auto& b, const auto& c) {
return StandardPaths::locate(a, b, c); // call the parent (this implicit)
});
ON_CALL(*this, standardLocations(_)).WillByDefault([this](const auto& loc) {
return StandardPaths::standardLocations(loc); // call the parent (this implicit)
});
ON_CALL(*this, writableLocation(_)).WillByDefault([this](const auto& loc) {
return StandardPaths::writableLocation(loc); // call the parent (this implicit)
});
}
| 1,627
|
C++
|
.cpp
| 40
| 37.65
| 103
| 0.726123
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,633
|
test_constants.cpp
|
canonical_multipass/tests/test_constants.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <multipass/constants.h>
#include <multipass/memory_size.h>
namespace mp = multipass;
using namespace testing;
TEST(Constants, constants_constraints) {
EXPECT_NO_THROW(std::stoi(mp::min_cpu_cores));
EXPECT_NO_THROW(std::stoi(mp::default_cpu_cores));
EXPECT_NO_THROW(mp::MemorySize{mp::min_memory_size});
EXPECT_NO_THROW(mp::MemorySize{mp::default_memory_size});
EXPECT_NO_THROW(mp::MemorySize{mp::min_disk_size});
EXPECT_NO_THROW(mp::MemorySize{mp::default_disk_size});
}
TEST(Constants, defaults_greater_or_equal_to_minimums)
{
EXPECT_GE(mp::MemorySize{mp::default_memory_size}, mp::MemorySize{mp::min_memory_size});
EXPECT_GE(mp::MemorySize{mp::default_disk_size}, mp::MemorySize{mp::min_disk_size});
EXPECT_GE(std::stoi(mp::default_cpu_cores), std::stoi(mp::min_cpu_cores));
}
| 1,479
|
C++
|
.cpp
| 35
| 39.6
| 92
| 0.73783
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,634
|
test_common_callbacks.cpp
|
canonical_multipass/tests/test_common_callbacks.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common.h"
#include "mock_client_platform.h"
#include "mock_client_rpc.h"
#include "stub_terminal.h"
#include <src/client/cli/cmd/animated_spinner.h>
#include <src/client/cli/cmd/common_callbacks.h>
#include <regex>
#include <sstream>
namespace mp = multipass;
namespace mpt = mp::test;
using namespace testing;
struct TestSpinnerCallbacks : public Test
{
auto clearStreamMatcher()
{
static const std::regex clear_regex{
R"(\u001B\[2K\u001B\[0A\u001B\[0E|^$)"}; /* A "clear" stream should have nothing on the current
line and the cursor in the leftmost position */
return Truly([](const auto& str) {
return std::regex_match(str, clear_regex); // (gtest regex not cutting it on macOS)
});
}
std::ostringstream out, err;
std::istringstream in;
mpt::StubTerminal term{out, err, in};
mp::AnimatedSpinner spinner{out};
};
enum class CommonCallbackType
{
Logging,
Reply,
Iterative
};
struct TestLoggingSpinnerCallbacks : public TestSpinnerCallbacks, public WithParamInterface<CommonCallbackType>
{
std::function<void(const mp::MountReply&, grpc::ClientReaderWriterInterface<mp::MountRequest, mp::MountReply>*)>
make_callback()
{
switch (GetParam())
{
case CommonCallbackType::Logging:
return mp::make_logging_spinner_callback<mp::MountRequest, mp::MountReply>(spinner, err);
break;
case CommonCallbackType::Reply:
return mp::make_reply_spinner_callback<mp::MountRequest, mp::MountReply>(spinner, err);
break;
case CommonCallbackType::Iterative:
return mp::make_iterative_spinner_callback<mp::MountRequest, mp::MountReply>(spinner, term);
break;
default:
assert(false && "shouldn't be here");
}
}
};
TEST_P(TestLoggingSpinnerCallbacks, loggingSpinnerCallbackLogs)
{
constexpr auto log = "message in a bottle";
mp::MountReply reply;
reply.set_log_line(log);
make_callback()(reply, nullptr);
EXPECT_THAT(err.str(), StrEq(log));
EXPECT_THAT(out.str(), clearStreamMatcher()); /* this is not empty because print stops, stop clears, and clear
prints ANSI escape characters to clear the line */
}
TEST_P(TestLoggingSpinnerCallbacks, loggingSpinnerCallbackIgnoresEmptyLog)
{
mp::MountReply reply;
make_callback()(reply, nullptr);
EXPECT_THAT(err.str(), IsEmpty());
EXPECT_THAT(out.str(), clearStreamMatcher());
}
INSTANTIATE_TEST_SUITE_P(TestLoggingSpinnerCallbacks,
TestLoggingSpinnerCallbacks,
Values(CommonCallbackType::Logging, CommonCallbackType::Reply, CommonCallbackType::Iterative));
struct TestReplySpinnerCallbacks : public TestSpinnerCallbacks, public WithParamInterface<CommonCallbackType>
{
std::function<void(const mp::MountReply&, grpc::ClientReaderWriterInterface<mp::MountRequest, mp::MountReply>*)>
make_callback()
{
switch (GetParam())
{
case CommonCallbackType::Reply:
return mp::make_reply_spinner_callback<mp::MountRequest, mp::MountReply>(spinner, err);
break;
case CommonCallbackType::Iterative:
return mp::make_iterative_spinner_callback<mp::MountRequest, mp::MountReply>(spinner, term);
break;
default:
assert(false && "shouldn't be here");
throw std::runtime_error{"bad test instantiation"};
}
}
};
TEST_P(TestReplySpinnerCallbacks, replySpinnerCallbackUpdatesSpinnerMessage)
{
constexpr auto msg = "answer";
mp::MountReply reply;
reply.set_reply_message(msg);
make_callback()(reply, nullptr);
EXPECT_THAT(err.str(), IsEmpty());
EXPECT_THAT(out.str(), HasSubstr(msg));
}
TEST_P(TestReplySpinnerCallbacks, replySpinnerCallbackIgnoresEmptyMessage)
{
mp::MountReply reply;
make_callback()(reply, nullptr);
EXPECT_THAT(err.str(), IsEmpty());
EXPECT_THAT(out.str(), IsEmpty());
}
INSTANTIATE_TEST_SUITE_P(TestReplySpinnerCallbacks,
TestReplySpinnerCallbacks,
Values(CommonCallbackType::Reply, CommonCallbackType::Iterative));
TEST_F(TestSpinnerCallbacks, iterativeSpinnerCallbackHandlesPasswordRequest)
{
constexpr auto pwd = "xyz";
auto [mock_client_platform, guard] = mpt::MockClientPlatform::inject<StrictMock>();
mpt::MockClientReaderWriter<mp::RestartRequest, mp::RestartReply> mock_client;
mp::RestartReply reply;
reply.set_password_requested(true);
EXPECT_CALL(*mock_client_platform, get_password(&term)).WillOnce(Return(pwd));
EXPECT_CALL(mock_client, Write(Property(&mp::RestartRequest::password, StrEq(pwd)), _)).WillOnce(Return(true));
auto cb = mp::make_iterative_spinner_callback<mp::RestartRequest, mp::RestartReply>(spinner, term);
cb(reply, &mock_client);
EXPECT_THAT(err.str(), IsEmpty());
EXPECT_THAT(out.str(), clearStreamMatcher());
}
TEST_F(TestSpinnerCallbacks, confirmationCallbackAnswers)
{
constexpr auto key = "local.instance-name.bridged";
mpt::MockClientReaderWriter<mp::SetRequest, mp::SetReply> mock_client;
mp::SetReply reply;
reply.set_needs_authorization(true);
EXPECT_CALL(mock_client, Write(_, _)).WillOnce(Return(true));
auto callback = mp::make_confirmation_callback<mp::SetRequest, mp::SetReply>(term, key);
callback(reply, &mock_client);
EXPECT_THAT(err.str(), IsEmpty());
EXPECT_THAT(out.str(), clearStreamMatcher());
}
| 6,266
|
C++
|
.cpp
| 153
| 34.862745
| 120
| 0.695459
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,635
|
test_url_downloader.cpp
|
canonical_multipass/tests/test_url_downloader.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_file_ops.h"
#include "mock_logger.h"
#include "mock_network.h"
#include "temp_dir.h"
#include <multipass/exceptions/aborted_download_exception.h>
#include <multipass/exceptions/download_exception.h>
#include <QTimer>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace std::chrono_literals;
using namespace testing;
namespace
{
struct URLDownloader : public Test
{
URLDownloader()
{
mock_network_access_manager = std::make_unique<NiceMock<mpt::MockQNetworkAccessManager>>();
EXPECT_CALL(*mock_network_manager_factory, make_network_manager(_)).WillOnce([this](auto...) {
return std::move(mock_network_access_manager);
});
};
mpt::TempDir cache_dir;
mpt::MockNetworkManagerFactory::GuardedMock attr{mpt::MockNetworkManagerFactory::inject()};
mpt::MockNetworkManagerFactory* mock_network_manager_factory{attr.first};
std::unique_ptr<NiceMock<mpt::MockQNetworkAccessManager>> mock_network_access_manager;
const QUrl fake_url{"http://a.fake.url"};
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
};
} // namespace
TEST_F(URLDownloader, simpleDownloadReturnsExpectedData)
{
const QByteArray test_data{"The answer to everything is 42."};
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce(Return(mock_reply));
EXPECT_CALL(*mock_reply, readData(_, _))
.WillOnce([&test_data](char* data, auto) {
auto data_size{test_data.size()};
memcpy(data, test_data.constData(), data_size);
return data_size;
})
.WillOnce(Return(0));
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
logger_scope.mock_logger->expect_log(mpl::Level::trace,
fmt::format("Found {} in cache: false", fake_url.toString()));
mp::URLDownloader downloader(cache_dir.path(), 1s);
QTimer::singleShot(0, [&mock_reply] { mock_reply->finished(); });
auto downloaded_data = downloader.download(fake_url);
EXPECT_EQ(downloaded_data, test_data);
}
TEST_F(URLDownloader, simpleDownloadNetworkTimeoutTriesCache)
{
mpt::MockQNetworkReply* mock_reply_abort = new mpt::MockQNetworkReply();
mpt::MockQNetworkReply* mock_reply_cache = new mpt::MockQNetworkReply();
const QByteArray test_data{"The answer to everything is 42."};
EXPECT_CALL(*mock_reply_abort, abort()).WillOnce([&mock_reply_abort] { mock_reply_abort->abort_operation(); });
EXPECT_CALL(*mock_reply_cache, readData(_, _))
.WillOnce([&test_data](char* data, auto) {
auto data_size{test_data.size()};
memcpy(data, test_data.constData(), data_size);
return data_size;
})
.WillOnce(Return(0));
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillOnce(Return(mock_reply_abort))
.WillOnce([&mock_reply_cache](auto...) {
QTimer::singleShot(0, [&mock_reply_cache] {
mock_reply_cache->set_attribute(QNetworkRequest::SourceIsFromCacheAttribute, QVariant(true));
mock_reply_cache->readyRead();
mock_reply_cache->finished();
});
return mock_reply_cache;
});
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
logger_scope.mock_logger->expect_log(mpl::Level::trace,
fmt::format("Found {} in cache: true", fake_url.toString()));
logger_scope.mock_logger->expect_log(
mpl::Level::warning, fmt::format("Error getting {}: Network timeout - trying cache.", fake_url.toString()));
mp::URLDownloader downloader(cache_dir.path(), 10ms);
auto downloaded_data = downloader.download(fake_url);
EXPECT_EQ(downloaded_data, test_data);
}
TEST_F(URLDownloader, simpleDownloadProxyAuthenticationRequiredAborts)
{
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([&mock_reply](auto...) {
QTimer::singleShot(0, [&mock_reply] {
mock_reply->set_error(QNetworkReply::ProxyAuthenticationRequiredError, "Proxy authorization required");
mock_reply->finished();
});
return mock_reply;
});
mp::URLDownloader downloader(cache_dir.path(), 10ms);
MP_EXPECT_THROW_THAT(downloader.download(fake_url), mp::AbortedDownloadException,
mpt::match_what(StrEq("Proxy authorization required")));
}
TEST_F(URLDownloader, simpleDownloadAbortAllStopsDownload)
{
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
EXPECT_CALL(*mock_reply, abort()).WillOnce([&mock_reply] { mock_reply->abort_operation(); });
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([&mock_reply](auto...) {
QTimer::singleShot(0, [&mock_reply] { mock_reply->readyRead(); });
return mock_reply;
});
mp::URLDownloader downloader(cache_dir.path(), 10ms);
downloader.abort_all_downloads();
MP_EXPECT_THROW_THAT(downloader.download(fake_url), mp::AbortedDownloadException,
mpt::match_what(StrEq("Operation canceled")));
}
TEST_F(URLDownloader, fileDownloadNoErrorHasExpectedResults)
{
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
const QByteArray test_data{"This is some data to put in a file when downloaded."};
const int download_type{-1};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([&mock_reply, &test_data](auto...) {
QTimer::singleShot(0, [&mock_reply, &test_data] {
mock_reply->downloadProgress(test_data.size(), test_data.size());
mock_reply->readyRead();
mock_reply->finished();
});
return mock_reply;
});
EXPECT_CALL(*mock_reply, readData(_, _))
.WillOnce([&test_data](char* data, auto) {
auto data_size{test_data.size()};
memcpy(data, test_data.constData(), data_size);
return data_size;
})
.WillRepeatedly(Return(0));
bool progress_called{false};
auto progress_monitor = [download_type, &progress_called](int type, int progress) {
EXPECT_EQ(type, download_type);
EXPECT_EQ(progress, 100);
progress_called = true;
return true;
};
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
logger_scope.mock_logger->expect_log(mpl::Level::trace,
fmt::format("Found {} in cache: false", fake_url.toString()));
mp::URLDownloader downloader(cache_dir.path(), 10ms);
mpt::TempDir file_dir;
QString download_file{file_dir.path() + "/foo.txt"};
downloader.download_to(fake_url, download_file, test_data.size(), download_type, progress_monitor);
EXPECT_TRUE(progress_called);
QFile test_file{download_file};
ASSERT_TRUE(test_file.exists());
test_file.open(QIODevice::ReadOnly);
auto file_data = test_file.readAll();
EXPECT_EQ(file_data, test_data);
}
TEST_F(URLDownloader, fileDownloadErrorTriesCache)
{
mpt::MockQNetworkReply* mock_reply_abort = new mpt::MockQNetworkReply();
mpt::MockQNetworkReply* mock_reply_cache = new mpt::MockQNetworkReply();
const QByteArray test_data{"This is some data to put in a file when downloaded."};
EXPECT_CALL(*mock_reply_abort, abort()).WillOnce([&mock_reply_abort] { mock_reply_abort->abort_operation(); });
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillOnce(Return(mock_reply_abort))
.WillOnce([&mock_reply_cache, &test_data](auto...) {
QTimer::singleShot(0, [&mock_reply_cache, &test_data] {
mock_reply_cache->set_attribute(QNetworkRequest::SourceIsFromCacheAttribute, QVariant(true));
mock_reply_cache->downloadProgress(test_data.size(), test_data.size());
mock_reply_cache->readyRead();
mock_reply_cache->finished();
});
return mock_reply_cache;
});
EXPECT_CALL(*mock_reply_cache, readData(_, _))
.WillOnce([&test_data](char* data, auto) {
auto data_size{test_data.size()};
memcpy(data, test_data.constData(), data_size);
return data_size;
})
.WillRepeatedly(Return(0));
auto progress_monitor = [](auto...) { return true; };
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
logger_scope.mock_logger->expect_log(mpl::Level::trace,
fmt::format("Found {} in cache: true", fake_url.toString()));
logger_scope.mock_logger->expect_log(
mpl::Level::warning, fmt::format("Error getting {}: Network timeout - trying cache.", fake_url.toString()));
mp::URLDownloader downloader(cache_dir.path(), 10ms);
mpt::TempDir file_dir;
QString download_file{file_dir.path() + "/foo.txt"};
downloader.download_to(fake_url, download_file, test_data.size(), -1, progress_monitor);
QFile test_file{download_file};
ASSERT_TRUE(test_file.exists());
test_file.open(QIODevice::ReadOnly);
auto file_data = test_file.readAll();
EXPECT_EQ(file_data, test_data);
}
TEST_F(URLDownloader, fileDownloadMonitorReturnFalseAborts)
{
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
EXPECT_CALL(*mock_reply, abort()).WillOnce([&mock_reply] { mock_reply->abort_operation(); });
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([&mock_reply](auto...) {
QTimer::singleShot(0, [&mock_reply] { mock_reply->downloadProgress(1000, 1000); });
return mock_reply;
});
auto progress_monitor = [](auto...) { return false; };
mp::URLDownloader downloader(cache_dir.path(), 10ms);
mpt::TempDir file_dir;
QString download_file{file_dir.path() + "/foo.txt"};
MP_EXPECT_THROW_THAT(downloader.download_to(fake_url, download_file, -1, -1, progress_monitor),
mp::AbortedDownloadException, mpt::match_what(StrEq("Operation canceled")));
EXPECT_FALSE(QFile::exists(download_file));
}
TEST_F(URLDownloader, fileDownloadZeroBytesReceivedDoesNotCallMonitor)
{
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([&mock_reply](auto...) {
QTimer::singleShot(0, [&mock_reply] {
mock_reply->downloadProgress(0, 1000);
mock_reply->finished();
});
return mock_reply;
});
EXPECT_CALL(*mock_reply, readData(_, _)).WillRepeatedly(Return(0));
bool progress_called{false};
auto progress_monitor = [&progress_called](auto...) {
progress_called = true;
return true;
};
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
logger_scope.mock_logger->expect_log(mpl::Level::trace,
fmt::format("Found {} in cache: false", fake_url.toString()));
mp::URLDownloader downloader(cache_dir.path(), 10ms);
mpt::TempDir file_dir;
QString download_file{file_dir.path() + "/foo.txt"};
downloader.download_to(fake_url, download_file, -1, -1, progress_monitor);
EXPECT_FALSE(progress_called);
}
TEST_F(URLDownloader, fileDownloadAbortAllStopDownload)
{
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
EXPECT_CALL(*mock_reply, abort()).WillOnce([&mock_reply] { mock_reply->abort_operation(); });
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([&mock_reply](auto...) {
QTimer::singleShot(0, [&mock_reply] {
mock_reply->readyRead();
mock_reply->finished();
});
return mock_reply;
});
auto progress_monitor = [](auto...) { return true; };
mp::URLDownloader downloader(cache_dir.path(), 10ms);
downloader.abort_all_downloads();
mpt::TempDir file_dir;
QString download_file{file_dir.path() + "/foo.txt"};
MP_EXPECT_THROW_THAT(downloader.download_to(fake_url, download_file, -1, -1, progress_monitor),
mp::AbortedDownloadException, mpt::match_what(StrEq("Operation canceled")));
}
TEST_F(URLDownloader, fileDownloadUnknownBytesSetToQueriedSize)
{
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
const QByteArray test_data{"This is some data to put in a file when downloaded."};
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([&mock_reply, &test_data](auto...) {
QTimer::singleShot(0, [&mock_reply, &test_data] {
mock_reply->downloadProgress(test_data.size(), -1);
mock_reply->readyRead();
mock_reply->finished();
});
return mock_reply;
});
EXPECT_CALL(*mock_reply, readData(_, _))
.WillOnce([&test_data](char* data, auto) {
auto data_size{test_data.size()};
memcpy(data, test_data.constData(), data_size);
return data_size;
})
.WillRepeatedly(Return(0));
auto progress_monitor = [](auto, int progress) {
EXPECT_EQ(progress, 100);
return true;
};
logger_scope.mock_logger->screen_logs(mpl::Level::trace);
logger_scope.mock_logger->expect_log(mpl::Level::trace,
fmt::format("Found {} in cache: false", fake_url.toString()));
mp::URLDownloader downloader(cache_dir.path(), 10ms);
mpt::TempDir file_dir;
QString download_file{file_dir.path() + "/foo.txt"};
downloader.download_to(fake_url, download_file, test_data.size(), -1, progress_monitor);
}
TEST_F(URLDownloader, fileDownloadTimeoutDoesNotWriteFile)
{
mpt::MockQNetworkReply* mock_reply_abort1 = new mpt::MockQNetworkReply();
mpt::MockQNetworkReply* mock_reply_abort2 = new mpt::MockQNetworkReply();
bool ready_read_fired{false};
EXPECT_CALL(*mock_reply_abort1, abort()).WillOnce([&mock_reply_abort1, &ready_read_fired] {
mock_reply_abort1->abort_operation();
// Fake data becoming ready after the network timeout
mock_reply_abort1->readyRead();
ready_read_fired = true;
});
EXPECT_CALL(*mock_reply_abort2, abort()).WillOnce([&mock_reply_abort2] { mock_reply_abort2->abort_operation(); });
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _))
.WillOnce(Return(mock_reply_abort1))
.WillOnce(Return(mock_reply_abort2));
auto progress_monitor = [](auto...) { return true; };
logger_scope.mock_logger->screen_logs(mpl::Level::warning);
logger_scope.mock_logger->expect_log(
mpl::Level::warning, fmt::format("Error getting {}: Network timeout - trying cache.", fake_url.toString()));
mp::URLDownloader downloader(cache_dir.path(), 10ms);
mpt::TempDir file_dir;
QString download_file{file_dir.path() + "/foo.txt"};
EXPECT_THROW(downloader.download_to(fake_url, download_file, -1, -1, progress_monitor), mp::DownloadException);
EXPECT_TRUE(ready_read_fired);
EXPECT_FALSE(QFile::exists(download_file));
}
TEST_F(URLDownloader, fileDownloadWriteFailsLogsErrorAndThrows)
{
const QByteArray test_data{"This is some data to put in a file when downloaded."};
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
EXPECT_CALL(*mock_reply, abort()).WillOnce([&mock_reply] { mock_reply->abort_operation(); });
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([&mock_reply](auto...) {
QTimer::singleShot(0, [&mock_reply] {
mock_reply->readyRead();
mock_reply->finished();
});
return mock_reply;
});
EXPECT_CALL(*mock_reply, readData(_, _))
.WillOnce([&test_data](char* data, auto) {
auto data_size{test_data.size()};
memcpy(data, test_data.constData(), data_size);
return data_size;
})
.WillRepeatedly(Return(0));
auto progress_monitor = [](auto...) { return true; };
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, write(_, _)).WillOnce(Return(-1));
logger_scope.mock_logger->screen_logs(mpl::Level::error);
logger_scope.mock_logger->expect_log(mpl::Level::error, "error writing image:");
mp::URLDownloader downloader(cache_dir.path(), 10ms);
mpt::TempDir file_dir;
QString download_file{file_dir.path() + "/foo.txt"};
EXPECT_THROW(downloader.download_to(fake_url, download_file, -1, -1, progress_monitor),
mp::AbortedDownloadException);
}
TEST_F(URLDownloader, lastModifiedHeaderReturnsExpectedData)
{
const QDateTime date_time{QDateTime::currentDateTimeUtc()};
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
mock_reply->set_header(QNetworkRequest::LastModifiedHeader, QVariant(date_time));
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce(Return(mock_reply));
mp::URLDownloader downloader(cache_dir.path(), 1s);
QTimer::singleShot(0, [&mock_reply] { mock_reply->finished(); });
auto last_modified = downloader.last_modified(fake_url);
EXPECT_EQ(date_time, last_modified);
}
TEST_F(URLDownloader, lastModifiedHeaderTimeoutThrows)
{
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
EXPECT_CALL(*mock_reply, abort()).WillOnce([&mock_reply] { mock_reply->abort_operation(); });
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce(Return(mock_reply));
logger_scope.mock_logger->screen_logs(mpl::Level::warning);
logger_scope.mock_logger->expect_log(
mpl::Level::warning, fmt::format("Cannot retrieve headers for {}: Network timeout", fake_url.toString()));
mp::URLDownloader downloader(cache_dir.path(), 10ms);
EXPECT_THROW(downloader.last_modified(fake_url), mp::DownloadException);
}
TEST_F(URLDownloader, lastModifiedHeaderErrorThrows)
{
const QString error_msg{"Host not found"};
mpt::MockQNetworkReply* mock_reply = new mpt::MockQNetworkReply();
EXPECT_CALL(*mock_network_access_manager, createRequest(_, _, _)).WillOnce([&mock_reply, &error_msg](auto...) {
QTimer::singleShot(0, [&mock_reply, &error_msg] {
mock_reply->set_error(QNetworkReply::HostNotFoundError, error_msg);
mock_reply->finished();
});
return mock_reply;
});
logger_scope.mock_logger->screen_logs(mpl::Level::warning);
logger_scope.mock_logger->expect_log(
mpl::Level::warning, fmt::format("Cannot retrieve headers for {}: {}", fake_url.toString(), error_msg));
mp::URLDownloader downloader(cache_dir.path(), 1s);
EXPECT_THROW(downloader.last_modified(fake_url), mp::DownloadException);
}
| 19,661
|
C++
|
.cpp
| 394
| 42.751269
| 118
| 0.66482
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,636
|
mock_ssh_client.cpp
|
canonical_multipass/tests/mock_ssh_client.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_ssh_client.h"
extern "C" {
IMPL_MOCK_DEFAULT(1, ssh_channel_request_shell);
IMPL_MOCK_DEFAULT(1, ssh_channel_request_pty);
IMPL_MOCK_DEFAULT(3, ssh_channel_change_pty_size);
}
| 820
|
C++
|
.cpp
| 22
| 35.545455
| 72
| 0.755332
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,637
|
test_with_mocked_bin_path.cpp
|
canonical_multipass/tests/test_with_mocked_bin_path.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "test_with_mocked_bin_path.h"
#include "path.h"
#include <QDir>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
void mpt::TestWithMockedBinPath::SetUp()
{
QByteArray new_path =
QByteArray::fromStdString(mpt::mock_bin_path()) + QDir::listSeparator().toLatin1() + qgetenv("PATH");
env = std::make_unique<SetEnvScope>("PATH", new_path);
}
void mpt::TestWithMockedBinPath::TearDown()
{
env.reset();
}
| 1,095
|
C++
|
.cpp
| 32
| 31.96875
| 109
| 0.741021
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,638
|
test_client_cert_store.cpp
|
canonical_multipass/tests/test_client_cert_store.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "file_operations.h"
#include "mock_file_ops.h"
#include "mock_logger.h"
#include "mock_utils.h"
#include "temp_dir.h"
#include <multipass/client_cert_store.h>
#include <multipass/constants.h>
#include <multipass/utils.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
constexpr auto cert_data = "-----BEGIN CERTIFICATE-----\n"
"MIIBUjCB+AIBKjAKBggqhkjOPQQDAjA1MQswCQYDVQQGEwJDQTESMBAGA1UECgwJ\n"
"Q2Fub25pY2FsMRIwEAYDVQQDDAlsb2NhbGhvc3QwHhcNMTgwNjIxMTM0MjI5WhcN\n"
"MTkwNjIxMTM0MjI5WjA1MQswCQYDVQQGEwJDQTESMBAGA1UECgwJQ2Fub25pY2Fs\n"
"MRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQA\n"
"FGNAqq7c5IMDeQ/cV4+EmogmkfpbTLSPfXgXVLHRsvL04xUAkqGpL+eyGFVE6dqa\n"
"J7sAPJJwlVj1xD0r5DX5MAoGCCqGSM49BAMCA0kAMEYCIQCvI0PYv9f201fbe4LP\n"
"BowTeYWSqMQtLNjvZgd++AAGhgIhALNPW+NRSKCXwadiIFgpbjPInLPqXPskLWSc\n"
"aXByaQyt\n"
"-----END CERTIFICATE-----\n";
constexpr auto cert2_data = "-----BEGIN CERTIFICATE-----\n"
"MIIBizCCATECBBv4mFwwCgYIKoZIzj0EAwIwUDELMAkGA1UEBhMCVVMxEjAQBgNV\n"
"BAoMCUNhbm9uaWNhbDEtMCsGA1UEAwwkNThhZGNkMjQtNDJmMi00ZjI0LWExYTYt\n"
"ODk5MDY3ZTdkODhkMB4XDTIxMTEwOTE1MDk0NloXDTIyMTEwOTE1MDk0NlowUDEL\n"
"MAkGA1UEBhMCVVMxEjAQBgNVBAoMCUNhbm9uaWNhbDEtMCsGA1UEAwwkNThhZGNk\n"
"MjQtNDJmMi00ZjI0LWExYTYtODk5MDY3ZTdkODhkMFkwEwYHKoZIzj0CAQYIKoZI\n"
"zj0DAQcDQgAEqybAYAPImXZX5tZSJi6oyvkt4S/sZbk+mkoeg8t9G2lLbMDSG6W1\n"
"yN7oKVc/A6QJ4SO7FmTAr0ruAYQkBo65czAKBggqhkjOPQQDAgNIADBFAiEA/J34\n"
"z4dITtBKaWWUVpGt9Ih2ZCzwinvAh3w3eUaI5hECIFiT1JaL6QRa3holvTRpDm5O\n"
"5ZaxnIFvH2NZ/dCmFWQT\n"
"-----END CERTIFICATE-----\n";
struct ClientCertStore : public testing::Test
{
ClientCertStore()
{
cert_dir = MP_UTILS.make_dir(temp_dir.path(), mp::authenticated_certs_dir,
QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);
}
mpt::TempDir temp_dir;
mp::Path cert_dir;
};
} // namespace
TEST_F(ClientCertStore, returns_empty_chain_if_no_certificate_found)
{
mp::ClientCertStore cert_store{temp_dir.path()};
auto cert_chain = cert_store.PEM_cert_chain();
EXPECT_TRUE(cert_chain.empty());
}
TEST_F(ClientCertStore, returns_persisted_certificate_chain)
{
mp::ClientCertStore cert_store{temp_dir.path()};
const QDir dir{cert_dir};
const auto cert_path = dir.filePath("multipass_client_certs.pem");
mpt::make_file_with_content(cert_path, cert_data);
auto cert_chain = cert_store.PEM_cert_chain();
EXPECT_THAT(cert_chain, StrEq(cert_data));
}
TEST_F(ClientCertStore, add_cert_throws_on_invalid_data)
{
mp::ClientCertStore cert_store{temp_dir.path()};
MP_EXPECT_THROW_THAT(cert_store.add_cert("not a certificate"), std::runtime_error,
mpt::match_what(StrEq("invalid certificate data")));
}
TEST_F(ClientCertStore, add_cert_stores_certificate)
{
mp::ClientCertStore cert_store{temp_dir.path()};
EXPECT_NO_THROW(cert_store.add_cert(cert_data));
const auto content = cert_store.PEM_cert_chain();
EXPECT_THAT(content, StrEq(cert_data));
}
TEST_F(ClientCertStore, verifyCertEmptyStoreReturnsFalse)
{
mp::ClientCertStore cert_store{temp_dir.path()};
ASSERT_TRUE(cert_store.PEM_cert_chain().empty());
EXPECT_FALSE(cert_store.verify_cert(cert_data));
const auto content = cert_store.PEM_cert_chain();
EXPECT_TRUE(content.empty());
}
TEST_F(ClientCertStore, verifyCertInStoreReturnsTrue)
{
const QDir dir{cert_dir};
const auto cert_path = dir.filePath("multipass_client_certs.pem");
mpt::make_file_with_content(cert_path, cert_data);
mp::ClientCertStore cert_store{temp_dir.path()};
ASSERT_FALSE(cert_store.PEM_cert_chain().empty());
EXPECT_TRUE(cert_store.verify_cert(cert_data));
}
TEST_F(ClientCertStore, addCertAlreadyExistingDoesNotAddAgain)
{
const QDir dir{cert_dir};
const auto cert_path = dir.filePath("multipass_client_certs.pem");
mpt::make_file_with_content(cert_path, cert_data);
mp::ClientCertStore cert_store{temp_dir.path()};
ASSERT_FALSE(cert_store.PEM_cert_chain().empty());
EXPECT_NO_THROW(cert_store.add_cert(cert_data));
const auto content = cert_store.PEM_cert_chain();
EXPECT_EQ(content, cert_data);
}
TEST_F(ClientCertStore, addCertWithExistingCertPersistsCerts)
{
const QDir dir{cert_dir};
const auto cert_path = dir.filePath("multipass_client_certs.pem");
mpt::make_file_with_content(cert_path, cert_data);
mp::ClientCertStore cert_store{temp_dir.path()};
ASSERT_FALSE(cert_store.PEM_cert_chain().empty());
cert_store.add_cert(cert2_data);
auto all_certs = std::string(cert_data) + std::string(cert2_data);
const auto content = cert_store.PEM_cert_chain();
EXPECT_EQ(content, all_certs);
}
TEST_F(ClientCertStore, storeEmptyReturnsTrueWhenNoCerts)
{
mp::ClientCertStore cert_store{temp_dir.path()};
EXPECT_TRUE(cert_store.empty());
}
TEST_F(ClientCertStore, storeEmptyReturnsFalseWhenCertExists)
{
const QDir dir{cert_dir};
const auto cert_path = dir.filePath("multipass_client_certs.pem");
mpt::make_file_with_content(cert_path, cert_data);
mp::ClientCertStore cert_store{temp_dir.path()};
EXPECT_FALSE(cert_store.empty());
}
TEST_F(ClientCertStore, openingFileForWritingFailsAndThrows)
{
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(false));
mp::ClientCertStore cert_store{temp_dir.path()};
MP_EXPECT_THROW_THAT(cert_store.add_cert(cert_data), std::runtime_error,
mpt::match_what(StrEq("failed to create file to store certificate")));
}
TEST_F(ClientCertStore, writingFileFailsAndThrows)
{
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce([](QFileDevice& file, QIODevice::OpenMode mode) {
return file.open(mode);
});
EXPECT_CALL(*mock_file_ops, write(_, _)).WillOnce(Return(-1));
EXPECT_CALL(*mock_file_ops, commit).WillOnce(Return(false));
mp::ClientCertStore cert_store{temp_dir.path()};
MP_EXPECT_THROW_THAT(cert_store.add_cert(cert_data), std::runtime_error,
mpt::match_what(StrEq("failed to write certificate")));
}
| 7,481
|
C++
|
.cpp
| 164
| 38.646341
| 111
| 0.695239
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,639
|
mock_sftpserver.cpp
|
canonical_multipass/tests/mock_sftpserver.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_sftpserver.h"
extern "C"
{
IMPL_MOCK_DEFAULT(2, sftp_server_new);
IMPL_MOCK_DEFAULT(1, sftp_server_init);
IMPL_MOCK_DEFAULT(3, sftp_reply_status);
IMPL_MOCK_DEFAULT(2, sftp_reply_attr);
IMPL_MOCK_DEFAULT(3, sftp_reply_data);
IMPL_MOCK_DEFAULT(3, sftp_reply_name);
IMPL_MOCK_DEFAULT(1, sftp_reply_names);
IMPL_MOCK_DEFAULT(4, sftp_reply_names_add);
IMPL_MOCK_DEFAULT(2, sftp_reply_handle);
IMPL_MOCK_DEFAULT(1, sftp_get_client_message);
IMPL_MOCK_DEFAULT(1, sftp_client_message_free);
IMPL_MOCK_DEFAULT(1, sftp_client_message_get_data);
IMPL_MOCK_DEFAULT(1, sftp_client_message_get_filename);
IMPL_MOCK_DEFAULT(2, sftp_handle);
IMPL_MOCK_DEFAULT(2, sftp_handle_alloc);
IMPL_MOCK_DEFAULT(2, sftp_handle_remove);
}
| 1,420
|
C++
|
.cpp
| 36
| 36.222222
| 72
| 0.728127
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,640
|
test_daemon_umount.cpp
|
canonical_multipass/tests/test_daemon_umount.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "daemon_test_fixture.h"
#include "mock_logger.h"
#include "mock_mount_handler.h"
#include "mock_platform.h"
#include "mock_server_reader_writer.h"
#include "mock_settings.h"
#include "mock_virtual_machine.h"
#include "mock_vm_image_vault.h"
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct TestDaemonUmount : public mpt::DaemonTestFixture
{
void SetUp() override
{
EXPECT_CALL(mock_settings, register_handler).WillRepeatedly(Return(nullptr));
EXPECT_CALL(mock_settings, unregister_handler).Times(AnyNumber());
config_builder.vault = std::make_unique<NiceMock<mpt::MockVMImageVault>>();
mock_factory = use_a_mock_vm_factory();
}
mpt::MockVirtualMachineFactory* mock_factory;
const std::string mock_instance_name{"real-zebraphant"};
const std::string mac_addr{"52:54:00:73:76:28"};
const std::string fake_target_path{"/home/ubuntu/foo"};
std::vector<mp::NetworkInterface> extra_interfaces;
mpt::MockPlatform::GuardedMock platform_attr{mpt::MockPlatform::inject<NiceMock>()};
mpt::MockPlatform* mock_platform = platform_attr.first;
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
};
} // namespace
TEST_F(TestDaemonUmount, missingInstanceFails)
{
mp::Daemon daemon{config_builder.build()};
const auto fake_instance = "fake";
mp::UmountRequest request;
auto entry = request.add_target_paths();
entry->set_instance_name(fake_instance);
auto status = call_daemon_slot(daemon, &mp::Daemon::umount, request,
StrictMock<mpt::MockServerReaderWriter<mp::UmountReply, mp::UmountRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), HasSubstr(fmt::format("instance '{}' does not exist", fake_instance)));
}
TEST_F(TestDaemonUmount, noTargetsUnmountsAll)
{
std::unordered_map<std::string, mp::VMMount> mounts{
{fake_target_path, {"foo", {}, {}, mp::VMMount::MountType::Native}},
{fake_target_path + "2", {"foo2", {}, {}, mp::VMMount::MountType::Native}}};
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces, mounts));
config_builder.data_directory = temp_dir->path();
auto mock_mount_handler = std::make_unique<mpt::MockMountHandler>();
auto mock_mount_handler2 = std::make_unique<mpt::MockMountHandler>();
EXPECT_CALL(*mock_mount_handler, is_active).WillOnce(Return(true));
EXPECT_CALL(*mock_mount_handler2, is_active).WillOnce(Return(true));
EXPECT_CALL(*mock_mount_handler, deactivate_impl(false));
EXPECT_CALL(*mock_mount_handler2, deactivate_impl(false));
auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_vm, make_native_mount_handler(fake_target_path, _))
.WillOnce(Return(std::move(mock_mount_handler)));
EXPECT_CALL(*mock_vm, make_native_mount_handler(fake_target_path + "2", _))
.WillOnce(Return(std::move(mock_mount_handler2)));
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm)));
mp::Daemon daemon{config_builder.build()};
mp::UmountRequest request;
auto entry = request.add_target_paths();
entry->set_instance_name(mock_instance_name);
auto status = call_daemon_slot(daemon, &mp::Daemon::umount, request,
StrictMock<mpt::MockServerReaderWriter<mp::UmountReply, mp::UmountRequest>>{});
EXPECT_TRUE(status.ok());
}
TEST_F(TestDaemonUmount, umountWithTargetOnlyStopsItsHandlers)
{
std::unordered_map<std::string, mp::VMMount> mounts{
{fake_target_path, {"foo", {}, {}, mp::VMMount::MountType::Native}},
{fake_target_path + "2", {"foo2", {}, {}, mp::VMMount::MountType::Native}},
{fake_target_path + "3", {"foo3", {}, {}, mp::VMMount::MountType::Native}}};
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces, mounts));
config_builder.data_directory = temp_dir->path();
auto mock_mount_handler = std::make_unique<mpt::MockMountHandler>();
auto mock_mount_handler2 = std::make_unique<mpt::MockMountHandler>();
auto mock_mount_handler3 = std::make_unique<mpt::MockMountHandler>();
EXPECT_CALL(*mock_mount_handler, is_active).WillOnce(Return(true));
EXPECT_CALL(*mock_mount_handler2, is_active).Times(0);
EXPECT_CALL(*mock_mount_handler3, is_active).WillOnce(Return(true));
EXPECT_CALL(*mock_mount_handler, deactivate_impl(false));
EXPECT_CALL(*mock_mount_handler2, deactivate_impl(false)).Times(0);
EXPECT_CALL(*mock_mount_handler3, deactivate_impl(false));
auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_vm, make_native_mount_handler(fake_target_path, _))
.WillOnce(Return(std::move(mock_mount_handler)));
EXPECT_CALL(*mock_vm, make_native_mount_handler(fake_target_path + "2", _))
.WillOnce(Return(std::move(mock_mount_handler2)));
EXPECT_CALL(*mock_vm, make_native_mount_handler(fake_target_path + "3", _))
.WillOnce(Return(std::move(mock_mount_handler3)));
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm)));
mp::Daemon daemon{config_builder.build()};
mp::UmountRequest request;
auto entry = request.add_target_paths();
entry->set_instance_name(mock_instance_name);
entry->set_target_path(fake_target_path);
auto entry2 = request.add_target_paths();
entry2->set_instance_name(mock_instance_name);
entry2->set_target_path(fake_target_path + "3");
auto status = call_daemon_slot(daemon, &mp::Daemon::umount, request,
StrictMock<mpt::MockServerReaderWriter<mp::UmountReply, mp::UmountRequest>>{});
EXPECT_TRUE(status.ok());
}
TEST_F(TestDaemonUmount, mountNotFound)
{
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces));
config_builder.data_directory = temp_dir->path();
EXPECT_CALL(*mock_factory, create_virtual_machine)
.WillOnce(Return(std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name)));
mp::Daemon daemon{config_builder.build()};
mp::UmountRequest request;
auto entry = request.add_target_paths();
entry->set_instance_name(mock_instance_name);
entry->set_target_path(fake_target_path);
auto status = call_daemon_slot(daemon, &mp::Daemon::umount, request,
StrictMock<mpt::MockServerReaderWriter<mp::UmountReply, mp::UmountRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(),
HasSubstr(fmt::format("path \"{}\" is not mounted in '{}'", fake_target_path, mock_instance_name)));
}
TEST_F(TestDaemonUmount, stoppingMountFails)
{
std::unordered_map<std::string, mp::VMMount> mounts{
{fake_target_path, {"foo", {}, {}, mp::VMMount::MountType::Native}}};
const auto [temp_dir, filename] = plant_instance_json(fake_json_contents(mac_addr, extra_interfaces, mounts));
config_builder.data_directory = temp_dir->path();
auto error = "device is busy";
auto mock_mount_handler = std::make_unique<mpt::MockMountHandler>();
EXPECT_CALL(*mock_mount_handler, is_active).WillOnce(Return(true));
EXPECT_CALL(*mock_mount_handler, deactivate_impl(false)).WillOnce(Throw(std::runtime_error{error}));
auto mock_vm = std::make_unique<NiceMock<mpt::MockVirtualMachine>>(mock_instance_name);
EXPECT_CALL(*mock_vm, make_native_mount_handler(fake_target_path, _))
.WillOnce(Return(std::move(mock_mount_handler)));
EXPECT_CALL(*mock_factory, create_virtual_machine).WillOnce(Return(std::move(mock_vm)));
mp::Daemon daemon{config_builder.build()};
mp::UmountRequest request;
auto entry = request.add_target_paths();
entry->set_instance_name(mock_instance_name);
auto status = call_daemon_slot(daemon, &mp::Daemon::umount, request,
StrictMock<mpt::MockServerReaderWriter<mp::UmountReply, mp::UmountRequest>>{});
EXPECT_EQ(status.error_code(), grpc::StatusCode::INVALID_ARGUMENT);
EXPECT_THAT(status.error_message(), HasSubstr(fmt::format("failed to unmount \"{}\" from '{}': {}",
fake_target_path, mock_instance_name, error)));
}
| 9,313
|
C++
|
.cpp
| 167
| 49.808383
| 116
| 0.696966
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,641
|
stub_process_factory.cpp
|
canonical_multipass/tests/stub_process_factory.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "stub_process_factory.h"
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace ::testing;
namespace
{
class StubProcess : public mp::Process
{
public:
StubProcess(std::unique_ptr<mp::ProcessSpec>&& spec,
std::vector<mpt::StubProcessFactory::ProcessInfo>& process_list)
{
mpt::StubProcessFactory::ProcessInfo p{spec->program(), spec->arguments()};
process_list.emplace_back(p);
}
QString program() const override
{
return "";
}
QStringList arguments() const override
{
return {};
}
QString working_directory() const override
{
return "";
}
QProcessEnvironment process_environment() const override
{
return QProcessEnvironment();
}
qint64 process_id() const override
{
return 0;
}
void start() override
{
emit started();
}
void terminate() override
{
mp::ProcessState exit_state{0, std::nullopt};
emit finished(exit_state);
}
void kill() override
{
mp::ProcessState exit_state{std::nullopt, mp::ProcessState::Error{QProcess::Crashed, QStringLiteral("")}};
emit finished(exit_state);
}
bool wait_for_started(int msecs = 30000) override
{
return true;
}
bool wait_for_finished(int msecs = 30000) override
{
return false;
}
bool wait_for_ready_read(int msecs = 30000) override
{
return true;
}
bool running() const override
{
return true;
}
mp::ProcessState process_state() const override
{
return mp::ProcessState();
}
QString error_string() const override
{
return {};
}
QByteArray read_all_standard_output() override
{
return "";
}
QByteArray read_all_standard_error() override
{
return "";
}
qint64 write(const QByteArray& data) override
{
return 0;
}
void close_write_channel() override
{
}
void set_process_channel_mode(QProcess::ProcessChannelMode) override
{
}
mp::ProcessState execute(const int /*timeout*/ = 3000) override
{
mp::ProcessState process_state;
process_state.exit_code = 0;
return process_state;
}
void setup_child_process() override
{
}
};
} // namespace
std::unique_ptr<mp::Process> mpt::StubProcessFactory::create_process(std::unique_ptr<mp::ProcessSpec>&& spec) const
{
return std::make_unique<StubProcess>(std::move(spec),
const_cast<std::vector<mpt::StubProcessFactory::ProcessInfo>&>(process_list));
}
std::unique_ptr<mp::test::StubProcessFactory::Scope> mp::test::StubProcessFactory::Inject()
{
ProcessFactory::reset(); // cannot mock unless singleton reset
ProcessFactory::mock<StubProcessFactory>();
return std::make_unique<mp::test::StubProcessFactory::Scope>();
}
mpt::StubProcessFactory::Scope::~Scope()
{
ProcessFactory::reset();
}
std::vector<mpt::StubProcessFactory::ProcessInfo> mpt::StubProcessFactory::Scope::process_list()
{
return stub_instance().process_list;
}
mpt::StubProcessFactory& mpt::StubProcessFactory::stub_instance()
{
return dynamic_cast<mpt::StubProcessFactory&>(instance());
}
| 3,953
|
C++
|
.cpp
| 141
| 22.921986
| 119
| 0.666051
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,642
|
test_sftp_utils.cpp
|
canonical_multipass/tests/test_sftp_utils.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_file_ops.h"
#include "mock_sftp.h"
#include "mock_ssh.h"
#include <multipass/ssh/sftp_utils.h>
#include <fmt/std.h>
namespace mp = multipass;
namespace mpt = multipass::test;
namespace fs = mp::fs;
using namespace testing;
namespace
{
auto get_dummy_attr(const char* name, uint8_t type)
{
auto attr = static_cast<sftp_attributes_struct*>(calloc(1, sizeof(struct sftp_attributes_struct)));
attr->name = strdup(name);
attr->type = type;
return attr;
}
} // namespace
struct SFTPUtils : testing::Test
{
mpt::MockFileOps::GuardedMock mock_file_ops_guard{mpt::MockFileOps::inject()};
mpt::MockFileOps* mock_file_ops{mock_file_ops_guard.first};
fs::path source_path = "source/path";
fs::path target_path = "target/path";
};
TEST_F(SFTPUtils, get_full_local_file_target__target_is_dir_child_is_not)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path / source_path.filename(), _)).WillOnce(Return(false));
EXPECT_EQ(MP_SFTPUTILS.get_local_file_target(source_path, target_path, false),
target_path / source_path.filename());
}
TEST_F(SFTPUtils, get_full_local_file_target__target_exists_not_dir)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path, _)).WillOnce(Return(false));
EXPECT_EQ(MP_SFTPUTILS.get_local_file_target(source_path, target_path, false), target_path);
}
TEST_F(SFTPUtils, get_full_local_file_target__target_not_exists_parent_does)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops, exists(target_path.parent_path(), _)).WillOnce(Return(true));
EXPECT_EQ(MP_SFTPUTILS.get_local_file_target(source_path, target_path, false), target_path);
}
TEST_F(SFTPUtils, get_full_local_file_target__target_not_exists_parent_does_recursive_fail)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce(Return(false));
auto err = std::make_error_code(std::errc::permission_denied);
EXPECT_CALL(*mock_file_ops, create_directories(target_path.parent_path(), _))
.WillOnce([&](auto, std::error_code& e) {
e = err;
return false;
});
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_local_file_target(source_path, target_path, true), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot create local directory {}: {}",
target_path.parent_path(), err.message()))));
}
TEST_F(SFTPUtils, get_full_local_file_target__target_not_exists_parent_neither)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops, exists(target_path.parent_path(), _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_local_file_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq("local target does not exist")));
}
TEST_F(SFTPUtils, get_full_local_file_target__target_is_dir_child_is_too)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path / source_path.filename(), _)).WillOnce(Return(true));
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_local_file_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot overwrite local directory {} with non-directory",
target_path / source_path.filename()))));
}
TEST_F(SFTPUtils, get_full_local_file_target__cannot_access_target)
{
auto err = std::make_error_code(std::errc::permission_denied);
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce([&](auto, std::error_code& e) {
e = err;
return false;
});
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_local_file_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot access {}: {}", target_path, err.message()))));
}
TEST_F(SFTPUtils, get_full_local_file_target__cannot_access_parent)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce(Return(false));
auto err = std::make_error_code(std::errc::permission_denied);
EXPECT_CALL(*mock_file_ops, exists(target_path.parent_path(), _)).WillOnce([&](auto, std::error_code& e) {
e = err;
return false;
});
MP_EXPECT_THROW_THAT(
MP_SFTPUTILS.get_local_file_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot access {}: {}", target_path.parent_path(), err.message()))));
}
TEST_F(SFTPUtils, get_full_local_file_target__cannot_access_child)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path, _)).WillOnce(Return(true));
auto err = std::make_error_code(std::errc::permission_denied);
EXPECT_CALL(*mock_file_ops, is_directory(target_path / source_path.filename(), _))
.WillOnce([&](auto, std::error_code& e) {
e = err;
return false;
});
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_local_file_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot access {}: {}", target_path / source_path.filename(),
err.message()))));
}
TEST_F(SFTPUtils, get_full_remote_file_target__target_is_dir_child_is_not)
{
REPLACE(sftp_stat, [&](auto, auto path) -> sftp_attributes {
if (target_path == path)
return get_dummy_attr(path, SSH_FILEXFER_TYPE_DIRECTORY);
if (target_path / source_path.filename() == path)
return get_dummy_attr(path, SSH_FILEXFER_TYPE_REGULAR);
return nullptr;
});
EXPECT_EQ(MP_SFTPUTILS.get_remote_file_target(nullptr, source_path, target_path, false),
target_path / source_path.filename());
}
TEST_F(SFTPUtils, get_full_remote_file_target__target_exists_not_dir)
{
REPLACE(sftp_stat, [&](auto, auto path) {
return target_path == path ? get_dummy_attr(path, SSH_FILEXFER_TYPE_REGULAR) : nullptr;
});
EXPECT_EQ(MP_SFTPUTILS.get_remote_file_target(nullptr, source_path, target_path, false), target_path);
}
TEST_F(SFTPUtils, get_full_remote_file_target__target_not_exists_parent_does)
{
REPLACE(sftp_stat, [&](auto, auto path) {
return target_path == path ? nullptr : get_dummy_attr(path, SSH_FILEXFER_TYPE_DIRECTORY);
});
EXPECT_EQ(MP_SFTPUTILS.get_remote_file_target(nullptr, source_path, target_path, false), target_path);
}
TEST_F(SFTPUtils, get_full_remote_file_target__target_not_exists_parent_does_recursive)
{
REPLACE(sftp_stat, [&](auto, auto path) {
return target_path == path ? nullptr : get_dummy_attr(path, SSH_FILEXFER_TYPE_DIRECTORY);
});
REPLACE(sftp_mkdir, [](auto...) { return SSH_FX_OK; });
EXPECT_EQ(MP_SFTPUTILS.get_remote_file_target(nullptr, source_path, target_path, true), target_path);
}
TEST_F(SFTPUtils, get_full_remote_file_target__target_not_exists_parent_neither)
{
REPLACE(sftp_stat, [](auto...) { return nullptr; });
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_remote_file_target(nullptr, source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq("remote target does not exist")));
}
TEST_F(SFTPUtils, get_full_remote_file_target__target_is_dir_child_is_too)
{
REPLACE(sftp_stat, [](auto, auto path) { return get_dummy_attr(path, SSH_FILEXFER_TYPE_DIRECTORY); });
MP_EXPECT_THROW_THAT(
MP_SFTPUTILS.get_remote_file_target(nullptr, source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot overwrite remote directory \"{}\" with non-directory",
target_path.u8string() + '/' + source_path.filename().u8string()))));
}
TEST_F(SFTPUtils, get_full_local_dir_target__target_exists_not_dir)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path, _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(
MP_SFTPUTILS.get_local_dir_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot overwrite local non-directory {} with directory", target_path))));
}
TEST_F(SFTPUtils, get_full_local_dir_target__cannot_access_target)
{
auto err = std::make_error_code(std::errc::permission_denied);
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillOnce([&](auto, std::error_code& e) {
e = err;
return false;
});
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_local_dir_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot access {}: {}", target_path, err.message()))));
}
TEST_F(SFTPUtils, get_full_local_dir_target__target_not_exists_can_create)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillRepeatedly(Return(false));
EXPECT_CALL(*mock_file_ops, create_directory(target_path, _)).WillOnce(Return(true));
EXPECT_EQ(MP_SFTPUTILS.get_local_dir_target(source_path, target_path, false), target_path);
}
TEST_F(SFTPUtils, get_full_local_dir_target__target_not_exists_cannot_create)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillRepeatedly(Return(false));
auto err = std::make_error_code(std::errc::permission_denied);
EXPECT_CALL(*mock_file_ops, create_directory(target_path, _)).WillOnce([&](auto, std::error_code& e) {
e = err;
return false;
});
MP_EXPECT_THROW_THAT(
MP_SFTPUTILS.get_local_dir_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot create local directory {}: {}", target_path, err.message()))));
}
TEST_F(SFTPUtils, get_full_local_dir_target__target_is_dir_child_is_not)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, exists(target_path / source_path.filename(), _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path / source_path.filename(), _)).WillRepeatedly(Return(false));
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_local_dir_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot overwrite local non-directory {} with directory",
target_path / source_path.filename()))));
}
TEST_F(SFTPUtils, get_full_local_dir_target__target_is_dir_child_not_exists_can_create)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, exists(target_path / source_path.filename(), _)).WillRepeatedly(Return(false));
EXPECT_CALL(*mock_file_ops, create_directory(target_path / source_path.filename(), _)).WillRepeatedly(Return(true));
EXPECT_EQ(MP_SFTPUTILS.get_local_dir_target(source_path, target_path, false), target_path / source_path.filename());
}
TEST_F(SFTPUtils, get_full_local_dir_target__target_is_dir_child_not_exists_cannot_create)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, exists(target_path / source_path.filename(), _)).WillRepeatedly(Return(false));
auto err = std::make_error_code(std::errc::permission_denied);
EXPECT_CALL(*mock_file_ops, create_directory(target_path / source_path.filename(), _))
.WillOnce([&](auto, std::error_code& e) {
e = err;
return false;
});
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_local_dir_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot create local directory {}: {}",
target_path / source_path.filename(), err.message()))));
}
TEST_F(SFTPUtils, get_full_local_dir_target__target_is_dir_cannot_access_child)
{
EXPECT_CALL(*mock_file_ops, exists(target_path, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, is_directory(target_path, _)).WillRepeatedly(Return(true));
auto err = std::make_error_code(std::errc::permission_denied);
EXPECT_CALL(*mock_file_ops, exists(target_path / source_path.filename(), _))
.WillRepeatedly([&](auto, std::error_code& e) {
e = err;
return false;
});
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_local_dir_target(source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot access {}: {}", target_path / source_path.filename(),
err.message()))));
}
TEST_F(SFTPUtils, get_full_remote_dir_target__target_exists_not_dir)
{
REPLACE(sftp_stat, [](auto, auto path) { return get_dummy_attr(path, SSH_FILEXFER_TYPE_REGULAR); });
MP_EXPECT_THROW_THAT(
MP_SFTPUTILS.get_remote_dir_target(nullptr, source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot overwrite remote non-directory {} with directory", target_path))));
}
TEST_F(SFTPUtils, get_full_remote_dir_target__target_not_exists_can_create)
{
REPLACE(sftp_stat, [](auto...) { return nullptr; });
REPLACE(sftp_mkdir, [](auto...) { return SSH_FX_OK; });
EXPECT_EQ(MP_SFTPUTILS.get_remote_dir_target(nullptr, source_path, target_path, false), target_path);
}
TEST_F(SFTPUtils, get_full_remote_dir_target__target_not_exists_can_create_recursive)
{
REPLACE(sftp_stat, [](auto...) { return nullptr; });
REPLACE(sftp_mkdir, [](auto...) { return SSH_FX_OK; });
EXPECT_EQ(MP_SFTPUTILS.get_remote_dir_target(nullptr, source_path, target_path, true), target_path);
}
TEST_F(SFTPUtils, get_full_remote_dir_target__target_not_exists_cannot_create)
{
REPLACE(sftp_stat, [](auto...) { return nullptr; });
REPLACE(sftp_mkdir, [](auto...) { return -1; });
auto err = "SFTP server: Permission denied";
REPLACE(ssh_get_error, [&](auto...) { return err; });
sftp_session_struct sftp{};
MP_EXPECT_THROW_THAT(
MP_SFTPUTILS.get_remote_dir_target(&sftp, source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot create remote directory {}: {}", target_path, err))));
}
TEST_F(SFTPUtils, get_full_remote_dir_target__target_is_dir_child_is_not)
{
auto target_child_path = target_path.u8string() + '/' + source_path.filename().u8string();
REPLACE(sftp_stat, [&](auto, auto path) -> sftp_attributes {
if (target_path == path)
return get_dummy_attr(path, SSH_FILEXFER_TYPE_DIRECTORY);
if (target_child_path == path)
return get_dummy_attr(path, SSH_FILEXFER_TYPE_REGULAR);
return nullptr;
});
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.get_remote_dir_target(nullptr, source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format(
"cannot overwrite remote non-directory \"{}\" with directory", target_child_path))));
}
TEST_F(SFTPUtils, get_full_remote_dir_target__target_is_dir_child_not_exists_can_create)
{
REPLACE(sftp_stat, [&](auto, auto path) {
return target_path == path ? get_dummy_attr(path, SSH_FILEXFER_TYPE_DIRECTORY) : nullptr;
});
REPLACE(sftp_mkdir, [](auto...) { return SSH_FX_OK; });
EXPECT_EQ(MP_SFTPUTILS.get_remote_dir_target(nullptr, source_path, target_path, false),
target_path / source_path.filename());
}
TEST_F(SFTPUtils, get_full_remote_dir_target__target_is_dir_child_not_exists_cannot_create)
{
REPLACE(sftp_stat, [&](auto, auto path) {
return target_path == path ? get_dummy_attr(path, SSH_FILEXFER_TYPE_DIRECTORY) : nullptr;
});
REPLACE(sftp_mkdir, [](auto...) { return -1; });
auto err = "SFTP server: Permission denied";
REPLACE(ssh_get_error, [&](auto...) { return err; });
sftp_session_struct sftp{};
MP_EXPECT_THROW_THAT(
MP_SFTPUTILS.get_remote_dir_target(&sftp, source_path, target_path, false), mp::SFTPError,
mpt::match_what(StrEq(fmt::format("cannot create remote directory \"{}\": {}",
target_path.u8string() + '/' + source_path.filename().u8string(), err))));
}
TEST_F(SFTPUtils, mkdir_success)
{
REPLACE(sftp_lstat, [](auto...) { return nullptr; });
REPLACE(sftp_mkdir, [](auto...) { return SSH_FX_OK; });
EXPECT_NO_THROW(MP_SFTPUTILS.mkdir_recursive(nullptr, "some/nested/path"));
}
TEST_F(SFTPUtils, mkdir_cannot_overwrite_non_directory)
{
REPLACE(sftp_lstat, [](auto...) { return get_dummy_attr("", SSH_FILEXFER_TYPE_REGULAR); });
MP_EXPECT_THROW_THAT(MP_SFTPUTILS.mkdir_recursive(nullptr, "some/nested/path"), mp::SFTPError,
mpt::match_what(StrEq("cannot overwrite remote non-directory \"some\" with directory")));
}
TEST_F(SFTPUtils, mkdir_cannot_create_dir)
{
REPLACE(sftp_lstat, [](auto...) { return nullptr; });
REPLACE(sftp_mkdir, [](auto...) { return -1; });
REPLACE(ssh_get_error, [](auto...) { return "SFTP server: Permission denied"; });
sftp_session_struct sftp{};
MP_EXPECT_THROW_THAT(
MP_SFTPUTILS.mkdir_recursive(&sftp, "some/nested/path"), mp::SFTPError,
mpt::match_what(StrEq("cannot create remote directory \"some\": SFTP server: Permission denied")));
}
| 18,856
|
C++
|
.cpp
| 348
| 47.652299
| 120
| 0.665148
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,643
|
test_sshfsmount.cpp
|
canonical_multipass/tests/test_sshfsmount.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_logger.h"
#include "mock_ssh_process_exit_status.h"
#include "sftp_server_test_fixture.h"
#include "signal.h"
#include "stub_ssh_key_provider.h"
#include <src/sshfs_mount/sshfs_mount.h>
#include <multipass/exceptions/sshfs_missing_error.h>
#include <multipass/logging/log.h>
#include <multipass/ssh/ssh_session.h>
#include <multipass/utils.h>
#include <algorithm>
#include <iterator>
#include <tuple>
#include <unordered_set>
#include <vector>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
typedef std::vector<std::pair<std::string, std::string>> CommandVector;
namespace
{
struct SshfsMount : public mp::test::SftpServerTest
{
mp::SshfsMount make_sshfsmount(std::optional<std::string> target = std::nullopt)
{
mp::SSHSession session{"a", 42, "ubuntu", key_provider};
return {std::move(session), default_source, target.value_or(default_target), default_mappings,
default_mappings};
}
auto make_exec_that_fails_for(const std::vector<std::string>& expected_cmds, bool& invoked)
{
auto request_exec = [this, expected_cmds, &invoked](ssh_channel, const char* raw_cmd) {
std::string cmd{raw_cmd};
for (const auto& expected_cmd : expected_cmds)
{
if (cmd.find(expected_cmd) != std::string::npos)
{
invoked = true;
exit_status_mock.set_exit_status(exit_status_mock.failure_status);
}
}
return SSH_OK;
};
return request_exec;
}
// The 'invoked' parameter binds the execution and read mocks. We need a better mechanism to make them
// cooperate better, i.e., make the reader read only when a command was issued.
auto make_exec_to_check_commands(const CommandVector& commands, std::string::size_type& remaining,
CommandVector::const_iterator& next_expected_cmd, std::string& output,
bool& invoked, std::optional<std::string>& fail_cmd,
std::optional<bool>& fail_invoked)
{
*fail_invoked = false;
auto request_exec = [this, &commands, &remaining, &next_expected_cmd, &output, &invoked, &fail_cmd,
&fail_invoked](ssh_channel, const char* raw_cmd) {
invoked = false;
std::string cmd{raw_cmd};
if (fail_cmd && cmd.find(*fail_cmd) != std::string::npos)
{
if (fail_invoked)
{
*fail_invoked = true;
}
exit_status_mock.set_exit_status(exit_status_mock.failure_status);
}
else if (next_expected_cmd != commands.end())
{
// Check if the first element of the given commands list is what we are expecting. In that case,
// give the correct answer. If not, check the rest of the list to see if we broke the execution
// order.
auto pred = [&cmd](auto it) { return cmd == it.first; };
CommandVector::const_iterator found_cmd = std::find_if(next_expected_cmd, commands.end(), pred);
if (found_cmd == next_expected_cmd)
{
invoked = true;
output = next_expected_cmd->second;
remaining = output.size();
++next_expected_cmd;
return SSH_OK;
}
else if (found_cmd != commands.end())
{
output = found_cmd->second;
remaining = output.size();
ADD_FAILURE() << "\"" << (found_cmd->first) << "\" executed out of order; expected \""
<< next_expected_cmd->first << "\"";
return SSH_OK;
}
}
// If the command list was entirely checked or if the executed command is not on the list, check the
// default commands to see if there is an answer to the current command.
auto it = default_cmds.find(cmd);
if (it != default_cmds.end())
{
output = it->second;
remaining = output.size();
invoked = true;
}
return SSH_OK;
};
return request_exec;
}
auto make_channel_read_return(const std::string& output, std::string::size_type& remaining, bool& prereq_invoked)
{
auto channel_read = [&output, &remaining, &prereq_invoked](ssh_channel, void* dest, uint32_t count,
int is_stderr, int) {
if (!prereq_invoked)
return 0u;
const auto num_to_copy = std::min(count, static_cast<uint32_t>(remaining));
const auto begin = output.begin() + output.size() - remaining;
std::copy_n(begin, num_to_copy, reinterpret_cast<char*>(dest));
remaining -= num_to_copy;
return num_to_copy;
};
return channel_read;
}
void test_command_execution(const CommandVector& commands, std::optional<std::string> target = std::nullopt,
std::optional<std::string> fail_cmd = std::nullopt,
std::optional<bool> fail_invoked = std::nullopt)
{
bool invoked{false};
std::string output;
auto remaining = output.size();
CommandVector::const_iterator next_expected_cmd = commands.begin();
auto channel_read = make_channel_read_return(output, remaining, invoked);
REPLACE(ssh_channel_read_timeout, channel_read);
auto request_exec = make_exec_to_check_commands(commands, remaining, next_expected_cmd, output, invoked,
fail_cmd, fail_invoked);
REPLACE(ssh_channel_request_exec, request_exec);
make_sshfsmount(target.value_or(default_target));
EXPECT_TRUE(next_expected_cmd == commands.end()) << "\"" << next_expected_cmd->first << "\" not executed";
}
mpt::ExitStatusMock exit_status_mock;
std::string default_source{"source"};
std::string default_target{"target"};
mp::id_mappings default_mappings;
int default_id{1000};
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
const mpt::StubSSHKeyProvider key_provider;
const std::unordered_map<std::string, std::string> default_cmds{
{"snap run multipass-sshfs.env", "LD_LIBRARY_PATH=/foo/bar\nSNAP=/baz\n"},
{"sudo env LD_LIBRARY_PATH=/foo/bar /baz/bin/sshfs -V", "FUSE library version: 3.0.0\n"},
{"echo $PWD/target", "/home/ubuntu/target\n"},
{"sudo /bin/bash -c 'P=\"/home/ubuntu/target\"; while [ ! -d \"$P/\" ]; do P=\"${P%/*}\"; done; echo $P/'",
"/home/ubuntu/\n"},
{"id -u", "1000\n"},
{"id -g", "1000\n"},
{"sudo env LD_LIBRARY_PATH=/foo/bar /baz/bin/sshfs -o slave -o transform_symlinks -o allow_other -o "
"Compression=no -o dcache_timeout=3 :\"source\" "
"\"target\"",
"don't care\n"}};
};
// Mocks an incorrect return from a given command.
struct SshfsMountFail : public SshfsMount, public testing::WithParamInterface<std::string>
{
};
// Mocks correct execution of a given vector of commands/answers. The first string specifies the parameter with
// which make_sshfsmount mock is called.
struct SshfsMountExecute : public SshfsMount, public testing::WithParamInterface<std::pair<std::string, CommandVector>>
{
};
struct SshfsMountExecuteAndNoFail
: public SshfsMount,
public testing::WithParamInterface<std::tuple<std::string, CommandVector, std::string>>
{
};
// Mocks the server raising a std::invalid_argument.
struct SshfsMountExecuteThrowInvArg : public SshfsMount, public testing::WithParamInterface<CommandVector>
{
};
// Mocks the server raising a std::runtime_error.
struct SshfsMountExecuteThrowRuntErr : public SshfsMount, public testing::WithParamInterface<CommandVector>
{
};
} // namespace
//
// Define some parameterized test fixtures.
//
TEST_P(SshfsMountFail, test_failed_invocation)
{
bool invoked_cmd{false};
std::string output;
std::string::size_type remaining;
auto channel_read = make_channel_read_return(output, remaining, invoked_cmd);
REPLACE(ssh_channel_read_timeout, channel_read);
CommandVector empty;
CommandVector::const_iterator it = empty.end();
std::optional<std::string> fail_cmd = std::make_optional(GetParam());
std::optional<bool> invoked_fail = std::make_optional(false);
auto request_exec = make_exec_to_check_commands(empty, remaining, it, output, invoked_cmd, fail_cmd, invoked_fail);
REPLACE(ssh_channel_request_exec, request_exec);
EXPECT_THROW(make_sshfsmount(), std::runtime_error);
EXPECT_TRUE(*invoked_fail);
}
TEST_P(SshfsMountExecute, test_successful_invocation)
{
std::string target = GetParam().first;
CommandVector commands = GetParam().second;
test_command_execution(commands, target);
}
TEST_P(SshfsMountExecuteAndNoFail, test_successful_invocation_and_fail)
{
std::string target = std::get<0>(GetParam());
CommandVector commands = std::get<1>(GetParam());
std::string fail_command = std::get<2>(GetParam());
ASSERT_NO_THROW(test_command_execution(commands, target, fail_command));
}
TEST_P(SshfsMountExecuteThrowInvArg, test_invalid_arg_when_executing)
{
EXPECT_THROW(test_command_execution(GetParam()), std::invalid_argument);
}
TEST_P(SshfsMountExecuteThrowRuntErr, test_runtime_error_when_executing)
{
EXPECT_THROW(test_command_execution(GetParam()), std::runtime_error);
}
//
// Instantiate the parameterized tests suites from above.
//
INSTANTIATE_TEST_SUITE_P(SshfsMountThrowWhenError, SshfsMountFail,
testing::Values("mkdir", "chown", "id -u", "id -g", "cd", "echo $PWD"));
// Commands to check that a version of FUSE smaller that 3 gives a correct answer.
CommandVector old_fuse_cmds = {
{"sudo env LD_LIBRARY_PATH=/foo/bar /baz/bin/sshfs -V", "FUSE library version: 2.9.0\n"},
{"sudo env LD_LIBRARY_PATH=/foo/bar /baz/bin/sshfs -o slave -o transform_symlinks -o "
"allow_other -o Compression=no -o nonempty -o cache=no :\"source\" \"/home/ubuntu/target\"",
"don't care\n"}};
// Commands to check that a version of FUSE at least 3.0.0 gives a correct answer.
CommandVector new_fuse_cmds = {{"sudo env LD_LIBRARY_PATH=/foo/bar /baz/bin/sshfs -V", "FUSE library version: 3.0.0\n"},
{"sudo env LD_LIBRARY_PATH=/foo/bar /baz/bin/sshfs -o slave -o transform_symlinks -o "
"allow_other -o Compression=no -o dir_cache=no :\"source\" \"/home/ubuntu/target\"",
"don't care\n"}};
// Commands to check that an unknown version of FUSE gives a correct answer.
CommandVector unk_fuse_cmds = {{"sudo env LD_LIBRARY_PATH=/foo/bar /baz/bin/sshfs -V", "weird fuse version\n"},
{"sudo env LD_LIBRARY_PATH=/foo/bar /baz/bin/sshfs -o slave -o transform_symlinks -o "
"allow_other -o Compression=no :\"source\" \"/home/ubuntu/target\"",
"don't care\n"}};
// Commands to check that the server correctly creates the mount target.
CommandVector exec_cmds = {
{"sudo /bin/bash -c 'P=\"/home/ubuntu/target\"; while [ ! -d \"$P/\" ]; do P=\"${P%/*}\"; done; echo $P/'",
"/home/ubuntu/\n"},
{"sudo /bin/bash -c 'cd \"/home/ubuntu/\" && mkdir -p \"target\"'", "\n"},
{"sudo /bin/bash -c 'cd \"/home/ubuntu/\" && chown -R 1000:1000 \"target\"'", "\n"}};
// Commands to check that it works with a path containing a space.
CommandVector space_cmds = {
{"echo $PWD/space\\ odyssey", "/home/ubuntu/space odyssey\n"},
{"sudo /bin/bash -c 'P=\"/home/ubuntu/space odyssey\"; while [ ! -d \"$P/\" ]; do P=\"${P%/*}\"; done; echo $P/'",
"/home/ubuntu/\n"}};
// Commands to check that the ~ expansion works.
CommandVector tilde1_cmds = {
{"echo ~/target", "/home/ubuntu/target\n"},
{"sudo /bin/bash -c 'P=\"/home/ubuntu/target\"; while [ ! -d \"$P/\" ]; do P=\"${P%/*}\"; done; echo $P/'",
"/home/ubuntu/\n"}};
// Commands to check that the ~user expansion works (assuming that user exists).
CommandVector tilde2_cmds = {
{"echo ~ubuntu/target", "/home/ubuntu/target\n"},
{"sudo /bin/bash -c 'P=\"/home/ubuntu/target\"; while [ ! -d \"$P/\" ]; do P=\"${P%/*}\"; done; echo $P/'",
"/home/ubuntu/\n"}};
// Commands to check that the server works if an absolute path is given.
CommandVector absolute_cmds = {
{"sudo /bin/bash -c 'P=\"/home/ubuntu/target\"; while [ ! -d \"$P/\" ]; do P=\"${P%/*}\"; done; echo $P/'",
"/home/ubuntu/\n"}};
// Commands to check that it works for a nonexisting path.
CommandVector nonexisting_path_cmds = {
{"sudo /bin/bash -c 'P=\"/nonexisting/path\"; while [ ! -d \"$P/\" ]; do P=\"${P%/*}\"; done; echo $P/'", "/\n"}};
// Check the execution of the CommandVector's above.
INSTANTIATE_TEST_SUITE_P(
SshfsMountSuccess, SshfsMountExecute,
testing::Values(std::make_pair("target", old_fuse_cmds), std::make_pair("target", new_fuse_cmds),
std::make_pair("target", unk_fuse_cmds), std::make_pair("target", exec_cmds),
std::make_pair("space odyssey", space_cmds), std::make_pair("~/target", tilde1_cmds),
std::make_pair("~ubuntu/target", tilde2_cmds), std::make_pair("/home/ubuntu/target", absolute_cmds),
std::make_pair("/nonexisting/path", nonexisting_path_cmds)));
// Commands to test that when a mount path already exists, no mkdir nor chown is ran.
CommandVector execute_no_mkdir_cmds = {
{"sudo /bin/bash -c 'P=\"/home/ubuntu/target\"; while [ ! -d \"$P/\" ]; do P=\"${P%/*}\"; done; echo $P/'",
"/home/ubuntu/target/\n"}};
INSTANTIATE_TEST_SUITE_P(SshfsMountSuccessAndAvoidCommands, SshfsMountExecuteAndNoFail,
testing::Values(std::make_tuple("target", execute_no_mkdir_cmds, "mkdir"),
std::make_tuple("target", execute_no_mkdir_cmds, "chown")));
// Check that some commands throw some exceptions.
CommandVector non_int_uid_cmds = {{"id -u", "ubuntu\n"}};
CommandVector non_int_gid_cmds = {{"id -g", "ubuntu\n"}};
CommandVector invalid_fuse_ver_cmds = {
{"sudo env LD_LIBRARY_PATH=/foo/bar /baz/bin/sshfs -V", "FUSE library version: fu.man.chu\n"}};
INSTANTIATE_TEST_SUITE_P(SshfsMountThrowInvArg, SshfsMountExecuteThrowInvArg,
testing::Values(non_int_uid_cmds, non_int_gid_cmds));
INSTANTIATE_TEST_SUITE_P(SshfsMountThrowRuntErr, SshfsMountExecuteThrowRuntErr, testing::Values(invalid_fuse_ver_cmds));
//
// Finally, individual test fixtures.
//
TEST_F(SshfsMount, throws_when_sshfs_does_not_exist)
{
bool invoked{false};
auto request_exec = make_exec_that_fails_for({"sudo multipass-sshfs.env", "which sshfs"}, invoked);
REPLACE(ssh_channel_request_exec, request_exec);
EXPECT_THROW(make_sshfsmount(), mp::SSHFSMissingError);
EXPECT_TRUE(invoked);
}
TEST_F(SshfsMount, unblocks_when_sftpserver_exits)
{
mpt::Signal client_message;
auto get_client_msg = [&client_message](sftp_session) {
client_message.wait();
return nullptr;
};
REPLACE(sftp_get_client_message, get_client_msg);
bool stopped_ok = false;
std::thread mount([&] {
test_command_execution(CommandVector());
stopped_ok = true;
});
client_message.signal();
mount.join();
EXPECT_TRUE(stopped_ok);
}
TEST_F(SshfsMount, blank_fuse_version_logs_error)
{
CommandVector commands = {{"sudo env LD_LIBRARY_PATH=/foo/bar /baz/bin/sshfs -V", "FUSE library version:\n"}};
logger_scope.mock_logger->screen_logs(mpl::Level::error);
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::warning), mpt::MockLogger::make_cstring_matcher(StrEq("sshfs mount")),
mpt::MockLogger::make_cstring_matcher(StrEq("Unable to parse the FUSE library version"))));
EXPECT_CALL(*logger_scope.mock_logger,
log(Eq(mpl::Level::debug), mpt::MockLogger::make_cstring_matcher(StrEq("sshfs mount")),
mpt::MockLogger::make_cstring_matcher(
StrEq("Unable to parse the FUSE library version: FUSE library version:"))));
test_command_execution(commands);
}
| 17,374
|
C++
|
.cpp
| 346
| 41.881503
| 120
| 0.626718
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,644
|
test_format_utils.cpp
|
canonical_multipass/tests/test_format_utils.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include <multipass/cli/format_utils.h>
#include <multipass/rpc/multipass.grpc.pb.h>
namespace mp = multipass;
using namespace testing;
TEST(InstanceStatusString, RUNNING_status_returns_Running)
{
mp::InstanceStatus status;
status.set_status(mp::InstanceStatus::RUNNING);
auto status_string = mp::format::status_string_for(status);
EXPECT_THAT(status_string, Eq("Running"));
}
TEST(InstanceStatusString, STOPPED_status_returns_Stopped)
{
mp::InstanceStatus status;
status.set_status(mp::InstanceStatus::STOPPED);
auto status_string = mp::format::status_string_for(status);
EXPECT_THAT(status_string, Eq("Stopped"));
}
TEST(InstanceStatusString, DELETED_status_returns_Deleted)
{
mp::InstanceStatus status;
status.set_status(mp::InstanceStatus::DELETED);
auto status_string = mp::format::status_string_for(status);
EXPECT_THAT(status_string, Eq("Deleted"));
}
TEST(InstanceStatusString, SUSPENDING_status_returns_Suspending)
{
mp::InstanceStatus status;
status.set_status(mp::InstanceStatus::SUSPENDING);
auto status_string = mp::format::status_string_for(status);
EXPECT_THAT(status_string, Eq("Suspending"));
}
TEST(InstanceStatusString, SUSPENDED_status_returns_Suspended)
{
mp::InstanceStatus status;
status.set_status(mp::InstanceStatus::SUSPENDED);
auto status_string = mp::format::status_string_for(status);
EXPECT_THAT(status_string, Eq("Suspended"));
}
TEST(InstanceStatusString, RESTARTING_status_returns_Restarting)
{
mp::InstanceStatus status;
status.set_status(mp::InstanceStatus::RESTARTING);
auto status_string = mp::format::status_string_for(status);
EXPECT_THAT(status_string, Eq("Restarting"));
}
TEST(InstanceStatusString, bogus_status_returns_Unknown)
{
mp::InstanceStatus status;
status.set_status(static_cast<mp::InstanceStatus_Status>(46));
auto status_string = mp::format::status_string_for(status);
EXPECT_THAT(status_string, Eq("Unknown"));
}
TEST(InstanceStatusString, STARTING_status_returns_Starting)
{
mp::InstanceStatus status;
status.set_status(mp::InstanceStatus::STARTING);
auto status_string = mp::format::status_string_for(status);
EXPECT_THAT(status_string, Eq("Starting"));
}
TEST(InstanceStatusString, DELAYED_SHUTDOWN_status_returns_Delayed_Shutdown)
{
mp::InstanceStatus status;
status.set_status(mp::InstanceStatus::DELAYED_SHUTDOWN);
auto status_string = mp::format::status_string_for(status);
EXPECT_THAT(status_string, Eq("Delayed Shutdown"));
}
TEST(AliasFilter, unwanted_aliases_filtered_out)
{
auto reply = mp::FindReply();
auto image = reply.add_images_info();
auto alias = image->add_aliases_info();
alias->set_alias("ubuntu");
alias = image->add_aliases_info();
alias->set_alias("default");
alias = image->add_aliases_info();
alias->set_alias("devel");
auto aliases = image->aliases_info();
mp::format::filter_aliases(aliases);
EXPECT_EQ(aliases.size(), 1);
EXPECT_EQ(aliases[0].alias(), "devel");
}
TEST(AliasFilter, single_character_aliases_filtered_out)
{
auto reply = mp::FindReply();
auto image = reply.add_images_info();
auto alias = image->add_aliases_info();
alias->set_alias("a");
alias = image->add_aliases_info();
alias->set_alias("b");
alias = image->add_aliases_info();
alias->set_alias("devel");
auto aliases = image->aliases_info();
mp::format::filter_aliases(aliases);
EXPECT_EQ(aliases.size(), 1);
EXPECT_EQ(aliases[0].alias(), "devel");
}
TEST(AliasFilter, wanted_aliases_not_filtered_out)
{
auto reply = mp::FindReply();
auto image = reply.add_images_info();
auto alias = image->add_aliases_info();
alias->set_alias("lts");
alias = image->add_aliases_info();
alias->set_alias("devel");
alias = image->add_aliases_info();
alias->set_alias("eoan");
auto aliases = image->aliases_info();
mp::format::filter_aliases(aliases);
EXPECT_THAT(aliases.size(), Eq(3));
EXPECT_THAT(aliases[0].alias(), Eq("lts"));
EXPECT_THAT(aliases[1].alias(), Eq("devel"));
EXPECT_THAT(aliases[2].alias(), Eq("eoan"));
}
TEST(AliasFilter, mixed_aliases_filtered_out)
{
auto reply = mp::FindReply();
auto image = reply.add_images_info();
auto alias = image->add_aliases_info();
alias->set_alias("lts");
alias = image->add_aliases_info();
alias->set_alias("d");
alias = image->add_aliases_info();
alias->set_alias("eoan");
alias = image->add_aliases_info();
alias->set_alias("ubuntu");
auto aliases = image->aliases_info();
mp::format::filter_aliases(aliases);
EXPECT_THAT(aliases.size(), Eq(2));
EXPECT_THAT(aliases[0].alias(), Eq("lts"));
EXPECT_THAT(aliases[1].alias(), Eq("eoan"));
}
TEST(AliasFilter, at_least_one_alias_left)
{
auto reply = mp::FindReply();
auto image = reply.add_images_info();
auto alias = image->add_aliases_info();
alias->set_alias("d");
auto aliases = image->aliases_info();
mp::format::filter_aliases(aliases);
EXPECT_EQ(aliases.size(), 1);
EXPECT_EQ(aliases[0].alias(), "d");
}
TEST(StaticFormatFunctions, columnWidthOnEmptyInputWorks)
{
std::vector<std::string> empty_vector;
const auto get_width = [](const auto& str) -> int { return str.length(); };
int min_w = 3;
ASSERT_EQ(mp::format::column_width(empty_vector.begin(), empty_vector.end(), get_width, 0, min_w),
mp::format::col_buffer);
}
TEST(StaticFormatFunctions, columnWidthOnWideInputWorks)
{
const std::string wider_str = "wide string example";
const auto str_vector = std::vector<std::string>{wider_str, "w2"};
const auto get_width = [](const auto& str) -> int { return str.length(); };
int min_w = 3;
int space = 1;
ASSERT_EQ(mp::format::column_width(str_vector.begin(), str_vector.end(), get_width, space, min_w),
wider_str.length() + mp::format::col_buffer);
}
TEST(StaticFormatFunctions, columnWidthOnNarrowInputWorks)
{
const auto str_vector = std::vector<std::string>{"n", "n2"};
const auto get_width = [](const auto& str) -> int { return str.length(); };
int min_w = 7;
int space = 2;
ASSERT_EQ(mp::format::column_width(str_vector.begin(), str_vector.end(), get_width, space, min_w), min_w);
}
| 7,009
|
C++
|
.cpp
| 186
| 33.763441
| 110
| 0.698272
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,645
|
test_base_snapshot.cpp
|
canonical_multipass/tests/test_base_snapshot.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "file_operations.h"
#include "mock_cloud_init_file_ops.h"
#include "mock_file_ops.h"
#include "mock_virtual_machine.h"
#include "path.h"
#include <multipass/json_utils.h>
#include <multipass/memory_size.h>
#include <multipass/virtual_machine_description.h>
#include <multipass/vm_specs.h>
#include <shared/base_snapshot.h>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <stdexcept>
#include <tuple>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
class MockBaseSnapshot : public mp::BaseSnapshot
{
public:
using mp::BaseSnapshot::BaseSnapshot;
MOCK_METHOD(void, capture_impl, (), (override));
MOCK_METHOD(void, erase_impl, (), (override));
MOCK_METHOD(void, apply_impl, (), (override));
friend bool operator==(const MockBaseSnapshot& a, const MockBaseSnapshot& b);
};
bool operator==(const MockBaseSnapshot& a, const MockBaseSnapshot& b)
{
return std::tuple(a.get_index(),
a.get_name(),
a.get_comment(),
a.get_cloud_init_instance_id(),
a.get_creation_timestamp(),
a.get_num_cores(),
a.get_mem_size(),
a.get_disk_space(),
a.get_extra_interfaces(),
a.get_state(),
a.get_mounts(),
a.get_metadata(),
a.get_parent(),
a.get_id()) == std::tuple(b.get_index(),
b.get_name(),
b.get_comment(),
a.get_cloud_init_instance_id(),
b.get_creation_timestamp(),
b.get_num_cores(),
b.get_mem_size(),
b.get_disk_space(),
b.get_extra_interfaces(),
b.get_state(),
b.get_mounts(),
b.get_metadata(),
b.get_parent(),
b.get_id());
}
struct TestBaseSnapshot : public Test
{
static mp::VMSpecs stub_specs()
{
mp::VMSpecs ret{};
ret.num_cores = 3;
ret.mem_size = mp::MemorySize{"1.5G"};
ret.disk_space = mp::MemorySize{"10G"};
ret.extra_interfaces = std::vector<mp::NetworkInterface>{{"eth13", "13:13:13:13:13:13", true},
{"eth14", "14:14:14:14:14:14", true}};
ret.default_mac_address = "12:12:12:12:12:12";
return ret;
}
static mp::VirtualMachineDescription stub_desc()
{
mp::VirtualMachineDescription desc{};
desc.extra_interfaces = std::vector<mp::NetworkInterface>{{"eth13", "13:13:13:13:13:13", true},
{"eth14", "14:14:14:14:14:14", true},
{"eth15", "15:15:15:15:15:15", true}};
return desc;
}
static QJsonObject test_snapshot_json()
{
static auto json_doc = [] {
QJsonParseError parse_error{};
const auto ret = QJsonDocument::fromJson(mpt::load_test_file(test_json_filename), &parse_error);
if (parse_error.error)
throw std::runtime_error{
fmt::format("Bad JSON test data in {}; error: {}", test_json_filename, parse_error.errorString())};
return ret;
}();
return json_doc.object();
}
static QJsonObject test_legacy_snapshot_json()
{
auto json = test_snapshot_json();
// Remove the "extra_interfaces" field.
auto snapshot_entry = json["snapshot"].toObject();
snapshot_entry.remove("extra_interfaces");
json["snapshot"] = snapshot_entry;
return json;
}
static void mod_snapshot_json(QJsonObject& json, const QString& key, const QJsonValue& new_value)
{
const auto snapshot_key = QStringLiteral("snapshot");
auto snapshot_json_ref = json[snapshot_key];
auto snapshot_json_copy = snapshot_json_ref.toObject();
snapshot_json_copy[key] = new_value;
snapshot_json_ref = snapshot_json_copy;
}
QString plant_snapshot_json(const QJsonObject& object, const QString& filename = "snapshot.json") const
{
const auto file_path = vm.tmp_dir->filePath(filename);
const QJsonDocument doc{object};
mpt::make_file_with_content(file_path, doc.toJson().toStdString());
return file_path;
}
QString derive_persisted_snapshot_file_path(int index)
{
return vm.tmp_dir->filePath(QString{"%1"}.arg(index, 4, 10, QLatin1Char('0')) + ".snapshot.json");
}
static constexpr auto* test_json_filename = "test_snapshot.json";
mp::VMSpecs specs = stub_specs();
mp::VirtualMachineDescription desc = stub_desc();
NiceMock<mpt::MockVirtualMachine> vm{"a-vm"};
const mpt::MockCloudInitFileOps::GuardedMock mock_cloud_init_file_ops_injection =
mpt::MockCloudInitFileOps::inject<NiceMock>();
QString test_json_file_path = mpt::test_data_path_for(test_json_filename);
};
TEST_F(TestBaseSnapshot, adoptsGivenValidName)
{
constexpr auto name = "a-name";
auto snapshot = MockBaseSnapshot{name, "", "", nullptr, specs, vm};
EXPECT_EQ(snapshot.get_name(), name);
}
TEST_F(TestBaseSnapshot, rejectsEmptyName)
{
const std::string empty{};
MP_EXPECT_THROW_THAT((MockBaseSnapshot{empty, "asdf", "", nullptr, specs, vm}),
std::runtime_error,
mpt::match_what(HasSubstr("empty")));
}
TEST_F(TestBaseSnapshot, adoptsGivenComment)
{
constexpr auto comment = "some comment";
auto snapshot = MockBaseSnapshot{"whatever", comment, "", nullptr, specs, vm};
EXPECT_EQ(snapshot.get_comment(), comment);
}
TEST_F(TestBaseSnapshot, adoptsGivenInstanceId)
{
constexpr std::string_view instance_id{"vm2"};
const auto snapshot = MockBaseSnapshot{"whatever", "some comment", std::string{instance_id}, nullptr, specs, vm};
EXPECT_EQ(snapshot.get_cloud_init_instance_id(), instance_id);
}
TEST_F(TestBaseSnapshot, adoptsGivenParent)
{
const auto parent = std::make_shared<MockBaseSnapshot>("root", "asdf", "", nullptr, specs, vm);
auto snapshot = MockBaseSnapshot{"descendant", "descends", "", parent, specs, vm};
EXPECT_EQ(snapshot.get_parent(), parent);
}
TEST_F(TestBaseSnapshot, adoptsNullParent)
{
auto snapshot = MockBaseSnapshot{"descendant", "descends", "", nullptr, specs, vm};
EXPECT_EQ(snapshot.get_parent(), nullptr);
}
TEST_F(TestBaseSnapshot, adoptsGivenSpecs)
{
auto snapshot = MockBaseSnapshot{"snapshot", "", "", nullptr, specs, vm};
EXPECT_EQ(snapshot.get_num_cores(), specs.num_cores);
EXPECT_EQ(snapshot.get_mem_size(), specs.mem_size);
EXPECT_EQ(snapshot.get_disk_space(), specs.disk_space);
EXPECT_EQ(snapshot.get_extra_interfaces(), specs.extra_interfaces);
EXPECT_EQ(snapshot.get_state(), specs.state);
EXPECT_EQ(snapshot.get_mounts(), specs.mounts);
EXPECT_EQ(snapshot.get_metadata(), specs.metadata);
}
TEST_F(TestBaseSnapshot, adoptsCustomMounts)
{
specs.mounts["toto"] =
mp::VMMount{"src", {{123, 234}, {567, 678}}, {{19, 91}}, multipass::VMMount::MountType::Classic};
specs.mounts["tata"] =
mp::VMMount{"fountain", {{234, 123}}, {{81, 18}, {9, 10}}, multipass::VMMount::MountType::Native};
auto snapshot = MockBaseSnapshot{"snapshot", "", "", nullptr, specs, vm};
EXPECT_EQ(snapshot.get_mounts(), specs.mounts);
}
TEST_F(TestBaseSnapshot, adoptsCustomMetadata)
{
QJsonObject json;
QJsonObject data;
data.insert("an-int", 7);
data.insert("a-str", "str");
json.insert("meta", data);
specs.metadata = json;
auto snapshot = MockBaseSnapshot{"snapshot", "", "", nullptr, specs, vm};
EXPECT_EQ(snapshot.get_metadata(), specs.metadata);
}
TEST_F(TestBaseSnapshot, adoptsNextIndex)
{
const int count = 123;
EXPECT_CALL(vm, get_snapshot_count).WillOnce(Return(count));
auto snapshot = MockBaseSnapshot{"tau", "ceti", "", nullptr, specs, vm};
EXPECT_EQ(snapshot.get_index(), count + 1);
}
TEST_F(TestBaseSnapshot, retrievesParentsProperties)
{
constexpr auto parent_name = "parent";
const int parent_index = 11;
EXPECT_CALL(vm, get_snapshot_count).WillOnce(Return(parent_index - 1)).WillOnce(Return(31));
auto parent = std::make_shared<MockBaseSnapshot>(parent_name, "", "", nullptr, specs, vm);
auto child = MockBaseSnapshot{"child", "", "", parent, specs, vm};
EXPECT_EQ(child.get_parents_index(), parent_index);
EXPECT_EQ(child.get_parents_name(), parent_name);
}
TEST_F(TestBaseSnapshot, adoptsCurrentTimestamp)
{
auto before = QDateTime::currentDateTimeUtc();
auto snapshot = MockBaseSnapshot{"foo", "", "", nullptr, specs, vm};
auto after = QDateTime::currentDateTimeUtc();
EXPECT_GE(snapshot.get_creation_timestamp(), before);
EXPECT_LE(snapshot.get_creation_timestamp(), after);
}
class TestSnapshotRejectedStates : public TestBaseSnapshot, public WithParamInterface<mp::VirtualMachine::State>
{
};
TEST_P(TestSnapshotRejectedStates, rejectsActiveState)
{
specs.state = GetParam();
MP_EXPECT_THROW_THAT((MockBaseSnapshot{"snapshot", "comment", "", nullptr, specs, vm}),
std::runtime_error,
mpt::match_what(HasSubstr("Unsupported VM state")));
}
INSTANTIATE_TEST_SUITE_P(TestBaseSnapshot,
TestSnapshotRejectedStates,
Values(mp::VirtualMachine::State::starting,
mp::VirtualMachine::State::restarting,
mp::VirtualMachine::State::running,
mp::VirtualMachine::State::delayed_shutdown,
mp::VirtualMachine::State::suspending,
mp::VirtualMachine::State::suspended,
mp::VirtualMachine::State::unknown));
class TestSnapshotInvalidCores : public TestBaseSnapshot, public WithParamInterface<int>
{
};
TEST_P(TestSnapshotInvalidCores, rejectsInvalidNumberOfCores)
{
specs.num_cores = GetParam();
MP_EXPECT_THROW_THAT((MockBaseSnapshot{"snapshot", "comment", "", nullptr, specs, vm}),
std::runtime_error,
mpt::match_what(HasSubstr("Invalid number of cores")));
}
INSTANTIATE_TEST_SUITE_P(TestBaseSnapshot, TestSnapshotInvalidCores, Values(0, -1, -12345));
TEST_F(TestBaseSnapshot, rejectsNullMemorySize)
{
specs.mem_size = mp::MemorySize{"0B"};
MP_EXPECT_THROW_THAT((MockBaseSnapshot{"snapshot", "comment", "", nullptr, specs, vm}),
std::runtime_error,
mpt::match_what(HasSubstr("Invalid memory size")));
}
TEST_F(TestBaseSnapshot, rejectsNullDiskSize)
{
specs.disk_space = mp::MemorySize{"0B"};
MP_EXPECT_THROW_THAT((MockBaseSnapshot{"snapshot", "comment", "", nullptr, specs, vm}),
std::runtime_error,
mpt::match_what(HasSubstr("Invalid disk size")));
}
TEST_F(TestBaseSnapshot, reconstructsFromJson)
{
MockBaseSnapshot{test_json_file_path, vm, desc};
}
TEST_F(TestBaseSnapshot, adoptsNameFromJson)
{
constexpr auto* snapshot_name = "cheeseball";
auto json = test_snapshot_json();
mod_snapshot_json(json, "name", snapshot_name);
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_name(), snapshot_name);
}
TEST_F(TestBaseSnapshot, adoptsCommentFromJson)
{
constexpr auto* snapshot_comment = "Look behind you, a three-headed monkey!";
auto json = test_snapshot_json();
mod_snapshot_json(json, "comment", snapshot_comment);
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_comment(), snapshot_comment);
}
TEST_F(TestBaseSnapshot, linksToParentFromJson)
{
constexpr auto parent_idx = 42;
constexpr auto parent_name = "s42";
auto json = test_snapshot_json();
mod_snapshot_json(json, "parent", parent_idx);
EXPECT_CALL(vm, get_snapshot(TypedEq<int>(parent_idx)))
.WillOnce(
Return(std::make_shared<MockBaseSnapshot>(parent_name, "mock parent snapshot", "", nullptr, specs, vm)));
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_parents_name(), parent_name);
}
TEST_F(TestBaseSnapshot, adoptsInstanceIdFromJson)
{
constexpr std::string_view new_instance_id{"vm2"};
auto json = test_snapshot_json();
mod_snapshot_json(json, "cloud_init_instance_id", QJsonValue{new_instance_id.data()});
const auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_cloud_init_instance_id(), new_instance_id);
}
TEST_F(TestBaseSnapshot, adoptsIndexFromJson)
{
constexpr auto index = 31;
auto json = test_snapshot_json();
mod_snapshot_json(json, "index", index);
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_index(), index);
}
TEST_F(TestBaseSnapshot, adoptsTimestampFromJson)
{
constexpr auto timestamp = "1990-10-01T01:02:03.999Z";
auto json = test_snapshot_json();
mod_snapshot_json(json, "creation_timestamp", timestamp);
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_creation_timestamp().toString(Qt::ISODateWithMs), timestamp);
}
TEST_F(TestBaseSnapshot, adoptsNumCoresFromJson)
{
constexpr auto num_cores = 9;
auto json = test_snapshot_json();
mod_snapshot_json(json, "num_cores", num_cores);
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_num_cores(), num_cores);
}
TEST_F(TestBaseSnapshot, adoptsMemSizeFromJson)
{
constexpr auto mem = "1073741824";
auto json = test_snapshot_json();
mod_snapshot_json(json, "mem_size", mem);
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_mem_size().in_bytes(), QString{mem}.toInt());
}
TEST_F(TestBaseSnapshot, adoptsDiskSpaceFromJson)
{
constexpr auto disk = "1073741824";
auto json = test_snapshot_json();
mod_snapshot_json(json, "disk_space", disk);
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_disk_space().in_bytes(), QString{disk}.toInt());
}
TEST_F(TestBaseSnapshot, adoptsExtraInterfacesFromJson)
{
std::vector<mp::NetworkInterface> extra_interfaces{{"eth15", "15:15:15:15:15:15", false}};
auto json = test_snapshot_json();
mod_snapshot_json(json, "extra_interfaces", MP_JSONUTILS.extra_interfaces_to_json_array(extra_interfaces));
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_extra_interfaces(), extra_interfaces);
}
TEST_F(TestBaseSnapshot, doesNotComplainOnLegacySnapshot)
{
auto json = test_legacy_snapshot_json();
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_extra_interfaces(), desc.extra_interfaces);
}
TEST_F(TestBaseSnapshot, adoptsStateFromJson)
{
constexpr auto state = mp::VirtualMachine::State::stopped;
auto json = test_snapshot_json();
mod_snapshot_json(json, "state", static_cast<int>(state));
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_state(), state);
}
TEST_F(TestBaseSnapshot, adoptsMetadataFromJson)
{
auto metadata = QJsonObject{};
metadata["arguments"] = "Meathook:\n"
"You've got a real attitude problem!\n"
"\n"
"Guybrush Threepwood:\n"
"Well... you've got a real hair problem!\n"
"\n"
"Meathook:\n"
"You just don't know when to quit, do you?\n"
"\n"
"Guybrush Threepwood:\n"
"Neither did your barber.";
auto json = test_snapshot_json();
mod_snapshot_json(json, "metadata", metadata);
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
EXPECT_EQ(snapshot.get_metadata(), metadata);
}
TEST_F(TestBaseSnapshot, adoptsMountsFromJson)
{
constexpr auto src_path = "You fight like a dairy farmer.";
constexpr auto dst_path = "How appropriate. You fight like a cow.";
constexpr auto host_uid = 1, instance_uid = 2, host_gid = 3, instance_gid = 4;
constexpr auto mount_type = mp::VMMount::MountType::Native;
QJsonArray mounts{};
QJsonObject mount{};
QJsonArray uid_mappings{};
QJsonObject uid_mapping{};
QJsonArray gid_mappings{};
QJsonObject gid_mapping{};
uid_mapping["host_uid"] = host_uid;
uid_mapping["instance_uid"] = instance_uid;
uid_mappings.append(uid_mapping);
gid_mapping["host_gid"] = host_gid;
gid_mapping["instance_gid"] = instance_gid;
gid_mappings.append(gid_mapping);
mount["source_path"] = src_path;
mount["target_path"] = dst_path;
mount["uid_mappings"] = uid_mappings;
mount["gid_mappings"] = gid_mappings;
mount["mount_type"] = static_cast<int>(mount_type);
mounts.append(mount);
auto json = test_snapshot_json();
mod_snapshot_json(json, "mounts", mounts);
auto snapshot = MockBaseSnapshot{plant_snapshot_json(json), vm, desc};
auto snapshot_mounts = snapshot.get_mounts();
ASSERT_THAT(snapshot_mounts, SizeIs(mounts.size()));
const auto [snapshot_mnt_dst, snapshot_mount] = *snapshot_mounts.begin();
EXPECT_EQ(snapshot_mnt_dst, dst_path);
EXPECT_EQ(snapshot_mount.get_source_path(), src_path);
EXPECT_EQ(snapshot_mount.get_mount_type(), mount_type);
ASSERT_THAT(snapshot_mount.get_uid_mappings(), SizeIs(uid_mappings.size()));
const auto [snapshot_host_uid, snapshot_instance_uid] = snapshot_mount.get_uid_mappings().front();
EXPECT_EQ(snapshot_host_uid, host_uid);
EXPECT_EQ(snapshot_instance_uid, instance_uid);
ASSERT_THAT(snapshot_mount.get_gid_mappings(), SizeIs(gid_mappings.size()));
const auto [snapshot_host_gid, snapshot_instance_gid] = snapshot_mount.get_gid_mappings().front();
EXPECT_EQ(snapshot_host_gid, host_gid);
EXPECT_EQ(snapshot_instance_gid, instance_gid);
}
class TestSnapshotRejectedNonPositiveIndices : public TestBaseSnapshot, public WithParamInterface<int>
{
};
TEST_P(TestSnapshotRejectedNonPositiveIndices, refusesNonPositiveIndexFromJson)
{
const auto index = GetParam();
auto json = test_snapshot_json();
mod_snapshot_json(json, "index", index);
MP_EXPECT_THROW_THAT((MockBaseSnapshot{plant_snapshot_json(json), vm, desc}),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr("not positive"), HasSubstr(std::to_string(index)))));
}
INSTANTIATE_TEST_SUITE_P(TestBaseSnapshot, TestSnapshotRejectedNonPositiveIndices, Values(0, -1, -31));
TEST_F(TestBaseSnapshot, refusesIndexAboveMax)
{
constexpr auto index = 25623956;
auto json = test_snapshot_json();
mod_snapshot_json(json, "index", index);
MP_EXPECT_THROW_THAT((MockBaseSnapshot{plant_snapshot_json(json), vm, desc}),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr("Maximum"), HasSubstr(std::to_string(index)))));
}
TEST_F(TestBaseSnapshot, setsName)
{
constexpr auto new_name = "Murray";
auto snapshot = MockBaseSnapshot{test_json_file_path, vm, desc};
snapshot.set_name(new_name);
EXPECT_EQ(snapshot.get_name(), new_name);
}
TEST_F(TestBaseSnapshot, setsComment)
{
constexpr auto new_comment = "I once owned a dog that was smarter than you.\n"
"He must have taught you everything you know.";
auto snapshot = MockBaseSnapshot{test_json_file_path, vm, desc};
snapshot.set_comment(new_comment);
EXPECT_EQ(snapshot.get_comment(), new_comment);
}
TEST_F(TestBaseSnapshot, setsParent)
{
auto child = MockBaseSnapshot{test_json_file_path, vm, desc};
auto parent = std::make_shared<MockBaseSnapshot>("parent", "", "", nullptr, specs, vm);
child.set_parent(parent);
EXPECT_EQ(child.get_parent(), parent);
}
class TestSnapshotPersistence : public TestBaseSnapshot,
public WithParamInterface<std::function<void(MockBaseSnapshot&)>>
{
};
TEST_P(TestSnapshotPersistence, persistsOnEdition)
{
constexpr auto index = 55;
auto setter = GetParam();
auto json = test_snapshot_json();
mod_snapshot_json(json, "index", index);
MockBaseSnapshot snapshot_orig{plant_snapshot_json(json), vm, desc};
setter(snapshot_orig);
const auto file_path = derive_persisted_snapshot_file_path(index);
const MockBaseSnapshot snapshot_edited{file_path, vm, desc};
EXPECT_EQ(snapshot_edited, snapshot_orig);
}
INSTANTIATE_TEST_SUITE_P(TestBaseSnapshot,
TestSnapshotPersistence,
Values([](MockBaseSnapshot& s) { s.set_name("asdf"); },
[](MockBaseSnapshot& s) { s.set_comment("fdsa"); },
[](MockBaseSnapshot& s) { s.set_parent(nullptr); }));
TEST_F(TestBaseSnapshot, capturePersists)
{
NiceMock<MockBaseSnapshot> snapshot{"Big Whoop", "treasure", "", nullptr, specs, vm};
snapshot.capture();
const auto expected_file = QFileInfo{derive_persisted_snapshot_file_path(snapshot.get_index())};
EXPECT_TRUE(expected_file.exists());
EXPECT_TRUE(expected_file.isFile());
}
TEST_F(TestBaseSnapshot, captureCallsImpl)
{
MockBaseSnapshot snapshot{"LeChuck", "'s Revenge", "", nullptr, specs, vm};
EXPECT_CALL(snapshot, capture_impl).Times(1);
snapshot.capture();
}
TEST_F(TestBaseSnapshot, applyCallsImpl)
{
MockBaseSnapshot snapshot{"Guybrush", "fears porcelain", "", nullptr, specs, vm};
EXPECT_CALL(snapshot, apply_impl).Times(1);
snapshot.apply();
}
TEST_F(TestBaseSnapshot, eraseCallsImpl)
{
NiceMock<MockBaseSnapshot> snapshot{"House of Mojo", "voodoo", "", nullptr, specs, vm};
snapshot.capture();
EXPECT_CALL(snapshot, erase_impl).Times(1);
snapshot.erase();
}
TEST_F(TestBaseSnapshot, eraseRemovesFile)
{
NiceMock<MockBaseSnapshot> snapshot{"House of Mojo", "voodoo", "", nullptr, specs, vm};
snapshot.capture();
const auto expected_file_path = derive_persisted_snapshot_file_path(snapshot.get_index());
ASSERT_TRUE(QFileInfo{expected_file_path}.exists());
snapshot.erase();
EXPECT_FALSE(QFileInfo{expected_file_path}.exists());
}
TEST_F(TestBaseSnapshot, eraseThrowsIfUnableToRenameFile)
{
NiceMock<MockBaseSnapshot> snapshot{"voodoo-sword", "Cursed Cutlass of Kaflu", "", nullptr, specs, vm};
snapshot.capture();
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
const auto expected_file_path = derive_persisted_snapshot_file_path(snapshot.get_index());
EXPECT_CALL(*mock_file_ops, rename(Property(&QFile::fileName, Eq(expected_file_path)), _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(snapshot.erase(),
std::runtime_error,
mpt::match_what(HasSubstr("Failed to move snapshot file")));
}
TEST_F(TestBaseSnapshot, restoresFileOnFailureToErase)
{
NiceMock<MockBaseSnapshot> snapshot{"ultimate-insult",
"A powerful weapon capable of crippling even the toughest pirate's ego.",
"",
nullptr,
specs,
vm};
snapshot.capture();
const auto expected_file_path = derive_persisted_snapshot_file_path(snapshot.get_index());
ASSERT_TRUE(QFileInfo{expected_file_path}.exists());
EXPECT_CALL(snapshot, erase_impl).WillOnce([&expected_file_path] {
ASSERT_FALSE(QFileInfo{expected_file_path}.exists());
throw std::runtime_error{"test"};
});
try
{
snapshot.erase();
FAIL() << "shouldn't be here";
}
catch (const std::runtime_error&)
{
EXPECT_TRUE(QFileInfo{expected_file_path}.exists());
}
}
TEST_F(TestBaseSnapshot, throwsIfUnableToOpenFile)
{
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, open(Property(&QFileDevice::fileName, Eq(test_json_file_path)), _))
.WillOnce(Return(false));
MP_EXPECT_THROW_THAT(
(MockBaseSnapshot{test_json_file_path, vm, desc}),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr("Could not open"), HasSubstr(test_json_file_path.toStdString()))));
}
TEST_F(TestBaseSnapshot, throwsOnEmptyJson)
{
const auto snapshot_file_path = plant_snapshot_json(QJsonObject{});
MP_EXPECT_THROW_THAT((MockBaseSnapshot{snapshot_file_path, vm, desc}),
std::runtime_error,
mpt::match_what(HasSubstr("Empty")));
}
TEST_F(TestBaseSnapshot, throwsOnBadFormat)
{
const auto snapshot_file_path = vm.tmp_dir->filePath("wrong");
mpt::make_file_with_content(
snapshot_file_path,
"(Guybrush): Can I call you Bob?\n"
"\n"
"(Murray): You may call me Murray! I am a powerful demonic force! I'm the harbinger of your doom, and the "
"forces of darkness will applaude me as I stride through the gates of hell, carrying your head on a pike!\n"
"\n"
"(Guybrush): \"Stride\"?\n"
"\n"
"(Murray): Alright, then. ROLL! I shall ROLL through the gates of hell! Must you take the fun out of "
"everything?");
MP_EXPECT_THROW_THAT((MockBaseSnapshot{snapshot_file_path, vm, desc}),
std::runtime_error,
mpt::match_what(HasSubstr("Could not parse snapshot JSON")));
}
TEST_F(TestBaseSnapshot, throwsOnMissingParent)
{
EXPECT_CALL(vm, get_snapshot(An<int>())).WillOnce(Throw(std::out_of_range{"Incognito"}));
MP_EXPECT_THROW_THAT((MockBaseSnapshot{test_json_file_path, vm, desc}),
std::runtime_error,
mpt::match_what(HasSubstr("Missing snapshot parent")));
}
} // namespace
| 27,563
|
C++
|
.cpp
| 624
| 36.230769
| 119
| 0.645013
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,646
|
mock_sftp.cpp
|
canonical_multipass/tests/mock_sftp.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_sftp.h"
extern "C"
{
IMPL_MOCK_DEFAULT(1, sftp_new);
IMPL_MOCK_DEFAULT(1, sftp_free);
IMPL_MOCK_DEFAULT(1, sftp_init);
IMPL_MOCK_DEFAULT(4, sftp_open);
IMPL_MOCK_DEFAULT(3, sftp_write);
IMPL_MOCK_DEFAULT(3, sftp_read);
IMPL_MOCK_DEFAULT(1, sftp_get_error);
IMPL_MOCK_DEFAULT(1, sftp_close);
IMPL_MOCK_DEFAULT(2, sftp_stat);
IMPL_MOCK_DEFAULT(2, sftp_lstat);
IMPL_MOCK_DEFAULT(2, sftp_opendir);
IMPL_MOCK_DEFAULT(2, sftp_readdir);
IMPL_MOCK_DEFAULT(2, sftp_readlink);
IMPL_MOCK_DEFAULT(3, sftp_mkdir);
IMPL_MOCK_DEFAULT(3, sftp_symlink);
IMPL_MOCK_DEFAULT(2, sftp_unlink);
IMPL_MOCK_DEFAULT(3, sftp_setstat);
IMPL_MOCK_DEFAULT(1, sftp_dir_eof);
IMPL_MOCK_DEFAULT(3, sftp_chmod);
}
| 1,400
|
C++
|
.cpp
| 39
| 32.538462
| 72
| 0.711765
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,647
|
test_timer.cpp
|
canonical_multipass/tests/test_timer.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "mock_singleton_helpers.h"
#include <multipass/timer.h>
#include <atomic>
#include <chrono>
#include <thread>
namespace mp = multipass;
namespace mpu = multipass::utils;
using namespace std::chrono;
using namespace std::chrono_literals;
using namespace testing;
namespace
{
struct MockTimerSyncFuncs : public mpu::TimerSyncFuncs
{
using TimerSyncFuncs::TimerSyncFuncs;
MOCK_METHOD(void, notify_all, (std::condition_variable&), (const, override));
MOCK_METHOD(void, wait, (std::condition_variable&, std::unique_lock<std::mutex>&, std::function<bool()>),
(const, override));
MOCK_METHOD(bool, wait_for,
(std::condition_variable&, std::unique_lock<std::mutex>&,
(const std::chrono::duration<int, std::milli>&), std::function<bool()>),
(const, override));
MP_MOCK_SINGLETON_BOILERPLATE(MockTimerSyncFuncs, TimerSyncFuncs);
};
struct TestTimer : public testing::Test
{
TestTimer()
: t{default_timeout, [this] {
{
std::lock_guard<std::mutex> test_lock{cv_m};
++timeout_count;
}
cv.notify_all();
}}
{
}
auto mock_wait(std::unique_lock<std::mutex>& timer_lock, std::atomic_bool& target_state)
{
std::unique_lock<std::mutex> test_lock(cv_m);
// Unlock the Timer's internal lock
timer_lock.unlock();
// Notify the test thread that the timer is running
target_state.store(true);
cv.notify_all();
// Wait for notification from main test thread
cv.wait(test_lock, [this] { return test_notify_called.load(); });
test_notify_called.store(false);
// Re-lock the Timer's internal lock before returning
timer_lock.lock();
}
auto make_mock_wait_for(const bool& timeout_status)
{
return [this, timeout_status](std::unique_lock<std::mutex>& timer_lock) {
mock_wait(timer_lock, timer_running);
return timeout_status;
};
}
void wait_for(const std::atomic_bool& target_state)
{
std::unique_lock<std::mutex> test_lock(cv_m);
cv.wait(test_lock, [&target_state] { return target_state.load(); });
}
std::unique_lock<std::mutex> notify_test_wait()
{
std::unique_lock<std::mutex> test_lock(cv_m);
test_notify_called.store(true);
cv.notify_all();
return test_lock;
}
void SetUp() override
{
ON_CALL(*mock_timer_sync_funcs, wait).WillByDefault(WithArg<1>([this](auto& timer_lock) {
mock_wait(timer_lock, timer_paused);
}));
EXPECT_CALL(*mock_timer_sync_funcs, notify_all)
.WillOnce(Return()) // Handles the Timer::stop() in Timer::start()
.WillRepeatedly([this](auto&...) { // Handles all other notify_all calls in Timer
notify_test_wait(); // discard returned lock
});
}
std::atomic_int timeout_count{0};
std::atomic_bool test_notify_called{false}, timer_running{false}, timer_paused{false};
std::condition_variable cv;
std::mutex cv_m;
const std::chrono::milliseconds default_timeout{10};
const std::chrono::seconds default_wait{1};
MockTimerSyncFuncs::GuardedMock attr{MockTimerSyncFuncs::inject()};
MockTimerSyncFuncs* mock_timer_sync_funcs = attr.first;
mpu::Timer t;
};
} // namespace
TEST_F(TestTimer, times_out)
{
EXPECT_CALL(*mock_timer_sync_funcs, wait_for(_, _, Eq(default_timeout), _))
.WillOnce(WithArg<1>(make_mock_wait_for(false)));
t.start();
ASSERT_EQ(timeout_count.load(), 0) << "Should not have timed out yet";
// Notify the mocked wait_for()
auto test_lock = notify_test_wait();
ASSERT_TRUE(cv.wait_for(test_lock, default_wait, [this] { return timeout_count.load() == 1; }))
<< "Did not time out in reasonable timeframe";
ASSERT_EQ(timeout_count.load(), 1) << "Should have timed out";
}
TEST_F(TestTimer, stops)
{
EXPECT_CALL(*mock_timer_sync_funcs, wait_for(_, _, Eq(default_timeout), _))
.WillOnce(WithArg<1>(make_mock_wait_for(true)));
t.start();
// Wait for the the timer to be "running" in the mocked wait_for()
wait_for(timer_running);
// stop() blocks until the Timer thread has joined, ie, it is finished
t.stop();
ASSERT_EQ(timeout_count.load(), 0) << "Should not have timed out";
}
TEST_F(TestTimer, pauses)
{
EXPECT_CALL(*mock_timer_sync_funcs, wait_for(_, _, Eq(default_timeout), _))
.WillOnce(WithArg<1>(make_mock_wait_for(true)));
EXPECT_CALL(*mock_timer_sync_funcs, wait);
t.start();
// Wait for the the timer to be "running" in the mocked wait_for()
wait_for(timer_running);
t.pause();
// Wait for the the timer to be "paused" in the mocked wait()
wait_for(timer_paused);
ASSERT_EQ(timeout_count.load(), 0) << "Should not have timed out";
}
TEST_F(TestTimer, resumes)
{
// The initial start
EXPECT_CALL(*mock_timer_sync_funcs, wait_for(_, _, Eq(default_timeout), _))
.WillOnce(WithArg<1>(make_mock_wait_for(true)));
// After resume() is called, there should be less time left than the default timeout
EXPECT_CALL(*mock_timer_sync_funcs, wait_for(_, _, Lt(default_timeout), _)).WillOnce(Return(false));
EXPECT_CALL(*mock_timer_sync_funcs, wait);
t.start();
// Wait for the the timer to be "running" in the mocked wait_for()
wait_for(timer_running);
t.pause();
// Wait for the the timer to be "paused" in the mocked wait()
wait_for(timer_paused);
t.resume();
std::unique_lock<std::mutex> test_lock(cv_m);
// Wait on the actual Timer timeout
ASSERT_TRUE(cv.wait_for(test_lock, default_wait, [this] { return timeout_count.load() == 1; }))
<< "Did not time out in reasonable timeframe";
ASSERT_EQ(timeout_count.load(), 1) << "Should have timed out";
}
TEST_F(TestTimer, stops_paused)
{
EXPECT_CALL(*mock_timer_sync_funcs, wait_for(_, _, Eq(default_timeout), _))
.WillOnce(WithArg<1>(make_mock_wait_for(true)));
EXPECT_CALL(*mock_timer_sync_funcs, wait);
t.start();
// Wait for the the timer to be "running" in the mocked wait_for()
wait_for(timer_running);
t.pause();
// Wait for the the timer to be "paused" in the mocked wait()
wait_for(timer_paused);
t.stop();
ASSERT_EQ(timeout_count.load(), 0) << "Should not have timed out";
}
TEST_F(TestTimer, cancels)
{
EXPECT_CALL(*mock_timer_sync_funcs, wait_for(_, _, Eq(default_timeout), _))
.WillOnce(WithArg<1>(make_mock_wait_for(true)));
// Don't use the TestTimer mpu::Timer since we are testing it going out of scope
{
mpu::Timer scoped_timer{default_timeout, [this] { ++timeout_count; }};
scoped_timer.start();
// Wait for the the timer to be "running" in the mocked wait_for()
wait_for(timer_running);
}
ASSERT_EQ(timeout_count.load(), 0) << "Should not have timed out";
}
TEST_F(TestTimer, restarts)
{
EXPECT_CALL(*mock_timer_sync_funcs, wait_for(_, _, Eq(default_timeout), _))
.WillOnce(WithArg<1>(make_mock_wait_for(true)))
.WillOnce(WithArg<1>(make_mock_wait_for(false)));
t.start();
// Wait for the the timer to be "running" in the mocked wait_for()
wait_for(timer_running);
ASSERT_EQ(timeout_count.load(), 0) << "Should not have timed out yet";
t.start(); // start() will stop the timer if it's running
// Wait for the the timer to be "running" again in the mocked wait_for()
wait_for(timer_running);
ASSERT_EQ(timeout_count.load(), 0) << "Should not have timed out yet";
// Notify the mocked wait_for()
auto test_lock = notify_test_wait();
// Wait on the Timer callback
ASSERT_TRUE(cv.wait_for(test_lock, default_wait, [this] { return timeout_count.load() > 0; }))
<< "Did not time out in reasonable timeframe";
ASSERT_EQ(timeout_count.load(), 1) << "Should have timed out once now";
}
TEST_F(TestTimer, stopped_ignores_pause)
{
// Indicates the Timer was never running
EXPECT_CALL(*mock_timer_sync_funcs, wait_for).Times(0);
t.pause();
ASSERT_EQ(timeout_count.load(), 0) << "Should not have timed out";
}
TEST_F(TestTimer, stopped_ignores_resume)
{
// Indicates the Timer was never running
EXPECT_CALL(*mock_timer_sync_funcs, wait_for).Times(0);
t.resume();
ASSERT_EQ(timeout_count.load(), 0) << "Should not have timed out";
}
TEST_F(TestTimer, running_ignores_resume)
{
EXPECT_CALL(*mock_timer_sync_funcs, wait_for(_, _, Eq(default_timeout), _))
.WillOnce(WithArg<1>(make_mock_wait_for(true)));
t.start();
// Wait for the the timer to be "running" in the mocked wait_for()
wait_for(timer_running);
t.resume();
ASSERT_EQ(timeout_count.load(), 0) << "Should not have timed out";
}
| 9,623
|
C++
|
.cpp
| 236
| 35.050847
| 109
| 0.649226
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,648
|
test_simple_streams_manifest.cpp
|
canonical_multipass/tests/test_simple_streams_manifest.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common.h"
#include "file_operations.h"
#include "mock_settings.h"
#include <multipass/constants.h>
#include <multipass/exceptions/manifest_exceptions.h>
#include <multipass/simple_streams_manifest.h>
#include <optional>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct TestSimpleStreamsManifest : public Test
{
void SetUp() override
{
EXPECT_CALL(mock_settings, get(Eq(mp::driver_key))).WillRepeatedly(Return("emu")); /* TODO parameterize driver
(code branches for lxd) */
}
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject<StrictMock>();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
};
TEST_F(TestSimpleStreamsManifest, can_parse_image_info)
{
auto json = mpt::load_test_file("good_manifest.json");
auto manifest = mp::SimpleStreamsManifest::fromJson(json, std::nullopt, "");
EXPECT_THAT(manifest->updated_at, Eq("Wed, 20 May 2020 16:47:50 +0000"));
EXPECT_THAT(manifest->products.size(), Eq(2u));
const auto info = manifest->image_records["default"];
ASSERT_THAT(info, NotNull());
EXPECT_FALSE(info->image_location.isEmpty());
}
TEST_F(TestSimpleStreamsManifest, can_find_info_by_alias)
{
auto json = mpt::load_test_file("good_manifest.json");
const auto host_url{"http://stream/url"};
auto manifest = mp::SimpleStreamsManifest::fromJson(json, std::nullopt, host_url);
const QString expected_id{"1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac"};
const QString expected_location =
QString("server/releases/xenial/release-20170516/ubuntu-16.04-server-cloudimg-%1-disk1.img").arg(MANIFEST_ARCH);
const auto info = manifest->image_records[expected_id];
ASSERT_THAT(info, NotNull());
EXPECT_THAT(info->image_location, Eq(expected_location));
EXPECT_THAT(info->id, Eq(expected_id));
EXPECT_THAT(info->stream_location, Eq(host_url));
}
TEST_F(TestSimpleStreamsManifest, throws_on_invalid_json)
{
QByteArray json;
EXPECT_THROW(mp::SimpleStreamsManifest::fromJson(json, std::nullopt, ""), mp::GenericManifestException);
}
TEST_F(TestSimpleStreamsManifest, throws_on_invalid_top_level_type)
{
auto json = mpt::load_test_file("invalid_top_level.json");
EXPECT_THROW(mp::SimpleStreamsManifest::fromJson(json, std::nullopt, ""), mp::GenericManifestException);
}
TEST_F(TestSimpleStreamsManifest, throws_when_missing_products)
{
auto json = mpt::load_test_file("missing_products_manifest.json");
EXPECT_THROW(mp::SimpleStreamsManifest::fromJson(json, std::nullopt, ""), mp::GenericManifestException);
}
TEST_F(TestSimpleStreamsManifest, throws_when_failed_to_parse_any_products)
{
auto json = mpt::load_test_file("missing_versions_manifest.json");
EXPECT_THROW(mp::SimpleStreamsManifest::fromJson(json, std::nullopt, ""), mp::EmptyManifestException);
json = mpt::load_test_file("missing_versions_manifest.json");
EXPECT_THROW(mp::SimpleStreamsManifest::fromJson(json, std::nullopt, ""), mp::EmptyManifestException);
}
TEST_F(TestSimpleStreamsManifest, chooses_newest_version)
{
auto json = mpt::load_test_file("releases/multiple_versions_manifest.json");
auto manifest = mp::SimpleStreamsManifest::fromJson(json, std::nullopt, "");
const QString expected_id{"8842e7a8adb01c7a30cc702b01a5330a1951b12042816e87efd24b61c5e2239f"};
const QString expected_location{"newest_image.img"};
const auto info = manifest->image_records["default"];
ASSERT_THAT(info, NotNull());
EXPECT_THAT(info->image_location, Eq(expected_location));
EXPECT_THAT(info->id, Eq(expected_id));
}
TEST_F(TestSimpleStreamsManifest, can_query_all_versions)
{
auto json = mpt::load_test_file("releases/multiple_versions_manifest.json");
auto manifest = mp::SimpleStreamsManifest::fromJson(json, std::nullopt, "");
QStringList all_known_hashes;
all_known_hashes << "1797c5c82016c1e65f4008fcf89deae3a044ef76087a9ec5b907c6d64a3609ac"
<< "8842e7a8adb01c7a30cc702b01a5330a1951b12042816e87efd24b61c5e2239f"
<< "1507bd2b3288ef4bacd3e699fe71b827b7ccf321ec4487e168a30d7089d3c8e4"
<< "ab115b83e7a8bebf3d3a02bf55ad0cb75a0ed515fcbc65fb0c9abe76c752921c";
for (const auto& hash : all_known_hashes)
{
const auto info = manifest->image_records[hash];
EXPECT_THAT(info, NotNull());
}
}
TEST_F(TestSimpleStreamsManifest, LXDDriverReturnsExpectedData)
{
EXPECT_CALL(mock_settings, get(Eq(mp::driver_key))).WillRepeatedly(Return("lxd"));
auto json = mpt::load_test_file("lxd_test_manifest.json");
auto manifest = mp::SimpleStreamsManifest::fromJson(json, std::nullopt, "");
EXPECT_EQ(manifest->products.size(), 2u);
const auto xenial_info = manifest->image_records["xenial"];
// combined_disk1-img_sha256 for xenial product
const QString expected_xenial_id{"09d24fab15c6e1c86a47d3de2e7fb6d01a10f9ff2655a43f0959a672e03e7674"};
EXPECT_EQ(xenial_info->id, expected_xenial_id);
// combined_disk-img_sha256 despite -kvm being available (canonical/multipass#2491)
const auto bionic_info = manifest->image_records["bionic"];
const QString expected_bionic_id{"09d24fab15c6e1c86a47d3de2e83d0d01a10f9ff2655a43f0959a672e03e7674"};
EXPECT_EQ(bionic_info->id, expected_bionic_id);
}
} // namespace
| 6,141
|
C++
|
.cpp
| 126
| 43.984127
| 120
| 0.736376
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,649
|
image_host_remote_count.cpp
|
canonical_multipass/tests/image_host_remote_count.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "image_host_remote_count.h"
#include <multipass/vm_image_host.h>
#include <multipass/vm_image_info.h>
#include <set>
#include <string>
namespace mp = multipass;
namespace mpt = multipass::test;
size_t mpt::count_remotes(mp::VMImageHost& host)
{
std::set<std::string> remotes;
auto counting_action = [&remotes](const std::string& remote, const VMImageInfo&) { remotes.insert(remote); };
host.update_manifests(false);
host.for_each_entry_do(counting_action);
return remotes.size();
}
| 1,145
|
C++
|
.cpp
| 31
| 34.612903
| 113
| 0.744585
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,650
|
test_backend_utils.cpp
|
canonical_multipass/tests/linux/test_backend_utils.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/mock_backend_utils.h"
#include "tests/mock_file_ops.h"
#include "tests/mock_logger.h"
#include "tests/mock_process_factory.h"
#include "tests/mock_singleton_helpers.h"
#include "tests/mock_utils.h"
#include <shared/shared_backend_utils.h>
#include <src/platform/backends/shared/linux/backend_utils.h>
#include <src/platform/backends/shared/linux/dbus_wrappers.h>
#include <multipass/format.h>
#include <multipass/logging/log.h>
#include <multipass/memory_size.h>
#include <QMap>
#include <QVariant>
#include <fcntl.h>
#include <sys/ioctl.h>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
namespace mp_dbus = mp::backend::dbus;
class MockDBusProvider : public mp_dbus::DBusProvider
{
public:
using DBusProvider::DBusProvider;
MOCK_METHOD(const mp_dbus::DBusConnection&, get_system_bus, (), (const, override));
MP_MOCK_SINGLETON_BOILERPLATE(MockDBusProvider, DBusProvider);
};
class MockDBusConnection : public mp_dbus::DBusConnection
{
public:
MockDBusConnection() : mp_dbus::DBusConnection(/* create_bus = */ false)
{
}
MOCK_METHOD(bool, is_connected, (), (const, override));
MOCK_METHOD(QDBusError, last_error, (), (const, override));
MOCK_METHOD(std::unique_ptr<mp_dbus::DBusInterface>, get_interface,
(const QString&, const QString&, const QString&), (const, override));
};
class MockDBusInterface : public mp_dbus::DBusInterface
{
public:
using DBusInterface::DBusInterface;
MOCK_METHOD(bool, is_valid, (), (const, override));
MOCK_METHOD(QDBusError, last_error, (), (const, override));
MOCK_METHOD(QString, interface, (), (const, override));
MOCK_METHOD(QString, path, (), (const, override));
MOCK_METHOD(QString, service, (), (const, override));
MOCK_METHOD(QDBusMessage, call_impl,
(QDBus::CallMode, const QString&, const QVariant&, const QVariant&, const QVariant&), (override));
};
struct CreateBridgeTest : public Test
{
void SetUp() override
{
logger_scope.mock_logger->screen_logs(mpl::Level::warning);
// These will accept any number of calls (0..N) but they can still be shadowed
EXPECT_CALL(*mock_dbus_provider, get_system_bus).WillRepeatedly(ReturnRef(mock_bus));
EXPECT_CALL(*mock_nm_root, is_valid).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_nm_settings, is_valid).WillRepeatedly(Return(true));
EXPECT_CALL(mock_bus, is_connected).WillRepeatedly(Return(true));
}
void inject_dbus_interfaces() // this moves the DBus interface mocks, so expectations must be set before calling
{
inject_root_interface();
inject_settings_interface();
}
void inject_root_interface() // moves mock, so expectations first please
{
EXPECT_CALL(mock_bus, get_interface(Eq("org.freedesktop.NetworkManager"), Eq("/org/freedesktop/NetworkManager"),
Eq("org.freedesktop.NetworkManager")))
.WillOnce(Return(ByMove(std::move(mock_nm_root))));
}
void inject_settings_interface() // moves mock, so expectations first please
{
EXPECT_CALL(mock_bus,
get_interface(Eq("org.freedesktop.NetworkManager"), Eq("/org/freedesktop/NetworkManager/Settings"),
Eq("org.freedesktop.NetworkManager.Settings")))
.WillOnce(Return(ByMove(std::move(mock_nm_settings))));
}
static auto make_obj_path_reply(const QString& obj_path)
{
return QDBusMessage{}.createReply(QVariant::fromValue(QDBusObjectPath{obj_path}));
}
static auto make_parent_connection_matcher(const char* child)
{
return Truly([child](const QVariant& arg) {
QMap<QString, QVariantMap> outer_map;
QMap<QString, QVariantMap>::const_iterator outer_it;
QVariantMap::const_iterator inner_it;
QString parent_name = get_bridge_name(child);
return (outer_map = arg.value<QMap<QString, QVariantMap>>()).size() == 2 &&
(outer_it = outer_map.find("connection")) != outer_map.end() && outer_it->size() == 3 &&
(inner_it = outer_it->find("id")) != outer_it->end() && inner_it->toString() == parent_name &&
(inner_it = outer_it->find("type")) != outer_it->end() && inner_it->toString() == "bridge" &&
(inner_it = outer_it->find("autoconnect-slaves")) != outer_it->end() && inner_it->toInt() == 1 &&
(outer_it = outer_map.find("bridge")) != outer_map.end() && outer_it->size() == 1 &&
(inner_it = outer_it->find("interface-name")) != outer_it->end() &&
inner_it->toString() == parent_name;
});
}
static auto make_child_connection_matcher(const char* child)
{
return Truly([child](const QVariant& arg) {
QMap<QString, QVariantMap> outer_map;
QMap<QString, QVariantMap>::const_iterator outer_it;
QVariantMap::const_iterator inner_it;
QString parent_name = get_bridge_name(child);
QString child_name = parent_name + "-child";
return (outer_map = arg.value<QMap<QString, QVariantMap>>()).size() == 1 &&
(outer_it = outer_map.find("connection")) != outer_map.end() && outer_it->size() == 6 &&
(inner_it = outer_it->find("id")) != outer_it->end() && inner_it->toString() == child_name &&
(inner_it = outer_it->find("type")) != outer_it->end() && inner_it->toString() == "802-3-ethernet" &&
(inner_it = outer_it->find("slave-type")) != outer_it->end() && inner_it->toString() == "bridge" &&
(inner_it = outer_it->find("master")) != outer_it->end() && inner_it->toString() == parent_name &&
(inner_it = outer_it->find("interface-name")) != outer_it->end() && inner_it->toString() == child &&
(inner_it = outer_it->find("autoconnect-priority")) != outer_it->end() && inner_it->toInt() > 0;
});
}
static auto make_object_path_matcher(const char* path)
{
return Property(&QVariant::value<QDBusObjectPath>,
Property(&QDBusObjectPath::path, mpt::match_qstring(Eq(path))));
}
static QString get_bridge_name(const char* child)
{
return (QString{"br-"} + child).left(15);
}
MockDBusProvider::GuardedMock mock_dbus_injection = MockDBusProvider::inject();
MockDBusProvider* mock_dbus_provider = mock_dbus_injection.first;
MockDBusConnection mock_bus{};
std::unique_ptr<MockDBusInterface> mock_nm_settings = std::make_unique<MockDBusInterface>();
std::unique_ptr<MockDBusInterface> mock_nm_root = std::make_unique<MockDBusInterface>();
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
const QVariant empty{};
};
TEST_F(CreateBridgeTest, creates_and_activates_connections) // success case
{
static constexpr auto network = "eth1234567890a";
static constexpr auto child_obj_path = "/an/obj/path/for/child";
static constexpr auto null_obj_path = "/";
{
InSequence seq{};
EXPECT_CALL(*mock_nm_settings,
call_impl(QDBus::Block, Eq("AddConnection"), make_parent_connection_matcher(network), empty, empty))
.WillOnce(Return(make_obj_path_reply("/a/b/c")));
EXPECT_CALL(*mock_nm_settings,
call_impl(QDBus::Block, Eq("AddConnection"), make_child_connection_matcher(network), empty, empty))
.WillOnce(Return(make_obj_path_reply(child_obj_path)));
auto null_obj_matcher = make_object_path_matcher(null_obj_path);
auto child_obj_matcher = make_object_path_matcher(child_obj_path);
EXPECT_CALL(*mock_nm_root, call_impl(QDBus::Block, Eq("ActivateConnection"), child_obj_matcher,
null_obj_matcher, null_obj_matcher))
.WillOnce(Return(make_obj_path_reply("/active/obj/path")));
}
inject_dbus_interfaces();
EXPECT_EQ(MP_BACKEND.create_bridge_with(network), get_bridge_name(network).toStdString());
}
TEST_F(CreateBridgeTest, throws_if_bus_disconnected)
{
auto msg = QStringLiteral("DBus error msg");
EXPECT_CALL(mock_bus, is_connected).WillOnce(Return(false));
EXPECT_CALL(mock_bus, last_error).WillOnce(Return(QDBusError{QDBusError::BadAddress, msg}));
MP_EXPECT_THROW_THAT(
MP_BACKEND.create_bridge_with("asdf"), mp::backend::CreateBridgeException,
mpt::match_what(AllOf(HasSubstr("Could not create bridge"), HasSubstr("Failed to connect to D-Bus system bus"),
HasSubstr(msg.toStdString()))));
}
struct CreateBridgeInvalidInterfaceTest : public CreateBridgeTest, WithParamInterface<bool>
{
};
TEST_P(CreateBridgeInvalidInterfaceTest, throws_if_interface_invalid)
{
bool invalid_root_interface = GetParam(); // otherwise, invalid settings interface
auto& mock_nm_interface = invalid_root_interface ? mock_nm_root : mock_nm_settings;
auto msg = QStringLiteral("DBus error msg");
EXPECT_CALL(*mock_nm_interface, is_valid).WillOnce(Return(false));
EXPECT_CALL(*mock_nm_interface, last_error).WillOnce(Return(QDBusError{QDBusError::InvalidInterface, msg}));
inject_root_interface();
if (!invalid_root_interface)
inject_settings_interface();
MP_ASSERT_THROW_THAT(
MP_BACKEND.create_bridge_with("whatever"), mp::backend::CreateBridgeException,
mpt::match_what(AllOf(HasSubstr("Could not reach remote D-Bus object"), HasSubstr(msg.toStdString()))));
}
INSTANTIATE_TEST_SUITE_P(CreateBridgeTest, CreateBridgeInvalidInterfaceTest, Values(true, false));
TEST_F(CreateBridgeTest, throws_on_failure_to_create_first_connection)
{
auto msg = QStringLiteral("Nope");
auto ifc = QStringLiteral("An interface");
auto obj = QStringLiteral("An object");
auto svc = QStringLiteral("A service");
EXPECT_CALL(*mock_nm_settings, call_impl(_, Eq("AddConnection"), _, _, _))
.WillOnce(Return(QDBusMessage::createError(QDBusError::AccessDenied, msg)));
EXPECT_CALL(*mock_nm_settings, interface).WillOnce(Return(ifc));
EXPECT_CALL(*mock_nm_settings, path).WillOnce(Return(obj));
EXPECT_CALL(*mock_nm_settings, service).WillOnce(Return(svc));
inject_dbus_interfaces();
MP_ASSERT_THROW_THAT(MP_BACKEND.create_bridge_with("umdolita"), mp::backend::CreateBridgeException,
mpt::match_what(AllOf(HasSubstr(msg.toStdString()), HasSubstr(ifc.toStdString()),
HasSubstr(obj.toStdString()), HasSubstr(svc.toStdString()))));
}
TEST_F(CreateBridgeTest, throws_on_failure_to_create_second_connection)
{
const auto msg = QStringLiteral("Still not");
const auto ifc = QStringLiteral("the interface");
const auto obj = QStringLiteral("the object");
const auto svc = QStringLiteral("the service");
const auto new_connection_path = QStringLiteral("/a/b/c");
EXPECT_CALL(*mock_nm_settings, call_impl(_, Eq("AddConnection"), _, _, _))
.WillOnce(Return(make_obj_path_reply(new_connection_path)))
.WillOnce(Return(QDBusMessage::createError(QDBusError::UnknownMethod, msg)));
EXPECT_CALL(*mock_nm_settings, interface).WillOnce(Return(ifc));
EXPECT_CALL(*mock_nm_settings, path).WillOnce(Return(obj));
EXPECT_CALL(*mock_nm_settings, service).WillOnce(Return(svc));
inject_dbus_interfaces();
std::unique_ptr<MockDBusInterface> mock_nm_connection = std::make_unique<MockDBusInterface>();
EXPECT_CALL(*mock_nm_connection, call_impl(_, Eq("Delete"), empty, empty, empty));
EXPECT_CALL(mock_bus, get_interface(Eq("org.freedesktop.NetworkManager"), Eq(new_connection_path),
Eq("org.freedesktop.NetworkManager.Settings.Connection")))
.WillOnce(Return(ByMove(std::move(mock_nm_connection))));
MP_ASSERT_THROW_THAT(MP_BACKEND.create_bridge_with("abc"), mp::backend::CreateBridgeException,
mpt::match_what(AllOf(HasSubstr(msg.toStdString()), HasSubstr(ifc.toStdString()),
HasSubstr(obj.toStdString()), HasSubstr(svc.toStdString()))));
}
TEST_F(CreateBridgeTest, throws_on_failure_to_activate_second_connection)
{
const auto msg = QStringLiteral("Refusing");
const auto ifc = QStringLiteral("interface");
const auto obj = QStringLiteral("object");
const auto svc = QStringLiteral("service");
const auto new_connection_path1 = QStringLiteral("/foo");
const auto new_connection_path2 = QStringLiteral("/bar");
EXPECT_CALL(*mock_nm_settings, call_impl(_, Eq("AddConnection"), _, _, _))
.WillOnce(Return(make_obj_path_reply(new_connection_path1)))
.WillOnce(Return(make_obj_path_reply(new_connection_path2)));
EXPECT_CALL(*mock_nm_root, call_impl(_, Eq("ActivateConnection"), _, _, _))
.WillOnce(Return(QDBusMessage::createError(QDBusError::InvalidArgs, msg)));
EXPECT_CALL(*mock_nm_root, interface).WillOnce(Return(ifc));
EXPECT_CALL(*mock_nm_root, path).WillOnce(Return(obj));
EXPECT_CALL(*mock_nm_root, service).WillOnce(Return(svc));
inject_dbus_interfaces();
std::unique_ptr<MockDBusInterface> mock_nm_connection1 = std::make_unique<MockDBusInterface>();
std::unique_ptr<MockDBusInterface> mock_nm_connection2 = std::make_unique<MockDBusInterface>();
EXPECT_CALL(*mock_nm_connection1, call_impl(_, Eq("Delete"), empty, empty, empty));
EXPECT_CALL(mock_bus, get_interface(Eq("org.freedesktop.NetworkManager"), Eq(new_connection_path1),
Eq("org.freedesktop.NetworkManager.Settings.Connection")))
.WillOnce(Return(ByMove(std::move(mock_nm_connection1))));
EXPECT_CALL(*mock_nm_connection2, call_impl(_, Eq("Delete"), empty, empty, empty));
EXPECT_CALL(mock_bus, get_interface(Eq("org.freedesktop.NetworkManager"), Eq(new_connection_path2),
Eq("org.freedesktop.NetworkManager.Settings.Connection")))
.WillOnce(Return(ByMove(std::move(mock_nm_connection2))));
MP_ASSERT_THROW_THAT(MP_BACKEND.create_bridge_with("kaka"), mp::backend::CreateBridgeException,
mpt::match_what(AllOf(HasSubstr(msg.toStdString()), HasSubstr(ifc.toStdString()),
HasSubstr(obj.toStdString()), HasSubstr(svc.toStdString()))));
}
TEST_F(CreateBridgeTest, logs_on_failure_to_rollback)
{
const auto child_path = QStringLiteral("/child");
const auto original_error = 255;
const auto rollback_error = "fail";
EXPECT_CALL(*mock_nm_settings, call_impl(_, Eq("AddConnection"), _, _, _))
.WillOnce(Return(make_obj_path_reply("/asdf")))
.WillOnce(Return(make_obj_path_reply(child_path)));
EXPECT_CALL(*mock_nm_root, call_impl(_, Eq("ActivateConnection"), _, _, _)).WillOnce(Throw(original_error));
inject_dbus_interfaces();
std::unique_ptr<MockDBusInterface> mock_nm_connection1 = std::make_unique<MockDBusInterface>();
EXPECT_CALL(*mock_nm_connection1, call_impl(_, Eq("Delete"), empty, empty, empty))
.WillOnce(Throw(std::runtime_error{rollback_error}));
EXPECT_CALL(mock_bus, get_interface(Eq("org.freedesktop.NetworkManager"), Eq(child_path),
Eq("org.freedesktop.NetworkManager.Settings.Connection")))
.WillOnce(Return(ByMove(std::move(mock_nm_connection1))));
logger_scope.mock_logger->expect_log(mpl::Level::error, rollback_error);
MP_ASSERT_THROW_THAT(MP_BACKEND.create_bridge_with("gigi"), int, Eq(original_error));
}
struct CreateBridgeExceptionTest : public CreateBridgeTest, WithParamInterface<bool>
{
};
TEST_P(CreateBridgeExceptionTest, create_bridge_exception_info)
{
auto rollback = GetParam();
static constexpr auto specific_info = "specific error details";
auto generic_msg = fmt::format("Could not {} bridge", rollback ? "rollback" : "create");
EXPECT_THAT((mp::backend::CreateBridgeException{specific_info, QDBusError{}, rollback}),
mpt::match_what(AllOf(HasSubstr(generic_msg), HasSubstr(specific_info))));
}
TEST_P(CreateBridgeExceptionTest, create_bridge_exception_includes_dbus_cause_when_available)
{
auto msg = QStringLiteral("DBus error msg");
QDBusError dbus_error = {QDBusError::Other, msg};
ASSERT_TRUE(dbus_error.isValid());
EXPECT_THAT((mp::backend::CreateBridgeException{"detail", dbus_error, GetParam()}),
mpt::match_what(HasSubstr(msg.toStdString())));
}
TEST_P(CreateBridgeExceptionTest, create_bridge_exception_mentions_unknown_cause_when_unavailable)
{
QDBusError dbus_error{};
ASSERT_FALSE(dbus_error.isValid());
EXPECT_THAT((mp::backend::CreateBridgeException{"detail", dbus_error, GetParam()}),
mpt::match_what(HasSubstr("unknown cause")));
}
INSTANTIATE_TEST_SUITE_P(CreateBridgeTest, CreateBridgeExceptionTest, Values(true, false));
} // namespace
TEST(LinuxBackendUtils, check_for_kvm_support_no_error_does_not_throw)
{
auto [mock_file_ops, file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, exists(A<const QFile&>())).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(true));
EXPECT_NO_THROW(MP_BACKEND.check_for_kvm_support());
}
TEST(LinuxBackendUtils, check_for_kvm_support_does_not_exist_throws_expected_error)
{
auto [mock_file_ops, file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, exists(A<const QFile&>())).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(MP_BACKEND.check_for_kvm_support(), std::runtime_error,
mpt::match_what(AllOf(HasSubstr("KVM support is not enabled on this machine."),
HasSubstr("Please ensure the following:"))));
}
TEST(LinuxBackendUtils, check_for_kvm_support_no_read_write_throws_expected_error)
{
auto [mock_file_ops, file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, exists(A<const QFile&>())).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(
MP_BACKEND.check_for_kvm_support(), std::runtime_error,
mpt::match_what(StrEq("The KVM device cannot be opened for reading and writing.\nPlease "
"ensure the Snap KVM interface is connected by issuing:\n$ snap connect multipass:kvm")));
}
TEST(LinuxBackendUtils, check_kvm_in_use_no_failure_does_not_throw)
{
auto [mock_linux_syscalls, guard] = mpt::MockLinuxSysCalls::inject();
EXPECT_CALL(*mock_linux_syscalls, close(_)).WillRepeatedly(Return(0));
EXPECT_CALL(*mock_linux_syscalls, ioctl(_, _, _)).WillOnce(Return(1));
EXPECT_CALL(*mock_linux_syscalls, open(_, _)).WillOnce(Return(1));
EXPECT_NO_THROW(MP_BACKEND.check_if_kvm_is_in_use());
}
TEST(LinuxBackendUtils, check_kvm_in_use_fails_throws_expected_message)
{
auto [mock_linux_syscalls, guard] = mpt::MockLinuxSysCalls::inject();
EXPECT_CALL(*mock_linux_syscalls, close(_)).WillRepeatedly(Return(0));
EXPECT_CALL(*mock_linux_syscalls, open(_, _)).WillOnce(Return(1));
EXPECT_CALL(*mock_linux_syscalls, ioctl(_, _, _)).WillOnce([](auto...) {
errno = EBUSY;
return -1;
});
MP_EXPECT_THROW_THAT(
MP_BACKEND.check_if_kvm_is_in_use(), std::runtime_error,
mpt::match_what(StrEq("Another virtual machine manager is currently running. Please shut it down before "
"starting a Multipass instance.")));
}
TEST(LinuxBackendUtils, linux_syscalls_return_expected_values)
{
const std::string null_path{"/dev/null"};
auto null_fd = MP_LINUX_SYSCALLS.open(null_path.c_str(), O_RDONLY);
EXPECT_NE(null_fd, -1);
// /dev/null does not accept ioctl calls, so it will fail
EXPECT_EQ(MP_LINUX_SYSCALLS.ioctl(null_fd, FIONREAD, 0), -1);
EXPECT_EQ(MP_LINUX_SYSCALLS.close(null_fd), 0);
}
TEST(LinuxBackendUtils, get_subnet_bridge_exists_returns_expected_data)
{
const std::string test_subnet{"10.102.12"};
const QString bridge_name{"test-bridge"};
auto [mock_utils, guard] = mpt::MockUtils::inject();
EXPECT_CALL(*mock_utils, run_cmd_for_output(QString("ip"), QStringList({"-4", "route", "show"}), _))
.WillOnce(Return(fmt::format("{}.0 dev {} proto kernel scope link", test_subnet, bridge_name)));
EXPECT_EQ(MP_BACKEND.get_subnet("foo", bridge_name), test_subnet);
}
TEST(LinuxBackendUtils, get_subnet_in_file_returns_expected_data)
{
const std::string test_subnet{"10.102.12"};
const QString bridge_name{"test-bridge"};
auto [mock_utils, utils_guard] = mpt::MockUtils::inject();
auto [mock_file_ops, file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_utils, run_cmd_for_output(QString("ip"), QStringList({"-4", "route", "show"}), _))
.WillOnce(Return(""));
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, size(_)).WillOnce(Return(1));
EXPECT_CALL(*mock_file_ops, read_all(_)).WillOnce(Return(QByteArray::fromStdString(test_subnet)));
EXPECT_EQ(MP_BACKEND.get_subnet("foo", bridge_name), test_subnet);
}
TEST(LinuxBackendUtils, get_subnet_not_in_file_writes_new_subnet_returns_expected_data)
{
const QString bridge_name{"test-bridge"};
std::string generated_subnet;
auto [mock_utils, utils_guard] = mpt::MockUtils::inject();
auto [mock_file_ops, file_ops_guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_utils, run_cmd_for_output(QString("ip"), QStringList({"-4", "route", "show"}), _))
.WillOnce(Return(""))
.WillOnce(Return("0.0.0.0"));
EXPECT_CALL(*mock_utils, run_cmd_for_status(QString("ping"), _, _)).WillRepeatedly(Return(false));
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, size(_)).WillOnce(Return(0));
EXPECT_CALL(*mock_file_ops, write(A<QFile&>(), _, _)).WillOnce([&generated_subnet](auto&, auto data, auto) {
generated_subnet = std::string(data);
return generated_subnet.length();
});
EXPECT_EQ(MP_BACKEND.get_subnet("foo", bridge_name), generated_subnet);
}
| 23,104
|
C++
|
.cpp
| 418
| 48.145933
| 120
| 0.671299
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,651
|
mock_apparmor_parser.cpp
|
canonical_multipass/tests/linux/mock_apparmor_parser.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
// looks for version just to ensure existence
if (argc == 2 && strcmp(argv[1], "-V") == 0)
{
cout << "AppArmor parser version 1.11" << endl;
return 0;
}
// stick all input in a file named /tmp/multipass-apparmor-profile.txt
fstream out("/tmp/multipass-apparmor-profile.txt", fstream::out);
out << "args: ";
for (int i = 1; i < argc; i++)
{
out << argv[i] << ", ";
}
out << endl;
string s;
std::getline(cin, s, '\0');
out << s;
return 0;
}
| 1,288
|
C++
|
.cpp
| 42
| 27.190476
| 74
| 0.664786
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,652
|
test_local_network_access_manager.cpp
|
canonical_multipass/tests/linux/test_local_network_access_manager.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "local_socket_server_test_fixture.h"
#include "mock_q_buffer.h"
#include "mock_q_local_socket.h"
#include "tests/common.h"
#include "tests/temp_dir.h"
#include <src/network/local_socket_reply.h>
#include <multipass/exceptions/http_local_socket_exception.h>
#include <multipass/exceptions/local_socket_connection_exception.h>
#include <multipass/network_access_manager.h>
#include <QBuffer>
#include <QEventLoop>
#include <QNetworkReply>
#include <QTimer>
#include <random>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
using HTTPErrorParamType = std::pair<QByteArray, QNetworkReply::NetworkError>;
constexpr auto max_bytes{32768};
constexpr auto max_content{65536};
auto generate_random_data(int length)
{
const std::string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_int_distribution<int> dist(0, str.size() - 1);
QByteArray random_data;
for (int i = 0; i < length; ++i)
{
random_data += str[dist(generator)];
}
return random_data;
}
struct LocalNetworkAccessManager : public Test
{
LocalNetworkAccessManager()
: socket_path{QString("%1/test_socket").arg(temp_dir.path())},
test_server{mpt::MockLocalSocketServer(socket_path)},
base_url{QString("unix://%1@1.0").arg(socket_path)}
{
download_timeout.setInterval(2000);
base_url.setHost("test");
}
auto handle_request(const QUrl& url, const QByteArray& verb, const QByteArray& data = QByteArray())
{
QNetworkRequest request{url};
request.setHeader(QNetworkRequest::UserAgentHeader, "Test");
if (!data.isEmpty())
{
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
auto data_size = data.size();
if (data_size < max_bytes)
{
request.setHeader(QNetworkRequest::ContentLengthHeader, data.size());
}
else
{
request.setRawHeader("Transfer-Encoding", "chunked");
}
}
std::unique_ptr<QNetworkReply> reply{manager.sendCustomRequest(request, verb, data)};
QObject::connect(reply.get(), &QNetworkReply::finished, &event_loop, &QEventLoop::quit);
QObject::connect(&download_timeout, &QTimer::timeout, [&] {
download_timeout.stop();
reply->abort();
});
download_timeout.start();
event_loop.exec();
return reply;
}
mp::NetworkAccessManager manager;
mpt::TempDir temp_dir;
QString socket_path;
mpt::MockLocalSocketServer test_server;
QUrl base_url;
QEventLoop event_loop;
QTimer download_timeout;
};
struct HTTPErrorsTestSuite : LocalNetworkAccessManager, WithParamInterface<HTTPErrorParamType>
{
};
struct LocalSocketWriteErrorTestSuite : LocalNetworkAccessManager, WithParamInterface<int>
{
};
const std::vector<int> local_socket_write_error_suite_inputs{0, 1, 2, 3, 4, 5, 6};
const std::vector<HTTPErrorParamType> http_error_suite_inputs{
{"HTTP/1.1 400 Bad Request\r\n\r\n", QNetworkReply::ProtocolInvalidOperationError},
{"HTTP/1.1 401 Authorization Required\r\n\r\n", QNetworkReply::AuthenticationRequiredError},
{"HTTP/1.1 403 Access Denied\r\n\r\n", QNetworkReply::ContentAccessDenied},
{"HTTP/1.1 404 Not Found\r\n\r\n", QNetworkReply::ContentNotFoundError},
{"HTTP/1.1 409 Resource Conflict\r\n\r\n", QNetworkReply::ContentConflictError},
{"HTTP/1.1 500 Internal Server Error\r\n\r\n", QNetworkReply::InternalServerError},
{"HTTP/1.1 501 Unknown Server Error\r\n\r\n", QNetworkReply::UnknownServerError},
{"HTTP/1.1 412 Precondition Failed\r\n\r\n", QNetworkReply::UnknownContentError}};
} // namespace
TEST_F(LocalNetworkAccessManager, no_error_returns_good_reply)
{
QByteArray http_response;
http_response += "HTTP/1.1 200 OK\r\n";
http_response += "\r\n";
auto server_response = [&http_response](auto...) { return http_response; };
test_server.local_socket_server_handler(server_response);
auto reply = handle_request(base_url, "GET");
EXPECT_EQ(reply->error(), QNetworkReply::NoError);
}
TEST_F(LocalNetworkAccessManager, reads_expected_data_not_chunked)
{
QByteArray reply_data{"Hello"};
QByteArray http_response;
http_response += "HTTP/1.1 200 OK\r\n";
http_response += "Content-Length: 5\r\n";
http_response += "\r\n";
http_response += reply_data;
http_response += "\r\n";
auto server_response = [&http_response](auto...) { return http_response; };
test_server.local_socket_server_handler(server_response);
auto reply = handle_request(base_url, "GET");
ASSERT_EQ(reply->error(), QNetworkReply::NoError);
auto data = reply->readAll();
EXPECT_EQ(data, reply_data);
}
TEST_F(LocalNetworkAccessManager, reads_expected_data_chunked)
{
QByteArray reply_data{"What's up?"};
QByteArray http_response;
http_response += "HTTP/1.1 200 OK\r\n";
http_response += "Content-Length: 10\r\n";
http_response += "Transfer-Encoding: chunked\r\n";
http_response += "\r\n";
http_response += "a\r\n";
http_response += reply_data;
http_response += "\r\n";
auto server_response = [&http_response](auto...) { return http_response; };
test_server.local_socket_server_handler(server_response);
auto reply = handle_request(base_url, "GET");
ASSERT_EQ(reply->error(), QNetworkReply::NoError);
auto data = reply->readAll();
EXPECT_EQ(data, reply_data);
}
TEST_F(LocalNetworkAccessManager, client_posts_correct_data)
{
QByteArray expected_data{"POST /1.0 HTTP/1.1\r\n"
"Host: test\r\n"
"User-Agent: Test\r\n"
"Connection: close\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: 11\r\n\r\n"
"Hello World\r\n"};
QByteArray http_response{"HTTP/1.1 200 OK\r\n\r\n"};
auto server_response = [&http_response, &expected_data](auto data) {
EXPECT_EQ(data, expected_data);
return http_response;
};
test_server.local_socket_server_handler(server_response);
handle_request(base_url, "POST", "Hello World");
}
TEST_F(LocalNetworkAccessManager, bad_http_server_response_has_error)
{
QByteArray malformed_http_response{"FOO/1.4 42 Yo\r\n"};
auto server_response = [&malformed_http_response](auto...) { return malformed_http_response; };
test_server.local_socket_server_handler(server_response);
auto reply = handle_request(base_url, "GET");
EXPECT_EQ(reply->error(), QNetworkReply::ProtocolFailure);
}
TEST_F(LocalNetworkAccessManager, malformed_unix_schema_throws)
{
base_url = "unix:///foo";
QNetworkRequest request{base_url};
EXPECT_THROW(manager.sendCustomRequest(request, "GET"), mp::LocalSocketConnectionException);
}
TEST_F(LocalNetworkAccessManager, unable_to_connect_throws)
{
base_url = "unix:///invalid/path@1.0";
QNetworkRequest request{base_url};
EXPECT_THROW(manager.sendCustomRequest(request, "GET"), mp::LocalSocketConnectionException);
}
TEST_F(LocalNetworkAccessManager, reply_abort_sets_expected_error)
{
download_timeout.setInterval(2);
auto reply = handle_request(base_url, "GET");
EXPECT_EQ(reply->error(), QNetworkReply::OperationCanceledError);
}
TEST_F(LocalNetworkAccessManager, other_request_uses_qnam)
{
QUrl url{QString("file://%1/missing_doc.txt").arg(temp_dir.path())};
auto reply = handle_request(url, "GET");
EXPECT_EQ(reply->error(), QNetworkReply::ProtocolUnknownError);
}
TEST_F(LocalNetworkAccessManager, query_in_url_is_preserved)
{
const QString query_string{"query=foo"};
QByteArray http_response;
http_response += "HTTP/1.1 200 OK\r\n";
http_response += "\r\n";
base_url.setQuery(query_string);
auto server_response = [&http_response, &query_string](auto data) {
EXPECT_TRUE(data.contains(query_string.toLatin1()));
return http_response;
};
test_server.local_socket_server_handler(server_response);
handle_request(base_url, "GET");
}
TEST_F(LocalNetworkAccessManager, sending_chunked_data_receives_expected_data)
{
QByteArray random_data = generate_random_data(max_content);
QByteArray http_response{"HTTP/1.1 200 OK\r\n\r\n"};
auto server_response = [&http_response, &random_data](auto data) {
QByteArray first_part = random_data.mid(0, 32768);
QByteArray second_part = random_data.mid(32768);
// Implies the data was split, ie, chunked
EXPECT_FALSE(data.contains(random_data));
// Implies that the correct data was still received
EXPECT_TRUE(data.contains(first_part));
EXPECT_TRUE(data.contains(second_part));
return http_response;
};
test_server.local_socket_server_handler(server_response);
handle_request(base_url, "POST", random_data);
}
TEST_F(LocalNetworkAccessManager, overflowing_response_works)
{
auto reply_data = generate_random_data(max_content * 2);
QByteArray http_response;
http_response += "HTTP/1.1 200 OK\r\n";
http_response += "Content-Length: 131072\r\n";
http_response += "\r\n";
http_response += reply_data;
http_response += "\r\n";
auto server_response = [&http_response](auto...) { return http_response; };
test_server.local_socket_server_handler(server_response);
auto reply = handle_request(base_url, "GET");
ASSERT_EQ(reply->error(), QNetworkReply::NoError);
auto data = reply->readAll();
EXPECT_EQ(data, reply_data);
}
TEST_F(LocalNetworkAccessManager, no_host_set_throws)
{
base_url.setHost("");
QNetworkRequest request{base_url};
EXPECT_THROW(manager.sendCustomRequest(request, "GET"), mp::HttpLocalSocketException);
}
TEST_F(LocalNetworkAccessManager, content_length_and_transfer_encoding_both_set_throws)
{
QNetworkRequest request{base_url};
QByteArray some_data{"This is some data"};
request.setHeader(QNetworkRequest::ContentLengthHeader, some_data.size());
request.setRawHeader("Transfer-Encoding", "chunked");
EXPECT_THROW(manager.sendCustomRequest(request, "POST", some_data), mp::HttpLocalSocketException);
}
TEST_F(LocalNetworkAccessManager, content_length_and_transfer_encoding_not_set_throws)
{
QNetworkRequest request{base_url};
QByteArray some_data{"This is some data"};
EXPECT_THROW(manager.sendCustomRequest(request, "POST", some_data), mp::HttpLocalSocketException);
}
TEST_F(LocalNetworkAccessManager, qiodevice_read_fails_throws)
{
auto mock_q_local_socket = std::make_unique<mpt::MockQLocalSocket>(10); // Not failing any writes
base_url.setHost("test");
QNetworkRequest request{base_url};
request.setAttribute(QNetworkRequest::CustomVerbAttribute, "POST");
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
request.setRawHeader("Transfer-Encoding", "chunked");
auto data{generate_random_data(32768)};
mpt::MockQBuffer buffer{&data};
EXPECT_THROW(mp::LocalSocketReply local_socket_reply(std::move(mock_q_local_socket), request, &buffer),
mp::HttpLocalSocketException);
EXPECT_TRUE(buffer.read_attempted());
}
TEST_P(HTTPErrorsTestSuite, returns_expected_error)
{
const auto http_response = GetParam().first;
const auto expected_error = GetParam().second;
auto server_response = [&http_response](auto...) { return http_response; };
test_server.local_socket_server_handler(server_response);
auto reply = handle_request(base_url, "GET");
EXPECT_EQ(reply->error(), expected_error);
}
TEST_P(LocalSocketWriteErrorTestSuite, write_fails_emits_error_and_returns)
{
const int writes_before_failure = GetParam();
auto mock_q_local_socket = std::make_unique<mpt::MockQLocalSocket>(writes_before_failure);
auto mock_q_local_socket_ptr = mock_q_local_socket.get();
base_url.setHost("test");
QNetworkRequest request{base_url};
request.setAttribute(QNetworkRequest::CustomVerbAttribute, "POST");
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
request.setRawHeader("Transfer-Encoding", "chunked");
auto data{generate_random_data(32768)};
QBuffer buffer{&data};
mp::LocalSocketReply local_socket_reply{std::move(mock_q_local_socket), request, &buffer};
EXPECT_EQ(local_socket_reply.error(), QNetworkReply::InternalServerError);
EXPECT_EQ(mock_q_local_socket_ptr->num_writes_called(), writes_before_failure + 1);
}
INSTANTIATE_TEST_SUITE_P(LocalNetworkAccessManager, HTTPErrorsTestSuite, ValuesIn(http_error_suite_inputs));
INSTANTIATE_TEST_SUITE_P(LocalNetworkAccessManager, LocalSocketWriteErrorTestSuite,
ValuesIn(local_socket_write_error_suite_inputs));
| 13,719
|
C++
|
.cpp
| 315
| 38.238095
| 108
| 0.70728
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,653
|
test_apparmored_process.cpp
|
canonical_multipass/tests/linux/test_apparmored_process.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_aa_syscalls.h"
#include "tests/common.h"
#include "tests/mock_environment_helpers.h"
#include "tests/mock_logger.h"
#include "tests/reset_process_factory.h"
#include "tests/temp_dir.h"
#include "tests/test_with_mocked_bin_path.h"
#include <src/platform/backends/shared/linux/process_factory.h>
#include <multipass/format.h>
#include <multipass/process/process.h>
#include <QFile>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
const auto apparmor_output_file = "/tmp/multipass-apparmor-profile.txt";
const auto apparmor_profile_text = "profile test_apparmor_profile() { stuff }";
class TestProcessSpec : public mp::ProcessSpec
{
QString program() const override
{
return "test_prog";
}
QStringList arguments() const override
{
return {"one", "two"};
}
QString apparmor_profile() const override
{
return apparmor_profile_text;
}
};
} // namespace
struct ApparmoredProcessNoFactoryTest : public mpt::TestWithMockedBinPath
{
ApparmoredProcessNoFactoryTest()
{
QFile::remove(apparmor_output_file);
is_enabled.returnValue(1);
}
void TearDown() override
{
QFile::remove(apparmor_output_file);
}
mpt::UnsetEnvScope env{"DISABLE_APPARMOR"};
mpt::ResetProcessFactory scope; // will otherwise pollute other tests
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
decltype(MOCK(aa_is_enabled)) is_enabled{MOCK(aa_is_enabled)};
};
struct ApparmoredProcessTest : public ApparmoredProcessNoFactoryTest
{
using ApparmoredProcessNoFactoryTest::ApparmoredProcessNoFactoryTest; // ctor
const mp::ProcessFactory& process_factory{MP_PROCFACTORY};
};
TEST_F(ApparmoredProcessTest, loads_profile_with_apparmor)
{
auto process = process_factory.create_process(std::make_unique<TestProcessSpec>());
// apparmor profile should have been installed
QFile apparmor_input(apparmor_output_file);
ASSERT_TRUE(apparmor_input.open(QIODevice::ReadOnly | QIODevice::Text));
auto input = apparmor_input.readAll();
EXPECT_TRUE(input.contains("args: -W, --abort-on-error, -r,"));
EXPECT_TRUE(input.contains(apparmor_profile_text));
}
TEST_F(ApparmoredProcessNoFactoryTest, snap_enables_cache_with_expected_args)
{
mpt::TempDir cache_dir;
const QByteArray snap_name{"multipass"};
mpt::SetEnvScope env_scope("SNAP_COMMON", cache_dir.path().toUtf8());
mpt::SetEnvScope env_scope2("SNAP_NAME", snap_name);
const mp::ProcessFactory& process_factory{MP_PROCFACTORY};
auto process = process_factory.create_process(std::make_unique<TestProcessSpec>());
// apparmor profile should have been installed
QFile apparmor_input(apparmor_output_file);
ASSERT_TRUE(apparmor_input.open(QIODevice::ReadOnly | QIODevice::Text));
auto input = apparmor_input.readAll();
EXPECT_TRUE(input.contains(
QString("args: -WL, %1/apparmor.d/cache/multipass, --abort-on-error, -r,").arg(cache_dir.path()).toUtf8()));
EXPECT_TRUE(input.contains(apparmor_profile_text));
}
TEST_F(ApparmoredProcessNoFactoryTest, no_output_file_when_no_apparmor)
{
REPLACE(aa_is_enabled, [] { return 0; });
const mp::ProcessFactory& process_factory{MP_PROCFACTORY};
auto process = process_factory.create_process(std::make_unique<TestProcessSpec>());
EXPECT_FALSE(QFile::exists(apparmor_output_file));
}
TEST_F(ApparmoredProcessTest, unloads_profile_with_apparmor_on_process_out_of_scope)
{
auto process = process_factory.create_process(std::make_unique<TestProcessSpec>());
process.reset();
// apparmor profile should have been removed
QFile apparmor_input(apparmor_output_file);
ASSERT_TRUE(apparmor_input.open(QIODevice::ReadOnly | QIODevice::Text));
auto input = apparmor_input.readAll();
EXPECT_TRUE(input.contains("args: -W, -R,"));
EXPECT_TRUE(input.contains(apparmor_profile_text));
}
// Copies of tests in LinuxProcessTest
TEST_F(ApparmoredProcessTest, execute_missing_command)
{
auto process = process_factory.create_process("a_missing_command");
auto process_state = process->execute();
EXPECT_FALSE(process_state.completed_successfully());
EXPECT_FALSE(process_state.exit_code);
ASSERT_TRUE(process_state.error);
EXPECT_EQ(QProcess::ProcessError::FailedToStart, process_state.error->state);
}
TEST_F(ApparmoredProcessTest, execute_crashing_command)
{
auto process = process_factory.create_process("mock_process");
auto process_state = process->execute();
EXPECT_FALSE(process_state.completed_successfully());
EXPECT_FALSE(process_state.exit_code);
ASSERT_TRUE(process_state.error);
EXPECT_EQ(QProcess::ProcessError::Crashed, process_state.error->state);
}
TEST_F(ApparmoredProcessTest, execute_good_command_with_positive_exit_code)
{
const int exit_code = 7;
auto process = process_factory.create_process("mock_process", {QString::number(exit_code)});
auto process_state = process->execute();
EXPECT_FALSE(process_state.completed_successfully());
EXPECT_TRUE(process_state.exit_code);
EXPECT_EQ(exit_code, process_state.exit_code.value());
EXPECT_EQ("Process returned exit code: 7", process_state.failure_message());
EXPECT_FALSE(process_state.error);
}
TEST_F(ApparmoredProcessTest, execute_good_command_with_zero_exit_code)
{
const int exit_code = 0;
auto process = process_factory.create_process("mock_process", {QString::number(exit_code)});
auto process_state = process->execute();
EXPECT_TRUE(process_state.completed_successfully());
EXPECT_TRUE(process_state.exit_code);
EXPECT_EQ(exit_code, process_state.exit_code.value());
EXPECT_EQ(QString(), process_state.failure_message());
EXPECT_FALSE(process_state.error);
}
TEST_F(ApparmoredProcessTest, process_state_when_runs_and_stops_ok)
{
const int exit_code = 7;
auto process = process_factory.create_process("mock_process", {QString::number(exit_code), "stay-alive"});
process->start();
EXPECT_TRUE(process->wait_for_started());
auto process_state = process->process_state();
EXPECT_FALSE(process_state.exit_code);
EXPECT_FALSE(process_state.error);
process->write(QByteArray(1, '\0')); // will make mock_process quit
EXPECT_TRUE(process->wait_for_finished());
process_state = process->process_state();
EXPECT_TRUE(process_state.exit_code);
EXPECT_EQ(exit_code, process_state.exit_code.value());
EXPECT_FALSE(process_state.error);
}
TEST_F(ApparmoredProcessTest, process_state_when_runs_but_fails_to_stop)
{
const int exit_code = 2;
auto process = process_factory.create_process("mock_process", {QString::number(exit_code), "stay-alive"});
process->start();
EXPECT_TRUE(process->wait_for_started());
auto process_state = process->process_state();
EXPECT_FALSE(process_state.exit_code);
EXPECT_FALSE(process_state.error);
EXPECT_FALSE(process->wait_for_finished(100)); // will hit timeout
process_state = process->process_state();
EXPECT_FALSE(process_state.exit_code);
ASSERT_TRUE(process_state.error);
EXPECT_EQ(QProcess::Timedout, process_state.error->state);
}
TEST_F(ApparmoredProcessTest, process_state_when_crashes_on_start)
{
auto process = process_factory.create_process("mock_process"); // will crash immediately
process->start();
// EXPECT_TRUE(process->wait_for_started()); // on start too soon, app hasn't crashed yet!
EXPECT_TRUE(process->wait_for_finished());
auto process_state = process->process_state();
EXPECT_FALSE(process_state.exit_code);
ASSERT_TRUE(process_state.error);
EXPECT_EQ(QProcess::Crashed, process_state.error->state);
}
TEST_F(ApparmoredProcessTest, process_state_when_crashes_while_running)
{
auto process = process_factory.create_process("mock_process", {QString::number(0), "stay-alive"});
process->start();
process->write("crash"); // will make mock_process crash
process->write(QByteArray(1, '\0'));
EXPECT_TRUE(process->wait_for_finished());
auto process_state = process->process_state();
EXPECT_FALSE(process_state.exit_code);
ASSERT_TRUE(process_state.error);
EXPECT_EQ(QProcess::Crashed, process_state.error->state);
}
TEST_F(ApparmoredProcessTest, process_state_when_failed_to_start)
{
auto process = process_factory.create_process("a_missing_process");
process->start();
EXPECT_FALSE(process->wait_for_started());
auto process_state = process->process_state();
EXPECT_FALSE(process_state.exit_code);
ASSERT_TRUE(process_state.error);
EXPECT_EQ(QProcess::FailedToStart, process_state.error->state);
}
TEST_F(ApparmoredProcessTest, process_state_when_runs_and_stops_immediately)
{
const int exit_code = 7;
auto process = process_factory.create_process("mock_process", {QString::number(exit_code)});
process->start();
EXPECT_TRUE(process->wait_for_started());
auto process_state = process->process_state();
EXPECT_FALSE(process_state.exit_code);
EXPECT_FALSE(process_state.error);
EXPECT_TRUE(process->wait_for_finished());
process_state = process->process_state();
EXPECT_TRUE(process_state.exit_code);
EXPECT_EQ(exit_code, process_state.exit_code.value());
EXPECT_FALSE(process_state.error);
}
TEST_F(ApparmoredProcessNoFactoryTest, logsAllExpectedMessagesOnStart)
{
logger_scope.mock_logger->screen_logs(mpl::Level::error);
logger_scope.mock_logger->expect_log(mpl::Level::info, "Using AppArmor support");
logger_scope.mock_logger->expect_log(mpl::Level::trace,
fmt::format("Loading AppArmor policy:\n{}", apparmor_profile_text));
const mp::ProcessFactory& process_factory{MP_PROCFACTORY};
auto process = process_factory.create_process(std::make_unique<TestProcessSpec>());
logger_scope.mock_logger->expect_log(mpl::Level::debug, "Applied AppArmor policy: multipass.test_prog");
logger_scope.mock_logger->expect_log(mpl::Level::trace,
fmt::format("Removing AppArmor policy:\n{}", apparmor_profile_text));
logger_scope.mock_logger->expect_log(
mpl::Level::debug, fmt::format("started: {} {}", process->program(), process->arguments().join(' ')));
process->start();
process->kill();
process->wait_for_finished();
}
| 11,105
|
C++
|
.cpp
| 253
| 39.573123
| 116
| 0.72804
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,654
|
test_platform_linux.cpp
|
canonical_multipass/tests/linux/test_platform_linux.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/fake_handle.h"
#include "tests/file_operations.h"
#include "tests/mock_environment_helpers.h"
#include "tests/mock_file_ops.h"
#include "tests/mock_process_factory.h"
#include "tests/mock_settings.h"
#include "tests/mock_standard_paths.h"
#include "tests/mock_utils.h"
#include "tests/qemu/linux/mock_dnsmasq_server.h"
#include "tests/temp_dir.h"
#include "tests/test_with_mocked_bin_path.h"
#include <src/platform/backends/libvirt/libvirt_virtual_machine_factory.h>
#include <src/platform/backends/libvirt/libvirt_wrapper.h>
#include <src/platform/backends/lxd/lxd_virtual_machine_factory.h>
#ifdef QEMU_ENABLED
#include <src/platform/backends/qemu/qemu_virtual_machine_factory.h>
#define DEFAULT_FACTORY mp::QemuVirtualMachineFactory
#define DEFAULT_DRIVER "qemu"
#else
#define DEFAULT_FACTORY mp::LXDVirtualMachineFactory
#define DEFAULT_DRIVER "lxd"
#endif
#include <src/platform/platform_linux_detail.h>
#include <multipass/constants.h>
#include <multipass/exceptions/autostart_setup_exception.h>
#include <multipass/exceptions/settings_exceptions.h>
#include <multipass/platform.h>
#include <multipass/utils.h>
#include <scope_guard.hpp>
#include <QDir>
#include <QFile>
#include <QString>
#include <stdexcept>
namespace mp = multipass;
namespace mpt = multipass::test;
namespace mpu = multipass::utils;
using namespace testing;
namespace
{
const auto backend_path = QStringLiteral("/tmp");
struct PlatformLinux : public mpt::TestWithMockedBinPath
{
template <typename VMFactoryType>
void aux_test_driver_factory(const QString& driver)
{
const mpt::MockDNSMasqServerFactory::GuardedMock dnsmasq_server_factory_attr{
mpt::MockDNSMasqServerFactory::inject<NiceMock>()};
auto factory = mpt::MockProcessFactory::Inject();
setup_driver_settings(driver);
decltype(mp::platform::vm_backend("")) factory_ptr;
EXPECT_NO_THROW(factory_ptr = mp::platform::vm_backend(backend_path););
EXPECT_TRUE(dynamic_cast<VMFactoryType*>(factory_ptr.get()));
}
void setup_driver_settings(const QString& driver)
{
EXPECT_CALL(mock_settings, get(Eq(mp::driver_key))).WillRepeatedly(Return(driver));
}
void with_minimally_mocked_libvirt(std::function<void()> test_contents)
{
mp::LibvirtWrapper libvirt_wrapper{""};
test_contents();
}
mpt::MockSettings::GuardedMock mock_settings_injection = mpt::MockSettings::inject();
mpt::MockSettings& mock_settings = *mock_settings_injection.first;
mpt::SetEnvScope disable_apparmor{"DISABLE_APPARMOR", "1"};
};
TEST_F(PlatformLinux, test_interpretation_of_winterm_setting_not_supported)
{
for (const auto* x : {"no", "matter", "what"})
EXPECT_THROW(mp::platform::interpret_setting(mp::winterm_key, x), mp::InvalidSettingException);
}
TEST_F(PlatformLinux, test_interpretation_of_unknown_settings_not_supported)
{
for (const auto* k : {"unimaginable", "katxama", "katxatxa"})
for (const auto* v : {"no", "matter", "what"})
EXPECT_THROW(mp::platform::interpret_setting(k, v), mp::InvalidSettingException);
}
TEST_F(PlatformLinux, test_no_extra_client_settings)
{
EXPECT_THAT(MP_PLATFORM.extra_client_settings(), IsEmpty());
}
TEST_F(PlatformLinux, test_no_extra_daemon_settings)
{
EXPECT_THAT(MP_PLATFORM.extra_daemon_settings(), IsEmpty());
}
TEST_F(PlatformLinux, test_empty_sync_winterm_profiles)
{
EXPECT_NO_THROW(mp::platform::sync_winterm_profiles());
}
TEST_F(PlatformLinux, test_default_driver)
{
EXPECT_THAT(MP_PLATFORM.default_driver(), AnyOf("qemu", "lxd"));
}
TEST_F(PlatformLinux, test_default_privileged_mounts)
{
EXPECT_EQ(MP_PLATFORM.default_privileged_mounts(), "true");
}
TEST_F(PlatformLinux, test_default_driver_produces_correct_factory)
{
aux_test_driver_factory<DEFAULT_FACTORY>(DEFAULT_DRIVER);
}
#ifdef QEMU_ENABLED
TEST_F(PlatformLinux, test_explicit_qemu_driver_produces_correct_factory)
{
aux_test_driver_factory<mp::QemuVirtualMachineFactory>("qemu");
}
#endif
TEST_F(PlatformLinux, test_libvirt_driver_produces_correct_factory)
{
auto test = [this] { aux_test_driver_factory<mp::LibVirtVirtualMachineFactory>("libvirt"); };
with_minimally_mocked_libvirt(test);
}
TEST_F(PlatformLinux, test_lxd_driver_produces_correct_factory)
{
aux_test_driver_factory<mp::LXDVirtualMachineFactory>("lxd");
}
TEST_F(PlatformLinux, test_qemu_in_env_var_is_ignored)
{
mpt::SetEnvScope env(mp::driver_env_var, "QEMU");
auto test = [this] { aux_test_driver_factory<mp::LibVirtVirtualMachineFactory>("libvirt"); };
with_minimally_mocked_libvirt(test);
}
TEST_F(PlatformLinux, test_libvirt_in_env_var_is_ignored)
{
mpt::SetEnvScope env(mp::driver_env_var, "LIBVIRT");
aux_test_driver_factory<DEFAULT_FACTORY>(DEFAULT_DRIVER);
}
TEST_F(PlatformLinux, blueprintsURLOverrideSetReturnsExpectedData)
{
const QString fake_url{"https://a.fake.url"};
mpt::SetEnvScope blueprints_url("MULTIPASS_BLUEPRINTS_URL", fake_url.toUtf8());
EXPECT_EQ(MP_PLATFORM.get_blueprints_url_override(), fake_url);
}
TEST_F(PlatformLinux, blueprintsURLOverrideNotSetReturnsEmptyString)
{
EXPECT_TRUE(MP_PLATFORM.get_blueprints_url_override().isEmpty());
}
TEST_F(PlatformLinux, test_is_remote_supported_returns_true)
{
EXPECT_TRUE(MP_PLATFORM.is_remote_supported("release"));
EXPECT_TRUE(MP_PLATFORM.is_remote_supported("daily"));
EXPECT_TRUE(MP_PLATFORM.is_remote_supported(""));
EXPECT_TRUE(MP_PLATFORM.is_remote_supported("snapcraft"));
EXPECT_TRUE(MP_PLATFORM.is_remote_supported("appliance"));
}
TEST_F(PlatformLinux, test_is_remote_supported_lxd)
{
setup_driver_settings("lxd");
EXPECT_TRUE(MP_PLATFORM.is_remote_supported("release"));
EXPECT_TRUE(MP_PLATFORM.is_remote_supported("daily"));
EXPECT_TRUE(MP_PLATFORM.is_remote_supported(""));
EXPECT_TRUE(MP_PLATFORM.is_remote_supported("appliance"));
EXPECT_TRUE(MP_PLATFORM.is_remote_supported("snapcraft"));
}
TEST_F(PlatformLinux, test_snap_returns_expected_default_address)
{
const QByteArray base_dir{"/tmp"};
const QByteArray snap_name{"multipass"};
mpt::SetEnvScope env("SNAP_COMMON", base_dir);
mpt::SetEnvScope env2("SNAP_NAME", snap_name);
EXPECT_EQ(mp::platform::default_server_address(), fmt::format("unix:{}/multipass_socket", base_dir.toStdString()));
}
TEST_F(PlatformLinux, test_not_snap_returns_expected_default_address)
{
const QByteArray snap_name{"multipass"};
mpt::UnsetEnvScope unset_env("SNAP_COMMON");
mpt::SetEnvScope env2("SNAP_NAME", snap_name);
EXPECT_EQ(mp::platform::default_server_address(), fmt::format("unix:/run/multipass_socket"));
}
TEST_F(PlatformLinux, test_is_alias_supported_returns_true)
{
EXPECT_TRUE(MP_PLATFORM.is_alias_supported("focal", "release"));
}
struct TestUnsupportedDrivers : public PlatformLinux, WithParamInterface<QString>
{
};
TEST_P(TestUnsupportedDrivers, test_unsupported_driver)
{
ASSERT_FALSE(MP_PLATFORM.is_backend_supported(GetParam()));
setup_driver_settings(GetParam());
EXPECT_THROW(mp::platform::vm_backend(backend_path), std::runtime_error);
}
INSTANTIATE_TEST_SUITE_P(PlatformLinux, TestUnsupportedDrivers,
Values(QStringLiteral("hyper-v"), QStringLiteral("other")));
TEST_F(PlatformLinux, retrieves_empty_bridges)
{
const mpt::TempDir tmp_dir;
const auto fake_bridge = "somebridge";
QDir fake_sys_class_net{tmp_dir.path()};
QDir bridge_dir{fake_sys_class_net.filePath(fake_bridge)};
mpt::make_file_with_content(bridge_dir.filePath("type"), "1");
ASSERT_TRUE(bridge_dir.mkpath("bridge"));
auto net_map = mp::platform::detail::get_network_interfaces_from(fake_sys_class_net.path());
using value_type = decltype(net_map)::value_type;
using Net = mp::NetworkInterfaceInfo;
EXPECT_THAT(net_map, ElementsAre(AllOf(
Field(&value_type::first, fake_bridge),
Field(&value_type::second, AllOf(Field(&Net::id, fake_bridge), Field(&Net::type, "bridge"),
Field(&Net::description, StrEq("Network bridge")))))));
}
TEST_F(PlatformLinux, retrieves_ethernet_devices)
{
const mpt::TempDir tmp_dir;
const auto fake_eth = "someth";
QDir fake_sys_class_net{tmp_dir.path()};
mpt::make_file_with_content(fake_sys_class_net.filePath(fake_eth) + "/type", "1");
auto net_map = mp::platform::detail::get_network_interfaces_from(fake_sys_class_net.path());
ASSERT_EQ(net_map.size(), 1u);
auto it = net_map.cbegin();
EXPECT_EQ(it->first, fake_eth);
EXPECT_EQ(it->second.id, fake_eth);
EXPECT_EQ(it->second.type, "ethernet");
EXPECT_EQ(it->second.description, "Ethernet device");
}
TEST_F(PlatformLinux, does_not_retrieve_unknown_networks)
{
const mpt::TempDir tmp_dir;
const auto fake_nets = {"eth0", "foo", "kkkkk"};
QDir fake_sys_class_net{tmp_dir.path()};
for (const auto& net : fake_nets)
ASSERT_TRUE(fake_sys_class_net.mkpath(net));
EXPECT_THAT(mp::platform::detail::get_network_interfaces_from(fake_sys_class_net.path()), IsEmpty());
}
TEST_F(PlatformLinux, does_not_retrieve_other_virtual)
{
const mpt::TempDir tmp_dir;
const auto fake_virt = "somevirt";
QDir fake_sys_class_net{tmp_dir.path() + "/virtual"};
mpt::make_file_with_content(fake_sys_class_net.filePath(fake_virt) + "/type", "1");
EXPECT_THAT(mp::platform::detail::get_network_interfaces_from(fake_sys_class_net.path()), IsEmpty());
}
TEST_F(PlatformLinux, does_not_retrieve_wireless)
{
const mpt::TempDir tmp_dir;
const auto fake_wifi = "somewifi";
QDir fake_sys_class_net{tmp_dir.path()};
QDir wifi_dir{fake_sys_class_net.filePath(fake_wifi)};
mpt::make_file_with_content(wifi_dir.filePath("type"), "1");
ASSERT_TRUE(wifi_dir.mkpath("wireless"));
EXPECT_THAT(mp::platform::detail::get_network_interfaces_from(fake_sys_class_net.path()), IsEmpty());
}
TEST_F(PlatformLinux, does_not_retrieve_protocols)
{
const mpt::TempDir tmp_dir;
const auto fake_net = "somenet";
QDir fake_sys_class_net{tmp_dir.path()};
mpt::make_file_with_content(fake_sys_class_net.filePath(fake_net) + "/type", "32");
EXPECT_THAT(mp::platform::detail::get_network_interfaces_from(fake_sys_class_net.path()), IsEmpty());
}
TEST_F(PlatformLinux, does_not_retrieve_other_specified_device_types)
{
const mpt::TempDir tmp_dir;
const auto fake_net = "somenet";
const auto uevent_contents = std::string{"asdf\nDEVTYPE=crazytype\nfdsa"};
QDir fake_sys_class_net{tmp_dir.path()};
QDir net_dir{fake_sys_class_net.filePath(fake_net)};
mpt::make_file_with_content(net_dir.filePath("type"), "1");
mpt::make_file_with_content(net_dir.filePath("uevent"), uevent_contents);
auto net_map = mp::platform::detail::get_network_interfaces_from(fake_sys_class_net.path());
EXPECT_THAT(mp::platform::detail::get_network_interfaces_from(fake_sys_class_net.path()), IsEmpty());
}
struct BridgeMemberTest : public PlatformLinux, WithParamInterface<std::vector<std::pair<std::string, bool>>>
{
};
TEST_P(BridgeMemberTest, retrieves_bridges_with_members)
{
const mpt::TempDir tmp_dir;
const auto fake_bridge = "aeiou";
QDir fake_sys_class_net{tmp_dir.path()};
QDir interface_dir{fake_sys_class_net.filePath(fake_bridge)};
QDir members_dir{interface_dir.filePath("brif")};
mpt::make_file_with_content(interface_dir.filePath("type"), "1");
ASSERT_TRUE(interface_dir.mkpath("bridge"));
ASSERT_TRUE(members_dir.mkpath("."));
using net_value_type = decltype(MP_PLATFORM.get_network_interfaces_info())::value_type;
std::vector<Matcher<net_value_type>> network_matchers{};
std::vector<Matcher<std::string>> substrs_matchers{};
for (const auto& [member, recognized] : GetParam())
{
QDir member_dir = fake_sys_class_net.filePath(QString::fromStdString(member));
ASSERT_TRUE(member_dir.mkpath("."));
ASSERT_TRUE(members_dir.mkpath(QString::fromStdString(member)));
if (recognized)
{
mpt::make_file_with_content(member_dir.filePath("type"), "1");
substrs_matchers.push_back(HasSubstr(member));
network_matchers.push_back(Field(&net_value_type::first, member));
}
else
substrs_matchers.push_back(Not(HasSubstr(member)));
}
auto net_map = mp::platform::detail::get_network_interfaces_from(fake_sys_class_net.path());
using Net = mp::NetworkInterfaceInfo;
network_matchers.push_back(
AllOf(Field(&net_value_type::first, fake_bridge),
Field(&net_value_type::second, AllOf(Field(&Net::id, fake_bridge), Field(&Net::type, "bridge"),
Field(&Net::description, AllOfArray(substrs_matchers))))));
EXPECT_THAT(net_map, UnorderedElementsAreArray(network_matchers));
}
using Param = std::vector<std::pair<std::string, bool>>;
INSTANTIATE_TEST_SUITE_P(
PlatformLinux, BridgeMemberTest,
Values(Param{{"en0", true}}, Param{{"en0", false}}, Param{{"en0", false}, {"en1", true}},
Param{{"asdf", true}, {"ggi", true}, {"a1", true}, {"fu", false}, {"ho", true}, {"ra", false}}));
using OSReleaseTestParam = std::pair<QStringList, std::pair<std::string, std::string>>;
struct OSReleaseTest : public PlatformLinux, WithParamInterface<OSReleaseTestParam>
{
};
OSReleaseTestParam parse_os_release_empty = {
{{"NAME=\"\""},
{"VERSION=\"21.04 (Hirsute Hippo)\""},
{"ID=ubuntu"},
{"ID_LIKE=debian"},
{"PRETTY_NAME=\"Ubuntu 21.04\""},
{"VERSION_ID=\"\""},
{"HOME_URL=\"https://www.ubuntu.com/\""},
{"SUPPORT_URL=\"https://help.ubuntu.com/\""},
{"BUG_REPORT_URL=\"https://bugs.launchpad.net/ubuntu/\""},
{"PRIVACY_POLICY_URL=\"https://www.ubuntu.com/legal/terms-and-policies/privacy-policy\""},
{"VERSION_CODENAME=hirsute"},
{"UBUNTU_CODENAME=hirsute"}},
{"unknown", "unknown"}};
OSReleaseTestParam parse_os_release_single_char_fields = {
{{"NAME=\"A\""},
{"VERSION=\"21.04 (Hirsute Hippo)\""},
{"ID=ubuntu"},
{"ID_LIKE=debian"},
{"PRETTY_NAME=\"Ubuntu 21.04\""},
{"VERSION_ID=\"B\""},
{"HOME_URL=\"https://www.ubuntu.com/\""},
{"SUPPORT_URL=\"https://help.ubuntu.com/\""},
{"BUG_REPORT_URL=\"https://bugs.launchpad.net/ubuntu/\""},
{"PRIVACY_POLICY_URL=\"https://www.ubuntu.com/legal/terms-and-policies/privacy-policy\""},
{"VERSION_CODENAME=hirsute"},
{"UBUNTU_CODENAME=hirsute"}},
{"A", "B"}};
OSReleaseTestParam parse_os_release_ubuntu2104lts = {
{{"NAME=\"Ubuntu\""},
{"VERSION=\"21.04 (Hirsute Hippo)\""},
{"ID=ubuntu"},
{"ID_LIKE=debian"},
{"PRETTY_NAME=\"Ubuntu 21.04\""},
{"VERSION_ID=\"21.04\""},
{"HOME_URL=\"https://www.ubuntu.com/\""},
{"SUPPORT_URL=\"https://help.ubuntu.com/\""},
{"BUG_REPORT_URL=\"https://bugs.launchpad.net/ubuntu/\""},
{"PRIVACY_POLICY_URL=\"https://www.ubuntu.com/legal/terms-and-policies/privacy-policy\""},
{"VERSION_CODENAME=hirsute"},
{"UBUNTU_CODENAME=hirsute"}},
{"Ubuntu", "21.04"}};
OSReleaseTestParam parse_os_release_ubuntu2104lts_rotation = {
{{"VERSION=\"21.04 (Hirsute Hippo)\""},
{"ID=ubuntu"},
{"ID_LIKE=debian"},
{"VERSION_ID=\"21.04\""},
{"PRETTY_NAME=\"Ubuntu 21.04\""},
{"HOME_URL=\"https://www.ubuntu.com/\""},
{"SUPPORT_URL=\"https://help.ubuntu.com/\""},
{"BUG_REPORT_URL=\"https://bugs.launchpad.net/ubuntu/\""},
{"PRIVACY_POLICY_URL=\"https://www.ubuntu.com/legal/terms-and-policies/privacy-policy\""},
{"VERSION_CODENAME=hirsute"},
{"NAME=\"Ubuntu\""},
{"UBUNTU_CODENAME=hirsute"}},
{"Ubuntu", "21.04"}};
TEST_P(OSReleaseTest, test_parse_os_release)
{
const auto& [input, expected] = GetParam();
auto output = multipass::platform::detail::parse_os_release(input);
EXPECT_EQ(expected.first, output.first.toStdString());
EXPECT_EQ(expected.second, output.second.toStdString());
}
INSTANTIATE_TEST_SUITE_P(PlatformLinux, OSReleaseTest,
Values(OSReleaseTestParam{{}, {"unknown", "unknown"}}, parse_os_release_empty,
parse_os_release_single_char_fields, parse_os_release_ubuntu2104lts,
parse_os_release_ubuntu2104lts_rotation));
TEST_F(PlatformLinux, find_os_release_none_found)
{
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, open(_, _)).Times(2).WillRepeatedly(Return(false));
auto output = multipass::platform::detail::find_os_release();
EXPECT_EQ(output->fileName(), "");
}
TEST_F(PlatformLinux, find_os_release_etc)
{
const auto expected_filename = QStringLiteral("/var/lib/snapd/hostfs/etc/os-release");
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
InSequence seq;
EXPECT_CALL(*mock_file_ops,
open(Property(&QFileDevice::fileName, Eq(expected_filename)), QIODevice::ReadOnly | QIODevice::Text))
.Times(1)
.WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, open(_, _)).Times(0); // no other open attempts
auto output = multipass::platform::detail::find_os_release();
EXPECT_EQ(output->fileName(), expected_filename);
}
TEST_F(PlatformLinux, find_os_release_usr_lib)
{
const auto expected_filename = QStringLiteral("/var/lib/snapd/hostfs/usr/lib/os-release");
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
InSequence seq;
EXPECT_CALL(*mock_file_ops, open(Property(&QFileDevice::fileName, Eq("/var/lib/snapd/hostfs/etc/os-release")),
QIODevice::ReadOnly | QIODevice::Text))
.WillOnce(Return(false));
EXPECT_CALL(*mock_file_ops,
open(Property(&QFileDevice::fileName, Eq(expected_filename)), QIODevice::ReadOnly | QIODevice::Text))
.WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, open(_, _)).Times(0); // no other open attempts
auto output = multipass::platform::detail::find_os_release();
EXPECT_EQ(output->fileName(), expected_filename);
}
TEST_F(PlatformLinux, read_os_release_from_file_not_found)
{
const std::string expected = "unknown-unknown";
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, open(_, _)).Times(2).WillRepeatedly(Return(false));
EXPECT_CALL(*mock_file_ops, is_open(testing::A<const QFile&>())).WillOnce(Return(false));
auto output = multipass::platform::detail::read_os_release();
EXPECT_EQ(expected, output);
}
TEST_F(PlatformLinux, read_os_release_from_file)
{
const auto& [input, expected_pair] = parse_os_release_ubuntu2104lts;
auto expected = fmt::format("{}-{}", expected_pair.first, expected_pair.second);
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
InSequence seq;
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, is_open(testing::A<const QFile&>())).WillOnce(Return(true));
for (const auto& line : input)
EXPECT_CALL(*mock_file_ops, read_line).WillOnce(Return(line)).RetiresOnSaturation();
EXPECT_CALL(*mock_file_ops, read_line).WillOnce(Return(QString{}));
auto output = multipass::platform::detail::read_os_release();
EXPECT_EQ(expected, output);
}
TEST_F(PlatformLinux, host_version_from_os)
{
const std::string expected = fmt::format("{}-{}", QSysInfo::productType(), QSysInfo::productVersion());
auto output = multipass::platform::host_version();
EXPECT_EQ(expected, output);
}
TEST_F(PlatformLinux, create_alias_script_works_unconfined)
{
const mpt::TempDir tmp_dir;
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::AppLocalDataLocation))
.WillOnce(Return(tmp_dir.path()));
EXPECT_NO_THROW(MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command", "map"}));
QFile checked_script(tmp_dir.path() + "/bin/alias_name");
checked_script.open(QFile::ReadOnly);
EXPECT_EQ(checked_script.readLine().toStdString(), "#!/bin/sh\n");
EXPECT_EQ(checked_script.readLine().toStdString(), "\n");
EXPECT_THAT(checked_script.readLine().toStdString(), HasSubstr("alias_name -- \"${@}\"\n"));
EXPECT_TRUE(checked_script.atEnd());
auto script_permissions = checked_script.permissions();
EXPECT_TRUE(script_permissions & QFileDevice::ExeOwner);
EXPECT_TRUE(script_permissions & QFileDevice::ExeGroup);
EXPECT_TRUE(script_permissions & QFileDevice::ExeOther);
}
TEST_F(PlatformLinux, create_alias_script_works_confined)
{
const mpt::TempDir tmp_dir;
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::AppLocalDataLocation))
.Times(0);
qputenv("SNAP_NAME", QByteArray{"multipass"});
qputenv("SNAP_USER_COMMON", tmp_dir.path().toUtf8());
EXPECT_NO_THROW(MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command", "map"}));
QFile checked_script(tmp_dir.path() + "/bin/alias_name");
checked_script.open(QFile::ReadOnly);
EXPECT_EQ(checked_script.readLine().toStdString(), "#!/bin/sh\n");
EXPECT_EQ(checked_script.readLine().toStdString(), "\n");
EXPECT_EQ(checked_script.readLine().toStdString(), "exec /usr/bin/snap run multipass alias_name -- \"${@}\"\n");
EXPECT_TRUE(checked_script.atEnd());
auto script_permissions = checked_script.permissions();
EXPECT_TRUE(script_permissions & QFileDevice::ExeOwner);
EXPECT_TRUE(script_permissions & QFileDevice::ExeGroup);
EXPECT_TRUE(script_permissions & QFileDevice::ExeOther);
qunsetenv("SNAP_NAME");
qunsetenv("SNAP_USER_COMMON");
}
TEST_F(PlatformLinux, create_alias_script_overwrites)
{
auto [mock_utils, guard1] = mpt::MockUtils::inject();
auto [mock_file_ops, guard2] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_utils, make_file_with_content(_, _, true)).Times(1);
EXPECT_CALL(*mock_file_ops, permissions(_)).WillOnce(Return(QFileDevice::ReadOwner | QFileDevice::WriteOwner));
EXPECT_CALL(*mock_file_ops, setPermissions(_, _)).WillOnce(Return(true));
EXPECT_NO_THROW(
MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "other_command", "map"}));
}
TEST_F(PlatformLinux, create_alias_script_throws_if_cannot_create_path)
{
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(
MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command", "map"}),
std::runtime_error, mpt::match_what(HasSubstr("failed to create dir '")));
}
TEST_F(PlatformLinux, create_alias_script_throws_if_cannot_write_script)
{
auto [mock_file_ops, guard] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_file_ops, mkpath(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, write(A<QFile&>(), _, _)).WillOnce(Return(747));
MP_EXPECT_THROW_THAT(
MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command", "map"}),
std::runtime_error, mpt::match_what(HasSubstr("failed to write to file '")));
}
TEST_F(PlatformLinux, create_alias_script_throws_if_cannot_set_permissions)
{
auto [mock_utils, guard1] = mpt::MockUtils::inject();
auto [mock_file_ops, guard2] = mpt::MockFileOps::inject();
EXPECT_CALL(*mock_utils, make_file_with_content(_, _, true)).Times(1);
EXPECT_CALL(*mock_file_ops, permissions(_)).WillOnce(Return(QFileDevice::ReadOwner | QFileDevice::WriteOwner));
EXPECT_CALL(*mock_file_ops, setPermissions(_, _)).WillOnce(Return(false));
MP_EXPECT_THROW_THAT(
MP_PLATFORM.create_alias_script("alias_name", mp::AliasDefinition{"instance", "command", "map"}),
std::runtime_error, mpt::match_what(HasSubstr("cannot set permissions to alias script '")));
}
TEST_F(PlatformLinux, remove_alias_script_works)
{
const mpt::TempDir tmp_dir;
QFile script_file(tmp_dir.path() + "/bin/alias_name");
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::AppLocalDataLocation))
.WillOnce(Return(tmp_dir.path()));
MP_UTILS.make_file_with_content(script_file.fileName().toStdString(), "script content\n");
EXPECT_NO_THROW(MP_PLATFORM.remove_alias_script("alias_name"));
EXPECT_FALSE(script_file.exists());
}
TEST_F(PlatformLinux, remove_alias_script_throws_if_cannot_remove_script)
{
const mpt::TempDir tmp_dir;
QFile script_file(tmp_dir.path() + "/bin/alias_name");
EXPECT_CALL(mpt::MockStandardPaths::mock_instance(), writableLocation(mp::StandardPaths::AppLocalDataLocation))
.WillOnce(Return(tmp_dir.path()));
MP_EXPECT_THROW_THAT(MP_PLATFORM.remove_alias_script("alias_name"), std::runtime_error,
mpt::match_what(StrEq("No such file or directory")));
}
} // namespace
| 25,871
|
C++
|
.cpp
| 553
| 41.972875
| 120
| 0.695709
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,655
|
mock_aa_syscalls.cpp
|
canonical_multipass/tests/linux/mock_aa_syscalls.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_aa_syscalls.h"
extern "C" IMPL_MOCK_DEFAULT(0, aa_is_enabled);
| 708
|
C++
|
.cpp
| 18
| 37.388889
| 72
| 0.751453
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,656
|
test_snap_utils.cpp
|
canonical_multipass/tests/linux/test_snap_utils.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/mock_environment_helpers.h"
#include <multipass/exceptions/snap_environment_exception.h>
#include <multipass/snap_utils.h>
#include <QFile>
#include <QTemporaryDir>
#include <utility>
namespace mp = multipass;
namespace mpt = multipass::test;
namespace mpu = multipass::utils;
using namespace testing;
namespace
{
const QByteArray snap_name{"multipass"};
} // namespace
TEST(Snap, recognizes_in_snap_when_snap_name_is_multipass)
{
mpt::SetEnvScope env{"SNAP_NAME", "multipass"};
EXPECT_TRUE(mpu::in_multipass_snap());
}
TEST(Snap, recognizes_not_in_snap_when_snap_name_is_empty)
{
mpt::UnsetEnvScope env{"SNAP_NAME"};
EXPECT_FALSE(mpu::in_multipass_snap());
}
TEST(Snap, recognizes_not_in_snap_when_snap_name_is_otherwise)
{
mpt::SetEnvScope env{"SNAP_NAME", "otherwise"};
EXPECT_FALSE(mpu::in_multipass_snap());
}
struct SnapDirs : public TestWithParam<std::pair<const char*, std::function<QByteArray()>>>
{
};
TEST_P(SnapDirs, test_snap_dir_no_throw_if_set)
{
const auto& [var, getter] = GetParam();
mpt::SetEnvScope env(var, "/tmp");
mpt::SetEnvScope env2("SNAP_NAME", snap_name);
EXPECT_NO_THROW(getter());
}
TEST_P(SnapDirs, test_snap_dir_throws_if_not_set)
{
const auto& [var, getter] = GetParam();
mpt::UnsetEnvScope env(var);
mpt::SetEnvScope env2("SNAP_NAME", snap_name);
EXPECT_THROW(getter(), mp::SnapEnvironmentException);
}
TEST_P(SnapDirs, test_snap_dir_throws_when_snap_name_not_set)
{
const auto& [var, getter] = GetParam();
QTemporaryDir snap_dir;
mpt::SetEnvScope env(var, snap_dir.path().toUtf8());
mpt::UnsetEnvScope env2("SNAP_NAME");
EXPECT_THROW(getter(), mp::SnapEnvironmentException);
}
TEST_P(SnapDirs, test_snap_dir_throws_when_snap_name_not_multipass)
{
const auto& [var, getter] = GetParam();
QByteArray other_name{"foo"};
QTemporaryDir snap_dir;
mpt::SetEnvScope env(var, snap_dir.path().toUtf8());
mpt::SetEnvScope env2("SNAP_NAME", other_name);
EXPECT_THROW(getter(), mp::SnapEnvironmentException);
}
TEST_P(SnapDirs, test_snap_dir_read_ok)
{
const auto& [var, getter] = GetParam();
QTemporaryDir snap_dir;
mpt::SetEnvScope env(var, snap_dir.path().toUtf8());
mpt::SetEnvScope env2("SNAP_NAME", snap_name);
EXPECT_EQ(snap_dir.path(), getter());
}
TEST_P(SnapDirs, test_snap_dir_resolves_links)
{
const auto& [var, getter] = GetParam();
QTemporaryDir snap_dir, link_dir;
link_dir.remove();
QFile::link(snap_dir.path(), link_dir.path());
mpt::SetEnvScope env(var, link_dir.path().toUtf8());
mpt::SetEnvScope env2("SNAP_NAME", snap_name);
EXPECT_EQ(snap_dir.path(), getter());
}
INSTANTIATE_TEST_SUITE_P(SnapUtils,
SnapDirs,
testing::Values(std::make_pair("SNAP", &mpu::snap_dir),
std::make_pair("SNAP_COMMON", &mpu::snap_common_dir),
std::make_pair("SNAP_REAL_HOME", &mpu::snap_real_home_dir)));
| 3,700
|
C++
|
.cpp
| 103
| 31.825243
| 102
| 0.691296
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,657
|
test_libvirt_backend.cpp
|
canonical_multipass/tests/libvirt/test_libvirt_backend.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/fake_handle.h"
#include "tests/mock_backend_utils.h"
#include "tests/mock_logger.h"
#include "tests/mock_ssh.h"
#include "tests/mock_status_monitor.h"
#include "tests/stub_ssh_key_provider.h"
#include "tests/stub_status_monitor.h"
#include "tests/temp_dir.h"
#include "tests/temp_file.h"
#include <src/platform/backends/libvirt/libvirt_virtual_machine_factory.h>
#include <multipass/auto_join_thread.h>
#include <multipass/exceptions/start_exception.h>
#include <multipass/memory_size.h>
#include <multipass/network_interface_info.h>
#include <multipass/virtual_machine.h>
#include <multipass/virtual_machine_description.h>
#include <cstdlib>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
using namespace std::chrono_literals;
struct LibVirtBackend : public Test
{
mpt::TempFile dummy_image;
mpt::TempFile dummy_cloud_init_iso;
mp::VirtualMachineDescription default_description{2,
mp::MemorySize{"3M"},
mp::MemorySize{}, // not used
"pied-piper-valley",
"",
{},
"ubuntu",
{dummy_image.name(), "", "", "", "", {}},
dummy_cloud_init_iso.name(),
{},
{},
{},
{}};
mpt::TempDir data_dir;
mpt::StubSSHKeyProvider key_provider;
// This indicates that LibvirtWrapper should open the test executable
std::string fake_libvirt_path{""};
mpt::MockLogger::Scope logger_scope{mpt::MockLogger::inject()};
mpt::MockBackend::GuardedMock backend_attr{mpt::MockBackend::inject<NiceMock>()};
mpt::MockBackend* mock_backend = backend_attr.first;
};
TEST_F(LibVirtBackend, libvirt_wrapper_missing_libvirt_throws)
{
EXPECT_THROW(mp::LibvirtWrapper{"missing_libvirt"}, mp::LibvirtOpenException);
}
TEST_F(LibVirtBackend, health_check_good_does_not_throw)
{
EXPECT_CALL(*mock_backend, check_for_kvm_support()).WillOnce(Return());
EXPECT_CALL(*mock_backend, check_if_kvm_is_in_use()).WillOnce(Return());
mp::LibVirtVirtualMachineFactory backend(data_dir.path(), fake_libvirt_path);
EXPECT_NO_THROW(backend.hypervisor_health_check());
}
TEST_F(LibVirtBackend, health_check_failed_connection_throws)
{
const std::string error_msg{"Not working"};
EXPECT_CALL(*mock_backend, check_for_kvm_support()).WillOnce(Return());
EXPECT_CALL(*mock_backend, check_if_kvm_is_in_use()).WillOnce(Return());
auto virGetLastErrorMessage = [&error_msg] { return error_msg.c_str(); };
static auto static_virGetLastErrorMessage = virGetLastErrorMessage;
mp::LibVirtVirtualMachineFactory backend(data_dir.path(), fake_libvirt_path);
backend.libvirt_wrapper->virConnectOpen = [](auto...) -> virConnectPtr { return nullptr; };
backend.libvirt_wrapper->virGetLastErrorMessage = [] { return static_virGetLastErrorMessage(); };
MP_EXPECT_THROW_THAT(
backend.hypervisor_health_check(), std::runtime_error,
mpt::match_what(StrEq(fmt::format(
"Cannot connect to libvirtd: {}\nPlease ensure libvirt is installed and running.", error_msg))));
}
TEST_F(LibVirtBackend, creates_in_off_state)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
mpt::StubVMStatusMonitor stub_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off));
}
TEST_F(LibVirtBackend, creates_in_suspended_state_with_managed_save)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virDomainHasManagedSaveImage = [](auto...) { return 1; };
mpt::StubVMStatusMonitor stub_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::suspended));
}
TEST_F(LibVirtBackend, machine_sends_monitoring_events)
{
REPLACE(ssh_connect, [](auto...) { return SSH_OK; });
REPLACE(ssh_userauth_publickey, [](auto...) { return SSH_AUTH_SUCCESS; });
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virNetworkGetDHCPLeases = [](auto, auto, auto leases, auto) {
virNetworkDHCPLeasePtr* leases_ret;
leases_ret = (virNetworkDHCPLeasePtr*)calloc(1, sizeof(virNetworkDHCPLeasePtr));
leases_ret[0] = (virNetworkDHCPLeasePtr)calloc(1, sizeof(virNetworkDHCPLease));
leases_ret[0]->ipaddr = strdup("0.0.0.0");
*leases = leases_ret;
return 1;
};
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_CALL(mock_monitor, on_resume());
machine->start();
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_RUNNING;
return 0;
};
machine->wait_until_ssh_up(2min);
EXPECT_CALL(mock_monitor, on_shutdown());
machine->shutdown();
EXPECT_CALL(mock_monitor, on_suspend());
machine->suspend();
}
TEST_F(LibVirtBackend, machine_persists_and_sets_state_on_start)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
machine->start();
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_RUNNING;
return 0;
};
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::starting));
}
TEST_F(LibVirtBackend, machine_persists_and_sets_state_on_shutdown)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_RUNNING;
return 0;
};
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
machine->shutdown();
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_SHUTOFF;
return 0;
};
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off));
}
TEST_F(LibVirtBackend, machine_persists_and_sets_state_on_suspend)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_RUNNING;
return 0;
};
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
machine->suspend();
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_SHUTOFF;
return 0;
};
backend.libvirt_wrapper->virDomainHasManagedSaveImage = [](auto...) { return 1; };
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::suspended));
}
TEST_F(LibVirtBackend, start_with_broken_libvirt_connection_throws)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virConnectOpen = [](auto...) -> virConnectPtr { return nullptr; };
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_THROW(machine->start(), std::runtime_error);
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::unknown));
}
TEST_F(LibVirtBackend, shutdown_with_broken_libvirt_connection_throws)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virConnectOpen = [](auto...) -> virConnectPtr { return nullptr; };
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_THROW(machine->shutdown(), std::runtime_error);
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::unknown));
}
TEST_F(LibVirtBackend, suspend_with_broken_libvirt_connection_throws)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virConnectOpen = [](auto...) -> virConnectPtr { return nullptr; };
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_THROW(machine->suspend(), std::runtime_error);
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::unknown));
}
TEST_F(LibVirtBackend, current_state_with_broken_libvirt_unknown)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virConnectOpen = [](auto...) -> virConnectPtr { return nullptr; };
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::unknown));
}
TEST_F(LibVirtBackend, current_state_delayed_shutdown_domain_running)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_RUNNING;
return 0;
};
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
machine->state = mp::VirtualMachine::State::delayed_shutdown;
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::delayed_shutdown));
}
TEST_F(LibVirtBackend, current_state_delayed_shutdown_domain_off)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
machine->state = mp::VirtualMachine::State::delayed_shutdown;
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off));
}
TEST_F(LibVirtBackend, current_state_off_domain_starts_running)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off));
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_RUNNING;
return 0;
};
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::running));
}
TEST_F(LibVirtBackend, returns_version_string)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virConnectGetVersion = [](virConnectPtr, unsigned long* hvVer) {
*hvVer = 1002003;
return 0;
};
EXPECT_EQ(backend.get_backend_version_string(), "libvirt-1.2.3");
}
TEST_F(LibVirtBackend, returns_version_string_when_error)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virConnectGetVersion = [](auto...) { return -1; };
EXPECT_EQ(backend.get_backend_version_string(), "libvirt-unknown");
}
TEST_F(LibVirtBackend, returns_version_string_when_lacking_capabilities)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
EXPECT_EQ(backend.get_backend_version_string(), "libvirt-unknown");
}
TEST_F(LibVirtBackend, returns_version_string_when_failed_connecting)
{
auto called{0};
auto virConnectGetVersion = [&called](auto...) {
++called;
return 0;
};
// Need this to "fake out" not being able to assign lambda's that capture directly
// to a pointer to a function.
static auto static_virConnectGetVersion = virConnectGetVersion;
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virConnectOpen = [](auto...) -> virConnectPtr { return nullptr; };
backend.libvirt_wrapper->virConnectGetVersion = [](virConnectPtr conn, long unsigned int* hwVer) {
return static_virConnectGetVersion(conn, hwVer);
};
EXPECT_EQ(backend.get_backend_version_string(), "libvirt-unknown");
EXPECT_EQ(called, 0);
}
TEST_F(LibVirtBackend, ssh_hostname_returns_expected_value)
{
mpt::StubVMStatusMonitor stub_monitor;
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
const std::string expected_ip{"10.10.0.34"};
auto virNetworkGetDHCPLeases = [&expected_ip](auto, auto, auto leases, auto) {
virNetworkDHCPLeasePtr* leases_ret;
leases_ret = (virNetworkDHCPLeasePtr*)calloc(1, sizeof(virNetworkDHCPLeasePtr));
leases_ret[0] = (virNetworkDHCPLeasePtr)calloc(1, sizeof(virNetworkDHCPLease));
leases_ret[0]->ipaddr = strdup(expected_ip.c_str());
*leases = leases_ret;
return 1;
};
static auto static_virNetworkGetDHCPLeases = virNetworkGetDHCPLeases;
backend.libvirt_wrapper->virNetworkGetDHCPLeases = [](virNetworkPtr network, const char* mac,
virNetworkDHCPLeasePtr** leases, unsigned int flags) {
return static_virNetworkGetDHCPLeases(network, mac, leases, flags);
};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->start();
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_RUNNING;
return 0;
};
EXPECT_EQ(machine->VirtualMachine::ssh_hostname(), expected_ip);
}
TEST_F(LibVirtBackend, ssh_hostname_timeout_throws_and_sets_unknown_state)
{
mpt::StubVMStatusMonitor stub_monitor;
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
backend.libvirt_wrapper->virNetworkGetDHCPLeases = [](auto...) { return 0; };
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->start();
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_RUNNING;
return 0;
};
EXPECT_THROW(machine->ssh_hostname(std::chrono::milliseconds(1)), std::runtime_error);
EXPECT_EQ(machine->state, mp::VirtualMachine::State::unknown);
}
TEST_F(LibVirtBackend, shutdown_while_starting_throws_and_sets_correct_state)
{
mpt::StubVMStatusMonitor stub_monitor;
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
auto destroy_called{false};
auto virDomainDestroy = [&backend, &destroy_called](auto...) {
destroy_called = true;
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_SHUTOFF;
return 0;
};
return 0;
};
static auto static_virDomainDestroy = virDomainDestroy;
backend.libvirt_wrapper->virDomainDestroy = [](virDomainPtr domain) { return static_virDomainDestroy(domain); };
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->start();
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_RUNNING;
return 0;
};
ASSERT_EQ(machine->state, mp::VirtualMachine::State::starting);
mp::AutoJoinThread thread = [&machine] { machine->shutdown(mp::VirtualMachine::ShutdownPolicy::Poweroff); };
using namespace std::chrono_literals;
while (!destroy_called)
std::this_thread::sleep_for(1ms);
MP_EXPECT_THROW_THAT(machine->ensure_vm_is_running(), mp::StartException,
mpt::match_what(StrEq("Instance failed to start")));
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::off);
}
TEST_F(LibVirtBackend, machineInOffStateLogsAndIgnoresShutdown)
{
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off));
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_SHUTOFF;
return 0;
};
logger_scope.mock_logger->screen_logs(mpl::Level::info);
logger_scope.mock_logger->expect_log(mpl::Level::info, "Ignoring shutdown since instance is already stopped.");
machine->shutdown();
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::off);
}
TEST_F(LibVirtBackend, machineNoForceCannotShutdownLogsAndThrows)
{
const std::string error_msg{"Not working"};
mp::LibVirtVirtualMachineFactory backend{data_dir.path(), fake_libvirt_path};
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
backend.libvirt_wrapper->virDomainGetState = [](auto, auto state, auto, auto) {
*state = VIR_DOMAIN_RUNNING;
return 0;
};
backend.libvirt_wrapper->virDomainShutdown = [](auto) { return -1; };
auto virGetLastErrorMessage = [&error_msg] { return error_msg.c_str(); };
static auto static_virGetLastErrorMessage = virGetLastErrorMessage;
backend.libvirt_wrapper->virGetLastErrorMessage = [] { return static_virGetLastErrorMessage(); };
logger_scope.mock_logger->screen_logs(mpl::Level::warning);
logger_scope.mock_logger->expect_log(mpl::Level::warning, error_msg);
MP_EXPECT_THROW_THAT(machine->shutdown(),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr("pied-piper-valley"), HasSubstr(error_msg))));
}
TEST_F(LibVirtBackend, lists_no_networks)
{
mp::LibVirtVirtualMachineFactory backend(data_dir.path(), fake_libvirt_path);
EXPECT_THROW(backend.networks(), mp::NotImplementedOnThisBackendException);
}
| 19,898
|
C++
|
.cpp
| 394
| 43.964467
| 116
| 0.699773
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,658
|
fake_libvirt_library.cpp
|
canonical_multipass/tests/libvirt/fake_libvirt_library.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/fake_handle.h"
#include <libvirt/libvirt.h>
#include <libvirt/virterror.h>
#include <stdlib.h>
#include <string.h>
namespace mpt = multipass::test;
/*
* These are default fake libvirt functions for testing. They return the most
* common values needed for testing.
* See test_libvirt_backend.cpp for examples on how to override these functions
* using LibvirtWrapper.
*/
virConnectPtr virConnectOpen(const char* name)
{
return mpt::fake_handle<virConnectPtr>();
}
int virConnectClose(virConnectPtr conn)
{
return 0;
}
char* virConnectGetCapabilities(virConnectPtr /*conn*/)
{
return strdup("");
}
int virConnectGetVersion(virConnectPtr /*conn*/, unsigned long* hvVer)
{
*hvVer = 0;
return 0;
}
int virDomainCreate(virDomainPtr /*domain*/)
{
return 0;
}
virDomainPtr virDomainDefineXML(virConnectPtr /*conn*/, const char* /*xml*/)
{
return mpt::fake_handle<virDomainPtr>();
}
int virDomainDestroy(virDomainPtr /*domain*/)
{
return 0;
}
int virDomainFree(virDomainPtr /*domain*/)
{
return 0;
}
int virDomainGetState(virDomainPtr /*domain*/, int* state, int* /*reason*/, unsigned int /*flags*/)
{
*state = VIR_DOMAIN_SHUTOFF;
return 0;
}
char* virDomainGetXMLDesc(virDomainPtr /*domain*/, unsigned int /*flags*/)
{
return strdup("mac");
}
int virDomainHasManagedSaveImage(virDomainPtr /*domain*/, unsigned int /*flags*/)
{
return 0;
}
virDomainPtr virDomainLookupByName(virConnectPtr /*conn*/, const char* /*name*/)
{
return mpt::fake_handle<virDomainPtr>();
}
int virDomainManagedSave(virDomainPtr /*domain*/, unsigned int /*flags*/)
{
return 0;
}
int virDomainShutdown(virDomainPtr /*domain*/)
{
return 0;
}
int virDomainUndefine(virDomainPtr /*domain*/)
{
return 0;
}
int virNetworkCreate(virNetworkPtr /*network*/)
{
return 0;
}
virNetworkPtr virNetworkCreateXML(virConnectPtr /*conn*/, const char* /*xmlDesc*/)
{
return mpt::fake_handle<virNetworkPtr>();
}
int virNetworkDestroy(virNetworkPtr /*network*/)
{
return 0;
}
void virNetworkDHCPLeaseFree(virNetworkDHCPLeasePtr lease)
{
free(lease);
}
int virNetworkFree(virNetworkPtr /*network*/)
{
return 0;
}
char* virNetworkGetBridgeName(virNetworkPtr /*network*/)
{
return strdup("mpvirt0");
}
int virNetworkGetDHCPLeases(virNetworkPtr /*network*/, const char* /*mac*/, virNetworkDHCPLeasePtr** /*leases*/,
unsigned int /*flags*/)
{
return 0;
}
int virNetworkIsActive(virNetworkPtr /*network*/)
{
return 1;
}
virNetworkPtr virNetworkLookupByName(virConnectPtr /*conn*/, const char* /*name*/)
{
return mpt::fake_handle<virNetworkPtr>();
}
const char* virGetLastErrorMessage()
{
static char fake_error[64] = "";
return fake_error;
}
int virDomainSetVcpusFlags(virDomainPtr /*domain*/, unsigned int /*nvcpus*/, unsigned int /*flags*/)
{
return 1;
}
int virDomainSetMemoryFlags(virDomainPtr /*domain*/, unsigned long /*memory*/, unsigned int /*flags*/)
{
return 1;
}
| 3,644
|
C++
|
.cpp
| 140
| 23.592857
| 112
| 0.737252
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,659
|
broken_libvirt_library.cpp
|
canonical_multipass/tests/libvirt/broken_libvirt_library.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <libvirt/libvirt.h>
/*
* This is a (very) broken libvirt implementation to test dlsym() handling
* in LibvirtWrapper, ie, not all functions are defined.
*/
virConnectPtr virConnectOpen(const char* /*name*/)
{
return nullptr;
}
| 874
|
C++
|
.cpp
| 25
| 32.96
| 74
| 0.751773
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,660
|
test_qemu_backend.cpp
|
canonical_multipass/tests/qemu/test_qemu_backend.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_qemu_platform.h"
#include "tests/common.h"
#include "tests/mock_cloud_init_file_ops.h"
#include "tests/mock_environment_helpers.h"
#include "tests/mock_logger.h"
#include "tests/mock_platform.h"
#include "tests/mock_process_factory.h"
#include "tests/mock_snapshot.h"
#include "tests/mock_status_monitor.h"
#include "tests/mock_virtual_machine.h"
#include "tests/path.h"
#include "tests/stub_process_factory.h"
#include "tests/stub_ssh_key_provider.h"
#include "tests/stub_status_monitor.h"
#include "tests/temp_dir.h"
#include "tests/temp_file.h"
#include "tests/test_with_mocked_bin_path.h"
#include <src/platform/backends/qemu/qemu_virtual_machine.h>
#include <src/platform/backends/qemu/qemu_virtual_machine_factory.h>
#include <multipass/auto_join_thread.h>
#include <multipass/exceptions/start_exception.h>
#include <multipass/exceptions/virtual_machine_state_exceptions.h>
#include <multipass/memory_size.h>
#include <multipass/platform.h>
#include <multipass/snapshot.h>
#include <multipass/virtual_machine.h>
#include <multipass/virtual_machine_description.h>
#include <multipass/vm_specs.h>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <thread>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
// copied from QemuVirtualMachine implementation
constexpr auto suspend_tag = "suspend";
// we need a whitespace to terminate the tag column in the fake output of qemu-img
const QByteArray fake_snapshot_list_with_suspend_tag = QByteArray{suspend_tag} + " ";
} // namespace
struct QemuBackend : public mpt::TestWithMockedBinPath
{
QemuBackend()
{
EXPECT_CALL(*mock_qemu_platform, remove_resources_for(_)).WillRepeatedly(Return());
EXPECT_CALL(*mock_qemu_platform, vm_platform_args(_)).WillRepeatedly(Return(QStringList()));
EXPECT_CALL(*mock_qemu_platform, get_directory_name()).WillRepeatedly(Return(QString()));
};
mpt::TempFile dummy_image;
mpt::TempFile dummy_cloud_init_iso;
mp::VirtualMachineDescription default_description{2,
mp::MemorySize{"3M"},
mp::MemorySize{}, // not used
"pied-piper-valley",
"",
{},
"",
{dummy_image.name(), "", "", "", {}, {}},
dummy_cloud_init_iso.name(),
{},
{},
{},
{}};
mpt::TempDir data_dir;
mpt::TempDir instance_dir;
const std::string tap_device{"tapfoo"};
const QString bridge_name{"dummy-bridge"};
const std::string subnet{"192.168.64"};
mpt::StubSSHKeyProvider key_provider{};
mpt::StubVMStatusMonitor stub_monitor{};
mpt::MockProcessFactory::Callback handle_external_process_calls = [](mpt::MockProcess* process) {
// Have "qemu-img snapshot" return a string with the suspend tag in it
if (process->program().contains("qemu-img") && process->arguments().contains("snapshot"))
{
mp::ProcessState exit_state;
exit_state.exit_code = 0;
ON_CALL(*process, execute(_)).WillByDefault(Return(exit_state));
ON_CALL(*process, read_all_standard_output()).WillByDefault(Return(fake_snapshot_list_with_suspend_tag));
}
else if (process->program() == "iptables")
{
mp::ProcessState exit_state;
exit_state.exit_code = 0;
ON_CALL(*process, execute(_)).WillByDefault(Return(exit_state));
}
};
static void handle_qemu_system(mpt::MockProcess* process)
{
if (process->program().contains("qemu-system"))
{
EXPECT_CALL(*process, start()).WillRepeatedly([process] {
emit process->state_changed(QProcess::Running);
emit process->started();
});
EXPECT_CALL(*process, wait_for_finished(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*process, write(_)).WillRepeatedly([process](const QByteArray& data) {
QJsonParseError parse_error;
auto json = QJsonDocument::fromJson(data, &parse_error);
if (parse_error.error == QJsonParseError::NoError)
{
auto json_object = json.object();
auto execute = json_object["execute"];
if (execute == "system_powerdown")
{
EXPECT_CALL(*process, wait_for_finished(_)).WillOnce([process](auto...) {
mp::ProcessState exit_state{0, std::nullopt};
emit process->finished(exit_state);
return true;
});
}
else if (execute == "human-monitor-command")
{
auto args = json_object["arguments"].toObject();
auto command_line = args["command-line"];
if (command_line == "savevm suspend")
{
EXPECT_CALL(*process, read_all_standard_output())
.WillRepeatedly(Return(
"{\"timestamp\": {\"seconds\": 1541188919, \"microseconds\": 838498}, \"event\": "
"\"RESUME\"}"));
EXPECT_CALL(*process, kill()).WillOnce([process] {
mp::ProcessState exit_state{
std::nullopt, mp::ProcessState::Error{QProcess::Crashed, QStringLiteral("")}};
emit process->error_occurred(QProcess::Crashed, "Crashed");
emit process->finished(exit_state);
});
emit process->ready_read_standard_output();
}
}
}
return data.size();
});
if (process->arguments().contains("-dump-vmstate"))
{
mp::ProcessState exit_state;
exit_state.exit_code = 0;
EXPECT_CALL(*process, execute(_)).WillOnce(Return(exit_state));
}
}
};
mpt::MockLogger::Scope logger_scope{mpt::MockLogger::inject()};
mpt::SetEnvScope env_scope{"DISABLE_APPARMOR", "1"};
std::unique_ptr<mpt::MockProcessFactory::Scope> process_factory{mpt::MockProcessFactory::Inject()};
std::unique_ptr<mpt::MockQemuPlatform> mock_qemu_platform{std::make_unique<mpt::MockQemuPlatform>()};
mpt::MockQemuPlatformFactory::GuardedMock qemu_platform_factory_attr{
mpt::MockQemuPlatformFactory::inject<NiceMock>()};
mpt::MockQemuPlatformFactory* mock_qemu_platform_factory{qemu_platform_factory_attr.first};
};
TEST_F(QemuBackend, creates_in_off_state)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off));
}
TEST_F(QemuBackend, machine_in_off_state_handles_shutdown)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off));
machine->shutdown();
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off));
}
TEST_F(QemuBackend, machine_start_shutdown_sends_monitoring_events)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
mp::QemuVirtualMachineFactory backend{data_dir.path()};
process_factory->register_callback(handle_qemu_system);
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
EXPECT_CALL(mock_monitor, on_resume());
machine->start();
machine->state = mp::VirtualMachine::State::running;
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
EXPECT_CALL(mock_monitor, on_shutdown());
machine->shutdown();
}
TEST_F(QemuBackend, machine_start_suspend_sends_monitoring_event)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
mp::QemuVirtualMachineFactory backend{data_dir.path()};
process_factory->register_callback(handle_qemu_system);
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
EXPECT_CALL(mock_monitor, on_resume());
machine->start();
machine->state = mp::VirtualMachine::State::running;
EXPECT_CALL(mock_monitor, on_suspend());
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
machine->suspend();
}
TEST_F(QemuBackend, throws_when_shutdown_while_starting)
{
mpt::MockProcess* vmproc = nullptr;
process_factory->register_callback([&vmproc](mpt::MockProcess* process) {
if (process->program().startsWith("qemu-system-") &&
!process->arguments().contains("-dump-vmstate")) // we only care about the actual vm process
{
vmproc = process; // save this to control later
}
});
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->start();
ASSERT_EQ(machine->state, mp::VirtualMachine::State::starting);
mp::AutoJoinThread thread{[&machine, vmproc] {
ON_CALL(*vmproc, running()).WillByDefault(Return(false));
machine->shutdown(mp::VirtualMachine::ShutdownPolicy::Poweroff);
}};
using namespace std::chrono_literals;
while (machine->state != mp::VirtualMachine::State::off)
std::this_thread::sleep_for(1ms);
MP_EXPECT_THROW_THAT(machine->ensure_vm_is_running(), mp::StartException,
Property(&mp::StartException::name, Eq(machine->vm_name)));
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::off);
}
TEST_F(QemuBackend, throws_on_shutdown_timeout)
{
static const std::string sub_error_msg1{"The QEMU process did not finish within "};
static const std::string sub_error_msg2{"seconds after being shutdown"};
mpt::MockProcess* vmproc = nullptr;
process_factory->register_callback([&vmproc](mpt::MockProcess* process) {
if (process->program().startsWith("qemu-system-") &&
!process->arguments().contains("-dump-vmstate")) // we only care about the actual vm process
{
vmproc = process; // save this to control later
}
});
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mpt::StubVMStatusMonitor stub_monitor;
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->start();
ASSERT_TRUE(vmproc);
EXPECT_CALL(*vmproc, wait_for_finished).WillOnce(Return(false)).WillRepeatedly(Return(true));
EXPECT_CALL(*vmproc, running).WillOnce(Return(true)).WillRepeatedly(Return(false));
machine->state = mp::VirtualMachine::State::running;
MP_EXPECT_THROW_THAT(machine->shutdown(),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr(sub_error_msg1), HasSubstr(sub_error_msg2))));
EXPECT_NE(machine->current_state(), mp::VirtualMachine::State::off);
}
TEST_F(QemuBackend, includes_error_when_shutdown_while_starting)
{
constexpr auto error_msg = "failing spectacularly";
mpt::MockProcess* vmproc = nullptr;
process_factory->register_callback([&vmproc](mpt::MockProcess* process) {
if (process->program().startsWith("qemu-system-") &&
!process->arguments().contains("-dump-vmstate")) // we only care about the actual vm process
{
vmproc = process; // save this to control later
EXPECT_CALL(*process, read_all_standard_error()).WillOnce(Return(error_msg));
}
});
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->start(); // we need this so that Process signals get connected to their handlers
EXPECT_EQ(machine->state, mp::VirtualMachine::State::starting);
ASSERT_TRUE(vmproc);
emit vmproc->ready_read_standard_error(); // fake process standard error having something to read
ON_CALL(*vmproc, running()).WillByDefault(Return(false)); /* simulate process not running anymore,
to avoid blocking on destruction */
mp::AutoJoinThread finishing_thread{[vmproc]() {
mp::ProcessState exit_state;
exit_state.exit_code = 1;
emit vmproc->finished(exit_state); /* note that this waits on a condition variable that is unblocked by
ensure_vm_is_running */
}};
using namespace std::chrono_literals;
while (machine->state != mp::VirtualMachine::State::off)
std::this_thread::sleep_for(1ms);
MP_EXPECT_THROW_THAT(
machine->ensure_vm_is_running(), mp::StartException,
AllOf(Property(&mp::StartException::name, Eq(machine->vm_name)),
mpt::match_what(AllOf(HasSubstr(error_msg), HasSubstr("shutdown"), HasSubstr("starting")))));
}
TEST_F(QemuBackend, machine_unknown_state_properly_shuts_down)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
mp::QemuVirtualMachineFactory backend{data_dir.path()};
process_factory->register_callback(handle_qemu_system);
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
EXPECT_CALL(mock_monitor, on_resume());
machine->start();
machine->state = mp::VirtualMachine::State::unknown;
EXPECT_CALL(mock_monitor, persist_state_for(_, _));
EXPECT_CALL(mock_monitor, on_shutdown());
machine->shutdown();
EXPECT_THAT(machine->current_state(), Eq(mp::VirtualMachine::State::off));
}
TEST_F(QemuBackend, suspendedStateNoForceShutdownThrows)
{
const std::string sub_error_msg{"Cannot shut down suspended instance"};
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->state = mp::VirtualMachine::State::suspended;
MP_EXPECT_THROW_THAT(machine->shutdown(), mp::VMStateInvalidException, mpt::match_what(HasSubstr(sub_error_msg)));
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::suspended);
}
TEST_F(QemuBackend, suspendingStateNoForceShutdownThrows)
{
const std::string sub_error_msg1{"Cannot shut down instance"};
const std::string sub_error_msg2{"while suspending."};
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->state = mp::VirtualMachine::State::suspending;
MP_EXPECT_THROW_THAT(machine->shutdown(),
mp::VMStateInvalidException,
mpt::match_what(AllOf(HasSubstr(sub_error_msg1), HasSubstr(sub_error_msg2))));
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::suspending);
}
TEST_F(QemuBackend, startingStateNoForceShutdownThrows)
{
const std::string sub_error_msg1{"Cannot shut down instance"};
const std::string sub_error_msg2{"while starting."};
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->state = mp::VirtualMachine::State::starting;
MP_EXPECT_THROW_THAT(machine->shutdown(),
mp::VMStateInvalidException,
mpt::match_what(AllOf(HasSubstr(sub_error_msg1), HasSubstr(sub_error_msg2))));
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::starting);
}
TEST_F(QemuBackend, forceShutdownKillsProcessAndLogs)
{
mpt::MockProcess* vmproc = nullptr;
process_factory->register_callback([&vmproc](mpt::MockProcess* process) {
if (process->program().startsWith("qemu-system-") &&
!process->arguments().contains("-dump-vmstate")) // we only care about the actual vm process
{
vmproc = process; // save this to control later
EXPECT_CALL(*process, kill()).WillOnce([process] {
mp::ProcessState exit_state{
std::nullopt,
mp::ProcessState::Error{QProcess::Crashed, QStringLiteral("Force stopped")}};
emit process->error_occurred(QProcess::Crashed, "Killed");
emit process->finished(exit_state);
});
}
});
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
logger_scope.mock_logger->screen_logs(mpl::Level::info);
logger_scope.mock_logger->expect_log(mpl::Level::info, "process program");
logger_scope.mock_logger->expect_log(mpl::Level::info, "process arguments");
logger_scope.mock_logger->expect_log(mpl::Level::info, "process started");
logger_scope.mock_logger->expect_log(mpl::Level::info, "Forcing shutdown");
logger_scope.mock_logger->expect_log(mpl::Level::info, "Killing process");
logger_scope.mock_logger->expect_log(mpl::Level::info, "Killed");
logger_scope.mock_logger->expect_log(mpl::Level::info, "Force stopped");
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->start(); // we need this so that Process signals get connected to their handlers
ASSERT_TRUE(vmproc);
machine->state = mp::VirtualMachine::State::running;
machine->shutdown(mp::VirtualMachine::ShutdownPolicy::Poweroff); // force shutdown
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::off);
}
TEST_F(QemuBackend, forceShutdownNoProcessLogs)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
logger_scope.mock_logger->screen_logs(mpl::Level::debug);
logger_scope.mock_logger->expect_log(mpl::Level::info, "Forcing shutdown");
logger_scope.mock_logger->expect_log(mpl::Level::debug, "No process to kill");
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->state = mp::VirtualMachine::State::unknown;
machine->shutdown(mp::VirtualMachine::ShutdownPolicy::Poweroff); // force shutdown
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::off);
}
TEST_F(QemuBackend, forceShutdownSuspendDeletesSuspendImageAndOffState)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mpt::MockProcessFactory::Callback snapshot_list_suspend_tag_callback = [](mpt::MockProcess* process) {
if (process->program().contains("qemu-img") && process->arguments().contains("snapshot") &&
process->arguments().contains("-l"))
{
EXPECT_CALL(*process, read_all_standard_output()).WillOnce(Return(fake_snapshot_list_with_suspend_tag));
}
};
process_factory->register_callback(snapshot_list_suspend_tag_callback);
logger_scope.mock_logger->screen_logs(mpl::Level::debug);
logger_scope.mock_logger->expect_log(mpl::Level::info, "Forcing shutdown");
logger_scope.mock_logger->expect_log(mpl::Level::debug, "No process to kill");
logger_scope.mock_logger->expect_log(mpl::Level::info, "Deleting suspend image");
mp::QemuVirtualMachineFactory backend{data_dir.path()};
const auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->state = mp::VirtualMachine::State::suspended;
machine->shutdown(mp::VirtualMachine::ShutdownPolicy::Poweroff);
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::off);
const std::vector<mpt::MockProcessFactory::ProcessInfo> processes = process_factory->process_list();
EXPECT_FALSE(processes.empty());
EXPECT_TRUE(processes.back().command == "qemu-img" && processes.back().arguments.contains("-d") &&
processes.back().arguments.contains(suspend_tag));
}
TEST_F(QemuBackend, forceShutdownSuspendedStateButNoSuspensionSnapshotInImage)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
logger_scope.mock_logger->screen_logs(mpl::Level::debug);
logger_scope.mock_logger->expect_log(mpl::Level::info, "Forcing shutdown");
logger_scope.mock_logger->expect_log(mpl::Level::debug, "No process to kill");
logger_scope.mock_logger->expect_log(mpl::Level::warning, "Image has no suspension snapshot, but the state is 7");
mp::QemuVirtualMachineFactory backend{data_dir.path()};
const auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->state = mp::VirtualMachine::State::suspended;
machine->shutdown(mp::VirtualMachine::ShutdownPolicy::Poweroff);
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::off);
}
TEST_F(QemuBackend, forceShutdownRunningStateButWithSuspensionSnapshotInImage)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mpt::MockProcessFactory::Callback snapshot_list_suspend_tag_callback = [](mpt::MockProcess* process) {
if (process->program().contains("qemu-img") && process->arguments().contains("snapshot") &&
process->arguments().contains("-l"))
{
EXPECT_CALL(*process, read_all_standard_output()).WillOnce(Return(fake_snapshot_list_with_suspend_tag));
}
};
process_factory->register_callback(snapshot_list_suspend_tag_callback);
logger_scope.mock_logger->screen_logs(mpl::Level::debug);
logger_scope.mock_logger->expect_log(mpl::Level::info, "Forcing shutdown");
logger_scope.mock_logger->expect_log(mpl::Level::debug, "No process to kill");
logger_scope.mock_logger->expect_log(mpl::Level::info, "Deleting suspend image");
logger_scope.mock_logger->expect_log(mpl::Level::warning, "Image has a suspension snapshot, but the state is 4");
mp::QemuVirtualMachineFactory backend{data_dir.path()};
const auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->state = mp::VirtualMachine::State::running;
machine->shutdown(mp::VirtualMachine::ShutdownPolicy::Poweroff);
EXPECT_EQ(machine->current_state(), mp::VirtualMachine::State::off);
const std::vector<mpt::MockProcessFactory::ProcessInfo> processes = process_factory->process_list();
EXPECT_FALSE(processes.empty());
EXPECT_TRUE(processes.back().command == "qemu-img" && processes.back().arguments.contains("-d") &&
processes.back().arguments.contains(suspend_tag));
}
TEST_F(QemuBackend, verify_dnsmasq_qemuimg_and_qemu_processes_created)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
auto factory = mpt::StubProcessFactory::Inject();
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->start();
machine->state = mp::VirtualMachine::State::running;
auto processes = factory->process_list();
EXPECT_TRUE(std::find_if(processes.cbegin(), processes.cend(),
[](const mpt::StubProcessFactory::ProcessInfo& process_info) {
return process_info.command == "qemu-img";
}) != processes.cend());
EXPECT_TRUE(std::find_if(processes.cbegin(), processes.cend(),
[](const mpt::StubProcessFactory::ProcessInfo& process_info) {
return process_info.command.startsWith("qemu-system-");
}) != processes.cend());
}
TEST_F(QemuBackend, verify_some_common_qemu_arguments)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mpt::MockProcess* qemu = nullptr;
process_factory->register_callback([&qemu](mpt::MockProcess* process) {
if (process->program().startsWith("qemu-system-") &&
!process->arguments().contains("-dump-vmstate")) // we only care about the actual vm process
{
qemu = process;
}
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->start();
machine->state = mp::VirtualMachine::State::running;
ASSERT_TRUE(qemu != nullptr);
const auto qemu_args = qemu->arguments();
EXPECT_TRUE(qemu_args.contains("-nographic"));
EXPECT_TRUE(qemu_args.contains("-serial"));
EXPECT_TRUE(qemu_args.contains("-qmp"));
EXPECT_TRUE(qemu_args.contains("stdio"));
EXPECT_TRUE(qemu_args.contains("-chardev"));
EXPECT_TRUE(qemu_args.contains("null,id=char0"));
}
TEST_F(QemuBackend, verify_qemu_arguments_when_resuming_suspend_image)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
process_factory->register_callback(handle_external_process_calls);
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
machine->start();
machine->state = mp::VirtualMachine::State::running;
auto processes = process_factory->process_list();
auto qemu = std::find_if(processes.cbegin(), processes.cend(),
[](const mpt::MockProcessFactory::ProcessInfo& process_info) {
return process_info.command.startsWith("qemu-system-");
});
ASSERT_TRUE(qemu != processes.cend());
EXPECT_TRUE(qemu->arguments.contains("-loadvm"));
EXPECT_TRUE(qemu->arguments.contains(suspend_tag));
}
TEST_F(QemuBackend, verify_qemu_arguments_when_resuming_suspend_image_uses_metadata)
{
constexpr auto machine_type = "k0mPuT0R";
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
process_factory->register_callback(handle_external_process_calls);
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
EXPECT_CALL(mock_monitor, retrieve_metadata_for(_))
.WillRepeatedly(Return(QJsonObject({{"machine_type", machine_type}})));
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
machine->start();
machine->state = mp::VirtualMachine::State::running;
auto processes = process_factory->process_list();
auto qemu = std::find_if(processes.cbegin(), processes.cend(),
[](const mpt::MockProcessFactory::ProcessInfo& process_info) {
return process_info.command.startsWith("qemu-system-");
});
ASSERT_TRUE(qemu != processes.cend());
ASSERT_TRUE(qemu->command.startsWith("qemu-system-"));
EXPECT_TRUE(qemu->arguments.contains("-machine"));
EXPECT_TRUE(qemu->arguments.contains(machine_type));
}
TEST_F(QemuBackend, verify_qemu_arguments_from_metadata_are_used)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mpt::MockProcessFactory::Callback callback = [](mpt::MockProcess* process) {
if (process->program().contains("qemu-img") && process->arguments().contains("snapshot"))
{
mp::ProcessState exit_state;
exit_state.exit_code = 0;
EXPECT_CALL(*process, execute(_)).WillOnce(Return(exit_state));
EXPECT_CALL(*process, read_all_standard_output()).WillOnce(Return(fake_snapshot_list_with_suspend_tag));
}
};
process_factory->register_callback(callback);
NiceMock<mpt::MockVMStatusMonitor> mock_monitor;
EXPECT_CALL(mock_monitor, retrieve_metadata_for(_))
.WillRepeatedly(Return(QJsonObject({{"arguments", QJsonArray{"-hi_there", "-hows_it_going"}}})));
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, mock_monitor);
machine->start();
machine->state = mp::VirtualMachine::State::running;
auto processes = process_factory->process_list();
auto qemu = std::find_if(processes.cbegin(), processes.cend(),
[](const mpt::MockProcessFactory::ProcessInfo& process_info) {
return process_info.command.startsWith("qemu-system-");
});
ASSERT_TRUE(qemu != processes.cend());
EXPECT_TRUE(qemu->arguments.contains("-hi_there"));
EXPECT_TRUE(qemu->arguments.contains("-hows_it_going"));
}
TEST_F(QemuBackend, returns_version_string)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
constexpr auto qemu_version_output = "QEMU emulator version 2.11.1(Debian 1:2.11+dfsg-1ubuntu7.15)\n"
"Copyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers\n";
mpt::MockProcessFactory::Callback callback = [](mpt::MockProcess* process) {
if (process->program().contains("qemu-system-") && process->arguments().contains("--version"))
{
mp::ProcessState exit_state;
exit_state.exit_code = 0;
EXPECT_CALL(*process, execute(_)).WillOnce(Return(exit_state));
EXPECT_CALL(*process, read_all_standard_output()).WillOnce(Return(qemu_version_output));
}
};
process_factory->register_callback(callback);
mp::QemuVirtualMachineFactory backend{data_dir.path()};
EXPECT_EQ(backend.get_backend_version_string(), "qemu-2.11.1");
}
TEST_F(QemuBackend, returns_version_string_when_failed_parsing)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
constexpr auto qemu_version_output = "Unparsable version string";
mpt::MockProcessFactory::Callback callback = [](mpt::MockProcess* process) {
if (process->program().contains("qemu-system-") && process->arguments().contains("--version"))
{
mp::ProcessState exit_state;
exit_state.exit_code = 0;
EXPECT_CALL(*process, execute(_)).WillOnce(Return(exit_state));
EXPECT_CALL(*process, read_all_standard_output()).WillRepeatedly(Return(qemu_version_output));
}
};
process_factory->register_callback(callback);
mp::QemuVirtualMachineFactory backend{data_dir.path()};
EXPECT_EQ(backend.get_backend_version_string(), "qemu-unknown");
}
TEST_F(QemuBackend, returns_version_string_when_errored)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mpt::MockProcessFactory::Callback callback = [](mpt::MockProcess* process) {
if (process->program().contains("qemu-system-") && process->arguments().contains("--version"))
{
mp::ProcessState exit_state;
exit_state.exit_code = 1;
EXPECT_CALL(*process, execute(_)).WillOnce(Return(exit_state));
EXPECT_CALL(*process, read_all_standard_output()).WillOnce(Return("Standard output\n"));
EXPECT_CALL(*process, read_all_standard_error()).WillOnce(Return("Standard error\n"));
}
};
process_factory->register_callback(callback);
mp::QemuVirtualMachineFactory backend{data_dir.path()};
EXPECT_EQ(backend.get_backend_version_string(), "qemu-unknown");
}
TEST_F(QemuBackend, returns_version_string_when_exec_failed)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mpt::MockProcessFactory::Callback callback = [](mpt::MockProcess* process) {
if (process->program().contains("qemu-system-") && process->arguments().contains("--version"))
{
mp::ProcessState exit_state;
exit_state.error = mp::ProcessState::Error{QProcess::Crashed, "Error message"};
EXPECT_CALL(*process, execute(_)).WillOnce(Return(exit_state));
EXPECT_CALL(*process, read_all_standard_output()).Times(0);
}
};
process_factory->register_callback(callback);
mp::QemuVirtualMachineFactory backend{data_dir.path()};
EXPECT_EQ(backend.get_backend_version_string(), "qemu-unknown");
}
TEST_F(QemuBackend, ssh_hostname_returns_expected_value)
{
const std::string expected_ip{"10.10.0.34"};
NiceMock<mpt::MockQemuPlatform> mock_qemu_platform;
ON_CALL(mock_qemu_platform, get_ip_for(_)).WillByDefault([&expected_ip](auto...) {
return std::optional<mp::IPAddress>{expected_ip};
});
mp::QemuVirtualMachine machine{default_description,
&mock_qemu_platform,
stub_monitor,
key_provider,
instance_dir.path()};
machine.start();
machine.state = mp::VirtualMachine::State::running;
EXPECT_EQ(machine.VirtualMachine::ssh_hostname(), expected_ip);
}
TEST_F(QemuBackend, gets_management_ip)
{
const std::string expected_ip{"10.10.0.35"};
NiceMock<mpt::MockQemuPlatform> mock_qemu_platform;
EXPECT_CALL(mock_qemu_platform, get_ip_for(_)).WillOnce(Return(expected_ip));
mp::QemuVirtualMachine machine{default_description,
&mock_qemu_platform,
stub_monitor,
key_provider,
instance_dir.path()};
machine.start();
machine.state = mp::VirtualMachine::State::running;
EXPECT_EQ(machine.management_ipv4(), expected_ip);
}
TEST_F(QemuBackend, fails_to_get_management_ip_if_dnsmasq_does_not_return_an_ip)
{
NiceMock<mpt::MockQemuPlatform> mock_qemu_platform;
EXPECT_CALL(mock_qemu_platform, get_ip_for(_)).WillOnce(Return(std::nullopt));
mp::QemuVirtualMachine machine{default_description,
&mock_qemu_platform,
stub_monitor,
key_provider,
instance_dir.path()};
machine.start();
machine.state = mp::VirtualMachine::State::running;
EXPECT_EQ(machine.management_ipv4(), "UNKNOWN");
}
TEST_F(QemuBackend, ssh_hostname_timeout_throws_and_sets_unknown_state)
{
NiceMock<mpt::MockQemuPlatform> mock_qemu_platform;
ON_CALL(mock_qemu_platform, get_ip_for(_)).WillByDefault([](auto...) { return std::nullopt; });
mp::QemuVirtualMachine machine{default_description,
&mock_qemu_platform,
stub_monitor,
key_provider,
instance_dir.path()};
machine.start();
machine.state = mp::VirtualMachine::State::running;
EXPECT_THROW(machine.ssh_hostname(std::chrono::milliseconds(1)), std::runtime_error);
EXPECT_EQ(machine.state, mp::VirtualMachine::State::unknown);
}
TEST_F(QemuBackend, logsErrorOnFailureToConvertToQcow2V3UponConstruction)
{
NiceMock<mpt::MockQemuPlatform> mock_qemu_platform{};
process_factory->register_callback([this](mpt::MockProcess* process) {
if (process->program().contains("qemu-img") && process->arguments().contains("compat=1.1"))
{
mp::ProcessState exit_state{};
exit_state.exit_code = 1;
ON_CALL(*process, execute).WillByDefault(Return(exit_state));
}
else
return handle_external_process_calls(process);
});
logger_scope.mock_logger->screen_logs(mpl::Level::error);
logger_scope.mock_logger->expect_log(mpl::Level::error, "Failed to amend image to QCOW2 v3");
mp::QemuVirtualMachine machine{default_description,
&mock_qemu_platform,
stub_monitor,
key_provider,
instance_dir.path()};
}
struct MockQemuVM : public mpt::MockVirtualMachineT<mp::QemuVirtualMachine>
{
using mpt::MockVirtualMachineT<mp::QemuVirtualMachine>::MockVirtualMachineT;
using mp::QemuVirtualMachine::make_specific_snapshot;
using mp::QemuVirtualMachine::require_snapshots_support;
MOCK_METHOD(void, drop_ssh_session, (), (override));
};
TEST_F(QemuBackend, dropsSSHSessionWhenStopping)
{
NiceMock<MockQemuVM> machine{"mock-qemu-vm", key_provider};
machine.state = multipass::VirtualMachine::State::running;
EXPECT_CALL(machine, drop_ssh_session());
MP_DELEGATE_MOCK_CALLS_ON_BASE(machine, shutdown, mp::QemuVirtualMachine);
machine.shutdown(mp::VirtualMachine::ShutdownPolicy::Powerdown);
}
TEST_F(QemuBackend, supportsSnapshots)
{
MockQemuVM vm{"asdf", key_provider};
EXPECT_NO_THROW(vm.require_snapshots_support());
}
TEST_F(QemuBackend, createsQemuSnapshotsFromSpecs)
{
MockQemuVM machine{"mock-qemu-vm", key_provider};
auto snapshot_name = "elvis";
auto snapshot_comment = "has left the building";
auto instance_id = "vm1";
const mp::VMSpecs specs{2,
mp::MemorySize{"3.21G"},
mp::MemorySize{"4.32M"},
"00:00:00:00:00:00",
{{"eth18", "18:18:18:18:18:18", true}},
"asdf",
mp::VirtualMachine::State::stopped,
{},
false,
{}};
auto snapshot = machine.make_specific_snapshot(snapshot_name, snapshot_comment, instance_id, specs, nullptr);
EXPECT_EQ(snapshot->get_name(), snapshot_name);
EXPECT_EQ(snapshot->get_comment(), snapshot_comment);
EXPECT_EQ(snapshot->get_num_cores(), specs.num_cores);
EXPECT_EQ(snapshot->get_mem_size(), specs.mem_size);
EXPECT_EQ(snapshot->get_disk_space(), specs.disk_space);
EXPECT_EQ(snapshot->get_extra_interfaces(), specs.extra_interfaces);
EXPECT_EQ(snapshot->get_state(), specs.state);
EXPECT_EQ(snapshot->get_parent(), nullptr);
}
TEST_F(QemuBackend, createsQemuSnapshotsFromJsonFile)
{
MockQemuVM machine{"mock-qemu-vm", key_provider};
const auto parent = std::make_shared<mpt::MockSnapshot>();
EXPECT_CALL(machine, get_snapshot(2)).WillOnce(Return(parent));
const mpt::MockCloudInitFileOps::GuardedMock mock_cloud_init_file_ops_injection =
mpt::MockCloudInitFileOps::inject<NiceMock>();
EXPECT_CALL(*mock_cloud_init_file_ops_injection.first, get_instance_id_from_cloud_init(_)).Times(1);
auto snapshot = machine.make_specific_snapshot(mpt::test_data_path_for("test_snapshot.json"));
EXPECT_EQ(snapshot->get_name(), "snapshot3");
EXPECT_EQ(snapshot->get_comment(), "A comment");
EXPECT_EQ(snapshot->get_num_cores(), 1);
EXPECT_EQ(snapshot->get_mem_size(), mp::MemorySize{"1G"});
EXPECT_EQ(snapshot->get_disk_space(), mp::MemorySize{"5G"});
EXPECT_EQ(snapshot->get_extra_interfaces(), std::vector<mp::NetworkInterface>{});
EXPECT_EQ(snapshot->get_state(), mp::VirtualMachine::State::off);
EXPECT_EQ(snapshot->get_parent(), parent);
}
TEST_F(QemuBackend, networks_returns_supported_networks)
{
ON_CALL(*mock_qemu_platform, is_network_supported(_)).WillByDefault(Return(true));
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
const std::map<std::string, mp::NetworkInterfaceInfo> networks{
{"lxdbr0", {"lxdbr0", "bridge", "gobbledygook"}},
{"mpbr0", {"mpbr0", "bridge", "gobbledygook"}},
{"virbr0", {"virbr0", "bridge", "gobbledygook"}},
{"mpqemubr0", {"mpqemubr0", "bridge", "gobbledygook"}},
{"enxe4b97a832426", {"enxe4b97a832426", "ethernet", "gobbledygook"}}};
auto [mock_platform, guard] = mpt::MockPlatform::inject();
EXPECT_CALL(*mock_platform, get_network_interfaces_info).WillOnce(Return(networks));
auto supported_nets = backend.networks();
EXPECT_EQ(supported_nets.size(), networks.size());
}
TEST_F(QemuBackend, remove_resources_for_calls_qemu_platform)
{
bool remove_resources_called{false};
const std::string test_name{"foo"};
EXPECT_CALL(*mock_qemu_platform, remove_resources_for(_))
.WillOnce([&remove_resources_called, &test_name](auto& name) {
remove_resources_called = true;
EXPECT_EQ(name, test_name);
});
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
backend.remove_resources_for(test_name);
EXPECT_TRUE(remove_resources_called);
}
TEST_F(QemuBackend, hypervisor_health_check_calls_qemu_platform)
{
bool health_check_called{false};
EXPECT_CALL(*mock_qemu_platform, platform_health_check()).WillOnce([&health_check_called] {
health_check_called = true;
});
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
backend.hypervisor_health_check();
EXPECT_TRUE(health_check_called);
}
TEST_F(QemuBackend, get_backend_directory_name_calls_qemu_platform)
{
bool get_directory_name_called{false};
const QString backend_dir_name{"foo"};
EXPECT_CALL(*mock_qemu_platform, get_directory_name())
.Times(2)
.WillRepeatedly([&get_directory_name_called, &backend_dir_name] {
get_directory_name_called = true;
return backend_dir_name;
});
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mp::QemuVirtualMachineFactory backend{data_dir.path()};
const auto dir_name = backend.get_backend_directory_name();
EXPECT_EQ(dir_name, backend_dir_name);
EXPECT_TRUE(get_directory_name_called);
}
TEST_F(QemuBackend, addNetworkInterface)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
const auto [mock_cloud_init_file_ops, _] = mpt::MockCloudInitFileOps::inject();
EXPECT_CALL(*mock_cloud_init_file_ops, add_extra_interface_to_cloud_init).Times(1);
mp::QemuVirtualMachineFactory backend{data_dir.path()};
auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
EXPECT_NO_THROW(machine->add_network_interface(0, "", {"", "", true}));
}
TEST_F(QemuBackend, createBridgeWithChecksWithQemuPlatform)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
EXPECT_CALL(*mock_qemu_platform, needs_network_prep()).Times(1).WillRepeatedly(Return(true));
mp::QemuVirtualMachineFactory backend{data_dir.path()};
std::vector<mp::NetworkInterface> extra_interfaces{{"eth1", "52:54:00:00:00:00", true}};
EXPECT_NO_THROW(backend.prepare_networking(extra_interfaces));
}
TEST_F(QemuBackend, removeAllSnapshotsFromTheImage)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
// The sole reason to register this callback is to make the extract_snapshot_tags function get a non-empty snapshot
// list input, so we can cover the for loops
mpt::MockProcessFactory::Callback snapshot_list_callback = [](mpt::MockProcess* process) {
if (process->program().contains("qemu-img") && process->arguments().contains("snapshot") &&
process->arguments().contains("-l"))
{
constexpr auto snapshot_list_output_stream =
R"(Snapshot list:
ID TAG VM SIZE DATE VM CLOCK ICOUNT
2 @s2 0 B 2024-06-11 23:22:59 00:00:00.000 0
3 @s3 0 B 2024-06-12 12:30:37 00:00:00.000 0)";
EXPECT_CALL(*process, read_all_standard_output()).WillOnce(Return(QByteArray{snapshot_list_output_stream}));
}
};
process_factory->register_callback(snapshot_list_callback);
mpt::StubVMStatusMonitor stub_monitor;
mp::QemuVirtualMachineFactory backend{data_dir.path()};
const auto machine = backend.create_virtual_machine(default_description, key_provider, stub_monitor);
EXPECT_NO_THROW(machine->remove_snapshots_from_image());
const std::vector<mpt::MockProcessFactory::ProcessInfo> processes = process_factory->process_list();
EXPECT_GE(processes.size(), 2);
const auto lastProcessInfo = processes.back();
const auto last2ndProcessInfo = processes[processes.size() - 2];
EXPECT_TRUE(lastProcessInfo.command == "qemu-img" && lastProcessInfo.arguments.contains("-d") &&
lastProcessInfo.arguments.contains("@s3"));
EXPECT_TRUE(last2ndProcessInfo.command == "qemu-img" && last2ndProcessInfo.arguments.contains("-d") &&
last2ndProcessInfo.arguments.contains("@s2"));
}
TEST_F(QemuBackend, createVmAndCloneInstanceDirData)
{
EXPECT_CALL(*mock_qemu_platform_factory, make_qemu_platform(_)).WillOnce([this](auto...) {
return std::move(mock_qemu_platform);
});
mpt::StubVMStatusMonitor stub_monitor;
mp::QemuVirtualMachineFactory backend{data_dir.path()};
const mpt::MockCloudInitFileOps::GuardedMock mock_cloud_init_file_ops_injection =
mpt::MockCloudInitFileOps::inject<NiceMock>();
EXPECT_CALL(*mock_cloud_init_file_ops_injection.first, update_cloned_cloud_init_unique_identifiers(_, _, _, _))
.Times(1);
EXPECT_TRUE(backend.create_vm_and_clone_instance_dir_data({},
{},
"dummy_src_name",
"dummy_dest_name",
{},
key_provider,
stub_monitor));
}
TEST(QemuPlatform, base_qemu_platform_returns_expected_values)
{
mpt::MockQemuPlatform qemu_platform;
mp::VirtualMachineDescription vm_desc;
EXPECT_CALL(qemu_platform, vmstate_platform_args()).WillOnce([&qemu_platform] {
return qemu_platform.QemuPlatform::vmstate_platform_args();
});
EXPECT_CALL(qemu_platform, get_directory_name()).WillOnce([&qemu_platform] {
return qemu_platform.QemuPlatform::get_directory_name();
});
EXPECT_TRUE(qemu_platform.vmstate_platform_args().isEmpty());
EXPECT_TRUE(qemu_platform.get_directory_name().isEmpty());
}
| 51,333
|
C++
|
.cpp
| 982
| 43.304481
| 120
| 0.650887
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,661
|
test_qemu_vm_process_spec.cpp
|
canonical_multipass/tests/qemu/test_qemu_vm_process_spec.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/mock_environment_helpers.h"
#include <src/platform/backends/qemu/qemu_vm_process_spec.h>
#include <QDir>
#include <QString>
#include <QStringList>
#include <QTemporaryDir>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
struct TestQemuVMProcessSpec : public Test
{
const mp::VirtualMachineDescription desc{2 /*cores*/,
mp::MemorySize{"3G"} /*mem_size*/,
mp::MemorySize{"4G"} /*disk_space*/,
"vm_name",
"00:11:22:33:44:55",
{},
"ssh_username",
{"/path/to/image", "", "", "", "", {}}, // VMImage
mp::Path{"/path/to/cloud_init.iso"},
{},
{},
{},
{}};
const QStringList platform_args{{"--enable-kvm", "-nic", "tap,ifname=tap_device,script=no,downscript=no"}};
const std::unordered_map<std::string, std::pair<std::string, QStringList>> mount_args{
{"path/to/target",
{"path/to/source",
{"-virtfs", "local,security_model=passthrough,uid_map=1000:1000,gid_map=1000:1000,path=path/to/"
"target,mount_tag=m810e457178f448d9afffc9d950d726"}}}};
};
TEST_F(TestQemuVMProcessSpec, default_arguments_correct)
{
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, std::nullopt);
EXPECT_EQ(spec.arguments(), QStringList({"--enable-kvm",
"-nic",
"tap,ifname=tap_device,script=no,downscript=no",
"-device",
"virtio-scsi-pci,id=scsi0",
"-drive",
"file=/path/to/image,if=none,format=qcow2,discard=unmap,id=hda",
"-device",
"scsi-hd,drive=hda,bus=scsi0.0",
"-smp",
"2",
"-m",
"3072M",
"-qmp",
"stdio",
"-chardev",
"null,id=char0",
"-serial",
"chardev:char0",
"-nographic",
"-cdrom",
"/path/to/cloud_init.iso",
"-virtfs",
"local,security_model=passthrough,uid_map=1000:1000,gid_map=1000:1000,"
"path=path/to/target,mount_tag=m810e457178f448d9afffc9d950d726"}));
}
TEST_F(TestQemuVMProcessSpec, resume_arguments_taken_from_resumedata)
{
const mp::QemuVMProcessSpec::ResumeData resume_data{"suspend_tag", "machine_type", false, {"-one", "-two"}};
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, resume_data);
EXPECT_EQ(spec.arguments(), QStringList({"-one", "-two", "-loadvm", "suspend_tag", "-machine", "machine_type"})
<< mount_args.begin()->second.second);
}
TEST_F(TestQemuVMProcessSpec, resume_with_missing_machine_type_guesses_correctly)
{
mp::QemuVMProcessSpec::ResumeData resume_data_missing_machine_info;
resume_data_missing_machine_info.suspend_tag = "suspend_tag";
resume_data_missing_machine_info.arguments = QStringList{"-args"};
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, resume_data_missing_machine_info);
EXPECT_EQ(spec.arguments(), QStringList({"-args", "-loadvm", "suspend_tag"}) << mount_args.begin()->second.second);
}
TEST_F(TestQemuVMProcessSpec, ResumeFixesVmnetFormat)
{
const mp::QemuVMProcessSpec::ResumeData resume_data{
"suspend_tag", "machine_type", false, {"vmnet-macos,mode=shared,foo"}};
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, resume_data);
EXPECT_EQ(spec.arguments(), QStringList({"vmnet-shared,foo", "-loadvm", "suspend_tag", "-machine", "machine_type"})
<< mount_args.begin()->second.second);
}
TEST_F(TestQemuVMProcessSpec, apparmorProfileIncludesFileMountPerms)
{
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, std::nullopt);
EXPECT_TRUE(spec.apparmor_profile().contains("path/to/source/ rw"));
EXPECT_TRUE(spec.apparmor_profile().contains("path/to/source/** rwlk"));
}
TEST_F(TestQemuVMProcessSpec, apparmor_profile_has_correct_name)
{
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, std::nullopt);
EXPECT_TRUE(spec.apparmor_profile().contains("profile multipass.vm_name.qemu-system-"));
}
TEST_F(TestQemuVMProcessSpec, apparmor_profile_includes_disk_images)
{
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, std::nullopt);
EXPECT_TRUE(spec.apparmor_profile().contains("/path/to/image rwk,"));
EXPECT_TRUE(spec.apparmor_profile().contains("/path/to/cloud_init.iso rk,"));
}
TEST_F(TestQemuVMProcessSpec, apparmor_profile_identifier)
{
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, std::nullopt);
EXPECT_EQ(spec.identifier(), "vm_name");
}
TEST_F(TestQemuVMProcessSpec, apparmor_profile_running_as_snap_correct)
{
const QByteArray snap_name{"multipass"};
QTemporaryDir snap_dir;
mpt::SetEnvScope e("SNAP", snap_dir.path().toUtf8());
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, std::nullopt);
EXPECT_TRUE(spec.apparmor_profile().contains("signal (receive) peer=snap.multipass.multipassd"));
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1/qemu/* r,").arg(snap_dir.path())));
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1/usr/bin/qemu-system-").arg(snap_dir.path())));
}
TEST_F(TestQemuVMProcessSpec, apparmor_profile_running_as_symlinked_snap_correct)
{
const QByteArray snap_name{"multipass"};
QTemporaryDir snap_dir, link_dir;
link_dir.remove();
QFile::link(snap_dir.path(), link_dir.path());
mpt::SetEnvScope e("SNAP", link_dir.path().toUtf8());
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, std::nullopt);
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1/qemu/* r,").arg(snap_dir.path())));
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1/usr/bin/qemu-system-").arg(snap_dir.path())));
}
TEST_F(TestQemuVMProcessSpec, apparmor_profile_not_running_as_snap_correct)
{
const QByteArray snap_name{"multipass"};
mpt::UnsetEnvScope e("SNAP");
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, std::nullopt);
EXPECT_TRUE(spec.apparmor_profile().contains("signal (receive) peer=unconfined"));
EXPECT_TRUE(spec.apparmor_profile().contains("/usr{,/local}/share/{seabios,ovmf,qemu,qemu-efi}/* r,"));
EXPECT_TRUE(spec.apparmor_profile().contains(" /usr/bin/qemu-system-")); // space wanted
}
TEST_F(TestQemuVMProcessSpec, apparmor_profile_lets_bridge_helper_run_in_snap)
{
const QByteArray snap_name{"multipass"};
QTemporaryDir snap_dir;
mpt::SetEnvScope e("SNAP", snap_dir.path().toUtf8());
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, std::nullopt);
EXPECT_TRUE(spec.apparmor_profile().contains(QString(" %1/bin/bridge_helper").arg(snap_dir.path())));
}
TEST_F(TestQemuVMProcessSpec, apparmor_profile_lets_bridge_helper_run_outside_snap)
{
const QByteArray snap_name{"multipass"};
mpt::UnsetEnvScope e("SNAP");
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::QemuVMProcessSpec spec(desc, platform_args, mount_args, std::nullopt);
EXPECT_TRUE(spec.apparmor_profile().contains(" /bin/bridge_helper"));
}
| 9,228
|
C++
|
.cpp
| 172
| 40.744186
| 119
| 0.588398
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,662
|
test_qemu_img_utils.cpp
|
canonical_multipass/tests/qemu/test_qemu_img_utils.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/mock_process_factory.h"
#include <src/platform/backends/shared/qemu_img_utils/qemu_img_utils.h>
#include <multipass/constants.h>
#include <multipass/memory_size.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
const auto success = mp::ProcessState{0, std::nullopt};
const auto failure = mp::ProcessState{1, std::nullopt};
const auto crash = mp::ProcessState{std::nullopt, mp::ProcessState::Error{QProcess::Crashed, "core dumped"}};
const auto null_string_matcher = static_cast<std::optional<decltype(_)>>(std::nullopt);
using ImageConversionParamType =
std::tuple<const char*, const char*, mp::ProcessState, bool, mp::ProcessState, std::optional<Matcher<std::string>>>;
void simulate_qemuimg_info_with_json(const mpt::MockProcess* process, const QString& expect_img,
const mp::ProcessState& produce_result, const QByteArray& produce_output = {})
{
ASSERT_EQ(process->program().toStdString(), "qemu-img");
const auto args = process->arguments();
ASSERT_EQ(args.size(), 3);
EXPECT_EQ(args.at(0), "info");
EXPECT_EQ(args.at(1), "--output=json");
EXPECT_EQ(args.at(2), expect_img);
InSequence s;
EXPECT_CALL(*process, execute).WillOnce(Return(produce_result));
if (produce_result.completed_successfully())
EXPECT_CALL(*process, read_all_standard_output).WillOnce(Return(produce_output));
else if (produce_result.exit_code)
EXPECT_CALL(*process, read_all_standard_error).WillOnce(Return(produce_output));
else
ON_CALL(*process, read_all_standard_error).WillByDefault(Return(produce_output));
}
void simulate_qemuimg_resize(mpt::MockProcess* process, const QString& expect_img, const mp::MemorySize& expect_size,
const mp::ProcessState& produce_result)
{
ASSERT_EQ(process->program().toStdString(), "qemu-img");
const auto args = process->arguments();
ASSERT_EQ(args.size(), 3);
EXPECT_EQ(args.at(0).toStdString(), "resize");
EXPECT_EQ(args.at(1), expect_img);
EXPECT_THAT(args.at(2),
ResultOf([](const auto& val) { return mp::MemorySize{val.toStdString()}; }, Eq(expect_size)));
EXPECT_CALL(*process, execute(mp::image_resize_timeout)).Times(1).WillOnce(Return(produce_result));
}
void simulate_qemuimg_convert(const mpt::MockProcess* process, const QString& img_path,
const QString& expected_img_path, const mp::ProcessState& produce_result)
{
ASSERT_EQ(process->program().toStdString(), "qemu-img");
const auto args = process->arguments();
ASSERT_EQ(args.size(), 6);
EXPECT_EQ(args.at(0), "convert");
EXPECT_EQ(args.at(1), "-p");
EXPECT_EQ(args.at(2), "-O");
EXPECT_EQ(args.at(3), "qcow2");
EXPECT_EQ(args.at(4), img_path);
EXPECT_EQ(args.at(5), expected_img_path);
EXPECT_CALL(*process, execute).WillOnce(Return(produce_result));
}
template <class Matcher>
void test_image_resizing(const char* img, const mp::MemorySize& img_virtual_size, const mp::MemorySize& requested_size,
const mp::ProcessState& qemuimg_resize_result, std::optional<Matcher> throw_msg_matcher)
{
auto process_count = 0;
auto mock_factory_scope = mpt::MockProcessFactory::Inject();
mock_factory_scope->register_callback([&](mpt::MockProcess* process) {
ASSERT_LE(++process_count, 1);
simulate_qemuimg_resize(process, img, requested_size, qemuimg_resize_result);
});
if (throw_msg_matcher)
MP_EXPECT_THROW_THAT(mp::backend::resize_instance_image(requested_size, img), std::runtime_error,
mpt::match_what(*throw_msg_matcher));
else
mp::backend::resize_instance_image(requested_size, img);
EXPECT_EQ(process_count, 1);
}
template <class Matcher>
void test_image_conversion(const char* img_path, const char* expected_img_path, const char* qemuimg_info_output,
const mp::ProcessState& qemuimg_info_result, bool attempt_convert,
const mp::ProcessState& qemuimg_convert_result, std::optional<Matcher> throw_msg_matcher)
{
auto process_count = 0;
auto mock_factory_scope = mpt::MockProcessFactory::Inject();
const auto expected_final_process_count = attempt_convert ? 2 : 1;
mock_factory_scope->register_callback([&](mpt::MockProcess* process) {
ASSERT_LE(++process_count, expected_final_process_count);
if (process_count == 1)
{
auto msg = QByteArray{qemuimg_info_output};
simulate_qemuimg_info_with_json(process, img_path, qemuimg_info_result, msg);
}
else
{
simulate_qemuimg_convert(process, img_path, expected_img_path, qemuimg_convert_result);
}
});
if (throw_msg_matcher)
MP_EXPECT_THROW_THAT(mp::backend::convert_to_qcow_if_necessary(img_path), std::runtime_error,
mpt::match_what(*throw_msg_matcher));
else
EXPECT_THAT(mp::backend::convert_to_qcow_if_necessary(img_path), Eq(expected_img_path));
EXPECT_EQ(process_count, expected_final_process_count);
}
struct ImageConversionTestSuite : public TestWithParam<ImageConversionParamType>
{
};
const std::vector<ImageConversionParamType> image_conversion_inputs{
{"/fake/img/path", "{\n \"format\": \"qcow2\"\n}", success, false, mp::ProcessState{}, null_string_matcher},
{"/fake/img/path.qcow2", "{\n \"format\": \"raw\"\n}", success, true, success, null_string_matcher},
{"/fake/img/path.qcow2", "not found", failure, false, mp::ProcessState{},
std::make_optional(HasSubstr("not found"))},
{"/fake/img/path.qcow2", "{\n \"format\": \"raw\"\n}", success, true, failure,
std::make_optional(HasSubstr("qemu-img failed"))}};
} // namespace
TEST(QemuImgUtils, image_resizing_checks_minimum_size_and_proceeds_when_larger)
{
const auto img = "/fake/img/path";
const auto min_size = mp::MemorySize{"1G"};
const auto request_size = mp::MemorySize{"3G"};
const auto qemuimg_resize_result = success;
const auto throw_msg_matcher = null_string_matcher;
test_image_resizing(img, min_size, request_size, qemuimg_resize_result, throw_msg_matcher);
}
TEST(QemuImgUtils, image_resizing_checks_minimum_size_and_proceeds_when_equal)
{
const auto img = "/fake/img/path";
const auto min_size = mp::MemorySize{"1234554321"};
const auto request_size = min_size;
const auto qemuimg_resize_result = success;
const auto throw_msg_matcher = null_string_matcher;
test_image_resizing(img, min_size, request_size, qemuimg_resize_result, throw_msg_matcher);
}
TEST(QemuImgUtils, image_resize_detects_resizing_exit_failure_and_throws)
{
const auto img = "imagine";
const auto min_size = mp::MemorySize{"100M"};
const auto request_size = mp::MemorySize{"400M"};
const auto qemuimg_resize_result = failure;
const auto throw_msg_matcher = std::make_optional(HasSubstr("qemu-img failed"));
test_image_resizing(img, min_size, request_size, qemuimg_resize_result, throw_msg_matcher);
}
TEST(QemuImgUtils, image_resize_detects_resizing_crash_failure_and_throws)
{
const auto img = "ubuntu";
const auto min_size = mp::MemorySize{"100M"};
const auto request_size = mp::MemorySize{"400M"};
const auto qemuimg_resize_result = crash;
const auto throw_msg_matcher =
std::make_optional(AllOf(HasSubstr("qemu-img failed"), HasSubstr(crash.failure_message().toStdString())));
test_image_resizing(img, min_size, request_size, qemuimg_resize_result, throw_msg_matcher);
}
TEST_P(ImageConversionTestSuite, properly_handles_image_conversion)
{
const auto img_path = "/fake/img/path";
const auto& [expected_img_path, qemuimg_info_output, qemuimg_info_result, attempt_convert, qemuimg_convert_result,
throw_msg_matcher] = GetParam();
test_image_conversion(img_path, expected_img_path, qemuimg_info_output, qemuimg_info_result, attempt_convert,
qemuimg_convert_result, throw_msg_matcher);
}
INSTANTIATE_TEST_SUITE_P(QemuImgUtils, ImageConversionTestSuite, ValuesIn(image_conversion_inputs));
| 8,899
|
C++
|
.cpp
| 177
| 44.581921
| 120
| 0.695507
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,663
|
test_qemu_vmstate_process_spec.cpp
|
canonical_multipass/tests/qemu/test_qemu_vmstate_process_spec.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/mock_environment_helpers.h"
#include <src/platform/backends/qemu/qemu_vmstate_process_spec.h>
#include <QStringList>
namespace mp = multipass;
using namespace testing;
struct TestQemuVmStateProcessSpec : public Test
{
QString file_name{"foo"};
};
TEST_F(TestQemuVmStateProcessSpec, default_arguments_correct)
{
mp::QemuVmStateProcessSpec spec{file_name};
EXPECT_EQ(spec.arguments(), QStringList({"-nographic", "-dump-vmstate", file_name}));
}
| 1,132
|
C++
|
.cpp
| 31
| 34.419355
| 89
| 0.765082
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,664
|
test_qemu_mount_handler.cpp
|
canonical_multipass/tests/qemu/test_qemu_mount_handler.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/mock_file_ops.h"
#include "tests/mock_logger.h"
#include "tests/mock_server_reader_writer.h"
#include "tests/mock_ssh_process_exit_status.h"
#include "tests/mock_ssh_test_fixture.h"
#include "tests/mock_virtual_machine.h"
#include "tests/stub_ssh_key_provider.h"
#include "qemu_mount_handler.h"
#include <multipass/utils.h>
#include <multipass/vm_mount.h>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct MockQemuVirtualMachine : mpt::MockVirtualMachineT<mp::QemuVirtualMachine>
{
explicit MockQemuVirtualMachine(const std::string& name)
: mpt::MockVirtualMachineT<mp::QemuVirtualMachine>{name, mpt::StubSSHKeyProvider{}}
{
}
MOCK_METHOD(mp::QemuVirtualMachine::MountArgs&, modifiable_mount_args, (), (override));
};
struct CommandOutput
{
CommandOutput(const std::string& output, int exit_code = 0) : output{output}, exit_code{exit_code}
{
}
std::string output;
int exit_code;
};
typedef std::unordered_map<std::string, CommandOutput> CommandOutputs;
std::string command_get_existing_parent(const std::string& path)
{
return fmt::format(R"(sudo /bin/bash -c 'P="{}"; while [ ! -d "$P/" ]; do P="${{P%/*}}"; done; echo $P/')", path);
}
std::string tag_from_target(const std::string& target)
{
return mp::utils::make_uuid(target).remove("-").left(30).prepend('m').toStdString();
}
std::string command_mount(const std::string& target)
{
return fmt::format("sudo mount -t 9p {} {} -o trans=virtio,version=9p2000.L,msize=536870912",
tag_from_target(target), target);
}
std::string command_umount(const std::string& target)
{
return fmt::format("if mountpoint -q {0}; then sudo umount {0}; else true; fi", target);
}
std::string command_mkdir(const std::string& parent, const std::string& missing)
{
return fmt::format("sudo /bin/bash -c 'cd \"{}\" && mkdir -p \"{}\"'", parent, missing);
}
std::string command_chown(const std::string& parent, const std::string& missing, int uid, int gid)
{
return fmt::format("sudo /bin/bash -c 'cd \"{}\" && chown -R {}:{} \"{}\"'", parent, uid, gid,
missing.substr(0, missing.find_first_of('/')));
}
std::string command_findmnt(const std::string& target)
{
return fmt::format("findmnt --type 9p | grep '{} {}'", target, tag_from_target(target));
}
struct QemuMountHandlerTest : public ::Test
{
QemuMountHandlerTest()
{
EXPECT_CALL(mock_file_ops, status)
.WillOnce(Return(mp::fs::file_status{mp::fs::file_type::directory, mp::fs::perms::all}));
EXPECT_CALL(vm, modifiable_mount_args).WillOnce(ReturnRef(mount_args));
}
// the returned lambda will modify `output` so that it can be used to mock ssh_channel_read_timeout
auto mocked_ssh_channel_request_exec(std::string& output)
{
return [&](ssh_channel, const char* command) {
if (const auto it = command_outputs.find(command); it != command_outputs.end())
{
output = it->second.output;
exit_status_mock.set_exit_status(it->second.exit_code);
}
else
{
ADD_FAILURE() << "unexpected command: " << command;
}
return SSH_OK;
};
}
static auto mocked_ssh_channel_read_timeout(const std::string& output)
{
return [&, copied = 0u](auto, void* dest, uint32_t count, auto...) mutable {
auto n = std::min(static_cast<std::string::size_type>(count), output.size() - copied);
std::copy_n(output.begin() + copied, n, static_cast<char*>(dest));
n ? copied += n : copied = 0;
return n;
};
}
mpt::StubSSHKeyProvider key_provider;
std::string default_source{"source"}, default_target{"target"};
mpt::MockFileOps::GuardedMock mock_file_ops_injection = mpt::MockFileOps::inject();
mpt::MockFileOps& mock_file_ops = *mock_file_ops_injection.first;
mp::id_mappings gid_mappings{{1, 2}}, uid_mappings{{5, 6}};
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject(mpl::Level::debug);
mpt::MockServerReaderWriter<mp::MountReply, mp::MountRequest> server;
mpt::MockSSHTestFixture mock_ssh_test_fixture;
mpt::ExitStatusMock exit_status_mock;
NiceMock<MockQemuVirtualMachine> vm{"my_instance"};
mp::QemuVirtualMachine::MountArgs mount_args;
mp::VMMount mount{default_source, gid_mappings, uid_mappings, mp::VMMount::MountType::Native};
CommandOutputs command_outputs{
{"echo $PWD/target", {"/home/ubuntu/target"}},
{command_get_existing_parent("/home/ubuntu/target"), {"/home/ubuntu/target"}},
{"id -u", {"1000"}},
{"id -g", {"1000"}},
{command_mount(default_target), {""}},
{command_umount(default_target), {""}},
{command_findmnt(default_target), {""}},
};
};
struct QemuMountHandlerFailCommand : public QemuMountHandlerTest, public testing::WithParamInterface<std::string>
{
const std::string parent = "/home/ubuntu";
const std::string missing = "target";
QemuMountHandlerFailCommand()
{
command_outputs.at(command_get_existing_parent("/home/ubuntu/target")) = parent;
command_outputs.insert({command_mkdir(parent, missing), {""}});
command_outputs.insert({command_chown(parent, missing, 1000, 1000), {""}});
}
};
} // namespace
TEST_F(QemuMountHandlerTest, mount_fails_when_vm_not_stopped)
{
EXPECT_CALL(vm, current_state()).WillOnce(Return(mp::VirtualMachine::State::running));
MP_EXPECT_THROW_THAT(
mp::QemuMountHandler(&vm, &key_provider, default_target, mount), mp::NativeMountNeedsStoppedVMException,
mpt::match_what(AllOf(HasSubstr("Please stop the instance"), HasSubstr("before attempting native mounts."))));
}
TEST_F(QemuMountHandlerTest, mount_fails_on_multiple_id_mappings)
{
const mp::VMMount mount{default_source, {{1, 2}, {3, 4}}, {{5, -1}, {6, 10}}, mp::VMMount::MountType::Native};
MP_EXPECT_THROW_THAT(mp::QemuMountHandler(&vm, &key_provider, default_target, mount), std::runtime_error,
mpt::match_what(StrEq("Only one mapping per native mount allowed.")));
}
TEST_F(QemuMountHandlerTest, mount_handles_mount_args)
{
{
mp::MountHandler::UPtr mount_handler;
EXPECT_NO_THROW(mount_handler =
std::make_unique<mp::QemuMountHandler>(&vm, &key_provider, default_target, mount));
EXPECT_EQ(mount_args.size(), 1);
const auto uid_arg = QString("uid_map=%1:%2,").arg(uid_mappings.front().first).arg(uid_mappings.front().second);
const auto gid_arg = QString{"gid_map=%1:%2,"}.arg(gid_mappings.front().first).arg(gid_mappings.front().second);
EXPECT_EQ(mount_args.begin()->second.second.join(' ').toStdString(),
fmt::format("-virtfs local,security_model=passthrough,{}{}path={},mount_tag={}",
uid_arg,
gid_arg,
mount.get_source_path(),
tag_from_target(default_target)));
}
EXPECT_EQ(mount_args.size(), 0);
}
TEST_F(QemuMountHandlerTest, mount_logs_init)
{
logger_scope.mock_logger->expect_log(
mpl::Level::info,
fmt::format("initializing native mount {} => {} in '{}'", mount.get_source_path(), default_target, vm.vm_name));
EXPECT_NO_THROW(mp::QemuMountHandler(&vm, &key_provider, default_target, mount));
}
TEST_F(QemuMountHandlerTest, recover_from_suspended)
{
mount_args[tag_from_target(default_target)] = {};
EXPECT_CALL(vm, current_state()).WillOnce(Return(mp::VirtualMachine::State::suspended));
logger_scope.mock_logger->expect_log(mpl::Level::info,
fmt::format("Found native mount {} => {} in '{}' while suspended",
mount.get_source_path(),
default_target,
vm.vm_name));
EXPECT_NO_THROW(mp::QemuMountHandler(&vm, &key_provider, default_target, mount));
}
TEST_F(QemuMountHandlerTest, start_success_stop_success)
{
std::string ssh_command_output;
REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output));
REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output));
mp::QemuMountHandler handler{&vm, &key_provider, default_target, mount};
EXPECT_NO_THROW(handler.activate(&server));
EXPECT_NO_THROW(handler.deactivate());
}
TEST_F(QemuMountHandlerTest, stop_fail_nonforce_throws)
{
auto error = "device is busy";
command_outputs.at(command_umount(default_target)) = {error, 1};
std::string ssh_command_output;
REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output));
REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output));
mp::QemuMountHandler handler{&vm, &key_provider, default_target, mount};
EXPECT_NO_THROW(handler.activate(&server));
MP_EXPECT_THROW_THAT(handler.deactivate(), std::runtime_error, mpt::match_what(StrEq(error)));
}
TEST_F(QemuMountHandlerTest, stop_fail_force_logs)
{
auto error = "device is busy";
command_outputs.at(command_umount(default_target)) = {error, 1};
std::string ssh_command_output;
REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output));
REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output));
mp::QemuMountHandler handler{&vm, &key_provider, default_target, mount};
EXPECT_NO_THROW(handler.activate(&server));
EXPECT_CALL(*logger_scope.mock_logger, log).WillRepeatedly(Return());
logger_scope.mock_logger->expect_log(
mpl::Level::warning,
fmt::format("Failed to gracefully stop mount \"{}\" in instance '{}': {}", default_target, vm.vm_name, error));
}
TEST_F(QemuMountHandlerTest, target_directory_missing)
{
const std::string parent = "/home/ubuntu";
const std::string missing = "target";
command_outputs.at(command_get_existing_parent("/home/ubuntu/target")) = parent;
command_outputs.insert({command_mkdir(parent, missing), {""}});
command_outputs.insert({command_chown(parent, missing, 1000, 1000), {""}});
std::string ssh_command_output;
REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output));
REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output));
mp::QemuMountHandler handler{&vm, &key_provider, default_target, mount};
EXPECT_NO_THROW(handler.activate(&server));
}
INSTANTIATE_TEST_SUITE_P(QemuMountHandlerFailCommand, QemuMountHandlerFailCommand,
testing::Values(command_mkdir("/home/ubuntu", "target"),
command_chown("/home/ubuntu", "target", 1000, 1000), "id -u", "id -g",
command_mount("target"), command_get_existing_parent("/home/ubuntu/target")));
TEST_P(QemuMountHandlerFailCommand, throw_on_fail)
{
const auto cmd = GetParam();
const auto error = "failed: " + cmd;
command_outputs.at(cmd) = {error, 1};
std::string ssh_command_output;
REPLACE(ssh_channel_request_exec, mocked_ssh_channel_request_exec(ssh_command_output));
REPLACE(ssh_channel_read_timeout, mocked_ssh_channel_read_timeout(ssh_command_output));
mp::QemuMountHandler handler{&vm, &key_provider, default_target, mount};
MP_EXPECT_THROW_THAT(handler.activate(&server), std::runtime_error, mpt::match_what(StrEq(error)));
}
| 12,402
|
C++
|
.cpp
| 257
| 41.715953
| 120
| 0.664876
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,665
|
test_qemu_snapshot.cpp
|
canonical_multipass/tests/qemu/test_qemu_snapshot.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/mock_cloud_init_file_ops.h"
#include "tests/mock_logger.h"
#include "tests/mock_process_factory.h"
#include "tests/mock_snapshot.h"
#include "tests/mock_virtual_machine.h"
#include "tests/path.h"
#include "tests/stub_ssh_key_provider.h"
#include <multipass/process/process.h>
#include <multipass/virtual_machine_description.h>
#include <multipass/vm_specs.h>
#include <src/platform/backends/qemu/qemu_snapshot.h>
#include <QJsonArray>
#include <QJsonObject>
#include <memory>
#include <unordered_map>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct PublicQemuSnapshot : public mp::QemuSnapshot
{
// clang-format off
// (keeping original declaration order)
using mp::QemuSnapshot::QemuSnapshot;
using mp::QemuSnapshot::capture_impl;
using mp::QemuSnapshot::erase_impl;
using mp::QemuSnapshot::apply_impl;
// clang-format on
};
struct TestQemuSnapshot : public Test
{
using ArgsMatcher = Matcher<QStringList>;
mp::QemuSnapshot quick_snapshot(const std::string& name = "asdf")
{
return mp::QemuSnapshot{name, "", "", nullptr, specs, vm, desc};
}
mp::QemuSnapshot loaded_snapshot()
{
return mp::QemuSnapshot{mpt::test_data_path_for("test_snapshot.json"), vm, desc};
}
template <typename T>
static std::string derive_tag(T&& index)
{
return fmt::format("@s{}", std::forward<T>(index));
}
static void set_common_expectations_on(mpt::MockProcess* process)
{
EXPECT_EQ(process->program(), "qemu-img");
EXPECT_CALL(*process, execute).WillOnce(Return(success));
}
static void set_tag_output(mpt::MockProcess* process, std::string tag)
{
EXPECT_CALL(*process, read_all_standard_output).WillOnce(Return(QByteArray::fromStdString(tag + ' ')));
}
mp::VirtualMachineDescription desc = [] {
mp::VirtualMachineDescription ret{};
ret.image.image_path = "raniunotuiroleh";
return ret;
}();
mpt::StubSSHKeyProvider key_provider{};
NiceMock<mpt::MockVirtualMachineT<mp::QemuVirtualMachine>> vm{"qemu-vm", key_provider};
ArgsMatcher list_args_matcher = ElementsAre("snapshot", "-l", desc.image.image_path);
const mpt::MockCloudInitFileOps::GuardedMock mock_cloud_init_file_ops_injection =
mpt::MockCloudInitFileOps::inject<NiceMock>();
inline static const auto success = mp::ProcessState{0, std::nullopt};
inline static const auto failure = mp::ProcessState{1, std::nullopt};
inline static const auto specs = [] {
const auto cpus = 3;
const auto mem_size = mp::MemorySize{"1.23G"};
const auto disk_space = mp::MemorySize{"3.21M"};
const std::vector<mp::NetworkInterface> extra_interfaces{{"eth15", "15:15:15:15:15:15", false}};
const auto state = mp::VirtualMachine::State::off;
const auto mounts =
std::unordered_map<std::string, mp::VMMount>{{"asdf", {"fdsa", {}, {}, mp::VMMount::MountType::Classic}}};
const auto metadata = [] {
auto metadata = QJsonObject{};
metadata["meta"] = "data";
return metadata;
}();
return mp::VMSpecs{cpus, mem_size, disk_space, "mac", extra_interfaces, "", state, mounts, false, metadata};
}();
};
TEST_F(TestQemuSnapshot, initializesBaseProperties)
{
const auto name = "name";
const auto comment = "comment";
const auto instance_id = "vm2";
const auto parent = std::make_shared<mpt::MockSnapshot>();
auto desc = mp::VirtualMachineDescription{};
auto vm = NiceMock<mpt::MockVirtualMachineT<mp::QemuVirtualMachine>>{"qemu-vm", key_provider};
const auto snapshot = mp::QemuSnapshot{name, comment, instance_id, parent, specs, vm, desc};
EXPECT_EQ(snapshot.get_name(), name);
EXPECT_EQ(snapshot.get_comment(), comment);
EXPECT_EQ(snapshot.get_parent(), parent);
EXPECT_EQ(snapshot.get_num_cores(), specs.num_cores);
EXPECT_EQ(snapshot.get_mem_size(), specs.mem_size);
EXPECT_EQ(snapshot.get_disk_space(), specs.disk_space);
EXPECT_EQ(snapshot.get_extra_interfaces(), specs.extra_interfaces);
EXPECT_EQ(snapshot.get_state(), specs.state);
EXPECT_EQ(snapshot.get_mounts(), specs.mounts);
EXPECT_EQ(snapshot.get_metadata(), specs.metadata);
}
TEST_F(TestQemuSnapshot, initializesBasePropertiesFromJson)
{
const auto parent = std::make_shared<mpt::MockSnapshot>();
EXPECT_CALL(vm, get_snapshot(2)).WillOnce(Return(parent));
const mp::QemuSnapshot snapshot{mpt::test_data_path_for("test_snapshot.json"), vm, desc};
EXPECT_EQ(snapshot.get_name(), "snapshot3");
EXPECT_EQ(snapshot.get_comment(), "A comment");
EXPECT_EQ(snapshot.get_parent(), parent);
EXPECT_EQ(snapshot.get_num_cores(), 1);
EXPECT_EQ(snapshot.get_mem_size(), mp::MemorySize{"1G"});
EXPECT_EQ(snapshot.get_disk_space(), mp::MemorySize{"5G"});
EXPECT_EQ(snapshot.get_extra_interfaces(), std::vector<mp::NetworkInterface>{});
EXPECT_EQ(snapshot.get_state(), mp::VirtualMachine::State::off);
auto mount_matcher1 =
Pair(Eq("guybrush"), Property(&mp::VMMount::get_mount_type, Eq(mp::VMMount::MountType::Classic)));
auto mount_matcher2 =
Pair(Eq("murray"), Property(&mp::VMMount::get_mount_type, Eq(mp::VMMount::MountType::Native)));
EXPECT_THAT(snapshot.get_mounts(), UnorderedElementsAre(mount_matcher1, mount_matcher2));
EXPECT_THAT(
snapshot.get_metadata(),
ResultOf([](const QJsonObject& metadata) { return metadata["arguments"].toArray(); }, Contains("-qmp")));
}
TEST_F(TestQemuSnapshot, capturesSnapshot)
{
auto snapshot_index = 3;
auto snapshot_tag = derive_tag(snapshot_index);
EXPECT_CALL(vm, get_snapshot_count).WillOnce(Return(snapshot_index - 1));
auto proc_count = 0;
ArgsMatcher capture_args_matcher{
ElementsAre("snapshot", "-c", QString::fromStdString(snapshot_tag), desc.image.image_path)};
auto mock_factory_scope = mpt::MockProcessFactory::Inject();
mock_factory_scope->register_callback([&](mpt::MockProcess* process) {
ASSERT_LE(++proc_count, 2);
set_common_expectations_on(process);
const auto& args_matcher = proc_count == 1 ? list_args_matcher : capture_args_matcher;
EXPECT_THAT(process->arguments(), args_matcher);
});
quick_snapshot().capture();
EXPECT_EQ(proc_count, 2);
}
TEST_F(TestQemuSnapshot, captureThrowsOnRepeatedTag)
{
auto snapshot_index = 22;
auto snapshot_tag = derive_tag(snapshot_index);
EXPECT_CALL(vm, get_snapshot_count).WillOnce(Return(snapshot_index - 1));
auto proc_count = 0;
auto mock_factory_scope = mpt::MockProcessFactory::Inject();
mock_factory_scope->register_callback([&](mpt::MockProcess* process) {
ASSERT_EQ(++proc_count, 1);
set_common_expectations_on(process);
EXPECT_THAT(process->arguments(), list_args_matcher);
set_tag_output(process, snapshot_tag);
});
MP_EXPECT_THROW_THAT(quick_snapshot("whatever").capture(),
std::runtime_error,
mpt::match_what(AllOf(HasSubstr("already exists"),
HasSubstr(snapshot_tag),
HasSubstr(desc.image.image_path.toStdString()))));
}
TEST_F(TestQemuSnapshot, erasesSnapshot)
{
auto snapshot = loaded_snapshot();
auto proc_count = 0;
auto mock_factory_scope = mpt::MockProcessFactory::Inject();
mock_factory_scope->register_callback([&](mpt::MockProcess* process) {
ASSERT_LE(++proc_count, 2);
set_common_expectations_on(process);
auto tag = derive_tag(snapshot.get_index());
if (proc_count == 1)
{
EXPECT_THAT(process->arguments(), list_args_matcher);
set_tag_output(process, tag);
}
else
{
EXPECT_THAT(process->arguments(),
ElementsAre("snapshot", "-d", QString::fromStdString(tag), desc.image.image_path));
}
});
snapshot.erase();
EXPECT_EQ(proc_count, 2);
}
TEST_F(TestQemuSnapshot, eraseLogsOnMissingTag)
{
auto snapshot = loaded_snapshot();
auto proc_count = 0;
auto mock_factory_scope = mpt::MockProcessFactory::Inject();
mock_factory_scope->register_callback([&](mpt::MockProcess* process) {
ASSERT_EQ(++proc_count, 1);
set_common_expectations_on(process);
EXPECT_THAT(process->arguments(), list_args_matcher);
set_tag_output(process, "some-tag-other-than-the-one-we-are-looking-for");
});
auto expected_log_level = mpl::Level::warning;
auto logger_scope = mpt::MockLogger::inject(expected_log_level);
logger_scope.mock_logger->expect_log(expected_log_level, "Could not find");
snapshot.erase();
}
TEST_F(TestQemuSnapshot, appliesSnapshot)
{
auto snapshot = loaded_snapshot();
auto proc_count = 0;
auto mock_factory_scope = mpt::MockProcessFactory::Inject();
mock_factory_scope->register_callback([&](mpt::MockProcess* process) {
ASSERT_EQ(++proc_count, 1);
set_common_expectations_on(process);
EXPECT_THAT(process->arguments(),
ElementsAre("snapshot",
"-a",
QString::fromStdString(derive_tag(snapshot.get_index())),
desc.image.image_path));
});
desc.num_cores = 8598;
desc.mem_size = mp::MemorySize{"49"};
desc.disk_space = mp::MemorySize{"328"};
desc.extra_interfaces = std::vector<mp::NetworkInterface>{{"eth16", "16:16:16:16:16:16", true}};
snapshot.apply();
EXPECT_EQ(desc.num_cores, snapshot.get_num_cores());
EXPECT_EQ(desc.mem_size, snapshot.get_mem_size());
EXPECT_EQ(desc.disk_space, snapshot.get_disk_space());
EXPECT_EQ(desc.extra_interfaces, snapshot.get_extra_interfaces());
}
TEST_F(TestQemuSnapshot, keepsDescOnFailure)
{
auto snapshot = loaded_snapshot();
auto proc_count = 0;
auto mock_factory_scope = mpt::MockProcessFactory::Inject();
mock_factory_scope->register_callback([&](mpt::MockProcess* process) {
ASSERT_EQ(++proc_count, 1);
EXPECT_CALL(*process, execute).WillOnce(Return(failure));
});
desc.num_cores = 123;
desc.mem_size = mp::MemorySize{"321"};
desc.disk_space = mp::MemorySize{"56K"};
desc.extra_interfaces = std::vector<mp::NetworkInterface>{{"eth17", "17:17:17:17:17:17", true}};
const auto orig_desc = desc;
MP_EXPECT_THROW_THAT(snapshot.apply(), std::runtime_error, mpt::match_what(HasSubstr("qemu-img failed")));
EXPECT_EQ(orig_desc.num_cores, desc.num_cores);
EXPECT_EQ(orig_desc.mem_size, desc.mem_size);
EXPECT_EQ(orig_desc.disk_space, desc.disk_space);
EXPECT_EQ(orig_desc.extra_interfaces, desc.extra_interfaces);
}
} // namespace
| 11,604
|
C++
|
.cpp
| 263
| 37.958175
| 118
| 0.671512
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,666
|
test_dnsmasq_server.cpp
|
canonical_multipass/tests/qemu/linux/test_dnsmasq_server.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/file_operations.h"
#include "tests/mock_environment_helpers.h"
#include "tests/mock_logger.h"
#include "tests/mock_process_factory.h"
#include "tests/reset_process_factory.h"
#include "tests/temp_dir.h"
#include "tests/test_with_mocked_bin_path.h"
#include <src/platform/backends/qemu/linux/dnsmasq_process_spec.h>
#include <src/platform/backends/qemu/linux/dnsmasq_server.h>
#include <multipass/logging/log.h>
#include <multipass/logging/logger.h>
#include <QDir>
#include <memory>
#include <stdexcept>
#include <string>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
using namespace std::string_literals;
namespace
{
struct CapturingLogger : public mp::logging::Logger
{
void log(mpl::Level level, mpl::CString category, mpl::CString message) const override
{
logged_lines.push_back(message.c_str());
}
mutable std::vector<std::string> logged_lines;
};
struct DNSMasqServer : public mpt::TestWithMockedBinPath
{
DNSMasqServer()
{
mpl::set_logger(logger);
}
~DNSMasqServer()
{
mpl::set_logger(nullptr);
}
void make_lease_entry(const std::string& expected_hw_addr)
{
mpt::make_file_with_content(
QDir{data_dir.path()}.filePath("dnsmasq.leases"),
fmt::format("0 {} {} dummy_name 00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12", expected_hw_addr,
expected_ip));
}
void make_lease_entry()
{
make_lease_entry(hw_addr);
}
mpt::SetEnvScope env_scope{"DISABLE_APPARMOR", "1"};
mpt::ResetProcessFactory scope; // will otherwise pollute other tests
mpt::TempDir data_dir;
std::shared_ptr<CapturingLogger> logger = std::make_shared<CapturingLogger>();
const QString bridge_name{"dummy-bridge"};
const std::string subnet{"192.168.64"};
const std::string error_subnet{"0.0.0"}; // This forces the mock dnsmasq process to exit with error
const std::string hw_addr{"00:01:02:03:04:05"};
const std::string expected_ip{"10.177.224.22"};
const std::string lease_entry =
"0 "s + hw_addr + " "s + expected_ip + " dummy_name 00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12";
mp::DNSMasqServer make_default_dnsmasq_server()
{
return mp::DNSMasqServer{data_dir.path(), bridge_name, subnet};
}
};
TEST_F(DNSMasqServer, starts_dnsmasq_process)
{
EXPECT_NO_THROW(mp::DNSMasqServer dns(data_dir.path(), bridge_name, subnet));
}
TEST_F(DNSMasqServer, finds_ip)
{
auto dns = make_default_dnsmasq_server();
make_lease_entry();
auto ip = dns.get_ip_for(hw_addr);
ASSERT_TRUE(ip);
EXPECT_EQ(ip.value(), mp::IPAddress(expected_ip));
}
TEST_F(DNSMasqServer, returns_null_ip_when_leases_file_does_not_exist)
{
auto dns = make_default_dnsmasq_server();
const std::string hw_addr{"00:01:02:03:04:05"};
auto ip = dns.get_ip_for(hw_addr);
EXPECT_FALSE(ip);
}
TEST_F(DNSMasqServer, release_mac_releases_ip)
{
const QString dhcp_release_called{QDir{data_dir.path()}.filePath("dhcp_release_called")};
mp::DNSMasqServer dns{data_dir.path(), dhcp_release_called, subnet};
make_lease_entry();
dns.release_mac(hw_addr);
EXPECT_TRUE(QFile::exists(dhcp_release_called));
}
TEST_F(DNSMasqServer, release_mac_logs_failure_on_missing_ip)
{
const QString dhcp_release_called{QDir{data_dir.path()}.filePath("dhcp_release_called")};
mp::DNSMasqServer dns{data_dir.path(), dhcp_release_called, subnet};
dns.release_mac(hw_addr);
EXPECT_FALSE(QFile::exists(dhcp_release_called));
EXPECT_TRUE(logger->logged_lines.size() > 0);
}
TEST_F(DNSMasqServer, release_mac_logs_failures)
{
const QString dhcp_release_called{QDir{data_dir.path()}.filePath("dhcp_release_called.fail")};
mp::DNSMasqServer dns{data_dir.path(), dhcp_release_called, subnet};
make_lease_entry();
dns.release_mac(hw_addr);
EXPECT_TRUE(QFile::exists(dhcp_release_called));
EXPECT_TRUE(logger->logged_lines.size() > 0);
}
TEST_F(DNSMasqServer, release_mac_crashes_logs_failure)
{
const QString dhcp_release_called{QDir{data_dir.path()}.filePath("dhcp_release_called")};
const std::string crash_hw_addr{"00:00:00:00:00:00"};
mp::DNSMasqServer dns{data_dir.path(), dhcp_release_called, subnet};
make_lease_entry(crash_hw_addr);
dns.release_mac(crash_hw_addr);
EXPECT_THAT(logger->logged_lines,
Contains(fmt::format("failed to release ip addr {} with mac {}: Crashed", expected_ip, crash_hw_addr)));
}
TEST_F(DNSMasqServer, dnsmasq_starts_and_does_not_throw)
{
auto dns = make_default_dnsmasq_server();
EXPECT_NO_THROW(dns.check_dnsmasq_running());
}
TEST_F(DNSMasqServer, dnsmasq_fails_and_throws)
{
EXPECT_THROW((mp::DNSMasqServer{data_dir.path(), bridge_name, error_subnet}), std::runtime_error);
}
TEST_F(DNSMasqServer, dnsmasq_creates_conf_file)
{
auto dns = make_default_dnsmasq_server();
EXPECT_FALSE(QDir(data_dir.path()).entryList({"dnsmasq-??????.conf"}, QDir::Files).isEmpty());
}
TEST_F(DNSMasqServer, dnsmasq_creates_empty_dnsmasq_hosts_file)
{
const QString dnsmasq_hosts{QDir{data_dir.path()}.filePath("dnsmasq.hosts")};
auto dns = make_default_dnsmasq_server();
EXPECT_TRUE(QFile::exists(dnsmasq_hosts));
}
struct DNSMasqServerMockedProcess : public DNSMasqServer
{
void SetUp() override
{
logger_scope.mock_logger->screen_logs(mpl::Level::warning); // warning and above expected explicitly in tests
}
void TearDown() override
{
ASSERT_TRUE(forked);
}
void setup(const mpt::MockProcessFactory::Callback& callback = {})
{
factory_scope->register_callback([this, callback](mpt::MockProcess* process) {
setup_process(process);
if (callback)
callback(process);
});
}
void setup_process(mpt::MockProcess* process)
{
ASSERT_EQ(process->program(), exe);
forked = true;
}
void setup_successful_start(mpt::MockProcess* process)
{
EXPECT_CALL(*process, start()).Times(1);
EXPECT_CALL(*process, wait_for_started(_)).WillOnce(Return(true));
EXPECT_CALL(*process, wait_for_finished(_)).WillOnce(Return(false));
}
void setup_successful_finish(mpt::MockProcess* process)
{
EXPECT_CALL(*process, running()).WillOnce(Return(true));
EXPECT_CALL(*process, terminate()).Times(1);
EXPECT_CALL(*process, wait_for_finished(_)).WillOnce(Return(true));
}
bool forked = false;
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
std::unique_ptr<mpt::MockProcessFactory::Scope> factory_scope = mpt::MockProcessFactory::Inject();
inline static const auto exe = mp::DNSMasqProcessSpec{{}, {}, {}, {}}.program();
};
TEST_F(DNSMasqServerMockedProcess, dnsmasq_check_skips_start_if_already_running)
{
setup([this](auto* process) {
InSequence seq;
setup_successful_start(process);
EXPECT_CALL(*process, running()).WillOnce(Return(true));
setup_successful_finish(process);
});
auto dns = make_default_dnsmasq_server();
dns.check_dnsmasq_running();
}
TEST_F(DNSMasqServerMockedProcess, dnsmasq_check_warns_and_starts_if_not_running)
{
logger_scope.mock_logger->expect_log(mpl::Level::warning, "Not running");
setup([this](auto* process) {
InSequence seq;
setup_successful_start(process);
EXPECT_CALL(*process, running()).WillOnce(Return(false));
setup_successful_start(process);
setup_successful_finish(process);
});
auto dns = make_default_dnsmasq_server();
dns.check_dnsmasq_running();
}
TEST_F(DNSMasqServerMockedProcess, dnsmasq_throws_on_failure_to_start)
{
logger_scope.mock_logger->expect_log(mpl::Level::error, "died");
setup([](auto* process) {
InSequence seq;
EXPECT_CALL(*process, start()).Times(1);
EXPECT_CALL(*process, wait_for_started(_)).WillOnce(Return(false));
EXPECT_CALL(*process, kill());
});
MP_EXPECT_THROW_THAT(make_default_dnsmasq_server(), std::runtime_error,
mpt::match_what(HasSubstr("failed to start")));
}
TEST_F(DNSMasqServerMockedProcess, dnsmasq_throws_when_it_dies_immediately)
{
constexpr auto msg = "an error msg";
setup([](auto* process) {
InSequence seq;
EXPECT_CALL(*process, start()).Times(1);
EXPECT_CALL(*process, wait_for_started(_)).WillOnce(Return(true));
EXPECT_CALL(*process, wait_for_finished(_)).WillOnce(Return(true));
mp::ProcessState state{2, mp::ProcessState::Error{QProcess::Crashed, msg}};
EXPECT_CALL(*process, process_state()).WillOnce(Return(state));
});
MP_EXPECT_THROW_THAT(make_default_dnsmasq_server(), std::runtime_error,
mpt::match_what(AllOf(HasSubstr(msg), HasSubstr("died"), HasSubstr("port 53"))));
}
TEST_F(DNSMasqServerMockedProcess, dnsmasq_logs_error_when_it_dies)
{
constexpr auto msg = "crash test dummy";
logger_scope.mock_logger->expect_log(mpl::Level::error, msg);
mp::Process* dnsmasq_proc = nullptr;
setup([this, &dnsmasq_proc](auto* process) {
InSequence seq;
setup_successful_start(process);
EXPECT_CALL(*process, running).WillOnce(Return(false));
dnsmasq_proc = process;
});
auto dns = make_default_dnsmasq_server();
ASSERT_TRUE(dnsmasq_proc);
mp::ProcessState state{-1, mp::ProcessState::Error{QProcess::Crashed, msg}};
emit dnsmasq_proc->finished(state);
}
} // namespace
| 10,345
|
C++
|
.cpp
| 265
| 34.10566
| 120
| 0.688842
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,667
|
test_dnsmasq_process_spec.cpp
|
canonical_multipass/tests/qemu/linux/test_dnsmasq_process_spec.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/mock_environment_helpers.h"
#include <src/platform/backends/qemu/linux/dnsmasq_process_spec.h>
#include <multipass/ip_address.h>
#include <QFile>
#include <QTemporaryDir>
namespace mp = multipass;
namespace mpt = multipass::test;
using namespace testing;
struct TestDnsmasqProcessSpec : public Test
{
const QString data_dir{"/data"};
const QString bridge_name{"bridgey"};
const std::string subnet{"1.2.3"};
const QString conf_file_path{"/path/to/file.conf"};
};
TEST_F(TestDnsmasqProcessSpec, default_arguments_correct)
{
const QByteArray snap_name{"multipass"};
mpt::SetEnvScope e1("SNAP", "/something");
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::DNSMasqProcessSpec spec(data_dir, bridge_name, subnet, conf_file_path);
EXPECT_EQ(
spec.arguments(),
QStringList({"--keep-in-foreground", "--strict-order", "--bind-interfaces", "--pid-file", "--domain=multipass",
"--local=/multipass/", "--except-interface=lo", "--interface=bridgey", "--listen-address=1.2.3.1",
"--dhcp-no-override", "--dhcp-ignore-clid", "--dhcp-authoritative",
"--dhcp-leasefile=/data/dnsmasq.leases", "--dhcp-hostsfile=/data/dnsmasq.hosts", "--dhcp-range",
"1.2.3.2,1.2.3.254,infinite", "--conf-file=/path/to/file.conf"}));
}
TEST_F(TestDnsmasqProcessSpec, apparmor_profile_has_correct_name)
{
mp::DNSMasqProcessSpec spec(data_dir, bridge_name, subnet, conf_file_path);
EXPECT_TRUE(spec.apparmor_profile().contains("profile multipass.dnsmasq"));
}
TEST_F(TestDnsmasqProcessSpec, apparmor_profile_permits_data_dirs)
{
mp::DNSMasqProcessSpec spec(data_dir, bridge_name, subnet, conf_file_path);
EXPECT_TRUE(spec.apparmor_profile().contains("/data/dnsmasq.leases rw,"));
EXPECT_TRUE(spec.apparmor_profile().contains("/data/dnsmasq.hosts r,"));
EXPECT_TRUE(spec.apparmor_profile().contains("/path/to/file.conf r,"));
}
TEST_F(TestDnsmasqProcessSpec, apparmor_profile_identifier)
{
mp::DNSMasqProcessSpec spec(data_dir, bridge_name, subnet, conf_file_path);
EXPECT_EQ(spec.identifier(), "");
}
TEST_F(TestDnsmasqProcessSpec, apparmor_profile_running_as_snap_correct)
{
const QByteArray snap_name{"multipass"};
QTemporaryDir snap_dir;
mpt::SetEnvScope e1("SNAP", snap_dir.path().toUtf8());
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::DNSMasqProcessSpec spec(data_dir, bridge_name, subnet, conf_file_path);
EXPECT_TRUE(spec.apparmor_profile().contains("signal (receive) peer=snap.multipass.multipassd"));
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1/usr/sbin/dnsmasq ixr,").arg(snap_dir.path())));
}
TEST_F(TestDnsmasqProcessSpec, apparmor_profile_running_as_symlinked_snap_correct)
{
const QByteArray snap_name{"multipass"};
QTemporaryDir snap_dir, link_dir;
link_dir.remove();
QFile::link(snap_dir.path(), link_dir.path());
mpt::SetEnvScope e1("SNAP", link_dir.path().toUtf8());
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::DNSMasqProcessSpec spec(data_dir, bridge_name, subnet, conf_file_path);
EXPECT_TRUE(spec.apparmor_profile().contains(QString("%1/usr/sbin/dnsmasq ixr,").arg(snap_dir.path())));
}
TEST_F(TestDnsmasqProcessSpec, apparmor_profile_not_running_as_snap_correct)
{
const QByteArray snap_name{"multipass"};
mpt::UnsetEnvScope e("SNAP");
mpt::SetEnvScope e2("SNAP_NAME", snap_name);
mp::DNSMasqProcessSpec spec(data_dir, bridge_name, subnet, conf_file_path);
EXPECT_TRUE(spec.apparmor_profile().contains("signal (receive) peer=unconfined"));
EXPECT_TRUE(spec.apparmor_profile().contains(" /usr/sbin/dnsmasq ixr,")); // space wanted
}
| 4,386
|
C++
|
.cpp
| 93
| 43.032258
| 119
| 0.715624
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,668
|
test_firewall_config.cpp
|
canonical_multipass/tests/qemu/linux/test_firewall_config.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tests/common.h"
#include "tests/mock_environment_helpers.h"
#include "tests/mock_logger.h"
#include "tests/mock_process_factory.h"
#include "tests/mock_utils.h"
#include "tests/reset_process_factory.h"
#include <src/platform/backends/qemu/linux/firewall_config.h>
#include <multipass/format.h>
#include <QString>
#include <tuple>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct FirewallConfig : public Test
{
mpt::SetEnvScope env_scope{"DISABLE_APPARMOR", "1"};
mpt::ResetProcessFactory scope; // will otherwise pollute other tests
const QString goodbr0{QStringLiteral("goodbr0")};
const QString evilbr0{QStringLiteral("evilbr0")};
const std::string subnet{"192.168.2"};
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
};
struct FirewallToUseTestSuite : FirewallConfig, WithParamInterface<std::tuple<std::string, QByteArray, QByteArray>>
{
};
struct KernelCheckTestSuite : FirewallConfig, WithParamInterface<std::tuple<std::string, std::string>>
{
};
} // namespace
TEST_F(FirewallConfig, iptablesNftErrorLogsWarningUsesIptablesLegacyByDefault)
{
const QString error_msg{"Cannot find iptables-nft"};
mpt::MockProcessFactory::Callback firewall_callback = [&error_msg](mpt::MockProcess* process) {
if (process->program() == "iptables-nft")
{
mp::ProcessState exit_state{1, mp::ProcessState::Error{QProcess::FailedToStart, error_msg}};
EXPECT_CALL(*process, execute(_)).WillOnce(Return(exit_state));
}
};
auto factory = mpt::MockProcessFactory::Inject();
factory->register_callback(firewall_callback);
logger_scope.mock_logger->screen_logs(mpl::Level::warning);
logger_scope.mock_logger->expect_log(mpl::Level::warning, fmt::format("Failure: {}", error_msg));
mp::FirewallConfig firewall_config{goodbr0, subnet};
}
TEST_F(FirewallConfig, firewallVerifyNoErrorDoesNotThrow)
{
mpt::MockProcessFactory::Callback firewall_callback = [this](mpt::MockProcess* process) {
if (process->arguments().contains(goodbr0))
{
mp::ProcessState exit_state;
exit_state.exit_code = 0;
EXPECT_CALL(*process, execute(_)).WillOnce(Return(exit_state));
}
};
auto factory = mpt::MockProcessFactory::Inject();
factory->register_callback(firewall_callback);
mp::FirewallConfig firewall_config{goodbr0, subnet};
EXPECT_NO_THROW(firewall_config.verify_firewall_rules());
}
TEST_F(FirewallConfig, firewallErrorThrowsOnVerify)
{
const QByteArray msg{"Evil bridge detected!"};
mpt::MockProcessFactory::Callback firewall_callback = [this, &msg](mpt::MockProcess* process) {
if (process->arguments().contains(evilbr0))
{
mp::ProcessState exit_state;
exit_state.exit_code = 1;
EXPECT_CALL(*process, execute(_)).WillOnce(Return(exit_state));
EXPECT_CALL(*process, read_all_standard_error()).WillOnce(Return(msg));
}
};
auto factory = mpt::MockProcessFactory::Inject();
factory->register_callback(firewall_callback);
mp::FirewallConfig firewall_config{evilbr0, subnet};
MP_EXPECT_THROW_THAT(firewall_config.verify_firewall_rules(), std::runtime_error,
mpt::match_what(HasSubstr(msg.data())));
}
TEST_F(FirewallConfig, dtorDeletesKnownRules)
{
const QByteArray base_rule{fmt::format("POSTROUTING -s {}.0/24 ! -d {}.0/24 -m comment --comment \"generated for "
"Multipass network {}\" -j MASQUERADE",
subnet, subnet, goodbr0)
.data()};
const QByteArray full_rule{"-A " + base_rule};
bool delete_called{false};
mpt::MockProcessFactory::Callback firewall_callback = [&base_rule, &full_rule,
&delete_called](mpt::MockProcess* process) {
if (process->arguments().contains("--list-rules"))
{
EXPECT_CALL(*process, read_all_standard_output()).WillRepeatedly(Return(full_rule));
}
else if (process->program() == "sh" && process->arguments().at(1).contains("--delete"))
{
delete_called = true;
EXPECT_TRUE(process->arguments().at(1).contains(base_rule));
}
};
auto factory = mpt::MockProcessFactory::Inject();
factory->register_callback(firewall_callback);
{
mp::FirewallConfig firewall_config{goodbr0, subnet};
}
EXPECT_TRUE(delete_called);
}
TEST_F(FirewallConfig, dtorDeleteErrorLogsErrorAndContinues)
{
const QByteArray base_rule{fmt::format("POSTROUTING -s {}.0/24 ! -d {}.0/24 -m comment --comment \"generated for "
"Multipass network {}\" -j MASQUERADE",
subnet, subnet, goodbr0)
.data()};
const QByteArray full_rule{"-A " + base_rule};
const QByteArray msg{"Bad stuff happened"};
mpt::MockProcessFactory::Callback firewall_callback = [&](mpt::MockProcess* process) {
if (process->arguments().contains("--list-rules"))
{
EXPECT_CALL(*process, read_all_standard_output()).WillRepeatedly(Return(full_rule));
}
else if (process->program() == "sh" && process->arguments().at(1).contains("--delete"))
{
if (process->arguments().at(1).contains(base_rule))
{
mp::ProcessState exit_state;
exit_state.exit_code = 1;
EXPECT_CALL(*process, execute(_)).WillRepeatedly(Return(exit_state));
EXPECT_CALL(*process, read_all_standard_error()).WillOnce(Return(msg));
}
}
};
auto factory = mpt::MockProcessFactory::Inject();
factory->register_callback(firewall_callback);
logger_scope.mock_logger->screen_logs(mpl::Level::error);
logger_scope.mock_logger->expect_log(mpl::Level::error, msg.toStdString(), AnyNumber());
{
mp::FirewallConfig firewall_config{goodbr0, subnet};
}
}
TEST_P(FirewallToUseTestSuite, usesExpectedFirewall)
{
const auto& param = GetParam();
mpt::MockProcessFactory::Callback firewall_callback = [¶m](mpt::MockProcess* process) {
if (process->program() == "iptables-nft" && process->arguments().contains("--list-rules"))
{
EXPECT_CALL(*process, read_all_standard_output()).WillOnce(Return(std::get<1>(param)));
}
else if (process->program() == "iptables-legacy" && process->arguments().contains("--list-rules"))
{
EXPECT_CALL(*process, read_all_standard_output()).WillOnce(Return(std::get<2>(param)));
}
};
auto factory = mpt::MockProcessFactory::Inject();
factory->register_callback(firewall_callback);
logger_scope.mock_logger->screen_logs(mpl::Level::info);
logger_scope.mock_logger->expect_log(mpl::Level::info, std::get<0>(param));
mp::FirewallConfig firewall_config{goodbr0, subnet};
}
INSTANTIATE_TEST_SUITE_P(FirewallConfig, FirewallToUseTestSuite,
Values(std::make_tuple("iptables-legacy", QByteArray(), "-N FOO"),
std::make_tuple("iptables-nft", "-N FOO", QByteArray()),
std::make_tuple("iptables-nft", QByteArray(), QByteArray()),
std::make_tuple("iptables-nft", "-N FOO", "-N FOO")));
TEST_P(KernelCheckTestSuite, usesIptablesAndLogsWithBadKernelInfo)
{
auto [kernel, msg] = GetParam();
bool nftables_called{false};
mpt::MockProcessFactory::Callback firewall_callback = [&nftables_called](mpt::MockProcess* process) {
if (process->program() == "iptables-legacy" && process->arguments().contains("--list-rules"))
{
EXPECT_CALL(*process, read_all_standard_output()).WillOnce(Return(QByteArray()));
}
else if (process->program() == "iptables-nft")
{
nftables_called = true;
}
};
auto factory = mpt::MockProcessFactory::Inject();
factory->register_callback(firewall_callback);
auto [mock_utils, guard] = mpt::MockUtils::inject();
EXPECT_CALL(*mock_utils, get_kernel_version()).WillOnce(Return(kernel));
logger_scope.mock_logger->screen_logs(mpl::Level::warning);
logger_scope.mock_logger->expect_log(mpl::Level::info, "iptables-legacy");
logger_scope.mock_logger->expect_log(mpl::Level::warning, msg);
mp::FirewallConfig firewall_config{goodbr0, subnet};
EXPECT_FALSE(nftables_called);
}
INSTANTIATE_TEST_SUITE_P(FirewallConfig, KernelCheckTestSuite,
Values(std::make_tuple("undefined", "Cannot parse kernel version \'undefined\'"),
std::make_tuple("4.20.1", "Kernel version does not meet minimum requirement of 5.2"),
std::make_tuple("5.1.4", "Kernel version does not meet minimum requirement of 5.2")));
| 9,770
|
C++
|
.cpp
| 208
| 38.951923
| 118
| 0.650163
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,669
|
mock_dnsmasq.cpp
|
canonical_multipass/tests/qemu/linux/mock_dnsmasq.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <QCommandLineParser>
#include <QCoreApplication>
#include <unistd.h>
int main(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
QCommandLineParser parser;
QCommandLineOption listenOption("listen-address", "Address to listen on", "address");
parser.addOption(listenOption);
parser.parse(QCoreApplication::arguments());
if (parser.isSet(listenOption))
{
auto address = parser.value(listenOption);
// For testing, we treat a 0.0.0 subnet as an error
if (address.contains("0.0.0"))
{
return 1;
}
}
pause(); // wait to be terminated from the outside
return 0;
}
| 1,303
|
C++
|
.cpp
| 38
| 30.289474
| 89
| 0.709062
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
20,670
|
test_qemu_platform_detail.cpp
|
canonical_multipass/tests/qemu/linux/test_qemu_platform_detail.cpp
|
/*
* Copyright (C) Canonical, Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mock_dnsmasq_server.h"
#include "mock_firewall_config.h"
#include "tests/common.h"
#include "tests/mock_backend_utils.h"
#include "tests/mock_file_ops.h"
#include "tests/mock_logger.h"
#include "tests/mock_process_factory.h"
#include "tests/mock_utils.h"
#include "tests/temp_dir.h"
#include <src/platform/backends/qemu/linux/qemu_platform_detail.h>
#include <QCoreApplication>
namespace mp = multipass;
namespace mpl = multipass::logging;
namespace mpt = multipass::test;
using namespace testing;
namespace
{
struct QemuPlatformDetail : public Test
{
QemuPlatformDetail()
: mock_dnsmasq_server{std::make_unique<mpt::MockDNSMasqServer>()},
mock_firewall_config{std::make_unique<mpt::MockFirewallConfig>()}
{
EXPECT_CALL(*mock_backend, get_subnet(_, _)).WillOnce([this](auto...) { return subnet; });
EXPECT_CALL(*mock_dnsmasq_server_factory, make_dnsmasq_server(_, _, _)).WillOnce([this](auto...) {
return std::move(mock_dnsmasq_server);
});
EXPECT_CALL(*mock_firewall_config_factory, make_firewall_config(_, _)).WillOnce([this](auto...) {
return std::move(mock_firewall_config);
});
EXPECT_CALL(*mock_utils, run_cmd_for_status(QString("ip"), _, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_utils,
run_cmd_for_status(QString("ip"), QStringList({"addr", "show", multipass_bridge_name}), _))
.WillOnce(Return(false))
.WillOnce(Return(true));
EXPECT_CALL(*mock_file_ops, open(_, _)).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_file_ops, write(_, _)).WillRepeatedly(Return(1));
};
mpt::TempDir data_dir;
const QString multipass_bridge_name{"mpqemubr0"};
const std::string hw_addr{"52:54:00:6f:29:7e"};
const std::string subnet{"192.168.64"};
const std::string name{"foo"};
std::unique_ptr<mpt::MockDNSMasqServer> mock_dnsmasq_server;
std::unique_ptr<mpt::MockFirewallConfig> mock_firewall_config;
mpt::MockUtils::GuardedMock utils_attr{mpt::MockUtils::inject<NiceMock>()};
mpt::MockUtils* mock_utils = utils_attr.first;
mpt::MockBackend::GuardedMock backend_attr{mpt::MockBackend::inject<NiceMock>()};
mpt::MockBackend* mock_backend = backend_attr.first;
mpt::MockDNSMasqServerFactory::GuardedMock dnsmasq_server_factory_attr{
mpt::MockDNSMasqServerFactory::inject<NiceMock>()};
mpt::MockDNSMasqServerFactory* mock_dnsmasq_server_factory = dnsmasq_server_factory_attr.first;
mpt::MockFirewallConfigFactory::GuardedMock firewall_config_factory_attr{
mpt::MockFirewallConfigFactory::inject<NiceMock>()};
mpt::MockFirewallConfigFactory* mock_firewall_config_factory = firewall_config_factory_attr.first;
mpt::MockFileOps::GuardedMock file_ops_attr{mpt::MockFileOps::inject<NiceMock>()};
mpt::MockFileOps* mock_file_ops = file_ops_attr.first;
mpt::MockLogger::Scope logger_scope = mpt::MockLogger::inject();
};
} // namespace
TEST_F(QemuPlatformDetail, ctor_sets_up_expected_virtual_switch)
{
const QString qstring_subnet{QString::fromStdString(subnet)};
EXPECT_CALL(*mock_utils, run_cmd_for_status(QString("ip"),
ElementsAre(QString("link"), QString("add"), multipass_bridge_name,
QString("address"), _, QString("type"), QString("bridge")),
_))
.WillOnce(Return(true));
EXPECT_CALL(*mock_utils, run_cmd_for_status(QString("ip"),
ElementsAre(QString("address"), QString("add"),
QString("%1.1/24").arg(qstring_subnet), QString("dev"),
multipass_bridge_name, "broadcast",
QString("%1.255").arg(qstring_subnet)),
_))
.WillOnce(Return(true));
EXPECT_CALL(*mock_utils, run_cmd_for_status(
QString("ip"),
ElementsAre(QString("link"), QString("set"), multipass_bridge_name, QString("up")), _))
.WillOnce(Return(true));
mp::QemuPlatformDetail qemu_platform_detail{data_dir.path()};
}
TEST_F(QemuPlatformDetail, get_ip_for_returns_expected_info)
{
const mp::IPAddress ip_address{fmt::format("{}.5", subnet)};
EXPECT_CALL(*mock_dnsmasq_server, get_ip_for(hw_addr)).WillOnce([&ip_address](auto...) { return ip_address; });
mp::QemuPlatformDetail qemu_platform_detail{data_dir.path()};
auto addr = qemu_platform_detail.get_ip_for(hw_addr);
EXPECT_EQ(*addr, ip_address);
}
TEST_F(QemuPlatformDetail, platform_args_generate_net_resources_removes_works_as_expected)
{
mp::VirtualMachineDescription vm_desc;
mp::NetworkInterface extra_interface{"br-en0", "52:54:00:98:76:54", true};
vm_desc.vm_name = "foo";
vm_desc.default_mac_address = hw_addr;
vm_desc.extra_interfaces = {extra_interface};
QString tap_name;
EXPECT_CALL(*mock_dnsmasq_server, release_mac(hw_addr)).WillOnce(Return());
EXPECT_CALL(
*mock_utils,
run_cmd_for_status(QString("ip"),
ElementsAre(QString("addr"), QString("show"), mpt::match_qstring(StartsWith("tap-"))), _))
.WillOnce([&tap_name](auto& cmd, auto& opts, auto...) {
tap_name = opts.last();
return false;
});
mp::QemuPlatformDetail qemu_platform_detail{data_dir.path()};
const auto platform_args = qemu_platform_detail.vm_platform_args(vm_desc);
// Tests the order and correctness of the arguments returned
std::vector<QString> expected_platform_args
{
#if defined Q_PROCESSOR_X86
"-bios", "OVMF.fd",
#elif defined Q_PROCESSOR_ARM
"-bios", "QEMU_EFI.fd",
#endif
"--enable-kvm", "-cpu", "host", "-nic",
QString::fromStdString(fmt::format("tap,ifname={},script=no,downscript=no,model=virtio-net-pci,mac={}",
tap_name,
vm_desc.default_mac_address)),
"-nic",
QString::fromStdString(fmt::format("bridge,br={},model=virtio-net-pci,mac={},helper={}",
extra_interface.id,
extra_interface.mac_address,
QCoreApplication::applicationDirPath() + "/bridge_helper"))
};
EXPECT_THAT(platform_args, ElementsAreArray(expected_platform_args));
EXPECT_CALL(*mock_utils,
run_cmd_for_status(QString("ip"), ElementsAre(QString("addr"), QString("show"), tap_name), _))
.WillOnce(Return(true));
EXPECT_CALL(*mock_utils,
run_cmd_for_status(QString("ip"), ElementsAre(QString("link"), QString("delete"), tap_name), _))
.WillOnce(Return(true));
qemu_platform_detail.remove_resources_for(name);
}
TEST_F(QemuPlatformDetail, platform_health_check_calls_expected_methods)
{
EXPECT_CALL(*mock_backend, check_for_kvm_support()).WillOnce(Return());
EXPECT_CALL(*mock_backend, check_if_kvm_is_in_use()).WillOnce(Return());
EXPECT_CALL(*mock_dnsmasq_server, check_dnsmasq_running()).WillOnce(Return());
EXPECT_CALL(*mock_firewall_config, verify_firewall_rules()).WillOnce(Return());
mp::QemuPlatformDetail qemu_platform_detail{data_dir.path()};
qemu_platform_detail.platform_health_check();
}
TEST_F(QemuPlatformDetail, opening_ipforward_file_failure_logs_expected_message)
{
logger_scope.mock_logger->screen_logs(mpl::Level::warning); // warning and above expected explicitly in tests
logger_scope.mock_logger->expect_log(mpl::Level::warning, "Unable to open /proc/sys/net/ipv4/ip_forward");
EXPECT_CALL(*mock_file_ops, open(_, _)).WillOnce(Return(false));
mp::QemuPlatformDetail qemu_platform_detail{data_dir.path()};
}
TEST_F(QemuPlatformDetail, writing_ipforward_file_failure_logs_expected_message)
{
logger_scope.mock_logger->screen_logs(mpl::Level::warning); // warning and above expected explicitly in tests
logger_scope.mock_logger->expect_log(mpl::Level::warning, "Failed to write to /proc/sys/net/ipv4/ip_forward");
EXPECT_CALL(*mock_file_ops, write(_, QByteArray("1"))).WillOnce(Return(-1));
mp::QemuPlatformDetail qemu_platform_detail{data_dir.path()};
}
TEST_F(QemuPlatformDetail, platformCorrectlySetsAuthorization)
{
mp::QemuPlatformDetail qemu_platform_detail{data_dir.path()};
std::vector<mp::NetworkInterfaceInfo> networks{mp::NetworkInterfaceInfo{"br-en0", "bridge", "", {"en0"}, false},
mp::NetworkInterfaceInfo{"mpbr0", "bridge", "", {}, false}};
const auto& bridged_network = networks.emplace_back(mp::NetworkInterfaceInfo{"en0", "ethernet", "", {}, false});
const auto& non_bridged_network = networks.emplace_back(mp::NetworkInterfaceInfo{"en1", "ethernet", "", {}, false});
qemu_platform_detail.set_authorization(networks);
EXPECT_FALSE(bridged_network.needs_authorization);
EXPECT_TRUE(non_bridged_network.needs_authorization);
}
TEST_F(QemuPlatformDetail, CreateBridgeWithCallsExpectedMethods)
{
EXPECT_CALL(*mock_backend, create_bridge_with("en0")).WillOnce(Return("br-en0"));
mp::QemuPlatformDetail qemu_platform_detail{data_dir.path()};
EXPECT_EQ(qemu_platform_detail.create_bridge_with(mp::NetworkInterfaceInfo{"en0", "ethernet", "", {}, true}),
"br-en0");
}
| 10,341
|
C++
|
.cpp
| 192
| 44.78125
| 120
| 0.648277
|
canonical/multipass
| 7,732
| 642
| 476
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.