diff --git a/CHANGELOG.md b/CHANGELOG.md index dae19c3c20..e63281d561 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Features +- Improved SDK diagnostic logs ([#1161](https://github.com/getsentry/sentry-dotnet/pull/1161)) - Add Scope observer to SentryOptions ([#1153](https://github.com/getsentry/sentry-dotnet/pull/1153)) ### Fixes diff --git a/benchmarks/Sentry.Benchmarks/FakeHttpClientFactory.cs b/benchmarks/Sentry.Benchmarks/FakeHttpClientFactory.cs index a6a38d2103..0d96202066 100644 --- a/benchmarks/Sentry.Benchmarks/FakeHttpClientFactory.cs +++ b/benchmarks/Sentry.Benchmarks/FakeHttpClientFactory.cs @@ -13,7 +13,7 @@ internal class FakeHttpClientFactory : ISentryHttpClientFactory public HttpClient Create(SentryOptions options) => new(new FakeMessageHandler()); } - internal class FakeMessageHandler : HttpMessageHandler + internal class FakeMessageHandler : DelegatingHandler { private readonly Task _result; diff --git a/samples/Sentry.Samples.AspNetCore.Basic/Program.cs b/samples/Sentry.Samples.AspNetCore.Basic/Program.cs index da54bbe242..30ac1b80f9 100644 --- a/samples/Sentry.Samples.AspNetCore.Basic/Program.cs +++ b/samples/Sentry.Samples.AspNetCore.Basic/Program.cs @@ -64,8 +64,7 @@ public static IWebHost BuildWebHost(string[] args) => // will include the Log messages and any custom scope modifications // as exemplified above. throw new Exception( - exceptionMessage ?? "An exception thrown from the ASP.NET Core pipeline" - ); + exceptionMessage ?? "An exception thrown from the ASP.NET Core pipeline"); }); }); }) diff --git a/src/Sentry.AspNet/Internal/SystemWebRequestEventProcessor.cs b/src/Sentry.AspNet/Internal/SystemWebRequestEventProcessor.cs index 1ffa53d3bf..6bcba42170 100644 --- a/src/Sentry.AspNet/Internal/SystemWebRequestEventProcessor.cs +++ b/src/Sentry.AspNet/Internal/SystemWebRequestEventProcessor.cs @@ -123,8 +123,7 @@ public SystemWebRequestEventProcessor(IRequestPayloadExtractor payloadExtractor, { @event.Sdk.AddPackage( $"nuget:{SdkVersion.Name}", - SdkVersion.Version - ); + SdkVersion.Version); } return @event; diff --git a/src/Sentry.AspNet/SentryAspNetOptionsExtensions.cs b/src/Sentry.AspNet/SentryAspNetOptionsExtensions.cs index 14e04ceb5f..eb7726dbb8 100644 --- a/src/Sentry.AspNet/SentryAspNetOptionsExtensions.cs +++ b/src/Sentry.AspNet/SentryAspNetOptionsExtensions.cs @@ -18,8 +18,7 @@ public static void AddAspNet(this SentryOptions options, RequestSize maxRequestB var payloadExtractor = new RequestBodyExtractionDispatcher( new IRequestPayloadExtractor[] {new FormRequestPayloadExtractor(), new DefaultRequestPayloadExtractor()}, options, - () => maxRequestBodySize - ); + () => maxRequestBodySize); var eventProcessor = new SystemWebRequestEventProcessor(payloadExtractor, options); diff --git a/src/Sentry.AspNetCore/SentryTracingMiddleware.cs b/src/Sentry.AspNetCore/SentryTracingMiddleware.cs index a6ac5ee880..4e00e0aa95 100644 --- a/src/Sentry.AspNetCore/SentryTracingMiddleware.cs +++ b/src/Sentry.AspNetCore/SentryTracingMiddleware.cs @@ -88,8 +88,7 @@ public SentryTracingMiddleware( _options.DiagnosticLogger?.LogInfo( "Started transaction with span ID '{0}' and trace ID '{1}'.", transaction.SpanId, - transaction.TraceId - ); + transaction.TraceId); return transaction; } @@ -145,8 +144,7 @@ public async Task InvokeAsync(HttpContext context) _options.DiagnosticLogger?.LogDebug( "Changed transaction name from '{0}' to '{1}' after request pipeline executed.", transaction.Name, - transactionName - ); + transactionName); } transaction.Name = transactionName; diff --git a/src/Sentry/Breadcrumb.cs b/src/Sentry/Breadcrumb.cs index 9c75babe25..d7816988d4 100644 --- a/src/Sentry/Breadcrumb.cs +++ b/src/Sentry/Breadcrumb.cs @@ -120,8 +120,7 @@ public void WriteTo(Utf8JsonWriter writer) writer.WriteString( "timestamp", - Timestamp.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffZ", DateTimeFormatInfo.InvariantInfo) - ); + Timestamp.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffZ", DateTimeFormatInfo.InvariantInfo)); writer.WriteStringIfNotWhiteSpace("message", Message); writer.WriteStringIfNotWhiteSpace("type", Type); diff --git a/src/Sentry/Dsn.cs b/src/Sentry/Dsn.cs index e5e540d01d..0e72a14f04 100644 --- a/src/Sentry/Dsn.cs +++ b/src/Sentry/Dsn.cs @@ -109,8 +109,7 @@ public static Dsn Parse(string dsn) path, secretKey, publicKey, - apiBaseUri - ); + apiBaseUri); } public static Dsn? TryParse(string? dsn) diff --git a/src/Sentry/GlobalSessionManager.cs b/src/Sentry/GlobalSessionManager.cs index ff46b9e78e..e0993eadc7 100644 --- a/src/Sentry/GlobalSessionManager.cs +++ b/src/Sentry/GlobalSessionManager.cs @@ -57,15 +57,13 @@ public GlobalSessionManager( ?? Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Sentry", - _options.Dsn!.GetHashString() - ); + _options.Dsn!.GetHashString()); Directory.CreateDirectory(directoryPath); _options.DiagnosticLogger?.LogDebug( "Created directory for installation ID file ({0}).", - directoryPath - ); + directoryPath); var filePath = Path.Combine(directoryPath, ".installation"); @@ -78,16 +76,14 @@ public GlobalSessionManager( { _options.DiagnosticLogger?.LogDebug( "File containing installation ID does not exist ({0}).", - filePath - ); + filePath); } catch (DirectoryNotFoundException) { // on PS4 we're seeing CreateDirectory work but ReadAllText throw DirectoryNotFoundException _options.DiagnosticLogger?.LogDebug( "Directory containing installation ID does not exist ({0}).", - filePath - ); + filePath); } // Generate new installation ID and store it in a file @@ -96,8 +92,7 @@ public GlobalSessionManager( _options.DiagnosticLogger?.LogDebug( "Saved installation ID '{0}' to file '{1}'.", - id, filePath - ); + id, filePath); return id; } @@ -107,8 +102,7 @@ public GlobalSessionManager( { _options.DiagnosticLogger?.LogError( "Failed to resolve persistent installation ID.", - ex - ); + ex); return null; } @@ -130,8 +124,7 @@ public GlobalSessionManager( if (string.IsNullOrWhiteSpace(installationId)) { _options.DiagnosticLogger?.LogError( - "Failed to find an appropriate network interface for installation ID." - ); + "Failed to find an appropriate network interface for installation ID."); return null; } @@ -142,8 +135,7 @@ public GlobalSessionManager( { _options.DiagnosticLogger?.LogError( "Failed to resolve hardware installation ID.", - ex - ); + ex); return null; } @@ -182,14 +174,12 @@ internal string GetMachineNameInstallationId() => { _options.DiagnosticLogger?.LogDebug( "Resolved installation ID '{0}'.", - id - ); + id); } else { _options.DiagnosticLogger?.LogDebug( - "Failed to resolve installation ID." - ); + "Failed to resolve installation ID."); } return _resolvedInstallationId = id; @@ -214,25 +204,18 @@ private void PersistSession(SessionUpdate update, DateTimeOffset? pauseTimestamp _options.DiagnosticLogger?.LogDebug( "Created persistence directory for session file '{0}'.", - _persistenceDirectoryPath - ); + _persistenceDirectoryPath); var filePath = Path.Combine(_persistenceDirectoryPath, PersistedSessionFileName); var persistedSessionUpdate = new PersistedSessionUpdate(update, pauseTimestamp); persistedSessionUpdate.WriteToFile(filePath); - _options.DiagnosticLogger?.LogInfo( - "Persisted session to a file '{0}'.", - filePath - ); + _options.DiagnosticLogger?.LogDebug("Persisted session to a file '{0}'.", filePath); } catch (Exception ex) { - _options.DiagnosticLogger?.LogError( - "Failed to persist session on the file system.", - ex - ); + _options.DiagnosticLogger?.LogError("Failed to persist session on the file system.", ex); } } @@ -256,16 +239,14 @@ private void DeletePersistedSession() { _options.DiagnosticLogger?.LogDebug( "Deleting persisted session file with contents: {0}", - File.ReadAllText(filePath) - ); + File.ReadAllText(filePath)); } catch (Exception ex) { _options.DiagnosticLogger?.LogError( "Failed to read the contents of persisted session file '{0}'.", ex, - filePath - ); + filePath); } } @@ -273,16 +254,14 @@ private void DeletePersistedSession() _options.DiagnosticLogger?.LogInfo( "Deleted persisted session file '{0}'.", - filePath - ); + filePath); } catch (Exception ex) { _options.DiagnosticLogger?.LogError( "Failed to delete persisted session from the file system: '{0}'", ex, - filePath - ); + filePath); } } @@ -316,16 +295,14 @@ private void DeletePersistedSession() _ when recoveredUpdate.PauseTimestamp is not null => SessionEndStatus.Exited, { } crashedLastRun => crashedLastRun() ? SessionEndStatus.Crashed : SessionEndStatus.Abnormal, _ => SessionEndStatus.Abnormal - } - ); + }); } catch (IOException ioEx) when (ioEx is FileNotFoundException or DirectoryNotFoundException) { // Not a notable error _options.DiagnosticLogger?.LogDebug( "A persisted session does not exist at {0}.", - filePath - ); + filePath); return null; } @@ -334,8 +311,7 @@ private void DeletePersistedSession() _options.DiagnosticLogger?.LogError( "Failed to recover persisted session from the file system '{0}'.", ex, - filePath - ); + filePath); return null; } @@ -349,8 +325,7 @@ private void DeletePersistedSession() { // Release health without release is just health (useless) _options.DiagnosticLogger?.LogError( - "Failed to start a session because there is no release information." - ); + "Failed to start a session because there is no release information."); return null; } @@ -367,8 +342,7 @@ private void DeletePersistedSession() if (previousSession is not null) { _options.DiagnosticLogger?.LogWarning( - "Starting a new session while an existing one is still active." - ); + "Starting a new session while an existing one is still active."); // End previous session EndSession(previousSession, _clock.GetUtcNow(), SessionEndStatus.Exited); @@ -376,8 +350,7 @@ private void DeletePersistedSession() _options.DiagnosticLogger?.LogInfo( "Started new session (SID: {0}; DID: {1}).", - session.Id, session.DistinctId - ); + session.Id, session.DistinctId); var update = session.CreateUpdate(true, _clock.GetUtcNow()); @@ -390,8 +363,7 @@ private SessionUpdate EndSession(Session session, DateTimeOffset timestamp, Sess { _options.DiagnosticLogger?.LogInfo( "Ended session (SID: {0}; DID: {1}) with status '{2}'.", - session.Id, session.DistinctId, status - ); + session.Id, session.DistinctId, status); var update = session.CreateUpdate(false, timestamp, status); @@ -406,8 +378,7 @@ private SessionUpdate EndSession(Session session, DateTimeOffset timestamp, Sess if (session is null) { _options.DiagnosticLogger?.LogDebug( - "Failed to end session because there is none active." - ); + "Failed to end session because there is none active."); return null; } @@ -433,8 +404,7 @@ public IReadOnlyList ResumeSession() if (_lastPauseTimestamp is not { } sessionPauseTimestamp) { _options.DiagnosticLogger?.LogDebug( - "Attempted to resume a session, but the current session hasn't been paused." - ); + "Attempted to resume a session, but the current session hasn't been paused."); return Array.Empty(); } @@ -450,8 +420,7 @@ public IReadOnlyList ResumeSession() _options.DiagnosticLogger?.LogDebug( "Paused session has been paused for {0}, which is longer than the configured timeout. " + "Starting a new session instead of resuming this one.", - pauseDuration - ); + pauseDuration); var updates = new List(2); @@ -472,8 +441,7 @@ public IReadOnlyList ResumeSession() _options.DiagnosticLogger?.LogDebug( "Paused session has been paused for {0}, which is shorter than the configured timeout.", - pauseDuration - ); + pauseDuration); return Array.Empty(); } @@ -489,8 +457,7 @@ public IReadOnlyList ResumeSession() if (session.ErrorCount > 1) { _options.DiagnosticLogger?.LogDebug( - "Reported an error on a session that already contains errors. Not creating an update." - ); + "Reported an error on a session that already contains errors. Not creating an update."); return null; } @@ -499,8 +466,7 @@ public IReadOnlyList ResumeSession() } _options.DiagnosticLogger?.LogDebug( - "Failed to report an error on a session because there is none active." - ); + "Failed to report an error on a session because there is none active."); return null; } diff --git a/src/Sentry/IHub.cs b/src/Sentry/IHub.cs index fa0cc302f0..13e5493be7 100644 --- a/src/Sentry/IHub.cs +++ b/src/Sentry/IHub.cs @@ -27,8 +27,7 @@ public interface IHub : /// ITransaction StartTransaction( ITransactionContext context, - IReadOnlyDictionary customSamplingContext - ); + IReadOnlyDictionary customSamplingContext); /// /// Binds specified exception the specified span. diff --git a/src/Sentry/Internal/BackgroundWorker.cs b/src/Sentry/Internal/BackgroundWorker.cs index 874b1cba81..1c07a736e2 100644 --- a/src/Sentry/Internal/BackgroundWorker.cs +++ b/src/Sentry/Internal/BackgroundWorker.cs @@ -96,8 +96,7 @@ private async Task WorkerAsync() { _options.DiagnosticLogger?.LogDebug( "Exiting immediately due to 0 shutdown timeout. #{0} in queue.", - _queue.Count - ); + _queue.Count); return; } @@ -106,8 +105,7 @@ private async Task WorkerAsync() _options.DiagnosticLogger?.LogDebug( "Shutdown scheduled. Stopping by: {0}. #{1} in queue.", _options.ShutdownTimeout, - _queue.Count - ); + _queue.Count); shutdownTimeout.CancelAfter(_options.ShutdownTimeout); } @@ -128,8 +126,7 @@ private async Task WorkerAsync() _options.DiagnosticLogger?.LogDebug( "Envelope {0} handed off to transport. #{1} in queue.", envelope.TryGetEventId(), - _queue.Count - ); + _queue.Count); await task.ConfigureAwait(false); } @@ -137,8 +134,7 @@ private async Task WorkerAsync() { _options.DiagnosticLogger?.LogInfo( "Shutdown token triggered. Time to exit. #{0} in queue.", - _queue.Count - ); + _queue.Count); return; } @@ -148,8 +144,7 @@ private async Task WorkerAsync() "Error while processing envelope (event ID: '{0}'). #{1} in queue.", exception, envelope.TryGetEventId(), - _queue.Count - ); + _queue.Count); } finally { @@ -201,8 +196,7 @@ public async Task FlushAsync(TimeSpan timeout) var timeoutWithShutdown = CancellationTokenSource.CreateLinkedTokenSource( timeoutSource.Token, _shutdownSource.Token, - flushSuccessSource.Token - ); + flushSuccessSource.Token); var counter = 0; var depth = int.MaxValue; @@ -250,8 +244,7 @@ void EventFlushedCallback(object? _, EventArgs __) { _options.DiagnosticLogger?.LogDebug(flushSuccessSource.IsCancellationRequested ? "Successfully flushed all events up to call to FlushAsync." - : "Timeout when trying to flush queue." - ); + : "Timeout when trying to flush queue."); } finally { @@ -300,8 +293,7 @@ public void Dispose() { _options.DiagnosticLogger?.LogWarning( "Worker stopped while {0} were still in the queue.", - _queue.Count - ); + _queue.Count); } } } diff --git a/src/Sentry/Internal/DuplicateEventDetectionEventProcessor.cs b/src/Sentry/Internal/DuplicateEventDetectionEventProcessor.cs index e3292796e0..968df9053a 100644 --- a/src/Sentry/Internal/DuplicateEventDetectionEventProcessor.cs +++ b/src/Sentry/Internal/DuplicateEventDetectionEventProcessor.cs @@ -25,21 +25,24 @@ internal class DuplicateEventDetectionEventProcessor : ISentryEventProcessor } if (@event.Exception == null - || !IsDuplicate(@event.Exception)) + || !IsDuplicate(@event.Exception, @event.EventId, true)) { return @event; } - _options.DiagnosticLogger?.LogDebug("Duplicate Exception detected. Event {0} will be discarded.", @event.EventId); return null; } - private bool IsDuplicate(Exception ex) + private bool IsDuplicate(Exception ex, SentryId eventId, bool debugLog) { if (_options.DeduplicateMode.HasFlag(DeduplicateMode.SameExceptionInstance)) { if (_capturedObjects.TryGetValue(ex, out _)) { + if (debugLog) + { + _options.DiagnosticLogger?.LogDebug("Duplicate Exception: 'SameExceptionInstance'. Event {0} will be discarded.", eventId); + } return true; } @@ -49,14 +52,21 @@ private bool IsDuplicate(Exception ex) if (_options.DeduplicateMode.HasFlag(DeduplicateMode.AggregateException) && ex is AggregateException aex) { - return aex.InnerExceptions.Any(IsDuplicate); + var result = aex.InnerExceptions.Any(e => IsDuplicate(e, eventId, false)); + if (result) + { + _options.DiagnosticLogger?.LogDebug("Duplicate Exception: 'AggregateException'. Event {0} will be discarded.", eventId); + } + + return result; } if (_options.DeduplicateMode.HasFlag(DeduplicateMode.InnerException) && ex.InnerException != null) { - if (IsDuplicate(ex.InnerException)) + if (IsDuplicate(ex.InnerException, eventId, false)) { + _options.DiagnosticLogger?.LogDebug("Duplicate Exception: 'SameExceptionInstance'. Event {0} will be discarded.", eventId); return true; } } diff --git a/src/Sentry/Internal/Http/CachingTransport.cs b/src/Sentry/Internal/Http/CachingTransport.cs index 0dd91732d4..a2d52624a8 100644 --- a/src/Sentry/Internal/Http/CachingTransport.cs +++ b/src/Sentry/Internal/Http/CachingTransport.cs @@ -67,10 +67,11 @@ private async Task CachedTransportBackgroundTask() { foreach (var filePath in Directory.EnumerateFiles(_processingDirectoryPath)) { - File.Move( - filePath, - Path.Combine(_isolatedCacheDirectoryPath, Path.GetFileName(filePath)) - ); + var destinationPath = Path.Combine(_isolatedCacheDirectoryPath, Path.GetFileName(filePath)); + _options.DiagnosticLogger?.LogDebug("Moving unprocessed file back to cache: {0} to {1}.", + filePath, destinationPath); + + File.Move(filePath, destinationPath); } } @@ -79,6 +80,7 @@ private async Task CachedTransportBackgroundTask() try { await _workerSignal.WaitAsync(_workerCts.Token).ConfigureAwait(false); + _options.DiagnosticLogger?.LogDebug("Worker signal triggered: flushing cached envelopes."); await ProcessCacheAsync(_workerCts.Token).ConfigureAwait(false); } catch (OperationCanceledException) @@ -87,10 +89,7 @@ private async Task CachedTransportBackgroundTask() } catch (Exception ex) { - _options.DiagnosticLogger?.LogError( - "Exception in background worker of CachingTransport.", - ex - ); + _options.DiagnosticLogger?.LogError("Exception in background worker of CachingTransport.", ex); // Wait a bit before retrying await Task.Delay(500, _workerCts.Token).ConfigureAwait(false); @@ -127,8 +126,7 @@ private void EnsureFreeSpaceInCache() // File has already been deleted (unexpected but not critical) _options.DiagnosticLogger?.LogWarning( "Cached envelope '{0}' has already been deleted.", - filePath - ); + filePath); } } } @@ -143,24 +141,18 @@ private IEnumerable GetCacheFilePaths() } catch (DirectoryNotFoundException) { - _options.DiagnosticLogger?.LogWarning( - "Cache directory is empty." - ); - + _options.DiagnosticLogger?.LogWarning("Cache directory is empty."); return Array.Empty(); } } private async Task ProcessCacheAsync(CancellationToken cancellationToken = default) { - _options.DiagnosticLogger?.LogDebug("Flushing cached envelopes."); - while (await TryPrepareNextCacheFileAsync(cancellationToken).ConfigureAwait(false) is { } envelopeFilePath) { _options.DiagnosticLogger?.LogDebug( "Reading cached envelope: {0}", - envelopeFilePath - ); + envelopeFilePath); try { @@ -173,23 +165,20 @@ private async Task ProcessCacheAsync(CancellationToken cancellationToken = defau _options.DiagnosticLogger?.LogDebug( "Sending cached envelope: {0}", - envelope.TryGetEventId() - ); + envelope.TryGetEventId()); await _innerTransport.SendEnvelopeAsync(envelope, cancellationToken).ConfigureAwait(false); _options.DiagnosticLogger?.LogDebug( "Successfully sent cached envelope: {0}", - envelope.TryGetEventId() - ); + envelope.TryGetEventId()); } catch (Exception ex) when (IsRetryable(ex)) { _options.DiagnosticLogger?.LogError( "Failed to send cached envelope: {0}, retrying after a delay.", ex, - envelopeFilePath - ); + envelopeFilePath); // Let the worker catch, log, wait a bit and retry. throw; @@ -199,8 +188,7 @@ private async Task ProcessCacheAsync(CancellationToken cancellationToken = defau _options.DiagnosticLogger?.LogError( "Failed to send cached envelope: {0}, discarding cached envelope.", ex, - envelopeFilePath - ); + envelopeFilePath); } // Envelope & file stream must be disposed prior to reaching this point @@ -216,8 +204,8 @@ private async Task ProcessCacheAsync(CancellationToken cancellationToken = defau // For that reason, we're not retrying IOException, to avoid any disk related exception from retrying. private static bool IsRetryable(Exception exception) => exception is OperationCanceledException // Timed-out or Shutdown triggered - || exception is HttpRequestException // Myriad of HTTP related errors - || exception is SocketException; // Network related + or HttpRequestException + or SocketException; // Network related // Gets the next cache file and moves it to "processing" private async Task TryPrepareNextCacheFileAsync( @@ -242,7 +230,7 @@ exception is OperationCanceledException // Timed-out or Shutdown triggered // already exists in the output directory. // That should never happen under normal workflows because the filenames // have high variance. -#if NETCOREAPP3_0 || NET5_0 +#if NETCOREAPP3_0_OR_GREATER File.Move(filePath, targetFilePath, true); #else File.Copy(filePath, targetFilePath, true); @@ -266,8 +254,7 @@ private async Task StoreToCacheAsync( $"{Guid.NewGuid().GetHashCode() % 1_0000}_" + // random 1-4 digits for extra variance $"{envelope.TryGetEventId()}_" + // event ID (may be empty) $"{envelope.GetHashCode()}" + // envelope hash code - $".{EnvelopeFileExt}" - ); + $".{EnvelopeFileExt}"); _options.DiagnosticLogger?.LogDebug("Storing file {0}.", envelopeFilePath); @@ -310,8 +297,11 @@ public async Task StopWorkerAsync() await _worker.ConfigureAwait(false); } - public async Task FlushAsync(CancellationToken cancellationToken = default) => + public async Task FlushAsync(CancellationToken cancellationToken = default) + { + _options.DiagnosticLogger?.LogDebug("External FlushAsync invocation: flushing cached envelopes."); await ProcessCacheAsync(cancellationToken).ConfigureAwait(false); + } public async ValueTask DisposeAsync() { @@ -324,8 +314,7 @@ public async ValueTask DisposeAsync() // Don't throw inside dispose _options.DiagnosticLogger?.LogError( "Error stopping worker during dispose.", - ex - ); + ex); } _workerSignal.Dispose(); diff --git a/src/Sentry/Internal/Http/HttpTransport.cs b/src/Sentry/Internal/Http/HttpTransport.cs index c64197d35c..d27b5f07c3 100644 --- a/src/Sentry/Internal/Http/HttpTransport.cs +++ b/src/Sentry/Internal/Http/HttpTransport.cs @@ -60,8 +60,7 @@ private Envelope ProcessEnvelope(Envelope envelope, DateTimeOffset instant) { _options.DiagnosticLogger?.LogDebug( "Envelope item of type {0} was discarded because it's rate-limited.", - envelopeItem.TryGetType() - ); + envelopeItem.TryGetType()); // Check if session update with init=true if (envelopeItem.Payload is JsonSerializable {Source: SessionUpdate {IsInitial: true} discardedSessionUpdate}) @@ -70,8 +69,7 @@ private Envelope ProcessEnvelope(Envelope envelope, DateTimeOffset instant) _options.DiagnosticLogger?.LogDebug( "Discarded envelope item containing initial session update (SID: {0}).", - discardedSessionUpdate.Id - ); + discardedSessionUpdate.Id); } continue; @@ -84,8 +82,7 @@ private Envelope ProcessEnvelope(Envelope envelope, DateTimeOffset instant) _options.DiagnosticLogger?.LogWarning( "Attachment '{0}' dropped because it's too large ({1} bytes).", envelopeItem.TryGetFileName(), - envelopeItem.TryGetLength() - ); + envelopeItem.TryGetLength()); continue; } @@ -98,15 +95,13 @@ private Envelope ProcessEnvelope(Envelope envelope, DateTimeOffset instant) { var modifiedEnvelopeItem = new EnvelopeItem( envelopeItem.Header, - new JsonSerializable(new SessionUpdate(sessionUpdate, true)) - ); + new JsonSerializable(new SessionUpdate(sessionUpdate, true))); envelopeItems.Add(modifiedEnvelopeItem); _options.DiagnosticLogger?.LogDebug( "Promoted envelope item with session update to initial following a discarded update (SID: {0}).", - sessionUpdate.Id - ); + sessionUpdate.Id); } else { @@ -150,8 +145,7 @@ public async Task SendEnvelopeAsync(Envelope envelope, CancellationToken cancell { _options.DiagnosticLogger?.LogInfo( "Envelope {0} was discarded because all contained items are rate-limited.", - envelope.TryGetEventId() - ); + envelope.TryGetEventId()); return; } @@ -169,11 +163,17 @@ public async Task SendEnvelopeAsync(Envelope envelope, CancellationToken cancell return; } - _options.DiagnosticLogger?.LogDebug( - "Envelope {0} successfully received by Sentry.", - processedEnvelope.TryGetEventId() - ); - + if (_options.DiagnosticLogger?.IsEnabled(SentryLevel.Debug) is true) + { + _options.DiagnosticLogger?.LogDebug("Envelope '{0}' sent successfully. Payload:\n{1}", + envelope.TryGetEventId(), + await envelope.SerializeToStringAsync(cancellationToken).ConfigureAwait(false)); + } + else + { + _options.DiagnosticLogger?.LogInfo("Envelope '{0}' successfully received by Sentry.", + processedEnvelope.TryGetEventId()); + } } private async Task HandleFailureAsync( @@ -182,7 +182,7 @@ private async Task HandleFailureAsync( CancellationToken cancellationToken) { // Spare the overhead if level is not enabled - if (_options.DiagnosticLogger?.IsEnabled(SentryLevel.Error) == true) + if (_options.DiagnosticLogger?.IsEnabled(SentryLevel.Error) is true) { if (string.Equals(response.Content.Headers.ContentType?.MediaType, "application/json", StringComparison.OrdinalIgnoreCase)) @@ -204,8 +204,7 @@ private async Task HandleFailureAsync( processedEnvelope.TryGetEventId(), response.StatusCode, errorMessage, - string.Join(", ", errorCauses) - ); + string.Join(", ", errorCauses)); } else { @@ -217,14 +216,21 @@ private async Task HandleFailureAsync( null, processedEnvelope.TryGetEventId(), response.StatusCode, - responseString - ); + responseString); + } + + // If debug level, dump the whole envelope to the logger + if (_options.DiagnosticLogger?.IsEnabled(SentryLevel.Debug) is true) + { + _options.DiagnosticLogger?.LogDebug("Failed envelope '{0}' has payload:\n{1}\n", + processedEnvelope.TryGetEventId(), + await processedEnvelope.SerializeToStringAsync(cancellationToken).ConfigureAwait(false)); } } // SDK is in debug mode, and envelope was too large. To help troubleshoot: const string persistLargeEnvelopePathEnvVar = "SENTRY_KEEP_LARGE_ENVELOPE_PATH"; - if (_options.DiagnosticLogger?.IsEnabled(SentryLevel.Debug) == true + if (_options.DiagnosticLogger?.IsEnabled(SentryLevel.Debug) is true && response.StatusCode == HttpStatusCode.RequestEntityTooLarge && _getEnvironmentVariable(persistLargeEnvelopePathEnvVar) is { } destinationDirectory) { diff --git a/src/Sentry/Internal/Http/RateLimit.cs b/src/Sentry/Internal/Http/RateLimit.cs index a1a0645bcf..51c1bbe454 100644 --- a/src/Sentry/Internal/Http/RateLimit.cs +++ b/src/Sentry/Internal/Http/RateLimit.cs @@ -29,8 +29,7 @@ public static RateLimit Parse(string rateLimitEncoded) return new RateLimit( categories, - retryAfter - ); + retryAfter); } public static IEnumerable ParseMany(string rateLimitsEncoded) => diff --git a/src/Sentry/Internal/Hub.cs b/src/Sentry/Internal/Hub.cs index 3423a5eac4..79238bad76 100644 --- a/src/Sentry/Internal/Hub.cs +++ b/src/Sentry/Internal/Hub.cs @@ -56,8 +56,7 @@ internal Hub( ScopeManager = scopeManager ?? new SentryScopeManager( options.ScopeStackContainer ?? new AsyncLocalScopeStackContainer(), options, - _ownedClient - ); + _ownedClient); _rootScope = options.IsGlobalModeEnabled ? DisabledHub.Instance @@ -131,8 +130,7 @@ public ITransaction StartTransaction( { var samplingContext = new TransactionSamplingContext( context, - customSamplingContext - ); + customSamplingContext); if (tracesSampler(samplingContext) is { } sampleRate) { @@ -187,8 +185,7 @@ public void StartSession() { _options.DiagnosticLogger?.LogError( "Failed to recover persisted session.", - ex - ); + ex); } } @@ -205,8 +202,7 @@ public void StartSession() { _options.DiagnosticLogger?.LogError( "Failed to start a session.", - ex - ); + ex); } } @@ -222,8 +218,7 @@ public void PauseSession() { _options.DiagnosticLogger?.LogError( "Failed to pause a session.", - ex - ); + ex); } } } @@ -243,8 +238,7 @@ public void ResumeSession() { _options.DiagnosticLogger?.LogError( "Failed to resume a session.", - ex - ); + ex); } } } @@ -263,8 +257,7 @@ private void EndSession(DateTimeOffset timestamp, SessionEndStatus status) { _options.DiagnosticLogger?.LogError( "Failed to end a session.", - ex - ); + ex); } } diff --git a/src/Sentry/Internal/SdkComposer.cs b/src/Sentry/Internal/SdkComposer.cs index 4fe087b4cc..e573b9002a 100644 --- a/src/Sentry/Internal/SdkComposer.cs +++ b/src/Sentry/Internal/SdkComposer.cs @@ -27,8 +27,7 @@ private ITransport CreateTransport() { _options.DiagnosticLogger?.LogDebug( "Using ISentryHttpClientFactory set through options: {0}.", - _options.SentryHttpClientFactory.GetType().Name - ); + _options.SentryHttpClientFactory.GetType().Name); } var httpClientFactory = _options.SentryHttpClientFactory ?? new DefaultSentryHttpClientFactory(); @@ -50,8 +49,7 @@ private ITransport CreateTransport() { _options.DiagnosticLogger?.LogDebug( "Flushing existing cache during transport activation up to {0}.", - _options.InitCacheFlushTimeout - ); + _options.InitCacheFlushTimeout); try { @@ -73,16 +71,14 @@ private ITransport CreateTransport() _options.DiagnosticLogger?.LogInfo( "Cache flushing is taking longer than the configured timeout of {0}. " + "Continuing without waiting for the task to finish.", - _options.InitCacheFlushTimeout - ); + _options.InitCacheFlushTimeout); } } catch (Exception ex) { _options.DiagnosticLogger?.LogError( "Cache flushing failed.", - ex - ); + ex); } } diff --git a/test/Sentry.Tests/Helpers/SerializableExtensions.cs b/src/Sentry/Internal/SerializableExtensions.cs similarity index 83% rename from test/Sentry.Tests/Helpers/SerializableExtensions.cs rename to src/Sentry/Internal/SerializableExtensions.cs index 9b2228ba91..25a206cc77 100644 --- a/test/Sentry.Tests/Helpers/SerializableExtensions.cs +++ b/src/Sentry/Internal/SerializableExtensions.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using Sentry.Protocol.Envelopes; -namespace Sentry.Tests.Helpers +namespace Sentry.Internal { internal static class SerializableExtensions { @@ -12,10 +12,10 @@ public static async Task SerializeToStringAsync( this ISerializable serializable, CancellationToken cancellationToken = default) { -#if !NET461 && !NETCOREAPP2_1 +#if !NET461 && !NETSTANDARD2_0 await #endif - using var stream = new MemoryStream(); + using var stream = new MemoryStream(); await serializable.SerializeAsync(stream, cancellationToken).ConfigureAwait(false); return Encoding.UTF8.GetString(stream.ToArray()); } diff --git a/src/Sentry/PlatformAbstractions/RuntimeInfo.cs b/src/Sentry/PlatformAbstractions/RuntimeInfo.cs index 286a5ac154..a3b2d60995 100644 --- a/src/Sentry/PlatformAbstractions/RuntimeInfo.cs +++ b/src/Sentry/PlatformAbstractions/RuntimeInfo.cs @@ -48,8 +48,7 @@ internal static void SetAdditionalParameters(Runtime runtime) return new Runtime( name ?? (match.Groups["name"].Value == string.Empty ? null : match.Groups["name"].Value.Trim()), match.Groups["version"].Value == string.Empty ? null : match.Groups["version"].Value.Trim(), - raw: rawRuntimeDescription - ); + raw: rawRuntimeDescription); } return new Runtime(name, raw: rawRuntimeDescription); diff --git a/src/Sentry/Scope.cs b/src/Sentry/Scope.cs index bc31b8db66..cdeb01fa37 100644 --- a/src/Sentry/Scope.cs +++ b/src/Sentry/Scope.cs @@ -206,7 +206,7 @@ public ITransaction? Transaction private ConcurrentBag _attachments = new(); #else private readonly ConcurrentBag _attachments = new(); - + #endif /// @@ -451,8 +451,7 @@ internal void Evaluate() { Options.DiagnosticLogger?.LogError( "Failed invoking event handler.", - ex - ); + ex); } finally { diff --git a/src/Sentry/ScopeExtensions.cs b/src/Sentry/ScopeExtensions.cs index d2feeb18cd..d21ef31918 100644 --- a/src/Sentry/ScopeExtensions.cs +++ b/src/Sentry/ScopeExtensions.cs @@ -117,8 +117,7 @@ public static void AddAttachment( { scope.Options.DiagnosticLogger?.LogWarning( "Cannot evaluate the size of attachment '{0}' because the stream is not seekable.", - fileName - ); + fileName); return; } @@ -130,8 +129,7 @@ public static void AddAttachment( type, new StreamAttachmentContent(stream), fileName, - contentType) - ); + contentType)); } /// @@ -158,8 +156,7 @@ public static void AddAttachment( type, new FileAttachmentContent(filePath), Path.GetFileName(filePath), - contentType) - ); + contentType)); /// /// Gets the last opened span. diff --git a/src/Sentry/SdkVersion.cs b/src/Sentry/SdkVersion.cs index 563bf569bd..9dd6daf6c2 100644 --- a/src/Sentry/SdkVersion.cs +++ b/src/Sentry/SdkVersion.cs @@ -16,8 +16,7 @@ namespace Sentry public sealed class SdkVersion : IJsonSerializable { private static readonly Lazy InstanceLazy = new( - () => typeof(ISentryClient).Assembly.GetNameAndVersion() - ); + () => typeof(ISentryClient).Assembly.GetNameAndVersion()); internal static SdkVersion Instance => InstanceLazy.Value; diff --git a/src/Sentry/SentryClient.cs b/src/Sentry/SentryClient.cs index 99dab11173..f0a3b75785 100644 --- a/src/Sentry/SentryClient.cs +++ b/src/Sentry/SentryClient.cs @@ -112,8 +112,7 @@ public void CaptureTransaction(Transaction transaction) if (transaction.SpanId.Equals(SpanId.Empty)) { _options.DiagnosticLogger?.LogWarning( - "Transaction dropped due to empty id." - ); + "Transaction dropped due to empty id."); return; } @@ -122,8 +121,7 @@ public void CaptureTransaction(Transaction transaction) string.IsNullOrWhiteSpace(transaction.Operation)) { _options.DiagnosticLogger?.LogWarning( - "Transaction discarded due to one or more required fields missing." - ); + "Transaction discarded due to one or more required fields missing."); return; } @@ -136,21 +134,18 @@ public void CaptureTransaction(Transaction transaction) _options.DiagnosticLogger?.LogWarning( "Capturing a transaction which has not been finished. " + "Please call transaction.Finish() instead of hub.CaptureTransaction(transaction) " + - "to properly finalize the transaction and send it to Sentry." - ); + "to properly finalize the transaction and send it to Sentry."); } // Sampling decision MUST have been made at this point Debug.Assert( transaction.IsSampled != null, - "Attempt to capture transaction without sampling decision." - ); + "Attempt to capture transaction without sampling decision."); if (transaction.IsSampled != true) { _options.DiagnosticLogger?.LogDebug( - "Transaction dropped by sampling." - ); + "Transaction dropped by sampling."); return; } @@ -256,14 +251,13 @@ private bool CaptureEnvelope(Envelope envelope) { if (Worker.EnqueueEnvelope(envelope)) { - _options.DiagnosticLogger?.LogDebug("Envelope queued up."); + _options.DiagnosticLogger?.LogInfo("Envelope queued up: '{0}'", envelope.TryGetEventId()); return true; } _options.DiagnosticLogger?.LogWarning( "The attempt to queue the event failed. Items in queue: {0}", - Worker.QueuedItems - ); + Worker.QueuedItems); return false; } @@ -287,7 +281,7 @@ private bool CaptureEnvelope(Envelope envelope) { {"message", e.Message} }; - if(e.StackTrace is not null) + if (e.StackTrace is not null) { data.Add("stackTrace", e.StackTrace); } diff --git a/src/Sentry/SentryClientExtensions.cs b/src/Sentry/SentryClientExtensions.cs index 44994ae29d..5af7b57807 100644 --- a/src/Sentry/SentryClientExtensions.cs +++ b/src/Sentry/SentryClientExtensions.cs @@ -41,8 +41,7 @@ public static SentryId CaptureMessage( { Message = message, Level = level - } - ); + }); } /// diff --git a/src/Sentry/SentryHttpMessageHandler.cs b/src/Sentry/SentryHttpMessageHandler.cs index b9f1813433..b1d1bd3ddc 100644 --- a/src/Sentry/SentryHttpMessageHandler.cs +++ b/src/Sentry/SentryHttpMessageHandler.cs @@ -54,8 +54,7 @@ protected override async Task SendAsync( { request.Headers.Add( SentryTraceHeader.HttpHeaderName, - traceHeader.ToString() - ); + traceHeader.ToString()); } // Prevent null reference exception in the following call @@ -70,8 +69,7 @@ protected override async Task SendAsync( var span = _hub.GetSpan()?.StartChild( "http.client", // e.g. "GET https://example.com" - $"{requestMethod} {url}" - ); + $"{requestMethod} {url}"); try { @@ -87,8 +85,7 @@ protected override async Task SendAsync( // This will handle unsuccessful status codes as well span?.Finish( - SpanStatusConverter.FromHttpStatusCode(response.StatusCode) - ); + SpanStatusConverter.FromHttpStatusCode(response.StatusCode)); return response; } diff --git a/src/Sentry/SentryOptions.cs b/src/Sentry/SentryOptions.cs index 563a5775de..91f39272c9 100644 --- a/src/Sentry/SentryOptions.cs +++ b/src/Sentry/SentryOptions.cs @@ -464,8 +464,7 @@ public double TracesSampleRate if (value < 0 || value > 1) { throw new InvalidOperationException( - $"The value {value} is not a valid tracing sample rate. Use values between 0 and 1." - ); + $"The value {value} is not a valid tracing sample rate. Use values between 0 and 1."); } _tracesSampleRate = value; diff --git a/src/Sentry/SentrySdk.cs b/src/Sentry/SentrySdk.cs index 4f94f69b8d..5cf78f0ca4 100644 --- a/src/Sentry/SentrySdk.cs +++ b/src/Sentry/SentrySdk.cs @@ -42,8 +42,7 @@ internal static IHub InitHub(SentryOptions options) if (Dsn.IsDisabled(dsn)) { options.DiagnosticLogger?.LogWarning( - "Init was called but no DSN was provided nor located. Sentry SDK will be disabled." - ); + "Init was called but no DSN was provided nor located. Sentry SDK will be disabled."); return DisabledHub.Instance; } diff --git a/src/Sentry/SessionUpdate.cs b/src/Sentry/SessionUpdate.cs index 02ca973a82..d17ad8589e 100644 --- a/src/Sentry/SessionUpdate.cs +++ b/src/Sentry/SessionUpdate.cs @@ -192,8 +192,7 @@ public static SessionUpdate FromJson(JsonElement json) isInitial, timestamp, sequenceNumber, - endStatus - ); + endStatus); } } } diff --git a/src/Sentry/Span.cs b/src/Sentry/Span.cs index 8f5f96ae04..f836d5e795 100644 --- a/src/Sentry/Span.cs +++ b/src/Sentry/Span.cs @@ -97,8 +97,7 @@ public Span(ISpan tracer) public SentryTraceHeader GetTraceHeader() => new( TraceId, SpanId, - IsSampled - ); + IsSampled); /// public void WriteTo(Utf8JsonWriter writer) diff --git a/src/Sentry/SpanId.cs b/src/Sentry/SpanId.cs index 71f36446af..8237e9e99e 100644 --- a/src/Sentry/SpanId.cs +++ b/src/Sentry/SpanId.cs @@ -38,8 +38,7 @@ private string GetNormalizedValue() => !string.IsNullOrWhiteSpace(_value) /// public bool Equals(SpanId other) => StringComparer.Ordinal.Equals( GetNormalizedValue(), - other.GetNormalizedValue() - ); + other.GetNormalizedValue()); /// public override bool Equals(object? obj) => obj is SpanId other && Equals(other); diff --git a/src/Sentry/SpanTracer.cs b/src/Sentry/SpanTracer.cs index a1deb108ff..4300c600e8 100644 --- a/src/Sentry/SpanTracer.cs +++ b/src/Sentry/SpanTracer.cs @@ -116,7 +116,6 @@ public void Finish(Exception exception) => public SentryTraceHeader GetTraceHeader() => new( TraceId, SpanId, - IsSampled - ); + IsSampled); } } diff --git a/src/Sentry/Transaction.cs b/src/Sentry/Transaction.cs index e049b47465..ee08f097a2 100644 --- a/src/Sentry/Transaction.cs +++ b/src/Sentry/Transaction.cs @@ -248,8 +248,7 @@ public void UnsetTag(string key) => public SentryTraceHeader GetTraceHeader() => new( TraceId, SpanId, - IsSampled - ); + IsSampled); /// public void WriteTo(Utf8JsonWriter writer) diff --git a/src/Sentry/TransactionTracer.cs b/src/Sentry/TransactionTracer.cs index d65497f14e..a640587883 100644 --- a/src/Sentry/TransactionTracer.cs +++ b/src/Sentry/TransactionTracer.cs @@ -256,7 +256,7 @@ public void Finish(Exception exception) => Finish(exception, SpanStatusConverter.FromException(exception)); /// - public ISpan? GetLastActiveSpan() => + public ISpan? GetLastActiveSpan() => // We need to sort by timestamp because the order of ConcurrentBag is not deterministic Spans.OrderByDescending(x => x.StartTimestamp).FirstOrDefault(s => !s.IsFinished); @@ -264,7 +264,6 @@ public void Finish(Exception exception) => public SentryTraceHeader GetTraceHeader() => new( TraceId, SpanId, - IsSampled - ); + IsSampled); } } diff --git a/src/Sentry/User.cs b/src/Sentry/User.cs index d7eb8746ec..38f593eb90 100644 --- a/src/Sentry/User.cs +++ b/src/Sentry/User.cs @@ -124,8 +124,7 @@ internal void CopyTo(User? user) user.InternalOther ??= InternalOther?.ToDictionary( entry => entry.Key, - entry => entry.Value - ); + entry => entry.Value); } /// diff --git a/test/Sentry.AspNet.Tests/HttpContextExtensionsTests.cs b/test/Sentry.AspNet.Tests/HttpContextExtensionsTests.cs index fb1ce44331..ea0ea61a4a 100644 --- a/test/Sentry.AspNet.Tests/HttpContextExtensionsTests.cs +++ b/test/Sentry.AspNet.Tests/HttpContextExtensionsTests.cs @@ -17,8 +17,7 @@ public void StartSentryTransaction_CreatesValidTransaction() { RequestType = "GET" }, - new HttpResponse(TextWriter.Null) - ); + new HttpResponse(TextWriter.Null)); // Act var transaction = context.StartSentryTransaction(); @@ -42,8 +41,7 @@ public void StartSentryTransaction_BindsToScope() { RequestType = "GET" }, - new HttpResponse(TextWriter.Null) - ); + new HttpResponse(TextWriter.Null)); // Act var transaction = context.StartSentryTransaction(); @@ -70,8 +68,7 @@ public void FinishSentryTransaction_FinishesTransaction() new HttpResponse(TextWriter.Null) { StatusCode = 404 - } - ); + }); // Act var transaction = context.StartSentryTransaction(); diff --git a/test/Sentry.AspNetCore.Tests/SentryHttpMessageHandlerBuilderFilterTests.cs b/test/Sentry.AspNetCore.Tests/SentryHttpMessageHandlerBuilderFilterTests.cs index 0f74150e54..ef732836e2 100644 --- a/test/Sentry.AspNetCore.Tests/SentryHttpMessageHandlerBuilderFilterTests.cs +++ b/test/Sentry.AspNetCore.Tests/SentryHttpMessageHandlerBuilderFilterTests.cs @@ -74,11 +74,15 @@ public async Task Generated_client_sends_Sentry_trace_header_automatically() .GetRequiredService() .CreateClient(); - await httpClient.GetAsync("https://example.com"); + // The framework setup pipeline would end up adding an HttpClientHandler and this test + // would require access to the Internet. So overriding it here + // so the request stops at our stub: + recorder.InnerHandler = new FakeHttpMessageHandler(); + + await httpClient.GetAsync("https://fake.tld"); }); }); - }) - ); + })); var client = server.CreateClient(); diff --git a/test/Sentry.AspNetCore.Tests/SentryTracingMiddlewareTests.cs b/test/Sentry.AspNetCore.Tests/SentryTracingMiddlewareTests.cs index 6bfeb95135..3a0644270e 100644 --- a/test/Sentry.AspNetCore.Tests/SentryTracingMiddlewareTests.cs +++ b/test/Sentry.AspNetCore.Tests/SentryTracingMiddlewareTests.cs @@ -54,8 +54,7 @@ public async Task Transactions_are_grouped_by_route() await ctx.Response.WriteAsync($"Person #{id}"); }); }); - }) - ); + })); var client = server.CreateClient(); @@ -65,8 +64,7 @@ public async Task Transactions_are_grouped_by_route() // Assert sentryClient.Received(2).CaptureTransaction( - Arg.Is(transaction => transaction.Name == "GET /person/{id}") - ); + Arg.Is(transaction => transaction.Name == "GET /person/{id}")); } [Fact] @@ -105,8 +103,7 @@ public async Task Transaction_is_bound_on_the_scope_automatically() return Task.CompletedTask; }); }); - }) - ); + })); var client = server.CreateClient(); @@ -149,8 +146,7 @@ public async Task Transaction_is_started_automatically_from_incoming_trace_heade { routes.Map("/person/{id}", _ => Task.CompletedTask); }); - }) - ); + })); var client = server.CreateClient(); @@ -208,8 +204,7 @@ public async Task Transaction_is_automatically_populated_with_request_data() return Task.CompletedTask; }); }); - }) - ); + })); var client = server.CreateClient(); @@ -265,8 +260,7 @@ public async Task Transaction_sampling_context_contains_HTTP_context_data() { routes.Map("/person/{id}", _ => Task.CompletedTask); }); - }) - ); + })); var client = server.CreateClient(); @@ -329,8 +323,7 @@ public async Task Transaction_binds_exception_thrown() { routes.Map("/person/{id}", _ => throw exception); }); - }) - ); + })); var client = server.CreateClient(); diff --git a/test/Sentry.Testing/FakeHttpMessageHandler.cs b/test/Sentry.Testing/FakeHttpMessageHandler.cs index 36e71268c9..3a7f82d27a 100644 --- a/test/Sentry.Testing/FakeHttpMessageHandler.cs +++ b/test/Sentry.Testing/FakeHttpMessageHandler.cs @@ -6,7 +6,7 @@ namespace Sentry.Testing { - public class FakeHttpMessageHandler : HttpMessageHandler + public class FakeHttpMessageHandler : DelegatingHandler { private readonly Func _getResponse; @@ -25,8 +25,7 @@ protected override Task SendAsync( return Task.FromResult( _getResponse is not null ? _getResponse(request) - : new HttpResponseMessage(HttpStatusCode.OK) - ); + : new HttpResponseMessage(HttpStatusCode.OK)); } } } diff --git a/test/Sentry.Testing/InMemoryDiagnosticLogger.cs b/test/Sentry.Testing/InMemoryDiagnosticLogger.cs index 1bd019f521..1816cd28d2 100644 --- a/test/Sentry.Testing/InMemoryDiagnosticLogger.cs +++ b/test/Sentry.Testing/InMemoryDiagnosticLogger.cs @@ -19,7 +19,6 @@ public record Entry( SentryLevel Level, string Message, Exception Exception, - object[] Args - ); + object[] Args); } } diff --git a/test/Sentry.Testing/RecordingHttpMessageHandler.cs b/test/Sentry.Testing/RecordingHttpMessageHandler.cs index ed92735622..6da5ff4507 100644 --- a/test/Sentry.Testing/RecordingHttpMessageHandler.cs +++ b/test/Sentry.Testing/RecordingHttpMessageHandler.cs @@ -22,7 +22,7 @@ protected override async Task SendAsync( // Clone the request to avoid ObjectDisposedException _requests.Add(await request.CloneAsync()); - InnerHandler ??= new HttpClientHandler(); + InnerHandler ??= new FakeHttpMessageHandler(); return await base.SendAsync(request, cancellationToken); } diff --git a/test/Sentry.Tests/GlobalSessionManagerTests.cs b/test/Sentry.Tests/GlobalSessionManagerTests.cs index edc566fdbe..94c3ba30f6 100644 --- a/test/Sentry.Tests/GlobalSessionManagerTests.cs +++ b/test/Sentry.Tests/GlobalSessionManagerTests.cs @@ -76,8 +76,7 @@ public void StartSession_CacheDirectoryProvided_InstallationIdFileCreated() _fixture.Options.CacheDirectoryPath!, "Sentry", _fixture.Options.Dsn!.GetHashString(), - ".installation" - ); + ".installation"); // Act sut.StartSession(); @@ -97,8 +96,7 @@ public void StartSession_CacheDirectoryNotProvided_InstallationIdFileCreated() Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Sentry", _fixture.Options.Dsn!.GetHashString(), - ".installation" - ); + ".installation"); // Act sut.StartSession(); @@ -167,8 +165,7 @@ public void ReportError_ActiveSessionDoesNotExist_LogsOutError() // Assert _fixture.Logger.Entries.Should().Contain(e => e.Message == "Failed to report an error on a session because there is none active." && - e.Level == SentryLevel.Debug - ); + e.Level == SentryLevel.Debug); } [Fact] @@ -202,8 +199,7 @@ public void EndSession_ActiveSessionDoesNotExist_DoesNothing() _fixture.Logger.Entries.Should().Contain(e => e.Message == "Failed to end session because there is none active." && - e.Level == SentryLevel.Debug - ); + e.Level == SentryLevel.Debug); } [Fact] @@ -368,8 +364,7 @@ public void TryGetPersistentInstallationId_SessionStarted_CrashDelegateReturnsTr var sut = _fixture.GetSut(); using var fixture = new Fixture(o => - o.CrashedLastRun = () => true - ); + o.CrashedLastRun = () => true); sut.StartSession(); diff --git a/test/Sentry.Tests/HubTests.cs b/test/Sentry.Tests/HubTests.cs index d85339b12f..ef371b32ac 100644 --- a/test/Sentry.Tests/HubTests.cs +++ b/test/Sentry.Tests/HubTests.cs @@ -170,8 +170,7 @@ public void CaptureException_FinishedSpanBoundToSameExceptionExists_EventIsLinke Arg.Is(evt => evt.Contexts.Trace.TraceId == transaction.TraceId && evt.Contexts.Trace.SpanId == transaction.SpanId), - Arg.Any() - ); + Arg.Any()); } [Fact] @@ -200,8 +199,7 @@ public void CaptureException_ActiveSpanExistsOnScope_EventIsLinkedToSpan() Arg.Is(evt => evt.Contexts.Trace.TraceId == transaction.TraceId && evt.Contexts.Trace.SpanId == transaction.SpanId), - Arg.Any() - ); + Arg.Any()); } [Fact] @@ -230,8 +228,7 @@ public void CaptureException_ActiveSpanExistsOnScopeButIsSampledOut_EventIsNotLi Arg.Is(evt => evt.Contexts.Trace.TraceId == default && evt.Contexts.Trace.SpanId == default), - Arg.Any() - ); + Arg.Any()); } [Fact] @@ -254,8 +251,7 @@ public void CaptureException_NoActiveSpanAndNoSpanBoundToSameException_EventIsNo Arg.Is(evt => evt.Contexts.Trace.TraceId == default && evt.Contexts.Trace.SpanId == default), - Arg.Any() - ); + Arg.Any()); } [Fact] @@ -351,8 +347,7 @@ public void CaptureEvent_ActiveSession_UnhandledExceptionSessionEndedAsCrashed() .OfType() .Single() .EndStatus == SessionEndStatus.Crashed - ) - ); + )); } [Fact] @@ -386,8 +381,7 @@ public void StartTransaction_FromTraceHeader_CopiesContext() var traceHeader = new SentryTraceHeader( SentryId.Parse("75302ac48a024bde9a3b3734a82e36c8"), SpanId.Parse("2000000000000000"), - true - ); + true); // Act var transaction = hub.StartTransaction("name", "operation", traceHeader); @@ -411,8 +405,7 @@ public void StartTransaction_FromTraceHeader_SampledInheritedFromParentRegardles var traceHeader = new SentryTraceHeader( SentryId.Parse("75302ac48a024bde9a3b3734a82e36c8"), SpanId.Parse("2000000000000000"), - true - ); + true); // Act var transaction = hub.StartTransaction("name", "operation", traceHeader); @@ -435,8 +428,7 @@ public void StartTransaction_FromTraceHeader_CustomSamplerCanSampleOutTransactio var traceHeader = new SentryTraceHeader( SentryId.Parse("75302ac48a024bde9a3b3734a82e36c8"), SpanId.Parse("2000000000000000"), - true - ); + true); // Act var transaction = hub.StartTransaction("foo", "bar", traceHeader); @@ -504,13 +496,11 @@ public void StartTransaction_StaticSampling_50PercentDistribution() // Assert transactionsSampledIn.Length.Should().BeCloseTo( (int)(0.5 * transactions.Length), - (uint)(allowedRelativeDeviation * transactions.Length) - ); + (uint)(allowedRelativeDeviation * transactions.Length)); transactionsSampledOut.Length.Should().BeCloseTo( (int)(0.5 * transactions.Length), - (uint)(allowedRelativeDeviation * transactions.Length) - ); + (uint)(allowedRelativeDeviation * transactions.Length)); } [Fact] @@ -538,13 +528,11 @@ public void StartTransaction_StaticSampling_25PercentDistribution() // Assert transactionsSampledIn.Length.Should().BeCloseTo( (int)(0.25 * transactions.Length), - (uint)(allowedRelativeDeviation * transactions.Length) - ); + (uint)(allowedRelativeDeviation * transactions.Length)); transactionsSampledOut.Length.Should().BeCloseTo( (int)(0.75 * transactions.Length), - (uint)(allowedRelativeDeviation * transactions.Length) - ); + (uint)(allowedRelativeDeviation * transactions.Length)); } [Fact] @@ -572,13 +560,11 @@ public void StartTransaction_StaticSampling_75PercentDistribution() // Assert transactionsSampledIn.Length.Should().BeCloseTo( (int)(0.75 * transactions.Length), - (uint)(allowedRelativeDeviation * transactions.Length) - ); + (uint)(allowedRelativeDeviation * transactions.Length)); transactionsSampledOut.Length.Should().BeCloseTo( (int)(0.25 * transactions.Length), - (uint)(allowedRelativeDeviation * transactions.Length) - ); + (uint)(allowedRelativeDeviation * transactions.Length)); } [Fact] @@ -628,8 +614,7 @@ public void StartTransaction_DynamicSampling_WithCustomContext_SampledIn() // Act var transaction = hub.StartTransaction( new TransactionContext("foo", "op"), - new Dictionary {["xxx"] = "zzz"} - ); + new Dictionary {["xxx"] = "zzz"}); // Assert transaction.IsSampled.Should().BeTrue(); @@ -648,8 +633,7 @@ public void StartTransaction_DynamicSampling_WithCustomContext_SampledOut() // Act var transaction = hub.StartTransaction( new TransactionContext("foo", "op"), - new Dictionary {["xxx"] = "yyy"} - ); + new Dictionary {["xxx"] = "yyy"}); // Assert transaction.IsSampled.Should().BeFalse(); diff --git a/test/Sentry.Tests/Internals/ApplicationVersionLocatorTests.cs b/test/Sentry.Tests/Internals/ApplicationVersionLocatorTests.cs index 91c22decba..ddbea1b63a 100644 --- a/test/Sentry.Tests/Internals/ApplicationVersionLocatorTests.cs +++ b/test/Sentry.Tests/Internals/ApplicationVersionLocatorTests.cs @@ -30,8 +30,7 @@ public void GetCurrent_VersionWithPrefix_ReturnsVersionAsIs() // Arrange var asm = AssemblyCreationHelper.CreateWithInformationalVersion( "app@1.0.0", - new AssemblyName("dynamic-assembly") - ); + new AssemblyName("dynamic-assembly")); // Act var version = ApplicationVersionLocator.GetCurrent(asm); diff --git a/test/Sentry.Tests/Internals/Http/CachingTransportTests.cs b/test/Sentry.Tests/Internals/Http/CachingTransportTests.cs index 037e690690..0f29be890d 100644 --- a/test/Sentry.Tests/Internals/Http/CachingTransportTests.cs +++ b/test/Sentry.Tests/Internals/Http/CachingTransportTests.cs @@ -184,8 +184,7 @@ public async Task DoesNotRetryOnNonTransientExceptions() .Returns(_ => isFailing ? Task.FromException(new InvalidOperationException()) - : Task.CompletedTask - ); + : Task.CompletedTask); await using var transport = new CachingTransport(innerTransport, options); diff --git a/test/Sentry.Tests/Internals/Http/HttpTransportTests.cs b/test/Sentry.Tests/Internals/Http/HttpTransportTests.cs index cfc29a89ad..4f53e0c58f 100644 --- a/test/Sentry.Tests/Internals/Http/HttpTransportTests.cs +++ b/test/Sentry.Tests/Internals/Http/HttpTransportTests.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using FluentAssertions; using NSubstitute; +using Sentry.Internal; using Sentry.Internal.Http; using Sentry.Protocol.Envelopes; using Sentry.Testing; @@ -33,12 +34,10 @@ public async Task SendEnvelopeAsync_CancellationToken_PassedToClient() var httpTransport = new HttpTransport( new SentryOptions {Dsn = DsnSamples.ValidDsnWithSecret}, - new HttpClient(httpHandler) - ); + new HttpClient(httpHandler)); var envelope = Envelope.FromEvent( - new SentryEvent(eventId: SentryResponses.ResponseId) - ); + new SentryEvent(eventId: SentryResponses.ResponseId)); #if NET5_0 await Assert.ThrowsAsync(() => httpTransport.SendEnvelopeAsync(envelope, token)); @@ -76,8 +75,7 @@ public async Task SendEnvelopeAsync_ResponseNotOkWithJsonMessage_LogsError() Debug = true, DiagnosticLogger = logger }, - new HttpClient(httpHandler) - ); + new HttpClient(httpHandler)); var envelope = Envelope.FromEvent(new SentryEvent()); @@ -219,8 +217,7 @@ public async Task SendEnvelopeAsync_ResponseNotOkWithStringMessage_LogsError() Debug = true, DiagnosticLogger = logger }, - new HttpClient(httpHandler) - ); + new HttpClient(httpHandler)); var envelope = Envelope.FromEvent(new SentryEvent()); @@ -258,8 +255,7 @@ public async Task SendEnvelopeAsync_ResponseNotOkNoMessage_LogsError() Debug = true, DiagnosticLogger = logger }, - new HttpClient(httpHandler) - ); + new HttpClient(httpHandler)); var envelope = Envelope.FromEvent(new SentryEvent()); @@ -285,16 +281,14 @@ public async Task SendEnvelopeAsync_ItemRateLimit_DropsItem() using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler( () => SentryResponses.GetRateLimitResponse("1234:event, 897:transaction") - ) - ); + )); var httpTransport = new HttpTransport( new SentryOptions { Dsn = DsnSamples.ValidDsnWithSecret }, - new HttpClient(httpHandler) - ); + new HttpClient(httpHandler)); // First request always goes through await httpTransport.SendEnvelopeAsync(Envelope.FromEvent(new SentryEvent())); @@ -318,8 +312,7 @@ public async Task SendEnvelopeAsync_ItemRateLimit_DropsItem() new EnvelopeItem( new Dictionary {["type"] = "other"}, new EmptySerializable()) - } - ); + }); var expectedEnvelope = new Envelope( new Dictionary(), @@ -328,8 +321,7 @@ public async Task SendEnvelopeAsync_ItemRateLimit_DropsItem() new EnvelopeItem( new Dictionary {["type"] = "other"}, new EmptySerializable()) - } - ); + }); var expectedEnvelopeSerialized = await expectedEnvelope.SerializeToStringAsync(); @@ -348,8 +340,7 @@ public async Task SendEnvelopeAsync_AttachmentTooLarge_DropsItem() { // Arrange using var httpHandler = new RecordingHttpMessageHandler( - new FakeHttpMessageHandler() - ); + new FakeHttpMessageHandler()); var logger = new InMemoryDiagnosticLogger(); @@ -361,27 +352,23 @@ public async Task SendEnvelopeAsync_AttachmentTooLarge_DropsItem() DiagnosticLogger = logger, Debug = true }, - new HttpClient(httpHandler) - ); + new HttpClient(httpHandler)); var attachmentNormal = new Attachment( AttachmentType.Default, new StreamAttachmentContent(new MemoryStream(new byte[] {1})), "test1.txt", - null - ); + null); var attachmentTooBig = new Attachment( AttachmentType.Default, new StreamAttachmentContent(new MemoryStream(new byte[] {1, 2, 3, 4, 5})), "test2.txt", - null - ); + null); using var envelope = Envelope.FromEvent( new SentryEvent(), - new[] {attachmentNormal, attachmentTooBig} - ); + new[] {attachmentNormal, attachmentTooBig}); // Act await httpTransport.SendEnvelopeAsync(envelope); @@ -395,8 +382,7 @@ public async Task SendEnvelopeAsync_AttachmentTooLarge_DropsItem() logger.Entries.Should().Contain(e => e.Message == "Attachment '{0}' dropped because it's too large ({1} bytes)." && e.Args[0].ToString() == "test2.txt" && - e.Args[1].ToString() == "5" - ); + e.Args[1].ToString() == "5"); actualEnvelopeSerialized.Should().NotContain("test2.txt"); } @@ -408,16 +394,14 @@ public async Task SendEnvelopeAsync_ItemRateLimit_PromotesNextSessionWithSameId( using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler( () => SentryResponses.GetRateLimitResponse("1:session") - ) - ); + )); var httpTransport = new HttpTransport( new SentryOptions { Dsn = DsnSamples.ValidDsnWithSecret }, - new HttpClient(httpHandler) - ); + new HttpClient(httpHandler)); var session = new Session("foo", "bar", "baz"); @@ -452,16 +436,14 @@ public async Task SendEnvelopeAsync_ItemRateLimit_DoesNotAffectNextSessionWithDi using var httpHandler = new RecordingHttpMessageHandler( new FakeHttpMessageHandler( () => SentryResponses.GetRateLimitResponse("1:session") - ) - ); + )); var httpTransport = new HttpTransport( new SentryOptions { Dsn = DsnSamples.ValidDsnWithSecret }, - new HttpClient(httpHandler) - ); + new HttpClient(httpHandler)); var session = new Session("foo", "bar", "baz"); @@ -496,8 +478,7 @@ public void CreateRequest_AuthHeader_IsSet() // Arrange var httpTransport = new HttpTransport( new SentryOptions {Dsn = DsnSamples.ValidDsnWithSecret}, - new HttpClient() - ); + new HttpClient()); var envelope = Envelope.FromEvent(new SentryEvent()); @@ -515,8 +496,7 @@ public void CreateRequest_RequestMethod_Post() // Arrange var httpTransport = new HttpTransport( new SentryOptions {Dsn = DsnSamples.ValidDsnWithSecret}, - new HttpClient() - ); + new HttpClient()); var envelope = Envelope.FromEvent(new SentryEvent()); @@ -533,8 +513,7 @@ public void CreateRequest_SentryUrl_FromOptions() // Arrange var httpTransport = new HttpTransport( new SentryOptions {Dsn = DsnSamples.ValidDsnWithSecret}, - new HttpClient() - ); + new HttpClient()); var envelope = Envelope.FromEvent(new SentryEvent()); @@ -553,8 +532,7 @@ public async Task CreateRequest_Content_IncludesEvent() // Arrange var httpTransport = new HttpTransport( new SentryOptions {Dsn = DsnSamples.ValidDsnWithSecret}, - new HttpClient() - ); + new HttpClient()); var envelope = Envelope.FromEvent(new SentryEvent()); diff --git a/test/Sentry.Tests/Internals/Http/RateLimitCategoryTests.cs b/test/Sentry.Tests/Internals/Http/RateLimitCategoryTests.cs index c2b2650603..db90c2f2c8 100644 --- a/test/Sentry.Tests/Internals/Http/RateLimitCategoryTests.cs +++ b/test/Sentry.Tests/Internals/Http/RateLimitCategoryTests.cs @@ -24,8 +24,7 @@ public void Matches_IncludedItemType_ShouldMatch(string categoryName, string ite var envelopeItem = new EnvelopeItem( new Dictionary {["type"] = itemType}, - new EmptySerializable() - ); + new EmptySerializable()); // Act var matches = category.Matches(envelopeItem); @@ -45,8 +44,7 @@ public void Matches_NotIncludedItemType_ShouldNotMatch(string categoryName, stri var envelopeItem = new EnvelopeItem( new Dictionary {["type"] = itemType}, - new EmptySerializable() - ); + new EmptySerializable()); // Act var matches = category.Matches(envelopeItem); diff --git a/test/Sentry.Tests/Internals/JsonTests.cs b/test/Sentry.Tests/Internals/JsonTests.cs index 33e843a0d4..0e08902716 100644 --- a/test/Sentry.Tests/Internals/JsonTests.cs +++ b/test/Sentry.Tests/Internals/JsonTests.cs @@ -186,8 +186,7 @@ public void WriteDynamicValue_ClassWithTimeZone_SerializedClassWithTimeZoneInfo( "tz_id", TimeSpan.FromHours(2), "my timezone", - "my timezone" - ); + "my timezone"); var expectedSerializedData = new[] { "\"Id\":1,\"Data\":\"1234\"", diff --git a/test/Sentry.Tests/Internals/ReleaseLocatorTests.cs b/test/Sentry.Tests/Internals/ReleaseLocatorTests.cs index e378429a9f..f11c8503cf 100644 --- a/test/Sentry.Tests/Internals/ReleaseLocatorTests.cs +++ b/test/Sentry.Tests/Internals/ReleaseLocatorTests.cs @@ -44,8 +44,7 @@ public void ResolveFromEnvironment_WithoutEnvironmentVariable_VersionOfEntryAsse { Assert.Equal( $"{ass!.GetName().Name}@{ass!.GetNameAndVersion().Version}", - ReleaseLocator.LocateFromEnvironment() - ); + ReleaseLocator.LocateFromEnvironment()); }); } } diff --git a/test/Sentry.Tests/Internals/ScopeStack/AsyncLocalScopeStackContainerTests.cs b/test/Sentry.Tests/Internals/ScopeStack/AsyncLocalScopeStackContainerTests.cs index 26999f284f..ba7498368a 100644 --- a/test/Sentry.Tests/Internals/ScopeStack/AsyncLocalScopeStackContainerTests.cs +++ b/test/Sentry.Tests/Internals/ScopeStack/AsyncLocalScopeStackContainerTests.cs @@ -17,13 +17,11 @@ public async Task Scopes_are_not_shared_between_parallel_async_executions() var scope1 = new KeyValuePair( Substitute.For(), - Substitute.For() - ); + Substitute.For()); var scope2 = new KeyValuePair( Substitute.For(), - Substitute.For() - ); + Substitute.For()); // Act & assert var task1 = Task.Run(async () => @@ -68,13 +66,11 @@ public async Task Scopes_are_not_shared_between_sequential_async_executions() var scope1 = new KeyValuePair( Substitute.For(), - Substitute.For() - ); + Substitute.For()); var scope2 = new KeyValuePair( Substitute.For(), - Substitute.For() - ); + Substitute.For()); // Act & assert await Task.Run(async () => @@ -117,13 +113,11 @@ public async Task Scopes_are_shared_between_nested_async_executions() var scope1 = new KeyValuePair( Substitute.For(), - Substitute.For() - ); + Substitute.For()); var scope2 = new KeyValuePair( Substitute.For(), - Substitute.For() - ); + Substitute.For()); // Act & assert await Task.Run(async () => diff --git a/test/Sentry.Tests/Internals/ScopeStack/GlobalScopeStackContainerTests.cs b/test/Sentry.Tests/Internals/ScopeStack/GlobalScopeStackContainerTests.cs index 8df826f10d..ce20d027cf 100644 --- a/test/Sentry.Tests/Internals/ScopeStack/GlobalScopeStackContainerTests.cs +++ b/test/Sentry.Tests/Internals/ScopeStack/GlobalScopeStackContainerTests.cs @@ -17,13 +17,11 @@ public async Task Scopes_are_shared_between_parallel_async_executions() var scope1 = new KeyValuePair( Substitute.For(), - Substitute.For() - ); + Substitute.For()); var scope2 = new KeyValuePair( Substitute.For(), - Substitute.For() - ); + Substitute.For()); // Act & assert await Task.Run(async () => diff --git a/test/Sentry.Tests/Internals/SentryScopeManagerTests.cs b/test/Sentry.Tests/Internals/SentryScopeManagerTests.cs index 4b700f16ba..6f92527be9 100644 --- a/test/Sentry.Tests/Internals/SentryScopeManagerTests.cs +++ b/test/Sentry.Tests/Internals/SentryScopeManagerTests.cs @@ -22,8 +22,7 @@ private class Fixture public SentryScopeManager GetSut() => new( SentryOptions.ScopeStackContainer ?? new AsyncLocalScopeStackContainer(), SentryOptions, - Client - ); + Client); } private readonly Fixture _fixture = new(); diff --git a/test/Sentry.Tests/Internals/SentryStackTraceFactoryTests.cs b/test/Sentry.Tests/Internals/SentryStackTraceFactoryTests.cs index 9043af1a20..7268a192d7 100644 --- a/test/Sentry.Tests/Internals/SentryStackTraceFactoryTests.cs +++ b/test/Sentry.Tests/Internals/SentryStackTraceFactoryTests.cs @@ -43,15 +43,13 @@ public void Create_NoExceptionAndAttachStackTraceOptionOnWithOriginalMode_Curren Assert.Equal( nameof(Create_NoExceptionAndAttachStackTraceOptionOnWithOriginalMode_CurrentStackTrace), - stackTrace.Frames.Last().Function - ); + stackTrace.Frames.Last().Function); Assert.DoesNotContain(stackTrace.Frames, p => p.Function?.StartsWith( nameof(SentryStackTraceFactory.CreateFrame) + '(', StringComparison.Ordinal - ) == true - ); + ) == true); } [Fact] @@ -70,15 +68,13 @@ public void Create_NoExceptionAndAttachStackTraceOptionOnWithEnhancedMode_Curren $"{GetType().Name}" + $".{nameof(Create_NoExceptionAndAttachStackTraceOptionOnWithEnhancedMode_CurrentStackTrace)}" + "()", - stackTrace.Frames.Last().Function - ); + stackTrace.Frames.Last().Function); Assert.DoesNotContain(stackTrace.Frames, p => p.Function?.StartsWith( nameof(SentryStackTraceFactory.CreateFrame) + '(', StringComparison.Ordinal - ) == true - ); + ) == true); } [Fact] diff --git a/test/Sentry.Tests/Protocol/BreadcrumbTests.cs b/test/Sentry.Tests/Protocol/BreadcrumbTests.cs index f39dec1ac8..838b8438d8 100644 --- a/test/Sentry.Tests/Protocol/BreadcrumbTests.cs +++ b/test/Sentry.Tests/Protocol/BreadcrumbTests.cs @@ -40,8 +40,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "\"data\":{\"key\":\"val\"}," + "\"category\":\"category1\"," + "\"level\":\"warning\"}", - actual - ); + actual); } [Theory] diff --git a/test/Sentry.Tests/Protocol/Context/DeviceTests.cs b/test/Sentry.Tests/Protocol/Context/DeviceTests.cs index 7849e2f68f..7dfa8a734c 100644 --- a/test/Sentry.Tests/Protocol/Context/DeviceTests.cs +++ b/test/Sentry.Tests/Protocol/Context/DeviceTests.cs @@ -27,8 +27,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "tz_id", TimeSpan.FromHours(2), "my timezone", - "my timezone" - ); + "my timezone"); var sut = new Device { diff --git a/test/Sentry.Tests/Protocol/Context/GpuTests.cs b/test/Sentry.Tests/Protocol/Context/GpuTests.cs index 4f852de309..95e8d910d2 100644 --- a/test/Sentry.Tests/Protocol/Context/GpuTests.cs +++ b/test/Sentry.Tests/Protocol/Context/GpuTests.cs @@ -48,8 +48,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "\"supports_ray_tracing\":false," + "\"supports_compute_shaders\":true," + "\"supports_geometry_shaders\":true}", - actual - ); + actual); } [Fact] diff --git a/test/Sentry.Tests/Protocol/Context/OperatingSystemTests.cs b/test/Sentry.Tests/Protocol/Context/OperatingSystemTests.cs index 66e30d0963..7693d46654 100644 --- a/test/Sentry.Tests/Protocol/Context/OperatingSystemTests.cs +++ b/test/Sentry.Tests/Protocol/Context/OperatingSystemTests.cs @@ -30,8 +30,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "\"build\":\"14393\"," + "\"kernel_version\":\"who knows\"," + "\"rooted\":true}", - actual - ); + actual); } [Fact] diff --git a/test/Sentry.Tests/Protocol/Context/TraceTests.cs b/test/Sentry.Tests/Protocol/Context/TraceTests.cs index 1d79db4085..27a6068a07 100644 --- a/test/Sentry.Tests/Protocol/Context/TraceTests.cs +++ b/test/Sentry.Tests/Protocol/Context/TraceTests.cs @@ -46,8 +46,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "\"op\":\"op123\"," + "\"status\":\"aborted\"" + "}", - actual - ); + actual); } [Fact] diff --git a/test/Sentry.Tests/Protocol/Envelopes/EnvelopeTests.cs b/test/Sentry.Tests/Protocol/Envelopes/EnvelopeTests.cs index 5218b06acf..04fa5f22d3 100644 --- a/test/Sentry.Tests/Protocol/Envelopes/EnvelopeTests.cs +++ b/test/Sentry.Tests/Protocol/Envelopes/EnvelopeTests.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading.Tasks; using FluentAssertions; +using Sentry.Internal; using Sentry.Protocol; using Sentry.Protocol.Envelopes; using Sentry.Testing; @@ -23,16 +24,14 @@ public async Task Serialization_EnvelopeWithoutItems_Success() // Arrange using var envelope = new Envelope( new Dictionary {["event_id"] = "12c2d058d58442709aa2eca08bf20986"}, - Array.Empty() - ); + Array.Empty()); // Act var output = await envelope.SerializeToStringAsync(); // Assert output.Should().Be( - "{\"event_id\":\"12c2d058d58442709aa2eca08bf20986\"}\n" - ); + "{\"event_id\":\"12c2d058d58442709aa2eca08bf20986\"}\n"); } [Fact] @@ -46,8 +45,7 @@ public async Task Deserialization_EnvelopeWithoutItems_Success() using var expectedEnvelope = new Envelope( new Dictionary {["event_id"] = "12c2d058d58442709aa2eca08bf20986"}, - Array.Empty() - ); + Array.Empty()); // Act using var envelope = await Envelope.DeserializeAsync(input); @@ -69,8 +67,7 @@ public async Task Serialization_EnvelopeWithoutHeader_Success() new StreamSerializable("{\"started\": \"2020-02-07T14:16:00Z\",\"attrs\":{\"release\":\"sentry-test@1.0.0\"}}" .ToMemoryStream()) ) - } - ); + }); // Act var output = await envelope.SerializeToStringAsync(); @@ -79,8 +76,7 @@ public async Task Serialization_EnvelopeWithoutHeader_Success() output.Should().Be( "{}\n" + "{\"type\":\"session\",\"length\":75}\n" + - "{\"started\": \"2020-02-07T14:16:00Z\",\"attrs\":{\"release\":\"sentry-test@1.0.0\"}}\n" - ); + "{\"started\": \"2020-02-07T14:16:00Z\",\"attrs\":{\"release\":\"sentry-test@1.0.0\"}}\n"); } [Fact] @@ -105,8 +101,7 @@ public async Task Deserialization_EnvelopeWithoutHeader_Success() new StreamSerializable("{\"started\": \"2020-02-07T14:16:00Z\",\"attrs\":{\"release\":\"sentry-test@1.0.0\"}}" .ToMemoryStream()) ) - } - ); + }); // Act using var envelope = await Envelope.DeserializeAsync(input); @@ -148,8 +143,7 @@ public async Task Serialization_EnvelopeWithTwoItems_Success() }, new StreamSerializable("{\"message\":\"hello world\",\"level\":\"error\"}".ToMemoryStream()) ) - } - ); + }); // Act var output = await envelope.SerializeToStringAsync(); @@ -160,8 +154,7 @@ public async Task Serialization_EnvelopeWithTwoItems_Success() "{\"type\":\"attachment\",\"length\":13,\"content_type\":\"text/plain\",\"filename\":\"hello.txt\"}\n" + "\xef\xbb\xbfHello\r\n\n" + "{\"type\":\"event\",\"length\":41,\"content_type\":\"application/json\",\"filename\":\"application.log\"}\n" + - "{\"message\":\"hello world\",\"level\":\"error\"}\n" - ); + "{\"message\":\"hello world\",\"level\":\"error\"}\n"); } [Fact] @@ -208,8 +201,7 @@ public async Task Deserialization_EnvelopeWithTwoItems_Success() }, new StreamSerializable("{\"message\":\"hello world\",\"level\":\"error\"}".ToMemoryStream()) ) - } - ); + }); // Act using var envelope = await Envelope.DeserializeAsync(input); @@ -243,8 +235,7 @@ public async Task Serialization_EnvelopeWithTwoEmptyItems_Success() }, new StreamSerializable(new MemoryStream()) ) - } - ); + }); // Act var output = await envelope.SerializeToStringAsync(); @@ -255,8 +246,7 @@ public async Task Serialization_EnvelopeWithTwoEmptyItems_Success() "{\"type\":\"attachment\",\"length\":0}\n" + "\n" + "{\"type\":\"attachment\",\"length\":0}\n" + - "\n" - ); + "\n"); } [Fact] @@ -295,8 +285,7 @@ public async Task Deserialization_EnvelopeWithTwoEmptyItems_Success() }, new StreamSerializable(new MemoryStream()) ) - } - ); + }); // Act using var envelope = await Envelope.DeserializeAsync(input); @@ -317,8 +306,7 @@ public async Task Serialization_EnvelopeWithItemWithoutLength_Success() new Dictionary {["type"] = "attachment"}, new StreamSerializable("helloworld".ToMemoryStream()) ) - } - ); + }); // Act var output = await envelope.SerializeToStringAsync(); @@ -327,8 +315,7 @@ public async Task Serialization_EnvelopeWithItemWithoutLength_Success() output.Should().Be( "{\"event_id\":\"9ec79c33ec9942ab8353589fcb2e04dc\"}\n" + "{\"type\":\"attachment\",\"length\":10}\n" + - "helloworld\n" - ); + "helloworld\n"); } [Fact] @@ -352,8 +339,7 @@ public async Task Deserialization_EnvelopeWithItemWithoutLength_Success() new Dictionary {["type"] = "attachment"}, new StreamSerializable("helloworld".ToMemoryStream()) ) - } - ); + }); // Act using var envelope = await Envelope.DeserializeAsync(input); @@ -433,8 +419,7 @@ public async Task Roundtrip_WithEvent_WithAttachment_Success() AttachmentType.Default, new StreamAttachmentContent(Stream.Null), "file.txt", - null - ); + null); using var envelope = Envelope.FromEvent(@event, new[] {attachment}); @@ -472,8 +457,7 @@ public async Task Roundtrip_WithEvent_WithSession_Success() AttachmentType.Default, new StreamAttachmentContent(Stream.Null), "file.txt", - null - ); + null); var sessionUpdate = new Session("foo", "bar", "baz").CreateUpdate(false, DateTimeOffset.Now); @@ -510,8 +494,7 @@ public async Task Roundtrip_WithUserFeedback_Success() SentryId.Create(), "Someone Nice", "foo@bar.com", - "Everything is great!" - ); + "Everything is great!"); using var envelope = Envelope.FromUserFeedback(feedback); @@ -576,8 +559,7 @@ public async Task Deserialization_EmptyStream_Throws() // Act & assert await Assert.ThrowsAnyAsync( - async () => await Envelope.DeserializeAsync(input) - ); + async () => await Envelope.DeserializeAsync(input)); } [Fact] @@ -591,8 +573,7 @@ public async Task Deserialization_InvalidData_Throws() // Act & assert await Assert.ThrowsAnyAsync( - async () => await Envelope.DeserializeAsync(input) - ); + async () => await Envelope.DeserializeAsync(input)); } [Fact] @@ -606,8 +587,7 @@ public async Task Deserialization_MalformedData_Throws() // Act & assert await Assert.ThrowsAnyAsync( - async () => await Envelope.DeserializeAsync(input) - ); + async () => await Envelope.DeserializeAsync(input)); } [Fact] diff --git a/test/Sentry.Tests/Protocol/Exceptions/MechanismTests.cs b/test/Sentry.Tests/Protocol/Exceptions/MechanismTests.cs index 9b944a50fd..099d9f65de 100644 --- a/test/Sentry.Tests/Protocol/Exceptions/MechanismTests.cs +++ b/test/Sentry.Tests/Protocol/Exceptions/MechanismTests.cs @@ -30,8 +30,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "\"description\":\"mechanism description\"," + "\"help_link\":\"https://helplink\"," + "\"handled\":true}", - actual - ); + actual); } [Theory] diff --git a/test/Sentry.Tests/Protocol/Exceptions/SentryExceptionTests.cs b/test/Sentry.Tests/Protocol/Exceptions/SentryExceptionTests.cs index 77473354d1..01b9eda123 100644 --- a/test/Sentry.Tests/Protocol/Exceptions/SentryExceptionTests.cs +++ b/test/Sentry.Tests/Protocol/Exceptions/SentryExceptionTests.cs @@ -39,8 +39,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "\"thread_id\":1," + "\"stacktrace\":{\"frames\":[{\"filename\":\"FileName\"}]}," + "\"mechanism\":{\"description\":\"Description\"}}", - actual - ); + actual); } [Fact] diff --git a/test/Sentry.Tests/Protocol/Exceptions/SentryStackFrameTests.cs b/test/Sentry.Tests/Protocol/Exceptions/SentryStackFrameTests.cs index 949963376a..5d66990b8a 100644 --- a/test/Sentry.Tests/Protocol/Exceptions/SentryStackFrameTests.cs +++ b/test/Sentry.Tests/Protocol/Exceptions/SentryStackFrameTests.cs @@ -55,8 +55,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "\"instruction_addr\":\"0xffffffff\"," + "\"instruction_offset\":5" + "}", - actual - ); + actual); } [Fact] diff --git a/test/Sentry.Tests/Protocol/PackageTests.cs b/test/Sentry.Tests/Protocol/PackageTests.cs index 00a43d9160..02409d594c 100644 --- a/test/Sentry.Tests/Protocol/PackageTests.cs +++ b/test/Sentry.Tests/Protocol/PackageTests.cs @@ -17,8 +17,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() Assert.Equal( "{\"name\":\"nuget:Sentry\"," + "\"version\":\"1.0.0-preview\"}", - actual - ); + actual); } [Theory] diff --git a/test/Sentry.Tests/Protocol/ScopeExtensionsTests.cs b/test/Sentry.Tests/Protocol/ScopeExtensionsTests.cs index 0125260029..3ac42f1db5 100644 --- a/test/Sentry.Tests/Protocol/ScopeExtensionsTests.cs +++ b/test/Sentry.Tests/Protocol/ScopeExtensionsTests.cs @@ -514,8 +514,7 @@ public void AddAttachment_AllArgumentsMatch() expectedStream, expectedFileName, expectedType, - expectedContentType - ); + expectedContentType); // Assert var attachment = Assert.Single(scope.Attachments); @@ -546,8 +545,7 @@ public void AddAttachment_FromStream_UnknownLength_IsDropped() Assert.Empty(scope.Attachments); Assert.Contains(logger.Entries, e => e.Message == "Cannot evaluate the size of attachment '{0}' because the stream is not seekable." && - e.Args[0].ToString() == "example.html" - ); + e.Args[0].ToString() == "example.html"); } [Fact] diff --git a/test/Sentry.Tests/Protocol/SdkVersionTests.cs b/test/Sentry.Tests/Protocol/SdkVersionTests.cs index 984ac62f3d..ec6a67c08d 100644 --- a/test/Sentry.Tests/Protocol/SdkVersionTests.cs +++ b/test/Sentry.Tests/Protocol/SdkVersionTests.cs @@ -36,8 +36,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "{\"packages\":[{\"name\":\"Sentry\",\"version\":\"1.0\"},{\"name\":\"Sentry.AspNetCore\",\"version\":\"2.0\"}]," + "\"name\":\"Sentry.Test.SDK\"," + "\"version\":\"0.0.1-preview1\"}", - actual - ); + actual); } [Theory] diff --git a/test/Sentry.Tests/Protocol/SentryMessageTests.cs b/test/Sentry.Tests/Protocol/SentryMessageTests.cs index 74333ec59a..787ffa3724 100644 --- a/test/Sentry.Tests/Protocol/SentryMessageTests.cs +++ b/test/Sentry.Tests/Protocol/SentryMessageTests.cs @@ -23,8 +23,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "{\"message\":\"Message {eventId} {name}\"," + "\"params\":[100,\"test-name\"]," + "\"formatted\":\"Message 100 test-name\"}", - actual - ); + actual); } [Theory] diff --git a/test/Sentry.Tests/Protocol/SentryThreadTests.cs b/test/Sentry.Tests/Protocol/SentryThreadTests.cs index e3b530a52b..b9146ee844 100644 --- a/test/Sentry.Tests/Protocol/SentryThreadTests.cs +++ b/test/Sentry.Tests/Protocol/SentryThreadTests.cs @@ -33,8 +33,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "\"crashed\":true," + "\"current\":true," + "\"stacktrace\":{\"frames\":[{\"filename\":\"test\"}]}}", - actual - ); + actual); } [Theory] diff --git a/test/Sentry.Tests/Protocol/TransactionTests.cs b/test/Sentry.Tests/Protocol/TransactionTests.cs index 6c097a9892..3181460927 100644 --- a/test/Sentry.Tests/Protocol/TransactionTests.cs +++ b/test/Sentry.Tests/Protocol/TransactionTests.cs @@ -61,8 +61,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "type", new Dictionary {{"data-key", "data-value"}}, "category", - BreadcrumbLevel.Warning) - ); + BreadcrumbLevel.Warning)); transaction.SetExtra("extra_key", "extra_value"); transaction.Fingerprint = new[] {"fingerprint"}; @@ -275,8 +274,7 @@ public void Finish_DropsUnfinishedSpans() t.Spans.Any(s => s.Operation == "op1") && t.Spans.All(s => s.Operation != "op2") && t.Spans.Any(s => s.Operation == "op3") - ) - ); + )); } [Fact] diff --git a/test/Sentry.Tests/Protocol/UserFeedbackTests.cs b/test/Sentry.Tests/Protocol/UserFeedbackTests.cs index 1bfd26c987..9091f3cd95 100644 --- a/test/Sentry.Tests/Protocol/UserFeedbackTests.cs +++ b/test/Sentry.Tests/Protocol/UserFeedbackTests.cs @@ -27,8 +27,7 @@ public void Serialization_SentryUserFeedbacks_Success() "\"name\":\"myName\"," + "\"email\":\"myEmail@service.com\"," + "\"comments\":\"my comment\"" + - "}" - ); + "}"); } } } diff --git a/test/Sentry.Tests/Protocol/UserTests.cs b/test/Sentry.Tests/Protocol/UserTests.cs index 1cf7114c8b..0025ae6bef 100644 --- a/test/Sentry.Tests/Protocol/UserTests.cs +++ b/test/Sentry.Tests/Protocol/UserTests.cs @@ -29,8 +29,7 @@ public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject() "\"username\":\"user-name\"," + "\"other\":{\"testCustomValueKey\":\"testCustomValue\"}" + "}", - actual - ); + actual); } [Fact] diff --git a/test/Sentry.Tests/ScopeTests.cs b/test/Sentry.Tests/ScopeTests.cs index daec943da2..db1b124251 100644 --- a/test/Sentry.Tests/ScopeTests.cs +++ b/test/Sentry.Tests/ScopeTests.cs @@ -58,8 +58,7 @@ public void OnEvaluate_EventHandlerThrows_LogsException() // Assert logger.Entries.Should().Contain(entry => entry.Message == "Failed invoking event handler." && - entry.Exception == exception - ); + entry.Exception == exception); } [Fact] diff --git a/test/Sentry.Tests/SentryClientTests.cs b/test/Sentry.Tests/SentryClientTests.cs index 3bf70a0b33..63165751a2 100644 --- a/test/Sentry.Tests/SentryClientTests.cs +++ b/test/Sentry.Tests/SentryClientTests.cs @@ -280,13 +280,11 @@ public void CaptureEvent_Sampling50Percent_EqualDistribution() // Assert sampledInEventsCount.Should().BeCloseTo( (int)(0.5 * eventIds.Length), - (uint)(allowedRelativeDeviation * eventIds.Length) - ); + (uint)(allowedRelativeDeviation * eventIds.Length)); sampledOutEventsCount.Should().BeCloseTo( (int)(0.5 * eventIds.Length), - (uint)(allowedRelativeDeviation * eventIds.Length) - ); + (uint)(allowedRelativeDeviation * eventIds.Length)); } [Fact] @@ -315,13 +313,11 @@ public void CaptureEvent_Sampling25Percent_AppropriateDistribution() // Assert sampledInEventsCount.Should().BeCloseTo( (int)(0.25 * eventIds.Length), - (uint)(allowedRelativeDeviation * eventIds.Length) - ); + (uint)(allowedRelativeDeviation * eventIds.Length)); sampledOutEventsCount.Should().BeCloseTo( (int)(0.75 * eventIds.Length), - (uint)(allowedRelativeDeviation * eventIds.Length) - ); + (uint)(allowedRelativeDeviation * eventIds.Length)); } [Fact] @@ -350,13 +346,11 @@ public void CaptureEvent_Sampling75Percent_AppropriateDistribution() // Assert sampledInEventsCount.Should().BeCloseTo( (int)(0.75 * eventIds.Length), - (uint)(allowedRelativeDeviation * eventIds.Length) - ); + (uint)(allowedRelativeDeviation * eventIds.Length)); sampledOutEventsCount.Should().BeCloseTo( (int)(0.25 * eventIds.Length), - (uint)(allowedRelativeDeviation * eventIds.Length) - ); + (uint)(allowedRelativeDeviation * eventIds.Length)); } [Fact] @@ -403,8 +397,7 @@ public void CaptureUserFeedback_EventIdEmpty_IgnoreUserFeedback() //Act sut.CaptureUserFeedback( - new UserFeedback(SentryId.Empty, "name", "email", "comment") - ); + new UserFeedback(SentryId.Empty, "name", "email", "comment")); //Assert _ = sut.Worker.DidNotReceive().EnqueueEnvelope(Arg.Any()); @@ -418,8 +411,7 @@ public void CaptureUserFeedback_ValidUserFeedback_FeedbackRegistered() //Act sut.CaptureUserFeedback( - new UserFeedback(SentryId.Parse("4eb98e5f861a41019f270a7a27e84f02"), "name", "email", "comment") - ); + new UserFeedback(SentryId.Parse("4eb98e5f861a41019f270a7a27e84f02"), "name", "email", "comment")); //Assert _ = sut.Worker.Received(1).EnqueueEnvelope(Arg.Any()); @@ -482,8 +474,7 @@ public void CaptureTransaction_ValidTransaction_Sent() { IsSampled = true, EndTimestamp = DateTimeOffset.Now // finished - } - ); + }); // Assert _ = client.Worker.Received(1).EnqueueEnvelope(Arg.Any()); @@ -528,8 +519,7 @@ public void CaptureTransaction_NoName_Ignored() { IsSampled = true, EndTimestamp = DateTimeOffset.Now // finished - } - ); + }); // Assert _ = client.Worker.DidNotReceive().EnqueueEnvelope(Arg.Any()); @@ -550,8 +540,7 @@ public void CaptureTransaction_NoOperation_Ignored() { IsSampled = true, EndTimestamp = DateTimeOffset.Now // finished - } - ); + }); // Assert _ = client.Worker.DidNotReceive().EnqueueEnvelope(Arg.Any()); @@ -572,8 +561,7 @@ public void CaptureTransaction_NotFinished_Sent() { IsSampled = true, EndTimestamp = null // not finished - } - ); + }); // Assert _ = client.Worker.Received(1).EnqueueEnvelope(Arg.Any()); diff --git a/test/Sentry.Tests/SentryHttpMessageHandlerTests.cs b/test/Sentry.Tests/SentryHttpMessageHandlerTests.cs index 131a3a5c5c..1824e661d3 100644 --- a/test/Sentry.Tests/SentryHttpMessageHandlerTests.cs +++ b/test/Sentry.Tests/SentryHttpMessageHandlerTests.cs @@ -19,23 +19,21 @@ public async Task SendAsync_SentryTraceHeaderNotSet_SetsHeader() var hub = Substitute.For(); hub.GetTraceHeader().ReturnsForAnyArgs( - SentryTraceHeader.Parse("75302ac48a024bde9a3b3734a82e36c8-1000000000000000-0") - ); + SentryTraceHeader.Parse("75302ac48a024bde9a3b3734a82e36c8-1000000000000000-0")); using var innerHandler = new RecordingHttpMessageHandler(new FakeHttpMessageHandler()); using var sentryHandler = new SentryHttpMessageHandler(innerHandler, hub); using var client = new HttpClient(sentryHandler); // Act - await client.GetAsync("https://example.com/"); + await client.GetAsync("https://localhost/"); using var request = innerHandler.GetRequests().Single(); // Assert request.Headers.Should().Contain(h => h.Key == "sentry-trace" && - string.Concat(h.Value) == "75302ac48a024bde9a3b3734a82e36c8-1000000000000000-0" - ); + string.Concat(h.Value) == "75302ac48a024bde9a3b3734a82e36c8-1000000000000000-0"); } [Fact] @@ -45,8 +43,7 @@ public async Task SendAsync_SentryTraceHeaderAlreadySet_NotOverwritten() var hub = Substitute.For(); hub.GetTraceHeader().ReturnsForAnyArgs( - SentryTraceHeader.Parse("75302ac48a024bde9a3b3734a82e36c8-1000000000000000-0") - ); + SentryTraceHeader.Parse("75302ac48a024bde9a3b3734a82e36c8-1000000000000000-0")); using var innerHandler = new RecordingHttpMessageHandler(new FakeHttpMessageHandler()); using var sentryHandler = new SentryHttpMessageHandler(innerHandler, hub); @@ -55,15 +52,14 @@ public async Task SendAsync_SentryTraceHeaderAlreadySet_NotOverwritten() client.DefaultRequestHeaders.Add("sentry-trace", "foobar"); // Act - await client.GetAsync("https://example.com/"); + await client.GetAsync("https://localhost/"); using var request = innerHandler.GetRequests().Single(); // Assert request.Headers.Should().Contain(h => h.Key == "sentry-trace" && - string.Concat(h.Value) == "foobar" - ); + string.Concat(h.Value) == "foobar"); } [Fact] @@ -75,8 +71,7 @@ public async Task SendAsync_TransactionOnScope_StartsNewSpan() var transaction = new TransactionTracer( hub, "foo", - "bar" - ); + "bar"); hub.GetSpan().ReturnsForAnyArgs(transaction); @@ -85,14 +80,13 @@ public async Task SendAsync_TransactionOnScope_StartsNewSpan() using var client = new HttpClient(sentryHandler); // Act - await client.GetAsync("https://example.com/"); + await client.GetAsync("https://localhost/"); // Assert transaction.Spans.Should().Contain(span => span.Operation == "http.client" && - span.Description == "GET https://example.com/" && - span.IsFinished - ); + span.Description == "GET https://localhost/" && + span.IsFinished); } [Fact] @@ -104,8 +98,7 @@ public async Task SendAsync_ExceptionThrown_ExceptionLinkedToSpan() var transaction = new TransactionTracer( hub, "foo", - "bar" - ); + "bar"); hub.GetSpan().ReturnsForAnyArgs(transaction); @@ -116,7 +109,7 @@ public async Task SendAsync_ExceptionThrown_ExceptionLinkedToSpan() using var client = new HttpClient(sentryHandler); // Act - await Assert.ThrowsAsync(() => client.GetAsync("https://example.com/")); + await Assert.ThrowsAsync(() => client.GetAsync("https://localhost/")); // Assert hub.Received(1).BindException(exception, Arg.Any()); // second argument is an implicitly created span @@ -131,7 +124,7 @@ public async Task SendAsync_Executed_BreadcrumbCreated() hub.When(h => h.ConfigureScope(Arg.Any>())) .Do(c => c.Arg>()(scope)); - var url = "https://example.com/"; + var url = "https://localhost/"; var urlKey = "url"; var methodKey = "method"; @@ -145,24 +138,25 @@ public async Task SendAsync_Executed_BreadcrumbCreated() var expectedType = "http"; var expectedCategory = "http"; using var sentryHandler = new SentryHttpMessageHandler(hub); + sentryHandler.InnerHandler = new FakeHttpMessageHandler(); // No reason to reach the Internet here using var client = new HttpClient(sentryHandler); // Act await client.GetAsync(url); - var BreadcrumbGenerated = scope.Breadcrumbs.First(); + var breadcrumbGenerated = scope.Breadcrumbs.First(); // Assert - Assert.Equal(expectedType, BreadcrumbGenerated.Type); - Assert.Equal(expectedCategory, BreadcrumbGenerated.Category); + Assert.Equal(expectedType, breadcrumbGenerated.Type); + Assert.Equal(expectedCategory, breadcrumbGenerated.Category); - Assert.True(BreadcrumbGenerated.Data.ContainsKey(urlKey)); - Assert.Equal(expectedBreadcrumbData[urlKey], BreadcrumbGenerated.Data[urlKey]); + Assert.True(breadcrumbGenerated.Data.ContainsKey(urlKey)); + Assert.Equal(expectedBreadcrumbData[urlKey], breadcrumbGenerated.Data[urlKey]); - Assert.True(BreadcrumbGenerated.Data.ContainsKey(methodKey)); - Assert.Equal(expectedBreadcrumbData[methodKey], BreadcrumbGenerated.Data[methodKey]); + Assert.True(breadcrumbGenerated.Data.ContainsKey(methodKey)); + Assert.Equal(expectedBreadcrumbData[methodKey], breadcrumbGenerated.Data[methodKey]); - Assert.True(BreadcrumbGenerated.Data.ContainsKey(statusKey)); - Assert.Equal(expectedBreadcrumbData[statusKey], BreadcrumbGenerated.Data[statusKey]); + Assert.True(breadcrumbGenerated.Data.ContainsKey(statusKey)); + Assert.Equal(expectedBreadcrumbData[statusKey], breadcrumbGenerated.Data[statusKey]); } } } diff --git a/test/Sentry.Tests/SentrySdkTests.cs b/test/Sentry.Tests/SentrySdkTests.cs index 1d437c7a88..26e5248cc6 100644 --- a/test/Sentry.Tests/SentrySdkTests.cs +++ b/test/Sentry.Tests/SentrySdkTests.cs @@ -440,8 +440,7 @@ public void CaptureMessage_SdkInitialized_IncludesScope() .Single() .Breadcrumbs .Single() - .Message == expected) - ); + .Message == expected)); } } diff --git a/test/Sentry.Tests/SessionTests.cs b/test/Sentry.Tests/SessionTests.cs index d3dae3c47a..931093c6b9 100644 --- a/test/Sentry.Tests/SessionTests.cs +++ b/test/Sentry.Tests/SessionTests.cs @@ -19,8 +19,7 @@ public void Serialization_Session_Success() "release123", "env123", "192.168.0.1", - "Google Chrome" - ); + "Google Chrome"); session.ReportError(); session.ReportError(); @@ -31,8 +30,7 @@ public void Serialization_Session_Success() true, DateTimeOffset.Parse("2020-01-02T00:00:00+00:00", CultureInfo.InvariantCulture), 5, - SessionEndStatus.Crashed - ); + SessionEndStatus.Crashed); // Act var json = sessionUpdate.ToJsonString(); @@ -55,8 +53,7 @@ public void Serialization_Session_Success() "\"ip_address\":\"192.168.0.1\"," + "\"user_agent\":\"Google Chrome\"" + "}" + - "}" - ); + "}"); } [Fact] @@ -70,8 +67,7 @@ public void CreateUpdate_IncrementsSequenceNumber() "release123", "env123", "192.168.0.1", - "Google Chrome" - ); + "Google Chrome"); // Act var sessionUpdate1 = session.CreateUpdate(true, DateTimeOffset.Now); diff --git a/test/Sentry.Tunnel.Tests/MockHttpMessageHandler.cs b/test/Sentry.Tunnel.Tests/MockHttpMessageHandler.cs index 1d8c27af1b..2112bb050f 100644 --- a/test/Sentry.Tunnel.Tests/MockHttpMessageHandler.cs +++ b/test/Sentry.Tunnel.Tests/MockHttpMessageHandler.cs @@ -9,7 +9,7 @@ namespace Sentry.Tunnel.Tests { - public class MockHttpMessageHandler : HttpMessageHandler + public class MockHttpMessageHandler : DelegatingHandler { private readonly string _response; private readonly HttpStatusCode _statusCode;