Skip to content

Commit 0c67142

Browse files
test
Did a bunch of cleanup on several connection tests to improve stability and use more recent integration test features. ClientOnlyConnectionTests reduced the transport connection timeout and increased the timeout helper. ConnectionApprovalTimeoutTests needed to have the server and client timeout values vary depending upon the test type. PeerDisconnectCallbackTests needed to trap for the peer disconnecting.
1 parent 610e2d6 commit 0c67142

File tree

4 files changed

+101
-75
lines changed

4 files changed

+101
-75
lines changed

com.unity.netcode.gameobjects/Tests/Runtime/ClientOnlyConnectionTests.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@ public void Setup()
3232
// Default is 1000ms per connection attempt and 60 connection attempts (60s)
3333
// Currently there is no easy way to set these values other than in-editor
3434
var unityTransport = m_NetworkManagerGameObject.AddComponent<UnityTransport>();
35-
unityTransport.ConnectTimeoutMS = 1000;
35+
unityTransport.ConnectTimeoutMS = 500;
3636
unityTransport.MaxConnectAttempts = 1;
37-
m_TimeoutHelper = new TimeoutHelper(2);
37+
m_TimeoutHelper = new TimeoutHelper(4);
3838
m_ClientNetworkManager.NetworkConfig.NetworkTransport = unityTransport;
3939
}
4040

@@ -49,7 +49,6 @@ public IEnumerator ClientFailsToConnect()
4949

5050
// Unity Transport throws an error when it times out
5151
LogAssert.Expect(LogType.Error, "Failed to connect to server.");
52-
5352
yield return NetcodeIntegrationTest.WaitForConditionOrTimeOut(() => m_WasDisconnected, m_TimeoutHelper);
5453
Assert.False(m_TimeoutHelper.TimedOut, "Timed out waiting for client to timeout waiting to connect!");
5554

com.unity.netcode.gameobjects/Tests/Runtime/ConnectionApproval.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,17 +92,23 @@ protected override void OnServerAndClientsCreated()
9292
private void Client_OnClientDisconnectCallback(ulong clientId)
9393
{
9494
m_ClientNetworkManagers[0].OnClientDisconnectCallback -= Client_OnClientDisconnectCallback;
95-
m_ClientDisconnectReasonValidated = m_ClientNetworkManagers[0].LocalClientId == clientId && m_ClientNetworkManagers[0].DisconnectReason.Contains(k_InvalidToken);
95+
m_ClientDisconnectReasonValidated = m_ClientNetworkManagers[0].LocalClientId == clientId && m_ClientNetworkManagers[0].ConnectionManager.ServerDisconnectReason.Contains(k_InvalidToken);
9696
}
9797

