C# Client Library
A C# Client Library for the AnalyzeRe REST API
Loading...
Searching...
No Matches
Test_API_Utilities.cs
Go to the documentation of this file.
1using System;
2using System.Net;
3using System.Security.Authentication;
4
5using AnalyzeRe;
12
13using RestSharp;
14#if MSTEST
15using Microsoft.VisualStudio.TestTools.UnitTesting;
16#elif NUNIT
17using NUnit.Framework;
18using TestClass = NUnit.Framework.TestFixtureAttribute;
19using TestMethod = NUnit.Framework.TestAttribute;
20using TestCategory = NUnit.Framework.CategoryAttribute;
21#endif
22
24{
25 [TestClass]
27 {
28 private const string TestCategory = "API Utilities";
29
31 {
33 {
34 // All tests in this class require a connection.
36 Assert.Inconclusive("RUN_OFFLINE = true");
37 });
38 }
39
40 [TestMethod, TestCategory(TestCategory)]
42 {
43 ELTLossSet mock = new ELTLossSet();
44 // Test various requests that should check the ID first.
45 AssertApi.ExceptionThrown<ArgumentException>(() => mock.Get());
46 AssertApi.ExceptionThrown<ArgumentException>(() => mock.Put());
47 AssertApi.ExceptionThrown<ArgumentException>(() => mock.PollUntilReady());
48 AssertApi.ExceptionThrown<ArgumentException>(() => mock.data.LargeFileUpload(null));
49 // POST should go through because no ID is required (but the server will return some other error)
50 AssertApi.ExceptionThrown<APIRequestException>(() => mock.Post());
51 // If the resource is given an ID, above requests should now work (but the server will now return a NotFound exception)
53 AssertApi.ExceptionThrown<APIRequestException>(() => mock.Get());
54
55 // Also test a few of the request methods for views
56 ILayerView mock_lv = new LayerView<ILayer>();
57 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.Get());
58 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.expected_loss(MetricsOptions.Default));
59 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.tail_metrics(1, MetricsOptions.Default));
60 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.tail_metrics_blocking(1, MetricsOptions.Default));
61 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.window_metrics(ProbabilityWindow.All, MetricsOptions.Default));
62 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.window_metrics_blocking(ProbabilityWindow.All, MetricsOptions.Default));
63 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.exceedance_probability(1, ExceedanceProbabilityOptions.Default));
64 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.co_metrics_blocking(ProbabilityWindow.All, mock_lv.ToReference(), CoMetricsOptions.Default));
65 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.co_metrics_blocking(ProbabilityWindow.All, mock_lv.ToReference(), CoMetricsOptions.Default));
66 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.ylt.Get(MetricsOptions.Default));
67 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.yelt.Get(YELTOptions.Default));
68 // Test the legacy back_allocation endpoint
69#pragma warning disable 618
70 AssertApi.ExceptionThrown<ArgumentException>(() => mock_lv.back_allocations(null));
71#pragma warning restore 618
72 }
73
74 [TestMethod, TestCategory(TestCategory)]
76 {
77 // Test setup will have ensured that authentication credentials have been set up
78 Assert.AreEqual(AuthenticationStatus.Authenticated, API.GetAuthenticationStatus());
79 Assert.AreEqual(AccessTokenStatus.Valid, API.AuthenticationToken.status);
80 }
81
82 [TestMethod, TestCategory(TestCategory)]
84 {
85 // Test setup will have ensured that authentication credentials have been set up
86 // So this method should execute without having any effect.
88 }
89
90 [TestMethod, TestCategory(TestCategory)]
92 {
93 // When a response comes in with a temporary SSL/TSL error, we expect this method
94 // to return "true", indicating that the request should automatically be retried.
95 MockResponse mockResponse = MockResponse.Error(
96 new WebException("Could not create SSL/TLS secure channel"));
97 Assert.IsTrue(API.TryHandleAuthenticationErrors(mockResponse));
98 // If, however, this error has happened more than "MaxRequestRetries", it should throw
99 AssertApi.ExceptionThrown<AuthenticationException>(
101 }
102
103 [TestMethod, TestCategory(TestCategory)]
105 {
106 // When a response is successful, we expect this method to return "false",
107 // indicating that there is no authentication related actions to take.
108 MockResponse mockResponse = MockResponse.Completed(HttpStatusCode.Accepted);
109 Assert.IsFalse(API.TryHandleAuthenticationErrors(mockResponse));
110
111 // Similarity, we expect "false" if the response is a non-authentication failure
112 IRestResponse authenticatedNotFoundResponse = API.ExecuteRestRequest(
113 "non_existant_endpoint", Method.HEAD, returnRawResponse: true);
114 Assert.IsFalse(API.TryHandleAuthenticationErrors(authenticatedNotFoundResponse));
115 }
116
117 [TestMethod, TestCategory(TestCategory)]
119 {
120 // We expect the API to raise a particular error message if the user supplied their
121 // own authentication header which turned out to be invalid.
122 RequestParameters badAuthParameters = new RequestParameters();
123 badAuthParameters.AddParameter("Authorization", "BadCredentials", ParameterType.HttpHeader);
124 AssertApi.ExceptionThrown<AuthenticationException>(
125 () => API.ExecuteRestRequest("", Method.HEAD, badAuthParameters),
126 exception => Assert.IsTrue(exception.Message.StartsWith(
127 "The current request included an authentication token (BadCredentials) " +
128 "which was rejected by the server, and which differs from the currently " +
129 "configured default authentication token"),
130 exception.Message));
131 }
132 }
133}
Create a test class that takes care of setting the server URL and cleaning up after each unit test.
void AddCommonTestInitializeAction(Action action)
Exposes sample resource objects, with built-in methods for injecting dependencies.
Definition Samples.cs:14
static string Valid_NonExistant_UUID
Definition Samples.cs:41
Retrieve settings from environment variables if they exist, or the project settings file otherwise.
static bool RUN_OFFLINE
Controls whether tests that normally require a connection to the server should be allowed to try to r...
static MockResponse Error(Exception requestException, ResponseStatus status=ResponseStatus.Error)
Create a mock response with the specified error.
static MockResponse Completed(HttpStatusCode httpStatus, ResponseStatus status=ResponseStatus.Completed)
Create a mock response with the specified error.
A custom exception class that includes the RestSharp.IRestResponse that generated the exception,...
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 void TryPromptForAuthentication()
Invoke the AuthenticationRequested event, which requests authentication credentials for the server....
static bool TryHandleAuthenticationErrors(IRestResponse response, int sequentialAttempts=0)
Checks an IRestResponse object for authentication errors, then invokes configured authentication dele...
static AuthenticationStatus GetAuthenticationStatus(bool force_request=false)
Determines whether we are currently authenticated against the server with the global default Authenti...
static IRestResponse ExecuteRestRequest(string resource, Method method, IEnumerable< Parameter > requestParameters=null, int? timeout=null, bool returnRawResponse=false, Action< Stream > responseStreamReader=null)
Perform a REST request on the server.
Represents the Analysis of a Layer.
Representation of a single loss set with an associated event loss table.
Definition ELTLossSet.cs:10
LargeDataSubResource data
An endpoint for accessing or modifying the data file attached to this resource.
Optional parameters which can be specified for co-metrics requests.
static new CoMetricsOptions Default
The default co-metrics request options used when none are specified.
Optional parameters which can be specified for exceedance probability requests.
static new ExceedanceProbabilityOptions Default
The default exceedance probability request options used when none are specified.
Optional parameters which can be specified for all metrics requests.
static new MetricsOptions Default
The default metrics request options used when none are specified.
Optional parameters which can be specified for yelt download requests.
Definition YELTOptions.cs:9
static new YELTOptions Default
The default yelt request options used when none are specified.
A probability range used to dictate the set of ordered trial losses in a loss distribution that shoul...
static ProbabilityWindow All
Returns a window representing the full probability range [0, 1], such that all trial losses will be i...
Helper class which makes it easier to build a set of request parameters.
RequestParameters AddParameter(Parameter parameter)
Adds the specified parameter to this list and returns the list.
AccessTokenStatus status
The AccessToken's current AccessTokenStatus (unauthorized / valid).
Represents the Analysis of a Layer.
AccessTokenStatus
An AccessToken's status (unauthorized / valid).
AuthenticationStatus
The status of authentication against the current server.