Merge upstream/master into fix/picture-loader-cache-offline

Keep the decoder-aware Accept header from this branch; upstream #6609 only
fixed the wildcard spelling of the previous hardcoded header.
This commit is contained in:
Lukas Brübach 2026-11-08 16:48:52 +01:00
commit 00ce5e9ce3
207 changed files with 5681 additions and 1240 deletions

View file

@ -301,6 +301,7 @@ cockatrice_add_test(
NAME
server_card_counter_test
SOURCES
${VERSION_STRING_CPP}
server_card_counter_test.cpp
LIBS
libcockatrice_network
@ -311,6 +312,7 @@ cockatrice_add_test(
NAME
server_dump_zone_test
SOURCES
${VERSION_STRING_CPP}
server_dump_zone_test.cpp
LIBS
libcockatrice_rng
@ -322,6 +324,7 @@ cockatrice_add_test(
NAME
server_counter_test
SOURCES
${VERSION_STRING_CPP}
server_counter_test.cpp
LIBS
libcockatrice_network
@ -333,6 +336,7 @@ cockatrice_add_test(
server_developer_role_test
NO_SANITIZE
SOURCES
${VERSION_STRING_CPP}
server_developer_role_test.cpp
LIBS
libcockatrice_network
@ -345,6 +349,7 @@ cockatrice_add_test(
server_moderator_role_test
NO_SANITIZE
SOURCES
${VERSION_STRING_CPP}
server_moderator_role_test.cpp
LIBS
libcockatrice_network
@ -352,6 +357,17 @@ cockatrice_add_test(
LABELS
server
)
cockatrice_add_test(
NAME
random_reveal_test
SOURCES
random_reveal_test.cpp
LIBS
libcockatrice_network_server_remote
libcockatrice_rng
LABELS
server
)
cockatrice_add_test(
NAME
server_game_join_test
@ -391,6 +407,7 @@ cockatrice_add_test(
NAME
local_client_lifetime_test
SOURCES
${VERSION_STRING_CPP}
local_client_lifetime_test.cpp
LIBS
libcockatrice_network
@ -412,6 +429,7 @@ cockatrice_add_test(
NAME
latency_tracker_test
SOURCES
${VERSION_STRING_CPP}
latency_tracker_test.cpp
LIBS
libcockatrice_network
@ -456,6 +474,31 @@ cockatrice_add_test(
INCLUDE_DIRS
${CMAKE_SOURCE_DIR}/cockatrice/src
)
cockatrice_add_test(
NAME
game_creation_options_test
SOURCES
${CMAKE_SOURCE_DIR}/cockatrice/src/interface/widgets/game_hosting/game_creation_options.cpp
game_creation_options_test.cpp
LIBS
libcockatrice_interfaces
libcockatrice_protocol
INCLUDE_DIRS
${CMAKE_SOURCE_DIR}/cockatrice/src
)
cockatrice_add_test(
NAME
create_game_form_widget_test
SOURCES
${CMAKE_SOURCE_DIR}/cockatrice/src/interface/widgets/game_hosting/create_game_form_widget.cpp
${CMAKE_SOURCE_DIR}/cockatrice/src/interface/widgets/game_hosting/game_creation_options.cpp
create_game_form_widget_test.cpp
LIBS
libcockatrice_interfaces
libcockatrice_protocol
INCLUDE_DIRS
${CMAKE_SOURCE_DIR}/cockatrice/src
)
cockatrice_add_test(
NAME
deck_hash_performance_test

View file

@ -21,10 +21,12 @@ cockatrice_add_test(
)
# ------------------------
# Filter String Test
# (guard must match the condition for libcockatrice_filters in the root CMakeLists.txt)
# Guard to match condition for libcockatrice_filters in the root CMakeLists.txt
# ------------------------
if(WITH_ORACLE OR WITH_CLIENT)
# ------------------------
# Filter String Test
# ------------------------
cockatrice_add_test(
NAME
filter_string_test
@ -36,6 +38,34 @@ if(WITH_ORACLE OR WITH_CLIENT)
libcockatrice_filters
)
# ------------------------
# Filter Tree Test
# ------------------------
cockatrice_add_test(
NAME
filter_tree_test
SOURCES
${VERSION_STRING_CPP}
filter_tree_test.cpp
mocks.cpp
LIBS
libcockatrice_filters
)
# ------------------------
# Filter Mode Test
# ------------------------
cockatrice_add_test(
NAME
filter_mode_test
SOURCES
${VERSION_STRING_CPP}
filter_mode_test.cpp
mocks.cpp
LIBS
libcockatrice_filters
)
# ------------------------
# Visual Display Model Test
# ------------------------

View file

@ -1,3 +1,4 @@
#include "../support/scoped_file_size_limit.h"
#include "libcockatrice/card/database/card_database.h"
#include "libcockatrice/card/database/card_database_loader.h"
#include "libcockatrice/card/database/card_database_querier.h"
@ -36,12 +37,6 @@
#include <libcockatrice/utility/card_ref.h>
#include <string>
#ifdef Q_OS_UNIX
#include <csignal>
#include <sys/resource.h>
#include <unistd.h>
#endif
namespace
{
@ -247,21 +242,14 @@ TEST(CardDatabaseTest, Xml4ShortWriteKeepsInstalledFile)
ASSERT_EQ(installed.write("installed database"), 18);
installed.close();
// A real filesystem write failure, isolated in the death-test child so the
// process-wide file limit never affects other cases or the parent runner.
ASSERT_EXIT(
{
std::signal(SIGXFSZ, SIG_IGN);
struct rlimit limit;
limit.rlim_cur = 128;
limit.rlim_max = 128;
if (setrlimit(RLIMIT_FSIZE, &limit) != 0) {
_exit(2);
}
CockatriceXml4Parser writer(&controller);
_exit(writer.saveToFile({}, sets, cards, fileName) ? 1 : 0);
},
::testing::ExitedWithCode(0), "");
// A real filesystem write failure: the soft file-size cap makes the writer's own
// flush fail without filling a disk. The cap is scoped rather than forked, because a
// death-test child under RLIMIT_FSIZE is killed by SIGSEGV on macOS.
test_support::ScopedFileSizeLimit fileSizeCap(128);
ASSERT_TRUE(fileSizeCap.isValid());
CockatriceXml4Parser writer(&controller);
EXPECT_FALSE(writer.saveToFile({}, sets, cards, fileName));
ASSERT_TRUE(installed.open(QIODevice::ReadOnly));
EXPECT_EQ(installed.readAll(), "installed database");

View file

@ -0,0 +1,147 @@
#include "libcockatrice/filters/filter_mode.h"
#include <gtest/gtest.h>
class FilterModeTest : public ::testing::Test
{
protected:
~FilterModeTest() override
{
for (CardFilter *filter : owned) {
delete filter;
}
}
/** @brief Create a filter owned by the fixture and append it to the set under test. */
const CardFilter *
add(const QString &term, CardFilter::Type type, CardFilter::Attr attr = CardFilter::Attr::AttrColor)
{
owned.append(new CardFilter(term, type, attr));
filters.append(owned.last());
return owned.last();
}
QList<CardFilter *> owned;
QList<const CardFilter *> filters;
};
TEST(FilterModeInfoTest, EachModeDescribesItsOwnFilters)
{
EXPECT_EQ(getFilterModeInfo(FilterMode::Includes).includeType, CardFilter::Type::TypeOr);
EXPECT_EQ(getFilterModeInfo(FilterMode::Includes).excludeType, CardFilter::Type::TypeEnd);
EXPECT_EQ(getFilterModeInfo(FilterMode::Includes).attr, CardFilter::Attr::AttrColor);
EXPECT_EQ(getFilterModeInfo(FilterMode::Excludes).includeType, CardFilter::Type::TypeAndNot);
EXPECT_EQ(getFilterModeInfo(FilterMode::Excludes).excludeType, CardFilter::Type::TypeEnd);
EXPECT_EQ(getFilterModeInfo(FilterMode::IncludeExclude).includeType, CardFilter::Type::TypeOr);
EXPECT_EQ(getFilterModeInfo(FilterMode::IncludeExclude).excludeType, CardFilter::Type::TypeAndNot);
EXPECT_EQ(getFilterModeInfo(FilterMode::ExactMatch).includeType, CardFilter::Type::TypeAnd);
EXPECT_EQ(getFilterModeInfo(FilterMode::ExactMatch).excludeType, CardFilter::Type::TypeAndNot);
// Color identity only excludes: the selected colors must be the identity, so nothing is included positively.
EXPECT_EQ(getFilterModeInfo(FilterMode::ColorIdentity).includeType, CardFilter::Type::TypeEnd);
EXPECT_EQ(getFilterModeInfo(FilterMode::ColorIdentity).excludeType, CardFilter::Type::TypeAndNot);
EXPECT_EQ(getFilterModeInfo(FilterMode::ColorIdentity).attr, CardFilter::Attr::AttrColorIdentity);
EXPECT_EQ(getFilterModeInfo(FilterMode::Custom).attr, CardFilter::Attr::AttrEnd);
}
TEST_F(FilterModeTest, EmptyFilterSetKeepsACompatibleMode)
{
// Includes and Color identity both allow an empty set, so the live mode is not swapped for another.
EXPECT_EQ(deriveFilterMode(filters, FilterMode::Includes), FilterMode::Includes);
EXPECT_EQ(deriveFilterMode(filters, FilterMode::ColorIdentity), FilterMode::ColorIdentity);
}
// Include / Exclude and Exact match always hold one filter per color, so an empty set cannot have come from
// them and falls back to the first mode that can describe it.
TEST_F(FilterModeTest, EmptyFilterSetFallsBackWhenTheModeNeedsOneFilterPerColor)
{
EXPECT_EQ(deriveFilterMode(filters, FilterMode::IncludeExclude), FilterMode::Includes);
EXPECT_EQ(deriveFilterMode(filters, FilterMode::ExactMatch), FilterMode::Includes);
}
TEST_F(FilterModeTest, IncludesFromOrFilters)
{
add("W", CardFilter::Type::TypeOr);
EXPECT_EQ(deriveFilterMode(filters, FilterMode::Includes), FilterMode::Includes);
// A single OR filter cannot come from Excludes, so the first mode that can produce it is selected.
EXPECT_EQ(deriveFilterMode(filters, FilterMode::Excludes), FilterMode::Includes);
}
TEST_F(FilterModeTest, ExcludesFromAndNotFilters)
{
add("W", CardFilter::Type::TypeAndNot);
EXPECT_EQ(deriveFilterMode(filters, FilterMode::Excludes), FilterMode::Excludes);
// Includes needs an OR or an end filter, so an AND NOT filter selects Excludes.
EXPECT_EQ(deriveFilterMode(filters, FilterMode::Includes), FilterMode::Excludes);
}
TEST_F(FilterModeTest, IncludeExcludeNeedsOneFilterPerColor)
{
add("W", CardFilter::Type::TypeOr);
for (const QChar color : QString("UBRG")) {
add(QString(color), CardFilter::Type::TypeAndNot);
}
EXPECT_EQ(deriveFilterMode(filters, FilterMode::IncludeExclude), FilterMode::IncludeExclude);
}
TEST_F(FilterModeTest, IncludeExcludeRejectsAnIncompleteColorSet)
{
add("W", CardFilter::Type::TypeOr);
add("U", CardFilter::Type::TypeAndNot);
EXPECT_EQ(deriveFilterMode(filters, FilterMode::IncludeExclude), FilterMode::Custom);
}
TEST_F(FilterModeTest, ExactMatchFromAndAndAndNotFilters)
{
add("W", CardFilter::Type::TypeAnd);
for (const QChar color : QString("UBRG")) {
add(QString(color), CardFilter::Type::TypeAndNot);
}
EXPECT_EQ(deriveFilterMode(filters, FilterMode::ExactMatch), FilterMode::ExactMatch);
}
TEST_F(FilterModeTest, ColorIdentityFromIdentityAndNotFilters)
{
for (const QChar color : QString("BRG")) {
add(QString(color), CardFilter::Type::TypeAndNot, CardFilter::Attr::AttrColorIdentity);
}
EXPECT_EQ(deriveFilterMode(filters, FilterMode::ColorIdentity), FilterMode::ColorIdentity);
}
TEST_F(FilterModeTest, MixedAttributesAreCustom)
{
add("W", CardFilter::Type::TypeOr, CardFilter::Attr::AttrColor);
add("U", CardFilter::Type::TypeAndNot, CardFilter::Attr::AttrColorIdentity);
EXPECT_EQ(deriveFilterMode(filters, FilterMode::Includes), FilterMode::Custom);
}
TEST_F(FilterModeTest, CustomLeavesAsSoonAsAModeCanExplainTheFilters)
{
add("W", CardFilter::Type::TypeOr);
EXPECT_EQ(deriveFilterMode(filters, FilterMode::Custom), FilterMode::Includes);
}
// Exact match with no color selected stores one AND NOT filter per color. That is a legitimate Exact match
// state, so the live mode is kept; a mode that cannot produce the set re-derives to Excludes, which produces
// the identical filters.
TEST_F(FilterModeTest, FullyExcludedColorSetIsExactMatchOrExcludes)
{
for (const QChar color : QString("WUBRG")) {
add(QString(color), CardFilter::Type::TypeAndNot);
}
EXPECT_EQ(deriveFilterMode(filters, FilterMode::ExactMatch), FilterMode::ExactMatch);
EXPECT_EQ(deriveFilterMode(filters, FilterMode::Includes), FilterMode::Excludes);
}

View file

@ -123,6 +123,25 @@ CardInfoPtr greenIdentityCard()
return CardInfo::newInstance("Identity Cat", "", false, {{"colors", "G"}, {"coloridentity", "G"}}, {}, {}, {}, {});
}
// A card whose color identity differs from its colors, so that a query reading the wrong one is visible.
CardInfoPtr splitIdentityCard()
{
return CardInfo::newInstance("Split Identity", "", false, {{"colors", "G"}, {"coloridentity", "W"}}, {}, {}, {},
{});
}
// "ci!" (exactly these color identities) used to read the camelCase "colorIdentity" property instead of the
// lowercase "coloridentity" key, so it matched the empty string and rejected every card.
TEST_F(CardQuery, ColorIdentityExactReadsTheColorIdentityProperty)
{
const CardData card = splitIdentityCard();
ASSERT_TRUE(FilterString("ci!w").check(card));
ASSERT_FALSE(FilterString("ci!g").check(card));
// "c!" still reads colors, not identity.
ASSERT_TRUE(FilterString("c!g").check(card));
ASSERT_FALSE(FilterString("c!w").check(card));
}
// Whitespace belongs around the separator, never inside an operator token: "c i: g" must not
// be read as the color-identity operator "ci" (it is a generic "c" AND a field query on "i").
TEST_F(CardQuery, ColorIdentityOperatorIsNotSplitByWhitespace)
@ -260,6 +279,22 @@ TEST_F(SetQuery, ComparisonMatchesByReleaseDate)
EXPECT_FALSE(FilterString("set<EOE").check(inBothSets));
}
TEST(FilterStringError, InvalidExpressionIsInvalidAndReportsAPosition)
{
const FilterString filter("t:(");
EXPECT_FALSE(filter.valid());
EXPECT_TRUE(filter.error().contains("position")) << "unexpected error text: " << filter.error().toStdString();
}
TEST(FilterStringError, ValidExpressionHasNoError)
{
const FilterString filter("t:creature");
EXPECT_TRUE(filter.valid());
EXPECT_TRUE(filter.error().isEmpty());
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);

View file

@ -0,0 +1,204 @@
#include "libcockatrice/filters/filter_tree.h"
#include <gtest/gtest.h>
#include <libcockatrice/card/card_localization.h>
#include <libcockatrice/filters/filter_string.h>
namespace
{
class FilterTreeTest : public ::testing::Test
{
protected:
void SetUp() override
{
language = CardSearchLanguage{};
island = CardInfo::newInstance("Island", "", false, {{"colors", ""}, {"coloridentity", "U"}}, {}, {}, {}, {});
artifact =
CardInfo::newInstance("Artifact", "", false, {{"colors", ""}, {"coloridentity", ""}}, {}, {}, {}, {});
truth = CardInfo::newInstance("Truth", "", false, {{"colors", "U"}, {"coloridentity", "U"}}, {}, {}, {}, {});
notDead =
CardInfo::newInstance("Not Dead", "", false, {{"colors", "B"}, {"coloridentity", "B"}}, {}, {}, {}, {});
wallOfDenial = CardInfo::newInstance("Wall of Denial", "", false, {{"colors", "WU"}, {"coloridentity", "WU"}},
{}, {}, {}, {});
maelstromAngel = CardInfo::newInstance("Maelstrom Archangel", "", false,
{{"colors", "WUBRG"}, {"coloridentity", "WUBRG"}}, {}, {}, {}, {});
}
CardSearchLanguage language;
CardData island; // c/u
CardData artifact; // c
CardData truth; // u
CardData notDead; // b
CardData wallOfDenial; // wu
CardData maelstromAngel; // wubrg
};
} // namespace
// =====================================================================================================================
// acceptColor
// =====================================================================================================================
TEST_F(FilterTreeTest, Color)
{
FilterTree filterTree;
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "wu");
ASSERT_FALSE(filterTree.acceptsCard(island, language));
ASSERT_FALSE(filterTree.acceptsCard(artifact, language));
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_FALSE(filterTree.acceptsCard(notDead, language));
ASSERT_TRUE(filterTree.acceptsCard(wallOfDenial, language));
ASSERT_TRUE(filterTree.acceptsCard(maelstromAngel, language));
}
TEST_F(FilterTreeTest, ColorColorless)
{
FilterTree filterTree;
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "c");
ASSERT_TRUE(filterTree.acceptsCard(island, language));
ASSERT_TRUE(filterTree.acceptsCard(artifact, language));
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_FALSE(filterTree.acceptsCard(notDead, language));
ASSERT_FALSE(filterTree.acceptsCard(wallOfDenial, language));
ASSERT_FALSE(filterTree.acceptsCard(maelstromAngel, language));
}
TEST_F(FilterTreeTest, ColorNot)
{
FilterTree filterTree;
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAndNot, "b");
ASSERT_TRUE(filterTree.acceptsCard(island, language));
ASSERT_TRUE(filterTree.acceptsCard(artifact, language));
ASSERT_TRUE(filterTree.acceptsCard(truth, language));
ASSERT_FALSE(filterTree.acceptsCard(notDead, language));
ASSERT_TRUE(filterTree.acceptsCard(wallOfDenial, language));
ASSERT_FALSE(filterTree.acceptsCard(maelstromAngel, language));
}
TEST_F(FilterTreeTest, ColorAliases)
{
FilterTree filterTree;
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "green");
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_TRUE(filterTree.acceptsCard(maelstromAngel, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "grn");
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_TRUE(filterTree.acceptsCard(maelstromAngel, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "blue");
ASSERT_TRUE(filterTree.acceptsCard(truth, language));
ASSERT_FALSE(filterTree.acceptsCard(notDead, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "blu");
ASSERT_TRUE(filterTree.acceptsCard(truth, language));
ASSERT_FALSE(filterTree.acceptsCard(notDead, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "black");
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_TRUE(filterTree.acceptsCard(notDead, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "blk");
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_TRUE(filterTree.acceptsCard(notDead, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "red");
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_TRUE(filterTree.acceptsCard(maelstromAngel, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "white");
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_TRUE(filterTree.acceptsCard(wallOfDenial, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "wht");
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_TRUE(filterTree.acceptsCard(wallOfDenial, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "colorless");
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_TRUE(filterTree.acceptsCard(artifact, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "colourless");
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_TRUE(filterTree.acceptsCard(artifact, language));
filterTree.clear();
filterTree.termNode(CardFilter::Attr::AttrColor, CardFilter::Type::TypeAnd, "none");
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_TRUE(filterTree.acceptsCard(artifact, language));
filterTree.clear();
}
// =====================================================================================================================
// acceptColorIdentity
// =====================================================================================================================
TEST_F(FilterTreeTest, ColorIdentity)
{
FilterTree filterTree;
filterTree.termNode(CardFilter::Attr::AttrColorIdentity, CardFilter::Type::TypeAnd, "wu");
ASSERT_FALSE(filterTree.acceptsCard(island, language));
ASSERT_FALSE(filterTree.acceptsCard(artifact, language));
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_FALSE(filterTree.acceptsCard(notDead, language));
ASSERT_TRUE(filterTree.acceptsCard(wallOfDenial, language));
ASSERT_TRUE(filterTree.acceptsCard(maelstromAngel, language));
}
TEST_F(FilterTreeTest, ColorIdentityColorless)
{
FilterTree filterTree;
filterTree.termNode(CardFilter::Attr::AttrColorIdentity, CardFilter::Type::TypeAnd, "c");
ASSERT_FALSE(filterTree.acceptsCard(island, language));
ASSERT_TRUE(filterTree.acceptsCard(artifact, language));
ASSERT_FALSE(filterTree.acceptsCard(truth, language));
ASSERT_FALSE(filterTree.acceptsCard(notDead, language));
ASSERT_FALSE(filterTree.acceptsCard(wallOfDenial, language));
ASSERT_FALSE(filterTree.acceptsCard(maelstromAngel, language));
}
TEST_F(FilterTreeTest, ColorIdentityNot)
{
FilterTree filterTree;
filterTree.termNode(CardFilter::Attr::AttrColorIdentity, CardFilter::Type::TypeAndNot, "b");
ASSERT_TRUE(filterTree.acceptsCard(island, language));
ASSERT_TRUE(filterTree.acceptsCard(artifact, language));
ASSERT_TRUE(filterTree.acceptsCard(truth, language));
ASSERT_FALSE(filterTree.acceptsCard(notDead, language));
ASSERT_TRUE(filterTree.acceptsCard(wallOfDenial, language));
ASSERT_FALSE(filterTree.acceptsCard(maelstromAngel, language));
}
TEST_F(FilterTreeTest, ColorIdentityMultiple)
{
// Simulate a WU commander.
FilterTree filterTree;
filterTree.termNode(CardFilter::Attr::AttrColorIdentity, CardFilter::Type::TypeAndNot, "b");
filterTree.termNode(CardFilter::Attr::AttrColorIdentity, CardFilter::Type::TypeAndNot, "r");
filterTree.termNode(CardFilter::Attr::AttrColorIdentity, CardFilter::Type::TypeAndNot, "g");
ASSERT_TRUE(filterTree.acceptsCard(island, language));
ASSERT_TRUE(filterTree.acceptsCard(artifact, language));
ASSERT_TRUE(filterTree.acceptsCard(truth, language));
ASSERT_FALSE(filterTree.acceptsCard(notDead, language));
ASSERT_TRUE(filterTree.acceptsCard(wallOfDenial, language));
ASSERT_FALSE(filterTree.acceptsCard(maelstromAngel, language));
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View file

@ -13,6 +13,10 @@
#include <QMetaObject>
#include <QString>
#include <gtest/gtest.h>
#include <libcockatrice/rng/rng_abstract.h>
// Referenced by other translation units in the server_remote library.
RNG_Abstract *rng = nullptr;
namespace
{

View file

@ -0,0 +1,132 @@
#include "interface/widgets/game_hosting/create_game_form_widget.h"
#include <QApplication>
#include <QMap>
#include <gtest/gtest.h>
namespace
{
const QMap<int, QString> gameTypes{{1, "Draft"}, {2, "Commander"}};
void expectSameOptions(const GameCreationOptions &actual, const GameCreationOptions &expected)
{
EXPECT_EQ(actual.description, expected.description);
EXPECT_EQ(actual.password, expected.password);
EXPECT_EQ(actual.maxPlayers, expected.maxPlayers);
EXPECT_EQ(actual.onlyBuddies, expected.onlyBuddies);
EXPECT_EQ(actual.onlyRegistered, expected.onlyRegistered);
EXPECT_EQ(actual.spectatorsAllowed, expected.spectatorsAllowed);
EXPECT_EQ(actual.spectatorsNeedPassword, expected.spectatorsNeedPassword);
EXPECT_EQ(actual.spectatorsCanTalk, expected.spectatorsCanTalk);
EXPECT_EQ(actual.spectatorsSeeEverything, expected.spectatorsSeeEverything);
EXPECT_EQ(actual.joinAsJudge, expected.joinAsJudge);
EXPECT_EQ(actual.joinAsSpectator, expected.joinAsSpectator);
EXPECT_EQ(actual.startingLifeTotal, expected.startingLifeTotal);
EXPECT_EQ(actual.shareDecklistsOnLoad, expected.shareDecklistsOnLoad);
EXPECT_EQ(actual.shufflePlayers, expected.shufflePlayers);
EXPECT_EQ(actual.gameTypeIds, expected.gameTypeIds);
}
} // namespace
TEST(CreateGameFormWidget, RegisteredHostDefaultsToRegisteredOnly)
{
const CreateGameFormWidget form(gameTypes, true, false);
const GameCreationOptions options = form.options();
EXPECT_TRUE(options.onlyRegistered);
EXPECT_FALSE(options.onlyBuddies);
EXPECT_EQ(options.maxPlayers, 2);
EXPECT_TRUE(options.spectatorsAllowed);
EXPECT_EQ(options.startingLifeTotal, 20);
EXPECT_TRUE(options.gameTypeIds.isEmpty());
}
TEST(CreateGameFormWidget, UnregisteredHostDefaultsToOpenJoin)
{
const CreateGameFormWidget form(gameTypes, false, false);
const GameCreationOptions options = form.options();
EXPECT_FALSE(options.onlyRegistered);
EXPECT_FALSE(options.onlyBuddies);
}
TEST(CreateGameFormWidget, SetOptionsRoundTripsEveryField)
{
CreateGameFormWidget form(gameTypes, true, true);
GameCreationOptions expected;
expected.description = "Some game";
expected.password = "hunter2";
expected.maxPlayers = 5;
expected.onlyBuddies = true;
expected.onlyRegistered = false;
expected.spectatorsAllowed = false;
expected.spectatorsNeedPassword = true;
expected.spectatorsCanTalk = true;
expected.spectatorsSeeEverything = true;
expected.joinAsJudge = true;
expected.joinAsSpectator = true;
expected.startingLifeTotal = 40;
expected.shareDecklistsOnLoad = true;
expected.shufflePlayers = true;
expected.gameTypeIds = {2};
form.setOptions(expected);
expectSameOptions(form.options(), expected);
}
TEST(CreateGameFormWidget, ResetRestoresDefaultsAndClearsTheGameType)
{
CreateGameFormWidget form(gameTypes, true, false);
GameCreationOptions configured;
configured.description = "Configured";
configured.maxPlayers = 8;
configured.onlyBuddies = true;
configured.joinAsJudge = true;
configured.gameTypeIds = {2};
form.setOptions(configured);
form.resetToDefaults();
const GameCreationOptions options = form.options();
EXPECT_TRUE(options.description.isEmpty());
EXPECT_EQ(options.maxPlayers, 2);
EXPECT_FALSE(options.onlyBuddies);
EXPECT_TRUE(options.onlyRegistered);
EXPECT_TRUE(options.spectatorsAllowed);
EXPECT_EQ(options.startingLifeTotal, 20);
EXPECT_FALSE(options.joinAsJudge);
EXPECT_TRUE(options.gameTypeIds.isEmpty());
}
TEST(CreateGameFormWidget, RememberSettingsFlagRoundTrips)
{
CreateGameFormWidget form(gameTypes, true, false);
EXPECT_FALSE(form.isRememberSettingsChecked());
form.setRememberSettingsChecked(true);
EXPECT_TRUE(form.isRememberSettingsChecked());
}
TEST(CreateGameFormWidget, SelectedGameTypesSettingStringUsesTheLegacyEncoding)
{
CreateGameFormWidget form(gameTypes, true, false);
GameCreationOptions configured;
configured.gameTypeIds = {1};
form.setOptions(configured);
EXPECT_EQ(form.selectedGameTypesSettingString(), "Draft, ");
}
int main(int argc, char **argv)
{
qputenv("QT_QPA_PLATFORM", "offscreen");
QApplication app(argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View file

@ -5,6 +5,7 @@
#include <libcockatrice/game/zones/hand_zone_logic.h>
#include <libcockatrice/game/zones/view_zone_logic.h>
#include <libcockatrice/utility/card_ref.h>
#include <libcockatrice/utility/zone_names.h>
namespace
{
@ -105,3 +106,30 @@ TEST(CardZoneLogicTest, ReorganizeSignalFiresOnAdd)
EXPECT_EQ(reorganizeSpy.count(), 1);
}
TEST(CardZoneLogicTest, LibraryEdgeViewIsLimitedToOneEndOfTheLibrary)
{
HandZoneLogic deck(nullptr, QString::fromLatin1(ZoneNames::DECK), false, true, true);
HandZoneLogic grave(nullptr, QString::fromLatin1(ZoneNames::GRAVE), false, true, true);
ZoneViewZoneLogic fullDeckView(nullptr, &deck, -1, false, false, false);
EXPECT_FALSE(fullDeckView.isLibraryEdgeView());
EXPECT_FALSE(fullDeckView.showsTopOfLibrary());
EXPECT_FALSE(fullDeckView.showsBottomOfLibrary());
ZoneViewZoneLogic emptyDeckView(nullptr, &deck, 0, false, false, false);
EXPECT_FALSE(emptyDeckView.isLibraryEdgeView());
ZoneViewZoneLogic topView(nullptr, &deck, 3, false, false, false);
EXPECT_TRUE(topView.isLibraryEdgeView());
EXPECT_TRUE(topView.showsTopOfLibrary());
EXPECT_FALSE(topView.showsBottomOfLibrary());
ZoneViewZoneLogic bottomView(nullptr, &deck, 3, false, false, true);
EXPECT_TRUE(bottomView.isLibraryEdgeView());
EXPECT_FALSE(bottomView.showsTopOfLibrary());
EXPECT_TRUE(bottomView.showsBottomOfLibrary());
ZoneViewZoneLogic graveView(nullptr, &grave, 3, false, false, false);
EXPECT_FALSE(graveView.isLibraryEdgeView());
}

View file

@ -0,0 +1,310 @@
#include "interface/widgets/game_hosting/game_creation_options.h"
#include <gtest/gtest.h>
#include <libcockatrice/interfaces/interface_game_settings_provider.h>
#include <libcockatrice/protocol/pb/room_commands.pb.h>
#include <libcockatrice/protocol/pb/serverinfo_game.pb.h>
namespace
{
/**
* @brief The remembered settings a test hands to fromSettings.
*
* The fake cannot itself be an aggregate (it derives from a polymorphic interface), so the
* remembered values live in a GameCreationOptions member and the getters read them from
* there. That keeps the test data in one designated initializer.
*/
class FakeGameSettings : public IGameSettingsProvider
{
public:
explicit FakeGameSettings(const GameCreationOptions &_options = {}) : options(_options)
{
}
[[nodiscard]] QString getGameDescription() const override
{
return options.description;
}
[[nodiscard]] int getMaxPlayers() const override
{
return options.maxPlayers;
}
[[nodiscard]] QString getGameTypes() const override
{
return gameTypes;
}
[[nodiscard]] bool getOnlyBuddies() const override
{
return options.onlyBuddies;
}
[[nodiscard]] bool getOnlyRegistered() const override
{
return options.onlyRegistered;
}
[[nodiscard]] bool getSpectatorsAllowed() const override
{
return options.spectatorsAllowed;
}
[[nodiscard]] bool getSpectatorsNeedPassword() const override
{
return options.spectatorsNeedPassword;
}
[[nodiscard]] bool getSpectatorsCanTalk() const override
{
return options.spectatorsCanTalk;
}
[[nodiscard]] bool getSpectatorsCanSeeEverything() const override
{
return options.spectatorsSeeEverything;
}
[[nodiscard]] bool getCreateGameAsSpectator() const override
{
return options.joinAsSpectator;
}
[[nodiscard]] int getDefaultStartingLifeTotal() const override
{
return options.startingLifeTotal;
}
[[nodiscard]] bool getShareDecklistsOnLoad() const override
{
return options.shareDecklistsOnLoad;
}
[[nodiscard]] bool getShufflePlayers() const override
{
return options.shufflePlayers;
}
[[nodiscard]] bool getRememberGameSettings() const override
{
return false;
}
[[nodiscard]] bool getLocalGameRememberSettings() const override
{
return false;
}
[[nodiscard]] int getLocalGameMaxPlayers() const override
{
return 0;
}
[[nodiscard]] int getLocalGameStartingLifeTotal() const override
{
return 0;
}
GameCreationOptions options;
/// The legacy "Name, " list; it has no GameCreationOptions counterpart.
QString gameTypes;
};
} // namespace
TEST(GameCreationOptions, DefaultsMatchTheDialog)
{
const GameCreationOptions options;
EXPECT_TRUE(options.description.isEmpty());
EXPECT_TRUE(options.password.isEmpty());
EXPECT_EQ(options.maxPlayers, 2);
EXPECT_FALSE(options.onlyBuddies);
EXPECT_FALSE(options.onlyRegistered);
EXPECT_TRUE(options.spectatorsAllowed);
EXPECT_FALSE(options.spectatorsNeedPassword);
EXPECT_FALSE(options.spectatorsCanTalk);
EXPECT_FALSE(options.spectatorsSeeEverything);
EXPECT_FALSE(options.joinAsJudge);
EXPECT_FALSE(options.joinAsSpectator);
EXPECT_EQ(options.startingLifeTotal, 20);
EXPECT_FALSE(options.shareDecklistsOnLoad);
EXPECT_FALSE(options.shufflePlayers);
EXPECT_TRUE(options.gameTypeIds.isEmpty());
}
TEST(GameCreationOptions, EveryFieldMapsToTheCommand)
{
GameCreationOptions options;
options.description = "Some game";
options.password = "hunter2";
options.maxPlayers = 4;
options.onlyBuddies = true;
options.onlyRegistered = true;
options.spectatorsAllowed = false;
options.spectatorsNeedPassword = true;
options.spectatorsCanTalk = true;
options.spectatorsSeeEverything = true;
options.joinAsJudge = true;
options.joinAsSpectator = true;
options.startingLifeTotal = 40;
options.shareDecklistsOnLoad = true;
options.shufflePlayers = true;
const Command_CreateGame cmd = options.toCreateGameCommand();
EXPECT_EQ(cmd.description(), "Some game");
EXPECT_EQ(cmd.password(), "hunter2");
EXPECT_EQ(cmd.max_players(), 4);
EXPECT_TRUE(cmd.only_buddies());
EXPECT_TRUE(cmd.only_registered());
EXPECT_FALSE(cmd.spectators_allowed());
EXPECT_TRUE(cmd.spectators_need_password());
EXPECT_TRUE(cmd.spectators_can_talk());
EXPECT_TRUE(cmd.spectators_see_everything());
EXPECT_TRUE(cmd.join_as_judge());
EXPECT_TRUE(cmd.join_as_spectator());
EXPECT_EQ(cmd.starting_life_total(), 40);
EXPECT_TRUE(cmd.share_decklists_on_load());
EXPECT_TRUE(cmd.shuffle_players());
}
TEST(GameCreationOptions, GameTypeIdsKeepTheirOrder)
{
GameCreationOptions options;
options.gameTypeIds = {7, 2, 5};
const Command_CreateGame cmd = options.toCreateGameCommand();
ASSERT_EQ(cmd.game_type_ids_size(), 3);
EXPECT_EQ(cmd.game_type_ids(0), 7);
EXPECT_EQ(cmd.game_type_ids(1), 2);
EXPECT_EQ(cmd.game_type_ids(2), 5);
}
TEST(GameCreationOptions, EmptyGameTypeIdsProduceAnEmptyRepeatedField)
{
GameCreationOptions options;
const Command_CreateGame cmd = options.toCreateGameCommand();
EXPECT_EQ(cmd.game_type_ids_size(), 0);
}
TEST(GameCreationOptions, DescriptionWhitespaceIsSimplified)
{
GameCreationOptions options;
options.description = " a b ";
const Command_CreateGame cmd = options.toCreateGameCommand();
EXPECT_EQ(cmd.description(), "a b");
}
TEST(GameCreationOptions, FromSettingsCopiesEveryRememberedField)
{
const FakeGameSettings settings{GameCreationOptions{.description = "Remembered game",
.password = {},
.maxPlayers = 6,
.onlyBuddies = true,
.onlyRegistered = true,
.spectatorsAllowed = false,
.spectatorsNeedPassword = true,
.spectatorsCanTalk = true,
.spectatorsSeeEverything = true,
.joinAsJudge = false,
.joinAsSpectator = true,
.startingLifeTotal = 40,
.shareDecklistsOnLoad = true,
.shufflePlayers = true,
.gameTypeIds = {}}};
const GameCreationOptions options = GameCreationOptions::fromSettings(settings, {}, true);
EXPECT_EQ(options.description, "Remembered game");
EXPECT_EQ(options.maxPlayers, 6);
EXPECT_TRUE(options.onlyBuddies);
EXPECT_TRUE(options.onlyRegistered);
EXPECT_FALSE(options.spectatorsAllowed);
EXPECT_TRUE(options.spectatorsNeedPassword);
EXPECT_TRUE(options.spectatorsCanTalk);
EXPECT_TRUE(options.spectatorsSeeEverything);
EXPECT_TRUE(options.joinAsSpectator);
EXPECT_EQ(options.startingLifeTotal, 40);
EXPECT_TRUE(options.shareDecklistsOnLoad);
EXPECT_TRUE(options.shufflePlayers);
}
TEST(GameCreationOptions, FromSettingsDropsJoinRestrictionsForUnregisteredHosts)
{
FakeGameSettings settings;
settings.options.onlyBuddies = true;
settings.options.onlyRegistered = true;
const GameCreationOptions options = GameCreationOptions::fromSettings(settings, {}, false);
EXPECT_FALSE(options.onlyBuddies);
EXPECT_FALSE(options.onlyRegistered);
}
TEST(GameCreationOptions, FromSettingsMatchesGameTypesByTheLegacyNameList)
{
FakeGameSettings settings;
settings.gameTypes = "Draft, Commander, ";
const QMap<int, QString> gameTypes{{1, "Draft"}, {2, "Commander"}, {3, "Standard"}};
const GameCreationOptions options = GameCreationOptions::fromSettings(settings, gameTypes, true);
EXPECT_EQ(options.gameTypeIds, QList<int>({1, 2}));
}
TEST(GameCreationOptions, FromSettingsDoesNotMatchGameTypesWithoutTheLegacySeparator)
{
FakeGameSettings settings;
settings.gameTypes = "Draft Commander";
const QMap<int, QString> gameTypes{{1, "Draft"}, {2, "Commander"}};
const GameCreationOptions options = GameCreationOptions::fromSettings(settings, gameTypes, true);
EXPECT_TRUE(options.gameTypeIds.isEmpty());
}
TEST(GameCreationOptions, FromGameInfoCopiesTheVisibleFields)
{
ServerInfo_Game gameInfo;
gameInfo.set_description("Some game");
gameInfo.set_max_players(4);
gameInfo.set_only_buddies(true);
gameInfo.set_only_registered(true);
gameInfo.set_spectators_allowed(false);
gameInfo.set_spectators_need_password(true);
gameInfo.set_spectators_can_chat(true);
gameInfo.set_spectators_omniscient(true);
gameInfo.set_share_decklists_on_load(true);
gameInfo.set_shuffle_players(true);
gameInfo.add_game_types(2);
const QMap<int, QString> gameTypes{{1, "Draft"}, {2, "Commander"}};
const GameCreationOptions options = GameCreationOptions::fromGameInfo(gameInfo, gameTypes);
EXPECT_EQ(options.description, "Some game");
EXPECT_EQ(options.maxPlayers, 4);
EXPECT_TRUE(options.onlyBuddies);
EXPECT_TRUE(options.onlyRegistered);
EXPECT_FALSE(options.spectatorsAllowed);
EXPECT_TRUE(options.spectatorsNeedPassword);
EXPECT_TRUE(options.spectatorsCanTalk);
EXPECT_TRUE(options.spectatorsSeeEverything);
EXPECT_TRUE(options.shareDecklistsOnLoad);
EXPECT_TRUE(options.shufflePlayers);
EXPECT_EQ(options.gameTypeIds, QList<int>({2}));
}
TEST(GameCreationOptions, FromGameInfoLeavesUnshownFieldsAtDefaults)
{
ServerInfo_Game gameInfo;
gameInfo.set_max_players(3);
const GameCreationOptions options = GameCreationOptions::fromGameInfo(gameInfo, {});
EXPECT_TRUE(options.password.isEmpty());
EXPECT_EQ(options.startingLifeTotal, 20);
EXPECT_FALSE(options.joinAsJudge);
EXPECT_FALSE(options.joinAsSpectator);
}
TEST(GameCreationOptions, FromGameInfoIgnoresUnknownGameTypeIds)
{
ServerInfo_Game gameInfo;
gameInfo.add_game_types(7);
gameInfo.add_game_types(9);
const QMap<int, QString> gameTypes{{1, "Draft"}, {7, "Commander"}};
const GameCreationOptions options = GameCreationOptions::fromGameInfo(gameInfo, gameTypes);
EXPECT_EQ(options.gameTypeIds, QList<int>({7}));
}

View file

@ -3,8 +3,12 @@
#include <gtest/gtest.h>
#include <initializer_list>
#include <libcockatrice/network/client/abstract/latency_tracker.h>
#include <libcockatrice/rng/rng_abstract.h>
#include <string>
// Referenced by other translation units in the server_remote library.
RNG_Abstract *rng = nullptr;
TEST(LatencyTrackerTest, EmptyTrackerYieldsZeroedStats)
{
LatencyTracker tracker;

View file

@ -23,10 +23,14 @@
#include <libcockatrice/card/printing/exact_card.h>
#include <libcockatrice/card/set/card_set.h>
#include <libcockatrice/interfaces/noop_card_set_priority_controller.h>
#include <libcockatrice/rng/rng_abstract.h>
#include <libcockatrice/settings/paths_settings.h>
#include <qnamespace.h>
#include <string>
// Referenced by other translation units in the server_remote library.
RNG_Abstract *rng = nullptr;
namespace
{

View file

@ -1,6 +1,7 @@
#include "../../oracle/src/database_writer.h"
#include "../../oracle/src/oracleimporter.h"
#include "../../oracle/src/raw_json_scanner.h"
#include "../support/scoped_file_size_limit.h"
#include "libcockatrice/card/card_info.h"
#include "gtest/gtest.h"
@ -33,12 +34,6 @@
#include <string>
#include <utility>
#ifdef Q_OS_UNIX
#include <csignal>
#include <sys/resource.h>
#include <unistd.h>
#endif
class OracleImporterTest : public ::testing::Test
{
protected:
@ -1336,20 +1331,16 @@ TEST(OracleDatabaseWriter, ShortWriteKeepsPreviouslyInstalledDatabase)
original.close();
const QByteArray data = "<cockatrice_carddatabase version=\"4\"><!--" + QByteArray(16384, 'x') +
"--><cards/></cockatrice_carddatabase>";
// A real filesystem write failure, isolated in the death-test child so the
// process-wide file limit never affects other cases or the parent runner.
ASSERT_EXIT(
{
std::signal(SIGXFSZ, SIG_IGN);
struct rlimit limit;
limit.rlim_cur = 128;
limit.rlim_max = 128;
if (setrlimit(RLIMIT_FSIZE, &limit) != 0) {
_exit(2);
}
_exit(OracleDatabase::saveXml(path, data) ? 1 : 0);
},
::testing::ExitedWithCode(0), "");
// A real filesystem write failure: the soft file-size cap makes the writer's own
// flush fail without filling a disk. The cap is scoped rather than forked, because a
// death-test child under RLIMIT_FSIZE is killed by SIGSEGV on macOS.
test_support::ScopedFileSizeLimit fileSizeCap(128);
ASSERT_TRUE(fileSizeCap.isValid());
QString error;
EXPECT_FALSE(OracleDatabase::saveXml(path, data, &error));
EXPECT_FALSE(error.isEmpty());
ASSERT_TRUE(original.open(QIODevice::ReadOnly));
EXPECT_EQ(original.readAll(), "installed database");
}

View file

@ -0,0 +1,151 @@
#include "game/game_config.h"
#include "game/server_abstract_player.h"
#include "game/server_card.h"
#include "game/server_cardzone.h"
#include "game/server_game.h"
#include "movecard_tests/server_test_helpers.h"
#include "server_abstractuserinterface.h"
#include "server_response_containers.h"
#include "server_room.h"
#include <QCoreApplication>
#include <gtest/gtest.h>
#include <libcockatrice/deck_list/deck_list.h>
#include <libcockatrice/protocol/pb/command_deck_select.pb.h>
#include <libcockatrice/protocol/pb/command_reveal_cards.pb.h>
#include <libcockatrice/protocol/pb/event_reveal_cards.pb.h>
#include <libcockatrice/protocol/pb/game_event_container.pb.h>
#include <libcockatrice/rng/rng_abstract.h>
#include <libcockatrice/utility/zone_names.h>
#include <memory>
namespace
{
class FirstRng : public RNG_Abstract
{
unsigned int rand(int min, int) override
{
return min;
}
} firstRng;
class User : public Server_AbstractUserInterface
{
public:
User(Server *server, const char *name) : Server_AbstractUserInterface(server)
{
ServerInfo_User info;
info.set_name(name);
setUserInfo(info);
}
int getLastCommandTime() const override
{
return 0;
}
bool addSaidMessageSize(int) override
{
return true;
}
void sendProtocolItem(const Response &) override
{
}
void sendProtocolItem(const SessionEvent &) override
{
}
void sendProtocolItem(const RoomEvent &) override
{
}
void sendProtocolItem(const GameEventContainer &) override
{
}
};
class RandomReveal : public ::testing::Test
{
protected:
FakeServer server;
User owner{&server, "Owner"}, target{&server, "Target"};
Server_Room room{0, 0, "", "", "", "", false, "", {}, &server};
std::unique_ptr<Server_Game> game;
Server_AbstractPlayer *player;
Server_CardZone *hand;
ResponseContainer response{1};
void SetUp() override
{
GameConfig config;
config.creatorInfo = *owner.getUserInfo();
config.gameId = 1;
config.maxPlayers = 2;
config.shareDecklistsOnLoad = false;
game = std::make_unique<Server_Game>(config, &room);
game->addPlayer(&owner, response, {});
game->addPlayer(&target, response, {});
for (auto *participant : game->getPlayers()) {
GameCommand command;
command.MutableExtension(Command_DeckSelect::ext)
->set_deck(DeckList().writeToString_Native().toStdString());
GameEventStorage events;
ASSERT_EQ(participant->processGameCommand(command, response, events), Response::RespOk);
participant->setReadyStart(true);
}
game->startGameIfReady(false);
QCoreApplication::processEvents();
ASSERT_TRUE(game->getGameStarted());
player = game->getPlayer(0);
hand = player->getZones().value(ZoneNames::HAND);
for (int i = 0; i < 4; ++i) {
hand->insertCard(
new Server_Card({.name = "Twin", .providerId = QString::number(i)}, player->newCardId(), i, 0), -1, 0);
}
}
Response::ResponseCode reveal(int count, GameEventStorage &events)
{
GameCommand command;
auto *request = command.MutableExtension(Command_RevealRandomCards::ext);
request->set_zone_name(ZoneNames::HAND);
request->set_player_id(1);
request->set_number_of_cards(count);
return player->processGameCommand(command, response, events);
}
};
TEST_F(RandomReveal, DistinctPhysicalCardsArePrivateAndLeaveTheHandUnchanged)
{
const auto original = hand->getCards();
GameEventStorage events;
ASSERT_EQ(reveal(2, events), Response::RespOk);
ASSERT_EQ(events.getGameEventList().size(), 2);
EXPECT_EQ(events.getPrivatePlayerId(), 1);
const auto *privateEvent = events.getGameEventList().at(0);
EXPECT_EQ(privateEvent->getRecipients(), GameEventStorageItem::SendToPrivate);
const auto &cards = privateEvent->getGameEvent().GetExtension(Event_RevealCards::ext);
ASSERT_EQ(cards.cards_size(), 2);
EXPECT_NE(cards.cards(0).id(), cards.cards(1).id());
const auto *publicEvent = events.getGameEventList().at(1);
EXPECT_EQ(publicEvent->getRecipients(), GameEventStorageItem::SendToOthers);
const auto &notice = publicEvent->getGameEvent().GetExtension(Event_RevealCards::ext);
EXPECT_EQ(notice.cards_size(), 0);
EXPECT_EQ(notice.number_of_cards(), 2);
EXPECT_EQ(hand->getCards(), original);
}
TEST_F(RandomReveal, InvalidCountsDoNotQueueAnyReveal)
{
for (int count : {0, -1, 5}) {
GameEventStorage events;
EXPECT_NE(reveal(count, events), Response::RespOk);
EXPECT_TRUE(events.getGameEventList().isEmpty());
}
}
} // namespace
RNG_Abstract *rng = &firstRng;
int main(int argc, char **argv)
{
QCoreApplication application(argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View file

@ -8,9 +8,13 @@
#include <QString>
#include <gtest/gtest.h>
#include <libcockatrice/network/server/remote/game/server_counter.h>
#include <libcockatrice/rng/rng_abstract.h>
#include <limits>
#include <string>
// Referenced by other translation units in the server_remote library.
RNG_Abstract *rng = nullptr;
TEST(ServerCounter, IncrementDoesNotOverflow)
{
Server_Counter c(1, "test", color(), 10, std::numeric_limits<int>::max());

View file

@ -7,8 +7,12 @@
#include <climits>
#include <gtest/gtest.h>
#include <libcockatrice/network/server/remote/game/dump_zone_range.h>
#include <libcockatrice/rng/rng_abstract.h>
#include <vector>
// Referenced by other translation units in the server_remote library.
RNG_Abstract *rng = nullptr;
namespace
{
/// Indices a dump request resolves to, as the handler would walk them.

View file

@ -1,4 +1,5 @@
#include "client/network/update/card_spoiler/spoiler_file.h"
#include "support/scoped_file_size_limit.h"
#include <QDir>
#include <QFile>
@ -6,12 +7,6 @@
#include <QTemporaryDir>
#include <gtest/gtest.h>
#ifdef Q_OS_UNIX
#include <csignal>
#include <sys/resource.h>
#include <unistd.h>
#endif
namespace
{
class SpoilerFileTest : public ::testing::Test
@ -123,25 +118,16 @@ TEST_F(SpoilerFileTest, FileInParentPathReportsFailureWithoutModifyingIt)
#ifdef Q_OS_UNIX
TEST_F(SpoilerFileTest, ShortWriteLeavesExistingFileIntact)
{
// Limit only the child process: a real short write exercises QSaveFile's
// buffered flush failure without depending on disk capacity or file ownership.
const QByteArray changed = "<cockatrice_carddatabase version=\"4\"><!--" + QByteArray(100000, 'x') +
"--><cards/></cockatrice_carddatabase>";
EXPECT_EXIT(
{
struct rlimit limit;
if (getrlimit(RLIMIT_FSIZE, &limit) != 0) {
_exit(2);
}
limit.rlim_cur = 128;
if (setrlimit(RLIMIT_FSIZE, &limit) != 0) {
_exit(3);
}
std::signal(SIGXFSZ, SIG_IGN);
const auto result = save(changed);
_exit(result == SpoilerFile::SaveResult::Failed && !error.isEmpty() ? 0 : 1);
},
::testing::ExitedWithCode(0), "");
// A real short write exercises QSaveFile's buffered flush failure without depending
// on disk capacity. The cap is scoped rather than forked, because a death-test child
// under RLIMIT_FSIZE is killed by SIGSEGV on macOS.
test_support::ScopedFileSizeLimit fileSizeCap(128);
ASSERT_TRUE(fileSizeCap.isValid());
EXPECT_EQ(save(changed), SpoilerFile::SaveResult::Failed);
EXPECT_FALSE(error.isEmpty());
EXPECT_EQ(read(), original);
EXPECT_EQ(QDir(directory.path()).entryList(QDir::Files), QStringList{"spoiler.xml"});
}

View file

@ -0,0 +1,83 @@
#ifndef COCKATRICE_TEST_SCOPED_FILE_SIZE_LIMIT_H
#define COCKATRICE_TEST_SCOPED_FILE_SIZE_LIMIT_H
#include <QtGlobal>
#ifdef Q_OS_UNIX
#include <algorithm>
#include <csignal>
#include <sys/resource.h>
namespace test_support
{
/**
* @brief Caps how large a single file may grow, so a writer's short-write path is reachable.
*
* Lowering RLIMIT_FSIZE makes the next write past the cap fail with EFBIG instead of
* filling a filesystem, which is the only way to fail an install step mid-write without
* depending on free disk space or file ownership. Only the soft limit is lowered, so the
* destructor can hand the process back exactly as it found it: ctest runs one case per
* process, but a whole test binary must not carry the cap into its neighbours.
*
* Do not use this inside a gtest death test. A forked child under RLIMIT_FSIZE is killed
* by SIGSEGV on the macOS runners, while the same case passes on Linux, so the fork is
* what breaks - not the writer. The guard alone isolates the failure just as well.
*/
class ScopedFileSizeLimit
{
public:
explicit ScopedFileSizeLimit(rlim_t maxBytes)
{
if (getrlimit(RLIMIT_FSIZE, &previousLimit) != 0) {
return;
}
struct sigaction ignore = {};
ignore.sa_handler = SIG_IGN;
sigemptyset(&ignore.sa_mask);
if (sigaction(SIGXFSZ, &ignore, &previousAction) != 0) {
return;
}
actionSaved = true;
struct rlimit capped = previousLimit;
capped.rlim_cur = std::min(maxBytes, previousLimit.rlim_max);
if (setrlimit(RLIMIT_FSIZE, &capped) != 0) {
return;
}
active = true;
}
~ScopedFileSizeLimit()
{
if (active) {
setrlimit(RLIMIT_FSIZE, &previousLimit);
}
if (actionSaved) {
sigaction(SIGXFSZ, &previousAction, nullptr);
}
}
ScopedFileSizeLimit(const ScopedFileSizeLimit &) = delete;
ScopedFileSizeLimit &operator=(const ScopedFileSizeLimit &) = delete;
/**
* @brief Whether the cap is in force; a test that needs the failure must assert this.
*/
[[nodiscard]] bool isValid() const
{
return active;
}
private:
bool active = false;
bool actionSaved = false;
struct rlimit previousLimit = {};
struct sigaction previousAction = {};
};
} // namespace test_support
#endif // Q_OS_UNIX
#endif // COCKATRICE_TEST_SCOPED_FILE_SIZE_LIMIT_H

View file

@ -9,12 +9,16 @@
#include <QStringLiteral>
#include <QTemporaryDir>
#include <gtest/gtest.h>
#include <libcockatrice/rng/rng_abstract.h>
#include <string>
// Owned by main.cpp in the real application; pixel_map_generator.cpp references
// it, so the test binary needs a definition even though it never renders.
ThemeManager *themeManager = nullptr;
// Referenced by other translation units in the server_remote library.
RNG_Abstract *rng = nullptr;
namespace
{
const QString LEGACY = QStringLiteral("Default");