98-
private bool ClientAndHostValidated()
98+
private bool ClientAndHostValidated(StringBuilder errorLog)
9999
{
100100
if (!m_Validated.ContainsKey(m_ServerNetworkManager.LocalClientId) || !m_Validated[m_ServerNetworkManager.LocalClientId])
101101
{
102+
errorLog.AppendLine($"Server does not contain a validation for Client-{m_ServerNetworkManager.LocalClientId}!");
102103
return false;
103104
}
104105
if (m_PlayerCreation == PlayerCreation.FailValidation)
105106
{
107+
if (!m_ClientDisconnectReasonValidated)
108+
{
109+
errorLog.AppendLine($"{nameof(m_ClientDisconnectReasonValidated)} is false!");
110+
}
111+
106112
return m_ClientDisconnectReasonValidated;
107113
}
108114
else
@@ -111,6 +117,7 @@ private bool ClientAndHostValidated()
111117
{
112118
if (!m_Validated.ContainsKey(client.LocalClientId) || !m_Validated[client.LocalClientId])
113119
{
120+
errorLog.AppendLine($"Client-{client.LocalClientId} was not in the validated list!");
114121
return false;
115122
}
116123
}
@@ -163,6 +170,7 @@ private void NetworkManagerObject_ConnectionApprovalCallback(NetworkManager.Conn
163170
{
164171
response.Approved = false;
165172
response.Reason = "Invalid validation token!";
173+
return;
166174
}
167175

168176
response.CreatePlayerObject = ShouldCheckForSpawnedPlayers();

com.unity.netcode.gameobjects/Tests/Runtime/ConnectionApprovalTimeoutTests.cs

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ public ConnectionApprovalTimeoutTests(ApprovalTimedOutTypes approvalFailureType)
2828

2929
// Must be >= 5 since this is an int value and the test waits for timeout - 1 to try to verify it doesn't
3030
// time out early
31-
private const int k_TestTimeoutPeriod = 5;
31+
private const int k_TestTimeoutPeriod = 3;
3232

3333
private Regex m_ExpectedLogMessage;
3434
private LogType m_LogType;
@@ -48,21 +48,47 @@ protected override IEnumerator OnTearDown()
4848

4949
protected override void OnServerAndClientsCreated()
5050
{
51-
m_ServerNetworkManager.NetworkConfig.ClientConnectionBufferTimeout = k_TestTimeoutPeriod;
51+
// The timeouts (client-server relative) need to be skewed such that either the server or the client will timeout prior to the other timing out.
52+
var serverTimeout = (int)(m_ApprovalFailureType == ApprovalTimedOutTypes.ServerDoesNotRespond ? k_TestTimeoutPeriod * 1.5f : k_TestTimeoutPeriod * 0.75f);
53+
var clientTimeout = (int)(m_ApprovalFailureType == ApprovalTimedOutTypes.ServerDoesNotRespond ? k_TestTimeoutPeriod * 0.75f : k_TestTimeoutPeriod * 1.5f);
54+
55+
m_ServerNetworkManager.ConnectionApprovalCallback = ConnectionApproval;
56+
57+
m_ServerNetworkManager.NetworkConfig.ConnectionApproval = true;
58+
m_ServerNetworkManager.NetworkConfig.ClientConnectionBufferTimeout = serverTimeout;
5259
m_ServerNetworkManager.LogLevel = LogLevel.Developer;
53-
m_ClientNetworkManagers[0].NetworkConfig.ClientConnectionBufferTimeout = k_TestTimeoutPeriod;
60+
61+
m_ClientNetworkManagers[0].NetworkConfig.ClientConnectionBufferTimeout = clientTimeout;
5462
m_ClientNetworkManagers[0].LogLevel = LogLevel.Developer;
63+
m_ClientNetworkManagers[0].NetworkConfig.ConnectionApproval = true;
64+
5565
base.OnServerAndClientsCreated();
5666
}
5767

68+
private void ConnectionApproval(NetworkManager.ConnectionApprovalRequest connectionApprovalRequest, NetworkManager.ConnectionApprovalResponse connectionApprovalResponse)
69+
{
70+
if (connectionApprovalRequest.ClientNetworkId != NetworkManager.ServerClientId)
71+
{
72+
// For these tests we just always place the newly connecting client into pending
73+
connectionApprovalResponse.Pending = true;
74+
}
75+
else
76+
{
77+
// We always approve the host
78+
connectionApprovalResponse.Approved = true;
79+
}
80+
}
81+
82+
private const string k_ExpectedLogWhenServerDoesNotRespond = "Timed out waiting for the server to approve the connection request.";
83+
private const string k_ExpectedLogWhenClientDoesNotRequest = "Server detected a transport connection from Client-1, but timed out waiting for the connection request message.";
84+
5885
protected override IEnumerator OnStartedServerAndClients()
5986
{
6087
if (m_ApprovalFailureType == ApprovalTimedOutTypes.ServerDoesNotRespond)
6188
{
62-
m_ServerNetworkManager.ConnectionManager.MockSkippingApproval = true;
6389
// We catch (don't process) the incoming approval message to simulate the server not sending the approved message in time
6490
m_ClientNetworkManagers[0].ConnectionManager.MessageManager.Hook(new MessageCatcher<ConnectionApprovedMessage>(m_ClientNetworkManagers[0]));
65-
m_ExpectedLogMessage = new Regex("Timed out waiting for the server to approve the connection request.");
91+
m_ExpectedLogMessage = new Regex(k_ExpectedLogWhenServerDoesNotRespond);
6692
m_LogType = LogType.Log;
6793
}
6894
else
@@ -72,7 +98,7 @@ protected override IEnumerator OnStartedServerAndClients()
7298
m_ServerNetworkManager.ConnectionManager.MessageManager.Hook(new MessageCatcher<ConnectionRequestMessage>(m_ServerNetworkManager));
7399

74100
// For this test, we know the timed out client will be Client-1
75-
m_ExpectedLogMessage = new Regex("Server detected a transport connection from Client-1, but timed out waiting for the connection request message.");
101+
m_ExpectedLogMessage = new Regex(k_ExpectedLogWhenClientDoesNotRequest);
76102
m_LogType = LogType.Warning;
77103
}
78104
yield return null;
@@ -87,16 +113,14 @@ public IEnumerator ValidateApprovalTimeout()
87113
// Verify we haven't received the time out message yet
88114
NetcodeLogAssert.LogWasNotReceived(LogType.Log, m_ExpectedLogMessage);
89115

90-
yield return new WaitForSeconds(k_TestTimeoutPeriod * 1.25f);
116+
yield return new WaitForSeconds(k_TestTimeoutPeriod * 1.55f);
91117

92118
// We should have the test relative log message by this time.
93119
NetcodeLogAssert.LogWasReceived(m_LogType, m_ExpectedLogMessage);
94120

95121
VerboseDebug("Checking connected client count");
96122
// It should only have the host client connected
97123
Assert.AreEqual(1, m_ServerNetworkManager.ConnectedClients.Count, $"Expected only one client when there were {m_ServerNetworkManager.ConnectedClients.Count} clients connected!");
98-
99-
100124
Assert.AreEqual(0, m_ServerNetworkManager.ConnectionManager.PendingClients.Count, $"Expected no pending clients when there were {m_ServerNetworkManager.ConnectionManager.PendingClients.Count} pending clients!");
101125
Assert.True(!m_ClientNetworkManagers[0].LocalClient.IsApproved, $"Expected the client to not have been approved, but it was!");
102126
}

com.unity.netcode.gameobjects/Tests/Runtime/PeerDisconnectCallbackTests.cs

Lines changed: 56 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.Collections;
22
using System.Collections.Generic;
33
using System.Linq;
4+
using System.Text;
45
using NUnit.Framework;
56
using Unity.Netcode.TestHelpers.Runtime;
67
using UnityEngine.TestTools;
@@ -46,16 +47,15 @@ protected override void OnServerAndClientsCreated()
4647
// Adjusting client and server timeout periods to reduce test time
4748
// Get the tick frequency in milliseconds and triple it for the heartbeat timeout
4849
var heartBeatTimeout = (int)(300 * (1.0f / m_ServerNetworkManager.NetworkConfig.TickRate));
49-
var unityTransport = m_ServerNetworkManager.NetworkConfig.NetworkTransport as Transports.UTP.UnityTransport;
50-
if (unityTransport != null)
51-
{
52-
unityTransport.HeartbeatTimeoutMS = heartBeatTimeout;
53-
}
5450

55-
unityTransport = m_ClientNetworkManagers[0].NetworkConfig.NetworkTransport as Transports.UTP.UnityTransport;
56-
if (unityTransport != null)
51+
foreach (var networkManager in m_NetworkManagers)
5752
{
58-
unityTransport.HeartbeatTimeoutMS = heartBeatTimeout;
53+
var unityTransport = networkManager.NetworkConfig.NetworkTransport as Transports.UTP.UnityTransport;
54+
if (unityTransport != null)
55+
{
56+
unityTransport.HeartbeatTimeoutMS = heartBeatTimeout;
57+
}
58+
networkManager.OnConnectionEvent += OnConnectionEventCallback;
5959
}
6060

6161
base.OnServerAndClientsCreated();
@@ -73,18 +73,29 @@ private void OnConnectionEventCallback(NetworkManager networkManager, Connection
7373
switch (data.EventType)
7474
{
7575
case ConnectionEvent.ClientDisconnected:
76-
Assert.IsFalse(data.PeerClientIds.IsCreated);
77-
++m_ClientDisconnectCount;
78-
break;
76+
{
77+
Assert.IsFalse(data.PeerClientIds.IsCreated);
78+
if (data.ClientId == m_TargetClientId)
79+
{
80+
++m_ClientDisconnectCount;
81+
}
82+
break;
83+
}
7984
case ConnectionEvent.PeerDisconnected:
80-
Assert.IsFalse(data.PeerClientIds.IsCreated);
81-
++m_PeerDisconnectCount;
82-
break;
85+
{
86+
if (data.ClientId == m_TargetClientId)
87+
{
88+
Assert.IsFalse(data.PeerClientIds.IsCreated);
89+
++m_PeerDisconnectCount;
90+
}
91+
break;
92+
}
8393
}
8494
}
8595

8696
private bool m_TargetClientShutdown;
8797
private NetworkManager m_TargetClient;
98+
private ulong m_TargetClientId;
8899

89100
private void ClientToDisconnect_OnClientStopped(bool wasHost)
90101
{
@@ -97,10 +108,10 @@ public IEnumerator TestPeerDisconnectCallback([Values] ClientDisconnectType clie
97108
{
98109
m_TargetClientShutdown = false;
99110
m_TargetClient = m_ClientNetworkManagers[disconnectedClient - 1];
111+
m_TargetClientId = m_TargetClient.LocalClientId;
100112
m_TargetClient.OnClientStopped += ClientToDisconnect_OnClientStopped;
101-
foreach (var client in m_ClientNetworkManagers)
113+
foreach (var client in m_NetworkManagers)
102114
{
103-
client.OnConnectionEvent += OnConnectionEventCallback;
104115
if (m_UseHost)
105116
{
106117
Assert.IsTrue(client.ConnectedClientsIds.Contains(0ul));
@@ -110,15 +121,6 @@ public IEnumerator TestPeerDisconnectCallback([Values] ClientDisconnectType clie
110121
Assert.IsTrue(client.ConnectedClientsIds.Contains(3ul));
111122
Assert.AreEqual(client.ServerIsHost, m_UseHost);
112123
}
113-
m_ServerNetworkManager.OnConnectionEvent += OnConnectionEventCallback;
114-
if (m_UseHost)
115-
{
116-
Assert.IsTrue(m_ServerNetworkManager.ConnectedClientsIds.Contains(0ul));
117-
}
118-
Assert.IsTrue(m_ServerNetworkManager.ConnectedClientsIds.Contains(1ul));
119-
Assert.IsTrue(m_ServerNetworkManager.ConnectedClientsIds.Contains(2ul));
120-
Assert.IsTrue(m_ServerNetworkManager.ConnectedClientsIds.Contains(3ul));
121-
Assert.AreEqual(m_ServerNetworkManager.ServerIsHost, m_UseHost);
122124

123125
// Set up a WaitForMessageReceived hook.
124126
// In some cases the message will be received during StopOneClient, but it is not guaranteed
@@ -135,6 +137,7 @@ public IEnumerator TestPeerDisconnectCallback([Values] ClientDisconnectType clie
135137
// Used to determine if all clients received the CreateObjectMessage
136138
var hooks = new MessageHooksConditional(messageHookEntriesForSpawn);
137139

140+
138141
if (clientDisconnectType == ClientDisconnectType.ServerDisconnectsClient)
139142
{
140143
m_ServerNetworkManager.DisconnectClient(disconnectedClient);
@@ -151,52 +154,44 @@ public IEnumerator TestPeerDisconnectCallback([Values] ClientDisconnectType clie
151154
yield return WaitForConditionOrTimeOut(() => m_TargetClientShutdown);
152155
AssertOnTimeout($"Timed out waiting for {m_TargetClient.name} to shutdown!");
153156

154-
foreach (var client in m_ClientNetworkManagers)
157+
// Check that the client is disconnected and all NetworkManagers have registered this
158+
yield return WaitForConditionOrTimeOut(CheckClientDisconnected);
159+
AssertOnTimeout($"Timed out waiting for {m_TargetClient.name} to register as having shutdown!");
160+
161+
// If disconnected, the server and the client that disconnected will be notified
162+
Assert.AreEqual(2, m_ClientDisconnectCount);
163+
// Host receives peer disconnect, dedicated server does not
164+
Assert.AreEqual(m_UseHost ? 3 : 2, m_PeerDisconnectCount);
165+
}
166+
167+
/// <summary>
168+
/// Conditional method to verify the <see cref="m_TargetClientId"/> is disconnected
169+
/// and that identifier is not contained on any <see cref="NetworkManager"/> instance's
170+
/// <see cref="NetworkManager.ConnectedClientsIds"/>.
171+
/// </summary>
172+
private bool CheckClientDisconnected(StringBuilder errorLog)
173+
{
174+
foreach (var networkManager in m_NetworkManagers)
155175
{
156-
if (!client.IsConnectedClient)
176+
if (!networkManager.IsConnectedClient)
157177
{
158-
Assert.IsEmpty(client.ConnectedClientsIds);
159-
continue;
160-
}
161-
if (m_UseHost)
162-
{
163-
Assert.IsTrue(client.ConnectedClientsIds.Contains(0ul), $"[Client-{client.LocalClientId}][Connected ({client.IsConnectedClient})] Still has client identifier 0!");
164-
}
165178

166-
for (var i = 1ul; i < 3ul; ++i)
167-
{
168-
if (i == disconnectedClient)
169-
{
170-
Assert.IsFalse(client.ConnectedClientsIds.Contains(i), $"[Client-{client.LocalClientId}][Connected ({client.IsConnectedClient})] Still has client identifier {i}!");
171-
}
172-
else
173-
{
174-
Assert.IsTrue(client.ConnectedClientsIds.Contains(i), $"[Client-{client.LocalClientId}][Connected ({client.IsConnectedClient})] Still has client identifier {i}!");
175-
}
179+
continue;
176180
}
177-
}
178-
if (m_UseHost)
179-
{
180-
Assert.IsTrue(m_ServerNetworkManager.ConnectedClientsIds.Contains(0ul));
181-
}
182-
183-
for (var i = 1ul; i < 3ul; ++i)
184-
{
185-
if (i == disconnectedClient)
181+
if (networkManager.LocalClientId == m_TargetClientId && ((networkManager.IsConnectedClient) || (networkManager.IsListening)))
186182
{
187-
Assert.IsFalse(m_ServerNetworkManager.ConnectedClientsIds.Contains(i));
183+
errorLog.AppendLine($"[Client-{networkManager.LocalClientId}] Is either still connected or still listening!");
184+
return false;
188185
}
189-
else
186+
if (networkManager.ConnectedClientsIds.Contains(m_TargetClientId))
190187
{
191-
Assert.IsTrue(m_ServerNetworkManager.ConnectedClientsIds.Contains(i));
188+
errorLog.AppendLine($"[Client-{networkManager.LocalClientId}] Is still has {m_TargetClientId} registered as a connected client!");
189+
return false;
192190
}
193191
}
194-
195-
// If disconnected, the server and the client that disconnected will be notified
196-
Assert.AreEqual(2, m_ClientDisconnectCount);
197-
// Host receives peer disconnect, dedicated server does not
198-
Assert.AreEqual(m_UseHost ? 3 : 2, m_PeerDisconnectCount);
192+
return true;
199193
}
200194

201195
}
202196
}
197+

0 commit comments

Comments
 (0)