Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 22974ce0

Přidáno uživatelem Pultak před asi 2 roky(ů)

re #9443 Added implementation of tests for ApiClient

Zobrazit rozdíly:

ld_client/LDClientTests/LDClientTests.csproj
1
<Project Sdk="Microsoft.NET.Sdk">
1
<Project Sdk="Microsoft.NET.Sdk">
2 2

  
3 3
  <PropertyGroup>
4 4
    <TargetFramework>net6.0</TargetFramework>
ld_client/LDClientTests/network/ApiClientTests.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Net.Http;
5
using System.Net.Http.Json;
6
using System.Runtime.CompilerServices;
7
using System.Text;
8
using System.Text.Json;
9
using System.Threading;
10
using System.Threading.Tasks;
11
using DiskQueue;
12
using LDClient.network;
13
using LDClient.network.data;
14
using Moq;
15
using Newtonsoft.Json.Serialization;
16
using NUnit.Framework;
17
using NUnit.Framework.Internal;
18

  
19

  
20
namespace LDClientTests.network {
21
    internal class ApiClientTests {
22

  
23
        private ApiClient _client;
24

  
25
        
26
        private Mock<IHttpClient> _httpClientMock;
27

  
28
        private Mock<IPersistentQueue> _cacheMock;
29
        private Mock<IPersistentQueueSession> _cacheSessionMock;
30

  
31
        public static readonly Payload ExamplePayload = new() {
32
            UserName = "honikCz",
33
            HostName = "Bramborak",
34
            TimeStamp = "2022-03-21 18:05:00",
35
            HeadDevice = new DebuggerInfo {
36
                SerialNumber = "C12345678912"
37
            },
38
            BodyDevice = new DebuggerInfo {
39
                SerialNumber = "C98765432198"
40
            },
41
            Status = ConnectionStatus.Connected
42
        };
43
        
44
        public static readonly string ApiUrl = "http://127.0.0.1";
45
        public static readonly string ApiEndPoint = "/lauterbach-debugger-logs/";
46
        public static readonly uint ApiPort = 8000;
47
        public static readonly uint ApiRetryPeriod = 50;
48
        public static readonly uint ApiMaxEntries = 10;
49
        public static readonly uint ApiMaxRetries = 5;
50
        
51
        
52
        [SetUp]
53
        public void Setup() {
54
            
55
            _httpClientMock = new Mock<IHttpClient>(MockBehavior.Strict);
56
            _cacheMock = new Mock<IPersistentQueue>(MockBehavior.Strict);
57

  
58
            _cacheSessionMock = new Mock<IPersistentQueueSession>(MockBehavior.Strict);
59
            _cacheSessionMock.Setup(x => x.Dequeue()).Returns(JsonSerializer.SerializeToUtf8Bytes(ExamplePayload));
60
            _cacheSessionMock.Setup(x => x.Dispose()).Callback(() => { });
61
            _cacheSessionMock.Setup(p => p.Enqueue(It.IsAny<byte[]>())).Callback(() => { });
62
            _cacheSessionMock.Setup(p => p.Flush()).Callback(() => { });
63

  
64
            _cacheMock.Setup(p => p.OpenSession()).Returns(_cacheSessionMock.Object);
65

  
66
            _client = new ApiClient(ApiUrl, ApiPort, ApiEndPoint, ApiRetryPeriod, ApiMaxEntries, ApiMaxRetries, _cacheMock.Object) {
67
                _client = _httpClientMock.Object
68
            };
69
        }
70

  
71

  
72
        [Test]
73
        public async Task SendPayloadAsync_SendingSuccess_PayloadSent() {
74
            _httpClientMock.Setup(p => p.PostAsJsonAsync(It.IsAny<Payload>()))
75
                .Returns(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)));
76

  
77
            await _client.SendPayloadAsync(ExamplePayload);
78

  
79
            _httpClientMock.Verify(x => x.PostAsJsonAsync(It.IsAny<Payload>()), Times.Once);
80
        }
81

  
82

  
83
        [Test]
84
        [TestCase(15, true)]
85
        [TestCase(0, false)]
