Skip to content

Commit f858b88

Browse files
Merge pull request #5076 from guoquanwu/hotfix/unit-test-port-unavailable
fix(test): fix port unavailability when running unit test
2 parents da2673c + ba8331b commit f858b88

4 files changed

Lines changed: 61 additions & 34 deletions

File tree

framework/src/test/java/org/tron/common/utils/PublicMethod.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import com.google.protobuf.ByteString;
44
import java.math.BigInteger;
5+
import java.util.Random;
6+
57
import org.tron.api.GrpcAPI;
68
import org.tron.api.WalletGrpc;
79
import org.tron.common.crypto.ECKey;
@@ -102,4 +104,12 @@ public static GrpcAPI.Return broadcastTransaction(
102104
}
103105
return response;
104106
}
107+
108+
public static int chooseRandomPort(int min, int max) {
109+
return new Random().nextInt(max - min + 1) + min;
110+
}
111+
112+
public static int chooseRandomPort() {
113+
return new Random().nextInt(65530 - 1024) + 1024;
114+
}
105115
}

framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import io.grpc.ManagedChannelBuilder;
55
import io.grpc.StatusRuntimeException;
66
import java.io.File;
7+
import java.util.concurrent.TimeUnit;
8+
79
import org.junit.After;
810
import org.junit.Assert;
911
import org.junit.Before;
@@ -20,6 +22,7 @@
2022
import org.tron.common.application.ApplicationFactory;
2123
import org.tron.common.application.TronApplicationContext;
2224
import org.tron.common.utils.FileUtil;
25+
import org.tron.common.utils.PublicMethod;
2326
import org.tron.core.ChainBaseManager;
2427
import org.tron.core.Constant;
2528
import org.tron.core.config.DefaultConfig;
@@ -38,7 +41,6 @@ public class LiteFnQueryGrpcInterceptorTest {
3841
private WalletGrpc.WalletBlockingStub blockingStubFull = null;
3942
private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null;
4043
private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubpBFT = null;
41-
private DatabaseGrpc.DatabaseBlockingStub databaseBlockingStub = null;
4244
private RpcApiService rpcApiService;
4345
private RpcApiServiceOnSolidity rpcApiServiceOnSolidity;
4446
private RpcApiServiceOnPBFT rpcApiServiceOnPBFT;
@@ -56,6 +58,9 @@ public class LiteFnQueryGrpcInterceptorTest {
5658
@Before
5759
public void init() {
5860
Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF);
61+
Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort());
62+
Args.getInstance().setRpcOnSolidityPort(PublicMethod.chooseRandomPort());
63+
Args.getInstance().setRpcOnPBFTPort(PublicMethod.chooseRandomPort());
5964
String fullnode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(),
6065
Args.getInstance().getRpcPort());
6166
String pBFTNode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(),
@@ -71,7 +76,6 @@ public void init() {
7176
blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelFull);
7277
blockingStubpBFT = WalletSolidityGrpc.newBlockingStub(channelpBFT);
7378
blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelFull);
74-
databaseBlockingStub = DatabaseGrpc.newBlockingStub(channelFull);
7579
rpcApiService = context.getBean(RpcApiService.class);
7680
rpcApiServiceOnSolidity = context.getBean(RpcApiServiceOnSolidity.class);
7781
rpcApiServiceOnPBFT = context.getBean(RpcApiServiceOnPBFT.class);
@@ -89,7 +93,13 @@ public void init() {
8993
* destroy the context.
9094
*/
9195
@After
92-
public void destroy() {
96+
public void destroy() throws InterruptedException {
97+
if (channelFull != null) {
98+
channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS);
99+
}
100+
if (channelpBFT != null) {
101+
channelpBFT.shutdown().awaitTermination(5, TimeUnit.SECONDS);
102+
}
93103
Args.clearParam();
94104
appTest.shutdownServices();
95105
appTest.shutdown();

framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import org.tron.common.application.ApplicationFactory;
2323
import org.tron.common.application.TronApplicationContext;
2424
import org.tron.common.utils.FileUtil;
25+
import org.tron.common.utils.PublicMethod;
2526
import org.tron.core.Constant;
2627
import org.tron.core.config.DefaultConfig;
2728
import org.tron.core.config.args.Args;
@@ -51,6 +52,9 @@ public class RpcApiAccessInterceptorTest {
5152
@BeforeClass
5253
public static void init() {
5354
Args.setParam(new String[] {"-d", dbPath}, Constant.TEST_CONF);
55+
Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort());
56+
Args.getInstance().setRpcOnSolidityPort(PublicMethod.chooseRandomPort());
57+
Args.getInstance().setRpcOnPBFTPort(PublicMethod.chooseRandomPort());
5458
String fullNode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(),
5559
Args.getInstance().getRpcPort());
5660
String solidityNode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(),

framework/src/test/java/org/tron/program/LiteFullNodeToolTest.java

Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
package org.tron.program;
22

3-
import com.google.protobuf.ByteString;
43
import io.grpc.ManagedChannel;
54
import io.grpc.ManagedChannelBuilder;
65
import java.io.File;
7-
import java.math.BigInteger;
86
import java.nio.file.Paths;
7+
import java.util.concurrent.TimeUnit;
8+
99
import org.junit.After;
1010
import org.junit.Before;
1111
import org.junit.Rule;
1212
import org.junit.Test;
1313
import org.junit.rules.ExpectedException;
1414
import org.slf4j.Logger;
1515
import org.slf4j.LoggerFactory;
16-
import org.tron.api.GrpcAPI;
1716
import org.tron.api.WalletGrpc;
1817
import org.tron.common.application.Application;
1918
import org.tron.common.application.ApplicationFactory;
@@ -23,22 +22,19 @@
2322
import org.tron.common.utils.FileUtil;
2423
import org.tron.common.utils.PublicMethod;
2524
import org.tron.common.utils.Utils;
26-
import org.tron.core.Wallet;
2725
import org.tron.core.config.DefaultConfig;
2826
import org.tron.core.config.args.Args;
2927
import org.tron.core.services.RpcApiService;
3028
import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity;
31-
import org.tron.protos.Protocol;
32-
import org.tron.protos.contract.BalanceContract;
3329
import org.tron.tool.litefullnode.LiteFullNodeTool;
34-
import stest.tron.wallet.common.client.utils.TransactionUtils;
3530

3631
public class LiteFullNodeToolTest {
3732

3833
private static final Logger logger = LoggerFactory.getLogger("Test");
3934

4035
private TronApplicationContext context;
4136
private WalletGrpc.WalletBlockingStub blockingStubFull = null;
37+
private ManagedChannel channelFull;
4238
private Application appTest;
4339

4440
private String databaseDir;
@@ -47,7 +43,7 @@ public class LiteFullNodeToolTest {
4743
public ExpectedException thrown = ExpectedException.none();
4844

4945

50-
private static final String DB_PATH = "output_lite_fn";
46+
private static String dbPath = "output_lite_fn";
5147

5248
/**
5349
* init logic.
@@ -63,7 +59,7 @@ public void startApp() {
6359

6460
String fullnode = String.format("%s:%d", "127.0.0.1",
6561
Args.getInstance().getRpcPort());
66-
ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullnode)
62+
channelFull = ManagedChannelBuilder.forTarget(fullnode)
6763
.usePlaintext(true)
6864
.build();
6965
blockingStubFull = WalletGrpc.newBlockingStub(channelFull);
@@ -86,59 +82,66 @@ public static void destroy(String dbPath) {
8682
/**
8783
* shutdown the fullnode.
8884
*/
89-
public void shutdown() {
85+
public void shutdown() throws InterruptedException {
86+
if (channelFull != null) {
87+
channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS);
88+
}
9089
appTest.shutdownServices();
9190
appTest.shutdown();
9291
context.destroy();
9392
}
9493

95-
@Before
9694
public void init() {
97-
destroy(DB_PATH); // delete if prev failed
98-
Args.setParam(new String[]{"-d", DB_PATH, "-w"}, "config-localtest.conf");
95+
destroy(dbPath); // delete if prev failed
96+
Args.setParam(new String[]{"-d", dbPath, "-w"}, "config-localtest.conf");
9997
// allow account root
10098
Args.getInstance().setAllowAccountStateRoot(1);
99+
Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort());
101100
databaseDir = Args.getInstance().getStorage().getDbDirectory();
102101
// init dbBackupConfig to avoid NPE
103102
Args.getInstance().dbBackupConfig = DbBackupConfig.getInstance();
104103
}
105104

106105
@After
107106
public void clear() {
108-
destroy(DB_PATH);
107+
destroy(dbPath);
109108
Args.clearParam();
109+
dbPath = "output_lite_fn";
110110
}
111111

112112
@Test
113-
public void testToolsWithLevelDB() {
113+
public void testToolsWithLevelDB() throws InterruptedException {
114114
logger.info("testToolsWithLevelDB start");
115115
testTools("LEVELDB", 1);
116116
}
117117

118118
@Test
119-
public void testToolsWithLevelDBV2() {
119+
public void testToolsWithLevelDBV2() throws InterruptedException {
120120
logger.info("testToolsWithLevelDB start");
121121
testTools("LEVELDB", 2);
122122
}
123123

124124
@Test
125-
public void testToolsWithRocksDB() {
125+
public void testToolsWithRocksDB() throws InterruptedException {
126126
logger.info("testToolsWithRocksDB start");
127127
testTools("ROCKSDB", 1);
128128
}
129129

130-
private void testTools(String dbType, int checkpointVersion) {
130+
private void testTools(String dbType, int checkpointVersion)
131+
throws InterruptedException {
132+
dbPath = String.format("%s_%s_%d", dbPath, dbType, System.currentTimeMillis());
133+
init();
131134
final String[] argsForSnapshot =
132135
new String[]{"-o", "split", "-t", "snapshot", "--fn-data-path",
133-
DB_PATH + File.separator + databaseDir, "--dataset-path",
134-
DB_PATH};
136+
dbPath + File.separator + databaseDir, "--dataset-path",
137+
dbPath};
135138
final String[] argsForHistory =
136139
new String[]{"-o", "split", "-t", "history", "--fn-data-path",
137-
DB_PATH + File.separator + databaseDir, "--dataset-path",
138-
DB_PATH};
140+
dbPath + File.separator + databaseDir, "--dataset-path",
141+
dbPath};
139142
final String[] argsForMerge =
140-
new String[]{"-o", "merge", "--fn-data-path", DB_PATH + File.separator + databaseDir,
141-
"--dataset-path", DB_PATH + File.separator + "history"};
143+
new String[]{"-o", "merge", "--fn-data-path", dbPath + File.separator + databaseDir,
144+
"--dataset-path", dbPath + File.separator + "history"};
142145
Args.getInstance().getStorage().setDbEngine(dbType);
143146
Args.getInstance().getStorage().setCheckpointVersion(checkpointVersion);
144147
LiteFullNodeTool.setRecentBlks(3);
@@ -149,7 +152,7 @@ private void testTools(String dbType, int checkpointVersion) {
149152
// stop the node
150153
shutdown();
151154
// delete tran-cache
152-
FileUtil.deleteDir(Paths.get(DB_PATH, databaseDir, "trans-cache").toFile());
155+
FileUtil.deleteDir(Paths.get(dbPath, databaseDir, "trans-cache").toFile());
153156
// generate snapshot
154157
LiteFullNodeTool.main(argsForSnapshot);
155158
// start fullnode
@@ -161,18 +164,18 @@ private void testTools(String dbType, int checkpointVersion) {
161164
// generate history
162165
LiteFullNodeTool.main(argsForHistory);
163166
// backup original database to database_bak
164-
File database = new File(Paths.get(DB_PATH, databaseDir).toString());
165-
if (!database.renameTo(new File(Paths.get(DB_PATH, databaseDir + "_bak").toString()))) {
167+
File database = new File(Paths.get(dbPath, databaseDir).toString());
168+
if (!database.renameTo(new File(Paths.get(dbPath, databaseDir + "_bak").toString()))) {
166169
throw new RuntimeException(
167170
String.format("rename %s to %s failed", database.getPath(),
168-
Paths.get(DB_PATH, databaseDir).toString()));
171+
Paths.get(dbPath, databaseDir).toString()));
169172
}
170173
// change snapshot to the new database
171-
File snapshot = new File(Paths.get(DB_PATH, "snapshot").toString());
172-
if (!snapshot.renameTo(new File(Paths.get(DB_PATH, databaseDir).toString()))) {
174+
File snapshot = new File(Paths.get(dbPath, "snapshot").toString());
175+
if (!snapshot.renameTo(new File(Paths.get(dbPath, databaseDir).toString()))) {
173176
throw new RuntimeException(
174177
String.format("rename snapshot to %s failed",
175-
Paths.get(DB_PATH, databaseDir).toString()));
178+
Paths.get(dbPath, databaseDir).toString()));
176179
}
177180
// start and validate the snapshot
178181
startApp();

0 commit comments

Comments
 (0)