-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEvents.cs
More file actions
253 lines (224 loc) · 8.29 KB
/
Events.cs
File metadata and controls
253 lines (224 loc) · 8.29 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Cognite.Extractor.Common;
using CogniteSdk;
using Moq;
using Xunit;
namespace Cognite.Extractor.Testing.Mock
{
/// <summary>
/// Mock implementation of the Events API.
/// </summary>
public class EventsMock
{
private long _nextId = 10000;
private readonly Dictionary<string, Event> _eventsByExternalId = new Dictionary<string, Event>();
private readonly Dictionary<long, Event> _eventsById = new Dictionary<long, Event>();
/// <summary>
/// All mocked events.
/// </summary>
public ICollection<Event> Events => _eventsById.Values;
/// <summary>
/// Mock an event, assigning it an ID.
/// </summary>
/// <param name="ev">Event to add.</param>
public void MockEvent(Event ev)
{
if (ev == null) throw new ArgumentNullException(nameof(ev));
ev.Id = _nextId++;
_eventsById[ev.Id] = ev;
if (!string.IsNullOrEmpty(ev.ExternalId))
{
_eventsByExternalId[ev.ExternalId] = ev;
}
}
/// <summary>
/// Remove a mocked event by its external ID, if it is present.
/// </summary>
/// <param name="externalId">External ID of event to remove.</param>
public bool Remove(string externalId)
{
if (_eventsByExternalId.TryGetValue(externalId, out var ev))
{
_eventsByExternalId.Remove(externalId);
_eventsById.Remove(ev.Id);
return true;
}
return false;
}
/// <summary>
/// Mock an event with the given external ID, assigning it an ID.
/// </summary>
/// <param name="externalId">External ID of the event to add.</param>
public void MockEvent(string externalId)
{
MockEvent(new Event
{
ExternalId = externalId,
Type = "someType",
StartTime = DateTime.UtcNow.ToUnixTimeMilliseconds(),
EndTime = DateTime.UtcNow.ToUnixTimeMilliseconds(),
CreatedTime = DateTime.UtcNow.ToUnixTimeMilliseconds(),
LastUpdatedTime = DateTime.UtcNow.ToUnixTimeMilliseconds(),
});
}
/// <summary>
/// Get an event by its identity, if it exists.
/// </summary>
/// <param name="id">Event ID</param>
/// <returns>The event, if it exists.</returns>
public Event? GetEvent(Identity id)
{
if (id == null) throw new ArgumentNullException(nameof(id));
if (id.Id.HasValue && _eventsById.TryGetValue(id.Id.Value, out var ev))
{
return ev;
}
else if (!string.IsNullOrEmpty(id.ExternalId) && _eventsByExternalId.TryGetValue(id.ExternalId, out var ev2))
{
return ev2;
}
return null;
}
/// <summary>
/// Get an event by its external ID, if it exists.
/// </summary>
/// <param name="externalId">Event external ID</param>
/// <returns>The event, if it exists.</returns>
public Event? GetEvent(string externalId)
{
if (externalId == null) throw new ArgumentNullException(nameof(externalId));
if (_eventsByExternalId.TryGetValue(externalId, out var ev))
{
return ev;
}
return null;
}
/// <summary>
/// Get an event by its internal ID, if it exists.
/// </summary>
/// <param name="id">Event ID</param>
/// <returns>The event, if it exists.</returns>
public Event? GetEvent(long id)
{
if (_eventsById.TryGetValue(id, out var ev))
{
return ev;
}
return null;
}
/// <summary>
/// Clear the events mock, removing all mocked events.
/// </summary>
public void Clear()
{
_nextId = 10000;
_eventsByExternalId.Clear();
_eventsById.Clear();
}
/// <summary>
/// Get a matcher for the /events/byids endpoint.
/// </summary>
/// <param name="times">Expected number of executions.</param>
public RequestMatcher MakeGetByIdsMatcher(Times times)
{
return new SimpleMatcher("POST", "/events/byids", EventsByIdsImpl, times);
}
/// <summary>
/// Get a matcher for the /events endpoint for creating events.
/// </summary>
/// <param name="times">Expected number of executions.</param>
public RequestMatcher MakeCreateEventsMatcher(Times times)
{
return new SimpleMatcher("POST", "/events$", EventsCreateImpl, times);
}
private async Task<HttpResponseMessage> EventsCreateImpl(RequestContext context, CancellationToken token)
{
var events = await context.ReadJsonBody<ItemsWithoutCursor<EventCreate>>().ConfigureAwait(false);
Assert.NotNull(events);
var created = new List<Event>();
var conflict = new List<string>();
foreach (var ev in events.Items)
{
if (ev.ExternalId != null && _eventsByExternalId.ContainsKey(ev.ExternalId))
{
conflict.Add(ev.ExternalId);
continue;
}
var newEvent = new Event
{
Id = _nextId++,
ExternalId = ev.ExternalId,
Type = ev.Type,
StartTime = ev.StartTime,
EndTime = ev.EndTime,
Source = ev.Source,
Description = ev.Description,
CreatedTime = DateTime.UtcNow.ToUnixTimeMilliseconds(),
LastUpdatedTime = DateTime.UtcNow.ToUnixTimeMilliseconds(),
Metadata = ev.Metadata,
};
_eventsById[newEvent.Id] = newEvent;
if (newEvent.ExternalId != null)
{
_eventsByExternalId[newEvent.ExternalId] = newEvent;
}
created.Add(newEvent);
}
if (conflict.Count > 0)
{
return context.CreateError(new CogniteError
{
Code = 409,
Message = "Conflict",
Duplicated = conflict.Distinct().Select(id => MockUtils.ToMultiValueDict(new Identity(id))).ToList()
});
}
return context.CreateJsonResponse(new ItemsWithoutCursor<Event> { Items = created });
}
private async Task<HttpResponseMessage> EventsByIdsImpl(RequestContext context, CancellationToken token)
{
var ids = await context.ReadJsonBody<ItemsWithIgnoreUnknownIds<RawIdentity>>().ConfigureAwait(false);
Assert.NotNull(ids);
var found = new List<Event>();
var missing = new List<Identity>();
foreach (var id in ids.Items)
{
Event? ev = null;
if (id.Id.HasValue)
{
_eventsById.TryGetValue(id.Id.Value, out ev);
}
else if (!string.IsNullOrEmpty(id.ExternalId))
{
_eventsByExternalId.TryGetValue(id.ExternalId, out ev);
}
if (ev != null)
{
found.Add(ev);
}
else
{
missing.Add(id.ToIdentity());
}
}
if (!ids.IgnoreUnknownIds && missing.Count > 0)
{
return context.CreateError(new CogniteError
{
Code = 400,
Message = "Events not found",
Missing = missing.Distinct().Select(MockUtils.ToMultiValueDict).ToList(),
});
}
return context.CreateJsonResponse(new ItemsWithoutCursor<Event>
{
Items = found
});
}
}
}