86
        public async Task SendPayloadAsync_SendingFailure_PayloadSaved2Cache(int itemsInQueueCount, bool isDequeueHappening) {
87

  
88
            _httpClientMock.Setup(p => p.PostAsJsonAsync(It.IsAny<Payload>()))
89
                .Returns(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.UnprocessableEntity)));
90
            _cacheMock.Setup(p => p.EstimatedCountOfItemsInQueue).Returns(itemsInQueueCount);
91

  
92
            await _client.SendPayloadAsync(ExamplePayload);
93
            
94
            _cacheSessionMock.Verify(p => p.Enqueue(It.IsAny<byte[]>()), Times.Once);
95
            _httpClientMock.Verify(x => x.PostAsJsonAsync(It.IsAny<Payload>()), Times.Once);
96
            _cacheSessionMock.Verify(x => x.Flush(), Times.Once);
97
            
98
            _cacheSessionMock.Verify(x => x.Dequeue(), isDequeueHappening ? Times.Once : Times.Never);
99
        }
100

  
101

  
102
        [Test]
103
        [Timeout(1000)]
104
        public void Run_EmptyCache_NothingSent() {
105
            //nothing in cache 
106
            _cacheMock.Setup(p => p.EstimatedCountOfItemsInQueue).Returns(0);
107
            _httpClientMock.Setup(p => p.PostAsJsonAsync(It.IsAny<Payload>()))
108
                .Returns(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.UnprocessableEntity)));
109

  
110
            var clientThread = new Thread(_client.Run);
111

  
112
            clientThread.Start();
113
            Thread.Sleep(400);
114
            _client.ClientRunning = false;
115
            //_processDetection.DetectionRunning = false;
116
            clientThread.Join();
117

  
118
            _httpClientMock.Verify(p => p.PostAsJsonAsync(It.IsAny<Payload>()), Times.Never);
119
            _cacheSessionMock.Verify(p => p.Enqueue(It.IsAny<byte[]>()), Times.Never);
120
            _cacheSessionMock.Verify(p => p.Flush(), Times.Never);
121
            _cacheMock.Verify(p => p.EstimatedCountOfItemsInQueue, Times.AtLeastOnce);
122

  
123
        }
124

  
125
        /// <summary>
126
        /// Some tests here can fail due to not long enough sleep period.
127
        /// 
128
        /// </summary>
129
        /// <param name="itemsInQueueCount"></param>
130
        /// <param name="flushedHappened"></param>
131
        /// <param name="testSleep"></param>
132
        [Test]
133
        [Timeout(5000)]
134
        [TestCase(100, 20, 2000)]
135
        [TestCase(15, 3, 600)]
136
        [TestCase(1, 1, 200)]
137
        [TestCase(6, 2, 400)]
138
        public void Run_CacheContainX_SentX(int itemsInQueueCount, int flushedHappened, int testSleep) {
139

  
140
            var cacheItemCount = itemsInQueueCount;
141
            //nothing in cache 
142
            _cacheMock.Setup(p => p.EstimatedCountOfItemsInQueue).Returns(() => { return cacheItemCount; });
143
            _httpClientMock.Setup(p => p.PostAsJsonAsync(It.IsAny<Payload>()))
144
                .Returns(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)));
145
            _cacheSessionMock.Setup(x => x.Dequeue())
146
                .Returns(() => {
147
                    --cacheItemCount;
148
                    return JsonSerializer.SerializeToUtf8Bytes(ExamplePayload);
149
                });
150

  
151
            var clientThread = new Thread(_client.Run);
152

  
153
            clientThread.Start();
154
            Thread.Sleep(testSleep);
155
            _client.ClientRunning = false;
156
            //_processDetection.DetectionRunning = false;
157
            clientThread.Join();
158

  
159
            _httpClientMock.Verify(p => p.PostAsJsonAsync(It.IsAny<Payload>()), Times.Exactly(itemsInQueueCount));
160
            _cacheSessionMock.Verify(p => p.Enqueue(It.IsAny<byte[]>()), Times.Never);
161
            _cacheSessionMock.Verify(p => p.Flush(), Times.Exactly(flushedHappened));
162
            _cacheMock.Verify(p => p.EstimatedCountOfItemsInQueue, Times.AtLeastOnce);
163
        }
164
        
165

  
166
    }
167
}

Také k dispozici: Unified diff