chromium/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc

// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "chrome/browser/media/webrtc/webrtc_event_log_manager.h"

#include <algorithm>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <optional>
#include <queue>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

#include "base/big_endian.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/gtest_util.h"
#include "base/test/scoped_command_line.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/media/webrtc/webrtc_event_log_manager_common.h"
#include "chrome/browser/media/webrtc/webrtc_event_log_manager_unittest_helpers.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/testing_pref_store.h"
#include "components/sync_preferences/pref_service_mock_factory.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/mock_render_process_host.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_network_connection_tracker.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/zlib/google/compression_utils.h"

#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_types.h"
#endif

#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h"
#include "components/account_id/account_id.h"
#include "components/user_manager/scoped_user_manager.h"
#endif

namespace webrtc_event_logging {

#if BUILDFLAG(IS_WIN)
#define NumberToStringType
#else
#define NumberToStringType
#endif

_;
Invoke;
NiceMock;

BrowserContext;
BrowserContextId;
MockRenderProcessHost;
PeerConnectionKey;
RenderProcessHost;

Compression;

namespace {

#if !BUILDFLAG(IS_ANDROID)

auto SaveFilePathTo(std::optional<base::FilePath>* output) {}

auto SaveKeyAndFilePathTo(std::optional<PeerConnectionKey>* key_output,
                          std::optional<base::FilePath>* file_path_output) {}

const int kMaxActiveRemoteLogFiles =;
const int kMaxPendingRemoteLogFiles =;
const char kSessionId[] =;

base::Time GetLastModificationTime(const base::FilePath& file_path) {}

#endif

// Common default/arbitrary values.
constexpr int kLid =;
constexpr size_t kWebAppId =;
constexpr int kFrameId =;

PeerConnectionKey GetPeerConnectionKey(RenderProcessHost* rph, int lid) {}

bool CreateRemoteBoundLogFile(const base::FilePath& dir,
                              size_t web_app_id,
                              const base::FilePath::StringPieceType& extension,
                              base::Time capture_time,
                              base::FilePath* file_path,
                              base::File* file) {}

// This implementation does not upload files, nor pretends to have finished an
// upload. Most importantly, it does not get rid of the locally-stored log file
// after finishing a simulated upload; this is useful because it keeps the file
// on disk, where unit tests may inspect it.
// This class enforces an expectation over the upload being cancelled or not.
class NullWebRtcEventLogUploader : public WebRtcEventLogUploader {};

class MockWebRtcLocalEventLogsObserver : public WebRtcLocalEventLogsObserver {};

class MockWebRtcRemoteEventLogsObserver : public WebRtcRemoteEventLogsObserver {};

}  // namespace

class WebRtcEventLogManagerTestBase : public ::testing::Test {};

#if !BUILDFLAG(IS_ANDROID)

class WebRtcEventLogManagerTest : public WebRtcEventLogManagerTestBase,
                                  public ::testing::WithParamInterface<bool> {};

class WebRtcEventLogManagerTestCacheClearing
    : public WebRtcEventLogManagerTest {};

const base::TimeDelta WebRtcEventLogManagerTestCacheClearing::kEpsion =;

class WebRtcEventLogManagerTestWithRemoteLoggingDisabled
    : public WebRtcEventLogManagerTestBase,
      public ::testing::WithParamInterface<bool> {};

class WebRtcEventLogManagerTestPolicy : public WebRtcEventLogManagerTestBase {};

class WebRtcEventLogManagerTestUploadSuppressionDisablingFlag
    : public WebRtcEventLogManagerTestBase {};

class WebRtcEventLogManagerTestForNetworkConnectivity
    : public WebRtcEventLogManagerTestBase,
      public ::testing::WithParamInterface<
          std::tuple<bool,
                     network::mojom::ConnectionType,
                     network::mojom::ConnectionType>> {};

class WebRtcEventLogManagerTestUploadDelay
    : public WebRtcEventLogManagerTestBase {};

// For testing compression issues.
class WebRtcEventLogManagerTestCompression
    : public WebRtcEventLogManagerTestBase {};

class WebRtcEventLogManagerTestIncognito
    : public WebRtcEventLogManagerTestBase {};

class WebRtcEventLogManagerTestHistory : public WebRtcEventLogManagerTestBase {};

namespace {

class PeerConnectionTrackerProxyForTesting
    : public WebRtcEventLogManager::PeerConnectionTrackerProxy {};

// The factory for the following fake uploader produces a sequence of
// uploaders which fail the test if given a file other than that which they
// expect. The factory itself likewise fails the test if destroyed before
// producing all expected uploaders, or if it's asked for more uploaders than
// it expects to create. This allows us to test for sequences of uploads.
class FileListExpectingWebRtcEventLogUploader : public WebRtcEventLogUploader {};

}  // namespace

TEST_F(WebRtcEventLogManagerTest, OnPeerConnectionAddedReturnsTrue) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionAddedReturnsFalseIfAlreadyAdded) {}

