From 85461090b887f4f2354beabd6eccac74a9bc4a3e Mon Sep 17 00:00:00 2001 From: Tejas Deshpande Date: Fri, 11 Apr 2025 11:16:46 -0400 Subject: [PATCH 1/8] init --- firebase-perf/firebase-perf.gradle | 2 + .../firebase/perf/FirebasePerformance.java | 18 ++++-- ...kt => FirebaseSessionsEnforcementCheck.kt} | 18 ++++-- .../FirebasePerformanceSessionSubscriber.kt | 13 ++-- .../perf/session/FirebaseSessionsHelper.kt | 24 +++++++ .../firebase/perf/session/PerfSession.java | 28 +++----- .../firebase/perf/session/SessionManager.java | 16 +++-- .../google/firebase/perf/util/Constants.java | 4 ++ .../session/FirebaseSessionsTestHelper.kt | 13 ++++ .../perf/session/PerfSessionTest.java | 49 +++++++++----- .../perf/session/SessionManagerTest.java | 26 ++++---- .../perf/session/gauges/GaugeManagerTest.java | 64 ++++++++++--------- .../perf/transport/TransportManagerTest.java | 13 ++-- 13 files changed, 177 insertions(+), 111 deletions(-) rename firebase-perf/src/main/java/com/google/firebase/perf/logging/{DebugEnforcementCheck.kt => FirebaseSessionsEnforcementCheck.kt} (62%) create mode 100644 firebase-perf/src/main/java/com/google/firebase/perf/session/FirebaseSessionsHelper.kt create mode 100644 firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt diff --git a/firebase-perf/firebase-perf.gradle b/firebase-perf/firebase-perf.gradle index 49c921edeb0..48bc21c7ffb 100644 --- a/firebase-perf/firebase-perf.gradle +++ b/firebase-perf/firebase-perf.gradle @@ -70,6 +70,7 @@ android { buildConfigField("String", "TRANSPORT_LOG_SRC", "String.valueOf(\"FIREPERF\")") buildConfigField("Boolean", "ENFORCE_DEFAULT_LOG_SRC", "Boolean.valueOf(false)") buildConfigField("String", "FIREPERF_VERSION_NAME", "String.valueOf(\"" + property("version") + "\")") + buildConfigField("Boolean", "ENFORCE_LEGACY_SESSIONS", "Boolean.valueOf(false)") if (project.hasProperty("fireperfBuildForAutopush")) { // This allows the SDK to be built for "Autopush" env when the mentioned flag @@ -77,6 +78,7 @@ android { // SDK or the Test App). buildConfigField("String", "TRANSPORT_LOG_SRC", "String.valueOf(\"FIREPERF_AUTOPUSH\")") buildConfigField("Boolean", "ENFORCE_DEFAULT_LOG_SRC", "Boolean.valueOf(true)") + buildConfigField("Boolean", "ENFORCE_LEGACY_SESSIONS", "Boolean.valueOf(true)") } minSdkVersion project.minSdkVersion diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/FirebasePerformance.java b/firebase-perf/src/main/java/com/google/firebase/perf/FirebasePerformance.java index 587bff395de..cce0389039b 100644 --- a/firebase-perf/src/main/java/com/google/firebase/perf/FirebasePerformance.java +++ b/firebase-perf/src/main/java/com/google/firebase/perf/FirebasePerformance.java @@ -34,7 +34,7 @@ import com.google.firebase.perf.config.RemoteConfigManager; import com.google.firebase.perf.logging.AndroidLogger; import com.google.firebase.perf.logging.ConsoleUrlGenerator; -import com.google.firebase.perf.logging.DebugEnforcementCheck; +import com.google.firebase.perf.logging.FirebaseSessionsEnforcementCheck; import com.google.firebase.perf.metrics.HttpMetric; import com.google.firebase.perf.metrics.Trace; import com.google.firebase.perf.session.FirebasePerformanceSessionSubscriber; @@ -44,8 +44,8 @@ import com.google.firebase.perf.util.ImmutableBundle; import com.google.firebase.perf.util.Timer; import com.google.firebase.remoteconfig.RemoteConfigComponent; -import com.google.firebase.sessions.BuildConfig; import com.google.firebase.sessions.api.FirebaseSessionsDependencies; +import com.google.firebase.sessions.api.SessionSubscriber; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.net.URL; @@ -96,6 +96,8 @@ public class FirebasePerformance implements FirebasePerformanceAttributable { // once during initialization and cache it. private final ImmutableBundle mMetadataBundle; + private final SessionSubscriber sessionSubscriber; + /** Valid HttpMethods for manual network APIs */ @StringDef({ HttpMethod.GET, @@ -169,9 +171,10 @@ public static FirebasePerformance getInstance() { this.mPerformanceCollectionForceEnabledState = false; this.configResolver = configResolver; this.mMetadataBundle = new ImmutableBundle(new Bundle()); + this.sessionSubscriber = new FirebasePerformanceSessionSubscriber(false); return; } - DebugEnforcementCheck.setEnforcement(BuildConfig.DEBUG); + FirebaseSessionsEnforcementCheck.setEnforcement(BuildConfig.ENFORCE_LEGACY_SESSIONS); TransportManager.getInstance() .initialize(firebaseApp, firebaseInstallationsApi, transportFactoryProvider); @@ -186,8 +189,8 @@ public static FirebasePerformance getInstance() { sessionManager.setApplicationContext(appContext); mPerformanceCollectionForceEnabledState = configResolver.getIsPerformanceCollectionEnabled(); - FirebaseSessionsDependencies.register( - new FirebasePerformanceSessionSubscriber(isPerformanceCollectionEnabled())); + sessionSubscriber = new FirebasePerformanceSessionSubscriber(isPerformanceCollectionEnabled()); + FirebaseSessionsDependencies.register(sessionSubscriber); if (logger.isLogcatEnabled() && isPerformanceCollectionEnabled()) { logger.info( @@ -463,4 +466,9 @@ private static ImmutableBundle extractMetadata(Context appContext) { Boolean getPerformanceCollectionForceEnabledState() { return mPerformanceCollectionForceEnabledState; } + + @VisibleForTesting + SessionSubscriber getSessionSubscriber() { + return sessionSubscriber; + } } diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/logging/DebugEnforcementCheck.kt b/firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt similarity index 62% rename from firebase-perf/src/main/java/com/google/firebase/perf/logging/DebugEnforcementCheck.kt rename to firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt index a2f3b186f9b..2a4607fadec 100644 --- a/firebase-perf/src/main/java/com/google/firebase/perf/logging/DebugEnforcementCheck.kt +++ b/firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt @@ -16,15 +16,25 @@ package com.google.firebase.perf.logging -class DebugEnforcementCheck { +import com.google.firebase.perf.session.PerfSession +import com.google.firebase.perf.session.isLegacy + +class FirebaseSessionsEnforcementCheck { companion object { /** When enabled, failed preconditions will cause assertion errors for debugging. */ @JvmStatic var enforcement: Boolean = false private var logger: AndroidLogger = AndroidLogger.getInstance() - public fun checkSession(isAqsAvailable: Boolean, failureMessage: String) { - if (!isAqsAvailable) { - Companion.logger.debug(failureMessage) + fun checkSession(session: PerfSession, failureMessage: String) { + if (session.isLegacy()) { + logger.debug("legacy session ${session.sessionId()}: $failureMessage") + assert(!enforcement) { failureMessage } + } + } + + fun checkSession(sessionId: String, failureMessage: String) { + if (sessionId.isLegacy()) { + logger.debug("legacy session ${sessionId}: $failureMessage") assert(!enforcement) { failureMessage } } } diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebasePerformanceSessionSubscriber.kt b/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebasePerformanceSessionSubscriber.kt index 08175baf1df..d3e13c63aa9 100644 --- a/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebasePerformanceSessionSubscriber.kt +++ b/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebasePerformanceSessionSubscriber.kt @@ -16,10 +16,10 @@ package com.google.firebase.perf.session +import com.google.firebase.perf.logging.FirebaseSessionsEnforcementCheck import com.google.firebase.perf.session.gauges.GaugeManager import com.google.firebase.perf.v1.ApplicationProcessState import com.google.firebase.sessions.api.SessionSubscriber -import java.util.UUID class FirebasePerformanceSessionSubscriber(override val isDataCollectionEnabled: Boolean) : SessionSubscriber { @@ -28,15 +28,10 @@ class FirebasePerformanceSessionSubscriber(override val isDataCollectionEnabled: override fun onSessionChanged(sessionDetails: SessionSubscriber.SessionDetails) { val currentPerfSession = SessionManager.getInstance().perfSession() + // TODO(b/394127311): Add logic to deal with app start gauges. + FirebaseSessionsEnforcementCheck.checkSession(currentPerfSession, "onSessionChanged") - // A [PerfSession] was created before a session was started. - if (!currentPerfSession.isAqsReady) { - GaugeManager.getInstance() - .logGaugeMetadata(currentPerfSession.sessionId(), ApplicationProcessState.FOREGROUND) - return - } - - val updatedSession = PerfSession.createWithId(UUID.randomUUID().toString()) + val updatedSession = PerfSession.createWithId(sessionDetails.sessionId) SessionManager.getInstance().updatePerfSession(updatedSession) GaugeManager.getInstance() .logGaugeMetadata(updatedSession.sessionId(), ApplicationProcessState.FOREGROUND) diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebaseSessionsHelper.kt b/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebaseSessionsHelper.kt new file mode 100644 index 00000000000..71e251119f4 --- /dev/null +++ b/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebaseSessionsHelper.kt @@ -0,0 +1,24 @@ +package com.google.firebase.perf.session + +import com.google.firebase.perf.util.Constants +import java.util.UUID + +/** Identifies whether the [PerfSession] is legacy or not. */ +fun PerfSession.isLegacy(): Boolean { + return this.sessionId().isLegacy() +} + +/** Identifies whether the string is from a legacy [PerfSession]. */ +fun String.isLegacy(): Boolean { + return this.startsWith(Constants.UNDEFINED_AQS_ID_PREFIX) +} + +/** Creates a valid session ID for [PerfSession] that can be predictably identified as legacy. */ +fun createLegacySessionId(): String { + val uuid = UUID.randomUUID().toString().replace("-", "") + return uuid.replaceRange( + 0, + Constants.UNDEFINED_AQS_ID_PREFIX.length, + Constants.UNDEFINED_AQS_ID_PREFIX + ) +} diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/session/PerfSession.java b/firebase-perf/src/main/java/com/google/firebase/perf/session/PerfSession.java index e4260034107..a89c8987896 100644 --- a/firebase-perf/src/main/java/com/google/firebase/perf/session/PerfSession.java +++ b/firebase-perf/src/main/java/com/google/firebase/perf/session/PerfSession.java @@ -24,7 +24,6 @@ import com.google.firebase.perf.util.Timer; import com.google.firebase.perf.v1.SessionVerbosity; import java.util.List; -import java.util.UUID; import java.util.concurrent.TimeUnit; /** Details of a session including a unique Id and related information. */ @@ -32,31 +31,24 @@ public class PerfSession implements Parcelable { private final Timer creationTime; private final String sessionId; private boolean isGaugeAndEventCollectionEnabled = false; - public final boolean isAqsReady; /* * Creates a PerfSession object and decides what metrics to collect. */ public static PerfSession createWithId(@Nullable String aqsSessionId) { - String sessionId; - Boolean isAqsReady; - if (aqsSessionId != null) { - sessionId = aqsSessionId; - isAqsReady = true; - } else { - sessionId = UUID.randomUUID().toString().replace("-", ""); - isAqsReady = false; + String sessionId = aqsSessionId; + if (sessionId == null) { + sessionId = FirebaseSessionsHelperKt.createLegacySessionId(); } - PerfSession session = new PerfSession(sessionId, new Clock(), isAqsReady); - session.setGaugeAndEventCollectionEnabled(shouldCollectGaugesAndEvents(sessionId)); + PerfSession session = new PerfSession(sessionId, new Clock()); + session.setGaugeAndEventCollectionEnabled(session.shouldCollectGaugesAndEvents()); return session; } /** Creates a PerfSession with the provided {@code sessionId} and {@code clock}. */ @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) - public PerfSession(String sessionId, Clock clock, boolean isAqsReady) { + public PerfSession(String sessionId, Clock clock) { this.sessionId = sessionId; - this.isAqsReady = isAqsReady; creationTime = clock.getTime(); } @@ -64,11 +56,11 @@ private PerfSession(@NonNull Parcel in) { super(); sessionId = in.readString(); isGaugeAndEventCollectionEnabled = in.readByte() != 0; - isAqsReady = in.readByte() != 0; creationTime = in.readParcelable(Timer.class.getClassLoader()); } /** Returns the sessionId for the given session. */ + @NonNull public String sessionId() { return sessionId; } @@ -160,10 +152,11 @@ public static com.google.firebase.perf.v1.PerfSession[] buildAndSort( } /** If true, Session Gauge collection is enabled. */ - public static boolean shouldCollectGaugesAndEvents(String sessionId) { + public boolean shouldCollectGaugesAndEvents() { ConfigResolver configResolver = ConfigResolver.getInstance(); return configResolver.isPerformanceMonitoringEnabled() - && (Math.abs(sessionId.hashCode() % 100) < configResolver.getSessionsSamplingRate() * 100); + && (Math.abs(this.sessionId.hashCode() % 100) + < configResolver.getSessionsSamplingRate() * 100); } /** @@ -187,7 +180,6 @@ public int describeContents() { public void writeToParcel(@NonNull Parcel out, int flags) { out.writeString(sessionId); out.writeByte((byte) (isGaugeAndEventCollectionEnabled ? 1 : 0)); - out.writeByte((byte) (isAqsReady ? 1 : 0)); out.writeParcelable(creationTime, 0); } diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/session/SessionManager.java b/firebase-perf/src/main/java/com/google/firebase/perf/session/SessionManager.java index f7f17cd4588..46320cf7622 100644 --- a/firebase-perf/src/main/java/com/google/firebase/perf/session/SessionManager.java +++ b/firebase-perf/src/main/java/com/google/firebase/perf/session/SessionManager.java @@ -19,7 +19,7 @@ import androidx.annotation.Keep; import androidx.annotation.VisibleForTesting; import com.google.firebase.perf.application.AppStateMonitor; -import com.google.firebase.perf.logging.DebugEnforcementCheck; +import com.google.firebase.perf.logging.FirebaseSessionsEnforcementCheck; import com.google.firebase.perf.session.gauges.GaugeManager; import com.google.firebase.perf.v1.ApplicationProcessState; import com.google.firebase.perf.v1.GaugeMetadata; @@ -49,8 +49,8 @@ public static SessionManager getInstance() { /** Returns the currently active PerfSession. */ public final PerfSession perfSession() { - DebugEnforcementCheck.Companion.checkSession( - perfSession.isAqsReady, "Access perf session from manger without aqs ready"); + FirebaseSessionsEnforcementCheck.Companion.checkSession( + perfSession, "Access perf session from manger without aqs ready"); return perfSession; } @@ -82,8 +82,8 @@ public void setApplicationContext(final Context appContext) { * @see PerfSession#isSessionRunningTooLong() */ public void stopGaugeCollectionIfSessionRunningTooLong() { - DebugEnforcementCheck.Companion.checkSession( - perfSession.isAqsReady, + FirebaseSessionsEnforcementCheck.Companion.checkSession( + perfSession, "Session is not ready while trying to stopGaugeCollectionIfSessionRunningTooLong"); if (perfSession.isSessionRunningTooLong()) { @@ -107,6 +107,8 @@ public void updatePerfSession(PerfSession perfSession) { this.perfSession = perfSession; + // TODO(b/394127311): Update/verify behavior for Firebase Sessions. + synchronized (clients) { for (Iterator> i = clients.iterator(); i.hasNext(); ) { SessionAwareObject callback = i.next().get(); @@ -159,8 +161,8 @@ public void unregisterForSessionUpdates(WeakReference client } private void startOrStopCollectingGauges(ApplicationProcessState appState) { - DebugEnforcementCheck.Companion.checkSession( - perfSession.isAqsReady, "Session is not ready while trying to startOrStopCollectingGauges"); + FirebaseSessionsEnforcementCheck.Companion.checkSession( + perfSession, "Session is not ready while trying to startOrStopCollectingGauges"); if (perfSession.isGaugeAndEventCollectionEnabled()) { gaugeManager.startCollectingGauges(perfSession, appState); diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/util/Constants.java b/firebase-perf/src/main/java/com/google/firebase/perf/util/Constants.java index f2704b903ce..42a126f014e 100644 --- a/firebase-perf/src/main/java/com/google/firebase/perf/util/Constants.java +++ b/firebase-perf/src/main/java/com/google/firebase/perf/util/Constants.java @@ -22,6 +22,10 @@ public class Constants { public static final String PREFS_NAME = "FirebasePerfSharedPrefs"; public static final String ENABLE_DISABLE = "isEnabled"; + // A non-hex character guarantees it isn't an AQS generated UUID. + // https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.uuid/-uuid/ + public static final String UNDEFINED_AQS_ID_PREFIX = "z"; + public static final double MIN_SAMPLING_RATE = 0.0; public static final double MAX_SAMPLING_RATE = 1.0; diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt b/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt new file mode 100644 index 00000000000..292b2bf0766 --- /dev/null +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt @@ -0,0 +1,13 @@ +package com.google.firebase.perf.session + +import com.google.firebase.perf.util.Clock + +fun createTestSession(suffix: Int): PerfSession { + // TODO(b/394127311): Add a method to verify legacy behavior. + // only hex characters and so it's AQS. + return PerfSession(testSessionId(suffix), Clock()) +} + +fun testSessionId(suffix: Int): String { + return "abc$suffix" +} diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java b/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java index 19d8aadf76b..9e4e3149e62 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java @@ -62,12 +62,24 @@ public void setUp() { @Test public void instanceCreation() { - PerfSession session = new PerfSession("sessionId", mockClock, true); + PerfSession session = PerfSession.createWithId("sessionId"); assertThat(session).isNotNull(); session.setGaugeAndEventCollectionEnabled(true); - Assert.assertTrue(session.isGaugeAndEventCollectionEnabled()); + assertThat(session.isVerbose()).isTrue(); session.setGaugeAndEventCollectionEnabled(false); - Assert.assertFalse(session.isGaugeAndEventCollectionEnabled()); + assertThat(session.isVerbose()).isFalse(); + assertThat(FirebaseSessionsHelperKt.isLegacy(session)).isFalse(); + } + + @Test + public void legacyInstanceCreation() { + PerfSession perfSession = PerfSession.createWithId(null); + assertThat(perfSession).isNotNull(); + perfSession.setGaugeAndEventCollectionEnabled(true); + assertThat(perfSession.isVerbose()).isTrue(); + perfSession.setGaugeAndEventCollectionEnabled(false); + assertThat(perfSession.isVerbose()).isFalse(); + assertThat(FirebaseSessionsHelperKt.isLegacy(perfSession)).isTrue(); } @Test @@ -76,19 +88,20 @@ public void shouldCollectGaugesAndEvents_perfMonDisabledAtRuntime_sessionNotVerb Bundle bundle = new Bundle(); bundle.putFloat("sessions_sampling_percentage", 100); configResolver.setMetadataBundle(new ImmutableBundle(bundle)); + PerfSession testSession = PerfSession.createWithId("aqsSessionId"); // By default, session is verbose if developer has set 100% of session verbosity. - assertThat(PerfSession.shouldCollectGaugesAndEvents("sessionId")).isTrue(); + assertThat(testSession.shouldCollectGaugesAndEvents()).isTrue(); // Case #1: developer has disabled Performance Monitoring during runtime. configResolver.setIsPerformanceCollectionEnabled(false); - assertThat(PerfSession.shouldCollectGaugesAndEvents("sessionId")).isFalse(); + assertThat(testSession.shouldCollectGaugesAndEvents()).isFalse(); // Case #2: developer has enabled Performance Monitoring during runtime. configResolver.setIsPerformanceCollectionEnabled(true); - assertThat(PerfSession.shouldCollectGaugesAndEvents("sessionId")).isTrue(); + assertThat(testSession.shouldCollectGaugesAndEvents()).isTrue(); } @Test @@ -99,20 +112,21 @@ public void shouldCollectGaugesAndEvents_perfMonDisabledAtBuildtime_verbosityDep bundle.putFloat("sessions_sampling_percentage", 100); bundle.putBoolean("firebase_performance_collection_enabled", false); configResolver.setMetadataBundle(new ImmutableBundle(bundle)); + PerfSession testSession = PerfSession.createWithId("aqsSessionId"); // By default, session is not verbose if developer disabled performance monitoring at build // time. - assertThat(PerfSession.shouldCollectGaugesAndEvents("sessionId")).isFalse(); + assertThat(testSession.shouldCollectGaugesAndEvents()).isFalse(); // Case #1: developer has enabled Performance Monitoring during runtime. configResolver.setIsPerformanceCollectionEnabled(true); - assertThat(PerfSession.shouldCollectGaugesAndEvents("sessionId")).isTrue(); + assertThat(testSession.shouldCollectGaugesAndEvents()).isTrue(); // Case #2: developer has disabled Performance Monitoring during runtime. configResolver.setIsPerformanceCollectionEnabled(false); - assertThat(PerfSession.shouldCollectGaugesAndEvents("sessionId")).isFalse(); + assertThat(testSession.shouldCollectGaugesAndEvents()).isFalse(); } @Test @@ -122,24 +136,25 @@ public void shouldCollectGaugesAndEvents_perfMonDeactivated_sessionNotVerbose() bundle.putFloat("sessions_sampling_percentage", 100); bundle.putBoolean("firebase_performance_collection_deactivated", true); configResolver.setMetadataBundle(new ImmutableBundle(bundle)); + PerfSession testSession = PerfSession.createWithId("aqsSessionId"); // Session will never be verbose if developer deactivated performance monitoring at build time. - assertThat(PerfSession.shouldCollectGaugesAndEvents("sessionId")).isFalse(); + assertThat(testSession.shouldCollectGaugesAndEvents()).isFalse(); // Case #1: developer has enabled Performance Monitoring during runtime. configResolver.setIsPerformanceCollectionEnabled(true); - assertThat(PerfSession.shouldCollectGaugesAndEvents("sessionId")).isFalse(); + assertThat(testSession.shouldCollectGaugesAndEvents()).isFalse(); // Case #2: developer has disabled Performance Monitoring during runtime. configResolver.setIsPerformanceCollectionEnabled(false); - assertThat(PerfSession.shouldCollectGaugesAndEvents("sessionId")).isFalse(); + assertThat(testSession.shouldCollectGaugesAndEvents()).isFalse(); } @Test public void testPerfSessionConversion() { - PerfSession session1 = new PerfSession("sessionId", mockClock, true); + PerfSession session1 = PerfSession.createWithId("aqsSessionId"); session1.setGaugeAndEventCollectionEnabled(true); com.google.firebase.perf.v1.PerfSession perfSession = session1.build(); @@ -150,7 +165,7 @@ public void testPerfSessionConversion() { @Test public void testPerfSessionConversionWithoutVerbosity() { - PerfSession session1 = new PerfSession("sessionId", mockClock, true); + PerfSession session1 = PerfSession.createWithId("sessionId"); com.google.firebase.perf.v1.PerfSession perfSession = session1.build(); Assert.assertEquals(session1.sessionId(), perfSession.getSessionId()); @@ -216,7 +231,7 @@ public void testIsExpiredReturnsFalseWhenCurrentSessionLengthIsLessThanMaxSessio - TimeUnit.MINUTES.toMicros(1)); // Default Max Session Length is 4 hours when(mockClock.getTime()).thenReturn(mockTimer); - PerfSession session = new PerfSession("sessionId", mockClock, true); + PerfSession session = new PerfSession("sessionId", mockClock); assertThat(session.isSessionRunningTooLong()).isFalse(); } @@ -227,7 +242,7 @@ public void testIsExpiredReturnsFalseWhenCurrentSessionLengthIsEqualToMaxSession .thenReturn(TimeUnit.HOURS.toMicros(4)); // Default Max Session Length is 4 hours when(mockClock.getTime()).thenReturn(mockTimer); - PerfSession session = new PerfSession("sessionId", mockClock, true); + PerfSession session = new PerfSession("sessionId", mockClock); assertThat(session.isSessionRunningTooLong()).isFalse(); } @@ -238,7 +253,7 @@ public void testIsExpiredReturnsTrueWhenCurrentSessionLengthIsGreaterThanMaxSess .thenReturn(TimeUnit.HOURS.toMicros(5)); // Default Max Session Length is 4 hours when(mockClock.getTime()).thenReturn(mockTimer); - PerfSession session = new PerfSession("sessionId", mockClock, true); + PerfSession session = new PerfSession("sessionId", mockClock); assertThat(session.isSessionRunningTooLong()).isTrue(); } } diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java b/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java index 2e1e080a98c..a4d3c315ad3 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java @@ -15,6 +15,7 @@ package com.google.firebase.perf.session; import static com.google.common.truth.Truth.assertThat; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.createTestSession; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -90,7 +91,7 @@ public void testUpdatePerfSessionMakesGaugeManagerStopCollectingGaugesIfSessionI SessionManager testSessionManager = new SessionManager(mockGaugeManager, mockPerfSession, mockAppStateMonitor); - testSessionManager.updatePerfSession(PerfSession.createWithId("testSessionId")); + testSessionManager.updatePerfSession(createTestSession(1)); verify(mockGaugeManager).stopCollectingGauges(); } @@ -100,9 +101,8 @@ public void testUpdatePerfSessionMakesGaugeManagerStopCollectingGaugesWhenSessio forceSessionsFeatureDisabled(); SessionManager testSessionManager = - new SessionManager( - mockGaugeManager, PerfSession.createWithId("testSessionId"), mockAppStateMonitor); - testSessionManager.updatePerfSession(PerfSession.createWithId("testSessionId2")); + new SessionManager(mockGaugeManager, createTestSession(1), mockAppStateMonitor); + testSessionManager.updatePerfSession(createTestSession(2)); verify(mockGaugeManager).stopCollectingGauges(); } @@ -112,7 +112,7 @@ public void testSessionIdDoesNotUpdateIfPerfSessionRunsTooLong() { Timer mockTimer = mock(Timer.class); when(mockClock.getTime()).thenReturn(mockTimer); - PerfSession session = new PerfSession("sessionId", mockClock, true); + PerfSession session = createTestSession(1); SessionManager testSessionManager = new SessionManager(mockGaugeManager, session, mockAppStateMonitor); @@ -122,7 +122,7 @@ public void testSessionIdDoesNotUpdateIfPerfSessionRunsTooLong() { .thenReturn(TimeUnit.HOURS.toMicros(5)); // Default Max Session Length is 4 hours assertThat(session.isSessionRunningTooLong()).isTrue(); - assertThat(testSessionManager.perfSession().sessionId()).isEqualTo("sessionId"); + assertThat(testSessionManager.perfSession().sessionId()).isEqualTo(session.sessionId()); } @Test @@ -131,10 +131,10 @@ public void testUpdatePerfSessionStartsCollectingGaugesIfSessionIsVerbose() { when(mockClock.getTime()).thenReturn(mockTimer); when(mockAppStateMonitor.getAppState()).thenReturn(ApplicationProcessState.FOREGROUND); - PerfSession previousSession = new PerfSession("previousSession", mockClock, true); + PerfSession previousSession = createTestSession(1); previousSession.setGaugeAndEventCollectionEnabled(false); - PerfSession newSession = new PerfSession("newSession", mockClock, true); + PerfSession newSession = createTestSession(2); newSession.setGaugeAndEventCollectionEnabled(true); SessionManager testSessionManager = @@ -155,7 +155,7 @@ public void testPerfSession_sessionAwareObjects_doesntNotifyIfNotRegistered() { FakeSessionAwareObject spySessionAwareObjectOne = spy(new FakeSessionAwareObject()); FakeSessionAwareObject spySessionAwareObjectTwo = spy(new FakeSessionAwareObject()); - testSessionManager.updatePerfSession(PerfSession.createWithId("testSessionId1")); + testSessionManager.updatePerfSession(createTestSession(1)); verify(spySessionAwareObjectOne, never()) .updateSession(ArgumentMatchers.nullable(PerfSession.class)); @@ -174,8 +174,8 @@ public void testPerfSession_sessionAwareObjects_NotifiesIfRegistered() { testSessionManager.registerForSessionUpdates(new WeakReference<>(spySessionAwareObjectOne)); testSessionManager.registerForSessionUpdates(new WeakReference<>(spySessionAwareObjectTwo)); - testSessionManager.updatePerfSession(PerfSession.createWithId("testSessionId1")); - testSessionManager.updatePerfSession(PerfSession.createWithId("testSessionId2")); + testSessionManager.updatePerfSession(createTestSession(1)); + testSessionManager.updatePerfSession(createTestSession(2)); verify(spySessionAwareObjectOne, times(2)) .updateSession(ArgumentMatchers.nullable(PerfSession.class)); @@ -199,11 +199,11 @@ public void testPerfSession_sessionAwareObjects_DoesNotNotifyIfUnregistered() { testSessionManager.registerForSessionUpdates(weakSpySessionAwareObjectOne); testSessionManager.registerForSessionUpdates(weakSpySessionAwareObjectTwo); - testSessionManager.updatePerfSession(PerfSession.createWithId("testSessionId1")); + testSessionManager.updatePerfSession(createTestSession(1)); testSessionManager.unregisterForSessionUpdates(weakSpySessionAwareObjectOne); testSessionManager.unregisterForSessionUpdates(weakSpySessionAwareObjectTwo); - testSessionManager.updatePerfSession(PerfSession.createWithId("testSessionId2")); + testSessionManager.updatePerfSession(createTestSession(2)); verify(spySessionAwareObjectOne, times(1)) .updateSession(ArgumentMatchers.nullable(PerfSession.class)); diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/gauges/GaugeManagerTest.java b/firebase-perf/src/test/java/com/google/firebase/perf/session/gauges/GaugeManagerTest.java index 7ba04852890..10ac1907e4b 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/gauges/GaugeManagerTest.java +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/gauges/GaugeManagerTest.java @@ -25,6 +25,8 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.createTestSession; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.testSessionId; import androidx.test.core.app.ApplicationProvider; import com.google.firebase.components.Lazy; @@ -124,7 +126,7 @@ public void setUp() { @Test public void testStartCollectingGaugesStartsCollectingMetricsInBackgroundState() { - PerfSession fakeSession = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession, ApplicationProcessState.BACKGROUND); verify(fakeCpuGaugeCollector) .startCollecting( @@ -138,7 +140,7 @@ public void testStartCollectingGaugesStartsCollectingMetricsInBackgroundState() @Test public void testStartCollectingGaugesStartsCollectingMetricsInForegroundState() { - PerfSession fakeSession = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession, ApplicationProcessState.FOREGROUND); verify(fakeCpuGaugeCollector) .startCollecting( @@ -153,7 +155,7 @@ public void testStartCollectingGaugesStartsCollectingMetricsInForegroundState() @Test public void testStartCollectingGaugesDoesNotStartCollectingMetricsWithUnknownApplicationProcessState() { - PerfSession fakeSession = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession = createTestSession(1); testGaugeManager.startCollectingGauges( fakeSession, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); verify(fakeCpuGaugeCollector, never()) @@ -167,7 +169,7 @@ public void testStartCollectingGaugesStartsCollectingMetricsInForegroundState() stopCollectingCPUMetric_invalidCPUCaptureFrequency_OtherMetricsWithValidFrequencyInBackground() { // PASS 1: Test with 0 doReturn(0L).when(mockConfigResolver).getSessionsCpuCaptureFrequencyBackgroundMs(); - PerfSession fakeSession1 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession1 = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession1, ApplicationProcessState.BACKGROUND); // Verify that Cpu metric collection is not started @@ -180,7 +182,7 @@ public void testStartCollectingGaugesStartsCollectingMetricsInForegroundState() // PASS 2: Test with -ve value doReturn(-25L).when(mockConfigResolver).getSessionsCpuCaptureFrequencyBackgroundMs(); - PerfSession fakeSession2 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession2 = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession2, ApplicationProcessState.BACKGROUND); // Verify that Cpu metric collection is not started @@ -197,7 +199,7 @@ public void testStartCollectingGaugesStartsCollectingMetricsInForegroundState() startCollectingGaugesOnBackground_invalidMemoryCaptureMs_onlyDisableMemoryCollection() { // PASS 1: Test with 0 doReturn(0L).when(mockConfigResolver).getSessionsMemoryCaptureFrequencyBackgroundMs(); - PerfSession fakeSession1 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession1 = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession1, ApplicationProcessState.BACKGROUND); // Verify that Memory metric collection is not started @@ -210,7 +212,7 @@ public void testStartCollectingGaugesStartsCollectingMetricsInForegroundState() // PASS 2: Test with -ve value doReturn(-25L).when(mockConfigResolver).getSessionsMemoryCaptureFrequencyBackgroundMs(); - PerfSession fakeSession2 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession2 = createTestSession(2); testGaugeManager.startCollectingGauges(fakeSession2, ApplicationProcessState.BACKGROUND); // Verify that Memory metric collection is not started @@ -226,7 +228,7 @@ public void testStartCollectingGaugesStartsCollectingMetricsInForegroundState() public void stopCollectingCPUMetric_invalidCPUCaptureFrequency_OtherMetricsWithValidFrequency() { // PASS 1: Test with 0 doReturn(0L).when(mockConfigResolver).getSessionsCpuCaptureFrequencyForegroundMs(); - PerfSession fakeSession1 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession1 = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession1, ApplicationProcessState.FOREGROUND); // Verify that Cpu metric collection is not started @@ -239,7 +241,7 @@ public void stopCollectingCPUMetric_invalidCPUCaptureFrequency_OtherMetricsWithV // PASS 2: Test with -ve value doReturn(-25L).when(mockConfigResolver).getSessionsCpuCaptureFrequencyForegroundMs(); - PerfSession fakeSession2 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession2 = createTestSession(2); testGaugeManager.startCollectingGauges(fakeSession2, ApplicationProcessState.FOREGROUND); // Verify that Cpu metric collection is not started @@ -256,7 +258,7 @@ public void stopCollectingCPUMetric_invalidCPUCaptureFrequency_OtherMetricsWithV startCollectingGaugesOnForeground_invalidMemoryCaptureMs_onlyDisableMemoryCollection() { // PASS 1: Test with 0 doReturn(0L).when(mockConfigResolver).getSessionsMemoryCaptureFrequencyForegroundMs(); - PerfSession fakeSession1 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession1 = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession1, ApplicationProcessState.FOREGROUND); // Verify that Memory metric collection is not started @@ -269,7 +271,7 @@ public void stopCollectingCPUMetric_invalidCPUCaptureFrequency_OtherMetricsWithV // PASS 2: Test with -ve value doReturn(-25L).when(mockConfigResolver).getSessionsMemoryCaptureFrequencyForegroundMs(); - PerfSession fakeSession2 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession2 = createTestSession(2); testGaugeManager.startCollectingGauges(fakeSession2, ApplicationProcessState.FOREGROUND); // Verify that Memory metric collection is not started @@ -283,7 +285,7 @@ public void stopCollectingCPUMetric_invalidCPUCaptureFrequency_OtherMetricsWithV @Test public void testStartCollectingGaugesDoesNotStartAJobToConsumeMetricsWithUnknownAppState() { - PerfSession fakeSession = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession = createTestSession(1); testGaugeManager.startCollectingGauges( fakeSession, ApplicationProcessState.APPLICATION_PROCESS_STATE_UNKNOWN); assertThat(fakeScheduledExecutorService.isEmpty()).isTrue(); @@ -294,14 +296,14 @@ public void stopCollectingCPUMetrics_invalidCPUCaptureFrequency_appInForegrounf( // PASS 1: Test with 0 doReturn(0L).when(mockConfigResolver).getSessionsCpuCaptureFrequencyForegroundMs(); - PerfSession fakeSession1 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession1 = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession1, ApplicationProcessState.FOREGROUND); assertThat(fakeScheduledExecutorService.isEmpty()).isFalse(); // PASS 2: Test with -ve value doReturn(-25L).when(mockConfigResolver).getSessionsCpuCaptureFrequencyForegroundMs(); - PerfSession fakeSession2 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession2 = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession2, ApplicationProcessState.FOREGROUND); assertThat(fakeScheduledExecutorService.isEmpty()).isFalse(); } @@ -311,14 +313,14 @@ public void stopCollectingGauges_invalidMemoryCollectionFrequency_appInForegroun // PASS 1: Test with 0 doReturn(0L).when(mockConfigResolver).getSessionsMemoryCaptureFrequencyForegroundMs(); - PerfSession fakeSession1 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession1 = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession1, ApplicationProcessState.FOREGROUND); assertThat(fakeScheduledExecutorService.isEmpty()).isFalse(); // PASS 2: Test with -ve value doReturn(-25L).when(mockConfigResolver).getSessionsMemoryCaptureFrequencyForegroundMs(); - PerfSession fakeSession2 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession2 = createTestSession(2); testGaugeManager.startCollectingGauges(fakeSession2, ApplicationProcessState.FOREGROUND); assertThat(fakeScheduledExecutorService.isEmpty()).isFalse(); } @@ -329,7 +331,7 @@ public void stopCollectingGauges_invalidGaugeCollectionFrequency_appInForeground doReturn(0L).when(mockConfigResolver).getSessionsCpuCaptureFrequencyForegroundMs(); doReturn(0L).when(mockConfigResolver).getSessionsMemoryCaptureFrequencyForegroundMs(); - PerfSession fakeSession1 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession1 = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession1, ApplicationProcessState.FOREGROUND); assertThat(fakeScheduledExecutorService.isEmpty()).isTrue(); @@ -337,7 +339,7 @@ public void stopCollectingGauges_invalidGaugeCollectionFrequency_appInForeground doReturn(-25L).when(mockConfigResolver).getSessionsCpuCaptureFrequencyForegroundMs(); doReturn(-25L).when(mockConfigResolver).getSessionsMemoryCaptureFrequencyForegroundMs(); - PerfSession fakeSession2 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession2 = createTestSession(2); testGaugeManager.startCollectingGauges(fakeSession2, ApplicationProcessState.FOREGROUND); assertThat(fakeScheduledExecutorService.isEmpty()).isTrue(); } @@ -347,7 +349,7 @@ public void startCollectingGauges_validGaugeCollectionFrequency_appInForeground( doReturn(25L).when(mockConfigResolver).getSessionsCpuCaptureFrequencyForegroundMs(); doReturn(15L).when(mockConfigResolver).getSessionsMemoryCaptureFrequencyForegroundMs(); - PerfSession fakeSession = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession, ApplicationProcessState.FOREGROUND); assertThat(fakeScheduledExecutorService.isEmpty()).isFalse(); @@ -357,7 +359,7 @@ public void startCollectingGauges_validGaugeCollectionFrequency_appInForeground( @Test public void testStartCollectingGaugesStartsAJobToConsumeTheGeneratedMetrics() { - PerfSession fakeSession = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession, ApplicationProcessState.BACKGROUND); assertThat(fakeScheduledExecutorService.isEmpty()).isFalse(); @@ -383,15 +385,15 @@ public void testStartCollectingGaugesStartsAJobToConsumeTheGeneratedMetrics() { getLastRecordedGaugeMetric(ApplicationProcessState.BACKGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric, fakeCpuMetricReading1, fakeCpuMetricReading2); + testSessionId(1), recordedGaugeMetric, fakeCpuMetricReading1, fakeCpuMetricReading2); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric, fakeMemoryMetricReading1, fakeMemoryMetricReading2); + testSessionId(1), recordedGaugeMetric, fakeMemoryMetricReading1, fakeMemoryMetricReading2); } @Test public void testStopCollectingGaugesStopsCollectingAllGaugeMetrics() { - PerfSession fakeSession = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession, ApplicationProcessState.BACKGROUND); verify(fakeCpuGaugeCollector) @@ -405,7 +407,7 @@ public void testStopCollectingGaugesStopsCollectingAllGaugeMetrics() { @Test public void testStopCollectingGaugesCreatesOneLastJobToConsumeAnyPendingMetrics() { - PerfSession fakeSession = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession, ApplicationProcessState.BACKGROUND); assertThat(fakeScheduledExecutorService.isEmpty()).isFalse(); @@ -426,14 +428,14 @@ public void testStopCollectingGaugesCreatesOneLastJobToConsumeAnyPendingMetrics( GaugeMetric recordedGaugeMetric = getLastRecordedGaugeMetric(ApplicationProcessState.BACKGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric, fakeCpuMetricReading); + testSessionId(1), recordedGaugeMetric, fakeCpuMetricReading); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric, fakeMemoryMetricReading); + testSessionId(1), recordedGaugeMetric, fakeMemoryMetricReading); } @Test public void testGaugeManagerClearsTheQueueEachRun() { - PerfSession fakeSession = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession = createTestSession(1); testGaugeManager.startCollectingGauges(fakeSession, ApplicationProcessState.BACKGROUND); @@ -465,7 +467,7 @@ public void testGaugeManagerClearsTheQueueEachRun() { @Test public void testStartingGaugeManagerWithNewSessionIdButSameAppState() { - PerfSession fakeSession1 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession1 = createTestSession(1); // Start collecting Gauges. testGaugeManager.startCollectingGauges(fakeSession1, ApplicationProcessState.BACKGROUND); @@ -479,9 +481,9 @@ public void testStartingGaugeManagerWithNewSessionIdButSameAppState() { GaugeMetric recordedGaugeMetric1 = getLastRecordedGaugeMetric(ApplicationProcessState.BACKGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric1, fakeCpuMetricReading1); + testSessionId(1), recordedGaugeMetric1, fakeCpuMetricReading1); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric1, fakeMemoryMetricReading1); + testSessionId(1), recordedGaugeMetric1, fakeMemoryMetricReading1); // One Cpu and Memory metric was added when the gauge was collecting for the previous sessionId. CpuMetricReading fakeCpuMetricReading2 = createFakeCpuMetricReading(400, 500); @@ -490,7 +492,7 @@ public void testStartingGaugeManagerWithNewSessionIdButSameAppState() { createFakeAndroidMetricReading(/* currentUsedAppJavaHeapMemoryKb= */ 2345); fakeMemoryGaugeCollector.memoryMetricReadings.add(fakeMemoryMetricReading2); - PerfSession fakeSession2 = new PerfSession("sessionId2", new Clock(), true); + PerfSession fakeSession2 = createTestSession(1); // Start collecting gauges for new session, but same app state. testGaugeManager.startCollectingGauges(fakeSession2, ApplicationProcessState.BACKGROUND); diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/transport/TransportManagerTest.java b/firebase-perf/src/test/java/com/google/firebase/perf/transport/TransportManagerTest.java index d1a5e1a7cc2..1814f1dfaa6 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/transport/TransportManagerTest.java +++ b/firebase-perf/src/test/java/com/google/firebase/perf/transport/TransportManagerTest.java @@ -25,6 +25,8 @@ import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.robolectric.Shadows.shadowOf; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.createTestSession; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.testSessionId; import android.content.Context; import android.content.pm.PackageInfo; @@ -1168,9 +1170,7 @@ public void logGaugeMetric_globalCustomAttributesAreNotAdded() { public void logTraceMetric_sessionEnabled_doesNotStripOffSessionId() { TraceMetric.Builder validTrace = createValidTraceMetric().toBuilder(); List perfSessions = new ArrayList<>(); - perfSessions.add( - new com.google.firebase.perf.session.PerfSession("fakeSessionId", new Clock(), true) - .build()); + perfSessions.add(createTestSession(1).build()); validTrace.addAllPerfSessions(perfSessions); testTransportManager.log(validTrace.build()); @@ -1179,7 +1179,7 @@ public void logTraceMetric_sessionEnabled_doesNotStripOffSessionId() { PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getTraceMetric().getPerfSessionsCount()).isEqualTo(1); assertThat(loggedPerfMetric.getTraceMetric().getPerfSessions(0).getSessionId()) - .isEqualTo("fakeSessionId"); + .isEqualTo(testSessionId(1)); } @Test @@ -1187,8 +1187,7 @@ public void logNetworkMetric_sessionEnabled_doesNotStripOffSessionId() { NetworkRequestMetric.Builder validNetworkRequest = createValidNetworkRequestMetric().toBuilder(); List perfSessions = new ArrayList<>(); - perfSessions.add( - new com.google.firebase.perf.session.PerfSession("fakeSessionId", new Clock(), true) + perfSessions.add(createTestSession(1) .build()); validNetworkRequest.clearPerfSessions().addAllPerfSessions(perfSessions); @@ -1198,7 +1197,7 @@ public void logNetworkMetric_sessionEnabled_doesNotStripOffSessionId() { PerfMetric loggedPerfMetric = getLastLoggedEvent(times(1)); assertThat(loggedPerfMetric.getNetworkRequestMetric().getPerfSessionsCount()).isEqualTo(1); assertThat(loggedPerfMetric.getNetworkRequestMetric().getPerfSessions(0).getSessionId()) - .isEqualTo("fakeSessionId"); + .isEqualTo(testSessionId(1)); } @Test From 2b14d29b517b31ff8555bbfcf5d2d2ade27504a2 Mon Sep 17 00:00:00 2001 From: Tejas Deshpande Date: Fri, 11 Apr 2025 11:48:12 -0400 Subject: [PATCH 2/8] Fix unit tests --- .../session/FirebaseSessionsTestHelper.kt | 2 +- .../perf/session/SessionManagerTest.java | 5 +- .../perf/session/gauges/GaugeManagerTest.java | 62 ++++++++++--------- .../perf/transport/TransportManagerTest.java | 8 +-- 4 files changed, 39 insertions(+), 38 deletions(-) diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt b/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt index 292b2bf0766..fe9033ced6e 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt @@ -9,5 +9,5 @@ fun createTestSession(suffix: Int): PerfSession { } fun testSessionId(suffix: Int): String { - return "abc$suffix" + return "abc$suffix" } diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java b/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java index a4d3c315ad3..58ca631781f 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java @@ -16,6 +16,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.createTestSession; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.testSessionId; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -58,7 +59,7 @@ public class SessionManagerTest extends FirebasePerformanceTestBase { @Before public void setUp() { initMocks(this); - when(mockPerfSession.sessionId()).thenReturn("sessionId"); + when(mockPerfSession.sessionId()).thenReturn(testSessionId(5)); when(mockAppStateMonitor.isColdStart()).thenReturn(false); AppStateMonitor.getInstance().setIsColdStart(false); } @@ -122,7 +123,7 @@ public void testSessionIdDoesNotUpdateIfPerfSessionRunsTooLong() { .thenReturn(TimeUnit.HOURS.toMicros(5)); // Default Max Session Length is 4 hours assertThat(session.isSessionRunningTooLong()).isTrue(); - assertThat(testSessionManager.perfSession().sessionId()).isEqualTo(session.sessionId()); + assertThat(testSessionManager.perfSession().sessionId()).isEqualTo(testSessionId(1)); } @Test diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/gauges/GaugeManagerTest.java b/firebase-perf/src/test/java/com/google/firebase/perf/session/gauges/GaugeManagerTest.java index 10ac1907e4b..61ae0c57132 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/gauges/GaugeManagerTest.java +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/gauges/GaugeManagerTest.java @@ -15,6 +15,8 @@ package com.google.firebase.perf.session.gauges; import static com.google.common.truth.Truth.assertThat; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.createTestSession; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.testSessionId; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; @@ -25,8 +27,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.createTestSession; -import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.testSessionId; import androidx.test.core.app.ApplicationProvider; import com.google.firebase.components.Lazy; @@ -34,7 +34,6 @@ import com.google.firebase.perf.config.ConfigResolver; import com.google.firebase.perf.session.PerfSession; import com.google.firebase.perf.transport.TransportManager; -import com.google.firebase.perf.util.Clock; import com.google.firebase.perf.util.Timer; import com.google.firebase.perf.v1.AndroidMemoryReading; import com.google.firebase.perf.v1.ApplicationProcessState; @@ -492,7 +491,7 @@ public void testStartingGaugeManagerWithNewSessionIdButSameAppState() { createFakeAndroidMetricReading(/* currentUsedAppJavaHeapMemoryKb= */ 2345); fakeMemoryGaugeCollector.memoryMetricReadings.add(fakeMemoryMetricReading2); - PerfSession fakeSession2 = createTestSession(1); + PerfSession fakeSession2 = createTestSession(2); // Start collecting gauges for new session, but same app state. testGaugeManager.startCollectingGauges(fakeSession2, ApplicationProcessState.BACKGROUND); @@ -502,9 +501,9 @@ public void testStartingGaugeManagerWithNewSessionIdButSameAppState() { GaugeMetric recordedGaugeMetric2 = getLastRecordedGaugeMetric(ApplicationProcessState.BACKGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric2, fakeCpuMetricReading2); + testSessionId(1), recordedGaugeMetric2, fakeCpuMetricReading2); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric2, fakeMemoryMetricReading2); + testSessionId(1), recordedGaugeMetric2, fakeMemoryMetricReading2); // Collect some more Cpu and Memory metrics and verify that they're associated with new // sessionId and state. @@ -518,14 +517,14 @@ public void testStartingGaugeManagerWithNewSessionIdButSameAppState() { GaugeMetric recordedGaugeMetric3 = getLastRecordedGaugeMetric(ApplicationProcessState.BACKGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId2", recordedGaugeMetric3, fakeCpuMetricReading3); + testSessionId(2), recordedGaugeMetric3, fakeCpuMetricReading3); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId2", recordedGaugeMetric3, fakeMemoryMetricReading3); + testSessionId(2), recordedGaugeMetric3, fakeMemoryMetricReading3); } @Test public void testStartGaugeManagerWithSameSessionIdButDifferentAppState() { - PerfSession fakeSession = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession = createTestSession(1); // Start collecting Gauges. testGaugeManager.startCollectingGauges(fakeSession, ApplicationProcessState.BACKGROUND); @@ -539,9 +538,9 @@ public void testStartGaugeManagerWithSameSessionIdButDifferentAppState() { GaugeMetric recordedGaugeMetric1 = getLastRecordedGaugeMetric(ApplicationProcessState.BACKGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric1, fakeCpuMetricReading1); + testSessionId(1), recordedGaugeMetric1, fakeCpuMetricReading1); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric1, fakeMemoryMetricReading1); + testSessionId(1), recordedGaugeMetric1, fakeMemoryMetricReading1); // One Cpu and Memory metric was added when the gauge was collecting for the previous sessionId. CpuMetricReading fakeCpuMetricReading2 = createFakeCpuMetricReading(400, 500); @@ -558,9 +557,9 @@ public void testStartGaugeManagerWithSameSessionIdButDifferentAppState() { GaugeMetric recordedGaugeMetric2 = getLastRecordedGaugeMetric(ApplicationProcessState.BACKGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric2, fakeCpuMetricReading2); + testSessionId(1), recordedGaugeMetric2, fakeCpuMetricReading2); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric2, fakeMemoryMetricReading2); + testSessionId(1), recordedGaugeMetric2, fakeMemoryMetricReading2); // Collect some more Cpu and Memory metrics and verify that they're associated with new // sessionId and state. @@ -574,14 +573,14 @@ public void testStartGaugeManagerWithSameSessionIdButDifferentAppState() { GaugeMetric recordedGaugeMetric3 = getLastRecordedGaugeMetric(ApplicationProcessState.FOREGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric3, fakeCpuMetricReading3); + testSessionId(1), recordedGaugeMetric3, fakeCpuMetricReading3); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric3, fakeMemoryMetricReading3); + testSessionId(1), recordedGaugeMetric3, fakeMemoryMetricReading3); } @Test public void testStartGaugeManagerWithNewSessionIdAndNewAppState() { - PerfSession fakeSession1 = new PerfSession("sessionId", new Clock(), true); + PerfSession fakeSession1 = createTestSession(1); // Start collecting Gauges. testGaugeManager.startCollectingGauges(fakeSession1, ApplicationProcessState.BACKGROUND); @@ -595,9 +594,9 @@ public void testStartGaugeManagerWithNewSessionIdAndNewAppState() { GaugeMetric recordedGaugeMetric1 = getLastRecordedGaugeMetric(ApplicationProcessState.BACKGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric1, fakeCpuMetricReading1); + testSessionId(1), recordedGaugeMetric1, fakeCpuMetricReading1); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric1, fakeMemoryMetricReading1); + testSessionId(1), recordedGaugeMetric1, fakeMemoryMetricReading1); // One Cpu and Memory metric was added when the gauge was collecting for the previous sessionId. CpuMetricReading fakeCpuMetricReading2 = createFakeCpuMetricReading(400, 500); @@ -606,7 +605,7 @@ public void testStartGaugeManagerWithNewSessionIdAndNewAppState() { createFakeAndroidMetricReading(/* currentUsedAppJavaHeapMemoryKb= */ 2345); fakeMemoryGaugeCollector.memoryMetricReadings.add(fakeMemoryMetricReading2); - PerfSession fakeSession2 = new PerfSession("sessionId2", new Clock(), true); + PerfSession fakeSession2 = createTestSession(2); // Start collecting gauges for new session and new app state testGaugeManager.startCollectingGauges(fakeSession2, ApplicationProcessState.FOREGROUND); @@ -616,9 +615,9 @@ public void testStartGaugeManagerWithNewSessionIdAndNewAppState() { GaugeMetric recordedGaugeMetric2 = getLastRecordedGaugeMetric(ApplicationProcessState.BACKGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric2, fakeCpuMetricReading2); + testSessionId(1), recordedGaugeMetric2, fakeCpuMetricReading2); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId", recordedGaugeMetric2, fakeMemoryMetricReading2); + testSessionId(1), recordedGaugeMetric2, fakeMemoryMetricReading2); // Collect some more Cpu and Memory metrics and verify that they're associated with new // sessionId and state. @@ -632,9 +631,9 @@ public void testStartGaugeManagerWithNewSessionIdAndNewAppState() { GaugeMetric recordedGaugeMetric3 = getLastRecordedGaugeMetric(ApplicationProcessState.FOREGROUND, 1); assertThatCpuGaugeMetricWasSentToTransport( - "sessionId2", recordedGaugeMetric3, fakeCpuMetricReading3); + testSessionId(2), recordedGaugeMetric3, fakeCpuMetricReading3); assertThatMemoryGaugeMetricWasSentToTransport( - "sessionId2", recordedGaugeMetric3, fakeMemoryMetricReading3); + testSessionId(2), recordedGaugeMetric3, fakeMemoryMetricReading3); } @Test @@ -643,13 +642,13 @@ public void testLogGaugeMetadataSendDataToTransport() { when(fakeGaugeMetadataManager.getMaxAppJavaHeapMemoryKb()).thenReturn(1000); when(fakeGaugeMetadataManager.getMaxEncouragedAppJavaHeapMemoryKb()).thenReturn(800); - testGaugeManager.logGaugeMetadata("sessionId", ApplicationProcessState.FOREGROUND); + testGaugeManager.logGaugeMetadata(testSessionId(1), ApplicationProcessState.FOREGROUND); GaugeMetric recordedGaugeMetric = getLastRecordedGaugeMetric(ApplicationProcessState.FOREGROUND, 1); GaugeMetadata recordedGaugeMetadata = recordedGaugeMetric.getGaugeMetadata(); - assertThat(recordedGaugeMetric.getSessionId()).isEqualTo("sessionId"); + assertThat(recordedGaugeMetric.getSessionId()).isEqualTo(testSessionId(1)); assertThat(recordedGaugeMetadata.getDeviceRamSizeKb()) .isEqualTo(fakeGaugeMetadataManager.getDeviceRamSizeKb()); @@ -660,7 +659,7 @@ public void testLogGaugeMetadataSendDataToTransport() { } @Test - public void testLogGaugeMetadataDoesntLogWhenGaugeMetadataManagerNotAvailable() { + public void testLogGaugeMetadataDoesNotLogWhenGaugeMetadataManagerNotAvailable() { testGaugeManager = new GaugeManager( @@ -671,7 +670,8 @@ public void testLogGaugeMetadataDoesntLogWhenGaugeMetadataManagerNotAvailable() new Lazy<>(() -> fakeCpuGaugeCollector), new Lazy<>(() -> fakeMemoryGaugeCollector)); - assertThat(testGaugeManager.logGaugeMetadata("sessionId", ApplicationProcessState.FOREGROUND)) + assertThat( + testGaugeManager.logGaugeMetadata(testSessionId(1), ApplicationProcessState.FOREGROUND)) .isFalse(); } @@ -687,18 +687,20 @@ public void testLogGaugeMetadataLogsAfterApplicationContextIsSet() { new Lazy<>(() -> fakeCpuGaugeCollector), new Lazy<>(() -> fakeMemoryGaugeCollector)); - assertThat(testGaugeManager.logGaugeMetadata("sessionId", ApplicationProcessState.FOREGROUND)) + assertThat( + testGaugeManager.logGaugeMetadata(testSessionId(1), ApplicationProcessState.FOREGROUND)) .isFalse(); testGaugeManager.initializeGaugeMetadataManager(ApplicationProvider.getApplicationContext()); - assertThat(testGaugeManager.logGaugeMetadata("sessionId", ApplicationProcessState.FOREGROUND)) + assertThat( + testGaugeManager.logGaugeMetadata(testSessionId(1), ApplicationProcessState.FOREGROUND)) .isTrue(); GaugeMetric recordedGaugeMetric = getLastRecordedGaugeMetric(ApplicationProcessState.FOREGROUND, 1); GaugeMetadata recordedGaugeMetadata = recordedGaugeMetric.getGaugeMetadata(); - assertThat(recordedGaugeMetric.getSessionId()).isEqualTo("sessionId"); + assertThat(recordedGaugeMetric.getSessionId()).isEqualTo(testSessionId(1)); } @Test diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/transport/TransportManagerTest.java b/firebase-perf/src/test/java/com/google/firebase/perf/transport/TransportManagerTest.java index 1814f1dfaa6..b10a48e135f 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/transport/TransportManagerTest.java +++ b/firebase-perf/src/test/java/com/google/firebase/perf/transport/TransportManagerTest.java @@ -15,6 +15,8 @@ package com.google.firebase.perf.transport; import static com.google.common.truth.Truth.assertThat; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.createTestSession; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.testSessionId; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.mock; @@ -25,8 +27,6 @@ import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.robolectric.Shadows.shadowOf; -import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.createTestSession; -import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.testSessionId; import android.content.Context; import android.content.pm.PackageInfo; @@ -42,7 +42,6 @@ import com.google.firebase.perf.config.ConfigResolver; import com.google.firebase.perf.session.SessionManager; import com.google.firebase.perf.shadows.ShadowPreconditions; -import com.google.firebase.perf.util.Clock; import com.google.firebase.perf.util.Constants; import com.google.firebase.perf.util.Constants.CounterNames; import com.google.firebase.perf.v1.AndroidMemoryReading; @@ -1187,8 +1186,7 @@ public void logNetworkMetric_sessionEnabled_doesNotStripOffSessionId() { NetworkRequestMetric.Builder validNetworkRequest = createValidNetworkRequestMetric().toBuilder(); List perfSessions = new ArrayList<>(); - perfSessions.add(createTestSession(1) - .build()); + perfSessions.add(createTestSession(1).build()); validNetworkRequest.clearPerfSessions().addAllPerfSessions(perfSessions); testTransportManager.log(validNetworkRequest.build()); From e1abc923fc17ea364b534db8a0a4f21d6d877704 Mon Sep 17 00:00:00 2001 From: Tejas Deshpande Date: Fri, 11 Apr 2025 12:05:33 -0400 Subject: [PATCH 3/8] fix test --- .../com/google/firebase/perf/session/SessionManagerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java b/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java index 58ca631781f..618dff747ff 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/SessionManagerTest.java @@ -113,7 +113,7 @@ public void testSessionIdDoesNotUpdateIfPerfSessionRunsTooLong() { Timer mockTimer = mock(Timer.class); when(mockClock.getTime()).thenReturn(mockTimer); - PerfSession session = createTestSession(1); + PerfSession session = new PerfSession(testSessionId(1), mockClock); SessionManager testSessionManager = new SessionManager(mockGaugeManager, session, mockAppStateMonitor); From e43ef174ab40e55b66c600c2fd5f6a804f0e1947 Mon Sep 17 00:00:00 2001 From: Tejas Deshpande Date: Fri, 11 Apr 2025 12:13:57 -0400 Subject: [PATCH 4/8] add copyright --- .../perf/session/FirebaseSessionsHelper.kt | 16 ++++++++++++++++ .../perf/session/FirebaseSessionsTestHelper.kt | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebaseSessionsHelper.kt b/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebaseSessionsHelper.kt index 71e251119f4..7ab9bbf6fee 100644 --- a/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebaseSessionsHelper.kt +++ b/firebase-perf/src/main/java/com/google/firebase/perf/session/FirebaseSessionsHelper.kt @@ -1,3 +1,19 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.google.firebase.perf.session import com.google.firebase.perf.util.Constants diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt b/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt index fe9033ced6e..f065ebf6f80 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt @@ -1,3 +1,19 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.google.firebase.perf.session import com.google.firebase.perf.util.Clock From 206d6ad10e5edc95fb1b7379b835584d15179ebd Mon Sep 17 00:00:00 2001 From: Tejas Deshpande Date: Fri, 11 Apr 2025 12:33:48 -0400 Subject: [PATCH 5/8] Update PerfSession test --- .../perf/session/PerfSessionTest.java | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java b/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java index 9e4e3149e62..58bb4f715ce 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java @@ -15,6 +15,8 @@ package com.google.firebase.perf.session; import static com.google.common.truth.Truth.assertThat; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.createTestSession; +import static com.google.firebase.perf.session.FirebaseSessionsTestHelperKt.testSessionId; import static com.google.firebase.perf.util.Constants.PREFS_NAME; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -154,7 +156,7 @@ public void shouldCollectGaugesAndEvents_perfMonDeactivated_sessionNotVerbose() @Test public void testPerfSessionConversion() { - PerfSession session1 = PerfSession.createWithId("aqsSessionId"); + PerfSession session1 = createTestSession(1); session1.setGaugeAndEventCollectionEnabled(true); com.google.firebase.perf.v1.PerfSession perfSession = session1.build(); @@ -165,7 +167,7 @@ public void testPerfSessionConversion() { @Test public void testPerfSessionConversionWithoutVerbosity() { - PerfSession session1 = PerfSession.createWithId("sessionId"); + PerfSession session1 = createTestSession(1); com.google.firebase.perf.v1.PerfSession perfSession = session1.build(); Assert.assertEquals(session1.sessionId(), perfSession.getSessionId()); @@ -175,21 +177,21 @@ public void testPerfSessionConversionWithoutVerbosity() { @Test public void testPerfSessionsCreateDisabledGaugeCollectionWhenVerboseSessionForceDisabled() { forceNonVerboseSession(); - PerfSession testPerfSession = PerfSession.createWithId("sessionId"); + PerfSession testPerfSession = createTestSession(1); assertThat(testPerfSession.isGaugeAndEventCollectionEnabled()).isFalse(); } @Test public void testPerfSessionsCreateDisabledGaugeCollectionWhenSessionsFeatureDisabled() { forceSessionsFeatureDisabled(); - PerfSession testPerfSession = PerfSession.createWithId("sessionId"); + PerfSession testPerfSession = createTestSession(1); assertThat(testPerfSession.isGaugeAndEventCollectionEnabled()).isFalse(); } @Test public void testPerfSessionsCreateEnablesGaugeCollectionWhenVerboseSessionForceEnabled() { forceVerboseSession(); - PerfSession testPerfSession = PerfSession.createWithId("sessionId"); + PerfSession testPerfSession = createTestSession(1); assertThat(testPerfSession.isGaugeAndEventCollectionEnabled()).isTrue(); } @@ -200,16 +202,16 @@ public void testBuildAndSortMovesTheVerboseSessionToTop() { // Next, create 3 non-verbose sessions List sessions = new ArrayList<>(); - sessions.add(PerfSession.createWithId("sessionId1")); - sessions.add(PerfSession.createWithId("sessionId2")); - sessions.add(PerfSession.createWithId("sessionId3")); + sessions.add(createTestSession(1)); + sessions.add(createTestSession(2)); + sessions.add(createTestSession(3)); // Force all the sessions from now onwards to be verbose forceVerboseSession(); // Next, create 2 verbose sessions - sessions.add(PerfSession.createWithId("sessionId4")); - sessions.add(PerfSession.createWithId("sessionId5")); + sessions.add(createTestSession(4)); + sessions.add(createTestSession(5)); // Verify that the first session in the list of sessions was not verbose assertThat(sessions.get(0).isVerbose()).isFalse(); @@ -231,7 +233,7 @@ public void testIsExpiredReturnsFalseWhenCurrentSessionLengthIsLessThanMaxSessio - TimeUnit.MINUTES.toMicros(1)); // Default Max Session Length is 4 hours when(mockClock.getTime()).thenReturn(mockTimer); - PerfSession session = new PerfSession("sessionId", mockClock); + PerfSession session = new PerfSession(testSessionId(1), mockClock); assertThat(session.isSessionRunningTooLong()).isFalse(); } @@ -242,7 +244,7 @@ public void testIsExpiredReturnsFalseWhenCurrentSessionLengthIsEqualToMaxSession .thenReturn(TimeUnit.HOURS.toMicros(4)); // Default Max Session Length is 4 hours when(mockClock.getTime()).thenReturn(mockTimer); - PerfSession session = new PerfSession("sessionId", mockClock); + PerfSession session = new PerfSession(testSessionId(1), mockClock); assertThat(session.isSessionRunningTooLong()).isFalse(); } @@ -253,7 +255,7 @@ public void testIsExpiredReturnsTrueWhenCurrentSessionLengthIsGreaterThanMaxSess .thenReturn(TimeUnit.HOURS.toMicros(5)); // Default Max Session Length is 4 hours when(mockClock.getTime()).thenReturn(mockTimer); - PerfSession session = new PerfSession("sessionId", mockClock); + PerfSession session = new PerfSession(testSessionId(1), mockClock); assertThat(session.isSessionRunningTooLong()).isTrue(); } } From e977ad9976bddfab3f431a2006cd8413b0a8b08f Mon Sep 17 00:00:00 2001 From: Tejas Deshpande Date: Fri, 11 Apr 2025 12:35:45 -0400 Subject: [PATCH 6/8] fix tests --- .../firebase/perf/session/PerfSessionTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java b/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java index 58bb4f715ce..6fe8e1a959c 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/PerfSessionTest.java @@ -191,7 +191,7 @@ public void testPerfSessionsCreateDisabledGaugeCollectionWhenSessionsFeatureDisa @Test public void testPerfSessionsCreateEnablesGaugeCollectionWhenVerboseSessionForceEnabled() { forceVerboseSession(); - PerfSession testPerfSession = createTestSession(1); + PerfSession testPerfSession = PerfSession.createWithId(testSessionId(1)); assertThat(testPerfSession.isGaugeAndEventCollectionEnabled()).isTrue(); } @@ -202,16 +202,16 @@ public void testBuildAndSortMovesTheVerboseSessionToTop() { // Next, create 3 non-verbose sessions List sessions = new ArrayList<>(); - sessions.add(createTestSession(1)); - sessions.add(createTestSession(2)); - sessions.add(createTestSession(3)); + sessions.add(PerfSession.createWithId(testSessionId(1))); + sessions.add(PerfSession.createWithId(testSessionId(2))); + sessions.add(PerfSession.createWithId(testSessionId(3))); // Force all the sessions from now onwards to be verbose forceVerboseSession(); // Next, create 2 verbose sessions - sessions.add(createTestSession(4)); - sessions.add(createTestSession(5)); + sessions.add(PerfSession.createWithId(testSessionId(4))); + sessions.add(PerfSession.createWithId(testSessionId(5))); // Verify that the first session in the list of sessions was not verbose assertThat(sessions.get(0).isVerbose()).isFalse(); From 82074aa1774b42b83fc0a5a2b97c5445a647f50d Mon Sep 17 00:00:00 2001 From: Tejas Deshpande Date: Fri, 11 Apr 2025 12:49:36 -0400 Subject: [PATCH 7/8] Remove unused checkSession --- .../perf/logging/FirebaseSessionsEnforcementCheck.kt | 7 ------- 1 file changed, 7 deletions(-) diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt b/firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt index 2a4607fadec..e7bac0fc722 100644 --- a/firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt +++ b/firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt @@ -31,12 +31,5 @@ class FirebaseSessionsEnforcementCheck { assert(!enforcement) { failureMessage } } } - - fun checkSession(sessionId: String, failureMessage: String) { - if (sessionId.isLegacy()) { - logger.debug("legacy session ${sessionId}: $failureMessage") - assert(!enforcement) { failureMessage } - } - } } } From 69bf460df86f68737930a45e97cf0fc51516c8e0 Mon Sep 17 00:00:00 2001 From: Tejas Deshpande Date: Mon, 14 Apr 2025 10:40:37 -0400 Subject: [PATCH 8/8] core review comments --- .../perf/logging/FirebaseSessionsEnforcementCheck.kt | 1 + .../com/google/firebase/perf/session/SessionManager.java | 6 +++--- .../firebase/perf/session/FirebaseSessionsTestHelper.kt | 4 +--- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt b/firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt index e7bac0fc722..0abef6b0008 100644 --- a/firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt +++ b/firebase-perf/src/main/java/com/google/firebase/perf/logging/FirebaseSessionsEnforcementCheck.kt @@ -25,6 +25,7 @@ class FirebaseSessionsEnforcementCheck { @JvmStatic var enforcement: Boolean = false private var logger: AndroidLogger = AndroidLogger.getInstance() + @JvmStatic fun checkSession(session: PerfSession, failureMessage: String) { if (session.isLegacy()) { logger.debug("legacy session ${session.sessionId()}: $failureMessage") diff --git a/firebase-perf/src/main/java/com/google/firebase/perf/session/SessionManager.java b/firebase-perf/src/main/java/com/google/firebase/perf/session/SessionManager.java index 46320cf7622..5a8540a6ffb 100644 --- a/firebase-perf/src/main/java/com/google/firebase/perf/session/SessionManager.java +++ b/firebase-perf/src/main/java/com/google/firebase/perf/session/SessionManager.java @@ -49,7 +49,7 @@ public static SessionManager getInstance() { /** Returns the currently active PerfSession. */ public final PerfSession perfSession() { - FirebaseSessionsEnforcementCheck.Companion.checkSession( + FirebaseSessionsEnforcementCheck.checkSession( perfSession, "Access perf session from manger without aqs ready"); return perfSession; @@ -82,7 +82,7 @@ public void setApplicationContext(final Context appContext) { * @see PerfSession#isSessionRunningTooLong() */ public void stopGaugeCollectionIfSessionRunningTooLong() { - FirebaseSessionsEnforcementCheck.Companion.checkSession( + FirebaseSessionsEnforcementCheck.checkSession( perfSession, "Session is not ready while trying to stopGaugeCollectionIfSessionRunningTooLong"); @@ -161,7 +161,7 @@ public void unregisterForSessionUpdates(WeakReference client } private void startOrStopCollectingGauges(ApplicationProcessState appState) { - FirebaseSessionsEnforcementCheck.Companion.checkSession( + FirebaseSessionsEnforcementCheck.checkSession( perfSession, "Session is not ready while trying to startOrStopCollectingGauges"); if (perfSession.isGaugeAndEventCollectionEnabled()) { diff --git a/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt b/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt index f065ebf6f80..a617af94a58 100644 --- a/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt +++ b/firebase-perf/src/test/java/com/google/firebase/perf/session/FirebaseSessionsTestHelper.kt @@ -24,6 +24,4 @@ fun createTestSession(suffix: Int): PerfSession { return PerfSession(testSessionId(suffix), Clock()) } -fun testSessionId(suffix: Int): String { - return "abc$suffix" -} +fun testSessionId(suffix: Int): String = "abc$suffix"