1
0
mirror of https://github.com/ppy/osu.git synced 2025-01-13 16:32:54 +08:00

Refactor test to be easier to work with

This commit is contained in:
Bartłomiej Dach 2022-12-22 11:10:33 +01:00
parent 722cf48614
commit 48dc2332fd
No known key found for this signature in database
3 changed files with 130 additions and 119 deletions

View File

@ -3,6 +3,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using NUnit.Framework; using NUnit.Framework;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Testing; using osu.Framework.Testing;
@ -12,6 +13,7 @@ using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.API.Requests.Responses;
using osu.Game.Online.Solo; using osu.Game.Online.Solo;
using osu.Game.Online.Spectator; using osu.Game.Online.Spectator;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu;
using osu.Game.Scoring; using osu.Game.Scoring;
using osu.Game.Users; using osu.Game.Users;
@ -33,9 +35,12 @@ namespace osu.Game.Tests.Visual.Online
private Action<GetUsersRequest>? handleGetUsersRequest; private Action<GetUsersRequest>? handleGetUsersRequest;
private Action<GetUserRequest>? handleGetUserRequest; private Action<GetUserRequest>? handleGetUserRequest;
private readonly Dictionary<(int userId, string rulesetName), UserStatistics> serverSideStatistics = new Dictionary<(int userId, string rulesetName), UserStatistics>();
[SetUpSteps] [SetUpSteps]
public void SetUpSteps() public void SetUpSteps()
{ {
AddStep("clear server-side stats", () => serverSideStatistics.Clear());
AddStep("set up request handling", () => AddStep("set up request handling", () =>
{ {
handleGetUserRequest = null; handleGetUserRequest = null;
@ -46,11 +51,52 @@ namespace osu.Game.Tests.Visual.Online
switch (request) switch (request)
{ {
case GetUsersRequest getUsersRequest: case GetUsersRequest getUsersRequest:
handleGetUsersRequest?.Invoke(getUsersRequest); if (handleGetUsersRequest != null)
{
handleGetUsersRequest?.Invoke(getUsersRequest);
}
else
{
int userId = getUsersRequest.UserIds.Single();
var response = new GetUsersResponse
{
Users = new List<APIUser>
{
new APIUser
{
Id = userId,
RulesetsStatistics = new Dictionary<string, UserStatistics>
{
["osu"] = tryGetStatistics(userId, "osu"),
["taiko"] = tryGetStatistics(userId, "taiko"),
["fruits"] = tryGetStatistics(userId, "fruits"),
["mania"] = tryGetStatistics(userId, "mania"),
}
}
}
};
getUsersRequest.TriggerSuccess(response);
}
return true; return true;
case GetUserRequest getUserRequest: case GetUserRequest getUserRequest:
handleGetUserRequest?.Invoke(getUserRequest); if (handleGetUserRequest != null)
{
handleGetUserRequest.Invoke(getUserRequest);
}
else
{
int userId = int.Parse(getUserRequest.Lookup);
string rulesetName = getUserRequest.Ruleset.ShortName;
var response = new APIUser
{
Id = userId,
Statistics = tryGetStatistics(userId, rulesetName)
};
getUserRequest.TriggerSuccess(response);
}
return true; return true;
default: default:
@ -65,120 +111,90 @@ namespace osu.Game.Tests.Visual.Online
}); });
} }
private UserStatistics tryGetStatistics(int userId, string rulesetName)
=> serverSideStatistics.TryGetValue((userId, rulesetName), out var stats) ? stats : new UserStatistics();
[Test] [Test]
public void TestStatisticsUpdateFiredAfterRegistrationAddedAndScoreProcessed() public void TestStatisticsUpdateFiredAfterRegistrationAddedAndScoreProcessed()
{ {
AddStep("fetch initial stats", () => int userId = getUserId();
{ long scoreId = getScoreId();
handleGetUsersRequest = req => req.TriggerSuccess(createInitialUserResponse(1234)); setUpUser(userId);
dummyAPI.LocalUser.Value = new APIUser { Id = 1234 };
}); var ruleset = new OsuRuleset().RulesetInfo;
SoloStatisticsUpdate? update = null; SoloStatisticsUpdate? update = null;
registerForUpdates(scoreId, ruleset, receivedUpdate => update = receivedUpdate);
AddStep("register for updates", () => watcher.RegisterForStatisticsUpdateAfter( feignScoreProcessing(userId, ruleset, 5_000_000);
new ScoreInfo(Beatmap.Value.BeatmapInfo, new OsuRuleset().RulesetInfo, new RealmUser())
{
Ruleset = new OsuRuleset().RulesetInfo,
OnlineID = 5678
},
receivedUpdate => update = receivedUpdate));
AddStep("feign score processing", AddStep("signal score processed", () => ((ISpectatorClient)spectatorClient).UserScoreProcessed(userId, scoreId));
() => handleGetUserRequest =
req => req.TriggerSuccess(createIncrementalUserResponse(1234, 5_000_000)));
AddStep("signal score processed", () => ((ISpectatorClient)spectatorClient).UserScoreProcessed(1234, 5678));
AddUntilStep("update received", () => update != null); AddUntilStep("update received", () => update != null);
AddAssert("values before are correct", () => update?.Before.TotalScore, () => Is.EqualTo(4_000_000)); AddAssert("values before are correct", () => update!.Before.TotalScore, () => Is.EqualTo(4_000_000));
AddAssert("values after are correct", () => update?.After.TotalScore, () => Is.EqualTo(5_000_000)); AddAssert("values after are correct", () => update!.After.TotalScore, () => Is.EqualTo(5_000_000));
} }
[Test] [Test]
public void TestStatisticsUpdateFiredAfterScoreProcessedAndRegistrationAdded() public void TestStatisticsUpdateFiredAfterScoreProcessedAndRegistrationAdded()
{ {
AddStep("fetch initial stats", () => int userId = getUserId();
{ setUpUser(userId);
handleGetUsersRequest = req => req.TriggerSuccess(createInitialUserResponse(1235));
dummyAPI.LocalUser.Value = new APIUser { Id = 1235 };
});
AddStep("feign score processing", long scoreId = getScoreId();
() => handleGetUserRequest = var ruleset = new OsuRuleset().RulesetInfo;
req => req.TriggerSuccess(createIncrementalUserResponse(1235, 5_000_000)));
AddStep("signal score processed", () => ((ISpectatorClient)spectatorClient).UserScoreProcessed(1235, 5678)); // note ordering - in this test processing completes *before* the registration is added.
feignScoreProcessing(userId, ruleset, 5_000_000);
SoloStatisticsUpdate? update = null; SoloStatisticsUpdate? update = null;
registerForUpdates(scoreId, ruleset, receivedUpdate => update = receivedUpdate);
// note ordering - this test checks that even if the registration is late, it will receive data. AddStep("signal score processed", () => ((ISpectatorClient)spectatorClient).UserScoreProcessed(userId, scoreId));
AddStep("register for updates", () => watcher.RegisterForStatisticsUpdateAfter(
new ScoreInfo(Beatmap.Value.BeatmapInfo, new OsuRuleset().RulesetInfo, new RealmUser())
{
Ruleset = new OsuRuleset().RulesetInfo,
OnlineID = 5678
},
receivedUpdate => update = receivedUpdate));
AddUntilStep("update received", () => update != null); AddUntilStep("update received", () => update != null);
AddAssert("values before are correct", () => update?.Before.TotalScore, () => Is.EqualTo(4_000_000)); AddAssert("values before are correct", () => update!.Before.TotalScore, () => Is.EqualTo(4_000_000));
AddAssert("values after are correct", () => update?.After.TotalScore, () => Is.EqualTo(5_000_000)); AddAssert("values after are correct", () => update!.After.TotalScore, () => Is.EqualTo(5_000_000));
} }
[Test] [Test]
public void TestStatisticsUpdateNotFiredIfUserLoggedOut() public void TestStatisticsUpdateNotFiredIfUserLoggedOut()
{ {
AddStep("fetch initial stats", () => int userId = getUserId();
{ setUpUser(userId);
handleGetUsersRequest = req => req.TriggerSuccess(createInitialUserResponse(1236));
dummyAPI.LocalUser.Value = new APIUser { Id = 1236 }; long scoreId = getScoreId();
}); var ruleset = new OsuRuleset().RulesetInfo;
SoloStatisticsUpdate? update = null; SoloStatisticsUpdate? update = null;
registerForUpdates(scoreId, ruleset, receivedUpdate => update = receivedUpdate);
AddStep("register for updates", () => watcher.RegisterForStatisticsUpdateAfter( feignScoreProcessing(userId, ruleset, 5_000_000);
new ScoreInfo(Beatmap.Value.BeatmapInfo, new OsuRuleset().RulesetInfo, new RealmUser())
{
Ruleset = new OsuRuleset().RulesetInfo,
OnlineID = 5678
},
receivedUpdate => update = receivedUpdate));
AddStep("feign score processing",
() => handleGetUserRequest =
req => req.TriggerSuccess(createIncrementalUserResponse(1236, 5_000_000)));
AddStep("log out user", () => dummyAPI.Logout()); AddStep("log out user", () => dummyAPI.Logout());
AddStep("signal score processed", () => ((ISpectatorClient)spectatorClient).UserScoreProcessed(1236, 5678)); AddStep("signal score processed", () => ((ISpectatorClient)spectatorClient).UserScoreProcessed(userId, scoreId));
AddWaitStep("wait a bit", 5); AddWaitStep("wait a bit", 5);
AddAssert("update not received", () => update == null); AddAssert("update not received", () => update == null);
AddStep("log in user", () => dummyAPI.Login("user", "password"));
} }
[Test] [Test]
public void TestStatisticsUpdateNotFiredIfAnotherUserLoggedIn() public void TestStatisticsUpdateNotFiredIfAnotherUserLoggedIn()
{ {
AddStep("fetch initial stats", () => int userId = getUserId();
{ setUpUser(userId);
handleGetUsersRequest = req => req.TriggerSuccess(createInitialUserResponse(1237));
dummyAPI.LocalUser.Value = new APIUser { Id = 1237 }; long scoreId = getScoreId();
}); var ruleset = new OsuRuleset().RulesetInfo;
SoloStatisticsUpdate? update = null; SoloStatisticsUpdate? update = null;
registerForUpdates(scoreId, ruleset, receivedUpdate => update = receivedUpdate);
AddStep("register for updates", () => watcher.RegisterForStatisticsUpdateAfter( feignScoreProcessing(userId, ruleset, 5_000_000);
new ScoreInfo(Beatmap.Value.BeatmapInfo, new OsuRuleset().RulesetInfo, new RealmUser())
{
Ruleset = new OsuRuleset().RulesetInfo,
OnlineID = 5678
},
receivedUpdate => update = receivedUpdate));
AddStep("feign score processing", AddStep("change user", () => dummyAPI.LocalUser.Value = new APIUser { Id = getUserId() });
() => handleGetUserRequest =
req => req.TriggerSuccess(createIncrementalUserResponse(1237, 5_000_000)));
AddStep("log out user", () => dummyAPI.LocalUser.Value = new APIUser { Id = 5555 }); AddStep("signal score processed", () => ((ISpectatorClient)spectatorClient).UserScoreProcessed(userId, scoreId));
AddStep("signal score processed", () => ((ISpectatorClient)spectatorClient).UserScoreProcessed(1237, 5678));
AddWaitStep("wait a bit", 5); AddWaitStep("wait a bit", 5);
AddAssert("update not received", () => update == null); AddAssert("update not received", () => update == null);
} }
@ -186,56 +202,51 @@ namespace osu.Game.Tests.Visual.Online
[Test] [Test]
public void TestStatisticsUpdateNotFiredIfScoreIdDoesNotMatch() public void TestStatisticsUpdateNotFiredIfScoreIdDoesNotMatch()
{ {
AddStep("fetch initial stats", () => int userId = getUserId();
{ setUpUser(userId);
handleGetUsersRequest = req => req.TriggerSuccess(createInitialUserResponse(1238));
dummyAPI.LocalUser.Value = new APIUser { Id = 1238 }; long scoreId = getScoreId();
}); var ruleset = new OsuRuleset().RulesetInfo;
SoloStatisticsUpdate? update = null; SoloStatisticsUpdate? update = null;
registerForUpdates(scoreId, ruleset, receivedUpdate => update = receivedUpdate);
AddStep("register for updates", () => watcher.RegisterForStatisticsUpdateAfter( feignScoreProcessing(userId, ruleset, 5_000_000);
new ScoreInfo(Beatmap.Value.BeatmapInfo, new OsuRuleset().RulesetInfo, new RealmUser())
{
Ruleset = new OsuRuleset().RulesetInfo,
OnlineID = 5678
},
receivedUpdate => update = receivedUpdate));
AddStep("feign score processing", AddStep("signal another score processed", () => ((ISpectatorClient)spectatorClient).UserScoreProcessed(userId, getScoreId()));
() => handleGetUserRequest =
req => req.TriggerSuccess(createIncrementalUserResponse(1238, 5_000_000)));
AddStep("signal score processed", () => ((ISpectatorClient)spectatorClient).UserScoreProcessed(1238, 9012));
AddWaitStep("wait a bit", 5); AddWaitStep("wait a bit", 5);
AddAssert("update not received", () => update == null); AddAssert("update not received", () => update == null);
} }
private GetUsersResponse createInitialUserResponse(int userId) => new GetUsersResponse private int nextUserId = 2000;
{ private long nextScoreId = 50000;
Users = new List<APIUser>
{
new APIUser
{
Id = userId,
RulesetsStatistics = new Dictionary<string, UserStatistics>
{
["osu"] = new UserStatistics { TotalScore = 4_000_000 },
["taiko"] = new UserStatistics { TotalScore = 3_000_000 },
["fruits"] = new UserStatistics { TotalScore = 2_000_000 },
["mania"] = new UserStatistics { TotalScore = 1_000_000 }
}
}
}
};
private APIUser createIncrementalUserResponse(int userId, long totalScore) => new APIUser private int getUserId() => ++nextUserId;
private long getScoreId() => ++nextScoreId;
private void setUpUser(int userId)
{ {
Id = userId, AddStep("fetch initial stats", () =>
Statistics = new UserStatistics
{ {
TotalScore = totalScore serverSideStatistics[(userId, "osu")] = new UserStatistics { TotalScore = 4_000_000 };
} serverSideStatistics[(userId, "taiko")] = new UserStatistics { TotalScore = 3_000_000 };
}; serverSideStatistics[(userId, "fruits")] = new UserStatistics { TotalScore = 2_000_000 };
serverSideStatistics[(userId, "mania")] = new UserStatistics { TotalScore = 1_000_000 };
dummyAPI.LocalUser.Value = new APIUser { Id = userId };
});
}
private void registerForUpdates(long scoreId, RulesetInfo rulesetInfo, Action<SoloStatisticsUpdate> onUpdateReady) =>
AddStep("register for updates", () => watcher.RegisterForStatisticsUpdateAfter(
new ScoreInfo(Beatmap.Value.BeatmapInfo, new OsuRuleset().RulesetInfo, new RealmUser())
{
Ruleset = rulesetInfo,
OnlineID = scoreId
},
onUpdateReady));
private void feignScoreProcessing(int userId, RulesetInfo rulesetInfo, long newTotalScore)
=> AddStep("feign score processing", () => serverSideStatistics[(userId, rulesetInfo.ShortName)] = new UserStatistics { TotalScore = newTotalScore });
} }
} }

