Compare commits

...
4 changed files with 628 additions and 30 deletions

No files matched your search

@@ -27,6 +27,34 @@ public class ConfigVoteSites extends YMLFile {
private VotingPluginMain plugin;
/** Internal scalar reads retain the already selected native section and file policy. */
private ScalarReads scalarReads(String site) {
return new ScalarReads(getData(site), isIgnoreCase());
}
private record ScalarReads(ConfigurationSection section, boolean folded) {
private String key(String leaf) {
// Leaf names are constants. Preserve native path semantics for unusual separators.
if (folded && leaf.indexOf(section.getRoot().options().pathSeparator()) < 0) {
var keys = section.getKeys(false);
// The null fallback checks configured values even when keys include defaults.
if (section.get(leaf, null) != null) return leaf;
for (String candidate : keys) {
if (candidate.equalsIgnoreCase(leaf) && section.get(candidate, null) != null) return candidate;
}
}
return leaf;
}
String getString(String leaf) { return section.getString(key(leaf)); }
String getString(String leaf, String fallback) { return section.getString(key(leaf), fallback); }
int getInt(String leaf) { return section.getInt(key(leaf)); }
int getInt(String leaf, int fallback) { return section.getInt(key(leaf), fallback); }
double getDouble(String leaf, double fallback) { return section.getDouble(key(leaf), fallback); }
boolean getBoolean(String leaf) { return section.getBoolean(key(leaf)); }
boolean getBoolean(String leaf, boolean fallback) { return section.getBoolean(key(leaf), fallback); }
boolean isString(String leaf) { return section.isString(key(leaf)); }
}
/**
* Constructs a new ConfigVoteSites.
*
@@ -194,7 +222,7 @@ public class ConfigVoteSites extends YMLFile {
* @return the display name
*/
public String getDisplayName(String site) {
return getData(site).getString("Name");
return scalarReads(site).getString("Name");
}
/**
@@ -226,7 +254,7 @@ public class ConfigVoteSites extends YMLFile {
* @return the permission to view
*/
public String getPermissionToView(String siteName) {
return getData(siteName).getString("PermissionToView", "");
return scalarReads(siteName).getString("PermissionToView", "");
}
/**
@@ -236,7 +264,7 @@ public class ConfigVoteSites extends YMLFile {
* @return the priority
*/
public int getPriority(String siteName) {
return getData(siteName).getInt("Priority");
return scalarReads(siteName).getInt("Priority");
}
/**
@@ -266,7 +294,7 @@ public class ConfigVoteSites extends YMLFile {
* @return the service site
*/
public String getServiceSite(String siteName) {
return getData(siteName).getString("ServiceSite");
return scalarReads(siteName).getString("ServiceSite");
}
/**
@@ -276,7 +304,7 @@ public class ConfigVoteSites extends YMLFile {
* @return the vote delay
*/
public ParsedDuration getVoteDelay(String site) {
ConfigurationSection sec = getData(site);
ScalarReads sec = scalarReads(site);
// NEW FORMAT (string)
if (sec.isString("VoteDelay")) {
@@ -299,7 +327,7 @@ public class ConfigVoteSites extends YMLFile {
* @return the vote delay daily hour
*/
public int getVoteDelayDailyHour(String siteName) {
return getData(siteName).getInt("VoteDelayDailyHour", 0);
return scalarReads(siteName).getInt("VoteDelayDailyHour", 0);
}
/**
@@ -309,7 +337,7 @@ public class ConfigVoteSites extends YMLFile {
* @return the vote site enabled
*/
public boolean getVoteSiteEnabled(String siteName) {
return getData(siteName).getBoolean("Enabled");
return scalarReads(siteName).getBoolean("Enabled");
}
/**
@@ -340,7 +368,8 @@ public class ConfigVoteSites extends YMLFile {
* @return true if rewards should be given offline
*/
public boolean getVoteSiteGiveOffline(String site) {
return getData(site).getBoolean("ForceOffline", getData(site).getBoolean("GiveOffline"));
ScalarReads reads = scalarReads(site);
return reads.getBoolean("ForceOffline", reads.getBoolean("GiveOffline"));
}
/**
@@ -350,7 +379,7 @@ public class ConfigVoteSites extends YMLFile {
* @return true if the site is hidden
*/
public boolean getVoteSiteHidden(String siteName) {
return getData(siteName).getBoolean("Hidden");
return scalarReads(siteName).getBoolean("Hidden");
}
/**
@@ -360,7 +389,7 @@ public class ConfigVoteSites extends YMLFile {
* @return true if can vote check should be ignored
*/
public boolean getVoteSiteIgnoreCanVote(String siteName) {
return getData(siteName).getBoolean("IgnoreCanVote");
return scalarReads(siteName).getBoolean("IgnoreCanVote");
}
/**
@@ -370,7 +399,7 @@ public class ConfigVoteSites extends YMLFile {
* @return true if vote delay resets daily
*/
public boolean getVoteSiteResetVoteDelayDaily(String siteName) {
return getData(siteName).getBoolean("VoteDelayDaily");
return scalarReads(siteName).getBoolean("VoteDelayDaily");
}
/**
@@ -474,7 +503,7 @@ public class ConfigVoteSites extends YMLFile {
* @return the vote URL
*/
public String getVoteURL(String siteName) {
return getData(siteName).getString("VoteURL", "");
return scalarReads(siteName).getString("VoteURL", "");
}
/**
@@ -484,7 +513,7 @@ public class ConfigVoteSites extends YMLFile {
* @return true if should wait until vote delay
*/
public boolean getWaitUntilVoteDelay(String siteName) {
return getData(siteName).getBoolean("WaitUntilVoteDelay", false);
return scalarReads(siteName).getBoolean("WaitUntilVoteDelay", false);
}
/**
@@ -154,7 +154,7 @@ public final class ControlInspectionService {
for (int index = 0; index < configuredNames.size(); index++) {
ConfigurationSection site = root == null ? null : root.getConfigurationSection(configuredNames.get(index));
if (site == null) continue;
String service = site.getString("ServiceSite", "");
String service = scalarReads(site).getString("ServiceSite", "");
if (service.isBlank()) continue;
configuredServices.add(lower(service));
if (index < MAX_ROWS) displayedServices.add(lower(service));
@@ -179,20 +179,23 @@ public final class ControlInspectionService {
for (String name : configuredNames.stream().limit(MAX_ROWS).toList()) {
ConfigurationSection site = root == null ? null : root.getConfigurationSection(name);
if (site == null) continue;
String fullService = site.getString("ServiceSite", "");
ScalarReads reads = scalarReads(site);
String fullService = reads.getString("ServiceSite", "");
String service = safe(fullService, 64);
ServiceHealth health = logged.get(lower(fullService));
Object enabledValue = reads.get("Enabled");
boolean enabled = enabledValue == null || Boolean.TRUE.equals(enabledValue);
JsonObject row = new JsonObject();
row.addProperty("key", safe(name, 64));
row.addProperty("displayName", safe(site.getString("Name", name), 100));
row.addProperty("displayName", safe(reads.getString("Name", name), 100));
row.addProperty("serviceSite", service);
row.addProperty("enabled", site.getBoolean("Enabled", true));
row.addProperty("hidden", site.getBoolean("Hidden", false));
row.addProperty("priority", site.getInt("Priority", 5));
row.addProperty("voteDelay", safe(String.valueOf(site.get("VoteDelay", "24h")), 80));
row.addProperty("enabled", enabled);
row.addProperty("hidden", reads.getBoolean("Hidden", false));
row.addProperty("priority", reads.getInt("Priority", 5));
row.addProperty("voteDelay", safe(String.valueOf(reads.get("VoteDelay", "24h")), 80));
row.addProperty("hasRewards", hasRewardConfiguration(site));
if (voteLogReadable) addHealth(row, health);
row.addProperty("status", !site.getBoolean("Enabled", true) ? "DISABLED"
row.addProperty("status", !enabled ? "DISABLED"
: fullService.isBlank() ? "SERVICE_SITE_MISSING"
: !voteLoggingAvailable ? "VOTE_LOG_UNAVAILABLE"
: !voteLogReadable ? "VOTE_LOG_UNREADABLE"
@@ -439,9 +442,9 @@ public final class ControlInspectionService {
.getConfigurationSection("VoteSites." + key);
result.addProperty("key", safe(key, 64));
if (section != null) {
result.addProperty("displayName", safe(section.getString("Name", key), 100));
result.addProperty("configuredServiceSite", safe(section.getString("ServiceSite", ""), 64));
result.addProperty("enabled", section.getBoolean("Enabled", true));
result.addProperty("displayName", safe(scalarReads(section).getString("Name", key), 100));
result.addProperty("configuredServiceSite", safe(scalarReads(section).getString("ServiceSite", ""), 64));
result.addProperty("enabled", scalarReads(section).getBoolean("Enabled", true));
}
}
result.addProperty("wouldAutoCreate", unconfigured && plugin.getConfigFile().isAutoCreateVoteSites());
@@ -559,21 +562,22 @@ public final class ControlInspectionService {
for (String name : allConfiguredVoteSiteNames().stream().limit(MAX_ROWS).toList()) {
ConfigurationSection site = root.getConfigurationSection(name);
if (site == null) continue;
ScalarReads reads = scalarReads(site);
JsonObject item = new JsonObject();
if (name.length() > 80 || name.codePoints().anyMatch(Character::isISOControl)) { siteComplete = false; continue; }
item.addProperty("name", name);
String service = site.getString("ServiceSite", "");
String service = reads.getString("ServiceSite", "");
if (service.length() <= 160 && service.codePoints().noneMatch(Character::isISOControl)) item.addProperty("serviceSite", service);
else siteComplete = false;
if (!site.contains("Enabled") || site.isBoolean("Enabled")) item.addProperty("enabled", plugin.getConfigVoteSites().getVoteSiteEnabled(name));
if (!reads.contains("Enabled") || reads.isBoolean("Enabled")) item.addProperty("enabled", reads.getBoolean("Enabled"));
else { siteComplete = false; NetworkHealthConfigFacts.invalid(result, "VoteSites.Enabled"); }
if (site.isBoolean("AutoCreated")) item.addProperty("autoCreated", site.getBoolean("AutoCreated"));
if (reads.isBoolean("AutoCreated")) item.addProperty("autoCreated", reads.getBoolean("AutoCreated"));
item.addProperty("hasRewards", hasRewardConfiguration(site));
try {
NetworkHealthConfigFacts.addDelay(item, site.get("VoteDelay"), site.get("VoteDelayMin"),
plugin.getConfigVoteSites().getVoteDelay(name));
NetworkHealthConfigFacts.addDelay(item, reads.get("VoteDelay"), reads.get("VoteDelayMin"),
reads.voteDelay());
} catch (IllegalArgumentException failure) { item.addProperty("delayValid", false); }
String url = site.getString("VoteURL", "");
String url = reads.getString("VoteURL", "");
item.addProperty("voteUrlState", url.isBlank() ? "BLANK"
: url.toLowerCase(Locale.ROOT).contains("example") ? "EXAMPLE" : validVoteUrl(url) ? "VALID" : "INVALID");
sites.add(item);
@@ -610,6 +614,43 @@ public final class ControlInspectionService {
? normalized : "INVALID";
}
private ScalarReads scalarReads(ConfigurationSection section) {
return new ScalarReads(section, plugin.getConfigVoteSites().isIgnoreCase());
}
/** Inspection predicates and values share the file's policy without wrapping native sections. */
private record ScalarReads(ConfigurationSection section, boolean folded) {
private String key(String leaf) {
if (folded && leaf.indexOf(section.getRoot().options().pathSeparator()) < 0) {
var keys = section.getKeys(false);
// The null fallback checks configured values even when keys include defaults.
if (section.get(leaf, null) != null) return leaf;
for (String candidate : keys) {
if (candidate.equalsIgnoreCase(leaf) && section.get(candidate, null) != null) return candidate;
}
}
return leaf;
}
String getString(String leaf, String fallback) { return section.getString(key(leaf), fallback); }
boolean getBoolean(String leaf) { return section.getBoolean(key(leaf)); }
boolean getBoolean(String leaf, boolean fallback) { return section.getBoolean(key(leaf), fallback); }
int getInt(String leaf, int fallback) { return section.getInt(key(leaf), fallback); }
boolean contains(String leaf) { return section.contains(key(leaf)); }
boolean isBoolean(String leaf) { return section.isBoolean(key(leaf)); }
Object get(String leaf) { return section.get(key(leaf)); }
Object get(String leaf, Object fallback) { return section.get(key(leaf), fallback); }
private com.bencodez.simpleapi.time.ParsedDuration voteDelay() {
if (section.isString(key("VoteDelay"))) {
return com.bencodez.simpleapi.time.ParsedDuration.parse(
section.getString(key("VoteDelay")), java.util.concurrent.TimeUnit.HOURS);
}
double hours = section.getDouble(key("VoteDelay"), 0);
double minutes = section.getDouble(key("VoteDelayMin"), 0);
return com.bencodez.simpleapi.time.ParsedDuration.ofMillis(
(long) (hours * 60 * 60 * 1000) + (long) (minutes * 60 * 1000));
}
}
private List<String> allConfiguredVoteSiteNames() {
ConfigurationSection root = plugin.getConfigVoteSites().getData().getConfigurationSection("VoteSites");
if (root == null) return List.of();
@@ -0,0 +1,219 @@
package com.bencodez.votingplugin.tests.control;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.List;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.jupiter.api.Test;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.config.ConfigVoteSites;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
class VoteSiteInspectionScalarTest {
private record Fixture(VotingPluginMain plugin, ConfigVoteSites sites, YamlConfiguration yaml) {
JsonObject inspect(String kind) {
return ControlInspectionServiceAccess.create(plugin).inspect(JsonParser.parseString(
"{\"kind\":\"" + kind + "\",\"filters\":{}}").getAsJsonObject()).getAsJsonObject("result");
}
}
private Fixture fixture(boolean folded) {
VotingPluginMain plugin = mock(VotingPluginMain.class, RETURNS_DEEP_STUBS);
ConfigVoteSites sites = mock(ConfigVoteSites.class, CALLS_REAL_METHODS);
YamlConfiguration yaml = new YamlConfiguration();
doReturn(yaml).when(sites).getData();
doReturn(folded).when(sites).isIgnoreCase();
when(plugin.getConfigVoteSites()).thenReturn(sites);
YamlConfiguration config = new YamlConfiguration();
when(plugin.getConfigFile().getData()).thenReturn(config);
when(plugin.getBungeeSettings().getData()).thenReturn(config);
when(plugin.getVoteSiteManager().getVoteSites()).thenReturn(List.of());
when(plugin.getServerData().getServiceSitesReadOnly()).thenReturn(List.of("route.example"));
when(plugin.getVoteLogMysqlTable()).thenReturn(null);
when(plugin.getServer().getPluginManager().getPlugins()).thenReturn(new org.bukkit.plugin.Plugin[0]);
return new Fixture(plugin, sites, yaml);
}
@Test void healthUsesFoldedServiceForConfiguredAndDetectedMatchingOnlyWhenEnabled() {
for (boolean folded : new boolean[] {false, true}) {
Fixture f = fixture(folded);
f.yaml.set("VoteSites.Example.servicesite", "route.example");
String before = f.yaml.saveToString();
JsonObject result = f.inspect("vote-site-health");
var site = result.getAsJsonArray("sites").get(0).getAsJsonObject();
assertEquals(folded ? "route.example" : "", site.get("serviceSite").getAsString());
assertEquals(folded ? 0 : 1, result.getAsJsonArray("detectedUnconfiguredServices").size());
assertEquals(before, f.yaml.saveToString());
verify(f.sites, never()).saveData();
}
}
@Test void networkPredicatesAndValuesResolveSameLeafAndKeepInvalidEvidence() {
for (boolean folded : new boolean[] {false, true}) {
Fixture f = fixture(folded);
f.yaml.set("VoteSites.Example.servicesite", "route.example");
f.yaml.set("VoteSites.Example.enabled", true);
f.yaml.set("VoteSites.Example.autocreated", false);
f.yaml.set("VoteSites.Example.votedelay", 2);
f.yaml.set("VoteSites.Example.voteurl", "https://voting.example/vote");
JsonObject site = f.inspect("network-health").getAsJsonArray("voteSites").get(0).getAsJsonObject();
assertEquals(folded, site.get("enabled").getAsBoolean());
assertEquals(folded ? "route.example" : "", site.get("serviceSite").getAsString());
assertEquals(folded ? "EXAMPLE" : "BLANK", site.get("voteUrlState").getAsString());
assertEquals(folded, site.has("autoCreated"));
f.yaml.set("VoteSites.Example.enabled", "invalid boolean");
JsonObject invalid = f.inspect("network-health");
if (folded) {
assertFalse(invalid.getAsJsonArray("voteSites").get(0).getAsJsonObject().has("enabled"));
assertFalse(invalid.get("voteSitesComplete").getAsBoolean());
}
}
}
@Test void resolutionRetainsTrueDefaultDistinctFromConfigGetterFalse() {
Fixture f = fixture(true);
f.yaml.set("VoteSites.Example.name", "Folded label");
f.yaml.set("VoteSites.Example.servicesite", "route.example");
when(f.plugin.getVoteSiteManager().getVoteSiteName(anyBoolean(), anyString(), anyString())).thenReturn("Example");
when(f.plugin.getVoteSiteManager().resolveVoteSite(anyString(), anyBoolean())).thenReturn(null);
when(f.plugin.getVoteSiteManager().getResolver().getConfiguredVoteSiteName(anyString(), anyString()))
.thenReturn("Example");
JsonObject result = ControlInspectionServiceAccess.create(f.plugin).inspect(JsonParser.parseString(
"{\"kind\":\"vote-site-resolution\",\"filters\":{\"serviceSite\":\"route.example\",\"includeDisabled\":\"true\"}}")
.getAsJsonObject()).getAsJsonObject("result");
assertEquals("Folded label", result.get("displayName").getAsString());
assertEquals("route.example", result.get("configuredServiceSite").getAsString());
assertTrue(result.get("enabled").getAsBoolean());
assertFalse(f.sites.getVoteSiteEnabled("Example"));
assertFalse(result.get("sideEffects").getAsBoolean());
}
@Test void networkKeepsNativeParentWhenRootFoldedLookupWouldSelectSibling() {
for (boolean lowerFirst : new boolean[] {false, true}) {
Fixture f = fixture(true);
for (String name : lowerFirst ? new String[] {"site", "Site"} : new String[] {"Site", "site"}) {
boolean upper = name.equals("Site");
f.yaml.set("VoteSites." + name + ".servicesite", upper ? "upper.example" : "lower.example");
f.yaml.set("VoteSites." + name + ".enabled", upper);
f.yaml.set("VoteSites." + name + ".votedelay", upper ? 2 : 5);
}
ConfigVoteSites nativeRootConfig = mock(ConfigVoteSites.class, CALLS_REAL_METHODS);
nativeRootConfig.setData(f.yaml);
nativeRootConfig.setIgnoreCase(true);
when(f.plugin.getConfigVoteSites()).thenReturn(nativeRootConfig);
String before = f.yaml.saveToString();
var rows = f.inspect("network-health").getAsJsonArray("voteSites");
assertEquals(2, rows.size());
for (var element : rows) {
var row = element.getAsJsonObject();
boolean upper = row.get("name").getAsString().equals("Site");
assertEquals(upper, row.get("enabled").getAsBoolean());
assertEquals(upper ? "upper.example" : "lower.example", row.get("serviceSite").getAsString());
assertEquals(upper ? 2 : 5, row.get("delayHours").getAsInt());
}
assertEquals(before, f.yaml.saveToString());
}
}
@Test void healthEnabledAndStatusAgreeWithCanonicalKey() {
for (boolean enabled : new boolean[] {false, true}) {
Fixture f = fixture(true);
f.yaml.set("VoteSites.Example.ServiceSite", "route.example");
f.yaml.set("VoteSites.Example.enabled", !enabled);
f.yaml.set("VoteSites.Example.Enabled", enabled);
JsonObject row = f.inspect("vote-site-health").getAsJsonArray("sites").get(0).getAsJsonObject();
assertEquals(enabled, f.sites.getVoteSiteEnabled("Example"));
assertEquals(enabled, row.get("enabled").getAsBoolean());
assertEquals(enabled ? "VOTE_LOG_UNAVAILABLE" : "DISABLED", row.get("status").getAsString());
f.yaml.set("VoteSites.Example.Enabled", null);
f.yaml.set("VoteSites.Example.enabled", false);
row = f.inspect("vote-site-health").getAsJsonArray("sites").get(0).getAsJsonObject();
assertFalse(row.get("enabled").getAsBoolean());
assertEquals("DISABLED", row.get("status").getAsString());
}
}
@Test void networkCanonicalWrongTypeIsNotReplacedByValidFoldedSibling() {
Fixture f = fixture(true);
f.yaml.set("VoteSites.Example.enabled", true);
f.yaml.set("VoteSites.Example.Enabled", "invalid boolean");
f.yaml.set("VoteSites.Example.servicesite", "lower.example");
f.yaml.set("VoteSites.Example.ServiceSite", "canonical.example");
JsonObject result = f.inspect("network-health");
JsonObject row = result.getAsJsonArray("voteSites").get(0).getAsJsonObject();
assertFalse(row.has("enabled"));
assertFalse(result.get("voteSitesComplete").getAsBoolean());
assertEquals("canonical.example", row.get("serviceSite").getAsString());
assertFalse(f.sites.getVoteSiteEnabled("Example"));
}
@Test void inspectionDefaultsDoNotHideConfiguredFoldedValuesWhenCopied() {
for (boolean copyDefaults : new boolean[] {false, true}) {
Fixture f = fixture(true);
f.yaml.set("VoteSites.Example.servicesite", "configured.example");
f.yaml.set("VoteSites.Example.enabled", false);
f.yaml.addDefault("VoteSites.Example.ServiceSite", "default.example");
f.yaml.addDefault("VoteSites.Example.Enabled", true);
f.yaml.options().copyDefaults(copyDefaults);
JsonObject row = f.inspect("vote-site-health").getAsJsonArray("sites").get(0).getAsJsonObject();
assertEquals("configured.example", row.get("serviceSite").getAsString());
assertFalse(row.get("enabled").getAsBoolean());
assertEquals("DISABLED", row.get("status").getAsString());
row = f.inspect("network-health").getAsJsonArray("voteSites").get(0).getAsJsonObject();
assertEquals("configured.example", row.get("serviceSite").getAsString());
assertFalse(row.get("enabled").getAsBoolean());
}
}
@Test void healthScalarFieldsFollowFilePolicyAndKeepRawDelayFormat() {
for (boolean folded : new boolean[] {false, true}) {
for (boolean lower : new boolean[] {false, true}) {
for (Object rawDelay : new Object[] {"2h", 2, true}) {
Fixture f = fixture(folded);
var site = f.yaml.createSection("VoteSites.Example");
site.set("ServiceSite", "route.example");
site.set(lower ? "name" : "Name", "Public label");
site.set(lower ? "hidden" : "Hidden", true);
site.set(lower ? "priority" : "Priority", 7);
site.set(lower ? "votedelay" : "VoteDelay", rawDelay);
String before = f.yaml.saveToString();
JsonObject row = f.inspect("vote-site-health").getAsJsonArray("sites").get(0).getAsJsonObject();
boolean found = folded || !lower;
assertEquals(found ? "Public label" : "Example", row.get("displayName").getAsString());
assertEquals(found, row.get("hidden").getAsBoolean());
assertEquals(found ? 7 : 5, row.get("priority").getAsInt());
assertEquals(found ? String.valueOf(rawDelay) : "24h", row.get("voteDelay").getAsString());
assertEquals(before, f.yaml.saveToString());
}
}
}
}
@Test void healthInvalidEnabledIsDisabledButAbsentKeepsTrueFallback() {
for (boolean folded : new boolean[] {false, true}) {
Fixture f = fixture(folded);
var site = f.yaml.createSection("VoteSites.Example");
site.set("ServiceSite", "route.example");
for (Object invalid : new Object[] {"invalid boolean", 0, List.of(true)}) {
site.set(folded ? "enabled" : "Enabled", invalid);
JsonObject row = f.inspect("vote-site-health").getAsJsonArray("sites").get(0).getAsJsonObject();
assertFalse(f.sites.getVoteSiteEnabled("Example"));
assertFalse(row.get("enabled").getAsBoolean());
assertEquals("DISABLED", row.get("status").getAsString());
}
site.set("enabled", true);
site.set("Enabled", "invalid boolean");
JsonObject row = f.inspect("vote-site-health").getAsJsonArray("sites").get(0).getAsJsonObject();
assertFalse(row.get("enabled").getAsBoolean(), "invalid canonical key must not select valid folded sibling");
site.set("enabled", null);
site.set("Enabled", null);
row = f.inspect("vote-site-health").getAsJsonArray("sites").get(0).getAsJsonObject();
assertTrue(row.get("enabled").getAsBoolean());
assertEquals("VOTE_LOG_UNAVAILABLE", row.get("status").getAsString());
}
}
}
@@ -0,0 +1,309 @@
package com.bencodez.votingplugin.tests.votesite;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.jupiter.api.Test;
import com.bencodez.votingplugin.VotingPluginMain;
import com.bencodez.votingplugin.config.ConfigVoteSites;
import com.bencodez.votingplugin.votesites.VoteSiteRegistry;
import com.bencodez.votingplugin.votesites.VoteSiteResolver;
import com.bencodez.votingplugin.votesites.VoteSiteValidator;
class VoteSiteScalarReadTest {
private ConfigVoteSites config(YamlConfiguration yaml, boolean folded) {
ConfigVoteSites config = mock(ConfigVoteSites.class, CALLS_REAL_METHODS);
doReturn(yaml).when(config).getData();
doReturn(folded).when(config).isIgnoreCase();
return config;
}
@Test void foldedLeafReadsUseAlreadySelectedNativeParent() {
for (boolean lowerFirst : new boolean[] {false, true}) {
YamlConfiguration yaml = new YamlConfiguration();
for (String parent : lowerFirst ? new String[] {"site", "Site"} : new String[] {"Site", "site"}) {
yaml.set("VoteSites." + parent + ".name", parent + " label");
yaml.set("VoteSites." + parent + ".servicesite", parent + ".example");
}
ConfigVoteSites config = config(yaml, true);
assertEquals("Site label", config.getDisplayName("Site"));
assertEquals("site label", config.getDisplayName("site"));
assertSame(yaml.getConfigurationSection("VoteSites.Site"), config.getData("Site"));
}
}
@Test void realResolverFindsFoldedServiceAndDisplayLeavesWithoutCreating() {
YamlConfiguration yaml = new YamlConfiguration();
yaml.set("VoteSites.Example.servicesite", "voting.example");
yaml.set("VoteSites.Example.name", "Example label");
ConfigVoteSites config = config(yaml, true);
VotingPluginMain plugin = mock(VotingPluginMain.class);
when(plugin.getConfigVoteSites()).thenReturn(config);
VoteSiteResolver resolver = new VoteSiteResolver(plugin, new VoteSiteRegistry(), new VoteSiteValidator(plugin));
assertEquals("Example", resolver.getConfiguredVoteSiteName("voting.example"));
assertEquals("Example", resolver.getConfiguredVoteSiteName("Example label"));
assertNull(resolver.getConfiguredVoteSiteName("unknown.example"));
verify(config, never()).tryGenerateVoteSite(anyString());
verify(config, never()).tryAutoGenerateVoteSite(anyString());
}
@Test void strictReadsAndNativeDefaultFallbackRemainUnchanged() {
YamlConfiguration yaml = new YamlConfiguration();
yaml.set("VoteSites.Example.name", "folded label");
yaml.addDefault("VoteSites.Example.Name", "native default");
ConfigVoteSites config = config(yaml, false);
assertEquals("native default", config.getDisplayName("Example"));
assertFalse(config.getVoteSiteEnabled("Example"));
assertEquals("", config.getVoteURL("Example"));
}
@Test void scalarDefaultsTypesAliasesAndLeafOrderMatchNativeGetters() {
for (boolean folded : new boolean[] {false, true}) {
YamlConfiguration yaml = new YamlConfiguration();
var site = yaml.createSection("VoteSites.Example");
yaml.addDefault("VoteSites.Example.Name", "default label");
ConfigVoteSites config = config(yaml, folded);
assertEquals("default label", config.getDisplayName("Example"));
assertEquals("", config.getPermissionToView("Example"));
assertEquals(0, config.getPriority("Example"));
assertNull(config.getServiceSite("Example"));
assertEquals(0, config.getVoteDelayDailyHour("Example"));
assertFalse(config.getVoteSiteEnabled("Example"));
assertFalse(config.getVoteSiteGiveOffline("Example"));
assertFalse(config.getVoteSiteHidden("Example"));
assertFalse(config.getVoteSiteIgnoreCanVote("Example"));
assertFalse(config.getVoteSiteResetVoteDelayDaily("Example"));
assertFalse(config.getWaitUntilVoteDelay("Example"));
site.set("GiveOffline", true);
site.set("ForceOffline", false);
assertFalse(config.getVoteSiteGiveOffline("Example"));
site.set("Priority", "not a number");
assertEquals(site.getInt("Priority"), config.getPriority("Example"));
site.set("Name", null);
site.set("name", "first");
site.set("Name", "second");
assertEquals("second", config.getDisplayName("Example"));
}
}
@Test void nativeIdentitiesExactWritesAndCapturedPolicySurviveReadsAndToggle() {
YamlConfiguration yaml = new YamlConfiguration();
var site = yaml.createSection("VoteSites.Example");
var item = site.createSection("Item");
var rewards = site.createSection("Rewards");
var lowerRewards = site.createSection("rewards");
site.set("name", "folded label");
ConfigVoteSites config = mock(ConfigVoteSites.class, CALLS_REAL_METHODS);
config.setData(yaml);
config.setIgnoreCase(true);
var root = config.getData();
var created = root.createSection("Created");
String before = yaml.saveToString();
assertEquals("folded label", config.getDisplayName("Example"));
assertSame(site, root.get("VoteSites.Example"));
assertSame(site, config.getData("Example"));
assertSame(site, config.getData("Example"));
assertSame(yaml, root.getConfigurationSection(""));
assertSame(yaml.getConfigurationSection("VoteSites"), site.getParent());
assertSame(created, yaml.getConfigurationSection("Created"));
assertSame(item, config.getItem("Example"));
assertSame(rewards, site.getValues(false).get("Rewards"));
assertSame(lowerRewards, site.getValues(false).get("rewards"));
assertEquals(before, yaml.saveToString());
rewards.set("Exact", 1);
lowerRewards.set("Exact", 2);
assertEquals(1, site.getInt("Rewards.Exact"));
assertEquals(2, site.getInt("rewards.Exact"));
config.setIgnoreCase(false);
assertSame(yaml, config.getData());
assertNull(config.getDisplayName("Example"));
config.setIgnoreCase(true);
assertEquals("folded label", config.getDisplayName("Example"));
}
@Test void separatorLeafAndMissingSectionKeepNativeBehavior() {
YamlConfiguration yaml = new YamlConfiguration();
yaml.options().pathSeparator('a');
var site = yaml.createSection("VoteSites.Example");
site.set("Name", "native path");
ConfigVoteSites config = config(yaml, true);
assertEquals(site.getString("Name"), config.getDisplayName("Example"));
doReturn(null).when(config).getData("Missing");
assertThrows(NullPointerException.class, () -> config.getDisplayName("Missing"));
}
@Test void allScalarGettersRetainCanonicalAndFoldedTypeContracts() {
for (boolean folded : new boolean[] {false, true}) {
for (boolean lower : new boolean[] {false, true}) {
YamlConfiguration yaml = new YamlConfiguration();
var site = yaml.createSection("VoteSites.Example");
String[] keys = {"Name", "PermissionToView", "Priority", "ServiceSite", "VoteDelayDailyHour",
"Enabled", "GiveOffline", "Hidden", "IgnoreCanVote", "VoteDelayDaily", "VoteURL", "WaitUntilVoteDelay"};
Object[] values = {"label", "vote.example", 7, "route.example", 3, true, true, true, true, true,
"https://voting.example/vote", true};
for (int i = 0; i < keys.length; i++) site.set(lower ? keys[i].toLowerCase(java.util.Locale.ROOT) : keys[i], values[i]);
ConfigVoteSites config = config(yaml, folded);
boolean found = folded || !lower;
assertEquals(found ? "label" : null, config.getDisplayName("Example"));
assertEquals(found ? "vote.example" : "", config.getPermissionToView("Example"));
assertEquals(found ? 7 : 0, config.getPriority("Example"));
assertEquals(found ? "route.example" : null, config.getServiceSite("Example"));
assertEquals(found ? 3 : 0, config.getVoteDelayDailyHour("Example"));
assertEquals(found, config.getVoteSiteEnabled("Example"));
assertEquals(found, config.getVoteSiteGiveOffline("Example"));
assertEquals(found, config.getVoteSiteHidden("Example"));
assertEquals(found, config.getVoteSiteIgnoreCanVote("Example"));
assertEquals(found, config.getVoteSiteResetVoteDelayDaily("Example"));
assertEquals(found, config.getWaitUntilVoteDelay("Example"));
assertEquals(found ? "https://voting.example/vote" : "", config.getVoteURL("Example"));
site.set(lower ? "forceoffline" : "ForceOffline", false);
assertFalse(config.getVoteSiteGiveOffline("Example"));
}
}
}
@Test void durationStringAndNumericAliasUseSameSelectedLeafPolicy() {
YamlConfiguration yaml = new YamlConfiguration();
var site = yaml.createSection("VoteSites.Example");
ConfigVoteSites config = config(yaml, true);
site.set("votedelay", "2h");
assertEquals(7_200_000L,
config.getVoteDelay("Example").getMillis());
site.set("votedelay", 1);
site.set("votedelaymin", 30);
assertEquals(5_400_000L,
config.getVoteDelay("Example").getMillis());
site.set("votedelay", "nonsense");
assertTrue(assertDoesNotThrow(() -> config.getVoteDelay("Example")).isEmpty());
}
@Test void exactConfigWritesStillSelectNativeRewardsAndNeverFoldLeafTargets() {
YamlConfiguration yaml = new YamlConfiguration();
var site = yaml.createSection("VoteSites.Example");
site.set("Rewards.Exact", 1);
site.set("rewards.Exact", 2);
ConfigVoteSites config = config(yaml, true);
doNothing().when(config).saveData();
config.set("Example", "Rewards.Exact", 3);
assertEquals(3, site.getInt("Rewards.Exact"));
assertEquals(2, site.getInt("rewards.Exact"));
verify(config).saveData();
}
@Test void nativeReloadKeepsCapturedPolicyAndDoesNotRewriteFile(
@org.junit.jupiter.api.io.TempDir java.nio.file.Path folder) throws Exception {
var file = folder.resolve("VoteSites.yml");
String bytes = "VoteSites:\n Example:\n name: before\n";
java.nio.file.Files.writeString(file, bytes);
ConfigVoteSites config = mock(ConfigVoteSites.class, CALLS_REAL_METHODS);
var field = com.bencodez.simpleapi.file.YMLFile.class.getDeclaredField("dFile");
field.setAccessible(true);
field.set(config, file.toFile());
config.setIgnoreCase(true);
config.reloadData();
assertEquals("before", config.getDisplayName("Example"));
assertEquals(bytes, java.nio.file.Files.readString(file));
bytes = bytes.replace("before", "after");
java.nio.file.Files.writeString(file, bytes);
config.reloadData();
assertEquals("after", config.getDisplayName("Example"));
assertTrue(config.isIgnoreCase());
assertEquals(bytes, java.nio.file.Files.readString(file));
config.setIgnoreCase(false);
config.reloadData();
assertNull(config.getDisplayName("Example"));
assertEquals(bytes, java.nio.file.Files.readString(file));
}
@Test void scalarSetterReadbackRemainsEffectiveWithExistingLowercaseLeaf() {
for (boolean folded : new boolean[] {false, true}) {
for (boolean lower : new boolean[] {false, true}) {
YamlConfiguration yaml = new YamlConfiguration();
yaml.set("VoteSites.Example." + (lower ? "enabled" : "Enabled"), true);
ConfigVoteSites config = config(yaml, folded);
doNothing().when(config).saveData();
config.setEnabled("Example", false);
assertEquals(Boolean.FALSE, yaml.get("VoteSites.Example.Enabled", null), "native exact setter wrote false");
assertFalse(config.getVoteSiteEnabled("Example"), "setter/readback must agree");
if (lower) assertTrue(yaml.getBoolean("VoteSites.Example.enabled"), "exact writes retain sibling");
}
}
}
@Test void canonicalKeysWinWithoutRewritingEarlierFoldedSiblings() {
YamlConfiguration yaml = new YamlConfiguration();
var site = yaml.createSection("VoteSites.Example");
site.set("name", "lower");
site.set("Name", "canonical");
site.set("priority", 7);
site.set("Priority", "invalid number");
ConfigVoteSites config = config(yaml, true);
String before = yaml.saveToString();
assertEquals("canonical", config.getDisplayName("Example"));
assertEquals(0, config.getPriority("Example"), "wrong canonical type must not select a folded sibling");
assertEquals(before, yaml.saveToString());
site.set("Name", null);
site.set("NAME", "later folded");
assertEquals("lower", config.getDisplayName("Example"));
site.set("name", null);
assertEquals("later folded", config.getDisplayName("Example"));
}
@Test void nativeDefaultIsFallbackRatherThanAnExplicitCanonicalLeaf() {
for (boolean copyDefaults : new boolean[] {false, true}) {
YamlConfiguration yaml = new YamlConfiguration();
var site = yaml.createSection("VoteSites.Example");
yaml.addDefault("VoteSites.Example.Name", "native default");
yaml.options().copyDefaults(copyDefaults);
site.set("name", "configured lower");
ConfigVoteSites config = config(yaml, true);
assertNull(site.get("Name", null), "native explicit-value lookup excludes defaults");
assertEquals("configured lower", config.getDisplayName("Example"));
site.set("name", null);
assertEquals("native default", config.getDisplayName("Example"));
}
}
@Test void scalarSetterFamilyRetainsExactWritesAndCanonicalReadback() {
for (boolean folded : new boolean[] {false, true}) {
YamlConfiguration yaml = new YamlConfiguration();
var site = yaml.createSection("VoteSites.Example");
site.set("name", "previous");
site.set("servicesite", "previous.example");
site.set("priority", 9);
site.set("forceoffline", true);
site.set("votedelay", "9h");
site.set("voteurl", "previous");
site.set("votedelaydailyhour", 9);
site.set("votedelaydaily", true);
ConfigVoteSites config = config(yaml, folded);
doNothing().when(config).saveData();
config.setDisplayName("Example", "current");
config.setServiceSite("Example", "current.example");
config.setPriority("Example", 3);
config.setForceOffline("Example", false);
config.setVoteDelay("Example", "2h");
config.setVoteURL("Example", "https://voting.example/vote");
config.setVoteDelayDailyHour("Example", 2);
config.setVoteDelayDaily("Example", false);
assertEquals("current", config.getDisplayName("Example"));
assertEquals("current.example", config.getServiceSite("Example"));
assertEquals(3, config.getPriority("Example"));
assertFalse(config.getVoteSiteGiveOffline("Example"));
assertEquals(7_200_000L, config.getVoteDelay("Example").getMillis());
assertEquals("https://voting.example/vote", config.getVoteURL("Example"));
assertEquals(2, config.getVoteDelayDailyHour("Example"));
assertFalse(config.getVoteSiteResetVoteDelayDaily("Example"));
assertEquals("previous", site.getString("name"));
assertEquals("previous.example", site.getString("servicesite"));
assertEquals(9, site.getInt("priority"));
assertTrue(site.getBoolean("forceoffline"));
assertEquals("9h", site.getString("votedelay"));
assertEquals("previous", site.getString("voteurl"));
assertEquals(9, site.getInt("votedelaydailyhour"));
assertTrue(site.getBoolean("votedelaydaily"));
}
}
}