|
| 1 | +using System; |
| 2 | +using System.Net.Http; |
| 3 | +using System.Net.Sockets; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using NUnit.Framework; |
| 6 | + |
| 7 | +namespace Test |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// Support for tests that exercise a live external web service (UniProt, Koina, PRIDE, ...). |
| 11 | + /// Such tests carry <c>[Category("ExternalService")]</c> so CI can run them in a dedicated, |
| 12 | + /// non-blocking job (see .github/workflows/Test.yml) instead of the required unit-test run. |
| 13 | + /// |
| 14 | + /// The hard part is telling two failures apart: |
| 15 | + /// * the service is unavailable (down, rate-limited, 5xx, timeout) - NOT our bug, so the |
| 16 | + /// test should be <b>skipped</b> ("we tried, the service is down, don't worry"); versus |
| 17 | + /// * the service answered but the contract is broken (our URL is wrong, the response no |
| 18 | + /// longer parses, an expected value is missing) - that is a real regression and must FAIL. |
| 19 | + /// |
| 20 | + /// <see cref="RunAsync"/> wraps a test body and converts availability failures into |
| 21 | + /// <see cref="Assert.Ignore(string)"/> (reported as Skipped) while letting genuine assertion |
| 22 | + /// failures propagate. A test signals "unavailable" from inside the body either by letting a |
| 23 | + /// transport exception bubble up or by calling <see cref="ThrowIfUnavailable"/> on the response. |
| 24 | + /// </summary> |
| 25 | + public static class ExternalServiceTestHelper |
| 26 | + { |
| 27 | + /// <summary> |
| 28 | + /// Runs <paramref name="testBody"/>; if the external service proves unavailable, marks the |
| 29 | + /// test Skipped (via Assert.Ignore) instead of Failed. Real assertion failures propagate. |
| 30 | + /// </summary> |
| 31 | + public static async Task RunAsync(string serviceName, Func<Task> testBody) |
| 32 | + { |
| 33 | + try |
| 34 | + { |
| 35 | + await testBody(); |
| 36 | + } |
| 37 | + catch (ExternalServiceUnavailableException e) |
| 38 | + { |
| 39 | + Skip(serviceName, $"unavailable ({e.Message})"); |
| 40 | + } |
| 41 | + catch (HttpRequestException e) |
| 42 | + { |
| 43 | + Skip(serviceName, $"unavailable ({e.Message})"); |
| 44 | + } |
| 45 | + catch (TaskCanceledException) |
| 46 | + { |
| 47 | + Skip(serviceName, "timed out"); |
| 48 | + } |
| 49 | + catch (SocketException e) |
| 50 | + { |
| 51 | + Skip(serviceName, $"unreachable ({e.Message})"); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + /// <summary> |
| 56 | + /// Records the skip reason on both the console/CI log (via TestContext.Progress, which is |
| 57 | + /// flushed immediately regardless of verbosity) and the NUnit test result, then skips the |
| 58 | + /// test. This is what surfaces the "we tried, the service is down, don't worry" message. |
| 59 | + /// </summary> |
| 60 | + private static void Skip(string serviceName, string reason) |
| 61 | + { |
| 62 | + string message = $"Skipping external-service test: {serviceName} {reason}. " + |
| 63 | + "This is a third-party availability problem, not a code failure."; |
| 64 | + TestContext.Progress.WriteLine(message); |
| 65 | + Assert.Ignore(message); |
| 66 | + } |
| 67 | + |
| 68 | + /// <summary> |
| 69 | + /// Probes an external service's health/readiness URL and skips the calling test (or, from a |
| 70 | + /// [OneTimeSetUp], the whole fixture) if it is unreachable. Use this for tests whose service |
| 71 | + /// call is buried deep in production code and cannot easily route through <see cref="RunAsync"/>. |
| 72 | + /// </summary> |
| 73 | + public static void EnsureReachable(string serviceName, string healthUrl) |
| 74 | + { |
| 75 | + try |
| 76 | + { |
| 77 | + using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(20) }; |
| 78 | + var response = client.GetAsync(healthUrl).GetAwaiter().GetResult(); |
| 79 | + ThrowIfUnavailable(response); |
| 80 | + if (!response.IsSuccessStatusCode) |
| 81 | + { |
| 82 | + throw new ExternalServiceUnavailableException($"health check returned HTTP {(int)response.StatusCode}"); |
| 83 | + } |
| 84 | + } |
| 85 | + catch (ExternalServiceUnavailableException e) |
| 86 | + { |
| 87 | + Skip(serviceName, $"unavailable ({e.Message})"); |
| 88 | + } |
| 89 | + catch (HttpRequestException e) |
| 90 | + { |
| 91 | + Skip(serviceName, $"unavailable ({e.Message})"); |
| 92 | + } |
| 93 | + catch (TaskCanceledException) |
| 94 | + { |
| 95 | + Skip(serviceName, "timed out"); |
| 96 | + } |
| 97 | + catch (SocketException e) |
| 98 | + { |
| 99 | + Skip(serviceName, $"unreachable ({e.Message})"); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + /// <summary> |
| 104 | + /// Classifies an HTTP response as a service-availability problem and, if so, throws |
| 105 | + /// <see cref="ExternalServiceUnavailableException"/> so <see cref="RunAsync"/> skips the test. |
| 106 | + /// Catches transport-level status codes (408/429/5xx) and known error bodies that some |
| 107 | + /// services (e.g. UniProt's streaming endpoint) return with an HTTP 200. |
| 108 | + /// </summary> |
| 109 | + public static void ThrowIfUnavailable(HttpResponseMessage response, string bodyText = null) |
| 110 | + { |
| 111 | + int status = (int)response.StatusCode; |
| 112 | + if (status == 408 || status == 429 || status >= 500) |
| 113 | + { |
| 114 | + throw new ExternalServiceUnavailableException($"HTTP {status} {response.ReasonPhrase}"); |
| 115 | + } |
| 116 | + |
| 117 | + // Some services answer 200 but stream an error message in the body. |
| 118 | + if (!string.IsNullOrWhiteSpace(bodyText) && |
| 119 | + bodyText.Contains("Error encountered when streaming data", StringComparison.OrdinalIgnoreCase)) |
| 120 | + { |
| 121 | + throw new ExternalServiceUnavailableException("service returned an error body instead of data"); |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + /// <summary> |
| 127 | + /// Marker exception meaning "the external service is unavailable" (as opposed to a real bug). |
| 128 | + /// <see cref="ExternalServiceTestHelper.RunAsync"/> turns this into a skipped test. |
| 129 | + /// </summary> |
| 130 | + public class ExternalServiceUnavailableException : Exception |
| 131 | + { |
| 132 | + public ExternalServiceUnavailableException(string message) : base(message) { } |
| 133 | + } |
| 134 | +} |
0 commit comments