TEST_F(WebRtcEventLogManagerTest, OnPeerConnectionRemovedReturnsTrue) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionRemovedReturnsFalseIfNeverAdded) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionRemovedReturnsFalseIfAlreadyRemoved) {}

TEST_F(WebRtcEventLogManagerTest, OnPeerConnectionSessionIdSetReturnsTrue) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionSessionIdSetReturnsFalseIfEmptyString) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionSessionIdSetReturnsFalseIfPeerConnectionNeverAdded) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionSessionIdSetReturnsFalseIfPeerConnectionAlreadyRemoved) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionSessionIdSetReturnsTrueIfAlreadyCalledSameId) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionSessionIdSetReturnsFalseIfAlreadyCalledDifferentId) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionSessionIdSetCalledOnRecreatedPeerConnectionSanity) {}

TEST_F(WebRtcEventLogManagerTest, EnableLocalLoggingReturnsTrue) {}

TEST_F(WebRtcEventLogManagerTest,
       EnableLocalLoggingReturnsFalseIfCalledWhenAlreadyEnabled) {}

TEST_F(WebRtcEventLogManagerTest, DisableLocalLoggingReturnsTrue) {}

TEST_F(WebRtcEventLogManagerTest, DisableLocalLoggingReturnsIfNeverEnabled) {}

TEST_F(WebRtcEventLogManagerTest, DisableLocalLoggingReturnsIfAlreadyDisabled) {}

TEST_F(WebRtcEventLogManagerTest,
       OnWebRtcEventLogWriteReturnsFalseAndFalseWhenAllLoggingDisabled) {}

TEST_F(WebRtcEventLogManagerTest,
       OnWebRtcEventLogWriteReturnsFalseAndFalseForUnknownPeerConnection) {}

TEST_F(WebRtcEventLogManagerTest,
       OnWebRtcEventLogWriteReturnsLocalTrueWhenPcKnownAndLocalLoggingOn) {}

TEST_F(WebRtcEventLogManagerTest,
       OnWebRtcEventLogWriteReturnsRemoteTrueWhenPcKnownAndRemoteLogging) {}

TEST_F(WebRtcEventLogManagerTest,
       OnWebRtcEventLogWriteReturnsTrueAndTrueeWhenAllLoggingEnabled) {}

TEST_F(WebRtcEventLogManagerTest,
       OnLocalLogStartedNotCalledIfLocalLoggingEnabledWithoutPeerConnections) {}

TEST_F(WebRtcEventLogManagerTest,
       OnLocalLogStoppedNotCalledIfLocalLoggingDisabledWithoutPeerConnections) {}

TEST_F(WebRtcEventLogManagerTest,
       OnLocalLogStartedCalledForOnPeerConnectionAddedAndLocalLoggingEnabled) {}

TEST_F(WebRtcEventLogManagerTest,
       OnLocalLogStartedCalledForLocalLoggingEnabledAndOnPeerConnectionAdded) {}

TEST_F(WebRtcEventLogManagerTest,
       OnLocalLogStoppedCalledAfterLocalLoggingDisabled) {}

