This repository has been archived by the owner on Apr 10, 2021. It is now read-only.
/
RavenDbTestBase.cs
294 lines (258 loc) · 12.8 KB
/
RavenDbTestBase.cs
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Embedded;
using WorldDomination.Raven.Client;
using WorldDomination.Raven.Client.Listeners;
namespace WorldDomination.Raven.Tests.Helpers
{
public abstract class RavenDbTestBase : IDisposable
{
//private bool _hasDocumentStoreBeenCreated = false;
private const string DefaultSessionKey = "DefaultSession";
private readonly Lazy<IDocumentStore> _documentStore;
private IDictionary<string, IAsyncDocumentSession> _asyncDocumentSessions;
private IList<IEnumerable> _dataToBeSeeded;
private ExistingDocumentStoreSettings _existingDocumentStoreSettings;
private IList<Type> _indexesToExecute;
protected RavenDbTestBase()
{
AlwaysWaitForNonStaleResultsAsOfLastWrite = true;
_documentStore = new Lazy<IDocumentStore>(() =>
{
var ds = CreateDocumentStoreAsync().ConfigureAwait(false);
return ds.GetAwaiter().GetResult();
});
}
/// <summary>
/// A collection of data, which will be 'seeded' during the document store initialization.
/// </summary>
protected IList<IEnumerable> DataToBeSeeded
{
get
{
Trace.TraceInformation(
"* {0} collection(s) of objects have been requested to be seeded (aka. Stored) in the database.",
_dataToBeSeeded == null
? 0
: _dataToBeSeeded.Count);
return _dataToBeSeeded;
}
set
{
// NOTE: why bother with this check? Because if the developer creates a document store and THEN
// tries to set this property, then the data will -not- be used. It's only used when the
// document store (in this library) is -first- created.
EnsureDocumentStoreHasNotBeenInitialized("DataToBeSeeded");
_dataToBeSeeded = value;
}
}
/// <summary>
/// Collection of Indexes which will be executed during the document store initialization.
/// </summary>
protected IList<Type> IndexesToExecute
{
get
{
Trace.TraceInformation("* {0} index(es)/result transformer(s) have been requested to be executed.",
_indexesToExecute == null
? 0
: _indexesToExecute.Count);
return _indexesToExecute;
}
set
{
EnsureDocumentStoreHasNotBeenInitialized("IndexesToExecute");
_indexesToExecute = value;
}
}
/// <summary>
/// Optional: provide an instance to an ExistingDocumentStoreSettings if you wish to connect to a real database.
/// </summary>
/// <remarks><b>CAREFUL!</b> This should rarely be used and most likely not during unit tests. The common scenario for using this is for some specific debugging against a real database (and hopefully that's a copy of some live database, also!) **</remarks>
protected ExistingDocumentStoreSettings ExistingDocumentStoreSettings
{
get { return _existingDocumentStoreSettings; }
set
{
if (DocumentStore != null)
{
throw new InvalidOperationException(
"The DocumentStore has already been created and Initialized. As such, the ExistingDocumentStoreSettings instance cannot be used. Therefore, set this value BEFORE your first call to a AsyncDocumentSession (which in effect creates the DocumentStore pointing to your desired location).");
}
_existingDocumentStoreSettings = value;
}
}
/// <summary>
/// Some custom document conventions. Eg. You might require a custom JsonContractResolver to serialize/deserialize IPAddresses.
/// </summary>
protected DocumentConvention DocumentConvention { get; set; }
/// <summary>
/// Block/Wait for the database to finish indexing any new data that was inserted.
/// </summary>
protected bool AlwaysWaitForNonStaleResultsAsOfLastWrite { get; set; }
/// <summary>
/// The main Document Store where all your lovely data will live and smile.
/// </summary>
protected IDocumentStore DocumentStore
{
get { return _documentStore.Value; }
}
/// <summary>
/// The 'default' Raven async document session.
/// </summary>
protected IAsyncDocumentSession AsyncDocumentSession
{
get { return AsyncDocumentSessions(DefaultSessionKey); }
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Trace.TraceInformation(
"Disposing of RavenDbTest class. This will clean up any Document Sessions and the Document Store.");
// NOTE: It's possible that an error occured while trying to create a document store.
// AS SUCH, the document store might not have been created correcfly.
// SO - please do NOT reference the property .. but the backing private member.
if (DocumentStore == null)
{
Trace.TraceInformation(" .... No RavenDb DocumentStore created - nothing to dispose of.");
return;
}
if (DocumentStore.WasDisposed)
{
Trace.TraceWarning(
"!!! DocumentStore was already disposed - so .. we can't dispose of it a 2nd time. Um .. you might want to check why it was already disposed, of....");
return;
}
// Assert for any errors.
Trace.TraceInformation("Asserting for any DocumentStore errors.");
DocumentStore.AssertDocumentStoreErrors();
// Clean up.
if (_asyncDocumentSessions != null)
{
Trace.TraceInformation("Found {0} Document Session{1} that exist. Lets clean them up :-",
_asyncDocumentSessions.Count,
_asyncDocumentSessions.Count == 1 ? string.Empty : "s");
foreach (var key in _asyncDocumentSessions.Keys)
{
Trace.TraceInformation(" - Found Key: " + key);
_asyncDocumentSessions[key].Dispose();
Trace.TraceInformation(" ... Document Session now disposed! ");
}
}
Trace.TraceInformation("Disposing the Document Store ... ");
DocumentStore.Dispose();
Trace.TraceInformation("Done!");
}
#endregion
/// <summary>
/// A named Raven async document session.
/// </summary>
/// <param name="key">The key name of an async document session.</param>
/// <returns>The RavenDb async document session.</returns>
protected IAsyncDocumentSession AsyncDocumentSessions(string key)
{
EnsureDocumentStoreHasBeenInitialized();
if (_asyncDocumentSessions == null)
{
Trace.TraceInformation("Creating a new async Document Session dictionary to hold all our sessions.");
_asyncDocumentSessions = new Dictionary<string, IAsyncDocumentSession>();
}
// Do we have the key?
if (!_asyncDocumentSessions.ContainsKey(key))
{
Trace.TraceInformation(
"Async Document Session Key [{0}] doesn't exist. Creating a new dictionary item.", key);
_asyncDocumentSessions.Add(key, DocumentStore.OpenAsyncSession());
}
return _asyncDocumentSessions[key];
}
private async Task<IDocumentStore> CreateDocumentStoreAsync()
{
IDocumentStore documentStore;
if (ExistingDocumentStoreSettings == null ||
string.IsNullOrWhiteSpace(ExistingDocumentStoreSettings.DocumentStoreUrl))
{
Trace.TraceInformation("Creating a new Embedded DocumentStore in **RAM**.");
Trace.TraceInformation(
"** NOTE: If you wish to target an existing document store, please set the 'DocumentStoreUrl' property.");
documentStore = new EmbeddableDocumentStore
{
RunInMemory = true,
Conventions = DocumentConvention ?? new DocumentConvention()
};
}
else
{
Trace.TraceInformation(
"The DocumentStore Url [{0}] was provided. Creating a new (normal) DocumentStore with a Tenant named [{1}].",
ExistingDocumentStoreSettings.DocumentStoreUrl,
ExistingDocumentStoreSettings.DefaultDatabase);
documentStore = new DocumentStore
{
Url = ExistingDocumentStoreSettings.DocumentStoreUrl,
DefaultDatabase = ExistingDocumentStoreSettings.DefaultDatabase,
Conventions = DocumentConvention ?? new DocumentConvention()
};
}
if (AlwaysWaitForNonStaleResultsAsOfLastWrite)
{
Trace.TraceInformation(
"Setting DocumentStore Conventions: ConsistencyOptions.AlwaysWaitForNonStaleResultsAsOfLastWrite. This means that the unit test will *always* wait for the index to complete before querying against it.");
documentStore.Conventions.DefaultQueryingConsistency =
ConsistencyOptions.AlwaysWaitForNonStaleResultsAsOfLastWrite;
}
else
{
Trace.TraceInformation(
"** NOTE: Not setting the ConsistencyOptions.AlwaysWaitForNonStaleResultsAsOfLastWrite option (as requested by you). This is generally when you are *streaming* some results from RavenDb.");
}
Trace.TraceInformation("Initializing data with Defaults :-");
await documentStore.InitializeWithDefaultsAsync(DataToBeSeeded, IndexesToExecute);
Trace.TraceInformation(" Done!");
// Force query's to wait for index's to catch up. Unit Testing only :P
Trace.TraceInformation(
"Forcing queries to always wait until they are not stale. aka. It's like => WaitForNonStaleResultsAsOfLastWrite.");
documentStore.Listeners.RegisterListener(new NoStaleQueriesListener());
Trace.TraceInformation("** Finished initializing the Document Store.");
Trace.TraceInformation(" ** Number of Documents: " +
documentStore.DatabaseCommands.GetStatistics().CountOfDocuments);
Trace.TraceInformation(" ** Number of Indexes: " +
documentStore.DatabaseCommands.GetStatistics().CountOfIndexes);
return documentStore;
}
private void EnsureDocumentStoreHasBeenInitialized()
{
if (DocumentStore == null)
{
var errorMessage =
string.Format(
"The DocumentStore has to be initialized before any operations can be processed against it.");
throw new InvalidOperationException(errorMessage);
}
}
private void EnsureDocumentStoreHasNotBeenInitialized(string listName)
{
if (string.IsNullOrWhiteSpace(listName))
{
throw new ArgumentNullException("listName");
}
if (_documentStore != null &&
_documentStore.IsValueCreated)
{
var errorMessage =
string.Format(
"The DocumentStore has already been created and Initialized. As such, changes to the {0} list will not be used. Therefore, set this collection BEFORE your first call to a DocumentSession (which in effect creates the DocumentStore if it has been created).",
listName);
throw new InvalidOperationException(errorMessage);
}
}
}
}