From ce3c14f33bbba4c19caa82d82c7c2749facbc626 Mon Sep 17 00:00:00 2001 From: Alexander Dinauer Date: Tue, 2 Apr 2024 14:11:40 +0200 Subject: [PATCH] Replace `IHub` with `IScopes` in core --- sentry/src/main/java/io/sentry/Baggage.java | 4 +- .../java/io/sentry/DirectoryProcessor.java | 8 +- .../main/java/io/sentry/EnvelopeSender.java | 10 +- .../src/main/java/io/sentry/Integration.java | 4 +- .../main/java/io/sentry/MonitorConfig.java | 2 +- .../src/main/java/io/sentry/OutboxSender.java | 14 +- .../io/sentry/PreviousSessionFinalizer.java | 8 +- ...achedEnvelopeFireAndForgetIntegration.java | 20 +- .../SendFireAndForgetEnvelopeSender.java | 6 +- .../sentry/SendFireAndForgetOutboxSender.java | 6 +- .../src/main/java/io/sentry/SentryTracer.java | 85 ++-- .../main/java/io/sentry/SentryWrapper.java | 21 +- .../io/sentry/ShutdownHookIntegration.java | 6 +- sentry/src/main/java/io/sentry/Span.java | 30 +- .../java/io/sentry/SpotlightIntegration.java | 2 +- .../UncaughtExceptionHandlerIntegration.java | 12 +- .../backpressure/BackpressureMonitor.java | 11 +- .../file/FileIOSpanManager.java | 6 +- .../file/SentryFileInputStream.java | 42 +- .../file/SentryFileOutputStream.java | 44 +- .../file/SentryFileReader.java | 7 +- .../file/SentryFileWriter.java | 6 +- .../java/io/sentry/util/CheckInUtils.java | 15 +- .../java/io/sentry/util/TracingUtils.java | 18 +- ...aultTransactionPerformanceCollectorTest.kt | 8 +- .../java/io/sentry/DirectoryProcessorTest.kt | 16 +- .../test/java/io/sentry/EnvelopeSenderTest.kt | 20 +- .../src/test/java/io/sentry/HubAdapterTest.kt | 92 ++-- sentry/src/test/java/io/sentry/HubTest.kt | 430 +++++++++--------- .../test/java/io/sentry/JsonSerializerTest.kt | 8 +- .../java/io/sentry/MainEventProcessorTest.kt | 6 +- .../test/java/io/sentry/OutboxSenderTest.kt | 28 +- .../io/sentry/PreviousSessionFinalizerTest.kt | 22 +- sentry/src/test/java/io/sentry/ScopeTest.kt | 24 +- .../test/java/io/sentry/ScopesAdapterTest.kt | 265 +++++++++++ ...hedEnvelopeFireAndForgetIntegrationTest.kt | 34 +- .../test/java/io/sentry/SentryClientTest.kt | 28 +- sentry/src/test/java/io/sentry/SentryTest.kt | 112 ++--- .../test/java/io/sentry/SentryWrapperTest.kt | 32 +- .../io/sentry/ShutdownHookIntegrationTest.kt | 22 +- sentry/src/test/java/io/sentry/SpanTest.kt | 24 +- .../sentry/TraceContextSerializationTest.kt | 6 +- ...UncaughtExceptionHandlerIntegrationTest.kt | 62 +-- .../backpressure/BackpressureMonitorTest.kt | 12 +- .../sentry/clientreport/ClientReportTest.kt | 8 +- .../file/FileIOSpanManagerTest.kt | 14 +- .../file/SentryFileInputStreamTest.kt | 22 +- .../file/SentryFileOutputStreamTest.kt | 12 +- .../file/SentryFileReaderTest.kt | 12 +- .../file/SentryFileWriterTest.kt | 12 +- .../internal/SpotlightIntegrationTest.kt | 10 +- .../java/io/sentry/protocol/SentrySpanTest.kt | 4 +- .../io/sentry/transport/RateLimiterTest.kt | 32 +- .../java/io/sentry/util/CheckInUtilsTest.kt | 91 ++-- .../java/io/sentry/util/TracingUtilsTest.kt | 30 +- 55 files changed, 1092 insertions(+), 793 deletions(-) create mode 100644 sentry/src/test/java/io/sentry/ScopesAdapterTest.kt diff --git a/sentry/src/main/java/io/sentry/Baggage.java b/sentry/src/main/java/io/sentry/Baggage.java index 8e19fceaf8..4a637bacdf 100644 --- a/sentry/src/main/java/io/sentry/Baggage.java +++ b/sentry/src/main/java/io/sentry/Baggage.java @@ -39,13 +39,13 @@ public final class Baggage { @NotNull public static Baggage fromHeader(final @Nullable String headerValue) { return Baggage.fromHeader( - headerValue, false, HubAdapter.getInstance().getOptions().getLogger()); + headerValue, false, ScopesAdapter.getInstance().getOptions().getLogger()); } @NotNull public static Baggage fromHeader(final @Nullable List headerValues) { return Baggage.fromHeader( - headerValues, false, HubAdapter.getInstance().getOptions().getLogger()); + headerValues, false, ScopesAdapter.getInstance().getOptions().getLogger()); } @ApiStatus.Internal diff --git a/sentry/src/main/java/io/sentry/DirectoryProcessor.java b/sentry/src/main/java/io/sentry/DirectoryProcessor.java index 5d60feba60..a6bb258f30 100644 --- a/sentry/src/main/java/io/sentry/DirectoryProcessor.java +++ b/sentry/src/main/java/io/sentry/DirectoryProcessor.java @@ -19,17 +19,17 @@ abstract class DirectoryProcessor { private static final long ENVELOPE_PROCESSING_DELAY = 100L; - private final @NotNull IHub hub; + private final @NotNull IScopes scopes; private final @NotNull ILogger logger; private final long flushTimeoutMillis; private final Queue processedEnvelopes; DirectoryProcessor( - final @NotNull IHub hub, + final @NotNull IScopes scopes, final @NotNull ILogger logger, final long flushTimeoutMillis, final int maxQueueSize) { - this.hub = hub; + this.scopes = scopes; this.logger = logger; this.flushTimeoutMillis = flushTimeoutMillis; this.processedEnvelopes = @@ -86,7 +86,7 @@ public void processDirectory(final @NotNull File directory) { } // in case there's rate limiting active, skip processing - final @Nullable RateLimiter rateLimiter = hub.getRateLimiter(); + final @Nullable RateLimiter rateLimiter = scopes.getRateLimiter(); if (rateLimiter != null && rateLimiter.isActiveForCategory(DataCategory.All)) { logger.log(SentryLevel.INFO, "DirectoryProcessor, rate limiting active."); return; diff --git a/sentry/src/main/java/io/sentry/EnvelopeSender.java b/sentry/src/main/java/io/sentry/EnvelopeSender.java index 598caad280..3a157f59d3 100644 --- a/sentry/src/main/java/io/sentry/EnvelopeSender.java +++ b/sentry/src/main/java/io/sentry/EnvelopeSender.java @@ -17,18 +17,18 @@ @ApiStatus.Internal public final class EnvelopeSender extends DirectoryProcessor implements IEnvelopeSender { - private final @NotNull IHub hub; + private final @NotNull IScopes scopes; private final @NotNull ISerializer serializer; private final @NotNull ILogger logger; public EnvelopeSender( - final @NotNull IHub hub, + final @NotNull IScopes scopes, final @NotNull ISerializer serializer, final @NotNull ILogger logger, final long flushTimeoutMillis, final int maxQueueSize) { - super(hub, logger, flushTimeoutMillis, maxQueueSize); - this.hub = Objects.requireNonNull(hub, "Hub is required."); + super(scopes, logger, flushTimeoutMillis, maxQueueSize); + this.scopes = Objects.requireNonNull(scopes, "Hub is required."); this.serializer = Objects.requireNonNull(serializer, "Serializer is required."); this.logger = Objects.requireNonNull(logger, "Logger is required."); } @@ -60,7 +60,7 @@ protected void processFile(final @NotNull File file, final @NotNull Hint hint) { logger.log( SentryLevel.ERROR, "Failed to deserialize cached envelope %s", file.getAbsolutePath()); } else { - hub.captureEnvelope(envelope, hint); + scopes.captureEnvelope(envelope, hint); } HintUtils.runIfHasTypeLogIfNot( diff --git a/sentry/src/main/java/io/sentry/Integration.java b/sentry/src/main/java/io/sentry/Integration.java index 54b17e4d51..1b1a520473 100644 --- a/sentry/src/main/java/io/sentry/Integration.java +++ b/sentry/src/main/java/io/sentry/Integration.java @@ -10,8 +10,8 @@ public interface Integration { /** * Registers an integration * - * @param hub the Hub + * @param scopes the Scopes * @param options the options */ - void register(@NotNull IHub hub, @NotNull SentryOptions options); + void register(@NotNull IScopes scopes, @NotNull SentryOptions options); } diff --git a/sentry/src/main/java/io/sentry/MonitorConfig.java b/sentry/src/main/java/io/sentry/MonitorConfig.java index d954a50466..763e3b65a4 100644 --- a/sentry/src/main/java/io/sentry/MonitorConfig.java +++ b/sentry/src/main/java/io/sentry/MonitorConfig.java @@ -21,7 +21,7 @@ public final class MonitorConfig implements JsonUnknown, JsonSerializable { public MonitorConfig(final @NotNull MonitorSchedule schedule) { this.schedule = schedule; - final SentryOptions.Cron defaultCron = HubAdapter.getInstance().getOptions().getCron(); + final SentryOptions.Cron defaultCron = ScopesAdapter.getInstance().getOptions().getCron(); if (defaultCron != null) { this.checkinMargin = defaultCron.getDefaultCheckinMargin(); this.maxRuntime = defaultCron.getDefaultMaxRuntime(); diff --git a/sentry/src/main/java/io/sentry/OutboxSender.java b/sentry/src/main/java/io/sentry/OutboxSender.java index 709cbb8580..f80bf030c8 100644 --- a/sentry/src/main/java/io/sentry/OutboxSender.java +++ b/sentry/src/main/java/io/sentry/OutboxSender.java @@ -36,20 +36,20 @@ public final class OutboxSender extends DirectoryProcessor implements IEnvelopeS @SuppressWarnings("CharsetObjectCanBeUsed") private static final Charset UTF_8 = Charset.forName("UTF-8"); - private final @NotNull IHub hub; + private final @NotNull IScopes scopes; private final @NotNull IEnvelopeReader envelopeReader; private final @NotNull ISerializer serializer; private final @NotNull ILogger logger; public OutboxSender( - final @NotNull IHub hub, + final @NotNull IScopes scopes, final @NotNull IEnvelopeReader envelopeReader, final @NotNull ISerializer serializer, final @NotNull ILogger logger, final long flushTimeoutMillis, final int maxQueueSize) { - super(hub, logger, flushTimeoutMillis, maxQueueSize); - this.hub = Objects.requireNonNull(hub, "Hub is required."); + super(scopes, logger, flushTimeoutMillis, maxQueueSize); + this.scopes = Objects.requireNonNull(scopes, "Hub is required."); this.envelopeReader = Objects.requireNonNull(envelopeReader, "Envelope reader is required."); this.serializer = Objects.requireNonNull(serializer, "Serializer is required."); this.logger = Objects.requireNonNull(logger, "Logger is required."); @@ -144,7 +144,7 @@ private void processEnvelope(final @NotNull SentryEnvelope envelope, final @NotN logUnexpectedEventId(envelope, event.getEventId(), currentItem); continue; } - hub.captureEvent(event, hint); + scopes.captureEvent(event, hint); logItemCaptured(currentItem); if (!waitFlush(hint)) { @@ -181,7 +181,7 @@ private void processEnvelope(final @NotNull SentryEnvelope envelope, final @NotN .getTrace() .setSamplingDecision(extractSamplingDecision(traceContext)); } - hub.captureTransaction(transaction, traceContext, hint); + scopes.captureTransaction(transaction, traceContext, hint); logItemCaptured(currentItem); if (!waitFlush(hint)) { @@ -197,7 +197,7 @@ private void processEnvelope(final @NotNull SentryEnvelope envelope, final @NotN final SentryEnvelope newEnvelope = new SentryEnvelope( envelope.getHeader().getEventId(), envelope.getHeader().getSdkVersion(), item); - hub.captureEnvelope(newEnvelope, hint); + scopes.captureEnvelope(newEnvelope, hint); logger.log( SentryLevel.DEBUG, "%s item %d is being captured.", diff --git a/sentry/src/main/java/io/sentry/PreviousSessionFinalizer.java b/sentry/src/main/java/io/sentry/PreviousSessionFinalizer.java index 458c6532ba..bda2a14477 100644 --- a/sentry/src/main/java/io/sentry/PreviousSessionFinalizer.java +++ b/sentry/src/main/java/io/sentry/PreviousSessionFinalizer.java @@ -33,11 +33,11 @@ final class PreviousSessionFinalizer implements Runnable { private final @NotNull SentryOptions options; - private final @NotNull IHub hub; + private final @NotNull IScopes scopes; - PreviousSessionFinalizer(final @NotNull SentryOptions options, final @NotNull IHub hub) { + PreviousSessionFinalizer(final @NotNull SentryOptions options, final @NotNull IScopes scopes) { this.options = options; - this.hub = hub; + this.scopes = scopes; } @Override @@ -116,7 +116,7 @@ public void run() { // SdkVersion will be outdated. final SentryEnvelope fromSession = SentryEnvelope.from(serializer, session, options.getSdkVersion()); - hub.captureEnvelope(fromSession); + scopes.captureEnvelope(fromSession); } } catch (Throwable e) { options.getLogger().log(SentryLevel.ERROR, "Error processing previous session.", e); diff --git a/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java b/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java index bc813fdd1e..2160d1607e 100644 --- a/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java +++ b/sentry/src/main/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegration.java @@ -18,7 +18,7 @@ public final class SendCachedEnvelopeFireAndForgetIntegration private final @NotNull SendFireAndForgetFactory factory; private @Nullable IConnectionStatusProvider connectionStatusProvider; - private @Nullable IHub hub; + private @Nullable IScopes scopes; private @Nullable SentryOptions options; private @Nullable SendFireAndForget sender; private final AtomicBoolean isInitialized = new AtomicBoolean(false); @@ -35,7 +35,7 @@ public interface SendFireAndForgetDirPath { public interface SendFireAndForgetFactory { @Nullable - SendFireAndForget create(@NotNull IHub hub, @NotNull SentryOptions options); + SendFireAndForget create(@NotNull IScopes scopes, @NotNull SentryOptions options); default boolean hasValidPath(final @Nullable String dirPath, final @NotNull ILogger logger) { if (dirPath == null || dirPath.isEmpty()) { @@ -66,8 +66,8 @@ public SendCachedEnvelopeFireAndForgetIntegration( } @Override - public void register(final @NotNull IHub hub, final @NotNull SentryOptions options) { - this.hub = Objects.requireNonNull(hub, "Hub is required"); + public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions options) { + this.scopes = Objects.requireNonNull(scopes, "Hub is required"); this.options = Objects.requireNonNull(options, "SentryOptions is required"); final String cachedDir = options.getCacheDirPath(); @@ -81,7 +81,7 @@ public void register(final @NotNull IHub hub, final @NotNull SentryOptions optio .log(SentryLevel.DEBUG, "SendCachedEventFireAndForgetIntegration installed."); addIntegrationToSdkVersion(getClass()); - sendCachedEnvelopes(hub, options); + sendCachedEnvelopes(scopes, options); } @Override @@ -95,14 +95,14 @@ public void close() throws IOException { @Override public void onConnectionStatusChanged( final @NotNull IConnectionStatusProvider.ConnectionStatus status) { - if (hub != null && options != null) { - sendCachedEnvelopes(hub, options); + if (scopes != null && options != null) { + sendCachedEnvelopes(scopes, options); } } @SuppressWarnings({"FutureReturnValueIgnored", "NullAway"}) private synchronized void sendCachedEnvelopes( - final @NotNull IHub hub, final @NotNull SentryOptions options) { + final @NotNull IScopes scopes, final @NotNull SentryOptions options) { try { options .getExecutorService() @@ -122,7 +122,7 @@ private synchronized void sendCachedEnvelopes( connectionStatusProvider = options.getConnectionStatusProvider(); connectionStatusProvider.addConnectionStatusObserver(this); - sender = factory.create(hub, options); + sender = factory.create(scopes, options); } // skip run only if we're certainly disconnected @@ -138,7 +138,7 @@ private synchronized void sendCachedEnvelopes( } // in case there's rate limiting active, skip processing - final @Nullable RateLimiter rateLimiter = hub.getRateLimiter(); + final @Nullable RateLimiter rateLimiter = scopes.getRateLimiter(); if (rateLimiter != null && rateLimiter.isActiveForCategory(DataCategory.All)) { options .getLogger() diff --git a/sentry/src/main/java/io/sentry/SendFireAndForgetEnvelopeSender.java b/sentry/src/main/java/io/sentry/SendFireAndForgetEnvelopeSender.java index e44d18a8d6..155946b95a 100644 --- a/sentry/src/main/java/io/sentry/SendFireAndForgetEnvelopeSender.java +++ b/sentry/src/main/java/io/sentry/SendFireAndForgetEnvelopeSender.java @@ -21,8 +21,8 @@ public SendFireAndForgetEnvelopeSender( @Override public @Nullable SendCachedEnvelopeFireAndForgetIntegration.SendFireAndForget create( - final @NotNull IHub hub, final @NotNull SentryOptions options) { - Objects.requireNonNull(hub, "Hub is required"); + final @NotNull IScopes scopes, final @NotNull SentryOptions options) { + Objects.requireNonNull(scopes, "Hub is required"); Objects.requireNonNull(options, "SentryOptions is required"); final String dirPath = sendFireAndForgetDirPath.getDirPath(); @@ -33,7 +33,7 @@ public SendFireAndForgetEnvelopeSender( final EnvelopeSender envelopeSender = new EnvelopeSender( - hub, + scopes, options.getSerializer(), options.getLogger(), options.getFlushTimeoutMillis(), diff --git a/sentry/src/main/java/io/sentry/SendFireAndForgetOutboxSender.java b/sentry/src/main/java/io/sentry/SendFireAndForgetOutboxSender.java index fda41610fd..e7913b5b2f 100644 --- a/sentry/src/main/java/io/sentry/SendFireAndForgetOutboxSender.java +++ b/sentry/src/main/java/io/sentry/SendFireAndForgetOutboxSender.java @@ -21,8 +21,8 @@ public SendFireAndForgetOutboxSender( @Override public @Nullable SendCachedEnvelopeFireAndForgetIntegration.SendFireAndForget create( - final @NotNull IHub hub, final @NotNull SentryOptions options) { - Objects.requireNonNull(hub, "Hub is required"); + final @NotNull IScopes scopes, final @NotNull SentryOptions options) { + Objects.requireNonNull(scopes, "Hub is required"); Objects.requireNonNull(options, "SentryOptions is required"); final String dirPath = sendFireAndForgetDirPath.getDirPath(); @@ -33,7 +33,7 @@ public SendFireAndForgetOutboxSender( final OutboxSender outboxSender = new OutboxSender( - hub, + scopes, options.getEnvelopeReader(), options.getSerializer(), options.getLogger(), diff --git a/sentry/src/main/java/io/sentry/SentryTracer.java b/sentry/src/main/java/io/sentry/SentryTracer.java index bc3b5eb531..7d82bbbc4a 100644 --- a/sentry/src/main/java/io/sentry/SentryTracer.java +++ b/sentry/src/main/java/io/sentry/SentryTracer.java @@ -26,7 +26,7 @@ public final class SentryTracer implements ITransaction { private final @NotNull SentryId eventId = new SentryId(); private final @NotNull Span root; private final @NotNull List children = new CopyOnWriteArrayList<>(); - private final @NotNull IHub hub; + private final @NotNull IScopes scopes; private @NotNull String name; /** @@ -52,31 +52,31 @@ public final class SentryTracer implements ITransaction { private final @Nullable TransactionPerformanceCollector transactionPerformanceCollector; private final @NotNull TransactionOptions transactionOptions; - public SentryTracer(final @NotNull TransactionContext context, final @NotNull IHub hub) { - this(context, hub, new TransactionOptions(), null); + public SentryTracer(final @NotNull TransactionContext context, final @NotNull IScopes scopes) { + this(context, scopes, new TransactionOptions(), null); } public SentryTracer( final @NotNull TransactionContext context, - final @NotNull IHub hub, + final @NotNull IScopes scopes, final @NotNull TransactionOptions transactionOptions) { - this(context, hub, transactionOptions, null); + this(context, scopes, transactionOptions, null); } SentryTracer( final @NotNull TransactionContext context, - final @NotNull IHub hub, + final @NotNull IScopes scopes, final @NotNull TransactionOptions transactionOptions, final @Nullable TransactionPerformanceCollector transactionPerformanceCollector) { Objects.requireNonNull(context, "context is required"); - Objects.requireNonNull(hub, "hub is required"); + Objects.requireNonNull(scopes, "scopes are required"); this.root = - new Span(context, this, hub, transactionOptions.getStartTimestamp(), transactionOptions); + new Span(context, this, scopes, transactionOptions.getStartTimestamp(), transactionOptions); this.name = context.getName(); this.instrumenter = context.getInstrumenter(); - this.hub = hub; + this.scopes = scopes; this.transactionPerformanceCollector = transactionPerformanceCollector; this.transactionNameSource = context.getTransactionNameSource(); this.transactionOptions = transactionOptions; @@ -84,7 +84,7 @@ public SentryTracer( if (context.getBaggage() != null) { this.baggage = context.getBaggage(); } else { - this.baggage = new Baggage(hub.getOptions().getLogger()); + this.baggage = new Baggage(scopes.getOptions().getLogger()); } // We are currently sending the performance data only in profiles, so there's no point in @@ -122,7 +122,8 @@ public void run() { try { timer.schedule(idleTimeoutTask, idleTimeout); } catch (Throwable e) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log(SentryLevel.WARNING, "Failed to schedule finish timer", e); // if we failed to schedule the finish timer for some reason, we finish it here right @@ -156,7 +157,7 @@ private void onDeadlineTimeoutReached() { return; } - final @NotNull SentryDate finishTimestamp = hub.getOptions().getDateProvider().now(); + final @NotNull SentryDate finishTimestamp = scopes.getOptions().getDateProvider().now(); // abort all child-spans first, this ensures the transaction can be finished, // even if waitForChildren is true @@ -186,7 +187,7 @@ public void finish( // if it's not set -> fallback to the current time if (finishTimestamp == null) { - finishTimestamp = hub.getOptions().getDateProvider().now(); + finishTimestamp = scopes.getOptions().getDateProvider().now(); } // auto-finish any idle spans first @@ -207,9 +208,10 @@ public void finish( ProfilingTraceData profilingTraceData = null; if (Boolean.TRUE.equals(isSampled()) && Boolean.TRUE.equals(isProfileSampled())) { profilingTraceData = - hub.getOptions() + scopes + .getOptions() .getTransactionProfiler() - .onTransactionFinish(this, performanceCollectionData, hub.getOptions()); + .onTransactionFinish(this, performanceCollectionData, scopes.getOptions()); } if (performanceCollectionData != null) { performanceCollectionData.clear(); @@ -222,7 +224,7 @@ public void finish( root.finish(finishStatus.spanStatus, finishTimestamp); - hub.configureScope( + scopes.configureScope( scope -> { scope.withTransaction( transaction -> { @@ -251,7 +253,8 @@ public void finish( if (dropIfNoChildren && children.isEmpty() && transactionOptions.getIdleTimeout() != null) { // if it's an idle transaction which has no children, we drop it to save user's quota - hub.getOptions() + scopes + .getOptions() .getLogger() .log( SentryLevel.DEBUG, @@ -261,7 +264,7 @@ public void finish( } transaction.getMeasurements().putAll(root.getMeasurements()); - hub.captureTransaction(transaction, traceContext(), hint, profilingTraceData); + scopes.captureTransaction(transaction, traceContext(), hint, profilingTraceData); } } @@ -292,7 +295,8 @@ public void run() { try { timer.schedule(deadlineTimeoutTask, deadlineTimeOut); } catch (Throwable e) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log(SentryLevel.WARNING, "Failed to schedule finish timer", e); // if we failed to schedule the finish timer for some reason, we finish it here right @@ -418,7 +422,7 @@ private ISpan createChild( return NoOpSpan.getInstance(); } - if (children.size() < hub.getOptions().getMaxSpans()) { + if (children.size() < scopes.getOptions().getMaxSpans()) { Objects.requireNonNull(parentSpanId, "parentSpanId is required"); Objects.requireNonNull(operation, "operation is required"); cancelIdleTimer(); @@ -428,7 +432,7 @@ private ISpan createChild( parentSpanId, this, operation, - this.hub, + this.scopes, timestamp, spanOptions, finishingSpan -> { @@ -451,7 +455,7 @@ private ISpan createChild( span.setData(SpanDataConvention.THREAD_ID, String.valueOf(Thread.currentThread().getId())); span.setData( SpanDataConvention.THREAD_NAME, - hub.getOptions().getMainThreadChecker().isMainThread() + scopes.getOptions().getMainThreadChecker().isMainThread() ? "main" : Thread.currentThread().getName()); this.children.add(span); @@ -460,7 +464,8 @@ private ISpan createChild( } return span; } else { - hub.getOptions() + scopes + .getOptions() .getLogger() .log( SentryLevel.WARNING, @@ -529,10 +534,11 @@ private ISpan createChild( return NoOpSpan.getInstance(); } - if (children.size() < hub.getOptions().getMaxSpans()) { + if (children.size() < scopes.getOptions().getMaxSpans()) { return root.startChild(operation, description, timestamp, instrumenter, spanOptions); } else { - hub.getOptions() + scopes + .getOptions() .getLogger() .log( SentryLevel.WARNING, @@ -567,7 +573,7 @@ public void finish(@Nullable SpanStatus status, @Nullable SentryDate finishDate) @Override public @Nullable TraceContext traceContext() { - if (hub.getOptions().isTraceSampling()) { + if (scopes.getOptions().isTraceSampling()) { updateBaggageValues(); return baggage.toTraceContext(); } else { @@ -579,12 +585,12 @@ private void updateBaggageValues() { synchronized (this) { if (baggage.isMutable()) { final AtomicReference userAtomicReference = new AtomicReference<>(); - hub.configureScope( + scopes.configureScope( scope -> { userAtomicReference.set(scope.getUser()); }); baggage.setValuesFromTransaction( - this, userAtomicReference.get(), hub.getOptions(), this.getSamplingDecision()); + this, userAtomicReference.get(), scopes.getOptions(), this.getSamplingDecision()); baggage.freeze(); } } @@ -592,7 +598,7 @@ private void updateBaggageValues() { @Override public @Nullable BaggageHeader toBaggageHeader(@Nullable List thirdPartyBaggageHeaders) { - if (hub.getOptions().isTraceSampling()) { + if (scopes.getOptions().isTraceSampling()) { updateBaggageValues(); return BaggageHeader.fromBaggageAndOutgoingHeader(baggage, thirdPartyBaggageHeaders); @@ -616,7 +622,8 @@ private boolean hasAllChildrenFinished() { @Override public void setOperation(final @NotNull String operation) { if (root.isFinished()) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log( SentryLevel.DEBUG, @@ -636,7 +643,8 @@ public void setOperation(final @NotNull String operation) { @Override public void setDescription(final @Nullable String description) { if (root.isFinished()) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log( SentryLevel.DEBUG, @@ -656,7 +664,8 @@ public void setDescription(final @Nullable String description) { @Override public void setStatus(final @Nullable SpanStatus status) { if (root.isFinished()) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log( SentryLevel.DEBUG, @@ -676,7 +685,8 @@ public void setStatus(final @Nullable SpanStatus status) { @Override public void setThrowable(final @Nullable Throwable throwable) { if (root.isFinished()) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log(SentryLevel.DEBUG, "The transaction is already finished. Throwable cannot be set"); return; @@ -698,7 +708,8 @@ public void setThrowable(final @Nullable Throwable throwable) { @Override public void setTag(final @NotNull String key, final @NotNull String value) { if (root.isFinished()) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log(SentryLevel.DEBUG, "The transaction is already finished. Tag %s cannot be set", key); return; @@ -720,7 +731,8 @@ public boolean isFinished() { @Override public void setData(@NotNull String key, @NotNull Object value) { if (root.isFinished()) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log( SentryLevel.DEBUG, "The transaction is already finished. Data %s cannot be set", key); @@ -795,7 +807,8 @@ public void setName(@NotNull String name) { @Override public void setName(@NotNull String name, @NotNull TransactionNameSource transactionNameSource) { if (root.isFinished()) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log( SentryLevel.DEBUG, diff --git a/sentry/src/main/java/io/sentry/SentryWrapper.java b/sentry/src/main/java/io/sentry/SentryWrapper.java index 1a39adee99..165ace7c83 100644 --- a/sentry/src/main/java/io/sentry/SentryWrapper.java +++ b/sentry/src/main/java/io/sentry/SentryWrapper.java @@ -27,16 +27,18 @@ public final class SentryWrapper { * @return the wrapped {@link Callable} * @param - the result type of the {@link Callable} */ + @SuppressWarnings("deprecation") public static Callable wrapCallable(final @NotNull Callable callable) { - final IHub newHub = Sentry.getCurrentHub().clone(); + // TODO replace with forking + final IScopes newHub = Sentry.getCurrentScopes().clone(); return () -> { - final IHub oldState = Sentry.getCurrentHub(); - Sentry.setCurrentHub(newHub); + final IScopes oldState = Sentry.getCurrentScopes(); + Sentry.setCurrentScopes(newHub); try { return callable.call(); } finally { - Sentry.setCurrentHub(oldState); + Sentry.setCurrentScopes(oldState); } }; } @@ -51,17 +53,18 @@ public static Callable wrapCallable(final @NotNull Callable callable) * @return the wrapped {@link Supplier} * @param - the result type of the {@link Supplier} */ + @SuppressWarnings("deprecation") public static Supplier wrapSupplier(final @NotNull Supplier supplier) { - - final IHub newHub = Sentry.getCurrentHub().clone(); + // TODO replace with forking + final IScopes newHub = Sentry.getCurrentScopes().clone(); return () -> { - final IHub oldState = Sentry.getCurrentHub(); - Sentry.setCurrentHub(newHub); + final IScopes oldState = Sentry.getCurrentScopes(); + Sentry.setCurrentScopes(newHub); try { return supplier.get(); } finally { - Sentry.setCurrentHub(oldState); + Sentry.setCurrentScopes(oldState); } }; } diff --git a/sentry/src/main/java/io/sentry/ShutdownHookIntegration.java b/sentry/src/main/java/io/sentry/ShutdownHookIntegration.java index b144f2d88a..d957a87ccf 100644 --- a/sentry/src/main/java/io/sentry/ShutdownHookIntegration.java +++ b/sentry/src/main/java/io/sentry/ShutdownHookIntegration.java @@ -27,12 +27,12 @@ public ShutdownHookIntegration() { } @Override - public void register(final @NotNull IHub hub, final @NotNull SentryOptions options) { - Objects.requireNonNull(hub, "Hub is required"); + public void register(final @NotNull IScopes scopes, final @NotNull SentryOptions options) { + Objects.requireNonNull(scopes, "Scopes are required"); Objects.requireNonNull(options, "SentryOptions is required"); if (options.isEnableShutdownHook()) { - thread = new Thread(() -> hub.flush(options.getFlushTimeoutMillis())); + thread = new Thread(() -> scopes.flush(options.getFlushTimeoutMillis())); runtime.addShutdownHook(thread); options.getLogger().log(SentryLevel.DEBUG, "ShutdownHookIntegration installed."); addIntegrationToSdkVersion(getClass()); diff --git a/sentry/src/main/java/io/sentry/Span.java b/sentry/src/main/java/io/sentry/Span.java index 850276dac3..1c9d180b29 100644 --- a/sentry/src/main/java/io/sentry/Span.java +++ b/sentry/src/main/java/io/sentry/Span.java @@ -35,7 +35,7 @@ public final class Span implements ISpan { /** A throwable thrown during the execution of the span. */ private @Nullable Throwable throwable; - private final @NotNull IHub hub; + private final @NotNull IScopes scopes; private final @NotNull AtomicBoolean finished = new AtomicBoolean(false); @@ -55,8 +55,8 @@ public final class Span implements ISpan { final @Nullable SpanId parentSpanId, final @NotNull SentryTracer transaction, final @NotNull String operation, - final @NotNull IHub hub) { - this(traceId, parentSpanId, transaction, operation, hub, null, new SpanOptions(), null); + final @NotNull IScopes scopes) { + this(traceId, parentSpanId, transaction, operation, scopes, null, new SpanOptions(), null); } Span( @@ -64,7 +64,7 @@ public final class Span implements ISpan { final @Nullable SpanId parentSpanId, final @NotNull SentryTracer transaction, final @NotNull String operation, - final @NotNull IHub hub, + final @NotNull IScopes scopes, final @Nullable SentryDate startTimestamp, final @NotNull SpanOptions options, final @Nullable SpanFinishedCallback spanFinishedCallback) { @@ -72,30 +72,30 @@ public final class Span implements ISpan { new SpanContext( traceId, new SpanId(), operation, parentSpanId, transaction.getSamplingDecision()); this.transaction = Objects.requireNonNull(transaction, "transaction is required"); - this.hub = Objects.requireNonNull(hub, "hub is required"); + this.scopes = Objects.requireNonNull(scopes, "Scopes are required"); this.options = options; this.spanFinishedCallback = spanFinishedCallback; if (startTimestamp != null) { this.startTimestamp = startTimestamp; } else { - this.startTimestamp = hub.getOptions().getDateProvider().now(); + this.startTimestamp = scopes.getOptions().getDateProvider().now(); } } public Span( final @NotNull TransactionContext context, final @NotNull SentryTracer sentryTracer, - final @NotNull IHub hub, + final @NotNull IScopes scopes, final @Nullable SentryDate startTimestamp, final @NotNull SpanOptions options) { this.context = Objects.requireNonNull(context, "context is required"); this.transaction = Objects.requireNonNull(sentryTracer, "sentryTracer is required"); - this.hub = Objects.requireNonNull(hub, "hub is required"); + this.scopes = Objects.requireNonNull(scopes, "scopes are required"); this.spanFinishedCallback = null; if (startTimestamp != null) { this.startTimestamp = startTimestamp; } else { - this.startTimestamp = hub.getOptions().getDateProvider().now(); + this.startTimestamp = scopes.getOptions().getDateProvider().now(); } this.options = options; } @@ -180,7 +180,7 @@ public void finish() { @Override public void finish(@Nullable SpanStatus status) { - finish(status, hub.getOptions().getDateProvider().now()); + finish(status, scopes.getOptions().getDateProvider().now()); } /** @@ -197,7 +197,7 @@ public void finish(final @Nullable SpanStatus status, final @Nullable SentryDate } this.context.setStatus(status); - this.timestamp = timestamp == null ? hub.getOptions().getDateProvider().now() : timestamp; + this.timestamp = timestamp == null ? scopes.getOptions().getDateProvider().now() : timestamp; if (options.isTrimStart() || options.isTrimEnd()) { @Nullable SentryDate minChildStart = null; @Nullable SentryDate maxChildEnd = null; @@ -230,7 +230,7 @@ public void finish(final @Nullable SpanStatus status, final @Nullable SentryDate } if (throwable != null) { - hub.setSpanContext(throwable, this, this.transaction.getName()); + scopes.setSpanContext(throwable, this, this.transaction.getName()); } if (spanFinishedCallback != null) { spanFinishedCallback.execute(this); @@ -343,7 +343,8 @@ public void setData(final @NotNull String key, final @NotNull Object value) { @Override public void setMeasurement(final @NotNull String name, final @NotNull Number value) { if (isFinished()) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log( SentryLevel.DEBUG, @@ -365,7 +366,8 @@ public void setMeasurement( final @NotNull Number value, final @NotNull MeasurementUnit unit) { if (isFinished()) { - hub.getOptions() + scopes + .getOptions() .getLogger() .log( SentryLevel.DEBUG, diff --git a/sentry/src/main/java/io/sentry/SpotlightIntegration.java b/sentry/src/main/java/io/sentry/SpotlightIntegration.java index 6d488bcbce..0b69ae79be 100644 --- a/sentry/src/main/java/io/sentry/SpotlightIntegration.java +++ b/sentry/src/main/java/io/sentry/SpotlightIntegration.java @@ -26,7 +26,7 @@ public final class SpotlightIntegration private @NotNull ISentryExecutorService executorService = NoOpSentryExecutorService.getInstance(); @Override - public void register(@NotNull IHub hub, @NotNull SentryOptions options) { + public void register(@NotNull IScopes scopes, @NotNull SentryOptions options) { this.options = options; this.logger = options.getLogger(); diff --git a/sentry/src/main/java/io/sentry/UncaughtExceptionHandlerIntegration.java b/sentry/src/main/java/io/sentry/UncaughtExceptionHandlerIntegration.java index 33e1a4a815..47ceaa084e 100644 --- a/sentry/src/main/java/io/sentry/UncaughtExceptionHandlerIntegration.java +++ b/sentry/src/main/java/io/sentry/UncaughtExceptionHandlerIntegration.java @@ -28,7 +28,7 @@ public final class UncaughtExceptionHandlerIntegration /** Reference to the pre-existing uncaught exception handler. */ private @Nullable Thread.UncaughtExceptionHandler defaultExceptionHandler; - private @Nullable IHub hub; + private @Nullable IScopes scopes; private @Nullable SentryOptions options; private boolean registered = false; @@ -43,7 +43,7 @@ public UncaughtExceptionHandlerIntegration() { } @Override - public final void register(final @NotNull IHub hub, final @NotNull SentryOptions options) { + public final void register(final @NotNull IScopes scopes, final @NotNull SentryOptions options) { if (registered) { options .getLogger() @@ -54,7 +54,7 @@ public final void register(final @NotNull IHub hub, final @NotNull SentryOptions } registered = true; - this.hub = Objects.requireNonNull(hub, "Hub is required"); + this.scopes = Objects.requireNonNull(scopes, "Hub is required"); this.options = Objects.requireNonNull(options, "SentryOptions is required"); this.options @@ -89,7 +89,7 @@ public final void register(final @NotNull IHub hub, final @NotNull SentryOptions @Override public void uncaughtException(Thread thread, Throwable thrown) { - if (options != null && hub != null) { + if (options != null && scopes != null) { options.getLogger().log(SentryLevel.INFO, "Uncaught exception received."); try { @@ -99,14 +99,14 @@ public void uncaughtException(Thread thread, Throwable thrown) { final SentryEvent event = new SentryEvent(throwable); event.setLevel(SentryLevel.FATAL); - final ITransaction transaction = hub.getTransaction(); + final ITransaction transaction = scopes.getTransaction(); if (transaction == null && event.getEventId() != null) { // if there's no active transaction on scope, this event can trigger flush notification exceptionHint.setFlushable(event.getEventId()); } final Hint hint = HintUtils.createWithTypeCheckHint(exceptionHint); - final @NotNull SentryId sentryId = hub.captureEvent(event, hint); + final @NotNull SentryId sentryId = scopes.captureEvent(event, hint); final boolean isEventDropped = sentryId.equals(SentryId.EMPTY_ID); final EventDropReason eventDropReason = HintUtils.getEventDropReason(hint); // in case the event has been dropped by multithreaded deduplicator, the other threads will diff --git a/sentry/src/main/java/io/sentry/backpressure/BackpressureMonitor.java b/sentry/src/main/java/io/sentry/backpressure/BackpressureMonitor.java index 2008a38c76..6541a7586a 100644 --- a/sentry/src/main/java/io/sentry/backpressure/BackpressureMonitor.java +++ b/sentry/src/main/java/io/sentry/backpressure/BackpressureMonitor.java @@ -1,6 +1,6 @@ package io.sentry.backpressure; -import io.sentry.IHub; +import io.sentry.IScopes; import io.sentry.ISentryExecutorService; import io.sentry.SentryLevel; import io.sentry.SentryOptions; @@ -12,12 +12,13 @@ public final class BackpressureMonitor implements IBackpressureMonitor, Runnable private static final int CHECK_INTERVAL_IN_MS = 10 * 1000; private final @NotNull SentryOptions sentryOptions; - private final @NotNull IHub hub; + private final @NotNull IScopes scopes; private int downsampleFactor = 0; - public BackpressureMonitor(final @NotNull SentryOptions sentryOptions, final @NotNull IHub hub) { + public BackpressureMonitor( + final @NotNull SentryOptions sentryOptions, final @NotNull IScopes scopes) { this.sentryOptions = sentryOptions; - this.hub = hub; + this.scopes = scopes; } @Override @@ -66,6 +67,6 @@ private void reschedule(final int delay) { } private boolean isHealthy() { - return hub.isHealthy(); + return scopes.isHealthy(); } } diff --git a/sentry/src/main/java/io/sentry/instrumentation/file/FileIOSpanManager.java b/sentry/src/main/java/io/sentry/instrumentation/file/FileIOSpanManager.java index 956996ce04..52963413b6 100644 --- a/sentry/src/main/java/io/sentry/instrumentation/file/FileIOSpanManager.java +++ b/sentry/src/main/java/io/sentry/instrumentation/file/FileIOSpanManager.java @@ -1,6 +1,6 @@ package io.sentry.instrumentation.file; -import io.sentry.IHub; +import io.sentry.IScopes; import io.sentry.ISpan; import io.sentry.SentryIntegrationPackageStorage; import io.sentry.SentryOptions; @@ -28,8 +28,8 @@ final class FileIOSpanManager { private final @NotNull SentryStackTraceFactory stackTraceFactory; - static @Nullable ISpan startSpan(final @NotNull IHub hub, final @NotNull String op) { - final ISpan parent = Platform.isAndroid() ? hub.getTransaction() : hub.getSpan(); + static @Nullable ISpan startSpan(final @NotNull IScopes scopes, final @NotNull String op) { + final ISpan parent = Platform.isAndroid() ? scopes.getTransaction() : scopes.getSpan(); return parent != null ? parent.startChild(op) : null; } diff --git a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileInputStream.java b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileInputStream.java index 04bb87ae7c..ea7d7f09a5 100644 --- a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileInputStream.java +++ b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileInputStream.java @@ -1,8 +1,8 @@ package io.sentry.instrumentation.file; -import io.sentry.HubAdapter; -import io.sentry.IHub; +import io.sentry.IScopes; import io.sentry.ISpan; +import io.sentry.ScopesAdapter; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; @@ -25,24 +25,24 @@ public final class SentryFileInputStream extends FileInputStream { private final @NotNull FileIOSpanManager spanManager; public SentryFileInputStream(final @Nullable String name) throws FileNotFoundException { - this(name != null ? new File(name) : null, HubAdapter.getInstance()); + this(name != null ? new File(name) : null, ScopesAdapter.getInstance()); } public SentryFileInputStream(final @Nullable File file) throws FileNotFoundException { - this(file, HubAdapter.getInstance()); + this(file, ScopesAdapter.getInstance()); } public SentryFileInputStream(final @NotNull FileDescriptor fdObj) { - this(fdObj, HubAdapter.getInstance()); + this(fdObj, ScopesAdapter.getInstance()); } - SentryFileInputStream(final @Nullable File file, final @NotNull IHub hub) + SentryFileInputStream(final @Nullable File file, final @NotNull IScopes scopes) throws FileNotFoundException { - this(init(file, null, hub)); + this(init(file, null, scopes)); } - SentryFileInputStream(final @NotNull FileDescriptor fdObj, final @NotNull IHub hub) { - this(init(fdObj, null, hub), fdObj); + SentryFileInputStream(final @NotNull FileDescriptor fdObj, final @NotNull IScopes scopes) { + this(init(fdObj, null, scopes), fdObj); } private SentryFileInputStream( @@ -60,24 +60,24 @@ private SentryFileInputStream(final @NotNull FileInputStreamInitData data) } private static FileInputStreamInitData init( - final @Nullable File file, @Nullable FileInputStream delegate, final @NotNull IHub hub) + final @Nullable File file, @Nullable FileInputStream delegate, final @NotNull IScopes scopes) throws FileNotFoundException { - final ISpan span = FileIOSpanManager.startSpan(hub, "file.read"); + final ISpan span = FileIOSpanManager.startSpan(scopes, "file.read"); if (delegate == null) { delegate = new FileInputStream(file); } - return new FileInputStreamInitData(file, span, delegate, hub.getOptions()); + return new FileInputStreamInitData(file, span, delegate, scopes.getOptions()); } private static FileInputStreamInitData init( final @NotNull FileDescriptor fd, @Nullable FileInputStream delegate, - final @NotNull IHub hub) { - final ISpan span = FileIOSpanManager.startSpan(hub, "file.read"); + final @NotNull IScopes scopes) { + final ISpan span = FileIOSpanManager.startSpan(scopes, "file.read"); if (delegate == null) { delegate = new FileInputStream(fd); } - return new FileInputStreamInitData(null, span, delegate, hub.getOptions()); + return new FileInputStreamInitData(null, span, delegate, scopes.getOptions()); } @Override @@ -128,25 +128,27 @@ public static FileInputStream create( final @NotNull FileInputStream delegate, final @Nullable String name) throws FileNotFoundException { return new SentryFileInputStream( - init(name != null ? new File(name) : null, delegate, HubAdapter.getInstance())); + init(name != null ? new File(name) : null, delegate, ScopesAdapter.getInstance())); } public static FileInputStream create( final @NotNull FileInputStream delegate, final @Nullable File file) throws FileNotFoundException { - return new SentryFileInputStream(init(file, delegate, HubAdapter.getInstance())); + return new SentryFileInputStream(init(file, delegate, ScopesAdapter.getInstance())); } public static FileInputStream create( final @NotNull FileInputStream delegate, final @NotNull FileDescriptor descriptor) { return new SentryFileInputStream( - init(descriptor, delegate, HubAdapter.getInstance()), descriptor); + init(descriptor, delegate, ScopesAdapter.getInstance()), descriptor); } static FileInputStream create( - final @NotNull FileInputStream delegate, final @Nullable File file, final @NotNull IHub hub) + final @NotNull FileInputStream delegate, + final @Nullable File file, + final @NotNull IScopes scopes) throws FileNotFoundException { - return new SentryFileInputStream(init(file, delegate, hub)); + return new SentryFileInputStream(init(file, delegate, scopes)); } } } diff --git a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileOutputStream.java b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileOutputStream.java index 9424710d71..4ef5022e1c 100644 --- a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileOutputStream.java +++ b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileOutputStream.java @@ -1,8 +1,8 @@ package io.sentry.instrumentation.file; -import io.sentry.HubAdapter; -import io.sentry.IHub; +import io.sentry.IScopes; import io.sentry.ISpan; +import io.sentry.ScopesAdapter; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; @@ -24,30 +24,31 @@ public final class SentryFileOutputStream extends FileOutputStream { private final @NotNull FileIOSpanManager spanManager; public SentryFileOutputStream(final @Nullable String name) throws FileNotFoundException { - this(name != null ? new File(name) : null, false, HubAdapter.getInstance()); + this(name != null ? new File(name) : null, false, ScopesAdapter.getInstance()); } public SentryFileOutputStream(final @Nullable String name, final boolean append) throws FileNotFoundException { - this(init(name != null ? new File(name) : null, append, null, HubAdapter.getInstance())); + this(init(name != null ? new File(name) : null, append, null, ScopesAdapter.getInstance())); } public SentryFileOutputStream(final @Nullable File file) throws FileNotFoundException { - this(file, false, HubAdapter.getInstance()); + this(file, false, ScopesAdapter.getInstance()); } public SentryFileOutputStream(final @Nullable File file, final boolean append) throws FileNotFoundException { - this(init(file, append, null, HubAdapter.getInstance())); + this(init(file, append, null, ScopesAdapter.getInstance())); } public SentryFileOutputStream(final @NotNull FileDescriptor fdObj) { - this(init(fdObj, null, HubAdapter.getInstance()), fdObj); + this(init(fdObj, null, ScopesAdapter.getInstance()), fdObj); } - SentryFileOutputStream(final @Nullable File file, final boolean append, final @NotNull IHub hub) + SentryFileOutputStream( + final @Nullable File file, final boolean append, final @NotNull IScopes scopes) throws FileNotFoundException { - this(init(file, append, null, hub)); + this(init(file, append, null, scopes)); } private SentryFileOutputStream( @@ -68,22 +69,24 @@ private static FileOutputStreamInitData init( final @Nullable File file, final boolean append, @Nullable FileOutputStream delegate, - @NotNull IHub hub) + @NotNull IScopes scopes) throws FileNotFoundException { - final ISpan span = FileIOSpanManager.startSpan(hub, "file.write"); + final ISpan span = FileIOSpanManager.startSpan(scopes, "file.write"); if (delegate == null) { delegate = new FileOutputStream(file, append); } - return new FileOutputStreamInitData(file, append, span, delegate, hub.getOptions()); + return new FileOutputStreamInitData(file, append, span, delegate, scopes.getOptions()); } private static FileOutputStreamInitData init( - final @NotNull FileDescriptor fd, @Nullable FileOutputStream delegate, @NotNull IHub hub) { - final ISpan span = FileIOSpanManager.startSpan(hub, "file.write"); + final @NotNull FileDescriptor fd, + @Nullable FileOutputStream delegate, + @NotNull IScopes scopes) { + final ISpan span = FileIOSpanManager.startSpan(scopes, "file.write"); if (delegate == null) { delegate = new FileOutputStream(fd); } - return new FileOutputStreamInitData(null, false, span, delegate, hub.getOptions()); + return new FileOutputStreamInitData(null, false, span, delegate, scopes.getOptions()); } @Override @@ -132,31 +135,32 @@ public static FileOutputStream create( final @NotNull FileOutputStream delegate, final @Nullable String name) throws FileNotFoundException { return new SentryFileOutputStream( - init(name != null ? new File(name) : null, false, delegate, HubAdapter.getInstance())); + init(name != null ? new File(name) : null, false, delegate, ScopesAdapter.getInstance())); } public static FileOutputStream create( final @NotNull FileOutputStream delegate, final @Nullable String name, final boolean append) throws FileNotFoundException { return new SentryFileOutputStream( - init(name != null ? new File(name) : null, append, delegate, HubAdapter.getInstance())); + init( + name != null ? new File(name) : null, append, delegate, ScopesAdapter.getInstance())); } public static FileOutputStream create( final @NotNull FileOutputStream delegate, final @Nullable File file) throws FileNotFoundException { - return new SentryFileOutputStream(init(file, false, delegate, HubAdapter.getInstance())); + return new SentryFileOutputStream(init(file, false, delegate, ScopesAdapter.getInstance())); } public static FileOutputStream create( final @NotNull FileOutputStream delegate, final @Nullable File file, final boolean append) throws FileNotFoundException { - return new SentryFileOutputStream(init(file, append, delegate, HubAdapter.getInstance())); + return new SentryFileOutputStream(init(file, append, delegate, ScopesAdapter.getInstance())); } public static FileOutputStream create( final @NotNull FileOutputStream delegate, final @NotNull FileDescriptor fdObj) { - return new SentryFileOutputStream(init(fdObj, delegate, HubAdapter.getInstance()), fdObj); + return new SentryFileOutputStream(init(fdObj, delegate, ScopesAdapter.getInstance()), fdObj); } } } diff --git a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileReader.java b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileReader.java index 0a225e65a5..38a83c7ff6 100644 --- a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileReader.java +++ b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileReader.java @@ -1,6 +1,6 @@ package io.sentry.instrumentation.file; -import io.sentry.IHub; +import io.sentry.IScopes; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; @@ -20,7 +20,8 @@ public SentryFileReader(final @NotNull FileDescriptor fd) { super(new SentryFileInputStream(fd)); } - SentryFileReader(final @NotNull File file, final @NotNull IHub hub) throws FileNotFoundException { - super(new SentryFileInputStream(file, hub)); + SentryFileReader(final @NotNull File file, final @NotNull IScopes scopes) + throws FileNotFoundException { + super(new SentryFileInputStream(file, scopes)); } } diff --git a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileWriter.java b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileWriter.java index 9588984612..93c901ec6c 100644 --- a/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileWriter.java +++ b/sentry/src/main/java/io/sentry/instrumentation/file/SentryFileWriter.java @@ -1,6 +1,6 @@ package io.sentry.instrumentation.file; -import io.sentry.IHub; +import io.sentry.IScopes; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; @@ -30,8 +30,8 @@ public SentryFileWriter(final @NotNull FileDescriptor fd) { super(new SentryFileOutputStream(fd)); } - SentryFileWriter(final @NotNull File file, final boolean append, final @NotNull IHub hub) + SentryFileWriter(final @NotNull File file, final boolean append, final @NotNull IScopes scopes) throws FileNotFoundException { - super(new SentryFileOutputStream(file, append, hub)); + super(new SentryFileOutputStream(file, append, scopes)); } } diff --git a/sentry/src/main/java/io/sentry/util/CheckInUtils.java b/sentry/src/main/java/io/sentry/util/CheckInUtils.java index e15603adaf..6719e24839 100644 --- a/sentry/src/main/java/io/sentry/util/CheckInUtils.java +++ b/sentry/src/main/java/io/sentry/util/CheckInUtils.java @@ -3,7 +3,7 @@ import io.sentry.CheckIn; import io.sentry.CheckInStatus; import io.sentry.DateUtils; -import io.sentry.IHub; +import io.sentry.IScopes; import io.sentry.MonitorConfig; import io.sentry.Sentry; import io.sentry.protocol.SentryId; @@ -30,18 +30,19 @@ public static U withCheckIn( final @Nullable MonitorConfig monitorConfig, final @NotNull Callable callable) throws Exception { - final @NotNull IHub hub = Sentry.getCurrentHub(); + final @NotNull IScopes scopes = Sentry.getCurrentScopes(); final long startTime = System.currentTimeMillis(); boolean didError = false; - hub.pushScope(); - TracingUtils.startNewTrace(hub); + // TODO fork instead + scopes.pushScope(); + TracingUtils.startNewTrace(scopes); CheckIn inProgressCheckIn = new CheckIn(monitorSlug, CheckInStatus.IN_PROGRESS); if (monitorConfig != null) { inProgressCheckIn.setMonitorConfig(monitorConfig); } - @Nullable SentryId checkInId = hub.captureCheckIn(inProgressCheckIn); + @Nullable SentryId checkInId = scopes.captureCheckIn(inProgressCheckIn); try { return callable.call(); } catch (Throwable t) { @@ -51,8 +52,8 @@ public static U withCheckIn( final @NotNull CheckInStatus status = didError ? CheckInStatus.ERROR : CheckInStatus.OK; CheckIn checkIn = new CheckIn(checkInId, monitorSlug, status); checkIn.setDuration(DateUtils.millisToSeconds(System.currentTimeMillis() - startTime)); - hub.captureCheckIn(checkIn); - hub.popScope(); + scopes.captureCheckIn(checkIn); + scopes.popScope(); } } diff --git a/sentry/src/main/java/io/sentry/util/TracingUtils.java b/sentry/src/main/java/io/sentry/util/TracingUtils.java index 2aeb613f2d..67f6459660 100644 --- a/sentry/src/main/java/io/sentry/util/TracingUtils.java +++ b/sentry/src/main/java/io/sentry/util/TracingUtils.java @@ -2,8 +2,8 @@ import io.sentry.Baggage; import io.sentry.BaggageHeader; -import io.sentry.IHub; import io.sentry.IScope; +import io.sentry.IScopes; import io.sentry.ISpan; import io.sentry.PropagationContext; import io.sentry.SentryOptions; @@ -14,8 +14,8 @@ public final class TracingUtils { - public static void startNewTrace(final @NotNull IHub hub) { - hub.configureScope( + public static void startNewTrace(final @NotNull IScopes scopes) { + scopes.configureScope( scope -> { scope.withPropagationContext( propagationContext -> { @@ -25,30 +25,30 @@ public static void startNewTrace(final @NotNull IHub hub) { } public static @Nullable TracingHeaders traceIfAllowed( - final @NotNull IHub hub, + final @NotNull IScopes scopes, final @NotNull String requestUrl, @Nullable List thirdPartyBaggageHeaders, final @Nullable ISpan span) { - final @NotNull SentryOptions sentryOptions = hub.getOptions(); + final @NotNull SentryOptions sentryOptions = scopes.getOptions(); if (sentryOptions.isTraceSampling() && shouldAttachTracingHeaders(requestUrl, sentryOptions)) { - return trace(hub, thirdPartyBaggageHeaders, span); + return trace(scopes, thirdPartyBaggageHeaders, span); } return null; } public static @Nullable TracingHeaders trace( - final @NotNull IHub hub, + final @NotNull IScopes scopes, @Nullable List thirdPartyBaggageHeaders, final @Nullable ISpan span) { - final @NotNull SentryOptions sentryOptions = hub.getOptions(); + final @NotNull SentryOptions sentryOptions = scopes.getOptions(); if (span != null && !span.isNoOp()) { return new TracingHeaders( span.toSentryTrace(), span.toBaggageHeader(thirdPartyBaggageHeaders)); } else { final @NotNull PropagationContextHolder returnValue = new PropagationContextHolder(); - hub.configureScope( + scopes.configureScope( (scope) -> { returnValue.propagationContext = maybeUpdateBaggage(scope, sentryOptions); }); diff --git a/sentry/src/test/java/io/sentry/DefaultTransactionPerformanceCollectorTest.kt b/sentry/src/test/java/io/sentry/DefaultTransactionPerformanceCollectorTest.kt index c0445efb23..1416fbbe3f 100644 --- a/sentry/src/test/java/io/sentry/DefaultTransactionPerformanceCollectorTest.kt +++ b/sentry/src/test/java/io/sentry/DefaultTransactionPerformanceCollectorTest.kt @@ -33,7 +33,7 @@ class DefaultTransactionPerformanceCollectorTest { private class Fixture { lateinit var transaction1: ITransaction lateinit var transaction2: ITransaction - val hub: IHub = mock() + val scopes: IScopes = mock() val options = SentryOptions() var mockTimer: Timer? = null val deferredExecutorService = DeferredExecutorService() @@ -47,7 +47,7 @@ class DefaultTransactionPerformanceCollectorTest { } init { - whenever(hub.options).thenReturn(options) + whenever(scopes.options).thenReturn(options) } fun getSut(memoryCollector: IPerformanceSnapshotCollector? = JavaMemoryCollector(), cpuCollector: IPerformanceSnapshotCollector? = mockCpuCollector, executorService: ISentryExecutorService = deferredExecutorService): TransactionPerformanceCollector { @@ -59,8 +59,8 @@ class DefaultTransactionPerformanceCollectorTest { if (memoryCollector != null) { options.addPerformanceCollector(memoryCollector) } - transaction1 = SentryTracer(TransactionContext("", ""), hub) - transaction2 = SentryTracer(TransactionContext("", ""), hub) + transaction1 = SentryTracer(TransactionContext("", ""), scopes) + transaction2 = SentryTracer(TransactionContext("", ""), scopes) val collector = DefaultTransactionPerformanceCollector(options) val timer: Timer = collector.getProperty("timer") ?: Timer(true) mockTimer = spy(timer) diff --git a/sentry/src/test/java/io/sentry/DirectoryProcessorTest.kt b/sentry/src/test/java/io/sentry/DirectoryProcessorTest.kt index e87f4256d5..0507b8499d 100644 --- a/sentry/src/test/java/io/sentry/DirectoryProcessorTest.kt +++ b/sentry/src/test/java/io/sentry/DirectoryProcessorTest.kt @@ -27,7 +27,7 @@ class DirectoryProcessorTest { private class Fixture { - var hub: IHub = mock() + var scopes: IScopes = mock() var envelopeReader: IEnvelopeReader = mock() var serializer: ISerializer = mock() var logger: ILogger = mock() @@ -40,7 +40,7 @@ class DirectoryProcessorTest { fun getSut(isRetryable: Boolean = false, isRateLimitingActive: Boolean = false): OutboxSender { val hintCaptor = argumentCaptor() - whenever(hub.captureEvent(any(), hintCaptor.capture())).then { + whenever(scopes.captureEvent(any(), hintCaptor.capture())).then { HintUtils.runIfHasType( hintCaptor.firstValue, Enqueable::class.java @@ -52,7 +52,7 @@ class DirectoryProcessorTest { val rateLimiter = mock { whenever(mock.isActiveForCategory(any())).thenReturn(true) } - whenever(hub.rateLimiter).thenReturn(rateLimiter) + whenever(scopes.rateLimiter).thenReturn(rateLimiter) } } HintUtils.runIfHasType( @@ -62,7 +62,7 @@ class DirectoryProcessorTest { retryable.isRetry = isRetryable } } - return OutboxSender(hub, envelopeReader, serializer, logger, 500, 30) + return OutboxSender(scopes, envelopeReader, serializer, logger, 500, 30) } } @@ -91,7 +91,7 @@ class DirectoryProcessorTest { whenever(fixture.serializer.deserialize(any(), eq(SentryEvent::class.java))).thenReturn(event) fixture.getSut().processDirectory(file) - verify(fixture.hub).captureEvent(any(), argWhere { !HintUtils.hasType(it, ApplyScopeData::class.java) }) + verify(fixture.scopes).captureEvent(any(), argWhere { !HintUtils.hasType(it, ApplyScopeData::class.java) }) } @Test @@ -100,7 +100,7 @@ class DirectoryProcessorTest { dir.mkdirs() assertTrue(dir.exists()) // sanity check fixture.getSut().processDirectory(file) - verify(fixture.hub, never()).captureEnvelope(any(), any()) + verify(fixture.scopes, never()).captureEnvelope(any(), any()) } @Test @@ -121,7 +121,7 @@ class DirectoryProcessorTest { sut.processDirectory(file) // should only capture once - verify(fixture.hub).captureEvent(any(), anyOrNull()) + verify(fixture.scopes).captureEvent(any(), anyOrNull()) } @Test @@ -139,7 +139,7 @@ class DirectoryProcessorTest { sut.processDirectory(file) // should only capture once - verify(fixture.hub).captureEvent(any(), anyOrNull()) + verify(fixture.scopes).captureEvent(any(), anyOrNull()) } private fun getTempEnvelope(fileName: String): String { diff --git a/sentry/src/test/java/io/sentry/EnvelopeSenderTest.kt b/sentry/src/test/java/io/sentry/EnvelopeSenderTest.kt index 6f0ea9cb8a..d63ee81854 100644 --- a/sentry/src/test/java/io/sentry/EnvelopeSenderTest.kt +++ b/sentry/src/test/java/io/sentry/EnvelopeSenderTest.kt @@ -23,7 +23,7 @@ import kotlin.test.assertFalse class EnvelopeSenderTest { private class Fixture { - var hub: IHub? = mock() + var scopes: IScopes? = mock() var logger: ILogger? = mock() var serializer: ISerializer? = mock() var options = SentryOptions().noFlushTimeout() @@ -35,7 +35,7 @@ class EnvelopeSenderTest { fun getSut(): EnvelopeSender { return EnvelopeSender( - hub!!, + scopes!!, serializer!!, logger!!, options.flushTimeoutMillis, @@ -62,7 +62,7 @@ class EnvelopeSenderTest { val sut = fixture.getSut() sut.processDirectory(File("i don't exist")) verify(fixture.logger)!!.log(eq(SentryLevel.WARNING), eq("Directory '%s' doesn't exist. No cached events to send."), any()) - verifyNoMoreInteractions(fixture.hub) + verifyNoMoreInteractions(fixture.scopes) } @Test @@ -72,7 +72,7 @@ class EnvelopeSenderTest { testFile.deleteOnExit() sut.processDirectory(testFile) verify(fixture.logger)!!.log(eq(SentryLevel.ERROR), eq("Cache dir %s is not a directory."), any()) - verifyNoMoreInteractions(fixture.hub) + verifyNoMoreInteractions(fixture.scopes) } @Test @@ -82,11 +82,11 @@ class EnvelopeSenderTest { sut.processDirectory(File(tempDirectory.toUri())) testFile.deleteOnExit() verify(fixture.logger)!!.log(eq(SentryLevel.DEBUG), eq("File '%s' doesn't match extension expected."), any()) - verify(fixture.hub, never())!!.captureEnvelope(any(), anyOrNull()) + verify(fixture.scopes, never())!!.captureEnvelope(any(), anyOrNull()) } @Test - fun `when directory has event files, processDirectory captures with hub`() { + fun `when directory has event files, processDirectory captures with scopes`() { val event = SentryEvent() val envelope = SentryEnvelope.from(fixture.serializer!!, event, null) whenever(fixture.serializer!!.deserializeEnvelope(any())).thenReturn(envelope) @@ -94,7 +94,7 @@ class EnvelopeSenderTest { val testFile = File(Files.createTempFile(tempDirectory, "send-cached-event-test", EnvelopeCache.SUFFIX_ENVELOPE_FILE).toUri()) testFile.deleteOnExit() sut.processDirectory(File(tempDirectory.toUri())) - verify(fixture.hub)!!.captureEnvelope(eq(envelope), any()) + verify(fixture.scopes)!!.captureEnvelope(eq(envelope), any()) } @Test @@ -108,12 +108,12 @@ class EnvelopeSenderTest { val hints = HintUtils.createWithTypeCheckHint(mock()) sut.processFile(testFile, hints) verify(fixture.logger)!!.log(eq(SentryLevel.ERROR), eq(expected), eq("Failed to capture cached envelope %s"), eq(testFile.absolutePath)) - verifyNoMoreInteractions(fixture.hub) + verifyNoMoreInteractions(fixture.scopes) assertFalse(testFile.exists()) } @Test - fun `when hub throws, file gets deleted`() { + fun `when scopes throws, file gets deleted`() { val expected = RuntimeException() whenever(fixture.serializer!!.deserializeEnvelope(any())).doThrow(expected) val sut = fixture.getSut() @@ -121,6 +121,6 @@ class EnvelopeSenderTest { testFile.deleteOnExit() sut.processFile(testFile, Hint()) verify(fixture.logger)!!.log(eq(SentryLevel.ERROR), eq(expected), eq("Failed to capture cached envelope %s"), eq(testFile.absolutePath)) - verifyNoMoreInteractions(fixture.hub) + verifyNoMoreInteractions(fixture.scopes) } } diff --git a/sentry/src/test/java/io/sentry/HubAdapterTest.kt b/sentry/src/test/java/io/sentry/HubAdapterTest.kt index 9686250d20..0e7e1d0f77 100644 --- a/sentry/src/test/java/io/sentry/HubAdapterTest.kt +++ b/sentry/src/test/java/io/sentry/HubAdapterTest.kt @@ -13,11 +13,11 @@ import kotlin.test.Test class HubAdapterTest { - val hub: Hub = mock() + val scopes: IScopes = mock() @BeforeTest fun `set up`() { - Sentry.setCurrentHub(hub) + Sentry.setCurrentScopes(scopes) } @AfterTest @@ -27,7 +27,7 @@ class HubAdapterTest { @Test fun `isEnabled calls Hub`() { HubAdapter.getInstance().isEnabled - verify(hub).isEnabled + verify(scopes).isEnabled } @Test fun `captureEvent calls Hub`() { @@ -35,27 +35,27 @@ class HubAdapterTest { val hint = mock() val scopeCallback = mock() HubAdapter.getInstance().captureEvent(event, hint) - verify(hub).captureEvent(eq(event), eq(hint)) + verify(scopes).captureEvent(eq(event), eq(hint)) HubAdapter.getInstance().captureEvent(event, hint, scopeCallback) - verify(hub).captureEvent(eq(event), eq(hint), eq(scopeCallback)) + verify(scopes).captureEvent(eq(event), eq(hint), eq(scopeCallback)) } @Test fun `captureMessage calls Hub`() { val scopeCallback = mock() val sentryLevel = mock() HubAdapter.getInstance().captureMessage("message", sentryLevel) - verify(hub).captureMessage(eq("message"), eq(sentryLevel)) + verify(scopes).captureMessage(eq("message"), eq(sentryLevel)) HubAdapter.getInstance().captureMessage("message", sentryLevel, scopeCallback) - verify(hub).captureMessage(eq("message"), eq(sentryLevel), eq(scopeCallback)) + verify(scopes).captureMessage(eq("message"), eq(sentryLevel), eq(scopeCallback)) } @Test fun `captureEnvelope calls Hub`() { val envelope = mock() val hint = mock() HubAdapter.getInstance().captureEnvelope(envelope, hint) - verify(hub).captureEnvelope(eq(envelope), eq(hint)) + verify(scopes).captureEnvelope(eq(envelope), eq(hint)) } @Test fun `captureException calls Hub`() { @@ -63,145 +63,145 @@ class HubAdapterTest { val hint = mock() val scopeCallback = mock() HubAdapter.getInstance().captureException(throwable, hint) - verify(hub).captureException(eq(throwable), eq(hint)) + verify(scopes).captureException(eq(throwable), eq(hint)) HubAdapter.getInstance().captureException(throwable, hint, scopeCallback) - verify(hub).captureException(eq(throwable), eq(hint), eq(scopeCallback)) + verify(scopes).captureException(eq(throwable), eq(hint), eq(scopeCallback)) } @Test fun `captureUserFeedback calls Hub`() { val userFeedback = mock() HubAdapter.getInstance().captureUserFeedback(userFeedback) - verify(hub).captureUserFeedback(eq(userFeedback)) + verify(scopes).captureUserFeedback(eq(userFeedback)) } @Test fun `captureCheckIn calls Hub`() { val checkIn = mock() HubAdapter.getInstance().captureCheckIn(checkIn) - verify(hub).captureCheckIn(eq(checkIn)) + verify(scopes).captureCheckIn(eq(checkIn)) } @Test fun `startSession calls Hub`() { HubAdapter.getInstance().startSession() - verify(hub).startSession() + verify(scopes).startSession() } @Test fun `endSession calls Hub`() { HubAdapter.getInstance().endSession() - verify(hub).endSession() + verify(scopes).endSession() } @Test fun `close calls Hub`() { HubAdapter.getInstance().close() - verify(hub).close(false) + verify(scopes).close(false) } @Test fun `close with isRestarting true calls Hub with isRestarting false`() { HubAdapter.getInstance().close(true) - verify(hub).close(false) + verify(scopes).close(false) } @Test fun `close with isRestarting false calls Hub with isRestarting false`() { HubAdapter.getInstance().close(false) - verify(hub).close(false) + verify(scopes).close(false) } @Test fun `addBreadcrumb calls Hub`() { val breadcrumb = mock() val hint = mock() HubAdapter.getInstance().addBreadcrumb(breadcrumb, hint) - verify(hub).addBreadcrumb(eq(breadcrumb), eq(hint)) + verify(scopes).addBreadcrumb(eq(breadcrumb), eq(hint)) } @Test fun `setLevel calls Hub`() { val sentryLevel = mock() HubAdapter.getInstance().setLevel(sentryLevel) - verify(hub).setLevel(eq(sentryLevel)) + verify(scopes).setLevel(eq(sentryLevel)) } @Test fun `setTransaction calls Hub`() { HubAdapter.getInstance().setTransaction("transaction") - verify(hub).setTransaction(eq("transaction")) + verify(scopes).setTransaction(eq("transaction")) } @Test fun `setUser calls Hub`() { val user = mock() HubAdapter.getInstance().setUser(user) - verify(hub).setUser(eq(user)) + verify(scopes).setUser(eq(user)) } @Test fun `setFingerprint calls Hub`() { val fingerprint = ArrayList() HubAdapter.getInstance().setFingerprint(fingerprint) - verify(hub).setFingerprint(eq(fingerprint)) + verify(scopes).setFingerprint(eq(fingerprint)) } @Test fun `clearBreadcrumbs calls Hub`() { HubAdapter.getInstance().clearBreadcrumbs() - verify(hub).clearBreadcrumbs() + verify(scopes).clearBreadcrumbs() } @Test fun `setTag calls Hub`() { HubAdapter.getInstance().setTag("key", "value") - verify(hub).setTag(eq("key"), eq("value")) + verify(scopes).setTag(eq("key"), eq("value")) } @Test fun `removeTag calls Hub`() { HubAdapter.getInstance().removeTag("key") - verify(hub).removeTag(eq("key")) + verify(scopes).removeTag(eq("key")) } @Test fun `setExtra calls Hub`() { HubAdapter.getInstance().setExtra("key", "value") - verify(hub).setExtra(eq("key"), eq("value")) + verify(scopes).setExtra(eq("key"), eq("value")) } @Test fun `removeExtra calls Hub`() { HubAdapter.getInstance().removeExtra("key") - verify(hub).removeExtra(eq("key")) + verify(scopes).removeExtra(eq("key")) } @Test fun `getLastEventId calls Hub`() { HubAdapter.getInstance().lastEventId - verify(hub).lastEventId + verify(scopes).lastEventId } @Test fun `pushScope calls Hub`() { HubAdapter.getInstance().pushScope() - verify(hub).pushScope() + verify(scopes).pushScope() } @Test fun `popScope calls Hub`() { HubAdapter.getInstance().popScope() - verify(hub).popScope() + verify(scopes).popScope() } @Test fun `withScope calls Hub`() { val scopeCallback = mock() HubAdapter.getInstance().withScope(scopeCallback) - verify(hub).withScope(eq(scopeCallback)) + verify(scopes).withScope(eq(scopeCallback)) } @Test fun `configureScope calls Hub`() { val scopeCallback = mock() HubAdapter.getInstance().configureScope(scopeCallback) - verify(hub).configureScope(eq(scopeCallback)) + verify(scopes).configureScope(eq(scopeCallback)) } @Test fun `bindClient calls Hub`() { val client = mock() HubAdapter.getInstance().bindClient(client) - verify(hub).bindClient(eq(client)) + verify(scopes).bindClient(eq(client)) } @Test fun `flush calls Hub`() { HubAdapter.getInstance().flush(1) - verify(hub).flush(eq(1)) + verify(scopes).flush(eq(1)) } @Test fun `clone calls Hub`() { HubAdapter.getInstance().clone() - verify(hub).clone() + verify(scopes).clone() } @Test fun `captureTransaction calls Hub`() { @@ -210,7 +210,7 @@ class HubAdapterTest { val hint = mock() val profilingTraceData = mock() HubAdapter.getInstance().captureTransaction(transaction, traceContext, hint, profilingTraceData) - verify(hub).captureTransaction(eq(transaction), eq(traceContext), eq(hint), eq(profilingTraceData)) + verify(scopes).captureTransaction(eq(transaction), eq(traceContext), eq(hint), eq(profilingTraceData)) } @Test fun `startTransaction calls Hub`() { @@ -218,48 +218,48 @@ class HubAdapterTest { val samplingContext = mock() val transactionOptions = mock() HubAdapter.getInstance().startTransaction(transactionContext) - verify(hub).startTransaction(eq(transactionContext), any()) + verify(scopes).startTransaction(eq(transactionContext), any()) - reset(hub) + reset(scopes) HubAdapter.getInstance().startTransaction(transactionContext, transactionOptions) - verify(hub).startTransaction(eq(transactionContext), eq(transactionOptions)) + verify(scopes).startTransaction(eq(transactionContext), eq(transactionOptions)) } @Test fun `traceHeaders calls Hub`() { HubAdapter.getInstance().traceHeaders() - verify(hub).traceHeaders() + verify(scopes).traceHeaders() } @Test fun `setSpanContext calls Hub`() { val throwable = mock() val span = mock() HubAdapter.getInstance().setSpanContext(throwable, span, "transactionName") - verify(hub).setSpanContext(eq(throwable), eq(span), eq("transactionName")) + verify(scopes).setSpanContext(eq(throwable), eq(span), eq("transactionName")) } @Test fun `getSpan calls Hub`() { HubAdapter.getInstance().span - verify(hub).span + verify(scopes).span } @Test fun `getTransaction calls Hub`() { HubAdapter.getInstance().transaction - verify(hub).transaction + verify(scopes).transaction } @Test fun `getOptions calls Hub`() { HubAdapter.getInstance().options - verify(hub).options + verify(scopes).options } @Test fun `isCrashedLastRun calls Hub`() { HubAdapter.getInstance().isCrashedLastRun - verify(hub).isCrashedLastRun + verify(scopes).isCrashedLastRun } @Test fun `reportFullyDisplayed calls Hub`() { HubAdapter.getInstance().reportFullyDisplayed() - verify(hub).reportFullyDisplayed() + verify(scopes).reportFullyDisplayed() } } diff --git a/sentry/src/test/java/io/sentry/HubTest.kt b/sentry/src/test/java/io/sentry/HubTest.kt index 8fac963e70..f30fd0a966 100644 --- a/sentry/src/test/java/io/sentry/HubTest.kt +++ b/sentry/src/test/java/io/sentry/HubTest.kt @@ -72,7 +72,7 @@ class HubTest { } @Test - fun `when hub is cloned, integrations are not registered`() { + fun `when scopes is cloned, integrations are not registered`() { val integrationMock = mock() val options = SentryOptions() options.cacheDirPath = file.absolutePath @@ -80,36 +80,36 @@ class HubTest { options.setSerializer(mock()) options.addIntegration(integrationMock) // val expected = HubAdapter.getInstance() - val hub = Hub(options) + val scopes = Hub(options) // verify(integrationMock).register(expected, options) - hub.clone() + scopes.clone() verifyNoMoreInteractions(integrationMock) } @Test - fun `when hub is cloned, scope changes are isolated`() { + fun `when scopes is cloned, scope changes are isolated`() { val options = SentryOptions() options.cacheDirPath = file.absolutePath options.dsn = "https://key@sentry.io/proj" options.setSerializer(mock()) - val hub = Hub(options) + val scopes = Hub(options) var firstScope: IScope? = null - hub.configureScope { + scopes.configureScope { firstScope = it - it.setTag("hub", "a") + it.setTag("scopes", "a") } var cloneScope: IScope? = null - val clone = hub.clone() + val clone = scopes.clone() clone.configureScope { cloneScope = it - it.setTag("hub", "b") + it.setTag("scopes", "b") } - assertEquals("a", firstScope!!.tags["hub"]) - assertEquals("b", cloneScope!!.tags["hub"]) + assertEquals("a", firstScope!!.tags["scopes"]) + assertEquals("b", cloneScope!!.tags["scopes"]) } @Test - fun `when hub is initialized, breadcrumbs are capped as per options`() { + fun `when scopes is initialized, breadcrumbs are capped as per options`() { val options = SentryOptions() options.cacheDirPath = file.absolutePath options.maxBreadcrumbs = 5 @@ -288,7 +288,7 @@ class HubTest { } @Test - fun `when captureEvent is called on disabled hub, lastEventId does not get overwritten`() { + fun `when captureEvent is called on disabled scopes, lastEventId does not get overwritten`() { val (sut, mockClient) = getEnabledHub() whenever(mockClient.captureEvent(any(), any(), anyOrNull())).thenReturn(SentryId(UUID.randomUUID())) val event = SentryEvent() @@ -827,14 +827,14 @@ class HubTest { @Test fun `when withScope throws an exception then it should be caught`() { - val (hub, _, logger) = getEnabledHub() + val (scopes, _, logger) = getEnabledHub() val exception = Exception("scope callback exception") val scopeCallback = ScopeCallback { throw exception } - hub.withScope(scopeCallback) + scopes.withScope(scopeCallback) verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } @@ -864,25 +864,25 @@ class HubTest { @Test fun `when configureScope throws an exception then it should be caught`() { - val (hub, _, logger) = getEnabledHub() + val (scopes, _, logger) = getEnabledHub() val exception = Exception("scope callback exception") val scopeCallback = ScopeCallback { throw exception } - hub.configureScope(scopeCallback) + scopes.configureScope(scopeCallback) verify(logger).log(eq(SentryLevel.ERROR), any(), eq(exception)) } //endregion @Test - fun `when integration is registered, hub is enabled`() { + fun `when integration is registered, scopes is enabled`() { val mock = mock() var options: SentryOptions? = null - // init main hub and make it enabled + // init main scopes and make it enabled Sentry.init { it.addIntegration(mock) it.dsn = "https://key@sentry.io/proj" @@ -892,8 +892,8 @@ class HubTest { } doAnswer { - val hub = it.arguments[0] as IHub - assertTrue(hub.isEnabled) + val scopes = it.arguments[0] as IScopes + assertTrue(scopes.isEnabled) }.whenever(mock).register(any(), eq(options!!)) verify(mock).register(any(), eq(options!!)) @@ -902,26 +902,26 @@ class HubTest { //region setLevel tests @Test fun `when setLevel is called on disabled client, do nothing`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.close() + scopes.close() - hub.setLevel(SentryLevel.INFO) + scopes.setLevel(SentryLevel.INFO) assertNull(scope?.level) } @Test fun `when setLevel is called, level is set`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.setLevel(SentryLevel.INFO) + scopes.setLevel(SentryLevel.INFO) assertEquals(SentryLevel.INFO, scope?.level) } //endregion @@ -929,74 +929,74 @@ class HubTest { //region setTransaction tests @Test fun `when setTransaction is called on disabled client, do nothing`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.close() + scopes.close() - hub.setTransaction("test") + scopes.setTransaction("test") assertNull(scope?.transactionName) } @Test fun `when setTransaction is called, and transaction is not set, transaction name is changed`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.setTransaction("test") + scopes.setTransaction("test") assertEquals("test", scope?.transactionName) } @Test fun `when setTransaction is called, and transaction is set, transaction name is changed`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - val tx = hub.startTransaction("test", "op") - hub.configureScope { it.setTransaction(tx) } + val tx = scopes.startTransaction("test", "op") + scopes.configureScope { it.setTransaction(tx) } assertEquals("test", scope?.transactionName) } @Test fun `when startTransaction is called with different instrumenter, no-op is returned`() { - val hub = generateHub() + val scopes = generateHub() val transactionContext = TransactionContext("test", "op").also { it.instrumenter = Instrumenter.OTEL } val transactionOptions = TransactionOptions() - val tx = hub.startTransaction(transactionContext, transactionOptions) + val tx = scopes.startTransaction(transactionContext, transactionOptions) assertTrue(tx is NoOpTransaction) } @Test fun `when startTransaction is called with different instrumenter, no-op is returned 2`() { - val hub = generateHub() { + val scopes = generateHub() { it.instrumenter = Instrumenter.OTEL } - val tx = hub.startTransaction("test", "op") + val tx = scopes.startTransaction("test", "op") assertTrue(tx is NoOpTransaction) } @Test fun `when startTransaction is called with configured instrumenter, it works`() { - val hub = generateHub() { + val scopes = generateHub() { it.instrumenter = Instrumenter.OTEL } val transactionContext = TransactionContext("test", "op").also { it.instrumenter = Instrumenter.OTEL } val transactionOptions = TransactionOptions() - val tx = hub.startTransaction(transactionContext, transactionOptions) + val tx = scopes.startTransaction(transactionContext, transactionOptions) assertFalse(tx is NoOpTransaction) } @@ -1005,27 +1005,27 @@ class HubTest { //region setUser tests @Test fun `when setUser is called on disabled client, do nothing`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.close() + scopes.close() - hub.setUser(User()) + scopes.setUser(User()) assertNull(scope?.user) } @Test fun `when setUser is called, user is set`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } val user = User() - hub.setUser(user) + scopes.setUser(user) assertEquals(user, scope?.user) } //endregion @@ -1033,40 +1033,40 @@ class HubTest { //region setFingerprint tests @Test fun `when setFingerprint is called on disabled client, do nothing`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.close() + scopes.close() val fingerprint = listOf("abc") - hub.setFingerprint(fingerprint) + scopes.setFingerprint(fingerprint) assertEquals(0, scope?.fingerprint?.count()) } @Test fun `when setFingerprint is called with null parameter, do nothing`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.callMethod("setFingerprint", List::class.java, null) + scopes.callMethod("setFingerprint", List::class.java, null) assertEquals(0, scope?.fingerprint?.count()) } @Test fun `when setFingerprint is called, fingerprint is set`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } val fingerprint = listOf("abc") - hub.setFingerprint(fingerprint) + scopes.setFingerprint(fingerprint) assertEquals(1, scope?.fingerprint?.count()) } //endregion @@ -1074,30 +1074,30 @@ class HubTest { //region clearBreadcrumbs tests @Test fun `when clearBreadcrumbs is called on disabled client, do nothing`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.addBreadcrumb(Breadcrumb()) + scopes.addBreadcrumb(Breadcrumb()) assertEquals(1, scope?.breadcrumbs?.count()) - hub.close() + scopes.close() assertEquals(0, scope?.breadcrumbs?.count()) } @Test fun `when clearBreadcrumbs is called, clear breadcrumbs`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.addBreadcrumb(Breadcrumb()) + scopes.addBreadcrumb(Breadcrumb()) assertEquals(1, scope?.breadcrumbs?.count()) - hub.clearBreadcrumbs() + scopes.clearBreadcrumbs() assertEquals(0, scope?.breadcrumbs?.count()) } //endregion @@ -1105,38 +1105,38 @@ class HubTest { //region setTag tests @Test fun `when setTag is called on disabled client, do nothing`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.close() + scopes.close() - hub.setTag("test", "test") + scopes.setTag("test", "test") assertEquals(0, scope?.tags?.count()) } @Test fun `when setTag is called with null parameters, do nothing`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.callMethod("setTag", parameterTypes = arrayOf(String::class.java, String::class.java), null, null) + scopes.callMethod("setTag", parameterTypes = arrayOf(String::class.java, String::class.java), null, null) assertEquals(0, scope?.tags?.count()) } @Test fun `when setTag is called, tag is set`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.setTag("test", "test") + scopes.setTag("test", "test") assertEquals(1, scope?.tags?.count()) } //endregion @@ -1144,38 +1144,38 @@ class HubTest { //region setExtra tests @Test fun `when setExtra is called on disabled client, do nothing`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.close() + scopes.close() - hub.setExtra("test", "test") + scopes.setExtra("test", "test") assertEquals(0, scope?.extras?.count()) } @Test fun `when setExtra is called with null parameters, do nothing`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.callMethod("setExtra", parameterTypes = arrayOf(String::class.java, String::class.java), null, null) + scopes.callMethod("setExtra", parameterTypes = arrayOf(String::class.java, String::class.java), null, null) assertEquals(0, scope?.extras?.count()) } @Test fun `when setExtra is called, extra is set`() { - val hub = generateHub() + val scopes = generateHub() var scope: IScope? = null - hub.configureScope { + scopes.configureScope { scope = it } - hub.setExtra("test", "test") + scopes.setExtra("test", "test") assertEquals(1, scope?.extras?.count()) } //endregion @@ -1488,19 +1488,19 @@ class HubTest { val mockTransactionProfiler = mock() val mockClient = mock() whenever(mockTransactionProfiler.onTransactionFinish(any(), anyOrNull(), anyOrNull())).thenAnswer { mockClient.captureEnvelope(mock()) } - val hub = generateHub { + val scopes = generateHub { it.setTransactionProfiler(mockTransactionProfiler) } - hub.bindClient(mockClient) + scopes.bindClient(mockClient) // Transaction is not sampled, so it should not be profiled val contexts = TransactionContext("name", "op", TracesSamplingDecision(false, null, true, null)) - val transaction = hub.startTransaction(contexts) + val transaction = scopes.startTransaction(contexts) transaction.finish() verify(mockClient, never()).captureEnvelope(any()) // Transaction is sampled, so it should be profiled val sampledContexts = TransactionContext("name", "op", TracesSamplingDecision(true, null, true, null)) - val sampledTransaction = hub.startTransaction(sampledContexts) + val sampledTransaction = scopes.startTransaction(sampledContexts) sampledTransaction.finish() verify(mockClient).captureEnvelope(any()) } @@ -1510,13 +1510,13 @@ class HubTest { val mockTransactionProfiler = mock() val mockClient = mock() whenever(mockTransactionProfiler.onTransactionFinish(any(), anyOrNull(), anyOrNull())).thenAnswer { mockClient.captureEnvelope(mock()) } - val hub = generateHub { + val scopes = generateHub { it.profilesSampleRate = 0.0 it.setTransactionProfiler(mockTransactionProfiler) } - hub.bindClient(mockClient) + scopes.bindClient(mockClient) val contexts = TransactionContext("name", "op") - val transaction = hub.startTransaction(contexts) + val transaction = scopes.startTransaction(contexts) transaction.finish() verify(mockClient, never()).captureEnvelope(any()) } @@ -1525,12 +1525,12 @@ class HubTest { fun `when profiler is running and isAppStartTransaction is false, startTransaction does not interact with profiler`() { val mockTransactionProfiler = mock() whenever(mockTransactionProfiler.isRunning).thenReturn(true) - val hub = generateHub { + val scopes = generateHub { it.profilesSampleRate = 1.0 it.setTransactionProfiler(mockTransactionProfiler) } val context = TransactionContext("name", "op") - hub.startTransaction(context, TransactionOptions().apply { isAppStartTransaction = false }) + scopes.startTransaction(context, TransactionOptions().apply { isAppStartTransaction = false }) verify(mockTransactionProfiler, never()).start() verify(mockTransactionProfiler, never()).bindTransaction(any()) } @@ -1539,12 +1539,12 @@ class HubTest { fun `when profiler is running and isAppStartTransaction is true, startTransaction binds current profile`() { val mockTransactionProfiler = mock() whenever(mockTransactionProfiler.isRunning).thenReturn(true) - val hub = generateHub { + val scopes = generateHub { it.profilesSampleRate = 1.0 it.setTransactionProfiler(mockTransactionProfiler) } val context = TransactionContext("name", "op") - val transaction = hub.startTransaction(context, TransactionOptions().apply { isAppStartTransaction = true }) + val transaction = scopes.startTransaction(context, TransactionOptions().apply { isAppStartTransaction = true }) verify(mockTransactionProfiler, never()).start() verify(mockTransactionProfiler).bindTransaction(eq(transaction)) } @@ -1553,12 +1553,12 @@ class HubTest { fun `when profiler is not running, startTransaction starts and binds current profile`() { val mockTransactionProfiler = mock() whenever(mockTransactionProfiler.isRunning).thenReturn(false) - val hub = generateHub { + val scopes = generateHub { it.profilesSampleRate = 1.0 it.setTransactionProfiler(mockTransactionProfiler) } val context = TransactionContext("name", "op") - val transaction = hub.startTransaction(context, TransactionOptions().apply { isAppStartTransaction = false }) + val transaction = scopes.startTransaction(context, TransactionOptions().apply { isAppStartTransaction = false }) verify(mockTransactionProfiler).start() verify(mockTransactionProfiler).bindTransaction(eq(transaction)) } @@ -1567,75 +1567,75 @@ class HubTest { //region startTransaction tests @Test fun `when startTransaction, creates transaction`() { - val hub = generateHub() + val scopes = generateHub() val contexts = TransactionContext("name", "op") - val transaction = hub.startTransaction(contexts) + val transaction = scopes.startTransaction(contexts) assertTrue(transaction is SentryTracer) assertEquals(contexts, transaction.root.spanContext) } @Test fun `when startTransaction with bindToScope set to false, transaction is not attached to the scope`() { - val hub = generateHub() + val scopes = generateHub() - hub.startTransaction("name", "op", TransactionOptions()) + scopes.startTransaction("name", "op", TransactionOptions()) - hub.configureScope { + scopes.configureScope { assertNull(it.span) } } @Test fun `when startTransaction without bindToScope set, transaction is not attached to the scope`() { - val hub = generateHub() + val scopes = generateHub() - hub.startTransaction("name", "op") + scopes.startTransaction("name", "op") - hub.configureScope { + scopes.configureScope { assertNull(it.span) } } @Test fun `when startTransaction with bindToScope set to true, transaction is attached to the scope`() { - val hub = generateHub() + val scopes = generateHub() - val transaction = hub.startTransaction("name", "op", TransactionOptions().also { it.isBindToScope = true }) + val transaction = scopes.startTransaction("name", "op", TransactionOptions().also { it.isBindToScope = true }) - hub.configureScope { + scopes.configureScope { assertEquals(transaction, it.span) } } @Test fun `when startTransaction and no tracing sampling is configured, event is not sampled`() { - val hub = generateHub { + val scopes = generateHub { it.tracesSampleRate = 0.0 } - val transaction = hub.startTransaction("name", "op") + val transaction = scopes.startTransaction("name", "op") assertFalse(transaction.isSampled!!) } @Test fun `when startTransaction and no profile sampling is configured, profile is not sampled`() { - val hub = generateHub { + val scopes = generateHub { it.tracesSampleRate = 1.0 it.profilesSampleRate = 0.0 } - val transaction = hub.startTransaction("name", "op") + val transaction = scopes.startTransaction("name", "op") assertTrue(transaction.isSampled!!) assertFalse(transaction.isProfileSampled!!) } @Test fun `when startTransaction with parent sampled and no traces sampler provided, transaction inherits sampling decision`() { - val hub = generateHub() + val scopes = generateHub() val transactionContext = TransactionContext("name", "op") transactionContext.parentSampled = true - val transaction = hub.startTransaction(transactionContext) + val transaction = scopes.startTransaction(transactionContext) assertNotNull(transaction) assertNotNull(transaction.isSampled) assertTrue(transaction.isSampled!!) @@ -1643,10 +1643,10 @@ class HubTest { @Test fun `when startTransaction with parent profile sampled and no profile sampler provided, transaction inherits profile sampling decision`() { - val hub = generateHub() + val scopes = generateHub() val transactionContext = TransactionContext("name", "op") transactionContext.setParentSampled(true, true) - val transaction = hub.startTransaction(transactionContext) + val transaction = scopes.startTransaction(transactionContext) assertTrue(transaction.isProfileSampled!!) } @@ -1717,11 +1717,11 @@ class HubTest { @Test fun `when tracesSampleRate and tracesSampler are not set on SentryOptions, startTransaction returns NoOp`() { - val hub = generateHub { + val scopes = generateHub { it.tracesSampleRate = null it.tracesSampler = null } - val transaction = hub.startTransaction(TransactionContext("name", "op", TracesSamplingDecision(true))) + val transaction = scopes.startTransaction(TransactionContext("name", "op", TracesSamplingDecision(true))) assertTrue(transaction is NoOpTransaction) } //endregion @@ -1729,81 +1729,81 @@ class HubTest { //region startTransaction tests @Test fun `when traceHeaders and no transaction is active, traceHeaders are generated from scope`() { - val hub = generateHub() + val scopes = generateHub() var spanId: SpanId? = null - hub.configureScope { spanId = it.propagationContext.spanId } + scopes.configureScope { spanId = it.propagationContext.spanId } - val traceHeader = hub.traceHeaders() + val traceHeader = scopes.traceHeaders() assertNotNull(traceHeader) assertEquals(spanId, traceHeader.spanId) } @Test fun `when traceHeaders and there is an active transaction, traceHeaders are not null`() { - val hub = generateHub() - val tx = hub.startTransaction("aTransaction", "op") - hub.configureScope { it.setTransaction(tx) } + val scopes = generateHub() + val tx = scopes.startTransaction("aTransaction", "op") + scopes.configureScope { it.setTransaction(tx) } - assertNotNull(hub.traceHeaders()) + assertNotNull(scopes.traceHeaders()) } //endregion //region getSpan tests @Test fun `when there is no active transaction, getSpan returns null`() { - val hub = generateHub() - assertNull(hub.span) + val scopes = generateHub() + assertNull(scopes.span) } @Test fun `when there is no active transaction, getTransaction returns null`() { - val hub = generateHub() - assertNull(hub.transaction) + val scopes = generateHub() + assertNull(scopes.transaction) } @Test fun `when there is active transaction bound to the scope, getTransaction and getSpan return active transaction`() { - val hub = generateHub() - val tx = hub.startTransaction("aTransaction", "op") - hub.configureScope { it.transaction = tx } + val scopes = generateHub() + val tx = scopes.startTransaction("aTransaction", "op") + scopes.configureScope { it.transaction = tx } - assertEquals(tx, hub.transaction) - assertEquals(tx, hub.span) + assertEquals(tx, scopes.transaction) + assertEquals(tx, scopes.span) } @Test - fun `when there is a transaction but the hub is closed, getTransaction returns null`() { - val hub = generateHub() - hub.startTransaction("name", "op") - hub.close() + fun `when there is a transaction but the scopes is closed, getTransaction returns null`() { + val scopes = generateHub() + scopes.startTransaction("name", "op") + scopes.close() - assertNull(hub.transaction) + assertNull(scopes.transaction) } @Test fun `when there is active span within a transaction bound to the scope, getSpan returns active span`() { - val hub = generateHub() - val tx = hub.startTransaction("aTransaction", "op") - hub.configureScope { it.setTransaction(tx) } - hub.configureScope { it.setTransaction(tx) } + val scopes = generateHub() + val tx = scopes.startTransaction("aTransaction", "op") + scopes.configureScope { it.setTransaction(tx) } + scopes.configureScope { it.setTransaction(tx) } val span = tx.startChild("op") - assertEquals(tx, hub.transaction) - assertEquals(span, hub.span) + assertEquals(tx, scopes.transaction) + assertEquals(span, scopes.span) } // endregion //region setSpanContext @Test fun `associates span context with throwable`() { - val (hub, mockClient) = getEnabledHub() - val transaction = hub.startTransaction("aTransaction", "op") + val (scopes, mockClient) = getEnabledHub() + val transaction = scopes.startTransaction("aTransaction", "op") val span = transaction.startChild("op") val exception = RuntimeException() - hub.setSpanContext(exception, span, "tx-name") - hub.captureEvent(SentryEvent(exception)) + scopes.setSpanContext(exception, span, "tx-name") + scopes.captureEvent(SentryEvent(exception)) verify(mockClient).captureEvent( check { @@ -1816,8 +1816,8 @@ class HubTest { @Test fun `returns null when no span context associated with throwable`() { - val hub = generateHub() as Hub - assertNull(hub.getSpanContext(RuntimeException())) + val scopes = generateHub() as Hub + assertNull(scopes.getSpanContext(RuntimeException())) } // endregion @@ -1826,9 +1826,9 @@ class HubTest { val nativeMarker = File(hashedFolder(), EnvelopeCache.NATIVE_CRASH_MARKER_FILE) nativeMarker.mkdirs() nativeMarker.createNewFile() - val hub = generateHub() as Hub + val scopes = generateHub() as Hub - assertTrue(hub.isCrashedLastRun!!) + assertTrue(scopes.isCrashedLastRun!!) assertTrue(nativeMarker.exists()) } @@ -1837,69 +1837,69 @@ class HubTest { val nativeMarker = File(hashedFolder(), EnvelopeCache.NATIVE_CRASH_MARKER_FILE) nativeMarker.mkdirs() nativeMarker.createNewFile() - val hub = generateHub { + val scopes = generateHub { it.isEnableAutoSessionTracking = false } - assertTrue(hub.isCrashedLastRun!!) + assertTrue(scopes.isCrashedLastRun!!) assertFalse(nativeMarker.exists()) } @Test fun `reportFullyDisplayed is ignored if TimeToFullDisplayTracing is disabled`() { var called = false - val hub = generateHub { + val scopes = generateHub { it.fullyDisplayedReporter.registerFullyDrawnListener { called = !called } } - hub.reportFullyDisplayed() + scopes.reportFullyDisplayed() assertFalse(called) } @Test fun `reportFullyDisplayed calls FullyDisplayedReporter if TimeToFullDisplayTracing is enabled`() { var called = false - val hub = generateHub { + val scopes = generateHub { it.isEnableTimeToFullDisplayTracing = true it.fullyDisplayedReporter.registerFullyDrawnListener { called = !called } } - hub.reportFullyDisplayed() + scopes.reportFullyDisplayed() assertTrue(called) } @Test fun `reportFullyDisplayed calls FullyDisplayedReporter only once`() { var called = false - val hub = generateHub { + val scopes = generateHub { it.isEnableTimeToFullDisplayTracing = true it.fullyDisplayedReporter.registerFullyDrawnListener { called = !called } } - hub.reportFullyDisplayed() + scopes.reportFullyDisplayed() assertTrue(called) - hub.reportFullyDisplayed() + scopes.reportFullyDisplayed() assertTrue(called) } @Test fun `reportFullDisplayed calls reportFullyDisplayed`() { - val hub = spy(generateHub()) - hub.reportFullDisplayed() - verify(hub).reportFullyDisplayed() + val scopes = spy(generateHub()) + scopes.reportFullDisplayed() + verify(scopes).reportFullyDisplayed() } @Test fun `continueTrace creates propagation context from headers and returns transaction context if performance enabled`() { - val hub = generateHub() + val scopes = generateHub() val traceId = SentryId() val parentSpanId = SpanId() - val transactionContext = hub.continueTrace("$traceId-$parentSpanId-1", listOf("sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET")) + val transactionContext = scopes.continueTrace("$traceId-$parentSpanId-1", listOf("sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET")) - hub.configureScope { scope -> + scopes.configureScope { scope -> assertEquals(traceId, scope.propagationContext.traceId) assertEquals(parentSpanId, scope.propagationContext.parentSpanId) } @@ -1910,16 +1910,16 @@ class HubTest { @Test fun `continueTrace creates new propagation context if header invalid and returns transaction context if performance enabled`() { - val hub = generateHub() + val scopes = generateHub() val traceId = SentryId() var propagationContextHolder = AtomicReference() - hub.configureScope { propagationContextHolder.set(it.propagationContext) } + scopes.configureScope { propagationContextHolder.set(it.propagationContext) } val propagationContextAtStart = propagationContextHolder.get()!! - val transactionContext = hub.continueTrace("invalid", listOf("sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET")) + val transactionContext = scopes.continueTrace("invalid", listOf("sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET")) - hub.configureScope { scope -> + scopes.configureScope { scope -> assertNotEquals(propagationContextAtStart.traceId, scope.propagationContext.traceId) assertNotEquals(propagationContextAtStart.parentSpanId, scope.propagationContext.parentSpanId) assertNotEquals(propagationContextAtStart.spanId, scope.propagationContext.spanId) @@ -1932,12 +1932,12 @@ class HubTest { @Test fun `continueTrace creates propagation context from headers and returns null if performance disabled`() { - val hub = generateHub { it.enableTracing = false } + val scopes = generateHub { it.enableTracing = false } val traceId = SentryId() val parentSpanId = SpanId() - val transactionContext = hub.continueTrace("$traceId-$parentSpanId-1", listOf("sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET")) + val transactionContext = scopes.continueTrace("$traceId-$parentSpanId-1", listOf("sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET")) - hub.configureScope { scope -> + scopes.configureScope { scope -> assertEquals(traceId, scope.propagationContext.traceId) assertEquals(parentSpanId, scope.propagationContext.parentSpanId) } @@ -1947,16 +1947,16 @@ class HubTest { @Test fun `continueTrace creates new propagation context if header invalid and returns null if performance disabled`() { - val hub = generateHub { it.enableTracing = false } + val scopes = generateHub { it.enableTracing = false } val traceId = SentryId() var propagationContextHolder = AtomicReference() - hub.configureScope { propagationContextHolder.set(it.propagationContext) } + scopes.configureScope { propagationContextHolder.set(it.propagationContext) } val propagationContextAtStart = propagationContextHolder.get()!! - val transactionContext = hub.continueTrace("invalid", listOf("sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET")) + val transactionContext = scopes.continueTrace("invalid", listOf("sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=$traceId,sentry-transaction=HTTP%20GET")) - hub.configureScope { scope -> + scopes.configureScope { scope -> assertNotEquals(propagationContextAtStart.traceId, scope.propagationContext.traceId) assertNotEquals(propagationContextAtStart.parentSpanId, scope.propagationContext.parentSpanId) assertNotEquals(propagationContextAtStart.spanId, scope.propagationContext.spanId) @@ -1966,32 +1966,32 @@ class HubTest { } @Test - fun `hub provides no tags for metrics, if metric option is disabled`() { - val hub = generateHub { + fun `scopes provides no tags for metrics, if metric option is disabled`() { + val scopes = generateHub { it.isEnableMetrics = false it.isEnableDefaultTagsForMetrics = true } as Hub assertTrue( - hub.defaultTagsForMetrics.isEmpty() + scopes.defaultTagsForMetrics.isEmpty() ) } @Test - fun `hub provides no tags for metrics, if default tags option is disabled`() { - val hub = generateHub { + fun `scopes provides no tags for metrics, if default tags option is disabled`() { + val scopes = generateHub { it.isEnableMetrics = true it.isEnableDefaultTagsForMetrics = false } as Hub assertTrue( - hub.defaultTagsForMetrics.isEmpty() + scopes.defaultTagsForMetrics.isEmpty() ) } @Test - fun `hub provides minimum default tags for metrics, if nothing is set up`() { - val hub = generateHub { + fun `scopes provides minimum default tags for metrics, if nothing is set up`() { + val scopes = generateHub { it.isEnableMetrics = true it.isEnableDefaultTagsForMetrics = true } as Hub @@ -2000,19 +2000,19 @@ class HubTest { mapOf( "environment" to "production" ), - hub.defaultTagsForMetrics + scopes.defaultTagsForMetrics ) } @Test - fun `hub provides default tags for metrics, based on options and running transaction`() { - val hub = generateHub { + fun `scopes provides default tags for metrics, based on options and running transaction`() { + val scopes = generateHub { it.isEnableMetrics = true it.isEnableDefaultTagsForMetrics = true it.environment = "test" it.release = "1.0" } as Hub - hub.startTransaction( + scopes.startTransaction( "name", "op", TransactionOptions().apply { isBindToScope = true } @@ -2024,72 +2024,72 @@ class HubTest { "release" to "1.0", "transaction" to "name" ), - hub.defaultTagsForMetrics + scopes.defaultTagsForMetrics ) } @Test - fun `hub provides no local metric aggregator if metrics feature is disabled`() { - val hub = generateHub { + fun `scopes provides no local metric aggregator if metrics feature is disabled`() { + val scopes = generateHub { it.isEnableMetrics = false it.isEnableSpanLocalMetricAggregation = true } as Hub - hub.startTransaction( + scopes.startTransaction( "name", "op", TransactionOptions().apply { isBindToScope = true } ) - assertNull(hub.localMetricsAggregator) + assertNull(scopes.localMetricsAggregator) } @Test - fun `hub provides no local metric aggregator if local aggregation feature is disabled`() { - val hub = generateHub { + fun `scopes provides no local metric aggregator if local aggregation feature is disabled`() { + val scopes = generateHub { it.isEnableMetrics = true it.isEnableSpanLocalMetricAggregation = false } as Hub - hub.startTransaction( + scopes.startTransaction( "name", "op", TransactionOptions().apply { isBindToScope = true } ) - assertNull(hub.localMetricsAggregator) + assertNull(scopes.localMetricsAggregator) } @Test - fun `hub provides local metric aggregator if feature is enabled`() { - val hub = generateHub { + fun `scopes provides local metric aggregator if feature is enabled`() { + val scopes = generateHub { it.isEnableMetrics = true it.isEnableSpanLocalMetricAggregation = true } as Hub - hub.startTransaction( + scopes.startTransaction( "name", "op", TransactionOptions().apply { isBindToScope = true } ) - assertNotNull(hub.localMetricsAggregator) + assertNotNull(scopes.localMetricsAggregator) } @Test - fun `hub startSpanForMetric starts a child span`() { - val hub = generateHub { + fun `scopes startSpanForMetric starts a child span`() { + val scopes = generateHub { it.isEnableMetrics = true it.isEnableSpanLocalMetricAggregation = true it.sampleRate = 1.0 } as Hub - val txn = hub.startTransaction( + val txn = scopes.startTransaction( "name.txn", "op.txn", TransactionOptions().apply { isBindToScope = true } ) - val span = hub.startSpanForMetric("op", "key")!! + val span = scopes.startSpanForMetric("op", "key")!! assertEquals("op", span.spanContext.op) assertEquals("key", span.spanContext.description) @@ -2098,7 +2098,7 @@ class HubTest { private val dsnTest = "https://key@sentry.io/proj" - private fun generateHub(optionsConfiguration: Sentry.OptionsConfiguration? = null): IHub { + private fun generateHub(optionsConfiguration: Sentry.OptionsConfiguration? = null): IScopes { val options = SentryOptions().apply { dsn = dsnTest cacheDirPath = file.absolutePath diff --git a/sentry/src/test/java/io/sentry/JsonSerializerTest.kt b/sentry/src/test/java/io/sentry/JsonSerializerTest.kt index 8dc4f804bc..bd3a3c2cff 100644 --- a/sentry/src/test/java/io/sentry/JsonSerializerTest.kt +++ b/sentry/src/test/java/io/sentry/JsonSerializerTest.kt @@ -43,7 +43,7 @@ class JsonSerializerTest { private class Fixture { val logger: ILogger = mock() val serializer: ISerializer - val hub = mock() + val scopes = mock() val traceFile = Files.createTempFile("test", "here").toFile() val options = SentryOptions() @@ -51,7 +51,7 @@ class JsonSerializerTest { options.dsn = "https://key@sentry.io/proj" options.setLogger(logger) options.isDebug = true - whenever(hub.options).thenReturn(options) + whenever(scopes.options).thenReturn(options) serializer = JsonSerializer(options) options.setSerializer(serializer) options.setEnvelopeReader(EnvelopeReader(serializer)) @@ -830,7 +830,7 @@ class JsonSerializerTest { trace.status = SpanStatus.OK trace.setTag("myTag", "myValue") trace.sampled = true - val tracer = SentryTracer(trace, fixture.hub) + val tracer = SentryTracer(trace, fixture.scopes) tracer.setData("dataKey", "dataValue") val span = tracer.startChild("child") span.finish(SpanStatus.OK) @@ -1300,7 +1300,7 @@ class JsonSerializerTest { status = SpanStatus.OK setTag("myTag", "myValue") } - val tracer = SentryTracer(trace, fixture.hub) + val tracer = SentryTracer(trace, fixture.scopes) val span = tracer.startChild("child") span.setMeasurement("test_measurement", 1, MeasurementUnit.Custom("test")) span.finish(SpanStatus.OK) diff --git a/sentry/src/test/java/io/sentry/MainEventProcessorTest.kt b/sentry/src/test/java/io/sentry/MainEventProcessorTest.kt index ec932ebc86..682626f08c 100644 --- a/sentry/src/test/java/io/sentry/MainEventProcessorTest.kt +++ b/sentry/src/test/java/io/sentry/MainEventProcessorTest.kt @@ -33,7 +33,7 @@ class MainEventProcessorTest { dist = "dist" sdkVersion = SdkVersion("test", "1.2.3") } - val hub = mock() + val scopes = mock() val getLocalhost = mock() lateinit var sentryTracer: SentryTracer private val hostnameCacheMock = Mockito.mockStatic(HostnameCache::class.java) @@ -72,8 +72,8 @@ class MainEventProcessorTest { } host } - whenever(hub.options).thenReturn(sentryOptions) - sentryTracer = SentryTracer(TransactionContext("", ""), hub) + whenever(scopes.options).thenReturn(sentryOptions) + sentryTracer = SentryTracer(TransactionContext("", ""), scopes) val hostnameCache = HostnameCache(hostnameCacheDuration) { getLocalhost } hostnameCacheMock.`when` { HostnameCache.getInstance() }.thenReturn(hostnameCache) diff --git a/sentry/src/test/java/io/sentry/OutboxSenderTest.kt b/sentry/src/test/java/io/sentry/OutboxSenderTest.kt index ab50e054d0..9274ed4400 100644 --- a/sentry/src/test/java/io/sentry/OutboxSenderTest.kt +++ b/sentry/src/test/java/io/sentry/OutboxSenderTest.kt @@ -30,7 +30,7 @@ class OutboxSenderTest { private class Fixture { val options = mock() - val hub = mock() + val scopes = mock() var envelopeReader = mock() val serializer = mock() val logger = mock() @@ -39,11 +39,11 @@ class OutboxSenderTest { whenever(options.dsn).thenReturn("https://key@sentry.io/proj") whenever(options.dateProvider).thenReturn(SentryNanotimeDateProvider()) whenever(options.mainThreadChecker).thenReturn(NoOpMainThreadChecker.getInstance()) - whenever(hub.options).thenReturn(this.options) + whenever(scopes.options).thenReturn(this.options) } fun getSut(): OutboxSender { - return OutboxSender(hub, envelopeReader, serializer, logger, 15000, 30) + return OutboxSender(scopes, envelopeReader, serializer, logger, 15000, 30) } } @@ -83,7 +83,7 @@ class OutboxSenderTest { val hints = HintUtils.createWithTypeCheckHint(mock()) sut.processEnvelopeFile(path, hints) - verify(fixture.hub).captureEvent(eq(expected), any()) + verify(fixture.scopes).captureEvent(eq(expected), any()) assertFalse(File(path).exists()) // Additionally make sure we have no errors logged verify(fixture.logger, never()).log(eq(SentryLevel.ERROR), any(), any()) @@ -94,7 +94,7 @@ class OutboxSenderTest { fun `when parser is EnvelopeReader and serializer return SentryTransaction, transaction captured, transactions sampled, file is deleted`() { fixture.envelopeReader = EnvelopeReader(JsonSerializer(fixture.options)) whenever(fixture.options.maxSpans).thenReturn(1000) - whenever(fixture.hub.options).thenReturn(fixture.options) + whenever(fixture.scopes.options).thenReturn(fixture.options) whenever(fixture.options.transactionProfiler).thenReturn(NoOpTransactionProfiler.getInstance()) val transactionContext = TransactionContext("fixture-name", "http") @@ -102,7 +102,7 @@ class OutboxSenderTest { transactionContext.status = SpanStatus.OK transactionContext.setTag("fixture-tag", "fixture-value") - val sentryTracer = SentryTracer(transactionContext, fixture.hub) + val sentryTracer = SentryTracer(transactionContext, fixture.scopes) val span = sentryTracer.startChild("child") span.finish(SpanStatus.OK) sentryTracer.finish() @@ -120,7 +120,7 @@ class OutboxSenderTest { val hints = HintUtils.createWithTypeCheckHint(mock()) sut.processEnvelopeFile(path, hints) - verify(fixture.hub).captureTransaction( + verify(fixture.scopes).captureTransaction( check { assertEquals(expected, it) assertTrue(it.isSampled) @@ -139,7 +139,7 @@ class OutboxSenderTest { fun `restores sampleRate`() { fixture.envelopeReader = EnvelopeReader(JsonSerializer(fixture.options)) whenever(fixture.options.maxSpans).thenReturn(1000) - whenever(fixture.hub.options).thenReturn(fixture.options) + whenever(fixture.scopes.options).thenReturn(fixture.options) whenever(fixture.options.transactionProfiler).thenReturn(NoOpTransactionProfiler.getInstance()) val transactionContext = TransactionContext("fixture-name", "http") @@ -148,7 +148,7 @@ class OutboxSenderTest { transactionContext.setTag("fixture-tag", "fixture-value") transactionContext.samplingDecision = TracesSamplingDecision(true, 0.00000021) - val sentryTracer = SentryTracer(transactionContext, fixture.hub) + val sentryTracer = SentryTracer(transactionContext, fixture.scopes) val span = sentryTracer.startChild("child") span.finish(SpanStatus.OK) sentryTracer.finish() @@ -166,7 +166,7 @@ class OutboxSenderTest { val hints = HintUtils.createWithTypeCheckHint(mock()) sut.processEnvelopeFile(path, hints) - verify(fixture.hub).captureTransaction( + verify(fixture.scopes).captureTransaction( check { assertEquals(expected, it) assertTrue(it.isSampled) @@ -207,7 +207,7 @@ class OutboxSenderTest { val hints = HintUtils.createWithTypeCheckHint(mock()) sut.processEnvelopeFile(path, hints) - verify(fixture.hub).captureEvent(any(), any()) + verify(fixture.scopes).captureEvent(any(), any()) assertFalse(File(path).exists()) // Additionally make sure we have no errors logged verify(fixture.logger, never()).log(eq(SentryLevel.ERROR), any(), any()) @@ -225,7 +225,7 @@ class OutboxSenderTest { val hints = HintUtils.createWithTypeCheckHint(mock()) sut.processEnvelopeFile(path, hints) - verify(fixture.hub).captureEnvelope(any(), any()) + verify(fixture.scopes).captureEnvelope(any(), any()) assertFalse(File(path).exists()) // Additionally make sure we have no errors logged verify(fixture.logger, never()).log(eq(SentryLevel.ERROR), any(), any()) @@ -245,7 +245,7 @@ class OutboxSenderTest { // Additionally make sure we have no errors logged verify(fixture.logger).log(eq(SentryLevel.ERROR), any(), any()) - verify(fixture.hub, never()).captureEvent(any()) + verify(fixture.scopes, never()).captureEvent(any()) assertFalse(File(path).exists()) } @@ -263,7 +263,7 @@ class OutboxSenderTest { // Additionally make sure we have no errors logged verify(fixture.logger).log(eq(SentryLevel.ERROR), any(), any()) - verify(fixture.hub, never()).captureEvent(any()) + verify(fixture.scopes, never()).captureEvent(any()) assertFalse(File(path).exists()) } diff --git a/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt b/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt index 239e90905e..87aa5e6715 100644 --- a/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt +++ b/sentry/src/test/java/io/sentry/PreviousSessionFinalizerTest.kt @@ -21,7 +21,7 @@ class PreviousSessionFinalizerTest { class Fixture { val options = SentryOptions() - val hub = mock() + val scopes = mock() val logger = mock() lateinit var sessionFile: File @@ -61,7 +61,7 @@ class PreviousSessionFinalizerTest { nativeCrashMarker.writeText(nativeCrashTimestamp.toString()) } } - return PreviousSessionFinalizer(options, hub) + return PreviousSessionFinalizer(options, scopes) } fun sessionFromEnvelope(envelope: SentryEnvelope): Session { @@ -80,7 +80,7 @@ class PreviousSessionFinalizerTest { val finalizer = fixture.getSut(null) finalizer.run() - verify(fixture.hub, never()).captureEnvelope(any()) + verify(fixture.scopes, never()).captureEnvelope(any()) } @Test @@ -88,7 +88,7 @@ class PreviousSessionFinalizerTest { val finalizer = fixture.getSut(tmpDir, sessionFileExists = false) finalizer.run() - verify(fixture.hub, never()).captureEnvelope(any()) + verify(fixture.scopes, never()).captureEnvelope(any()) } @Test @@ -96,7 +96,7 @@ class PreviousSessionFinalizerTest { val finalizer = fixture.getSut(tmpDir, sessionFileExists = true, session = null) finalizer.run() - verify(fixture.hub, never()).captureEnvelope(any()) + verify(fixture.scopes, never()).captureEnvelope(any()) } @Test @@ -107,7 +107,7 @@ class PreviousSessionFinalizerTest { ) finalizer.run() - verify(fixture.hub).captureEnvelope( + verify(fixture.scopes).captureEnvelope( argThat { val session = fixture.sessionFromEnvelope(this) session.release == "io.sentry.sample@1.0" && @@ -133,7 +133,7 @@ class PreviousSessionFinalizerTest { ) finalizer.run() - verify(fixture.hub).captureEnvelope( + verify(fixture.scopes).captureEnvelope( argThat { val session = fixture.sessionFromEnvelope(this) session.release == "io.sentry.sample@1.0" && @@ -156,7 +156,7 @@ class PreviousSessionFinalizerTest { ) finalizer.run() - verify(fixture.hub).captureEnvelope( + verify(fixture.scopes).captureEnvelope( argThat { val session = fixture.sessionFromEnvelope(this) session.release == "io.sentry.sample@1.0" && @@ -170,7 +170,7 @@ class PreviousSessionFinalizerTest { val finalizer = fixture.getSut(tmpDir, sessionFileExists = true) finalizer.run() - verify(fixture.hub, never()).captureEnvelope(any()) + verify(fixture.scopes, never()).captureEnvelope(any()) assertFalse(fixture.sessionFile.exists()) } @@ -189,7 +189,7 @@ class PreviousSessionFinalizerTest { argThat { startsWith("Timed out waiting to flush previous session to its own file in session finalizer.") }, any() ) - verify(fixture.hub, never()).captureEnvelope(any()) + verify(fixture.scopes, never()).captureEnvelope(any()) } @Test @@ -202,6 +202,6 @@ class PreviousSessionFinalizerTest { argThat { startsWith("Timed out waiting to flush previous session to its own file in session finalizer.") }, any() ) - verify(fixture.hub, never()).captureEnvelope(any()) + verify(fixture.scopes, never()).captureEnvelope(any()) } } diff --git a/sentry/src/test/java/io/sentry/ScopeTest.kt b/sentry/src/test/java/io/sentry/ScopeTest.kt index 906c897c62..86794d7b19 100644 --- a/sentry/src/test/java/io/sentry/ScopeTest.kt +++ b/sentry/src/test/java/io/sentry/ScopeTest.kt @@ -114,7 +114,7 @@ class ScopeTest { scope.setExtra("extra", "extra") val transaction = - SentryTracer(TransactionContext("transaction-name", "op"), NoOpHub.getInstance()) + SentryTracer(TransactionContext("transaction-name", "op"), NoOpScopes.getInstance()) scope.transaction = transaction val attachment = Attachment("path/log.txt") @@ -192,7 +192,7 @@ class ScopeTest { scope.setTransaction( SentryTracer( TransactionContext("newTransaction", "op"), - NoOpHub.getInstance() + NoOpScopes.getInstance() ) ) @@ -265,7 +265,7 @@ class ScopeTest { fun `clear scope resets scope to default state`() { val scope = Scope(SentryOptions()) scope.level = SentryLevel.WARNING - scope.setTransaction(SentryTracer(TransactionContext("", "op"), NoOpHub.getInstance())) + scope.setTransaction(SentryTracer(TransactionContext("", "op"), NoOpScopes.getInstance())) scope.user = User() scope.request = Request() scope.fingerprint = mutableListOf("finger") @@ -822,7 +822,7 @@ class ScopeTest { @Test fun `Scope getTransaction returns the transaction if there is no active span`() { val scope = Scope(SentryOptions()) - val transaction = SentryTracer(TransactionContext("name", "op"), NoOpHub.getInstance()) + val transaction = SentryTracer(TransactionContext("name", "op"), NoOpScopes.getInstance()) scope.transaction = transaction assertEquals(transaction, scope.span) } @@ -830,7 +830,7 @@ class ScopeTest { @Test fun `Scope getTransaction returns the current span if there is an unfinished span`() { val scope = Scope(SentryOptions()) - val transaction = SentryTracer(TransactionContext("name", "op"), NoOpHub.getInstance()) + val transaction = SentryTracer(TransactionContext("name", "op"), NoOpScopes.getInstance()) scope.transaction = transaction val span = transaction.startChild("op") assertEquals(span, scope.span) @@ -839,7 +839,7 @@ class ScopeTest { @Test fun `Scope getTransaction returns the current span if there is a finished span`() { val scope = Scope(SentryOptions()) - val transaction = SentryTracer(TransactionContext("name", "op"), NoOpHub.getInstance()) + val transaction = SentryTracer(TransactionContext("name", "op"), NoOpScopes.getInstance()) scope.transaction = transaction val span = transaction.startChild("op") span.finish() @@ -849,7 +849,7 @@ class ScopeTest { @Test fun `Scope getTransaction returns the latest span if there is a list of active span`() { val scope = Scope(SentryOptions()) - val transaction = SentryTracer(TransactionContext("name", "op"), NoOpHub.getInstance()) + val transaction = SentryTracer(TransactionContext("name", "op"), NoOpScopes.getInstance()) scope.transaction = transaction val span = transaction.startChild("op") val innerSpan = span.startChild("op") @@ -859,7 +859,7 @@ class ScopeTest { @Test fun `Scope setTransaction sets transaction name`() { val scope = Scope(SentryOptions()) - val transaction = SentryTracer(TransactionContext("name", "op"), NoOpHub.getInstance()) + val transaction = SentryTracer(TransactionContext("name", "op"), NoOpScopes.getInstance()) scope.transaction = transaction scope.setTransaction("new-name") assertNotNull(scope.transaction) { @@ -871,7 +871,7 @@ class ScopeTest { @Test fun `Scope setTransaction with null does not clear transaction`() { val scope = Scope(SentryOptions()) - val transaction = SentryTracer(TransactionContext("name", "op"), NoOpHub.getInstance()) + val transaction = SentryTracer(TransactionContext("name", "op"), NoOpScopes.getInstance()) scope.transaction = transaction scope.callMethod("setTransaction", String::class.java, null) assertNotNull(scope.transaction) @@ -936,7 +936,7 @@ class ScopeTest { fun `when transaction is started, sets transaction name on the transaction object`() { val scope = Scope(SentryOptions()) val sentryTransaction = - SentryTracer(TransactionContext("transaction-name", "op"), NoOpHub.getInstance()) + SentryTracer(TransactionContext("transaction-name", "op"), NoOpScopes.getInstance()) scope.transaction = sentryTransaction assertEquals("transaction-name", scope.transactionName) scope.setTransaction("new-name") @@ -950,7 +950,7 @@ class ScopeTest { val scope = Scope(SentryOptions()) scope.setTransaction("transaction-a") val sentryTransaction = - SentryTracer(TransactionContext("transaction-name", "op"), NoOpHub.getInstance()) + SentryTracer(TransactionContext("transaction-name", "op"), NoOpScopes.getInstance()) scope.setTransaction(sentryTransaction) assertEquals("transaction-name", scope.transactionName) scope.clearTransaction() @@ -961,7 +961,7 @@ class ScopeTest { fun `withTransaction returns the current Transaction bound to the Scope`() { val scope = Scope(SentryOptions()) val sentryTransaction = - SentryTracer(TransactionContext("transaction-name", "op"), NoOpHub.getInstance()) + SentryTracer(TransactionContext("transaction-name", "op"), NoOpScopes.getInstance()) scope.setTransaction(sentryTransaction) scope.withTransaction { diff --git a/sentry/src/test/java/io/sentry/ScopesAdapterTest.kt b/sentry/src/test/java/io/sentry/ScopesAdapterTest.kt new file mode 100644 index 0000000000..85a0b6ef75 --- /dev/null +++ b/sentry/src/test/java/io/sentry/ScopesAdapterTest.kt @@ -0,0 +1,265 @@ +package io.sentry + +import io.sentry.protocol.SentryTransaction +import io.sentry.protocol.User +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.reset +import org.mockito.kotlin.verify +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test + +class ScopesAdapterTest { + + val scopes: IScopes = mock() + + @BeforeTest + fun `set up`() { + Sentry.setCurrentScopes(scopes) + } + + @AfterTest + fun shutdown() { + Sentry.close() + } + + @Test fun `isEnabled calls Hub`() { + ScopesAdapter.getInstance().isEnabled + verify(scopes).isEnabled + } + + @Test fun `captureEvent calls Hub`() { + val event = mock() + val hint = mock() + val scopeCallback = mock() + ScopesAdapter.getInstance().captureEvent(event, hint) + verify(scopes).captureEvent(eq(event), eq(hint)) + + ScopesAdapter.getInstance().captureEvent(event, hint, scopeCallback) + verify(scopes).captureEvent(eq(event), eq(hint), eq(scopeCallback)) + } + + @Test fun `captureMessage calls Hub`() { + val scopeCallback = mock() + val sentryLevel = mock() + ScopesAdapter.getInstance().captureMessage("message", sentryLevel) + verify(scopes).captureMessage(eq("message"), eq(sentryLevel)) + + ScopesAdapter.getInstance().captureMessage("message", sentryLevel, scopeCallback) + verify(scopes).captureMessage(eq("message"), eq(sentryLevel), eq(scopeCallback)) + } + + @Test fun `captureEnvelope calls Hub`() { + val envelope = mock() + val hint = mock() + ScopesAdapter.getInstance().captureEnvelope(envelope, hint) + verify(scopes).captureEnvelope(eq(envelope), eq(hint)) + } + + @Test fun `captureException calls Hub`() { + val throwable = mock() + val hint = mock() + val scopeCallback = mock() + ScopesAdapter.getInstance().captureException(throwable, hint) + verify(scopes).captureException(eq(throwable), eq(hint)) + + ScopesAdapter.getInstance().captureException(throwable, hint, scopeCallback) + verify(scopes).captureException(eq(throwable), eq(hint), eq(scopeCallback)) + } + + @Test fun `captureUserFeedback calls Hub`() { + val userFeedback = mock() + ScopesAdapter.getInstance().captureUserFeedback(userFeedback) + verify(scopes).captureUserFeedback(eq(userFeedback)) + } + + @Test fun `captureCheckIn calls Hub`() { + val checkIn = mock() + ScopesAdapter.getInstance().captureCheckIn(checkIn) + verify(scopes).captureCheckIn(eq(checkIn)) + } + + @Test fun `startSession calls Hub`() { + ScopesAdapter.getInstance().startSession() + verify(scopes).startSession() + } + + @Test fun `endSession calls Hub`() { + ScopesAdapter.getInstance().endSession() + verify(scopes).endSession() + } + + @Test fun `close calls Hub`() { + ScopesAdapter.getInstance().close() + verify(scopes).close(false) + } + + @Test fun `close with isRestarting true calls Hub with isRestarting false`() { + ScopesAdapter.getInstance().close(true) + verify(scopes).close(false) + } + + @Test fun `close with isRestarting false calls Hub with isRestarting false`() { + ScopesAdapter.getInstance().close(false) + verify(scopes).close(false) + } + + @Test fun `addBreadcrumb calls Hub`() { + val breadcrumb = mock() + val hint = mock() + ScopesAdapter.getInstance().addBreadcrumb(breadcrumb, hint) + verify(scopes).addBreadcrumb(eq(breadcrumb), eq(hint)) + } + + @Test fun `setLevel calls Hub`() { + val sentryLevel = mock() + ScopesAdapter.getInstance().setLevel(sentryLevel) + verify(scopes).setLevel(eq(sentryLevel)) + } + + @Test fun `setTransaction calls Hub`() { + ScopesAdapter.getInstance().setTransaction("transaction") + verify(scopes).setTransaction(eq("transaction")) + } + + @Test fun `setUser calls Hub`() { + val user = mock() + ScopesAdapter.getInstance().setUser(user) + verify(scopes).setUser(eq(user)) + } + + @Test fun `setFingerprint calls Hub`() { + val fingerprint = ArrayList() + ScopesAdapter.getInstance().setFingerprint(fingerprint) + verify(scopes).setFingerprint(eq(fingerprint)) + } + + @Test fun `clearBreadcrumbs calls Hub`() { + ScopesAdapter.getInstance().clearBreadcrumbs() + verify(scopes).clearBreadcrumbs() + } + + @Test fun `setTag calls Hub`() { + ScopesAdapter.getInstance().setTag("key", "value") + verify(scopes).setTag(eq("key"), eq("value")) + } + + @Test fun `removeTag calls Hub`() { + ScopesAdapter.getInstance().removeTag("key") + verify(scopes).removeTag(eq("key")) + } + + @Test fun `setExtra calls Hub`() { + ScopesAdapter.getInstance().setExtra("key", "value") + verify(scopes).setExtra(eq("key"), eq("value")) + } + + @Test fun `removeExtra calls Hub`() { + ScopesAdapter.getInstance().removeExtra("key") + verify(scopes).removeExtra(eq("key")) + } + + @Test fun `getLastEventId calls Hub`() { + ScopesAdapter.getInstance().lastEventId + verify(scopes).lastEventId + } + + @Test fun `pushScope calls Hub`() { + ScopesAdapter.getInstance().pushScope() + verify(scopes).pushScope() + } + + @Test fun `popScope calls Hub`() { + ScopesAdapter.getInstance().popScope() + verify(scopes).popScope() + } + + @Test fun `withScope calls Hub`() { + val scopeCallback = mock() + ScopesAdapter.getInstance().withScope(scopeCallback) + verify(scopes).withScope(eq(scopeCallback)) + } + + @Test fun `configureScope calls Hub`() { + val scopeCallback = mock() + ScopesAdapter.getInstance().configureScope(scopeCallback) + verify(scopes).configureScope(eq(scopeCallback)) + } + + @Test fun `bindClient calls Hub`() { + val client = mock() + ScopesAdapter.getInstance().bindClient(client) + verify(scopes).bindClient(eq(client)) + } + + @Test fun `flush calls Hub`() { + ScopesAdapter.getInstance().flush(1) + verify(scopes).flush(eq(1)) + } + + @Test fun `clone calls Hub`() { + ScopesAdapter.getInstance().clone() + verify(scopes).clone() + } + + @Test fun `captureTransaction calls Hub`() { + val transaction = mock() + val traceContext = mock() + val hint = mock() + val profilingTraceData = mock() + ScopesAdapter.getInstance().captureTransaction(transaction, traceContext, hint, profilingTraceData) + verify(scopes).captureTransaction(eq(transaction), eq(traceContext), eq(hint), eq(profilingTraceData)) + } + + @Test fun `startTransaction calls Hub`() { + val transactionContext = mock() + val samplingContext = mock() + val transactionOptions = mock() + ScopesAdapter.getInstance().startTransaction(transactionContext) + verify(scopes).startTransaction(eq(transactionContext), any()) + + reset(scopes) + + ScopesAdapter.getInstance().startTransaction(transactionContext, transactionOptions) + verify(scopes).startTransaction(eq(transactionContext), eq(transactionOptions)) + } + + @Test fun `traceHeaders calls Hub`() { + ScopesAdapter.getInstance().traceHeaders() + verify(scopes).traceHeaders() + } + + @Test fun `setSpanContext calls Hub`() { + val throwable = mock() + val span = mock() + ScopesAdapter.getInstance().setSpanContext(throwable, span, "transactionName") + verify(scopes).setSpanContext(eq(throwable), eq(span), eq("transactionName")) + } + + @Test fun `getSpan calls Hub`() { + ScopesAdapter.getInstance().span + verify(scopes).span + } + + @Test fun `getTransaction calls Hub`() { + ScopesAdapter.getInstance().transaction + verify(scopes).transaction + } + + @Test fun `getOptions calls Hub`() { + ScopesAdapter.getInstance().options + verify(scopes).options + } + + @Test fun `isCrashedLastRun calls Hub`() { + ScopesAdapter.getInstance().isCrashedLastRun + verify(scopes).isCrashedLastRun + } + + @Test fun `reportFullyDisplayed calls Hub`() { + ScopesAdapter.getInstance().reportFullyDisplayed() + verify(scopes).reportFullyDisplayed() + } +} diff --git a/sentry/src/test/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegrationTest.kt b/sentry/src/test/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegrationTest.kt index 78623f90a7..beed31a198 100644 --- a/sentry/src/test/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegrationTest.kt +++ b/sentry/src/test/java/io/sentry/SendCachedEnvelopeFireAndForgetIntegrationTest.kt @@ -19,7 +19,7 @@ import kotlin.test.assertTrue class SendCachedEnvelopeFireAndForgetIntegrationTest { private class Fixture { - var hub: IHub = mock() + var scopes: IScopes = mock() var logger: ILogger = mock() var options = SentryOptions() val sender = mock() @@ -45,7 +45,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { fun `when cacheDirPath returns null, register logs and exit`() { fixture.options.cacheDirPath = null val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) verify(fixture.logger).log(eq(SentryLevel.ERROR), eq("No cache dir path is defined in options.")) verify(fixture.sender, never()).send() } @@ -73,7 +73,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { val sut = SendCachedEnvelopeFireAndForgetIntegration(CustomFactory()) fixture.options.cacheDirPath = "abc" fixture.options.executorService = ImmediateExecutorService() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) verify(fixture.logger).log(eq(SentryLevel.ERROR), eq("SendFireAndForget factory is null.")) verify(fixture.sender, never()).send() } @@ -85,7 +85,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { mock() ) val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) assertNotNull(fixture.options.sdkVersion) assert(fixture.options.sdkVersion!!.integrationSet.contains("SendCachedEnvelopeFireAndForget")) } @@ -96,7 +96,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { fixture.options.executorService.close(0) whenever(fixture.callback.create(any(), any())).thenReturn(mock()) val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) verify(fixture.logger).log(eq(SentryLevel.ERROR), eq("Failed to call the executor. Cached events will not be sent. Did you call Sentry.close()?"), any()) } @@ -108,7 +108,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { fixture.options.cacheDirPath = "cache" val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) verify(connectionStatusProvider).addConnectionStatusObserver(any()) } @@ -122,9 +122,9 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { fixture.options.cacheDirPath = "cache" val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) verify(fixture.sender, never()).send() } @@ -139,7 +139,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { fixture.options.cacheDirPath = "cache" val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) verify(fixture.sender).send() } @@ -155,7 +155,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { fixture.options.cacheDirPath = "cache" val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) // when there's no connection no factory create call should be done verify(fixture.sender, never()).send() @@ -183,9 +183,9 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { val rateLimiter = mock { whenever(mock.isActiveForCategory(any())).thenReturn(true) } - whenever(fixture.hub.rateLimiter).thenReturn(rateLimiter) + whenever(fixture.scopes.rateLimiter).thenReturn(rateLimiter) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) // no factory call should be done if there's rate limiting active verify(fixture.sender, never()).send() @@ -196,8 +196,8 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { fixture.options.executorService = ImmediateExecutorService() fixture.options.cacheDirPath = "cache" val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) - verify(fixture.callback).create(eq(fixture.hub), eq(fixture.options)) + sut.register(fixture.scopes, fixture.options) + verify(fixture.callback).create(eq(fixture.scopes), eq(fixture.options)) } @Test @@ -205,7 +205,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { fixture.options.executorService = mock() fixture.options.cacheDirPath = "cache" val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) verify(fixture.callback, never()).create(any(), any()) } @@ -215,7 +215,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { fixture.options.executorService = deferredExecutorService val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) verify(fixture.sender, never()).send() sut.close() @@ -224,7 +224,7 @@ class SendCachedEnvelopeFireAndForgetIntegrationTest { } private class CustomFactory : SendCachedEnvelopeFireAndForgetIntegration.SendFireAndForgetFactory { - override fun create(hub: IHub, options: SentryOptions): SendCachedEnvelopeFireAndForgetIntegration.SendFireAndForget? { + override fun create(scopes: IScopes, options: SentryOptions): SendCachedEnvelopeFireAndForgetIntegration.SendFireAndForget? { return null } } diff --git a/sentry/src/test/java/io/sentry/SentryClientTest.kt b/sentry/src/test/java/io/sentry/SentryClientTest.kt index de540bf90c..eac2b0be29 100644 --- a/sentry/src/test/java/io/sentry/SentryClientTest.kt +++ b/sentry/src/test/java/io/sentry/SentryClientTest.kt @@ -70,7 +70,7 @@ class SentryClientTest { var transport = mock() var factory = mock() val maxAttachmentSize: Long = (5 * 1024 * 1024).toLong() - val hub = mock() + val scopes = mock() val sentryTracer: SentryTracer var sentryOptions: SentryOptions = SentryOptions().apply { @@ -88,8 +88,8 @@ class SentryClientTest { init { whenever(factory.create(any(), any())).thenReturn(transport) - whenever(hub.options).thenReturn(sentryOptions) - sentryTracer = SentryTracer(TransactionContext("a-transaction", "op"), hub) + whenever(scopes.options).thenReturn(sentryOptions) + sentryTracer = SentryTracer(TransactionContext("a-transaction", "op"), scopes) } var attachment = Attachment("hello".toByteArray(), "hello.txt", "text/plain", true) @@ -1456,9 +1456,9 @@ class SentryClientTest { @Test fun `when captureTransaction with scope, transaction should use user data`() { - val hub: IHub = mock() - whenever(hub.options).thenReturn(SentryOptions()) - val transaction = SentryTransaction(SentryTracer(TransactionContext("tx", "op"), hub)) + val scopes: IScopes = mock() + whenever(scopes.options).thenReturn(SentryOptions()) + val transaction = SentryTransaction(SentryTracer(TransactionContext("tx", "op"), scopes)) val scope = createScope() val sut = fixture.getSut() @@ -1487,7 +1487,7 @@ class SentryClientTest { val event = SentryEvent() val sut = fixture.getSut() val scope = createScope() - val transaction = SentryTracer(TransactionContext("a-transaction", "op"), fixture.hub) + val transaction = SentryTracer(TransactionContext("a-transaction", "op"), fixture.scopes) scope.setTransaction(transaction) val span = transaction.startChild("op") sut.captureEvent(event, scope) @@ -1558,7 +1558,7 @@ class SentryClientTest { fixture.sentryOptions.release = "optionsRelease" fixture.sentryOptions.environment = "optionsEnvironment" val sut = fixture.getSut() - val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.hub) + val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.scopes) val transaction = SentryTransaction(sentryTracer) transaction.release = "transactionRelease" transaction.environment = "transactionEnvironment" @@ -1571,7 +1571,7 @@ class SentryClientTest { fun `when transaction does not have SDK version set, and the SDK version is set on options, options values are applied to transactions`() { fixture.sentryOptions.sdkVersion = SdkVersion("sdk.name", "version") val sut = fixture.getSut() - val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.hub) + val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.scopes) val transaction = SentryTransaction(sentryTracer) sut.captureTransaction(transaction, sentryTracer.traceContext()) assertEquals(fixture.sentryOptions.sdkVersion, transaction.sdk) @@ -1581,7 +1581,7 @@ class SentryClientTest { fun `when transaction has SDK version set, and the SDK version is set on options, options values are not applied to transactions`() { fixture.sentryOptions.sdkVersion = SdkVersion("sdk.name", "version") val sut = fixture.getSut() - val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.hub) + val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.scopes) val transaction = SentryTransaction(sentryTracer) val sdkVersion = SdkVersion("transaction.sdk.name", "version") transaction.sdk = sdkVersion @@ -1593,7 +1593,7 @@ class SentryClientTest { fun `when transaction does not have tags, and tags are set on options, options values are applied to transactions`() { fixture.sentryOptions.setTag("tag1", "value1") val sut = fixture.getSut() - val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.hub) + val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.scopes) val transaction = SentryTransaction(sentryTracer) sut.captureTransaction(transaction, sentryTracer.traceContext()) assertEquals(mapOf("tag1" to "value1"), transaction.tags) @@ -1604,7 +1604,7 @@ class SentryClientTest { fixture.sentryOptions.setTag("tag1", "value1") fixture.sentryOptions.setTag("tag2", "value2") val sut = fixture.getSut() - val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.hub) + val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.scopes) val transaction = SentryTransaction(sentryTracer) transaction.setTag("tag3", "value3") transaction.setTag("tag2", "transaction-tag") @@ -1618,7 +1618,7 @@ class SentryClientTest { @Test fun `captured transactions without a platform, have the default platform set`() { val sut = fixture.getSut() - val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.hub) + val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.scopes) val transaction = SentryTransaction(sentryTracer) sut.captureTransaction(transaction, sentryTracer.traceContext()) assertEquals("java", transaction.platform) @@ -1627,7 +1627,7 @@ class SentryClientTest { @Test fun `captured transactions with a platform, do not get the platform overwritten`() { val sut = fixture.getSut() - val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.hub) + val sentryTracer = SentryTracer(TransactionContext("name", "op"), fixture.scopes) val transaction = SentryTransaction(sentryTracer) transaction.platform = "abc" sut.captureTransaction(transaction, sentryTracer.traceContext()) diff --git a/sentry/src/test/java/io/sentry/SentryTest.kt b/sentry/src/test/java/io/sentry/SentryTest.kt index 0f4966b44a..70728d2900 100644 --- a/sentry/src/test/java/io/sentry/SentryTest.kt +++ b/sentry/src/test/java/io/sentry/SentryTest.kt @@ -63,27 +63,27 @@ class SentryTest { } @Test - fun `init multiple times calls hub close with isRestarting true`() { - val hub = mock() + fun `init multiple times calls scopes close with isRestarting true`() { + val scopes = mock() Sentry.init { it.dsn = dsn } - Sentry.setCurrentHub(hub) + Sentry.setCurrentScopes(scopes) Sentry.init { it.dsn = dsn } - verify(hub).close(eq(true)) + verify(scopes).close(eq(true)) } @Test - fun `close calls hub close with isRestarting false`() { - val hub = mock() + fun `close calls scopes close with isRestarting false`() { + val scopes = mock() Sentry.init { it.dsn = dsn } - Sentry.setCurrentHub(hub) + Sentry.setCurrentScopes(scopes) Sentry.close() - verify(hub).close(eq(false)) + verify(scopes).close(eq(false)) } @Test @@ -213,7 +213,7 @@ class SentryTest { Sentry.init { it.isEnableExternalConfiguration = true } - assertTrue(HubAdapter.getInstance().isEnabled) + assertTrue(ScopesAdapter.getInstance().isEnabled) } finally { temporaryFolder.delete() } @@ -229,10 +229,10 @@ class SentryTest { Sentry.setTag("none", "shouldNotExist") var value: String? = null - Sentry.getCurrentHub().configureScope { + Sentry.getCurrentScopes().configureScope { value = it.tags[value] } - assertTrue(Sentry.getCurrentHub() is NoOpHub) + assertTrue(Sentry.getCurrentScopes().isNoOp) assertNull(value) } @@ -245,10 +245,10 @@ class SentryTest { Sentry.setTag("none", "shouldNotExist") var value: String? = null - Sentry.getCurrentHub().configureScope { + Sentry.getCurrentScopes().configureScope { value = it.tags[value] } - assertTrue(Sentry.getCurrentHub() is NoOpHub) + assertTrue(Sentry.getCurrentScopes().isNoOp) assertNull(value) } @@ -267,7 +267,7 @@ class SentryTest { Sentry.init { it.dsn = dsn } val client = mock() - Sentry.getCurrentHub().bindClient(client) + Sentry.getCurrentScopes().bindClient(client) val userFeedback = UserFeedback(SentryId.EMPTY_ID) Sentry.captureUserFeedback(userFeedback) @@ -369,11 +369,11 @@ class SentryTest { } @Test - fun `using sentry before calling init creates NoOpHub but after init Sentry uses a new clone`() { - // noop as not yet initialized, caches NoOpHub in ThreadLocal + fun `using sentry before calling init creates NoOpScopes but after init Sentry uses a new clone`() { + // noop as not yet initialized, caches NoOpScopes in ThreadLocal Sentry.captureMessage("noop caused") - assertTrue(Sentry.getCurrentHub() is NoOpHub) + assertTrue(Sentry.getCurrentScopes().isNoOp) // init Sentry in another thread val thread = Thread() { @@ -387,18 +387,18 @@ class SentryTest { Sentry.captureMessage("should work now") - val hub = Sentry.getCurrentHub() - assertNotNull(hub) - assertFalse(hub is NoOpHub) + val scopes = Sentry.getCurrentScopes() + assertNotNull(scopes) + assertFalse(scopes.isNoOp) } @Test - fun `main hub can be cloned and does not share scope with current hub`() { - // noop as not yet initialized, caches NoOpHub in ThreadLocal + fun `main scopes can be cloned and does not share scope with current scopes`() { + // noop as not yet initialized, caches NoOpScopes in ThreadLocal Sentry.addBreadcrumb("breadcrumbNoOp") Sentry.captureMessage("messageNoOp") - assertTrue(Sentry.getCurrentHub() is NoOpHub) + assertTrue(Sentry.getCurrentScopes().isNoOp) val capturedEvents = mutableListOf() @@ -418,14 +418,14 @@ class SentryTest { Sentry.addBreadcrumb("breadcrumbCurrent") - val hub = Sentry.getCurrentHub() - assertNotNull(hub) - assertFalse(hub is NoOpHub) + val scopes = Sentry.getCurrentScopes() + assertNotNull(scopes) + assertFalse(Sentry.getCurrentScopes().isNoOp) val newMainHubClone = Sentry.cloneMainHub() newMainHubClone.addBreadcrumb("breadcrumbMainClone") - hub.captureMessage("messageCurrent") + scopes.captureMessage("messageCurrent") newMainHubClone.captureMessage("messageMainClone") assertEquals(2, capturedEvents.size) @@ -444,12 +444,12 @@ class SentryTest { } @Test - fun `main hub is not cloned in global hub mode and shares scope with current hub`() { - // noop as not yet initialized, caches NoOpHub in ThreadLocal + fun `main scopes is not cloned in global scopes mode and shares scope with current scopes`() { + // noop as not yet initialized, caches NoOpScopes in ThreadLocal Sentry.addBreadcrumb("breadcrumbNoOp") Sentry.captureMessage("messageNoOp") - assertTrue(Sentry.getCurrentHub() is NoOpHub) + assertTrue(Sentry.getCurrentScopes().isNoOp) val capturedEvents = mutableListOf() @@ -469,14 +469,14 @@ class SentryTest { Sentry.addBreadcrumb("breadcrumbCurrent") - val hub = Sentry.getCurrentHub() - assertNotNull(hub) - assertFalse(hub is NoOpHub) + val scopes = Sentry.getCurrentScopes() + assertNotNull(scopes) + assertFalse(scopes.isNoOp) val newMainHubClone = Sentry.cloneMainHub() newMainHubClone.addBreadcrumb("breadcrumbMainClone") - hub.captureMessage("messageCurrent") + scopes.captureMessage("messageCurrent") newMainHubClone.captureMessage("messageMainClone") assertEquals(2, capturedEvents.size) @@ -669,25 +669,25 @@ class SentryTest { } @Test - fun `reportFullyDisplayed calls hub reportFullyDisplayed`() { - val hub = mock() + fun `reportFullyDisplayed calls scopes reportFullyDisplayed`() { + val scopes = mock() Sentry.init { it.dsn = dsn } - Sentry.setCurrentHub(hub) + Sentry.setCurrentScopes(scopes) Sentry.reportFullyDisplayed() - verify(hub).reportFullyDisplayed() + verify(scopes).reportFullyDisplayed() } @Test fun `reportFullDisplayed calls reportFullyDisplayed`() { - val hub = mock() + val scopes = mock() Sentry.init { it.dsn = dsn } - Sentry.setCurrentHub(hub) + Sentry.setCurrentScopes(scopes) Sentry.reportFullDisplayed() - verify(hub).reportFullyDisplayed() + verify(scopes).reportFullyDisplayed() } @Test @@ -806,11 +806,11 @@ class SentryTest { it.serializer.deserialize(previousSessionFile.bufferedReader(), Session::class.java)!!.environment ) - it.addIntegration { hub, _ -> + it.addIntegration { scopes, _ -> // this is just a hack to trigger the previousSessionFlush latch, so the finalizer // does not time out waiting. We have to do it as integration, because this is where - // the hub is already initialized - hub.startSession() + // the scopes is already initialized + scopes.startSession() } } @@ -861,7 +861,7 @@ class SentryTest { Sentry.init { it.dsn = dsn } val client = mock() - Sentry.getCurrentHub().bindClient(client) + Sentry.getCurrentScopes().bindClient(client) val checkIn = CheckIn("some_slug", CheckInStatus.OK) Sentry.captureCheckIn(checkIn) @@ -910,18 +910,18 @@ class SentryTest { } @Test - fun `getSpan calls hub getSpan`() { - val hub = mock() + fun `getSpan calls scopes getSpan`() { + val scopes = mock() Sentry.init({ it.dsn = dsn }, false) - Sentry.setCurrentHub(hub) + Sentry.setCurrentScopes(scopes) Sentry.getSpan() - verify(hub).span + verify(scopes).span } @Test - fun `getSpan calls returns root span if globalhub mode is enabled on Android`() { + fun `getSpan calls returns root span if globalscopes mode is enabled on Android`() { PlatformTestManipulator.pretendIsAndroid(true) Sentry.init({ it.dsn = dsn @@ -938,7 +938,7 @@ class SentryTest { } @Test - fun `getSpan calls returns child span if globalhub mode is enabled, but the platform is not Android`() { + fun `getSpan calls returns child span if globalscopes mode is enabled, but the platform is not Android`() { PlatformTestManipulator.pretendIsAndroid(false) Sentry.init({ it.dsn = dsn @@ -954,7 +954,7 @@ class SentryTest { } @Test - fun `getSpan calls returns child span if globalhub mode is disabled`() { + fun `getSpan calls returns child span if globalscopes mode is disabled`() { Sentry.init({ it.dsn = dsn it.enableTracing = true @@ -1140,15 +1140,15 @@ class SentryTest { } @Test - fun `metrics calls hub getMetrics`() { - val hub = mock() + fun `metrics calls scopes getMetrics`() { + val scopes = mock() Sentry.init({ it.dsn = dsn }, false) - Sentry.setCurrentHub(hub) + Sentry.setCurrentScopes(scopes) Sentry.metrics() - verify(hub).metrics() + verify(scopes).metrics() } private class InMemoryOptionsObserver : IOptionsObserver { diff --git a/sentry/src/test/java/io/sentry/SentryWrapperTest.kt b/sentry/src/test/java/io/sentry/SentryWrapperTest.kt index 7f6d449eac..2fb9b38566 100644 --- a/sentry/src/test/java/io/sentry/SentryWrapperTest.kt +++ b/sentry/src/test/java/io/sentry/SentryWrapperTest.kt @@ -35,20 +35,20 @@ class SentryWrapperTest { } } - val mainHub = Sentry.getCurrentHub() - val threadedHub = Sentry.getCurrentHub().clone() + val mainHub = Sentry.getCurrentScopes() + val threadedHub = Sentry.getCurrentScopes().clone() executor.submit { - Sentry.setCurrentHub(threadedHub) + Sentry.setCurrentScopes(threadedHub) }.get() - assertEquals(mainHub, Sentry.getCurrentHub()) + assertEquals(mainHub, Sentry.getCurrentScopes()) val callableFuture = CompletableFuture.supplyAsync( SentryWrapper.wrapSupplier { - assertNotEquals(mainHub, Sentry.getCurrentHub()) - assertNotEquals(threadedHub, Sentry.getCurrentHub()) + assertNotEquals(mainHub, Sentry.getCurrentScopes()) + assertNotEquals(threadedHub, Sentry.getCurrentScopes()) "Result 1" }, executor @@ -57,8 +57,8 @@ class SentryWrapperTest { callableFuture.join() executor.submit { - assertNotEquals(mainHub, Sentry.getCurrentHub()) - assertEquals(threadedHub, Sentry.getCurrentHub()) + assertNotEquals(mainHub, Sentry.getCurrentScopes()) + assertEquals(threadedHub, Sentry.getCurrentScopes()) }.get() } @@ -169,20 +169,20 @@ class SentryWrapperTest { it.dsn = dsn } - val mainHub = Sentry.getCurrentHub() - val threadedHub = Sentry.getCurrentHub().clone() + val mainHub = Sentry.getCurrentScopes() + val threadedHub = Sentry.getCurrentScopes().clone() executor.submit { - Sentry.setCurrentHub(threadedHub) + Sentry.setCurrentScopes(threadedHub) }.get() - assertEquals(mainHub, Sentry.getCurrentHub()) + assertEquals(mainHub, Sentry.getCurrentScopes()) val callableFuture = executor.submit( SentryWrapper.wrapCallable { - assertNotEquals(mainHub, Sentry.getCurrentHub()) - assertNotEquals(threadedHub, Sentry.getCurrentHub()) + assertNotEquals(mainHub, Sentry.getCurrentScopes()) + assertNotEquals(threadedHub, Sentry.getCurrentScopes()) "Result 1" } ) @@ -190,8 +190,8 @@ class SentryWrapperTest { callableFuture.get() executor.submit { - assertNotEquals(mainHub, Sentry.getCurrentHub()) - assertEquals(threadedHub, Sentry.getCurrentHub()) + assertNotEquals(mainHub, Sentry.getCurrentScopes()) + assertEquals(threadedHub, Sentry.getCurrentScopes()) }.get() } } diff --git a/sentry/src/test/java/io/sentry/ShutdownHookIntegrationTest.kt b/sentry/src/test/java/io/sentry/ShutdownHookIntegrationTest.kt index d6ce0ff043..428a34635f 100644 --- a/sentry/src/test/java/io/sentry/ShutdownHookIntegrationTest.kt +++ b/sentry/src/test/java/io/sentry/ShutdownHookIntegrationTest.kt @@ -16,7 +16,7 @@ class ShutdownHookIntegrationTest { private class Fixture { val runtime = mock() val options = SentryOptions() - val hub = mock() + val scopes = mock() fun getSut(): ShutdownHookIntegration { return ShutdownHookIntegration(runtime) @@ -29,7 +29,7 @@ class ShutdownHookIntegrationTest { fun `registration attaches shutdown hook to runtime`() { val integration = fixture.getSut() - integration.register(fixture.hub, fixture.options) + integration.register(fixture.scopes, fixture.options) verify(fixture.runtime).addShutdownHook(any()) } @@ -39,7 +39,7 @@ class ShutdownHookIntegrationTest { val integration = fixture.getSut() fixture.options.isEnableShutdownHook = false - integration.register(fixture.hub, fixture.options) + integration.register(fixture.scopes, fixture.options) verify(fixture.runtime, never()).addShutdownHook(any()) } @@ -48,7 +48,7 @@ class ShutdownHookIntegrationTest { fun `registration removes shutdown hook from runtime`() { val integration = fixture.getSut() - integration.register(fixture.hub, fixture.options) + integration.register(fixture.scopes, fixture.options) integration.close() verify(fixture.runtime).removeShutdownHook(any()) @@ -58,13 +58,13 @@ class ShutdownHookIntegrationTest { fun `hook calls flush`() { val integration = fixture.getSut() - integration.register(fixture.hub, fixture.options) + integration.register(fixture.scopes, fixture.options) assertNotNull(integration.hook) { it.start() it.join() } - verify(fixture.hub).flush(any()) + verify(fixture.scopes).flush(any()) } @Test @@ -72,13 +72,13 @@ class ShutdownHookIntegrationTest { val integration = fixture.getSut() fixture.options.flushTimeoutMillis = 10000 - integration.register(fixture.hub, fixture.options) + integration.register(fixture.scopes, fixture.options) assertNotNull(integration.hook) { it.start() it.join() } - verify(fixture.hub).flush(eq(10000)) + verify(fixture.scopes).flush(eq(10000)) } @Test @@ -86,7 +86,7 @@ class ShutdownHookIntegrationTest { val integration = fixture.getSut() whenever(fixture.runtime.removeShutdownHook(any())).thenThrow(java.lang.IllegalStateException("Shutdown in progress")) - integration.register(fixture.hub, fixture.options) + integration.register(fixture.scopes, fixture.options) integration.close() verify(fixture.runtime).removeShutdownHook(any()) @@ -97,7 +97,7 @@ class ShutdownHookIntegrationTest { val integration = fixture.getSut() whenever(fixture.runtime.removeShutdownHook(any())).thenThrow(java.lang.IllegalStateException()) - integration.register(fixture.hub, fixture.options) + integration.register(fixture.scopes, fixture.options) assertFails { integration.close() @@ -110,7 +110,7 @@ class ShutdownHookIntegrationTest { fun `Integration adds itself to integration list`() { val integration = fixture.getSut() - integration.register(fixture.hub, fixture.options) + integration.register(fixture.scopes, fixture.options) assertTrue( fixture.options.sdkVersion!!.integrationSet.contains("ShutdownHook") diff --git a/sentry/src/test/java/io/sentry/SpanTest.kt b/sentry/src/test/java/io/sentry/SpanTest.kt index ae9d9bd07f..fd36c31933 100644 --- a/sentry/src/test/java/io/sentry/SpanTest.kt +++ b/sentry/src/test/java/io/sentry/SpanTest.kt @@ -21,10 +21,10 @@ import kotlin.test.assertTrue class SpanTest { private class Fixture { - val hub = mock() + val scopes = mock() init { - whenever(hub.options).thenReturn( + whenever(scopes.options).thenReturn( SentryOptions().apply { dsn = "https://key@sentry.io/proj" isTraceSampling = true @@ -36,9 +36,9 @@ class SpanTest { return Span( SentryId(), SpanId(), - SentryTracer(TransactionContext("name", "op"), hub), + SentryTracer(TransactionContext("name", "op"), scopes), "op", - hub, + scopes, null, options, null @@ -46,7 +46,7 @@ class SpanTest { } fun getRootSut(options: TransactionOptions = TransactionOptions()): Span { - return SentryTracer(TransactionContext("name", "op"), hub, options).root + return SentryTracer(TransactionContext("name", "op"), scopes, options).root } } @@ -106,10 +106,10 @@ class SpanTest { parentSpanId, SentryTracer( TransactionContext("name", "op", TracesSamplingDecision(true)), - fixture.hub + fixture.scopes ), "op", - fixture.hub + fixture.scopes ) val sentryTrace = span.toSentryTrace() @@ -163,17 +163,17 @@ class SpanTest { } @Test - fun `when span has throwable set set, it assigns itself to throwable on the Hub`() { + fun `when span has throwable set set, it assigns itself to throwable on the Scopes`() { val transaction = SentryTracer( TransactionContext("name", "op"), - fixture.hub + fixture.scopes ) val span = transaction.startChild("op") val ex = RuntimeException() span.throwable = ex span.finish() - verify(fixture.hub).setSpanContext(ex, span, "name") + verify(fixture.scopes).setSpanContext(ex, span, "name") } @Test @@ -188,7 +188,7 @@ class SpanTest { span.finish(SpanStatus.UNKNOWN_ERROR) // call only once - verify(fixture.hub).setSpanContext(any(), any(), any()) + verify(fixture.scopes).setSpanContext(any(), any(), any()) assertEquals(SpanStatus.OK, span.status) assertEquals(timestamp, span.finishDate) } @@ -496,7 +496,7 @@ class SpanTest { } private fun getTransaction(transactionContext: TransactionContext = TransactionContext("name", "op")): SentryTracer { - return SentryTracer(transactionContext, fixture.hub) + return SentryTracer(transactionContext, fixture.scopes) } private fun startChildFromSpan(): Span { diff --git a/sentry/src/test/java/io/sentry/TraceContextSerializationTest.kt b/sentry/src/test/java/io/sentry/TraceContextSerializationTest.kt index e79e5ebf8c..0847c9448f 100644 --- a/sentry/src/test/java/io/sentry/TraceContextSerializationTest.kt +++ b/sentry/src/test/java/io/sentry/TraceContextSerializationTest.kt @@ -54,10 +54,10 @@ class TraceContextSerializationTest { private fun createTraceContext(sRate: Double): TraceContext { val baggage = Baggage(fixture.logger) - val hub: IHub = mock() - whenever(hub.options).thenReturn(SentryOptions()) + val scopes: IScopes = mock() + whenever(scopes.options).thenReturn(SentryOptions()) baggage.setValuesFromTransaction( - SentryTracer(TransactionContext("name", "op"), hub), + SentryTracer(TransactionContext("name", "op"), scopes), User().apply { id = "user-id" others = mapOf("segment" to "pro") diff --git a/sentry/src/test/java/io/sentry/UncaughtExceptionHandlerIntegrationTest.kt b/sentry/src/test/java/io/sentry/UncaughtExceptionHandlerIntegrationTest.kt index 01353d5ac0..ec366e1901 100644 --- a/sentry/src/test/java/io/sentry/UncaughtExceptionHandlerIntegrationTest.kt +++ b/sentry/src/test/java/io/sentry/UncaughtExceptionHandlerIntegrationTest.kt @@ -30,7 +30,7 @@ class UncaughtExceptionHandlerIntegrationTest { val defaultHandler = mock() val thread = mock() val throwable = Throwable("test") - val hub = mock() + val scopes = mock() val options = SentryOptions() val logger = mock() @@ -63,17 +63,17 @@ class UncaughtExceptionHandlerIntegrationTest { fun `when uncaughtException is called, sentry captures exception`() { val sut = fixture.getSut(isPrintUncaughtStackTrace = false) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) sut.uncaughtException(fixture.thread, fixture.throwable) - verify(fixture.hub).captureEvent(any(), any()) + verify(fixture.scopes).captureEvent(any(), any()) } @Test fun `when register is called, current handler is not lost`() { val sut = fixture.getSut(hasDefaultHandler = true, isPrintUncaughtStackTrace = false) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) sut.uncaughtException(fixture.thread, fixture.throwable) verify(fixture.defaultHandler).uncaughtException(fixture.thread, fixture.throwable) @@ -81,7 +81,7 @@ class UncaughtExceptionHandlerIntegrationTest { @Test fun `when uncaughtException is called, exception captured has handled=false`() { - whenever(fixture.hub.captureException(any())).thenAnswer { invocation -> + whenever(fixture.scopes.captureException(any())).thenAnswer { invocation -> val e = invocation.getArgument(1) assertNotNull(e) assertNotNull(e.exceptionMechanism) @@ -91,22 +91,22 @@ class UncaughtExceptionHandlerIntegrationTest { val sut = fixture.getSut(isPrintUncaughtStackTrace = false) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) sut.uncaughtException(fixture.thread, fixture.throwable) - verify(fixture.hub).captureEvent(any(), any()) + verify(fixture.scopes).captureEvent(any(), any()) } @Test - fun `when hub is closed, integrations should be closed`() { + fun `when scopes is closed, integrations should be closed`() { val integrationMock = mock() val options = SentryOptions() options.dsn = "https://key@sentry.io/proj" options.addIntegration(integrationMock) options.cacheDirPath = fixture.file.absolutePath options.setSerializer(mock()) - val hub = Hub(options) - hub.close() + val scopes = Hub(options) + scopes.close() verify(integrationMock).close() } @@ -117,7 +117,7 @@ class UncaughtExceptionHandlerIntegrationTest { isPrintUncaughtStackTrace = false ) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) verify(fixture.handler, never()).defaultUncaughtExceptionHandler = any() } @@ -126,7 +126,7 @@ class UncaughtExceptionHandlerIntegrationTest { fun `When defaultUncaughtExceptionHandler is enabled, should install Sentry UncaughtExceptionHandler`() { val sut = fixture.getSut(isPrintUncaughtStackTrace = false) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) verify(fixture.handler).defaultUncaughtExceptionHandler = argWhere { it is UncaughtExceptionHandlerIntegration } @@ -136,7 +136,7 @@ class UncaughtExceptionHandlerIntegrationTest { fun `When defaultUncaughtExceptionHandler is set and integration is closed, default uncaught exception handler is reset to previous handler`() { val sut = fixture.getSut(hasDefaultHandler = true, isPrintUncaughtStackTrace = false) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) whenever(fixture.handler.defaultUncaughtExceptionHandler) .thenReturn(sut) sut.close() @@ -148,7 +148,7 @@ class UncaughtExceptionHandlerIntegrationTest { fun `When defaultUncaughtExceptionHandler is not set and integration is closed, default uncaught exception handler is reset to null`() { val sut = fixture.getSut(isPrintUncaughtStackTrace = false) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) whenever(fixture.handler.defaultUncaughtExceptionHandler) .thenReturn(sut) sut.close() @@ -165,7 +165,7 @@ class UncaughtExceptionHandlerIntegrationTest { val sut = fixture.getSut(isPrintUncaughtStackTrace = true) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) sut.uncaughtException(fixture.thread, RuntimeException("This should be printed!")) assertTrue( @@ -185,7 +185,7 @@ class UncaughtExceptionHandlerIntegrationTest { fun `waits for event to flush on disk`() { val capturedEventId = SentryId() - whenever(fixture.hub.captureEvent(any(), any())).thenAnswer { invocation -> + whenever(fixture.scopes.captureEvent(any(), any())).thenAnswer { invocation -> val hint = HintUtils.getSentrySdkHint(invocation.getArgument(1)) as DiskFlushNotification thread { @@ -197,10 +197,10 @@ class UncaughtExceptionHandlerIntegrationTest { val sut = fixture.getSut(flushTimeoutMillis = 5000) - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) sut.uncaughtException(fixture.thread, fixture.throwable) - verify(fixture.hub).captureEvent(any(), any()) + verify(fixture.scopes).captureEvent(any(), any()) // shouldn't fall into timed out state, because we marked event as flushed on another thread verify(fixture.logger, never()).log( any(), @@ -211,14 +211,14 @@ class UncaughtExceptionHandlerIntegrationTest { @Test fun `does not block flushing when the event was dropped`() { - whenever(fixture.hub.captureEvent(any(), any())).thenReturn(SentryId.EMPTY_ID) + whenever(fixture.scopes.captureEvent(any(), any())).thenReturn(SentryId.EMPTY_ID) val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) sut.uncaughtException(fixture.thread, fixture.throwable) - verify(fixture.hub).captureEvent(any(), any()) + verify(fixture.scopes).captureEvent(any(), any()) // we do not call markFlushed, hence it should time out waiting for flush, but because // we drop the event, it should not even come to this if-check verify(fixture.logger, never()).log( @@ -231,17 +231,17 @@ class UncaughtExceptionHandlerIntegrationTest { @Test fun `waits for event to flush on disk if it was dropped by multithreaded deduplicator`() { val hintCaptor = argumentCaptor() - whenever(fixture.hub.captureEvent(any(), hintCaptor.capture())).thenAnswer { + whenever(fixture.scopes.captureEvent(any(), hintCaptor.capture())).thenAnswer { HintUtils.setEventDropReason(hintCaptor.firstValue, MULTITHREADED_DEDUPLICATION) return@thenAnswer SentryId.EMPTY_ID } val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) sut.uncaughtException(fixture.thread, fixture.throwable) - verify(fixture.hub).captureEvent(any(), any()) + verify(fixture.scopes).captureEvent(any(), any()) // we do not call markFlushed, even though we dropped the event, the reason was // MULTITHREADED_DEDUPLICATION, so it should time out verify(fixture.logger).log( @@ -254,15 +254,15 @@ class UncaughtExceptionHandlerIntegrationTest { @Test fun `when there is no active transaction on scope, sets current event id as flushable`() { val eventCaptor = argumentCaptor() - whenever(fixture.hub.captureEvent(eventCaptor.capture(), any())) + whenever(fixture.scopes.captureEvent(eventCaptor.capture(), any())) .thenReturn(SentryId.EMPTY_ID) val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) sut.uncaughtException(fixture.thread, fixture.throwable) - verify(fixture.hub).captureEvent( + verify(fixture.scopes).captureEvent( any(), argThat { (HintUtils.getSentrySdkHint(this) as UncaughtExceptionHint) @@ -274,16 +274,16 @@ class UncaughtExceptionHandlerIntegrationTest { @Test fun `when there is active transaction on scope, does not set current event id as flushable`() { val eventCaptor = argumentCaptor() - whenever(fixture.hub.transaction).thenReturn(mock()) - whenever(fixture.hub.captureEvent(eventCaptor.capture(), any())) + whenever(fixture.scopes.transaction).thenReturn(mock()) + whenever(fixture.scopes.captureEvent(eventCaptor.capture(), any())) .thenReturn(SentryId.EMPTY_ID) val sut = fixture.getSut() - sut.register(fixture.hub, fixture.options) + sut.register(fixture.scopes, fixture.options) sut.uncaughtException(fixture.thread, fixture.throwable) - verify(fixture.hub).captureEvent( + verify(fixture.scopes).captureEvent( any(), argThat { !(HintUtils.getSentrySdkHint(this) as UncaughtExceptionHint) diff --git a/sentry/src/test/java/io/sentry/backpressure/BackpressureMonitorTest.kt b/sentry/src/test/java/io/sentry/backpressure/BackpressureMonitorTest.kt index c010c97238..cf234574bf 100644 --- a/sentry/src/test/java/io/sentry/backpressure/BackpressureMonitorTest.kt +++ b/sentry/src/test/java/io/sentry/backpressure/BackpressureMonitorTest.kt @@ -1,6 +1,6 @@ package io.sentry.backpressure -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.ISentryExecutorService import io.sentry.SentryOptions import io.sentry.backpressure.BackpressureMonitor.MAX_DOWNSAMPLE_FACTOR @@ -17,13 +17,13 @@ class BackpressureMonitorTest { class Fixture { val options = SentryOptions() - val hub = mock() + val scopes = mock() val executor = mock() fun getSut(): BackpressureMonitor { options.executorService = executor whenever(executor.isClosed).thenReturn(false) whenever(executor.schedule(any(), any())).thenReturn(mock>()) - return BackpressureMonitor(options, hub) + return BackpressureMonitor(options, scopes) } } @@ -38,7 +38,7 @@ class BackpressureMonitorTest { @Test fun `downsampleFactor increases with negative health checks up to max`() { val sut = fixture.getSut() - whenever(fixture.hub.isHealthy).thenReturn(false) + whenever(fixture.scopes.isHealthy).thenReturn(false) assertEquals(0, sut.downsampleFactor) (1..MAX_DOWNSAMPLE_FACTOR).forEach { i -> @@ -54,13 +54,13 @@ class BackpressureMonitorTest { @Test fun `downsampleFactor goes back to 0 after positive health check`() { val sut = fixture.getSut() - whenever(fixture.hub.isHealthy).thenReturn(false) + whenever(fixture.scopes.isHealthy).thenReturn(false) assertEquals(0, sut.downsampleFactor) sut.checkHealth() assertEquals(1, sut.downsampleFactor) - whenever(fixture.hub.isHealthy).thenReturn(true) + whenever(fixture.scopes.isHealthy).thenReturn(true) sut.checkHealth() assertEquals(0, sut.downsampleFactor) } diff --git a/sentry/src/test/java/io/sentry/clientreport/ClientReportTest.kt b/sentry/src/test/java/io/sentry/clientreport/ClientReportTest.kt index b4615cac76..d27e5c0228 100644 --- a/sentry/src/test/java/io/sentry/clientreport/ClientReportTest.kt +++ b/sentry/src/test/java/io/sentry/clientreport/ClientReportTest.kt @@ -7,7 +7,7 @@ import io.sentry.DataCategory import io.sentry.DateUtils import io.sentry.EventProcessor import io.sentry.Hint -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.NoOpLogger import io.sentry.ProfilingTraceData import io.sentry.Sentry @@ -47,9 +47,9 @@ class ClientReportTest { @Test fun `lost envelope can be recorded`() { givenClientReportRecorder() - val hub = mock() - whenever(hub.options).thenReturn(opts) - val transaction = SentryTracer(TransactionContext("name", "op"), hub) + val scopes = mock() + whenever(scopes.options).thenReturn(opts) + val transaction = SentryTracer(TransactionContext("name", "op"), scopes) val lostClientReport = ClientReport( DateUtils.getCurrentDateTime(), diff --git a/sentry/src/test/java/io/sentry/instrumentation/file/FileIOSpanManagerTest.kt b/sentry/src/test/java/io/sentry/instrumentation/file/FileIOSpanManagerTest.kt index 00c89f27be..f6271b5b5e 100644 --- a/sentry/src/test/java/io/sentry/instrumentation/file/FileIOSpanManagerTest.kt +++ b/sentry/src/test/java/io/sentry/instrumentation/file/FileIOSpanManagerTest.kt @@ -1,6 +1,6 @@ package io.sentry.instrumentation.file -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.ISpan import io.sentry.ITransaction import io.sentry.util.PlatformTestManipulator @@ -20,25 +20,25 @@ class FileIOSpanManagerTest { @Test fun `startSpan uses transaction on Android platform`() { - val hub = mock() + val scopes = mock() val transaction = mock() - whenever(hub.transaction).thenReturn(transaction) + whenever(scopes.transaction).thenReturn(transaction) PlatformTestManipulator.pretendIsAndroid(true) - FileIOSpanManager.startSpan(hub, "op.read") + FileIOSpanManager.startSpan(scopes, "op.read") verify(transaction).startChild(any()) } @Test fun `startSpan uses last span on non-Android platforms`() { - val hub = mock() + val scopes = mock() val span = mock() - whenever(hub.span).thenReturn(span) + whenever(scopes.span).thenReturn(span) PlatformTestManipulator.pretendIsAndroid(false) - FileIOSpanManager.startSpan(hub, "op.read") + FileIOSpanManager.startSpan(scopes, "op.read") verify(span).startChild(any()) } } diff --git a/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileInputStreamTest.kt b/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileInputStreamTest.kt index 5e27eb451d..063b6d6428 100644 --- a/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileInputStreamTest.kt +++ b/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileInputStreamTest.kt @@ -1,6 +1,6 @@ package io.sentry.instrumentation.file -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.SentryOptions import io.sentry.SentryTracer import io.sentry.SpanDataConvention @@ -29,7 +29,7 @@ import kotlin.test.assertTrue class SentryFileInputStreamTest { class Fixture { - val hub = mock() + val scopes = mock() lateinit var sentryTracer: SentryTracer private val options = SentryOptions() @@ -40,21 +40,21 @@ class SentryFileInputStreamTest { sendDefaultPii: Boolean = false ): SentryFileInputStream { tmpFile?.writeText("Text") - whenever(hub.options).thenReturn( + whenever(scopes.options).thenReturn( options.apply { isSendDefaultPii = sendDefaultPii mainThreadChecker = MainThreadChecker.getInstance() addInAppInclude("org.junit") } ) - sentryTracer = SentryTracer(TransactionContext("name", "op"), hub) + sentryTracer = SentryTracer(TransactionContext("name", "op"), scopes) if (activeTransaction) { - whenever(hub.span).thenReturn(sentryTracer) + whenever(scopes.span).thenReturn(sentryTracer) } return if (fileDescriptor == null) { - SentryFileInputStream(tmpFile, hub) + SentryFileInputStream(tmpFile, scopes) } else { - SentryFileInputStream(fileDescriptor, hub) + SentryFileInputStream(fileDescriptor, scopes) } } @@ -62,13 +62,13 @@ class SentryFileInputStreamTest { tmpFile: File? = null, delegate: FileInputStream ): SentryFileInputStream { - whenever(hub.options).thenReturn(options) - sentryTracer = SentryTracer(TransactionContext("name", "op"), hub) - whenever(hub.span).thenReturn(sentryTracer) + whenever(scopes.options).thenReturn(options) + sentryTracer = SentryTracer(TransactionContext("name", "op"), scopes) + whenever(scopes.span).thenReturn(sentryTracer) return SentryFileInputStream.Factory.create( delegate, tmpFile, - hub + scopes ) as SentryFileInputStream } } diff --git a/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileOutputStreamTest.kt b/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileOutputStreamTest.kt index f6a09830c2..8b175adc2d 100644 --- a/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileOutputStreamTest.kt +++ b/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileOutputStreamTest.kt @@ -1,6 +1,6 @@ package io.sentry.instrumentation.file -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.SentryOptions import io.sentry.SentryTracer import io.sentry.SpanDataConvention @@ -24,7 +24,7 @@ import kotlin.test.assertTrue class SentryFileOutputStreamTest { class Fixture { - val hub = mock() + val scopes = mock() lateinit var sentryTracer: SentryTracer internal fun getSut( @@ -32,17 +32,17 @@ class SentryFileOutputStreamTest { activeTransaction: Boolean = true, append: Boolean = false ): SentryFileOutputStream { - whenever(hub.options).thenReturn( + whenever(scopes.options).thenReturn( SentryOptions().apply { mainThreadChecker = MainThreadChecker.getInstance() addInAppInclude("org.junit") } ) - sentryTracer = SentryTracer(TransactionContext("name", "op"), hub) + sentryTracer = SentryTracer(TransactionContext("name", "op"), scopes) if (activeTransaction) { - whenever(hub.span).thenReturn(sentryTracer) + whenever(scopes.span).thenReturn(sentryTracer) } - return SentryFileOutputStream(tmpFile, append, hub) + return SentryFileOutputStream(tmpFile, append, scopes) } } diff --git a/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileReaderTest.kt b/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileReaderTest.kt index 2485579e7a..38781d718b 100644 --- a/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileReaderTest.kt +++ b/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileReaderTest.kt @@ -1,6 +1,6 @@ package io.sentry.instrumentation.file -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.SentryOptions import io.sentry.SentryTracer import io.sentry.SpanDataConvention @@ -17,7 +17,7 @@ import kotlin.test.assertEquals class SentryFileReaderTest { class Fixture { - val hub = mock() + val scopes = mock() lateinit var sentryTracer: SentryTracer internal fun getSut( @@ -25,16 +25,16 @@ class SentryFileReaderTest { activeTransaction: Boolean = true ): SentryFileReader { tmpFile.writeText("TEXT") - whenever(hub.options).thenReturn( + whenever(scopes.options).thenReturn( SentryOptions().apply { mainThreadChecker = MainThreadChecker.getInstance() } ) - sentryTracer = SentryTracer(TransactionContext("name", "op"), hub) + sentryTracer = SentryTracer(TransactionContext("name", "op"), scopes) if (activeTransaction) { - whenever(hub.span).thenReturn(sentryTracer) + whenever(scopes.span).thenReturn(sentryTracer) } - return SentryFileReader(tmpFile, hub) + return SentryFileReader(tmpFile, scopes) } } diff --git a/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileWriterTest.kt b/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileWriterTest.kt index f0738d8725..8f3d96b4d7 100644 --- a/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileWriterTest.kt +++ b/sentry/src/test/java/io/sentry/instrumentation/file/SentryFileWriterTest.kt @@ -1,6 +1,6 @@ package io.sentry.instrumentation.file -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.SentryOptions import io.sentry.SentryTracer import io.sentry.SpanDataConvention @@ -17,7 +17,7 @@ import kotlin.test.assertEquals class SentryFileWriterTest { class Fixture { - val hub = mock() + val scopes = mock() lateinit var sentryTracer: SentryTracer internal fun getSut( @@ -25,16 +25,16 @@ class SentryFileWriterTest { activeTransaction: Boolean = true, append: Boolean = false ): SentryFileWriter { - whenever(hub.options).thenReturn( + whenever(scopes.options).thenReturn( SentryOptions().apply { mainThreadChecker = MainThreadChecker.getInstance() } ) - sentryTracer = SentryTracer(TransactionContext("name", "op"), hub) + sentryTracer = SentryTracer(TransactionContext("name", "op"), scopes) if (activeTransaction) { - whenever(hub.span).thenReturn(sentryTracer) + whenever(scopes.span).thenReturn(sentryTracer) } - return SentryFileWriter(tmpFile, append, hub) + return SentryFileWriter(tmpFile, append, scopes) } } diff --git a/sentry/src/test/java/io/sentry/internal/SpotlightIntegrationTest.kt b/sentry/src/test/java/io/sentry/internal/SpotlightIntegrationTest.kt index 73aa339f26..0a91bec562 100644 --- a/sentry/src/test/java/io/sentry/internal/SpotlightIntegrationTest.kt +++ b/sentry/src/test/java/io/sentry/internal/SpotlightIntegrationTest.kt @@ -1,6 +1,6 @@ package io.sentry.internal -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.SentryOptions import io.sentry.SentryOptions.BeforeEnvelopeCallback import io.sentry.SpotlightIntegration @@ -19,7 +19,7 @@ class SpotlightIntegrationTest { } val spotlight = SpotlightIntegration() - spotlight.register(mock(), options) + spotlight.register(mock(), options) assertNull(options.beforeEnvelopeCallback) } @@ -33,7 +33,7 @@ class SpotlightIntegrationTest { } val spotlight = SpotlightIntegration() - spotlight.register(mock(), options) + spotlight.register(mock(), options) assertEquals(envelopeCallback, options.beforeEnvelopeCallback) } @@ -45,7 +45,7 @@ class SpotlightIntegrationTest { } val spotlight = SpotlightIntegration() - spotlight.register(mock(), options) + spotlight.register(mock(), options) assertEquals(options.beforeEnvelopeCallback, spotlight) spotlight.close() @@ -71,7 +71,7 @@ class SpotlightIntegrationTest { } val spotlight = SpotlightIntegration() - spotlight.register(mock(), options) + spotlight.register(mock(), options) assertEquals("http://example.com:1234/stream", spotlight.spotlightConnectionUrl) } diff --git a/sentry/src/test/java/io/sentry/protocol/SentrySpanTest.kt b/sentry/src/test/java/io/sentry/protocol/SentrySpanTest.kt index 27499be0a0..d67b0186be 100644 --- a/sentry/src/test/java/io/sentry/protocol/SentrySpanTest.kt +++ b/sentry/src/test/java/io/sentry/protocol/SentrySpanTest.kt @@ -1,6 +1,6 @@ package io.sentry.protocol -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.SentryLongDate import io.sentry.SentryTracer import io.sentry.Span @@ -19,7 +19,7 @@ class SentrySpanTest { val span = Span( TransactionContext("name", "op"), mock(), - mock(), + mock(), SentryLongDate(1000000), SpanOptions() ) diff --git a/sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt b/sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt index d9e217b0ac..2b1be98611 100644 --- a/sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt +++ b/sentry/src/test/java/io/sentry/transport/RateLimiterTest.kt @@ -4,7 +4,7 @@ import io.sentry.Attachment import io.sentry.CheckIn import io.sentry.CheckInStatus import io.sentry.Hint -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.ISerializer import io.sentry.NoOpLogger import io.sentry.ProfilingTraceData @@ -80,10 +80,10 @@ class RateLimiterTest { fun `parse X-Sentry-Rate-Limit and set its values and retry after should be true`() { val rateLimiter = fixture.getSUT() whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0) - val hub: IHub = mock() - whenever(hub.options).thenReturn(SentryOptions()) + val scopes: IScopes = mock() + whenever(scopes.options).thenReturn(SentryOptions()) val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent()) - val transaction = SentryTransaction(SentryTracer(TransactionContext("name", "op"), hub)) + val transaction = SentryTransaction(SentryTracer(TransactionContext("name", "op"), scopes)) val transactionItem = SentryEnvelopeItem.fromEvent(fixture.serializer, transaction) val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem, transactionItem)) @@ -97,10 +97,10 @@ class RateLimiterTest { fun `parse X-Sentry-Rate-Limit and set its values and retry after should be false`() { val rateLimiter = fixture.getSUT() whenever(fixture.currentDateProvider.currentTimeMillis).thenReturn(0, 0, 1001) - val hub: IHub = mock() - whenever(hub.options).thenReturn(SentryOptions()) + val scopes: IScopes = mock() + whenever(scopes.options).thenReturn(SentryOptions()) val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent()) - val transaction = SentryTransaction(SentryTracer(TransactionContext("name", "op"), hub)) + val transaction = SentryTransaction(SentryTracer(TransactionContext("name", "op"), scopes)) val transactionItem = SentryEnvelopeItem.fromEvent(fixture.serializer, transaction) val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem, transactionItem)) @@ -191,9 +191,9 @@ class RateLimiterTest { it.setName("John Me") } ) - val hub = mock() - whenever(hub.options).thenReturn(SentryOptions()) - val transaction = SentryTracer(TransactionContext("name", "op"), hub) + val scopes = mock() + whenever(scopes.options).thenReturn(SentryOptions()) + val transaction = SentryTracer(TransactionContext("name", "op"), scopes) val sessionItem = SentryEnvelopeItem.fromSession(fixture.serializer, Session("123", User(), "env", "release")) val attachmentItem = SentryEnvelopeItem.fromAttachment(fixture.serializer, NoOpLogger.getInstance(), Attachment("{ \"number\": 10 }".toByteArray(), "log.json"), 1000) @@ -219,8 +219,8 @@ class RateLimiterTest { @Test fun `records only dropped items as lost`() { val rateLimiter = fixture.getSUT() - val hub = mock() - whenever(hub.options).thenReturn(SentryOptions()) + val scopes = mock() + whenever(scopes.options).thenReturn(SentryOptions()) val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent()) val userFeedbackItem = SentryEnvelopeItem.fromUserFeedback( @@ -233,7 +233,7 @@ class RateLimiterTest { it.setName("John Me") } ) - val transaction = SentryTracer(TransactionContext("name", "op"), hub) + val transaction = SentryTracer(TransactionContext("name", "op"), scopes) val profileItem = SentryEnvelopeItem.fromProfilingTrace(ProfilingTraceData(File(""), transaction), 1000, fixture.serializer) val sessionItem = SentryEnvelopeItem.fromSession(fixture.serializer, Session("123", User(), "env", "release")) val attachmentItem = SentryEnvelopeItem.fromAttachment(fixture.serializer, NoOpLogger.getInstance(), Attachment("{ \"number\": 10 }".toByteArray(), "log.json"), 1000) @@ -253,12 +253,12 @@ class RateLimiterTest { @Test fun `drop profile items as lost`() { val rateLimiter = fixture.getSUT() - val hub = mock() - whenever(hub.options).thenReturn(SentryOptions()) + val scopes = mock() + whenever(scopes.options).thenReturn(SentryOptions()) val eventItem = SentryEnvelopeItem.fromEvent(fixture.serializer, SentryEvent()) val f = File.createTempFile("test", "trace") - val transaction = SentryTracer(TransactionContext("name", "op"), hub) + val transaction = SentryTracer(TransactionContext("name", "op"), scopes) val profileItem = SentryEnvelopeItem.fromProfilingTrace(ProfilingTraceData(f, transaction), 1000, fixture.serializer) val envelope = SentryEnvelope(SentryEnvelopeHeader(), arrayListOf(eventItem, profileItem)) diff --git a/sentry/src/test/java/io/sentry/util/CheckInUtilsTest.kt b/sentry/src/test/java/io/sentry/util/CheckInUtilsTest.kt index a285cd5832..9f330348b0 100644 --- a/sentry/src/test/java/io/sentry/util/CheckInUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/CheckInUtilsTest.kt @@ -1,7 +1,8 @@ package io.sentry.util import io.sentry.CheckInStatus -import io.sentry.IHub +import io.sentry.HubScopesWrapper +import io.sentry.IScopes import io.sentry.MonitorConfig import io.sentry.MonitorSchedule import io.sentry.MonitorScheduleUnit @@ -56,30 +57,31 @@ class CheckInUtilsTest { @Test fun `sends check-in for wrapped supplier`() { Mockito.mockStatic(Sentry::class.java).use { sentry -> - val hub = mock() - sentry.`when` { Sentry.getCurrentHub() }.thenReturn(hub) - whenever(hub.options).thenReturn(SentryOptions()) + val scopes = mock() + sentry.`when` { Sentry.getCurrentScopes() }.thenReturn(scopes) + sentry.`when` { Sentry.getCurrentHub() }.thenReturn(HubScopesWrapper(scopes)) + whenever(scopes.options).thenReturn(SentryOptions()) val returnValue = CheckInUtils.withCheckIn("monitor-1") { return@withCheckIn "test1" } assertEquals("test1", returnValue) - inOrder(hub) { - verify(hub).pushScope() - verify(hub).configureScope(any()) - verify(hub).captureCheckIn( + inOrder(scopes) { + verify(scopes).pushScope() + verify(scopes).configureScope(any()) + verify(scopes).captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.IN_PROGRESS.apiName(), it.status) } ) - verify(hub).captureCheckIn( + verify(scopes).captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.OK.apiName(), it.status) } ) - verify(hub).popScope() + verify(scopes).popScope() } } } @@ -87,8 +89,9 @@ class CheckInUtilsTest { @Test fun `sends check-in for wrapped supplier with exception`() { Mockito.mockStatic(Sentry::class.java).use { sentry -> - val hub = mock() - sentry.`when` { Sentry.getCurrentHub() }.thenReturn(hub) + val scopes = mock() + sentry.`when` { Sentry.getCurrentScopes() }.thenReturn(scopes) + sentry.`when` { Sentry.getCurrentHub() }.thenReturn(HubScopesWrapper(scopes)) try { CheckInUtils.withCheckIn("monitor-1") { @@ -99,22 +102,22 @@ class CheckInUtilsTest { assertEquals("thrown on purpose", e.message) } - inOrder(hub) { - verify(hub).pushScope() - verify(hub).configureScope(any()) - verify(hub).captureCheckIn( + inOrder(scopes) { + verify(scopes).pushScope() + verify(scopes).configureScope(any()) + verify(scopes).captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.IN_PROGRESS.apiName(), it.status) } ) - verify(hub).captureCheckIn( + verify(scopes).captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.ERROR.apiName(), it.status) } ) - verify(hub).popScope() + verify(scopes).popScope() } } } @@ -122,32 +125,33 @@ class CheckInUtilsTest { @Test fun `sends check-in for wrapped supplier with upsert`() { Mockito.mockStatic(Sentry::class.java).use { sentry -> - val hub = mock() - sentry.`when` { Sentry.getCurrentHub() }.thenReturn(hub) - whenever(hub.options).thenReturn(SentryOptions()) + val scopes = mock() + sentry.`when` { Sentry.getCurrentScopes() }.thenReturn(scopes) + sentry.`when` { Sentry.getCurrentHub() }.thenReturn(HubScopesWrapper(scopes)) + whenever(scopes.options).thenReturn(SentryOptions()) val monitorConfig = MonitorConfig(MonitorSchedule.interval(7, MonitorScheduleUnit.DAY)) val returnValue = CheckInUtils.withCheckIn("monitor-1", monitorConfig) { "test1" } assertEquals("test1", returnValue) - inOrder(hub) { - verify(hub).pushScope() - verify(hub).configureScope(any()) - verify(hub).captureCheckIn( + inOrder(scopes) { + verify(scopes).pushScope() + verify(scopes).configureScope(any()) + verify(scopes).captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertSame(monitorConfig, it.monitorConfig) assertEquals(CheckInStatus.IN_PROGRESS.apiName(), it.status) } ) - verify(hub).captureCheckIn( + verify(scopes).captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.OK.apiName(), it.status) } ) - verify(hub).popScope() + verify(scopes).popScope() } } } @@ -155,9 +159,10 @@ class CheckInUtilsTest { @Test fun `sends check-in for wrapped supplier with upsert and thresholds`() { Mockito.mockStatic(Sentry::class.java).use { sentry -> - val hub = mock() - sentry.`when` { Sentry.getCurrentHub() }.thenReturn(hub) - whenever(hub.options).thenReturn(SentryOptions()) + val scopes = mock() + sentry.`when` { Sentry.getCurrentScopes() }.thenReturn(scopes) + sentry.`when` { Sentry.getCurrentHub() }.thenReturn(HubScopesWrapper(scopes)) + whenever(scopes.options).thenReturn(SentryOptions()) val monitorConfig = MonitorConfig(MonitorSchedule.interval(7, MonitorScheduleUnit.DAY)).apply { failureIssueThreshold = 10 recoveryThreshold = 20 @@ -167,23 +172,23 @@ class CheckInUtilsTest { } assertEquals("test1", returnValue) - inOrder(hub) { - verify(hub).pushScope() - verify(hub).configureScope(any()) - verify(hub).captureCheckIn( + inOrder(scopes) { + verify(scopes).pushScope() + verify(scopes).configureScope(any()) + verify(scopes).captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertSame(monitorConfig, it.monitorConfig) assertEquals(CheckInStatus.IN_PROGRESS.apiName(), it.status) } ) - verify(hub).captureCheckIn( + verify(scopes).captureCheckIn( check { assertEquals("monitor-1", it.monitorSlug) assertEquals(CheckInStatus.OK.apiName(), it.status) } ) - verify(hub).popScope() + verify(scopes).popScope() } } } @@ -191,9 +196,10 @@ class CheckInUtilsTest { @Test fun `sets defaults for MonitorConfig from SentryOptions`() { Mockito.mockStatic(Sentry::class.java).use { sentry -> - val hub = mock() - sentry.`when` { Sentry.getCurrentHub() }.thenReturn(hub) - whenever(hub.options).thenReturn( + val scopes = mock() + sentry.`when` { Sentry.getCurrentScopes() }.thenReturn(scopes) + sentry.`when` { Sentry.getCurrentHub() }.thenReturn(HubScopesWrapper(scopes)) + whenever(scopes.options).thenReturn( SentryOptions().apply { cron = SentryOptions.Cron().apply { defaultCheckinMargin = 20 @@ -218,9 +224,10 @@ class CheckInUtilsTest { @Test fun `defaults for MonitorConfig from SentryOptions can be overridden`() { Mockito.mockStatic(Sentry::class.java).use { sentry -> - val hub = mock() - sentry.`when` { Sentry.getCurrentHub() }.thenReturn(hub) - whenever(hub.options).thenReturn( + val scopes = mock() + sentry.`when` { Sentry.getCurrentScopes() }.thenReturn(scopes) + sentry.`when` { Sentry.getCurrentHub() }.thenReturn(HubScopesWrapper(scopes)) + whenever(scopes.options).thenReturn( SentryOptions().apply { cron = SentryOptions.Cron().apply { defaultCheckinMargin = 20 diff --git a/sentry/src/test/java/io/sentry/util/TracingUtilsTest.kt b/sentry/src/test/java/io/sentry/util/TracingUtilsTest.kt index e38410641e..b3f640aeec 100644 --- a/sentry/src/test/java/io/sentry/util/TracingUtilsTest.kt +++ b/sentry/src/test/java/io/sentry/util/TracingUtilsTest.kt @@ -1,7 +1,7 @@ package io.sentry.util import io.sentry.Baggage -import io.sentry.IHub +import io.sentry.IScopes import io.sentry.NoOpSpan import io.sentry.Scope import io.sentry.ScopeCallback @@ -29,18 +29,18 @@ class TracingUtilsTest { val options = SentryOptions().apply { dsn = "https://key@sentry.io/proj" } - val hub = mock() + val scopes = mock() val scope = Scope(options) lateinit var span: Span val preExistingBaggage = listOf("some-baggage-key=some-baggage-value") fun setup() { - whenever(hub.options).thenReturn(options) - doAnswer { (it.arguments[0] as ScopeCallback).run(scope) }.whenever(hub).configureScope(any()) + whenever(scopes.options).thenReturn(options) + doAnswer { (it.arguments[0] as ScopeCallback).run(scope) }.whenever(scopes).configureScope(any()) span = Span( TransactionContext("name", "op", TracesSamplingDecision(true)), - SentryTracer(TransactionContext("name", "op", TracesSamplingDecision(true)), hub), - hub, + SentryTracer(TransactionContext("name", "op", TracesSamplingDecision(true)), scopes), + scopes, null, SpanOptions() ) @@ -53,7 +53,7 @@ class TracingUtilsTest { fun `returns headers if allowed from scope without span`() { fixture.setup() - val headers = TracingUtils.traceIfAllowed(fixture.hub, "https://sentry.io/hello", fixture.preExistingBaggage, null) + val headers = TracingUtils.traceIfAllowed(fixture.scopes, "https://sentry.io/hello", fixture.preExistingBaggage, null) assertNotNull(headers) assertNotNull(headers.baggageHeader) @@ -68,7 +68,7 @@ class TracingUtilsTest { fun `returns headers if allowed from scope if span is noop`() { fixture.setup() - val headers = TracingUtils.traceIfAllowed(fixture.hub, "https://sentry.io/hello", fixture.preExistingBaggage, NoOpSpan.getInstance()) + val headers = TracingUtils.traceIfAllowed(fixture.scopes, "https://sentry.io/hello", fixture.preExistingBaggage, NoOpSpan.getInstance()) assertNotNull(headers) assertNotNull(headers.baggageHeader) @@ -83,7 +83,7 @@ class TracingUtilsTest { fixture.scope.propagationContext.baggage = Baggage.fromHeader("sentry-public_key=502f25099c204a2fbf4cb16edc5975d1,sentry-sample_rate=1,sentry-trace_id=2722d9f6ec019ade60c776169d9a8904,sentry-transaction=HTTP%20GET").also { it.freeze() } fixture.setup() - val headers = TracingUtils.traceIfAllowed(fixture.hub, "https://sentry.io/hello", fixture.preExistingBaggage, null) + val headers = TracingUtils.traceIfAllowed(fixture.scopes, "https://sentry.io/hello", fixture.preExistingBaggage, null) assertNotNull(headers) assertNotNull(headers.baggageHeader) @@ -98,7 +98,7 @@ class TracingUtilsTest { fun `returns headers if allowed from span`() { fixture.setup() - val headers = TracingUtils.traceIfAllowed(fixture.hub, "https://sentry.io/hello", fixture.preExistingBaggage, fixture.span) + val headers = TracingUtils.traceIfAllowed(fixture.scopes, "https://sentry.io/hello", fixture.preExistingBaggage, fixture.span) assertNotNull(headers) assertNotNull(headers.baggageHeader) @@ -112,7 +112,7 @@ class TracingUtilsTest { fixture.options.isTraceSampling = false fixture.setup() - val headers = TracingUtils.traceIfAllowed(fixture.hub, "https://sentry.io/hello", fixture.preExistingBaggage, null) + val headers = TracingUtils.traceIfAllowed(fixture.scopes, "https://sentry.io/hello", fixture.preExistingBaggage, null) assertNull(headers) } @@ -122,7 +122,7 @@ class TracingUtilsTest { fixture.options.isTraceSampling = false fixture.setup() - val headers = TracingUtils.traceIfAllowed(fixture.hub, "https://sentry.io/hello", fixture.preExistingBaggage, fixture.span) + val headers = TracingUtils.traceIfAllowed(fixture.scopes, "https://sentry.io/hello", fixture.preExistingBaggage, fixture.span) assertNull(headers) } @@ -132,7 +132,7 @@ class TracingUtilsTest { fixture.options.setTracePropagationTargets(listOf("some-host-that-does-not-exist")) fixture.setup() - val headers = TracingUtils.traceIfAllowed(fixture.hub, "https://sentry.io/hello", fixture.preExistingBaggage, null) + val headers = TracingUtils.traceIfAllowed(fixture.scopes, "https://sentry.io/hello", fixture.preExistingBaggage, null) assertNull(headers) } @@ -142,7 +142,7 @@ class TracingUtilsTest { fixture.options.setTracePropagationTargets(listOf("some-host-that-does-not-exist")) fixture.setup() - val headers = TracingUtils.traceIfAllowed(fixture.hub, "https://sentry.io/hello", fixture.preExistingBaggage, fixture.span) + val headers = TracingUtils.traceIfAllowed(fixture.scopes, "https://sentry.io/hello", fixture.preExistingBaggage, fixture.span) assertNull(headers) } @@ -153,7 +153,7 @@ class TracingUtilsTest { val propagationContextBefore = fixture.scope.propagationContext - TracingUtils.startNewTrace(fixture.hub) + TracingUtils.startNewTrace(fixture.scopes) assertNotEquals(propagationContextBefore.traceId, fixture.scope.propagationContext.traceId) assertNotEquals(propagationContextBefore.spanId, fixture.scope.propagationContext.spanId)