TEST_F(WebRtcEventLogManagerTest,
       OnLocalLogStoppedCalledAfterOnPeerConnectionRemoved) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogCreatesEmptyFileWhenStarted) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogCreateAndWriteToFile) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogMultipleWritesToSameFile) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogFileSizeLimitNotExceeded) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogSanityOverUnlimitedFileSizes) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogNoWriteAfterLogStopped) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogOnlyWritesTheLogsAfterStarted) {}

// Note: This test also covers the scenario LocalLogExistingFilesNotOverwritten,
// which is therefore not explicitly tested.
TEST_F(WebRtcEventLogManagerTest, LocalLoggingRestartCreatesNewFile) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogMultipleActiveFiles) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogLimitActiveLocalLogFiles) {}

// When a log reaches its maximum size limit, it is closed, and no longer
// counted towards the limit.
TEST_F(WebRtcEventLogManagerTest, LocalLogFilledLogNotCountedTowardsLogsLimit) {}

TEST_F(WebRtcEventLogManagerTest,
       LocalLogForRemovedPeerConnectionNotCountedTowardsLogsLimit) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogIllegalPath) {}

#if BUILDFLAG(IS_POSIX)
TEST_F(WebRtcEventLogManagerTest, LocalLogLegalPathWithoutPermissionsSanity) {}
#endif  // BUILDFLAG(IS_POSIX)

TEST_F(WebRtcEventLogManagerTest, LocalLogEmptyStringHandledGracefully) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogFilenameMatchesExpectedFormat) {}

TEST_F(WebRtcEventLogManagerTest,
       LocalLogFilenameMatchesExpectedFormatRepeatedFilename) {}

TEST_F(WebRtcEventLogManagerTest,
       OnRemoteLogStartedNotCalledIfRemoteLoggingNotEnabled) {}

TEST_F(WebRtcEventLogManagerTest,
       OnRemoteLogStoppedNotCalledIfRemoteLoggingNotEnabled) {}

TEST_F(WebRtcEventLogManagerTest,
       OnRemoteLogStartedCalledIfRemoteLoggingEnabled) {}

TEST_F(WebRtcEventLogManagerTest,
       OnRemoteLogStoppedCalledIfRemoteLoggingEnabledThenPcRemoved) {}

TEST_F(WebRtcEventLogManagerTest,
       BrowserContextInitializationCreatesDirectoryForRemoteLogs) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsFalseIfUnknownPeerConnection) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsFalseIfUnknownSessionId) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsTrueIfKnownSessionId) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsFalseIfRestartAttempt) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsFalseIfUnlimitedFileSize) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsTrueIfFileSizeAtOrBelowLimit) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsFalseIfFileSizeToSmall) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsFalseIfExcessivelyLargeFileSize) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsFalseIfExcessivelyLargeOutputPeriodMs) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsFalseIfPeerConnectionAlreadyClosed) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingDoesNotReturnIdWhenUnsuccessful) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingReturnsLegalIdWhenSuccessful) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingSavesToFileWithCorrectFileNameFormat) {}

TEST_F(WebRtcEventLogManagerTest, StartRemoteLoggingCreatesEmptyFile) {}

// TODO(crbug.com/40752893): Fix this flaky test.
TEST_F(WebRtcEventLogManagerTest,
       DISABLED_RemoteLogFileCreatedInCorrectDirectory) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingSanityIfDuplicateIdsInDifferentRendererProcesses) {}

TEST_F(WebRtcEventLogManagerTest,
       OnWebRtcEventLogWriteWritesToTheRemoteBoundFile) {}

TEST_F(WebRtcEventLogManagerTest, WriteToBothLocalAndRemoteFiles) {}

TEST_F(WebRtcEventLogManagerTest, MultipleWritesToSameRemoteBoundLogfile) {}

TEST_F(WebRtcEventLogManagerTest,
       RemoteLogFileSizeLimitNotExceededSingleWrite) {}

TEST_F(WebRtcEventLogManagerTest,
       RemoteLogFileSizeLimitNotExceededMultipleWrites) {}

TEST_F(WebRtcEventLogManagerTest,
       LogMultipleActiveRemoteLogsSameBrowserContext) {}

// TODO(crbug.com/40709493): Fix this flaky test.
TEST_F(WebRtcEventLogManagerTest,
       DISABLED_LogMultipleActiveRemoteLogsDifferentBrowserContexts) {}