View File

@ -9,7 +9,7 @@ namespace osu.Game.Online.API.Requests
{ {
public class GetUsersRequest : APIRequest<GetUsersResponse> public class GetUsersRequest : APIRequest<GetUsersResponse>
{ {
private readonly int[] userIds; public readonly int[] UserIds;
private const int max_ids_per_request = 50; private const int max_ids_per_request = 50;
@ -18,9 +18,9 @@ namespace osu.Game.Online.API.Requests
if (userIds.Length > max_ids_per_request) if (userIds.Length > max_ids_per_request)
throw new ArgumentException($"{nameof(GetUsersRequest)} calls only support up to {max_ids_per_request} IDs at once"); throw new ArgumentException($"{nameof(GetUsersRequest)} calls only support up to {max_ids_per_request} IDs at once");
this.userIds = userIds; UserIds = userIds;
} }
protected override string Target => "users/?ids[]=" + string.Join("&ids[]=", userIds); protected override string Target => "users/?ids[]=" + string.Join("&ids[]=", UserIds);
} }
} }

View File

@ -71,7 +71,7 @@ namespace osu.Game.Online.Solo
if (!api.IsLoggedIn) if (!api.IsLoggedIn)
return; return;
Debug.Assert(localUser != null && localUser.OnlineID > 1); Debug.Assert(localUser != null);
var userRequest = new GetUsersRequest(new[] { localUser.OnlineID }); var userRequest = new GetUsersRequest(new[] { localUser.OnlineID });
userRequest.Success += response => Schedule(() => userRequest.Success += response => Schedule(() =>