C# Client Library
A C# Client Library for the AnalyzeRe REST API
Loading...
Searching...
No Matches
Test_API_HTTPS.cs
Go to the documentation of this file.
1using System;
2using System.Diagnostics;
3using System.IO;
4using System.Security.Authentication;
5
6using AnalyzeRe;
10
11using RestSharp;
12#if MSTEST
13using Microsoft.VisualStudio.TestTools.UnitTesting;
14#elif NUNIT
15using NUnit.Framework;
16using TestClass = NUnit.Framework.TestFixtureAttribute;
17using TestMethod = NUnit.Framework.TestAttribute;
18using TestCategory = NUnit.Framework.CategoryAttribute;
19#endif
20
22{
23 [TestClass]
25 {
26 private const string TestCategory = "HTTPS API Server";
27
28 private readonly string _httpsUrl = EnvironmentSettings.API_URL;
29
30 #region Test Setup
32 {
34 {
35 // Cannot test different API configurations in parallel with a static API
36 // These tests are all disabled because changing the API's authentication settings
37 // while tests are running in parallel will cause other running tests to fail
38 Assert.Inconclusive("ARE-939 - non-static API");
39
41 });
42 // Purge the automatically cached authentication credentials for the test server.
44 }
45 #endregion Test Setup
46
47 #region Test Valid Credentials
48 [TestMethod, TestCategory(TestCategory)]
50 {
51 API.AuthenticationToken = GetCorrectCredentials();
53 Assert.AreEqual(AccessTokenStatus.Valid, API.AuthenticationToken.status);
54 }
55
56 [TestMethod, TestCategory(TestCategory)]
58 {
59 API.AuthenticationRequested += ValidAuthenticationRequestedHandler;
61 Assert.AreEqual(AccessTokenStatus.Valid, API.AuthenticationToken.status);
62 }
63
64 [TestMethod, TestCategory(TestCategory)]
66 {
67 API.AuthenticationRequested += (ref IAccessToken authenticate, string auth) =>
68 Console.WriteLine("I'm just an AuthenticationRequested logger.");
69 API.AuthenticationRequested += ValidAuthenticationRequestedHandler;
70 API.AuthenticationRequested += (ref IAccessToken authenticate, string auth) =>
71 Console.WriteLine("I'm just an AuthenticationRequested logger too.");
73 Assert.AreEqual(AccessTokenStatus.Valid, API.AuthenticationToken.status);
74 }
75 #endregion Test Valid Credentials
76
77 #region Test Invalid AuthenticationToken Credentials
78 [TestMethod, TestCategory(TestCategory)]
80 {
81 API.AuthenticationToken = null;
82 TestUnauthorizedRequest("The server requires authorization, but no authentication " +
83 "settings have been configured. Please either handle the " +
84 "API.AuthenticationRequested event appropriately, or set " +
85 "the global default AnalyzeRe.API.AuthenticationToken directly.");
86 }
87
88 [TestMethod, TestCategory(TestCategory)]
90 {
91 API.AuthenticationToken = new BasicAuthenticationToken("bad", "bad");
92 Assert.AreEqual(AccessTokenStatus.Unknown, API.AuthenticationToken.status);
93 TestUnauthorizedRequest("The server requires authentication, and the current " +
94 "authentication token " + @"(Basic YmFkOmJhZA==)" +
95 " was rejected. Please verify the credentials supplied.");
96 Assert.AreEqual(AccessTokenStatus.Unauthorized, API.AuthenticationToken.status);
97 }
98
99 [TestMethod, TestCategory(TestCategory)]
101 {
102 API.AuthenticationToken = new BasicAuthenticationToken();
103 Assert.AreEqual(AccessTokenStatus.Unknown, API.AuthenticationToken.status);
104 TestUnauthorizedRequest("The server requires authentication, and the current " +
105 "authentication token " + @"(Basic )" +
106 " was rejected. Please verify the credentials supplied.");
107 Assert.AreEqual(AccessTokenStatus.Unauthorized, API.AuthenticationToken.status);
108 }
109
110 [TestMethod, TestCategory(TestCategory)]
112 {
113 API.AuthenticationToken = new BasicAuthenticationToken(null, null);
114 Assert.AreEqual(AccessTokenStatus.Unknown, API.AuthenticationToken.status);
115 TestUnauthorizedRequest("The server requires authentication, and the current " +
116 "authentication token " + @"(Basic Og==)" +
117 " was rejected. Please verify the credentials supplied.");
118 Assert.AreEqual(AccessTokenStatus.Unauthorized, API.AuthenticationToken.status);
119 }
120 #endregion Test Invalid AuthenticationToken Credentials
121
122 #region Test Invalid AuthenticationRequested Event
128 [TestMethod, TestCategory(TestCategory)]
130 {
131 API.AuthenticationRequested += (ref IAccessToken authenticate, string auth) =>
132 ((BasicAuthenticationToken)authenticate).GenerateAccessToken("bad", "bad");
133 TestUnauthorizedRequest("Request failed after " + API.MaxRequestRetries +
134 " failed authentication attempts.");
135 Assert.AreEqual(AccessTokenStatus.Unauthorized, API.AuthenticationToken.status);
136 }
137
138 [TestMethod, TestCategory(TestCategory)]
140 {
141 TestUnauthorizedRequest("The server requires authorization, but no authentication " +
142 "settings have been configured. Please either handle the " +
143 "API.AuthenticationRequested event appropriately, or set " +
144 "the global default AnalyzeRe.API.AuthenticationToken directly.");
145 Assert.IsNull(API.AuthenticationToken);
146 }
147
148 [TestMethod, TestCategory(TestCategory)]
150 {
151 API.AuthenticationRequested += (ref IAccessToken authenticate, string auth) => { };
152 TestUnauthorizedRequest("The server requires authentication.");
153 Assert.IsNull(API.AuthenticationToken);
154 }
155
156 [TestMethod, TestCategory(TestCategory)]
158 {
159 API.AuthenticationRequested += (ref IAccessToken authenticate, string auth) =>
160 { throw new Exception("I don't know what I'm doing"); };
161 TestUnauthorizedRequest("Error while invoking the AuthenticationRequested event: " +
162 "I don't know what I'm doing");
163 Assert.IsNull(API.AuthenticationToken);
164 }
165 #endregion Test Invalid AuthenticationRequested Event
166
167 #region Test GetAuthenticationStatus
168 [TestMethod, TestCategory(TestCategory)]
170 {
171 API.AuthenticationToken = null;
172 Assert.AreEqual(AuthenticationStatus.AuthenticationRequired, API.GetAuthenticationStatus());
173 }
174
175 [TestMethod, TestCategory(TestCategory)]
177 {
178 API.AuthenticationToken = GetCorrectCredentials();
179 Assert.AreEqual(AuthenticationStatus.Authenticated, API.GetAuthenticationStatus());
180 Assert.AreEqual(AccessTokenStatus.Valid, API.AuthenticationToken.status);
181 }
182
183 [TestMethod, TestCategory(TestCategory), TestCategory("Skipped")]
185 {
186 // With API v1, we only support HTTPS & BasicAuth. This test can be removed when
187 // AuthenticationStatus.NoAuthenticationRequired is eliminated as a possible enumeration value.
188 Skip.Indefinitely("The default test URL requires authentication, so we " +
189 "cannot test the response when a server doesn't require authentication.");
190 API.ServerURL = _httpsUrl;
191 Assert.AreEqual(AuthenticationStatus.NoAuthenticationRequired, API.GetAuthenticationStatus());
192 }
193
194 [TestMethod, TestCategory(TestCategory)]
196 {
197 API.AuthenticationToken = new BasicAuthenticationToken("bad", "bad");
198 Assert.AreEqual(AuthenticationStatus.InvalidCredentials, API.GetAuthenticationStatus());
199 Assert.AreEqual(AccessTokenStatus.Unauthorized, API.AuthenticationToken.status);
200 }
201
202 [TestMethod, TestCategory(TestCategory)]
204 {
205 API.ServerURL = "Invalid";
206 Assert.AreEqual(AuthenticationStatus.Error, API.GetAuthenticationStatus());
207 }
208 #endregion Test GetAuthenticationStatus
209
210 #region Test Credential Caching
212 [TestMethod, TestCategory(TestCategory)]
214 {
215 API.AuthenticationRequested += ValidAuthenticationRequestedHandler;
217 API.AuthenticationRequested -= ValidAuthenticationRequestedHandler;
218 Assert.AreEqual(AccessTokenStatus.Valid, API.AuthenticationToken.status);
219 // Reset the server URL. The API will automatically reset the AuthenticationToken as well.
220 API.ServerURL = null;
221 Assert.IsNull(API.AuthenticationToken);
222 // ReSharper disable HeuristicUnreachableCode (API alters AuthenticationToken)
223 API.ServerURL = _httpsUrl;
224 Assert.IsNotNull(API.AuthenticationToken);
225 Assert.AreEqual(AccessTokenStatus.Valid, API.AuthenticationToken.status);
227 // ReSharper restore HeuristicUnreachableCode
228 }
229
231 [TestMethod, TestCategory(TestCategory)]
233 {
234 API.AuthenticationRequested += ValidAuthenticationRequestedHandler;
236 API.AuthenticationRequested -= ValidAuthenticationRequestedHandler;
237 Assert.AreEqual(AccessTokenStatus.Valid, API.AuthenticationToken.status);
238 // Reset the server URL. The API will automatically reset the AuthenticationToken as well.
239 API.ServerURL = null;
240 Assert.IsNull(API.AuthenticationToken);
241 // ReSharper disable HeuristicUnreachableCode (API alters AuthenticationToken)
242 // Same as previous test but now we clear the cache:
244 API.ServerURL = _httpsUrl;
245 Assert.IsNull(API.AuthenticationToken);
246 TestUnauthorizedRequest("The server requires authorization, but no authentication " +
247 "settings have been configured. Please either handle the " +
248 "API.AuthenticationRequested event appropriately, or set " +
249 "the global default AnalyzeRe.API.AuthenticationToken directly.");
250 // ReSharper restore HeuristicUnreachableCode
251 }
252
253 #endregion Test Credential Caching
254
255 #region Miscellaneous Tests
258 [TestMethod, TestCategory(TestCategory)]
260 {
261 Assert.IsTrue(API.IsAReServerActive(_httpsUrl),
262 "No active server found at " + _httpsUrl);
263 }
264
266 [TestMethod, TestCategory(TestCategory)]
268 {
269 // First, set up the valid credentials
270 API.AuthenticationRequested += ValidAuthenticationRequestedHandler;
271 // Now inject a resource with data
273
274 // Next, delete the credentials so that the next request is unauthorized
275 API.AuthenticationToken = null;
276 void StreamReader(Stream stream) =>
277 Console.WriteLine("Stream contained:\n" + new StreamReader(stream).ReadToEnd());
278 void TestGetStream() => eventCatalog.data.GetStream(StreamReader);
279 // Now request a stream, expecting to get an authentication error
280 AssertApi.ExceptionThrown<APIRequestException>(TestGetStream, ex => Assert.AreEqual(
281 "The initial request could not be completed due to an authentication error. " +
282 "Please reset the stream and try again."
283 , ex.Message));
284 // This should still have fired the event, setting up credentials for us,
285 // but these credentials haven't been validated yet.
286 Assert.IsNotNull(API.AuthenticationToken);
287 Assert.AreEqual(AccessTokenStatus.Unauthorized, API.AuthenticationToken.status);
288 // We should be authenticated now, so a second call shouldn't raise an exception
289 TestGetStream();
290 Assert.AreEqual(AccessTokenStatus.Valid, API.AuthenticationToken.status);
291
293 }
294 #endregion Miscellaneous Tests
295
296 #region Test Override Authentication
299 [TestMethod, TestCategory(TestCategory)]
301 {
302 API.GetResourceList<AnalysisProfile>(new[]{ new Parameter
303 {
304 Name = "Authorization",
305 Value = GetCorrectCredentials().ToString(),
306 Type = ParameterType.HttpHeader
307 }});
308 // The global default authentication token should still not be set
309 Assert.IsNull(API.AuthenticationToken);
310 }
311
314 [TestMethod, TestCategory(TestCategory)]
316 {
317 AssertApi.ExceptionThrown<AuthenticationException>(() =>
318 API.GetResourceList<AnalysisProfile>(new[]{ new Parameter
319 {
320 Name = "Authorization",
321 Value = "bad",
322 Type = ParameterType.HttpHeader
323 }}),
324 ex => Assert.AreEqual(
325 "The current request included an authentication token (bad) " +
326 "which was rejected by the server. Either correct the \"Authorization\" " +
327 "header parameter supplied to this request, or exclude it entirely and use " +
328 "the 'API.AuthenticationRequested' event or 'API.AuthenticationToken' to " +
329 "automatically handle authentication for Analyze Re API requests."
330 , ex.Message));
331 }
332
335 [TestMethod, TestCategory(TestCategory)]
337 {
338 BasicAuthenticationToken token = new BasicAuthenticationToken("bad", "bad");
339 API.AuthenticationToken = token;
340 AssertApi.ExceptionThrown<AuthenticationException>(() =>
341 API.GetResourceList<AnalysisProfile>(new[]{ new Parameter
342 {
343 Name = "Authorization",
344 Value = token.ToString(),
345 Type = ParameterType.HttpHeader
346 }}),
347 ex => Assert.AreEqual(
348 "The current request included an authentication token (Basic YmFkOmJhZA==) " +
349 "which was rejected by the server. Either correct the \"Authorization\" " +
350 "header parameter supplied to this request, or exclude it entirely and use " +
351 "the 'API.AuthenticationRequested' event or 'API.AuthenticationToken' to " +
352 "automatically handle authentication for Analyze Re API requests."
353 , ex.Message));
354 }
355
359 [TestMethod, TestCategory(TestCategory)]
361 {
362 API.AuthenticationToken = GetCorrectCredentials();
363 AssertApi.ExceptionThrown<AuthenticationException>(() =>
364 API.GetResourceList<AnalysisProfile>(new[]{ new Parameter
365 {
366 Name = "Authorization",
367 Value = "bad",
368 Type = ParameterType.HttpHeader
369 }}),
370 ex => Assert.AreEqual(
371 "The current request included an authentication token (bad) which was rejected " +
372 "by the server, and which differs from the currently configured default " +
373 "authentication token (" + GetCorrectCredentials().ToString() + "). Either " +
374 "correct the \"Authorization\" header parameter supplied to this request, " +
375 "or exclude it entirely and the default authentication token will be used."
376 , ex.Message));
377 }
378 #endregion Test Override Authentication
379
380 #region Helper Methods
381 private void ValidAuthenticationRequestedHandler(ref IAccessToken authenticate, string auth)
382 {
383 ((BasicAuthenticationToken)authenticate).GenerateAccessToken(
385 }
386
393
395 {
397 }
398
399 public void TestUnauthorizedRequest(string expectedMessage)
400 {
401 AssertApi.ExceptionThrown<AuthenticationException>(
402 () => API.GetResourceList<AnalysisProfile>(), ex =>
403 {
404 Assert.AreEqual(expectedMessage, ex.Message);
405 Debug.WriteLine("Caught expected exception: " + ex);
406 });
407 }
408 #endregion Helper Methods
409 }
410}
void AddCommonTestCleanupAction(Action action)
void AddCommonTestInitializeAction(Action action)
Exposes sample resource objects, with built-in methods for injecting dependencies.
Definition Samples.cs:14
IInjectableResource< EventCatalog > EventCatalog
void Test_API_HTTPS_Server_Credentials_Cached()
Note: Credential caching only works using the AuthenticationRequested event.
void Test_API_HTTPS_Server_Active()
Ensure that the server shows up as an active analyze re server, even without credentials.
void Test_API_HTTPS_Server_OverrideAuthentication_Invalid_MatchingDefaultAuth()
Test that overriding the default authentication credentials with the same bad parameters results in a...
void Test_API_HTTPS_Server_AuthenticationRequestedEvent_Invalid()
Test an authentication handler incorrectly set up to supply the same invalid credentials on every cal...
void Test_API_HTTPS_Server_AuthenticationRequestedEvent_GetStream()
Test that an authentication error on GetStream expected behaviour.
void Test_API_HTTPS_Server_OverrideAuthentication_Valid()
Test that the user can supply credentials without setting the global default authentication settings.
void Test_API_HTTPS_Server_OverrideAuthentication_Invalid_NoDefaultAuth()
Test that manually specifying incorrect authentication credentials when there are no default credenti...
void Test_API_HTTPS_Server_CachedCredentialsCleared()
Note: Credential caching only works using the AuthenticationRequested event.
void Test_API_HTTPS_Server_OverrideAuthentication_Invalid_NotMatchingDefaultAuth()
Test that overriding the current default authentication credentials (which are good) with some bad pa...
Retrieve settings from environment variables if they exist, or the project settings file otherwise.
static string API_URL
The URL against which server tests are run.
static string HTTPS_USER
The username for the HTTPS server authentication.
static string HTTPS_PASSWORD
The password for the HTTPS server authentication.
Class used in unit tests to mark tests as skipped by using Assert.Inconclusive() method.
Definition SkipUntil.cs:14
static void Indefinitely(string ticket=null)
Skip the specified test.
Definition SkipUntil.cs:54
A custom exception class that includes the RestSharp.IRestResponse that generated the exception,...
LargeDataSubResource data
An endpoint for accessing or modifying the data file attached to this resource. Also contains a Large...
IRestResponse GetStream(Action< Stream > consumeStream, IEnumerable< Parameter > parameters=null, int? timeout=null)
Perform a GET on the supplied URL and provide an action for consuming the response stream rather than...
API methods / requests made available to the user.
static IAccessToken AuthenticationToken
The AccessToken storing authentication information for requests made to the server.
static volatile int MaxRequestRetries
When a temporary communication failure occurs (such as a socket error or an authentication failure fo...
static bool IsAReServerActive(string checkServerURL, int? timeout=null)
Determines if the provided URL is a valid running Analyze Re server.
static ICollectionResponse< IAPIResource > GetResourceList(Type resourceType, IEnumerable< Parameter > requestParameters=null, string collectionNameOverride=null, int? timeout=null)
Get a collection of resources from the server.
static AuthenticationStatus GetAuthenticationStatus(bool force_request=false)
Determines whether we are currently authenticated against the server with the global default Authenti...
static void ClearCachedAuthenticationCredentials(string server=null)
The Analyze Re API .NET Client Library caches authentication tokens that have been validated via the ...
A configuration of resources used to simulate a layer or portfolio.
An AccessToken storing basic authentication information for requests made to the server.
override string ToString()
Returns the representation of this access token that could be placed in an "Authorization" header.
Representation of an event catalog. The event catalog may cover multiple region/perils,...
T Posted
The posted resource, ready to be referenced.
An AccessToken storing authentication information for requests made to the server.
AccessTokenStatus status
The AccessToken's current AccessTokenStatus (unauthorized / valid).
AccessTokenStatus
An AccessToken's status (unauthorized / valid).
AuthenticationStatus
The status of authentication against the current server.