TEST_F(WebRtcEventLogManagerTest, DifferentRemoteLogsMayHaveDifferentMaximums) {}

TEST_F(WebRtcEventLogManagerTest, RemoteLogFileClosedWhenCapacityReached) {}

#if BUILDFLAG(IS_POSIX)
// TODO(crbug.com/40545136): Add unit tests for lacking read permissions when
// looking to upload the file.
TEST_F(WebRtcEventLogManagerTest,
       FailureToCreateRemoteLogsDirHandledGracefully) {}

TEST_F(WebRtcEventLogManagerTest, GracefullyHandleFailureToStartRemoteLogFile) {}
#endif  // BUILDFLAG(IS_POSIX)

TEST_F(WebRtcEventLogManagerTest, RemoteLogLimitActiveLogFiles) {}

TEST_F(WebRtcEventLogManagerTest,
       RemoteLogFilledLogNotCountedTowardsLogsLimit) {}

TEST_F(WebRtcEventLogManagerTest,
       RemoteLogForRemovedPeerConnectionNotCountedTowardsLogsLimit) {}

TEST_F(WebRtcEventLogManagerTest,
       ActiveLogsForBrowserContextCountedTowardsItsPendingsLogsLimit) {}

TEST_F(WebRtcEventLogManagerTest,
       ObserveLimitOnMaximumPendingLogsPerBrowserContext) {}

// This also tests the scenario UploadOrderDependsOnLastModificationTime.
TEST_F(WebRtcEventLogManagerTest,
       LogsFromPreviousSessionBecomePendingLogsWhenBrowserContextInitialized) {}

// It is possible for remote-bound logs to be compressed or uncompressed.
// We show that logs from a previous session are captured even if they are
// different, with regards to compression, compared to last time.
TEST_F(WebRtcEventLogManagerTest,
       LogsCapturedPreviouslyMadePendingEvenIfDifferentExtensionsUsed) {}

TEST_P(WebRtcEventLogManagerTest,
       WhenOnPeerConnectionRemovedFinishedRemoteLogUploadedAndFileDeleted) {}

TEST_P(WebRtcEventLogManagerTest, DestroyedRphTriggersLogUpload) {}

// Note that SuppressUploading() and UnSuppressUploading() use the behavior
// guaranteed by this test.
TEST_F(WebRtcEventLogManagerTest, UploadOnlyWhenNoActivePeerConnections) {}

TEST_F(WebRtcEventLogManagerTest, ExpiredFilesArePrunedRatherThanUploaded) {}

// TODO(crbug.com/40545136): Add a test showing that a file expiring while
// another is being uploaded, is not uploaded after the current upload is
// completed. This is significant because Chrome might stay up for a long time.

TEST_F(WebRtcEventLogManagerTest, RemoteLogEmptyStringHandledGracefully) {}

#if BUILDFLAG(IS_POSIX)
TEST_F(WebRtcEventLogManagerTest,
       UnopenedRemoteLogFilesNotCountedTowardsActiveLogsLimit) {}
#endif  // BUILDFLAG(IS_POSIX)

TEST_F(WebRtcEventLogManagerTest,
       NoStartWebRtcSendingEventLogsWhenLocalEnabledWithoutPeerConnection) {}

TEST_F(WebRtcEventLogManagerTest,
       NoStartWebRtcSendingEventLogsWhenPeerConnectionButNoLoggingEnabled) {}

TEST_F(WebRtcEventLogManagerTest,
       StartWebRtcSendingEventLogsWhenLocalEnabledThenOnPeerConnectionAdded) {}

TEST_F(WebRtcEventLogManagerTest,
       StartWebRtcSendingEventLogsWhenOnPeerConnectionAddedThenLocalEnabled) {}

TEST_F(WebRtcEventLogManagerTest,
       StartWebRtcSendingEventLogsWhenRemoteLoggingEnabled) {}

TEST_F(WebRtcEventLogManagerTest,
       InstructWebRtcToStopSendingEventLogsWhenLocalLoggingStopped) {}

