~ruther/NosSmooth

ref: c610aeff9689feebc00cd6262b9c4c123287318d NosSmooth/Tests/NosSmooth.Game.Tests/PacketFileClient.cs -rw-r--r-- 9.3 KiB
c610aeff — Rutherther tests(game): add support for game integration tests 2 years ago
                                                                                
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
//
//  PacketFileClient.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Text.RegularExpressions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NosSmooth.Core.Client;
using NosSmooth.Core.Commands;
using NosSmooth.Core.Extensions;
using NosSmooth.Core.Packets;
using NosSmooth.Data.NOSFiles;
using NosSmooth.Data.NOSFiles.Extensions;
using NosSmooth.Game.Extensions;
using NosSmooth.Game.Tests.Helpers;
using NosSmooth.Packets;
using NosSmooth.PacketSerializer;
using NosSmooth.PacketSerializer.Abstractions.Attributes;
using NosSmooth.PacketSerializer.Errors;
using NosSmooth.PacketSerializer.Extensions;
using NosSmooth.PacketSerializer.Packets;
using Remora.Results;
using Xunit.Abstractions;

namespace NosSmooth.Game.Tests;

/// <summary>
/// A client used for tests. Supports loading just part of a file with packets.
/// </summary>
public class PacketFileClient : BaseNostaleClient, IDisposable
{
    private const string LineRegex = ".*\\[(Recv|Send)\\]\t(.*)";
    private const string LabelRegex = "##(.*)";

    // TODO: make this class cleaner

    private readonly FileStream _stream;
    private readonly StreamReader _reader;
    private readonly IPacketSerializer _packetSerializer;
    private readonly PacketHandler _packetHandler;
    private readonly ILogger<PacketFileClient> _logger;
    private string? _nextLabel;
    private bool _skip;
    private bool _readToLabel;

    /// <summary>
    /// Builds a file client for the given test.
    /// </summary>
    /// <param name="testName">The name of the test.</param>
    /// <param name="testOutputHelper">The output helper to output logs to.</param>
    /// <typeparam name="TTest">The test type.</typeparam>
    /// <returns>A file client and the associated game.</returns>
    public static (PacketFileClient Client, Game Game) CreateFor<TTest>(string testName, ITestOutputHelper testOutputHelper)
    {
        var services = new ServiceCollection()
            .AddLogging(b => b.AddProvider(new XUnitLoggerProvider(testOutputHelper)))
            .AddNostaleCore()
            .AddNostaleGame()
            .AddSingleton<PacketFileClient>(p => CreateFor<TTest>(p, testName))
            .AddSingleton<INostaleClient>(p => p.GetRequiredService<PacketFileClient>())
            .AddNostaleDataFiles()
            .BuildServiceProvider();

        services.GetRequiredService<IPacketTypesRepository>().AddDefaultPackets();
        if (!services.GetRequiredService<NostaleDataFilesManager>().Initialize().IsSuccess)
        {
            throw new Exception("Data not initialized correctly.");
        }

        return (services.GetRequiredService<PacketFileClient>(), services.GetRequiredService<Game>());
    }

    /// <summary>
    /// Create a file client for the given test.
    /// </summary>
    /// <param name="services">The services provider.</param>
    /// <param name="testName">The name of the test.</param>
    /// <typeparam name="TTest">The test class.</typeparam>
    /// <returns>A client.</returns>
    public static PacketFileClient CreateFor<TTest>(IServiceProvider services, string testName)
    {
        var prefix = "NosSmooth.Game.Tests.";
        var name = typeof(TTest).FullName!.Substring(prefix.Length).Replace("Tests", string.Empty);

        var splitted = name.Split('.');
        var path = "Packets/";

        foreach (var entry in splitted)
        {
            path += entry + "/";
        }

        path += testName + ".log";

        return Create
        (
            services,
            path
        );
    }

