-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy pathRpcObserverTests.cs
More file actions
357 lines (304 loc) · 14 KB
/
RpcObserverTests.cs
File metadata and controls
357 lines (304 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using Unity.Netcode.TestHelpers.Runtime;
using Unity.Netcode;
using Unity.Collections;
namespace TestProject.RuntimeTests
{
/// <summary>
/// Integration test to validate ClientRpcs will only
/// send to observers of the NetworkObject
/// </summary>
[TestFixture(HostOrServer.Host)]
[TestFixture(HostOrServer.Server)]
public class RpcObserverTests : NetcodeIntegrationTest
{
protected override int NumberOfClients => 9;
private GameObject m_TestPrefab;
private GameObject m_ServerPrefabInstance;
private RpcObserverObject m_ServerRpcObserverObject;
private NativeArray<ulong> m_NonObserverArrayError;
private bool m_ArrayAllocated;
public RpcObserverTests(HostOrServer hostOrServer) : base(hostOrServer) { }
protected override void OnServerAndClientsCreated()
{
m_TestPrefab = CreateNetworkObjectPrefab($"{nameof(RpcObserverObject)}");
m_TestPrefab.AddComponent<RpcObserverObject>();
}
protected override IEnumerator OnServerAndClientsConnected()
{
m_ServerPrefabInstance = SpawnObject(m_TestPrefab, m_ServerNetworkManager);
m_ServerRpcObserverObject = m_ServerPrefabInstance.GetComponent<RpcObserverObject>();
return base.OnServerAndClientsConnected();
}
[UnityTest]
public IEnumerator ClientRpcObserverTest()
{
// Wait for all clients to report they have spawned an instance of our test prefab
yield return WaitForConditionOrTimeOut(m_ServerRpcObserverObject.AllClientsSpawned);
var nonObservers = new List<ulong>();
// We start out with all clients being observers of the test prefab
// Test that all clients receive the RPC
yield return RunRpcObserverTest(nonObservers);
// This hides the test prefab from one client and then runs the test
// and repeats until all clients are no longer observers
foreach (var clientId in m_ServerNetworkManager.ConnectedClientsIds)
{
if (clientId == m_ServerNetworkManager.LocalClientId)
{
continue;
}
// Hide it from the client
m_ServerRpcObserverObject.NetworkObject.NetworkHide(clientId);
nonObservers.Add(clientId);
// Provide 1 tick for the client to hide the NetworkObject
yield return s_DefaultWaitForTick;
// Run the test
yield return RunRpcObserverTest(nonObservers);
}
// ****** Verify that sending to non-observer(s) generates error ******
var clientRpcParams = new ClientRpcParams();
// Verify that we get an error message when we try to send to a non-observer using TargetClientIds
clientRpcParams.Send.TargetClientIds = new List<ulong>() { nonObservers[0] };
m_ServerNetworkManager.LogLevel = LogLevel.Error;
LogAssert.Expect(LogType.Error, "[Netcode] " + m_ServerRpcObserverObject.GenerateObserverErrorMessage(clientRpcParams, nonObservers[0]));
m_ServerRpcObserverObject.ObserverMessageClientRpc(clientRpcParams);
yield return s_DefaultWaitForTick;
m_NonObserverArrayError = new NativeArray<ulong>(clientRpcParams.Send.TargetClientIds.ToArray(), Allocator.Persistent);
m_ArrayAllocated = true;
// Now clean the TargetClientIds to prepare for the next TargetClientIdsNativeArray error check
clientRpcParams.Send.TargetClientIds = null;
// Now verify that we get an error message when we try to send to a non-observer using TargetClientIdsNativeArray
clientRpcParams.Send.TargetClientIdsNativeArray = m_NonObserverArrayError;
LogAssert.Expect(LogType.Error, "[Netcode] " + m_ServerRpcObserverObject.GenerateObserverErrorMessage(clientRpcParams, nonObservers[0]));
m_ServerRpcObserverObject.ObserverMessageClientRpc(clientRpcParams);
yield return s_DefaultWaitForTick;
// Validate we can still just send to the host-client when no clients are connected
if (m_UseHost)
{
m_ServerRpcObserverObject.ResetTest();
foreach (var clientId in nonObservers)
{
m_ServerNetworkManager.DisconnectClient(clientId);
}
yield return s_DefaultWaitForTick;
m_ServerRpcObserverObject.ObserverMessageClientRpc();
yield return s_DefaultWaitForTick;
Assert.True(m_ServerRpcObserverObject.HostReceivedMessage, "Host failed to receive the ClientRpc when no clients were connected!");
Assert.False(m_ServerRpcObserverObject.NonObserversReceivedRPC(nonObservers), $"Non-observers ({m_ServerRpcObserverObject.GetClientIdsAsString(nonObservers)}) received the RPC message!");
}
m_ServerNetworkManager.LogLevel = LogLevel.Normal;
}
/// <summary>
/// This will send an RPC to all observers of the test prefab and check
/// to see if the observer clients receive the message and also confirms
/// that the non-observer clients did not receive the message.
/// </summary>
private IEnumerator RunRpcObserverTest(List<ulong> nonObservers)
{
m_ServerRpcObserverObject.ResetTest();
m_ServerRpcObserverObject.ObserverMessageClientRpc();
yield return WaitForConditionOrTimeOut(m_ServerRpcObserverObject.AllObserversReceivedRPC);
Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for all clients to receive message!\n" +
$"Clients that received the message:{m_ServerRpcObserverObject.GetClientIdsAsString()}");
Assert.False(m_ServerRpcObserverObject.NonObserversReceivedRPC(nonObservers), $"Non-observers ({m_ServerRpcObserverObject.GetClientIdsAsString(nonObservers)}) received the RPC message!");
// Always verify the host received the RPC
if (m_UseHost)
{
Assert.True(m_ServerRpcObserverObject.HostReceivedMessage, $"Host failed to receive the ClientRpc with the following observers: {m_ServerRpcObserverObject.GetClientIdsAsString()}!");
}
}
/// <summary>
/// Validates that when a NetworkObject is despawned but not destroyed
/// and then re-spawned that the observer list is cleared
/// </summary>
[UnityTest]
public IEnumerator DespawnRespawnObserverTest()
{
var nonObservers = new List<ulong>();
m_ServerRpcObserverObject.ResetTest();
// Wait for all clients to report they have spawned an instance of our test prefab
yield return WaitForConditionOrTimeOut(m_ServerRpcObserverObject.AllClientsSpawned);
m_ServerRpcObserverObject.ObserverMessageClientRpc();
yield return WaitForConditionOrTimeOut(m_ServerRpcObserverObject.AllObserversReceivedRPC);
Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for all clients to receive message!\n" +
$"Clients that received the message:{m_ServerRpcObserverObject.GetClientIdsAsString()}");
Assert.False(m_ServerRpcObserverObject.NonObserversReceivedRPC(nonObservers), $"Non-observers ({m_ServerRpcObserverObject.GetClientIdsAsString(nonObservers)}) received the RPC message!");
m_ServerRpcObserverObject.NetworkObject.Despawn(false);
Assert.True(m_ServerRpcObserverObject.NetworkObject.Observers.Count == 0, $"Despawned {m_ServerRpcObserverObject.name} but it still has {m_ServerRpcObserverObject.NetworkObject.Observers.Count} observers!");
for (int i = 4; i < NumberOfClients; i++)
{
nonObservers.Add(m_ClientNetworkManagers[i].LocalClientId);
m_ServerNetworkManager.DisconnectClient(m_ClientNetworkManagers[i].LocalClientId);
}
yield return s_DefaultWaitForTick;
m_ServerRpcObserverObject.ResetTest();
m_ServerRpcObserverObject.NetworkObject.Spawn();
m_ServerRpcObserverObject.ObserverMessageClientRpc();
yield return WaitForConditionOrTimeOut(m_ServerRpcObserverObject.AllObserversReceivedRPC);
Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for all clients to receive message!\n" +
$"Clients that received the message:{m_ServerRpcObserverObject.GetClientIdsAsString()}");
Assert.False(m_ServerRpcObserverObject.NonObserversReceivedRPC(nonObservers), $"Non-observers ({m_ServerRpcObserverObject.GetClientIdsAsString(nonObservers)}) received the RPC message!");
// Always verify the host received the RPC
if (m_UseHost)
{
Assert.True(m_ServerRpcObserverObject.HostReceivedMessage, $"Host failed to receive the ClientRpc with the following observers: {m_ServerRpcObserverObject.GetClientIdsAsString()}!");
}
}
protected override IEnumerator OnTearDown()
{
// Make sure to dispose of the native array
if (m_ArrayAllocated)
{
m_ArrayAllocated = false;
m_NonObserverArrayError.Dispose();
}
return base.OnTearDown();
}
}
/// <summary>
/// Test prefab component used with RpcObserverTests
/// </summary>
public class RpcObserverObject : NetworkBehaviour
{
public readonly List<ulong> ObserversThatReceivedRPC = new List<ulong>();
public static readonly List<ulong> ClientInstancesSpawned = new List<ulong>();
protected bool m_NotifyClientReceivedMessage;
public bool HostReceivedMessage { get; internal set; }
public string GetClientIdsAsString(List<ulong> clientIds = null)
{
if (clientIds == null)
{
clientIds = ObserversThatReceivedRPC;
}
var clientIdsAsString = string.Empty;
foreach (var clientId in clientIds)
{
clientIdsAsString += $"({clientId})";
}
return clientIdsAsString;
}
/// <summary>
/// Returns true if all connected clients have spawned the test prefab
/// </summary>
public bool AllClientsSpawned()
{
if (!IsServer)
{
return false;
}
foreach (var clientId in NetworkManager.ConnectedClientsIds)
{
if (clientId == NetworkManager.LocalClientId)
{
continue;
}
if (!ClientInstancesSpawned.Contains(clientId))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns true if all observers have received the RPC
/// </summary>
public bool AllObserversReceivedRPC()
{
if (!IsServer)
{
return false;
}
foreach (var clientId in NetworkObject.Observers)
{
if (clientId == NetworkManager.LocalClientId)
{
continue;
}
if (!ObserversThatReceivedRPC.Contains(clientId))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns true if any clientId in the nonObservers list received the RPC
/// </summary>
/// <param name="nonObservers">list of clientIds that should not have received the RPC message</param>
public bool NonObserversReceivedRPC(List<ulong> nonObservers)
{
foreach (var clientId in nonObservers)
{
// return false if a non-observer received the RPC
if (ObserversThatReceivedRPC.Contains(clientId))
{
return true;
}
}
return false;
}
/// <summary>
/// Clears the received
/// </summary>
public void ResetTest()
{
ObserversThatReceivedRPC.Clear();
HostReceivedMessage = false;
}
/// <summary>
/// Called from server-host once per test run
/// </summary>
[ClientRpc]
public void ObserverMessageClientRpc(ClientRpcParams clientRpcParams = default)
{
if (IsHost)
{
HostReceivedMessage = true;
}
else
{
m_NotifyClientReceivedMessage = true;
}
}
/// <summary>
/// Called by each observer client that received the ObserverMessageClientRpc message
/// The sender id is added to the ObserversThatReceivedRPC list
/// </summary>
[ServerRpc(RequireOwnership = false)]
public void ObserverMessageServerRpc(ServerRpcParams serverRpcParams = default)
{
ObserversThatReceivedRPC.Add(serverRpcParams.Receive.SenderClientId);
}
public override void OnNetworkSpawn()
{
if (IsClient)
{
ClientInstancesSpawned.Add(NetworkManager.LocalClientId);
}
}
public override void OnNetworkDespawn()
{
if (IsClient)
{
ClientInstancesSpawned.Remove(NetworkManager.LocalClientId);
}
}
private void Update()
{
if (IsServer)
{
return;
}
if (m_NotifyClientReceivedMessage)
{
m_NotifyClientReceivedMessage = false;
ObserverMessageServerRpc();
}
}
}
}