// #1 - Local logging was the cause of the logs.
TEST_F(WebRtcEventLogManagerTest,
       InstructWebRtcToStopSendingEventLogsWhenOnPeerConnectionRemoved1) {}

// #2 - Remote logging was the cause of the logs.
TEST_F(WebRtcEventLogManagerTest,
       InstructWebRtcToStopSendingEventLogsWhenOnPeerConnectionRemoved2) {}

// #1 - Local logging added first.
TEST_F(WebRtcEventLogManagerTest,
       SecondLoggingTargetDoesNotInitiateWebRtcLogging1) {}

// #2 - Remote logging added first.
TEST_F(WebRtcEventLogManagerTest,
       SecondLoggingTargetDoesNotInitiateWebRtcLogging2) {}

TEST_F(WebRtcEventLogManagerTest,
       DisablingLocalLoggingWhenRemoteLoggingEnabledDoesNotStopWebRtcLogging) {}

TEST_F(WebRtcEventLogManagerTest,
       DisablingLocalLoggingAfterPcRemovalHasNoEffectOnWebRtcLogging) {}

// Once a peer connection with a given key was removed, it may not again be
// added. But, if this impossible case occurs, WebRtcEventLogManager will
// not crash.
TEST_F(WebRtcEventLogManagerTest, SanityOverRecreatingTheSamePeerConnection) {}

// The logs would typically be binary. However, the other tests only cover ASCII
// characters, for readability. This test shows that this is not a problem.
TEST_F(WebRtcEventLogManagerTest, LogAllPossibleCharacters) {}

TEST_F(WebRtcEventLogManagerTest, LocalLogsClosedWhenRenderProcessHostExits) {}

TEST_F(WebRtcEventLogManagerTest, RemoteLogsClosedWhenRenderProcessHostExits) {}

// Once a RenderProcessHost exits/crashes, its PeerConnections are removed,
// which means that they can no longer suppress an upload.
TEST_F(WebRtcEventLogManagerTest,
       RenderProcessHostExitCanRemoveUploadSuppression) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionAddedOverDestroyedRphReturnsFalse) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionRemovedOverDestroyedRphReturnsFalse) {}

TEST_F(WebRtcEventLogManagerTest,
       OnPeerConnectionStoppedOverDestroyedRphReturnsFalse) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingOverDestroyedRphReturnsFalse) {}

TEST_F(WebRtcEventLogManagerTest,
       OnWebRtcEventLogWriteOverDestroyedRphReturnsFalseAndFalse) {}

TEST_F(WebRtcEventLogManagerTest, DifferentProfilesCanHaveDifferentPolicies) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingWithTooLowWebAppIdRejected) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingWithTooHighWebAppIdRejected) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingWithInRangeWebAppIdAllowedMin) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingWithInRangeWebAppIdAllowedMax) {}

// Only one remote-bound event log allowed per
TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingOverMultipleWebAppsDisallowed) {}

TEST_F(WebRtcEventLogManagerTest,
       StartRemoteLoggingWebAppIdIncorporatedIntoFileName) {}

INSTANTIATE_TEST_SUITE_P();

TEST_F(WebRtcEventLogManagerTestCacheClearing,
       ClearCacheForBrowserContextRemovesPendingFilesInRange) {}

TEST_F(WebRtcEventLogManagerTestCacheClearing,
       ClearCacheForBrowserContextCancelsActiveLogFilesIfInRange) {}

TEST_F(WebRtcEventLogManagerTestCacheClearing,
       ClearCacheForBrowserContextCancelsFileUploadIfInRange) {}

TEST_F(WebRtcEventLogManagerTestCacheClearing,
       ClearCacheForBrowserContextDoesNotRemovePendingFilesOutOfRange) {}

TEST_F(WebRtcEventLogManagerTestCacheClearing,
       ClearCacheForBrowserContextDoesNotCancelActiveLogFilesIfOutOfRange) {}

TEST_F(WebRtcEventLogManagerTestCacheClearing,
       ClearCacheForBrowserContextDoesNotCancelFileUploadIfOutOfRange) {}