    /// <summary>
    /// Create an instance of PacketFileClient for the given file.
    /// </summary>
    /// <param name="services">The services provider.</param>
    /// <param name="fileName">The file name.</param>
    /// <returns>A client.</returns>
    public static PacketFileClient Create(IServiceProvider services, string fileName)
    {
        return (PacketFileClient)ActivatorUtilities.CreateInstance
            (services, typeof(PacketFileClient), new[] { File.OpenRead(fileName) });
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="PacketFileClient"/> class.
    /// </summary>
    /// <param name="stream">The file stream.</param>
    /// <param name="packetSerializer">The packet serializer.</param>
    /// <param name="commandProcessor">The command processor.</param>
    /// <param name="packetHandler">The packet handler.</param>
    /// <param name="logger">The logger.</param>
    public PacketFileClient
    (
        FileStream stream,
        IPacketSerializer packetSerializer,
        CommandProcessor commandProcessor,
        PacketHandler packetHandler,
        ILogger<PacketFileClient> logger
    )
        : base(commandProcessor, packetSerializer)
    {
        _stream = stream;
        _reader = new StreamReader(_stream);
        _packetSerializer = packetSerializer;
        _packetHandler = packetHandler;
        _logger = logger;
    }

    /// <summary>
    /// Start executing until the given label is hit.
    /// </summary>
    /// <param name="label">The label to hit.</param>
    /// <returns>An asynchronous operation.</returns>
    public async Task ExecuteUntilLabelAsync(string label)
    {
        _readToLabel = false;
        _nextLabel = label;
        await RunAsync();

        if (!_readToLabel)
        {
            throw new Exception($"Label {label} not found.");
        }
    }

    /// <summary>
    /// Start executing until the end of the file.
    /// </summary>
    /// <returns>An asynchronous operation.</returns>
    public Task ExecuteToEnd()
    {
        _nextLabel = null;
        return RunAsync();
    }

    /// <summary>
    /// Skip cursor until the given label is hit.
    /// </summary>
    /// <param name="label">The label to hit.</param>
    /// <returns>An asynchronous operation.</returns>
    public async Task SkipUntilLabelAsync(string label)
    {
        try
        {
            _readToLabel = false;
            _nextLabel = label;
            _skip = true;
            await RunAsync();
        }
        finally
        {
            _skip = false;
        }

        if (!_readToLabel)
        {
            throw new Exception($"Label {label} not found.");
        }
    }

    /// <inheritdoc />
    public override async Task<Result> RunAsync(CancellationToken stopRequested = default)
    {
        var packetRegex = new Regex(LineRegex);
        var labelRegex = new Regex(LabelRegex);
        while (!_reader.EndOfStream)
        {
            stopRequested.ThrowIfCancellationRequested();
            var line = await _reader.ReadLineAsync(stopRequested);
            if (string.IsNullOrEmpty(line))
            {
                continue;
            }

            var labelMatch = labelRegex.Match(line);
            if (labelMatch.Success)
            {
                var label = labelMatch.Groups[1].Value;
                if (label == _nextLabel)
                {
                    _readToLabel = true;
                    break;
                }

                continue;
            }

            if (_skip)
            {
                continue;
            }

            var packetMatch = packetRegex.Match(line);
            if (!packetMatch.Success)
            {
                _logger.LogWarning($"Could not find match on line {line}");
                continue;
            }

            var type = packetMatch.Groups[1].Value;
            var packetStr = packetMatch.Groups[2].Value;

            var source = type == "Recv" ? PacketSource.Server : PacketSource.Client;
            var packet = CreatePacket(packetStr, source);
            Result result = await _packetHandler.HandlePacketAsync
            (
                this,
                source,
                packet,
                packetStr,
                stopRequested
            );
            if (!result.IsSuccess)
            {
                _logger.LogResultError(result);
            }
        }

        return Result.FromSuccess();
    }

    /// <inheritdoc/>
    public override Task<Result> SendPacketAsync(string packetString, CancellationToken ct = default)
    {
        return _packetHandler.HandlePacketAsync
        (
            this,
            PacketSource.Client,
            CreatePacket(packetString, PacketSource.Client),
            packetString,
            ct
        );
    }

    /// <inheritdoc/>
    public override Task<Result> ReceivePacketAsync(string packetString, CancellationToken ct = default)
    {
        return _packetHandler.HandlePacketAsync
        (
            this,
            PacketSource.Server,
            CreatePacket(packetString, PacketSource.Server),
            packetString,
            ct
        );
    }

    private IPacket CreatePacket(string packetStr, PacketSource source)
    {
        var packetResult = _packetSerializer.Deserialize(packetStr, source);
        if (!packetResult.IsSuccess)
        {
            if (packetResult.Error is PacketConverterNotFoundError err)
            {
                return new UnresolvedPacket(err.Header, packetStr);
            }

            return new ParsingFailedPacket(packetResult, packetStr);
        }

        return packetResult.Entity;
    }

    /// <inheritdoc />
    public void Dispose()
    {
        _stream.Dispose();
        _reader.Dispose();
    }
}
Do not follow this link