Skip to content
Merged
5 changes: 5 additions & 0 deletions framework/src/test/java/org/tron/common/BaseMethodTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.tron.common.application.Application;
import org.tron.common.application.ApplicationFactory;
import org.tron.common.application.TronApplicationContext;
import org.tron.common.utils.PeerManagerStateResetter;
import org.tron.core.ChainBaseManager;
import org.tron.core.config.DefaultConfig;
import org.tron.core.config.args.Args;
Expand Down Expand Up @@ -42,6 +43,9 @@ public abstract class BaseMethodTest {
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();

@Rule
public final VMConfigRule vmConfigRule = new VMConfigRule();

protected TronApplicationContext context;
protected Application appT;
protected Manager dbManager;
Expand All @@ -57,6 +61,7 @@ protected String configFile() {

@Before
public final void initContext() throws IOException {
PeerManagerStateResetter.reset();
String[] baseArgs = new String[]{
"--output-directory", temporaryFolder.newFolder().toString()};
String[] allArgs = mergeArgs(baseArgs, extraArgs());
Expand Down
11 changes: 11 additions & 0 deletions framework/src/test/java/org/tron/common/BaseTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
import lombok.extern.slf4j.Slf4j;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
Expand All @@ -17,6 +19,7 @@
import org.tron.common.crypto.ECKey;
import org.tron.common.parameter.CommonParameter;
import org.tron.common.utils.Commons;
import org.tron.common.utils.PeerManagerStateResetter;
import org.tron.common.utils.Sha256Hash;
import org.tron.consensus.base.Param;
import org.tron.core.ChainBaseManager;
Expand Down Expand Up @@ -64,6 +67,9 @@ public abstract class BaseTest {
@ClassRule
public static final TemporaryFolder temporaryFolder = new TemporaryFolder();

@Rule
public final VMConfigRule vmConfigRule = new VMConfigRule();

@Resource
protected Manager dbManager;
@Resource
Expand All @@ -75,6 +81,11 @@ public abstract class BaseTest {
private static Application appT1;


@Before
public void resetPeerManagerState() {
PeerManagerStateResetter.reset();
}

@PostConstruct
private void prepare() {
appT1 = appT;
Expand Down
52 changes: 52 additions & 0 deletions framework/src/test/java/org/tron/common/VMConfigRule.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package org.tron.common;

import java.lang.reflect.Field;
import org.junit.rules.ExternalResource;
import org.tron.common.parameter.CommonParameter;
import org.tron.core.vm.config.ConfigLoader;
import org.tron.core.vm.config.VMConfig;

/**
* Restores VM flags after each test, including failed setup and assertion paths.
*
* <p>Snapshotting enumerates {@link VMConfig.Snapshot} fields reflectively, so any static flag
* not mirrored there is outside this rule's protection: when adding a static flag to
* {@link VMConfig} or {@link ConfigLoader}, it must also be mirrored into
* {@code VMConfig.Snapshot} (before/after save and restore) or it will leak across tests.
*
* <p>This is a method-level rule: the baseline is captured before every test method, so global
* flags written from class-level {@code @BeforeClass} code are not covered — such classes must
* add their own {@code @AfterClass} to reset them manually (a leaked London hard-fork flag from
* class-level setup is an instance of exactly this gap).
*/
public class VMConfigRule extends ExternalResource {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NIT] VMConfigRule covers method scope only; class-scope VM flag leaks still rely on manual afterClass lists

As a @rule (method-level), this does not wrap @BeforeClass/static blocks. AllowTvmCompatibleEvmTest sets 6 VM flags in @BeforeClass and still restores them via a hand-maintained @afterclass list — and the missing initAllowTvmLondon(0) entry fixed in this very PR is proof that the manual-list mechanism keeps leaking. The 13 VMTestBase subclasses inherit the rule, but any class-scope flag mutation remains uncovered.

Suggestion: add a @ClassRule-level VM snapshot restore on VMTestBase (or BaseTest/BaseMethodTest) so @BeforeClass leaks are covered automatically; alternatively, state explicitly in this class's javadoc that class-scope mutations are not covered and document the recommended pattern. Fine as a follow-up, does not block.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented in the VMConfigRule javadoc: the Snapshot enumeration blind spot (static flags added to VMConfig/ConfigLoader must be mirrored into VMConfig.Snapshot or they leak across tests) and the method-level-rule boundary (@BeforeClass writes are outside the baseline and need a manual @AfterClass reset — the missed London flag was exactly this gap, fixed in 9c8dac0). A @ClassRule-based variant that would cover class-level setup mechanically is noted as a follow-up; kept out of this PR to avoid churning shared test infra further.

Pushed as 9f4e65d.


private VMConfig.Snapshot savedSnapshot;
private boolean savedLoaderDisabled;
private boolean savedHardFork;
private boolean savedTrace;

@Override
protected void before() throws Exception {
Field global = VMConfig.class.getDeclaredField("globalSnapshot");
global.setAccessible(true);
VMConfig.Snapshot current = (VMConfig.Snapshot) global.get(null);
savedSnapshot = new VMConfig.Snapshot();
// init* methods mutate the snapshot in place, so saving only its reference is insufficient.
for (Field flag : VMConfig.Snapshot.class.getFields()) {
flag.set(savedSnapshot, flag.get(current));
}
savedLoaderDisabled = ConfigLoader.disable;
savedHardFork = CommonParameter.ENERGY_LIMIT_HARD_FORK;
savedTrace = VMConfig.vmTrace();
VMConfig.clearLocalSnapshot();
}

@Override
protected void after() {
VMConfig.setGlobalSnapshot(savedSnapshot);
ConfigLoader.disable = savedLoaderDisabled;
VMConfig.initVmHardFork(savedHardFork);
VMConfig.setVmTrace(savedTrace);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.tron.common.backup;

import io.netty.channel.Channel;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
Expand All @@ -9,8 +10,8 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import org.junit.After;
import org.junit.Assert;
Expand All @@ -25,6 +26,7 @@
import org.tron.common.backup.socket.UdpEvent;
import org.tron.common.parameter.CommonParameter;
import org.tron.common.utils.PublicMethod;
import org.tron.common.utils.ReflectUtils;
import org.tron.core.config.args.Args;
import org.tron.core.config.args.InetUtil;

Expand All @@ -34,7 +36,8 @@ public class BackupManagerTest {
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private BackupManager manager;
private BackupServer backupServer;
private BiFunction<String, Boolean, InetAddress> savedLookup;
private BiFunction<String, Boolean, InetAddress> previousDnsLookup;
private boolean backupServerClosed;

@Before
public void setUp() throws Exception {
Expand All @@ -43,13 +46,36 @@ public void setUp() throws Exception {
CommonParameter.getInstance().setBackupPort(PublicMethod.chooseRandomPort());
manager = new BackupManager();
backupServer = new BackupServer(manager);
savedLookup = InetUtil.dnsLookup;
previousDnsLookup = InetUtil.dnsLookup;
}

@After
public void tearDown() {
InetUtil.dnsLookup = savedLookup;
public void tearDown() throws Exception {
List<Throwable> errors = new ArrayList<>();
Channel channel = null;
if (backupServer != null) {
try {
channel = BackupTestUtils.getChannel(backupServer);
} catch (Throwable t) {
errors.add(t);
}
}
if (!backupServerClosed && backupServer != null) {
BackupTestUtils.runQuietly(errors, backupServer::close);
}
if (manager != null) {
BackupTestUtils.runQuietly(errors, manager::stop);
}
Channel captured = channel;
BackupTestUtils.runQuietly(errors, () -> {
if (captured != null) {
Assert.assertFalse("backup channel must close", captured.isOpen());
}
BackupTestUtils.assertExecutorsTerminated(manager, backupServer);
});
InetUtil.dnsLookup = previousDnsLookup;
Args.clearParam();
BackupTestUtils.throwIfAnyError(errors);
}

@Test
Expand Down Expand Up @@ -121,7 +147,7 @@ public void test() throws Exception {
}

@Test
public void testSendKeepAliveMessage() throws Exception {
public void testBackupServerLifecycleDuringKeepAliveInterval() throws Exception {
CommonParameter parameter = CommonParameter.getInstance();
parameter.setBackupPriority(8);
List<String> members = new ArrayList<>();
Expand All @@ -134,21 +160,19 @@ public void testSendKeepAliveMessage() throws Exception {

Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.MASTER);
backupServer.initServer();
awaitBackupServerReady();
manager.init();

Thread.sleep(parameter.getKeepAliveInterval() + 1000);//test send KeepAliveMessage

field = manager.getClass().getDeclaredField("executorService");
field.setAccessible(true);
ScheduledExecutorService executorService = (ScheduledExecutorService) field.get(manager);
executorService.shutdown();

Field field2 = backupServer.getClass().getDeclaredField("executor");
field2.setAccessible(true);
ExecutorService executorService2 = (ExecutorService) field2.get(backupServer);
executorService2.shutdown();
long keepAliveDeadline = System.nanoTime()
+ TimeUnit.MILLISECONDS.toNanos(parameter.getKeepAliveInterval() + 1000L);
BackupTestUtils.awaitCondition("keep-alive interval",
() -> System.nanoTime() >= keepAliveDeadline);

Assert.assertEquals(BackupManager.BackupStatusEnum.INIT, manager.getStatus());
Channel channel = BackupTestUtils.getChannel(backupServer);
backupServer.close();
backupServerClosed = true;
Assert.assertFalse("backup channel must close", channel.isOpen());
BackupTestUtils.assertExecutorsTerminated(manager, backupServer);
}

// ===== domain-handling tests for init() =====
Expand All @@ -161,8 +185,8 @@ public void testInitResolvesDomainsToMembers() throws Exception {
InetUtil.dnsLookup = (host, ipv4) ->
("node.example.com".equals(host) && ipv4) ? resolved : null;
manager.init();
Set<String> members = getField(manager, "members");
Map<String, String> cache = getField(manager, "domainIpCache");
Set<String> members = ReflectUtils.getFieldValue(manager, "members");
Map<String, String> cache = ReflectUtils.getFieldValue(manager, "domainIpCache");
Assert.assertTrue(members.contains("1.2.3.4"));
Assert.assertEquals("1.2.3.4", cache.get("node.example.com"));
manager.stop();
Expand All @@ -174,8 +198,8 @@ public void testInitSkipsUnresolvableDomain() throws Exception {
Collections.singletonList("bad.invalid.domain"));
InetUtil.dnsLookup = (host, ipv4) -> null;
manager.init();
Set<String> members = getField(manager, "members");
Map<String, String> cache = getField(manager, "domainIpCache");
Set<String> members = ReflectUtils.getFieldValue(manager, "members");
Map<String, String> cache = ReflectUtils.getFieldValue(manager, "domainIpCache");
Assert.assertTrue("unresolvable domain should be silently dropped", members.isEmpty());
Assert.assertTrue(cache.isEmpty());
manager.stop();
Expand All @@ -190,7 +214,7 @@ public void testInitSkipsDomainResolvingToLocalIp() throws Exception {
InetUtil.dnsLookup = (host, ipv4) ->
("self.local.host".equals(host) && ipv4) ? selfAddr : null;
manager.init();
Set<String> members = getField(manager, "members");
Set<String> members = ReflectUtils.getFieldValue(manager, "members");
Assert.assertFalse("domain resolving to local IP should not be in members",
members.contains(localIp));
manager.stop();
Expand All @@ -200,8 +224,8 @@ public void testInitSkipsDomainResolvingToLocalIp() throws Exception {

@Test(timeout = 5000)
public void testRefreshMemberIpsIpChanged() throws Exception {
Set<String> members = getField(manager, "members");
Map<String, String> cache = getField(manager, "domainIpCache");
Set<String> members = ReflectUtils.getFieldValue(manager, "members");
Map<String, String> cache = ReflectUtils.getFieldValue(manager, "domainIpCache");
members.add("1.1.1.1");
cache.put("peer.tron.network", "1.1.1.1");

Expand All @@ -216,8 +240,8 @@ public void testRefreshMemberIpsIpChanged() throws Exception {

@Test(timeout = 5000)
public void testRefreshMemberIpsIpUnchanged() throws Exception {
Set<String> members = getField(manager, "members");
Map<String, String> cache = getField(manager, "domainIpCache");
Set<String> members = ReflectUtils.getFieldValue(manager, "members");
Map<String, String> cache = ReflectUtils.getFieldValue(manager, "domainIpCache");
members.add("1.1.1.1");
cache.put("peer.tron.network", "1.1.1.1");

Expand All @@ -231,8 +255,8 @@ public void testRefreshMemberIpsIpUnchanged() throws Exception {

@Test(timeout = 5000)
public void testRefreshMemberIpsDnsFailure() throws Exception {
Set<String> members = getField(manager, "members");
Map<String, String> cache = getField(manager, "domainIpCache");
Set<String> members = ReflectUtils.getFieldValue(manager, "members");
Map<String, String> cache = ReflectUtils.getFieldValue(manager, "domainIpCache");
members.add("1.1.1.1");
cache.put("peer.tron.network", "1.1.1.1");

Expand All @@ -242,16 +266,18 @@ public void testRefreshMemberIpsDnsFailure() throws Exception {
Assert.assertEquals("1.1.1.1", cache.get("peer.tron.network"));
}

@SuppressWarnings("unchecked")
private <T> T getField(Object obj, String name) throws Exception {
Field f = obj.getClass().getDeclaredField(name);
f.setAccessible(true);
return (T) f.get(obj);
}

private void invokeRefreshMemberIps(BackupManager mgr) throws Exception {
Method m = mgr.getClass().getDeclaredMethod("refreshMemberIps");
m.setAccessible(true);
m.invoke(mgr);
}

private void awaitBackupServerReady() throws Exception {
BackupTestUtils.awaitCondition("backup channel to become active",
() -> BackupTestUtils.getChannel(backupServer) != null
&& BackupTestUtils.getChannel(backupServer).isActive());
BackupTestUtils.awaitCondition("backup message handler assignment",
() -> ReflectUtils.getFieldObject(manager, "messageHandler") != null);
}

}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package org.tron.common.backup;

import io.netty.channel.Channel;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
Expand All @@ -23,6 +25,8 @@ public class BackupServerTest {
@Rule
public Timeout globalTimeout = Timeout.seconds(60);
private BackupServer backupServer;
private BackupManager backupManager;
private boolean backupServerClosed;

@Before
public void setUp() throws Exception {
Expand All @@ -32,21 +36,39 @@ public void setUp() throws Exception {
List<String> members = new ArrayList<>();
members.add("127.0.0.2");
CommonParameter.getInstance().setBackupMembers(members);
BackupManager backupManager = new BackupManager();
backupManager = new BackupManager();
backupManager.init();
backupServer = new BackupServer(backupManager);
}

@After
public void tearDown() {
backupServer.close();
public void tearDown() throws Exception {
List<Throwable> errors = new ArrayList<>();
if (!backupServerClosed && backupServer != null) {
BackupTestUtils.runQuietly(errors, backupServer::close);
}
if (backupManager != null) {
BackupTestUtils.runQuietly(errors, backupManager::stop);
}
BackupTestUtils.runQuietly(errors,
() -> BackupTestUtils.assertExecutorsTerminated(backupManager, backupServer));
Args.clearParam();
BackupTestUtils.throwIfAnyError(errors);
}

@Test(timeout = 60_000)
public void test() throws InterruptedException {
public void test() throws Exception {
backupServer.initServer();
// wait for the server to start so channel is assigned before close() is called
Thread.sleep(1000);
BackupTestUtils.awaitCondition("backup channel to become active",
() -> BackupTestUtils.getChannel(backupServer) != null
&& BackupTestUtils.getChannel(backupServer).isActive());
Channel channel = BackupTestUtils.getChannel(backupServer);
Assert.assertTrue("backup channel must be active after startup", channel.isActive());

backupServer.close();
backupServerClosed = true;

Assert.assertFalse("backup channel must close", channel.isOpen());
BackupTestUtils.assertExecutorsTerminated(backupManager, backupServer);
}
}
Loading
Loading