TEST_F(WebRtcEventLogManagerTestCacheClearing,
       ClearCacheForBrowserContextDoesNotRemovePendingFilesFromOtherProfiles) {}

TEST_F(WebRtcEventLogManagerTestCacheClearing,
       ClearCacheForBrowserContextDoesNotCancelActiveLogsFromOtherProfiles) {}

TEST_F(WebRtcEventLogManagerTestCacheClearing,
       ClearCacheForBrowserContextDoesNotCancelFileUploadFromOtherProfiles) {}

// Show that clearing browser cache, while it removes remote-bound logs, does
// not interfere with local-bound logging, even if that happens on the same PC.
TEST_F(WebRtcEventLogManagerTestCacheClearing,
       ClearCacheForBrowserContextDoesNotInterfereWithLocalLogs) {}

// When cache clearing cancels the active upload, the next (non-deleted) pending
// file becomes eligible for upload.
TEST_F(WebRtcEventLogManagerTestCacheClearing,
       UploadCancellationTriggersUploadOfNextPendingFile) {}

TEST_P(WebRtcEventLogManagerTestWithRemoteLoggingDisabled,
       SanityOnPeerConnectionAdded) {}

TEST_P(WebRtcEventLogManagerTestWithRemoteLoggingDisabled,
       SanityOnPeerConnectionRemoved) {}

TEST_P(WebRtcEventLogManagerTestWithRemoteLoggingDisabled,
       SanityOnPeerConnectionStopped) {}

TEST_P(WebRtcEventLogManagerTestWithRemoteLoggingDisabled,
       SanityEnableLocalLogging) {}

TEST_P(WebRtcEventLogManagerTestWithRemoteLoggingDisabled,
       SanityDisableLocalLogging) {}

TEST_P(WebRtcEventLogManagerTestWithRemoteLoggingDisabled,
       SanityStartRemoteLogging) {}

TEST_P(WebRtcEventLogManagerTestWithRemoteLoggingDisabled,
       SanityOnWebRtcEventLogWrite) {}

INSTANTIATE_TEST_SUITE_P();

// This test is redundant; it is provided for completeness; see following tests.
TEST_F(WebRtcEventLogManagerTestPolicy, StartsEnabledAllowsRemoteLogging) {}

// This test is redundant; it is provided for completeness; see following tests.
TEST_F(WebRtcEventLogManagerTestPolicy, StartsDisabledRejectsRemoteLogging) {}

TEST_F(WebRtcEventLogManagerTestPolicy, NotManagedRejectsRemoteLogging) {}

#if BUILDFLAG(IS_CHROMEOS_ASH)
std::unique_ptr<user_manager::ScopedUserManager>
WebRtcEventLogManagerTestPolicy::GetScopedUserManager(
    user_manager::UserType user_type) {
  const AccountId kAccountId = AccountId::FromUserEmailGaiaId("name", "id");
  auto fake_user_manager = std::make_unique<ash::FakeChromeUserManager>();
  // On Chrome OS, there are different user types, some of which can be
  // affiliated with the device if the device is enterprise-enrolled, i.e. the
  // logged in account belongs to the org that owns the device. For our
  // purposes here, affiliation does not matter for the determination of the
  // policy default, so we can set it to false here. We do not need a user
  // to profile mapping either, so profile can be a nullptr.
  fake_user_manager->AddUserWithAffiliationAndTypeAndProfile(
      kAccountId, /*is_affiliated*/ false, user_type, /*profile*/ nullptr);
  return std::make_unique<user_manager::ScopedUserManager>(
      std::move(fake_user_manager));
}
#endif

TEST_F(WebRtcEventLogManagerTestPolicy,
       ManagedProfileAllowsRemoteLoggingByDefault) {}

// Currently we only test the case of supervised child profiles for Chrome OS
// here. Other user types for Chrome OS are tested in the unit test for
// ProfileDefaultsToLoggingEnabledTestCase in
// webrtc_event_log_manager_common_unittest because the test setup in this
// class currently does not seem to allow for an easy setup of some user types.
// TODO(crbug.com/1035829): Figure out whether this can be resolved by tweaking
// the test setup or whether the Active Directory services need to be adapted
// for easy testing.
#if BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(WebRtcEventLogManagerTestPolicy,
       ManagedProfileDoesNotAllowRemoteLoggingForSupervisedProfiles) {
  SetUp(true);  // Feature generally enabled (kill-switch not engaged).

  const bool allow_remote_logging = false;

  std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager =
      GetScopedUserManager(user_manager::UserType::kChild);

  auto browser_context = CreateBrowserContextWithCustomSupervision(
      "name", true /* is_managed_profile */,
      false /* has_device_level_policies */, true /* is_supervised */,
      std::nullopt);

  auto rph = std::make_unique<MockRenderProcessHost>(browser_context.get());
  const auto key = GetPeerConnectionKey(rph.get(), kLid);

  ASSERT_TRUE(OnPeerConnectionAdded(key));
  ASSERT_TRUE(OnPeerConnectionSessionIdSet(key));
  EXPECT_EQ(StartRemoteLogging(key), allow_remote_logging);
}
#endif

#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(WebRtcEventLogManagerTestPolicy,
       OnlyManagedByPlatformPoliciesDoesNotAllowRemoteLoggingByDefault) {}
#endif

void WebRtcEventLogManagerTestPolicy::TestManagedProfileAfterBeingExplicitlySet(
    bool explicitly_set_value) {}

TEST_F(WebRtcEventLogManagerTestPolicy,
       ManagedProfileAllowsRemoteLoggingAfterBeingExplicitlyEnabled) {}

TEST_F(WebRtcEventLogManagerTestPolicy,
       ManagedProfileDisallowsRemoteLoggingAfterBeingDisabled) {}

// #1 and #2 differ in the order of AddPeerConnection and the changing of
// the pref value.
TEST_F(WebRtcEventLogManagerTestPolicy,
       StartsEnabledThenDisabledRejectsRemoteLogging1) {}

// #1 and #2 differ in the order of AddPeerConnection and the changing of
// the pref value.
TEST_F(WebRtcEventLogManagerTestPolicy,
       StartsEnabledThenDisabledRejectsRemoteLogging2) {}

// #1 and #2 differ in the order of AddPeerConnection and the changing of
// the pref value.
TEST_F(WebRtcEventLogManagerTestPolicy,
       StartsDisabledThenEnabledAllowsRemoteLogging1) {}

// #1 and #2 differ in the order of AddPeerConnection and the changing of
// the pref value.
TEST_F(WebRtcEventLogManagerTestPolicy,
       StartsDisabledThenEnabledAllowsRemoteLogging2) {}

TEST_F(WebRtcEventLogManagerTestPolicy,
       StartsDisabledThenEnabledUploadsPendingLogFiles) {}

TEST_F(WebRtcEventLogManagerTestPolicy,
       StartsEnabledThenDisabledDoesNotUploadPendingLogFiles) {}

TEST_F(WebRtcEventLogManagerTestPolicy,
       StartsEnabledThenDisabledDeletesPendingLogFiles) {}

TEST_F(WebRtcEventLogManagerTestPolicy,
       StartsEnabledThenDisabledCancelsAndDeletesCurrentlyUploadedLogFile) {}

// This test makes sure that if the policy was enabled in the past, but was
// disabled while Chrome was not running, pending logs created during the
// earlier session will be deleted from disk.
TEST_F(WebRtcEventLogManagerTestPolicy,
       PendingLogsFromPreviousSessionRemovedIfPolicyDisabledAtNewSessionStart) {}

TEST_F(WebRtcEventLogManagerTestPolicy,
       PendingLogsFromPreviousSessionRemovedIfRemoteLoggingKillSwitchEngaged) {}

TEST_F(WebRtcEventLogManagerTestUploadSuppressionDisablingFlag,
       UploadingNotSuppressedByActivePeerConnections) {}

TEST_P(WebRtcEventLogManagerTestForNetworkConnectivity,
       DoNotUploadPendingLogsIfConnectedToUnsupportedNetworkType) {}

TEST_P(WebRtcEventLogManagerTestForNetworkConnectivity,
       UploadPendingLogsIfConnectedToSupportedNetworkType) {}

TEST_P(WebRtcEventLogManagerTestForNetworkConnectivity,
       UploadPendingLogsIfConnectionTypeChangesFromUnsupportedToSupported) {}

TEST_P(WebRtcEventLogManagerTestForNetworkConnectivity,
       DoNotUploadPendingLogsAtStartupIfConnectedToUnsupportedNetworkType) {}

TEST_P(WebRtcEventLogManagerTestForNetworkConnectivity,
       UploadPendingLogsAtStartupIfConnectedToSupportedNetworkType) {}

INSTANTIATE_TEST_SUITE_P();

TEST_F(WebRtcEventLogManagerTestUploadDelay, DoNotInitiateUploadBeforeDelay) {}

// WhenOnPeerConnectionRemovedFinishedRemoteLogUploadedAndFileDeleted has some
// overlap with this, but we still include this test for explicitness and
// clarity.
TEST_F(WebRtcEventLogManagerTestUploadDelay, InitiateUploadAfterDelay) {}

TEST_F(WebRtcEventLogManagerTestUploadDelay,
       OnPeerConnectionAddedDuringDelaySuppressesUpload) {}

TEST_F(WebRtcEventLogManagerTestUploadDelay,
       ClearCacheForBrowserContextDuringDelayCancelsItsUpload) {}

TEST_F(WebRtcEventLogManagerTestCompression,
       ErroredFilesDueToBadEstimationDeletedRatherThanUploaded) {}

TEST_F(WebRtcEventLogManagerTestIncognito, StartRemoteLoggingFails) {}

TEST_F(WebRtcEventLogManagerTestIncognito,
       StartRemoteLoggingDoesNotCreateDirectoryOrFiles) {}

TEST_F(WebRtcEventLogManagerTestIncognito,
       OnWebRtcEventLogWriteReturnsFalseForRemotePart) {}

TEST_F(WebRtcEventLogManagerTestHistory,
       CorrectHistoryReturnedForActivelyWrittenLog) {}

TEST_F(WebRtcEventLogManagerTestHistory, CorrectHistoryReturnedForPendingLog) {}

TEST_F(WebRtcEventLogManagerTestHistory,
       CorrectHistoryReturnedForActivelyUploadedLog) {}

// See ExpiredLogFilesAreReplacedByHistoryFiles for verification of the
// creation of history files of this type.
TEST_F(WebRtcEventLogManagerTestHistory,
       ExpiredLogFilesReplacedByHistoryFilesAndGetHistoryReportsAccordingly) {}

// Since the uploader mocks do not write the history files, it is not easy
// to check that the correct result is returned for GetHistory() for either
// a successful or an unsuccessful upload from the WebRtcEventLogManager level.
// Instead, this is checked by WebRtcEventLogUploaderImplTest.
// TODO(crbug.com/40545136): Add the tests mention in the comment above.

TEST_F(WebRtcEventLogManagerTestHistory, ClearingCacheRemovesHistoryFiles) {}

TEST_F(WebRtcEventLogManagerTestHistory,
       ClearingCacheDoesNotLeaveBehindHistoryForRemovedLogs) {}

// TODO(crbug.com/40545136): Add a test for the limit on the number of history
// files allowed to remain on disk.

#else  // BUILDFLAG(IS_ANDROID)

class WebRtcEventLogManagerTestOnMobileDevices
    : public WebRtcEventLogManagerTestBase {
 public:
  WebRtcEventLogManagerTestOnMobileDevices() {
    // features::kWebRtcRemoteEventLog not defined on mobile, and can therefore
    // not be forced on. This test is here to make sure that when the feature
    // is changed to be on by default, it will still be off for mobile devices.
    CreateWebRtcEventLogManager();
  }
};

TEST_F(WebRtcEventLogManagerTestOnMobileDevices, RemoteBoundLoggingDisabled) {
  const auto key = GetPeerConnectionKey(rph_.get(), kLid);
  ASSERT_TRUE(OnPeerConnectionAdded(key));
  ASSERT_TRUE(OnPeerConnectionSessionIdSet(key));
  EXPECT_FALSE(StartRemoteLogging(key));
}

#endif

}  // namespace webrtc_event_logging