Commit c23cd6ae authored by Becca Hughes's avatar Becca Hughes Committed by Commit Bot

[Media History] Support incognito

Media History needs to support incognito
for Media Feeds. For an OTR profile we
allow reads from the original profile but
no writes.

BUG=1051239

Change-Id: I03d152d6701ef034d4ce05d9970c64c720b22011
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2091592Reviewed-by: default avatarTommy Steimel <steimel@chromium.org>
Commit-Queue: Becca Hughes <beccahughes@chromium.org>
Cr-Commit-Position: refs/heads/master@{#747892}
parent 08186e84
...@@ -36,7 +36,9 @@ constexpr base::TimeDelta kTestClipDuration = ...@@ -36,7 +36,9 @@ constexpr base::TimeDelta kTestClipDuration =
} // namespace } // namespace
class MediaHistoryBrowserTest : public InProcessBrowserTest { // Runs the test with a param to signify the profile being incognito if true.
class MediaHistoryBrowserTest : public InProcessBrowserTest,
public testing::WithParamInterface<bool> {
public: public:
MediaHistoryBrowserTest() = default; MediaHistoryBrowserTest() = default;
~MediaHistoryBrowserTest() override = default; ~MediaHistoryBrowserTest() override = default;
...@@ -54,44 +56,51 @@ class MediaHistoryBrowserTest : public InProcessBrowserTest { ...@@ -54,44 +56,51 @@ class MediaHistoryBrowserTest : public InProcessBrowserTest {
InProcessBrowserTest::SetUpOnMainThread(); InProcessBrowserTest::SetUpOnMainThread();
} }
bool SetupPageAndStartPlaying(const GURL& url) { static bool SetupPageAndStartPlaying(Browser* browser, const GURL& url) {
ui_test_utils::NavigateToURL(browser(), url); ui_test_utils::NavigateToURL(browser, url);
bool played = false; bool played = false;
EXPECT_TRUE(content::ExecuteScriptAndExtractBool( EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
GetWebContents(), "attemptPlay();", &played)); browser->tab_strip_model()->GetActiveWebContents(), "attemptPlay();",
&played));
return played; return played;
} }
bool SetMediaMetadata() { static bool SetMediaMetadata(Browser* browser) {
return content::ExecuteScript(GetWebContents(), "setMediaMetadata();"); return content::ExecuteScript(
browser->tab_strip_model()->GetActiveWebContents(),
"setMediaMetadata();");
} }
bool SetMediaMetadataWithArtwork() { static bool SetMediaMetadataWithArtwork(Browser* browser) {
return content::ExecuteScript(GetWebContents(), return content::ExecuteScript(
"setMediaMetadataWithArtwork();"); browser->tab_strip_model()->GetActiveWebContents(),
"setMediaMetadataWithArtwork();");
} }
bool FinishPlaying() { static bool FinishPlaying(Browser* browser) {
return content::ExecuteScript(GetWebContents(), "finishPlaying();"); return content::ExecuteScript(
browser->tab_strip_model()->GetActiveWebContents(), "finishPlaying();");
} }
std::vector<mojom::MediaHistoryPlaybackSessionRowPtr> GetPlaybackSessionsSync( static std::vector<mojom::MediaHistoryPlaybackSessionRowPtr>
int max_sessions) { GetPlaybackSessionsSync(MediaHistoryKeyedService* service, int max_sessions) {
return GetPlaybackSessionsSync( return GetPlaybackSessionsSync(
max_sessions, base::BindRepeating([](const base::TimeDelta& duration, service, max_sessions,
const base::TimeDelta& position) { base::BindRepeating([](const base::TimeDelta& duration,
const base::TimeDelta& position) {
return duration.InSeconds() != position.InSeconds(); return duration.InSeconds() != position.InSeconds();
})); }));
} }
std::vector<mojom::MediaHistoryPlaybackSessionRowPtr> GetPlaybackSessionsSync( static std::vector<mojom::MediaHistoryPlaybackSessionRowPtr>
int max_sessions, GetPlaybackSessionsSync(MediaHistoryKeyedService* service,
MediaHistoryStore::GetPlaybackSessionsFilter filter) { int max_sessions,
MediaHistoryStore::GetPlaybackSessionsFilter filter) {
base::RunLoop run_loop; base::RunLoop run_loop;
std::vector<mojom::MediaHistoryPlaybackSessionRowPtr> out; std::vector<mojom::MediaHistoryPlaybackSessionRowPtr> out;
GetMediaHistoryService()->GetPlaybackSessions( service->GetPlaybackSessions(
max_sessions, std::move(filter), max_sessions, std::move(filter),
base::BindLambdaForTesting( base::BindLambdaForTesting(
[&](std::vector<mojom::MediaHistoryPlaybackSessionRowPtr> [&](std::vector<mojom::MediaHistoryPlaybackSessionRowPtr>
...@@ -104,11 +113,12 @@ class MediaHistoryBrowserTest : public InProcessBrowserTest { ...@@ -104,11 +113,12 @@ class MediaHistoryBrowserTest : public InProcessBrowserTest {
return out; return out;
} }
mojom::MediaHistoryStatsPtr GetStatsSync() { static mojom::MediaHistoryStatsPtr GetStatsSync(
MediaHistoryKeyedService* service) {
base::RunLoop run_loop; base::RunLoop run_loop;
mojom::MediaHistoryStatsPtr stats_out; mojom::MediaHistoryStatsPtr stats_out;
GetMediaHistoryService()->GetMediaHistoryStats( service->GetMediaHistoryStats(
base::BindLambdaForTesting([&](mojom::MediaHistoryStatsPtr stats) { base::BindLambdaForTesting([&](mojom::MediaHistoryStatsPtr stats) {
stats_out = std::move(stats); stats_out = std::move(stats);
run_loop.Quit(); run_loop.Quit();
...@@ -189,9 +199,9 @@ class MediaHistoryBrowserTest : public InProcessBrowserTest { ...@@ -189,9 +199,9 @@ class MediaHistoryBrowserTest : public InProcessBrowserTest {
return expected_metadata; return expected_metadata;
} }
void SimulateNavigationToCommit() { void SimulateNavigationToCommit(Browser* browser) {
// Navigate to trigger the session to be saved. // Navigate to trigger the session to be saved.
ui_test_utils::NavigateToURL(browser(), embedded_test_server()->base_url()); ui_test_utils::NavigateToURL(browser, embedded_test_server()->base_url());
// Wait until the session has finished saving. // Wait until the session has finished saving.
content::RunAllTasksUntilIdle(); content::RunAllTasksUntilIdle();
...@@ -205,33 +215,45 @@ class MediaHistoryBrowserTest : public InProcessBrowserTest { ...@@ -205,33 +215,45 @@ class MediaHistoryBrowserTest : public InProcessBrowserTest {
return embedded_test_server()->GetURL("/media/media_history.html?alt=1"); return embedded_test_server()->GetURL("/media/media_history.html?alt=1");
} }
content::WebContents* GetWebContents() { static content::MediaSession* GetMediaSession(Browser* browser) {
return browser()->tab_strip_model()->GetActiveWebContents(); return content::MediaSession::Get(
browser->tab_strip_model()->GetActiveWebContents());
} }
content::MediaSession* GetMediaSession() { static MediaHistoryKeyedService* GetMediaHistoryService(Browser* browser) {
return content::MediaSession::Get(GetWebContents()); return MediaHistoryKeyedServiceFactory::GetForProfile(browser->profile());
} }
MediaHistoryKeyedService* GetMediaHistoryService() { static MediaHistoryKeyedService* GetOTRMediaHistoryService(Browser* browser) {
return MediaHistoryKeyedServiceFactory::GetForProfile(browser()->profile()); return MediaHistoryKeyedServiceFactory::GetForProfile(
browser->profile()->GetOffTheRecordProfile());
} }
Browser* CreateBrowserFromParam() {
return GetParam() ? CreateIncognitoBrowser() : browser();
}
bool IsReadOnly() const { return GetParam(); }
private: private:
base::test::ScopedFeatureList scoped_feature_list_; base::test::ScopedFeatureList scoped_feature_list_;
}; };
IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest, INSTANTIATE_TEST_SUITE_P(All, MediaHistoryBrowserTest, testing::Bool());
IN_PROC_BROWSER_TEST_P(MediaHistoryBrowserTest,
RecordMediaSession_OnNavigate_Incomplete) { RecordMediaSession_OnNavigate_Incomplete) {
EXPECT_TRUE(SetupPageAndStartPlaying(GetTestURL())); auto* browser = CreateBrowserFromParam();
EXPECT_TRUE(SetMediaMetadataWithArtwork());
EXPECT_TRUE(SetupPageAndStartPlaying(browser, GetTestURL()));
EXPECT_TRUE(SetMediaMetadataWithArtwork(browser));
auto expected_metadata = GetExpectedMetadata(); auto expected_metadata = GetExpectedMetadata();
auto expected_artwork = GetExpectedArtwork(); auto expected_artwork = GetExpectedArtwork();
{ {
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kActive); media_session::mojom::MediaSessionInfo::SessionState::kActive);
observer.WaitForExpectedMetadata(expected_metadata); observer.WaitForExpectedMetadata(expected_metadata);
...@@ -240,253 +262,367 @@ IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest, ...@@ -240,253 +262,367 @@ IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest,
expected_artwork); expected_artwork);
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
// Verify the session in the database. // Verify the session in the database.
auto sessions = GetPlaybackSessionsSync(1); auto sessions = GetPlaybackSessionsSync(GetMediaHistoryService(browser), 1);
EXPECT_EQ(1u, sessions.size());
EXPECT_EQ(GetTestURL(), sessions[0]->url); if (IsReadOnly()) {
EXPECT_EQ(kTestClipDuration, sessions[0]->duration); EXPECT_TRUE(sessions.empty());
EXPECT_LT(base::TimeDelta(), sessions[0]->position); } else {
EXPECT_EQ(expected_metadata.title, sessions[0]->metadata.title); EXPECT_EQ(1u, sessions.size());
EXPECT_EQ(expected_metadata.artist, sessions[0]->metadata.artist); EXPECT_EQ(GetTestURL(), sessions[0]->url);
EXPECT_EQ(expected_metadata.album, sessions[0]->metadata.album); EXPECT_EQ(kTestClipDuration, sessions[0]->duration);
EXPECT_EQ(expected_metadata.source_title, sessions[0]->metadata.source_title); EXPECT_LT(base::TimeDelta(), sessions[0]->position);
EXPECT_EQ(expected_artwork, sessions[0]->artwork); EXPECT_EQ(expected_metadata.title, sessions[0]->metadata.title);
EXPECT_EQ(expected_metadata.artist, sessions[0]->metadata.artist);
EXPECT_EQ(expected_metadata.album, sessions[0]->metadata.album);
EXPECT_EQ(expected_metadata.source_title,
sessions[0]->metadata.source_title);
EXPECT_EQ(expected_artwork, sessions[0]->artwork);
}
// The OTR service should have the same data.
EXPECT_EQ(sessions,
GetPlaybackSessionsSync(GetOTRMediaHistoryService(browser), 1));
{ {
// Check the tables have the expected number of records // Check the tables have the expected number of records
mojom::MediaHistoryStatsPtr stats = GetStatsSync(); mojom::MediaHistoryStatsPtr stats =
EXPECT_EQ(1, stats->table_row_counts[MediaHistoryOriginTable::kTableName]); GetStatsSync(GetMediaHistoryService(browser));
EXPECT_EQ(1, stats->table_row_counts[MediaHistorySessionTable::kTableName]);
EXPECT_EQ( if (IsReadOnly()) {
7, stats->table_row_counts[MediaHistorySessionImagesTable::kTableName]); EXPECT_EQ(0,
EXPECT_EQ(6, stats->table_row_counts[MediaHistoryImagesTable::kTableName]); stats->table_row_counts[MediaHistoryOriginTable::kTableName]);
EXPECT_EQ(0,
stats->table_row_counts[MediaHistorySessionTable::kTableName]);
EXPECT_EQ(
0,
stats->table_row_counts[MediaHistorySessionImagesTable::kTableName]);
EXPECT_EQ(0,
stats->table_row_counts[MediaHistoryImagesTable::kTableName]);
} else {
EXPECT_EQ(1,
stats->table_row_counts[MediaHistoryOriginTable::kTableName]);
EXPECT_EQ(1,
stats->table_row_counts[MediaHistorySessionTable::kTableName]);
EXPECT_EQ(
7,
stats->table_row_counts[MediaHistorySessionImagesTable::kTableName]);
EXPECT_EQ(6,
stats->table_row_counts[MediaHistoryImagesTable::kTableName]);
}
// The OTR service should have the same data.
EXPECT_EQ(stats, GetStatsSync(GetOTRMediaHistoryService(browser)));
} }
} }
IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest, IN_PROC_BROWSER_TEST_P(MediaHistoryBrowserTest,
RecordMediaSession_DefaultMetadata) { RecordMediaSession_DefaultMetadata) {
EXPECT_TRUE(SetupPageAndStartPlaying(GetTestURL())); auto* browser = CreateBrowserFromParam();
EXPECT_TRUE(SetupPageAndStartPlaying(browser, GetTestURL()));
media_session::MediaMetadata expected_metadata = GetExpectedDefaultMetadata(); media_session::MediaMetadata expected_metadata = GetExpectedDefaultMetadata();
{ {
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kActive); media_session::mojom::MediaSessionInfo::SessionState::kActive);
observer.WaitForExpectedMetadata(expected_metadata); observer.WaitForExpectedMetadata(expected_metadata);
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
// Verify the session in the database. // Verify the session in the database.
auto sessions = GetPlaybackSessionsSync(1); auto sessions = GetPlaybackSessionsSync(GetMediaHistoryService(browser), 1);
EXPECT_EQ(1u, sessions.size());
EXPECT_EQ(GetTestURL(), sessions[0]->url); if (IsReadOnly()) {
EXPECT_EQ(kTestClipDuration, sessions[0]->duration); EXPECT_TRUE(sessions.empty());
EXPECT_LT(base::TimeDelta(), sessions[0]->position); } else {
EXPECT_EQ(expected_metadata.title, sessions[0]->metadata.title); EXPECT_EQ(1u, sessions.size());
EXPECT_EQ(expected_metadata.artist, sessions[0]->metadata.artist); EXPECT_EQ(GetTestURL(), sessions[0]->url);
EXPECT_EQ(expected_metadata.album, sessions[0]->metadata.album); EXPECT_EQ(kTestClipDuration, sessions[0]->duration);
EXPECT_EQ(expected_metadata.source_title, sessions[0]->metadata.source_title); EXPECT_LT(base::TimeDelta(), sessions[0]->position);
EXPECT_TRUE(sessions[0]->artwork.empty()); EXPECT_EQ(expected_metadata.title, sessions[0]->metadata.title);
EXPECT_EQ(expected_metadata.artist, sessions[0]->metadata.artist);
EXPECT_EQ(expected_metadata.album, sessions[0]->metadata.album);
EXPECT_EQ(expected_metadata.source_title,
sessions[0]->metadata.source_title);
EXPECT_TRUE(sessions[0]->artwork.empty());
}
// The OTR service should have the same data.
EXPECT_EQ(sessions,
GetPlaybackSessionsSync(GetOTRMediaHistoryService(browser), 1));
} }
IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest, IN_PROC_BROWSER_TEST_P(MediaHistoryBrowserTest,
RecordMediaSession_OnNavigate_Complete) { RecordMediaSession_OnNavigate_Complete) {
EXPECT_TRUE(SetupPageAndStartPlaying(GetTestURL())); auto* browser = CreateBrowserFromParam();
EXPECT_TRUE(FinishPlaying());
EXPECT_TRUE(SetupPageAndStartPlaying(browser, GetTestURL()));
EXPECT_TRUE(FinishPlaying(browser));
media_session::MediaMetadata expected_metadata = GetExpectedDefaultMetadata(); media_session::MediaMetadata expected_metadata = GetExpectedDefaultMetadata();
{ {
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kActive); media_session::mojom::MediaSessionInfo::SessionState::kActive);
observer.WaitForExpectedMetadata(expected_metadata); observer.WaitForExpectedMetadata(expected_metadata);
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
{ {
// The session will not be returned since it is complete. // The session will not be returned since it is complete.
auto sessions = GetPlaybackSessionsSync(1); auto sessions = GetPlaybackSessionsSync(GetMediaHistoryService(browser), 1);
EXPECT_TRUE(sessions.empty()); EXPECT_TRUE(sessions.empty());
// The OTR service should have the same data.
EXPECT_TRUE(
GetPlaybackSessionsSync(GetOTRMediaHistoryService(browser), 1).empty());
} }
{ {
// If we remove the filter when we get the sessions we should see a result. // If we remove the filter when we get the sessions we should see a result.
auto sessions = GetPlaybackSessionsSync( auto filter = base::BindRepeating(
1, base::BindRepeating( [](const base::TimeDelta& duration, const base::TimeDelta& position) {
[](const base::TimeDelta& duration, return true;
const base::TimeDelta& position) { return true; })); });
auto sessions =
GetPlaybackSessionsSync(GetMediaHistoryService(browser), 1, filter);
if (IsReadOnly()) {
EXPECT_TRUE(sessions.empty());
} else {
EXPECT_EQ(1u, sessions.size());
EXPECT_EQ(GetTestURL(), sessions[0]->url);
}
EXPECT_EQ(1u, sessions.size()); // The OTR service should have the same data.
EXPECT_EQ(GetTestURL(), sessions[0]->url); EXPECT_EQ(sessions, GetPlaybackSessionsSync(
GetOTRMediaHistoryService(browser), 1, filter));
} }
} }
IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest, DoNotRecordSessionIfNotActive) { IN_PROC_BROWSER_TEST_P(MediaHistoryBrowserTest, DoNotRecordSessionIfNotActive) {
ui_test_utils::NavigateToURL(browser(), GetTestURL()); auto* browser = CreateBrowserFromParam();
EXPECT_TRUE(SetMediaMetadata());
ui_test_utils::NavigateToURL(browser, GetTestURL());
EXPECT_TRUE(SetMediaMetadata(browser));
media_session::MediaMetadata expected_metadata = GetExpectedDefaultMetadata(); media_session::MediaMetadata expected_metadata = GetExpectedDefaultMetadata();
{ {
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kInactive); media_session::mojom::MediaSessionInfo::SessionState::kInactive);
observer.WaitForExpectedMetadata(expected_metadata); observer.WaitForExpectedMetadata(expected_metadata);
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
// Verify the session has not been stored in the database. // Verify the session has not been stored in the database.
auto sessions = GetPlaybackSessionsSync(1); auto sessions = GetPlaybackSessionsSync(GetMediaHistoryService(browser), 1);
EXPECT_TRUE(sessions.empty()); EXPECT_TRUE(sessions.empty());
// The OTR service should have the same data.
EXPECT_TRUE(
GetPlaybackSessionsSync(GetOTRMediaHistoryService(browser), 1).empty());
} }
IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest, GetPlaybackSessions) { IN_PROC_BROWSER_TEST_P(MediaHistoryBrowserTest, GetPlaybackSessions) {
auto* browser = CreateBrowserFromParam();
auto expected_default_metadata = GetExpectedDefaultMetadata(); auto expected_default_metadata = GetExpectedDefaultMetadata();
{ {
// Start a session. // Start a session.
EXPECT_TRUE(SetupPageAndStartPlaying(GetTestURL())); EXPECT_TRUE(SetupPageAndStartPlaying(browser, GetTestURL()));
EXPECT_TRUE(SetMediaMetadataWithArtwork()); EXPECT_TRUE(SetMediaMetadataWithArtwork(browser));
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kActive); media_session::mojom::MediaSessionInfo::SessionState::kActive);
observer.WaitForExpectedMetadata(GetExpectedMetadata()); observer.WaitForExpectedMetadata(GetExpectedMetadata());
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
{ {
// Start a second session on a different URL. // Start a second session on a different URL.
EXPECT_TRUE(SetupPageAndStartPlaying(GetTestAltURL())); EXPECT_TRUE(SetupPageAndStartPlaying(browser, GetTestAltURL()));
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kActive); media_session::mojom::MediaSessionInfo::SessionState::kActive);
observer.WaitForExpectedMetadata(expected_default_metadata); observer.WaitForExpectedMetadata(expected_default_metadata);
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
{ {
// Get the two most recent playback sessions and check they are in order. // Get the two most recent playback sessions and check they are in order.
auto sessions = GetPlaybackSessionsSync(2); auto sessions = GetPlaybackSessionsSync(GetMediaHistoryService(browser), 2);
EXPECT_EQ(2u, sessions.size());
EXPECT_EQ(GetTestAltURL(), sessions[0]->url); if (IsReadOnly()) {
EXPECT_EQ(GetTestURL(), sessions[1]->url); EXPECT_TRUE(sessions.empty());
} else {
EXPECT_EQ(2u, sessions.size());
EXPECT_EQ(GetTestAltURL(), sessions[0]->url);
EXPECT_EQ(GetTestURL(), sessions[1]->url);
}
// The OTR service should have the same data.
EXPECT_EQ(sessions,
GetPlaybackSessionsSync(GetOTRMediaHistoryService(browser), 2));
} }
{ {
// Get the last playback session. // Get the last playback session.
auto sessions = GetPlaybackSessionsSync(1); auto sessions = GetPlaybackSessionsSync(GetMediaHistoryService(browser), 1);
EXPECT_EQ(1u, sessions.size());
EXPECT_EQ(GetTestAltURL(), sessions[0]->url); if (IsReadOnly()) {
EXPECT_TRUE(sessions.empty());
} else {
EXPECT_EQ(1u, sessions.size());
EXPECT_EQ(GetTestAltURL(), sessions[0]->url);
}
// The OTR service should have the same data.
EXPECT_EQ(sessions,
GetPlaybackSessionsSync(GetOTRMediaHistoryService(browser), 1));
} }
{ {
// Start the first page again and seek to 4 seconds in with different // Start the first page again and seek to 4 seconds in with different
// metadata. // metadata.
EXPECT_TRUE(SetupPageAndStartPlaying(GetTestURL())); EXPECT_TRUE(SetupPageAndStartPlaying(browser, GetTestURL()));
EXPECT_TRUE(content::ExecuteScript(GetWebContents(), "seekToFour()")); EXPECT_TRUE(content::ExecuteScript(
browser->tab_strip_model()->GetActiveWebContents(), "seekToFour()"));
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kActive); media_session::mojom::MediaSessionInfo::SessionState::kActive);
observer.WaitForExpectedMetadata(expected_default_metadata); observer.WaitForExpectedMetadata(expected_default_metadata);
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
{ {
// Check that recent playback sessions only returns two playback sessions // Check that recent playback sessions only returns two playback sessions
// because the first one was collapsed into the third one since they // because the first one was collapsed into the third one since they
// have the same URL. We should also use the data from the most recent // have the same URL. We should also use the data from the most recent
// playback. // playback.
auto sessions = GetPlaybackSessionsSync(3); auto sessions = GetPlaybackSessionsSync(GetMediaHistoryService(browser), 3);
EXPECT_EQ(2u, sessions.size());
EXPECT_EQ(GetTestURL(), sessions[0]->url); if (IsReadOnly()) {
EXPECT_EQ(GetTestAltURL(), sessions[1]->url); EXPECT_TRUE(sessions.empty());
} else {
EXPECT_EQ(2u, sessions.size());
EXPECT_EQ(GetTestURL(), sessions[0]->url);
EXPECT_EQ(GetTestAltURL(), sessions[1]->url);
EXPECT_EQ(kTestClipDuration, sessions[0]->duration);
EXPECT_EQ(4, sessions[0]->position.InSeconds());
EXPECT_EQ(expected_default_metadata.title, sessions[0]->metadata.title);
EXPECT_EQ(expected_default_metadata.artist, sessions[0]->metadata.artist);
EXPECT_EQ(expected_default_metadata.album, sessions[0]->metadata.album);
EXPECT_EQ(expected_default_metadata.source_title,
sessions[0]->metadata.source_title);
}
EXPECT_EQ(kTestClipDuration, sessions[0]->duration); // The OTR service should have the same data.
EXPECT_EQ(4, sessions[0]->position.InSeconds()); EXPECT_EQ(sessions,
EXPECT_EQ(expected_default_metadata.title, sessions[0]->metadata.title); GetPlaybackSessionsSync(GetOTRMediaHistoryService(browser), 3));
EXPECT_EQ(expected_default_metadata.artist, sessions[0]->metadata.artist);
EXPECT_EQ(expected_default_metadata.album, sessions[0]->metadata.album);
EXPECT_EQ(expected_default_metadata.source_title,
sessions[0]->metadata.source_title);
} }
{ {
// Start the first page again and finish playing. // Start the first page again and finish playing.
EXPECT_TRUE(SetupPageAndStartPlaying(GetTestURL())); EXPECT_TRUE(SetupPageAndStartPlaying(browser, GetTestURL()));
EXPECT_TRUE(FinishPlaying()); EXPECT_TRUE(FinishPlaying(browser));
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kActive); media_session::mojom::MediaSessionInfo::SessionState::kActive);
observer.WaitForExpectedMetadata(expected_default_metadata); observer.WaitForExpectedMetadata(expected_default_metadata);
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
{ {
// Get the recent playbacks and the test URL should not appear at all // Get the recent playbacks and the test URL should not appear at all
// because playback has completed for that URL. // because playback has completed for that URL.
auto sessions = GetPlaybackSessionsSync(4); auto sessions = GetPlaybackSessionsSync(GetMediaHistoryService(browser), 4);
EXPECT_EQ(1u, sessions.size());
EXPECT_EQ(GetTestAltURL(), sessions[0]->url); if (IsReadOnly()) {
EXPECT_TRUE(sessions.empty());
} else {
EXPECT_EQ(1u, sessions.size());
EXPECT_EQ(GetTestAltURL(), sessions[0]->url);
}
// The OTR service should have the same data.
EXPECT_EQ(sessions,
GetPlaybackSessionsSync(GetOTRMediaHistoryService(browser), 4));
} }
{ {
// Start the first session again. // Start the first session again.
EXPECT_TRUE(SetupPageAndStartPlaying(GetTestURL())); EXPECT_TRUE(SetupPageAndStartPlaying(browser, GetTestURL()));
EXPECT_TRUE(SetMediaMetadata()); EXPECT_TRUE(SetMediaMetadata(browser));
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kActive); media_session::mojom::MediaSessionInfo::SessionState::kActive);
observer.WaitForExpectedMetadata(GetExpectedMetadata()); observer.WaitForExpectedMetadata(GetExpectedMetadata());
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
{ {
// The test URL should now appear in the recent playbacks list again since // The test URL should now appear in the recent playbacks list again since
// it is incomplete again. // it is incomplete again.
auto sessions = GetPlaybackSessionsSync(2); auto sessions = GetPlaybackSessionsSync(GetMediaHistoryService(browser), 2);
EXPECT_EQ(2u, sessions.size());
EXPECT_EQ(GetTestURL(), sessions[0]->url); if (IsReadOnly()) {
EXPECT_EQ(GetTestAltURL(), sessions[1]->url); EXPECT_TRUE(sessions.empty());
} else {
EXPECT_EQ(2u, sessions.size());
EXPECT_EQ(GetTestURL(), sessions[0]->url);
EXPECT_EQ(GetTestAltURL(), sessions[1]->url);
}
// The OTR service should have the same data.
EXPECT_EQ(sessions,
GetPlaybackSessionsSync(GetOTRMediaHistoryService(browser), 2));
} }
} }
IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest, IN_PROC_BROWSER_TEST_P(MediaHistoryBrowserTest,
SaveImagesWithDifferentSessions) { SaveImagesWithDifferentSessions) {
auto* browser = CreateBrowserFromParam();
auto expected_metadata = GetExpectedMetadata(); auto expected_metadata = GetExpectedMetadata();
auto expected_artwork = GetExpectedArtwork(); auto expected_artwork = GetExpectedArtwork();
{ {
// Start a session. // Start a session.
EXPECT_TRUE(SetupPageAndStartPlaying(GetTestURL())); EXPECT_TRUE(SetupPageAndStartPlaying(browser, GetTestURL()));
EXPECT_TRUE(SetMediaMetadataWithArtwork()); EXPECT_TRUE(SetMediaMetadataWithArtwork(browser));
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kActive); media_session::mojom::MediaSessionInfo::SessionState::kActive);
observer.WaitForExpectedMetadata(expected_metadata); observer.WaitForExpectedMetadata(expected_metadata);
...@@ -495,7 +631,7 @@ IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest, ...@@ -495,7 +631,7 @@ IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest,
expected_artwork); expected_artwork);
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
std::vector<media_session::MediaImage> expected_alt_artwork; std::vector<media_session::MediaImage> expected_alt_artwork;
...@@ -517,12 +653,13 @@ IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest, ...@@ -517,12 +653,13 @@ IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest,
{ {
// Start a second session on a different URL. // Start a second session on a different URL.
EXPECT_TRUE(SetupPageAndStartPlaying(GetTestAltURL())); EXPECT_TRUE(SetupPageAndStartPlaying(browser, GetTestAltURL()));
EXPECT_TRUE(content::ExecuteScript(GetWebContents(), EXPECT_TRUE(content::ExecuteScript(
"setMediaMetadataWithAltArtwork();")); browser->tab_strip_model()->GetActiveWebContents(),
"setMediaMetadataWithAltArtwork();"));
media_session::test::MockMediaSessionMojoObserver observer( media_session::test::MockMediaSessionMojoObserver observer(
*GetMediaSession()); *GetMediaSession(browser));
observer.WaitForState( observer.WaitForState(
media_session::mojom::MediaSessionInfo::SessionState::kActive); media_session::mojom::MediaSessionInfo::SessionState::kActive);
observer.WaitForExpectedMetadata(expected_metadata); observer.WaitForExpectedMetadata(expected_metadata);
...@@ -531,15 +668,24 @@ IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest, ...@@ -531,15 +668,24 @@ IN_PROC_BROWSER_TEST_F(MediaHistoryBrowserTest,
expected_alt_artwork); expected_alt_artwork);
} }
SimulateNavigationToCommit(); SimulateNavigationToCommit(browser);
// Verify the session in the database. // Verify the session in the database.
auto sessions = GetPlaybackSessionsSync(2); auto sessions = GetPlaybackSessionsSync(GetMediaHistoryService(browser), 2);
EXPECT_EQ(2u, sessions.size());
EXPECT_EQ(GetTestAltURL(), sessions[0]->url); if (IsReadOnly()) {
EXPECT_EQ(expected_alt_artwork, sessions[0]->artwork); EXPECT_TRUE(sessions.empty());
EXPECT_EQ(GetTestURL(), sessions[1]->url); } else {
EXPECT_EQ(expected_artwork, sessions[1]->artwork); EXPECT_EQ(2u, sessions.size());
EXPECT_EQ(GetTestAltURL(), sessions[0]->url);
EXPECT_EQ(expected_alt_artwork, sessions[0]->artwork);
EXPECT_EQ(GetTestURL(), sessions[1]->url);
EXPECT_EQ(expected_artwork, sessions[1]->artwork);
}
// The OTR service should have the same data.
EXPECT_EQ(sessions,
GetPlaybackSessionsSync(GetOTRMediaHistoryService(browser), 2));
} }
} // namespace media_history } // namespace media_history
...@@ -16,22 +16,59 @@ ...@@ -16,22 +16,59 @@
namespace media_history { namespace media_history {
// StoreHolder will in most cases hold a local MediaHistoryStore. However, for
// OTR profiles we hold a pointer to the original profile store. When accessing
// MediaHistoryStore you should use GetForRead for read operations and
// GetForWrite for write operations. This can be null if the store is read only.
class MediaHistoryKeyedService::StoreHolder {
public:
explicit StoreHolder(std::unique_ptr<MediaHistoryStore> local)
: local_(std::move(local)) {}
explicit StoreHolder(MediaHistoryKeyedService* remote) : remote_(remote) {}
~StoreHolder() = default;
StoreHolder(const StoreHolder& t) = delete;
StoreHolder& operator=(const StoreHolder&) = delete;
MediaHistoryStore* GetForRead() {
if (local_)
return local_.get();
return remote_->store_->GetForRead();
}
MediaHistoryStore* GetForWrite() {
if (local_)
return local_.get();
return nullptr;
}
private:
std::unique_ptr<MediaHistoryStore> local_;
MediaHistoryKeyedService* remote_ = nullptr;
};
MediaHistoryKeyedService::MediaHistoryKeyedService(Profile* profile) MediaHistoryKeyedService::MediaHistoryKeyedService(Profile* profile)
: profile_(profile) { : profile_(profile) {
DCHECK(!profile->IsOffTheRecord());
// May be null in tests. // May be null in tests.
history::HistoryService* history = HistoryServiceFactory::GetForProfile( history::HistoryService* history = HistoryServiceFactory::GetForProfile(
profile, ServiceAccessType::IMPLICIT_ACCESS); profile, ServiceAccessType::IMPLICIT_ACCESS);
if (history) if (history)
history->AddObserver(this); history->AddObserver(this);
auto db_task_runner = base::ThreadPool::CreateUpdateableSequencedTaskRunner( if (profile->IsOffTheRecord()) {
{base::MayBlock(), base::TaskPriority::USER_VISIBLE, MediaHistoryKeyedService* original =
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); MediaHistoryKeyedService::Get(profile->GetOriginalProfile());
DCHECK(original);
media_history_store_ = store_ = std::make_unique<StoreHolder>(original);
std::make_unique<MediaHistoryStore>(profile_, std::move(db_task_runner)); } else {
auto db_task_runner = base::ThreadPool::CreateUpdateableSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
store_ = std::make_unique<StoreHolder>(std::make_unique<MediaHistoryStore>(
profile_, std::move(db_task_runner)));
}
} }
// static // static
...@@ -55,9 +92,14 @@ void MediaHistoryKeyedService::Shutdown() { ...@@ -55,9 +92,14 @@ void MediaHistoryKeyedService::Shutdown() {
void MediaHistoryKeyedService::OnURLsDeleted( void MediaHistoryKeyedService::OnURLsDeleted(
history::HistoryService* history_service, history::HistoryService* history_service,
const history::DeletionInfo& deletion_info) { const history::DeletionInfo& deletion_info) {
// The store might not always be writable.
auto* store = store_->GetForWrite();
if (!store)
return;
if (deletion_info.IsAllHistory()) { if (deletion_info.IsAllHistory()) {
// Destroy the old database and create a new one. // Destroy the old database and create a new one.
media_history_store_->EraseDatabaseAndCreateNew(); store->EraseDatabaseAndCreateNew();
return; return;
} }
...@@ -80,7 +122,7 @@ void MediaHistoryKeyedService::OnURLsDeleted( ...@@ -80,7 +122,7 @@ void MediaHistoryKeyedService::OnURLsDeleted(
} }
if (!no_more_origins.empty()) if (!no_more_origins.empty())
media_history_store_->DeleteAllOriginData(no_more_origins); store->DeleteAllOriginData(no_more_origins);
// TODO(https://crbug.com/1024352): For any origins that still have data we // TODO(https://crbug.com/1024352): For any origins that still have data we
// should remove data by URL. // should remove data by URL.
...@@ -88,24 +130,25 @@ void MediaHistoryKeyedService::OnURLsDeleted( ...@@ -88,24 +130,25 @@ void MediaHistoryKeyedService::OnURLsDeleted(
void MediaHistoryKeyedService::SavePlayback( void MediaHistoryKeyedService::SavePlayback(
const content::MediaPlayerWatchTime& watch_time) { const content::MediaPlayerWatchTime& watch_time) {
media_history_store_->SavePlayback(watch_time); if (auto* store = store_->GetForWrite())
store->SavePlayback(watch_time);
} }
void MediaHistoryKeyedService::GetMediaHistoryStats( void MediaHistoryKeyedService::GetMediaHistoryStats(
base::OnceCallback<void(mojom::MediaHistoryStatsPtr)> callback) { base::OnceCallback<void(mojom::MediaHistoryStatsPtr)> callback) {
media_history_store_->GetMediaHistoryStats(std::move(callback)); store_->GetForRead()->GetMediaHistoryStats(std::move(callback));
} }
void MediaHistoryKeyedService::GetOriginRowsForDebug( void MediaHistoryKeyedService::GetOriginRowsForDebug(
base::OnceCallback<void(std::vector<mojom::MediaHistoryOriginRowPtr>)> base::OnceCallback<void(std::vector<mojom::MediaHistoryOriginRowPtr>)>
callback) { callback) {
media_history_store_->GetOriginRowsForDebug(std::move(callback)); store_->GetForRead()->GetOriginRowsForDebug(std::move(callback));
} }
void MediaHistoryKeyedService::GetMediaHistoryPlaybackRowsForDebug( void MediaHistoryKeyedService::GetMediaHistoryPlaybackRowsForDebug(
base::OnceCallback<void(std::vector<mojom::MediaHistoryPlaybackRowPtr>)> base::OnceCallback<void(std::vector<mojom::MediaHistoryPlaybackRowPtr>)>
callback) { callback) {
media_history_store_->GetMediaHistoryPlaybackRowsForDebug( store_->GetForRead()->GetMediaHistoryPlaybackRowsForDebug(
std::move(callback)); std::move(callback));
} }
...@@ -114,7 +157,7 @@ void MediaHistoryKeyedService::GetPlaybackSessions( ...@@ -114,7 +157,7 @@ void MediaHistoryKeyedService::GetPlaybackSessions(
base::Optional<GetPlaybackSessionsFilter> filter, base::Optional<GetPlaybackSessionsFilter> filter,
base::OnceCallback< base::OnceCallback<
void(std::vector<mojom::MediaHistoryPlaybackSessionRowPtr>)> callback) { void(std::vector<mojom::MediaHistoryPlaybackSessionRowPtr>)> callback) {
media_history_store_->GetPlaybackSessions(num_sessions, filter, store_->GetForRead()->GetPlaybackSessions(num_sessions, filter,
std::move(callback)); std::move(callback));
} }
...@@ -123,17 +166,23 @@ void MediaHistoryKeyedService::SavePlaybackSession( ...@@ -123,17 +166,23 @@ void MediaHistoryKeyedService::SavePlaybackSession(
const media_session::MediaMetadata& metadata, const media_session::MediaMetadata& metadata,
const base::Optional<media_session::MediaPosition>& position, const base::Optional<media_session::MediaPosition>& position,
const std::vector<media_session::MediaImage>& artwork) { const std::vector<media_session::MediaImage>& artwork) {
media_history_store_->SavePlaybackSession(url, metadata, position, artwork); if (auto* store = store_->GetForWrite())
store->SavePlaybackSession(url, metadata, position, artwork);
} }
void MediaHistoryKeyedService::GetURLsInTableForTest( void MediaHistoryKeyedService::GetURLsInTableForTest(
const std::string& table, const std::string& table,
base::OnceCallback<void(std::set<GURL>)> callback) { base::OnceCallback<void(std::set<GURL>)> callback) {
media_history_store_->GetURLsInTableForTest(table, std::move(callback)); store_->GetForRead()->GetURLsInTableForTest(table, std::move(callback));
} }
void MediaHistoryKeyedService::SaveMediaFeed(const GURL& url) { void MediaHistoryKeyedService::SaveMediaFeed(const GURL& url) {
media_history_store_->SaveMediaFeed(url); if (auto* store = store_->GetForWrite())
store->SaveMediaFeed(url);
}
void MediaHistoryKeyedService::PostTaskToDBForTest(base::OnceClosure callback) {
store_->GetForRead()->PostTaskToDBForTest(std::move(callback));
} }
} // namespace media_history } // namespace media_history
...@@ -83,14 +83,18 @@ class MediaHistoryKeyedService : public KeyedService, ...@@ -83,14 +83,18 @@ class MediaHistoryKeyedService : public KeyedService,
// Saves a newly discovered media feed in the media history store. // Saves a newly discovered media feed in the media history store.
void SaveMediaFeed(const GURL& url); void SaveMediaFeed(const GURL& url);
protected:
friend class MediaHistoryKeyedServiceTest;
void GetURLsInTableForTest(const std::string& table, void GetURLsInTableForTest(const std::string& table,
base::OnceCallback<void(std::set<GURL>)> callback); base::OnceCallback<void(std::set<GURL>)> callback);
// Posts an empty task to the database thread. The callback will be called
// on the calling thread when the empty task is completed. This can be used
// for waiting for database operations in tests.
void PostTaskToDBForTest(base::OnceClosure callback);
private: private:
std::unique_ptr<MediaHistoryStore> media_history_store_; class StoreHolder;
std::unique_ptr<StoreHolder> store_;
Profile* profile_; Profile* profile_;
......
...@@ -16,9 +16,6 @@ namespace media_history { ...@@ -16,9 +16,6 @@ namespace media_history {
// static // static
MediaHistoryKeyedService* MediaHistoryKeyedServiceFactory::GetForProfile( MediaHistoryKeyedService* MediaHistoryKeyedServiceFactory::GetForProfile(
Profile* profile) { Profile* profile) {
if (profile->IsOffTheRecord())
return nullptr;
return static_cast<MediaHistoryKeyedService*>( return static_cast<MediaHistoryKeyedService*>(
GetInstance()->GetServiceForBrowserContext(profile, true)); GetInstance()->GetServiceForBrowserContext(profile, true));
} }
...@@ -46,9 +43,14 @@ bool MediaHistoryKeyedServiceFactory::ServiceIsCreatedWithBrowserContext() ...@@ -46,9 +43,14 @@ bool MediaHistoryKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
KeyedService* MediaHistoryKeyedServiceFactory::BuildServiceInstanceFor( KeyedService* MediaHistoryKeyedServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const { content::BrowserContext* context) const {
DCHECK(!context->IsOffTheRecord());
return new MediaHistoryKeyedService(Profile::FromBrowserContext(context)); return new MediaHistoryKeyedService(Profile::FromBrowserContext(context));
} }
content::BrowserContext*
MediaHistoryKeyedServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
// Enable incognito profiles.
return context;
}
} // namespace media_history } // namespace media_history
...@@ -37,6 +37,9 @@ class MediaHistoryKeyedServiceFactory ...@@ -37,6 +37,9 @@ class MediaHistoryKeyedServiceFactory
KeyedService* BuildServiceInstanceFor( KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override; content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
DISALLOW_COPY_AND_ASSIGN(MediaHistoryKeyedServiceFactory); DISALLOW_COPY_AND_ASSIGN(MediaHistoryKeyedServiceFactory);
}; };
......
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/history/media_history_keyed_service_factory.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media_history {
class MediaHistoryKeyedServiceFactoryUnitTest : public testing::Test {
public:
MediaHistoryKeyedServiceFactoryUnitTest() = default;
private:
content::BrowserTaskEnvironment task_environment_;
};
TEST_F(MediaHistoryKeyedServiceFactoryUnitTest, GetForOTRProfile) {
TestingProfile profile;
Profile* otr_profile = profile.GetOffTheRecordProfile();
EXPECT_EQ(nullptr,
MediaHistoryKeyedServiceFactory::GetForProfile(otr_profile));
}
} // namespace media_history
...@@ -590,4 +590,9 @@ void MediaHistoryStore::SaveMediaFeed(const GURL& url) { ...@@ -590,4 +590,9 @@ void MediaHistoryStore::SaveMediaFeed(const GURL& url) {
base::BindOnce(&MediaHistoryStoreInternal::SaveMediaFeed, db_, url)); base::BindOnce(&MediaHistoryStoreInternal::SaveMediaFeed, db_, url));
} }
void MediaHistoryStore::PostTaskToDBForTest(base::OnceClosure callback) {
db_->db_task_runner_->PostTaskAndReply(FROM_HERE, base::DoNothing(),
std::move(callback));
}
} // namespace media_history } // namespace media_history
...@@ -102,6 +102,8 @@ class MediaHistoryStore { ...@@ -102,6 +102,8 @@ class MediaHistoryStore {
void GetURLsInTableForTest(const std::string& table, void GetURLsInTableForTest(const std::string& table,
base::OnceCallback<void(std::set<GURL>)> callback); base::OnceCallback<void(std::set<GURL>)> callback);
void PostTaskToDBForTest(base::OnceClosure callback);
private: private:
scoped_refptr<MediaHistoryStoreInternal> db_; scoped_refptr<MediaHistoryStoreInternal> db_;
......
...@@ -55,7 +55,9 @@ std::unique_ptr<KeyedService> BuildTestHistoryService( ...@@ -55,7 +55,9 @@ std::unique_ptr<KeyedService> BuildTestHistoryService(
} // namespace } // namespace
class MediaHistoryStoreUnitTest : public testing::Test { // Runs the test with a param to signify the profile being incognito if true.
class MediaHistoryStoreUnitTest : public testing::Test,
public testing::WithParamInterface<bool> {
public: public:
MediaHistoryStoreUnitTest() = default; MediaHistoryStoreUnitTest() = default;
void SetUp() override { void SetUp() override {
...@@ -64,37 +66,42 @@ class MediaHistoryStoreUnitTest : public testing::Test { ...@@ -64,37 +66,42 @@ class MediaHistoryStoreUnitTest : public testing::Test {
TestingProfile::Builder profile_builder; TestingProfile::Builder profile_builder;
profile_builder.SetPath(temp_dir_.GetPath()); profile_builder.SetPath(temp_dir_.GetPath());
g_temp_history_dir = temp_dir_.GetPath(); g_temp_history_dir = temp_dir_.GetPath();
profile_ = profile_builder.Build(); profile_ = profile_builder.Build();
HistoryServiceFactory::GetInstance()->SetTestingFactory( HistoryServiceFactory::GetInstance()->SetTestingFactory(
profile_.get(), base::BindRepeating(&BuildTestHistoryService)); profile_.get(), base::BindRepeating(&BuildTestHistoryService));
// Set up the media history store.
service_ = std::make_unique<MediaHistoryKeyedService>(profile_.get());
// Sleep the thread to allow the media history store to asynchronously // Sleep the thread to allow the media history store to asynchronously
// create the database and tables before proceeding with the tests and // create the database and tables before proceeding with the tests and
// tearing down the temporary directory. // tearing down the temporary directory.
content::RunAllTasksUntilIdle(); WaitForDB();
// Set up the local DB connection used for assertions. // Set up the local DB connection used for assertions.
base::FilePath db_file = base::FilePath db_file =
temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Media History")); temp_dir_.GetPath().Append(FILE_PATH_LITERAL("Media History"));
ASSERT_TRUE(db_.Open(db_file)); ASSERT_TRUE(db_.Open(db_file));
// Set up the media history store for OTR.
otr_service_ = std::make_unique<MediaHistoryKeyedService>(
profile_->GetOffTheRecordProfile());
} }
void TearDown() override { void TearDown() override { WaitForDB(); }
service_->Shutdown();
void WaitForDB() {
base::RunLoop run_loop;
MediaHistoryKeyedService::Get(profile_.get())
->PostTaskToDBForTest(run_loop.QuitClosure());
content::RunAllTasksUntilIdle(); run_loop.Run();
} }
mojom::MediaHistoryStatsPtr GetStatsSync() { mojom::MediaHistoryStatsPtr GetStatsSync(MediaHistoryKeyedService* service) {
base::RunLoop run_loop; base::RunLoop run_loop;
mojom::MediaHistoryStatsPtr stats_out; mojom::MediaHistoryStatsPtr stats_out;
service()->GetMediaHistoryStats( service->GetMediaHistoryStats(
base::BindLambdaForTesting([&](mojom::MediaHistoryStatsPtr stats) { base::BindLambdaForTesting([&](mojom::MediaHistoryStatsPtr stats) {
stats_out = std::move(stats); stats_out = std::move(stats);
run_loop.Quit(); run_loop.Quit();
...@@ -104,11 +111,12 @@ class MediaHistoryStoreUnitTest : public testing::Test { ...@@ -104,11 +111,12 @@ class MediaHistoryStoreUnitTest : public testing::Test {
return stats_out; return stats_out;
} }
std::vector<mojom::MediaHistoryOriginRowPtr> GetOriginRowsSync() { std::vector<mojom::MediaHistoryOriginRowPtr> GetOriginRowsSync(
MediaHistoryKeyedService* service) {
base::RunLoop run_loop; base::RunLoop run_loop;
std::vector<mojom::MediaHistoryOriginRowPtr> out; std::vector<mojom::MediaHistoryOriginRowPtr> out;
service()->GetOriginRowsForDebug(base::BindLambdaForTesting( service->GetOriginRowsForDebug(base::BindLambdaForTesting(
[&](std::vector<mojom::MediaHistoryOriginRowPtr> rows) { [&](std::vector<mojom::MediaHistoryOriginRowPtr> rows) {
out = std::move(rows); out = std::move(rows);
run_loop.Quit(); run_loop.Quit();
...@@ -118,11 +126,12 @@ class MediaHistoryStoreUnitTest : public testing::Test { ...@@ -118,11 +126,12 @@ class MediaHistoryStoreUnitTest : public testing::Test {
return out; return out;
} }
std::vector<mojom::MediaHistoryPlaybackRowPtr> GetPlaybackRowsSync() { std::vector<mojom::MediaHistoryPlaybackRowPtr> GetPlaybackRowsSync(
MediaHistoryKeyedService* service) {
base::RunLoop run_loop; base::RunLoop run_loop;
std::vector<mojom::MediaHistoryPlaybackRowPtr> out; std::vector<mojom::MediaHistoryPlaybackRowPtr> out;
service()->GetMediaHistoryPlaybackRowsForDebug(base::BindLambdaForTesting( service->GetMediaHistoryPlaybackRowsForDebug(base::BindLambdaForTesting(
[&](std::vector<mojom::MediaHistoryPlaybackRowPtr> rows) { [&](std::vector<mojom::MediaHistoryPlaybackRowPtr> rows) {
out = std::move(rows); out = std::move(rows);
run_loop.Quit(); run_loop.Quit();
...@@ -132,7 +141,18 @@ class MediaHistoryStoreUnitTest : public testing::Test { ...@@ -132,7 +141,18 @@ class MediaHistoryStoreUnitTest : public testing::Test {
return out; return out;
} }
MediaHistoryKeyedService* service() const { return service_.get(); } MediaHistoryKeyedService* service() const {
// If the param is true then we use the OTR service to simulate being in
// incognito.
if (GetParam())
return otr_service();
return MediaHistoryKeyedService::Get(profile_.get());
}
MediaHistoryKeyedService* otr_service() const { return otr_service_.get(); }
bool IsReadOnly() const { return GetParam(); }
private: private:
base::ScopedTempDir temp_dir_; base::ScopedTempDir temp_dir_;
...@@ -143,11 +163,13 @@ class MediaHistoryStoreUnitTest : public testing::Test { ...@@ -143,11 +163,13 @@ class MediaHistoryStoreUnitTest : public testing::Test {
private: private:
sql::Database db_; sql::Database db_;
std::unique_ptr<MediaHistoryKeyedService> service_; std::unique_ptr<MediaHistoryKeyedService> otr_service_;
std::unique_ptr<TestingProfile> profile_; std::unique_ptr<TestingProfile> profile_;
}; };
TEST_F(MediaHistoryStoreUnitTest, CreateDatabaseTables) { INSTANTIATE_TEST_SUITE_P(All, MediaHistoryStoreUnitTest, testing::Bool());
TEST_P(MediaHistoryStoreUnitTest, CreateDatabaseTables) {
ASSERT_TRUE(GetDB().DoesTableExist("origin")); ASSERT_TRUE(GetDB().DoesTableExist("origin"));
ASSERT_TRUE(GetDB().DoesTableExist("playback")); ASSERT_TRUE(GetDB().DoesTableExist("playback"));
ASSERT_TRUE(GetDB().DoesTableExist("playbackSession")); ASSERT_TRUE(GetDB().DoesTableExist("playbackSession"));
...@@ -156,7 +178,7 @@ TEST_F(MediaHistoryStoreUnitTest, CreateDatabaseTables) { ...@@ -156,7 +178,7 @@ TEST_F(MediaHistoryStoreUnitTest, CreateDatabaseTables) {
ASSERT_FALSE(GetDB().DoesTableExist("mediaFeed")); ASSERT_FALSE(GetDB().DoesTableExist("mediaFeed"));
} }
TEST_F(MediaHistoryStoreUnitTest, SavePlayback) { TEST_P(MediaHistoryStoreUnitTest, SavePlayback) {
const auto now_before = const auto now_before =
(base::Time::Now() - base::TimeDelta::FromMinutes(1)).ToJsTime(); (base::Time::Now() - base::TimeDelta::FromMinutes(1)).ToJsTime();
...@@ -172,41 +194,56 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback) { ...@@ -172,41 +194,56 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback) {
service()->SavePlayback(watch_time); service()->SavePlayback(watch_time);
// Wait until the playbacks have finished saving. // Wait until the playbacks have finished saving.
content::RunAllTasksUntilIdle(); WaitForDB();
const auto now_after_b = base::Time::Now().ToJsTime(); const auto now_after_b = base::Time::Now().ToJsTime();
// Verify that the playback table contains the expected number of items. // Verify that the playback table contains the expected number of items.
std::vector<mojom::MediaHistoryPlaybackRowPtr> playbacks = std::vector<mojom::MediaHistoryPlaybackRowPtr> playbacks =
GetPlaybackRowsSync(); GetPlaybackRowsSync(service());
EXPECT_EQ(2u, playbacks.size());
if (IsReadOnly()) {
EXPECT_EQ("http://google.com/test", playbacks[0]->url.spec()); EXPECT_TRUE(playbacks.empty());
EXPECT_FALSE(playbacks[0]->has_audio); } else {
EXPECT_TRUE(playbacks[0]->has_video); EXPECT_EQ(2u, playbacks.size());
EXPECT_EQ(base::TimeDelta::FromSeconds(60), playbacks[0]->watchtime);
EXPECT_LE(now_before, playbacks[0]->last_updated_time); EXPECT_EQ("http://google.com/test", playbacks[0]->url.spec());
EXPECT_GE(now_after_a, playbacks[0]->last_updated_time); EXPECT_FALSE(playbacks[0]->has_audio);
EXPECT_TRUE(playbacks[0]->has_video);
EXPECT_EQ("http://google.com/test", playbacks[1]->url.spec()); EXPECT_EQ(base::TimeDelta::FromSeconds(60), playbacks[0]->watchtime);
EXPECT_FALSE(playbacks[1]->has_audio); EXPECT_LE(now_before, playbacks[0]->last_updated_time);
EXPECT_TRUE(playbacks[1]->has_video); EXPECT_GE(now_after_a, playbacks[0]->last_updated_time);
EXPECT_EQ(base::TimeDelta::FromSeconds(60), playbacks[1]->watchtime);
EXPECT_LE(now_before, playbacks[1]->last_updated_time); EXPECT_EQ("http://google.com/test", playbacks[1]->url.spec());
EXPECT_GE(now_after_b, playbacks[1]->last_updated_time); EXPECT_FALSE(playbacks[1]->has_audio);
EXPECT_TRUE(playbacks[1]->has_video);
EXPECT_EQ(base::TimeDelta::FromSeconds(60), playbacks[1]->watchtime);
EXPECT_LE(now_before, playbacks[1]->last_updated_time);
EXPECT_GE(now_after_b, playbacks[1]->last_updated_time);
}
// Verify that the origin table contains the expected number of items. // Verify that the origin table contains the expected number of items.
std::vector<mojom::MediaHistoryOriginRowPtr> origins = GetOriginRowsSync(); std::vector<mojom::MediaHistoryOriginRowPtr> origins =
EXPECT_EQ(1u, origins.size()); GetOriginRowsSync(service());
EXPECT_EQ("http://google.com", origins[0]->origin.Serialize());
EXPECT_LE(now_before, origins[0]->last_updated_time); if (IsReadOnly()) {
EXPECT_GE(now_after_b, origins[0]->last_updated_time); EXPECT_TRUE(origins.empty());
} else {
EXPECT_EQ(1u, origins.size());
EXPECT_EQ("http://google.com", origins[0]->origin.Serialize());
EXPECT_LE(now_before, origins[0]->last_updated_time);
EXPECT_GE(now_after_b, origins[0]->last_updated_time);
}
// The OTR service should have the same data.
EXPECT_EQ(origins, GetOriginRowsSync(otr_service()));
EXPECT_EQ(playbacks, GetPlaybackRowsSync(otr_service()));
} }
TEST_F(MediaHistoryStoreUnitTest, GetStats) { TEST_P(MediaHistoryStoreUnitTest, GetStats) {
{ {
// Check all the tables are empty. // Check all the tables are empty.
mojom::MediaHistoryStatsPtr stats = GetStatsSync(); mojom::MediaHistoryStatsPtr stats = GetStatsSync(service());
EXPECT_EQ(0, stats->table_row_counts[MediaHistoryOriginTable::kTableName]); EXPECT_EQ(0, stats->table_row_counts[MediaHistoryOriginTable::kTableName]);
EXPECT_EQ(0, EXPECT_EQ(0,
stats->table_row_counts[MediaHistoryPlaybackTable::kTableName]); stats->table_row_counts[MediaHistoryPlaybackTable::kTableName]);
...@@ -214,6 +251,9 @@ TEST_F(MediaHistoryStoreUnitTest, GetStats) { ...@@ -214,6 +251,9 @@ TEST_F(MediaHistoryStoreUnitTest, GetStats) {
EXPECT_EQ( EXPECT_EQ(
0, stats->table_row_counts[MediaHistorySessionImagesTable::kTableName]); 0, stats->table_row_counts[MediaHistorySessionImagesTable::kTableName]);
EXPECT_EQ(0, stats->table_row_counts[MediaHistoryImagesTable::kTableName]); EXPECT_EQ(0, stats->table_row_counts[MediaHistoryImagesTable::kTableName]);
// The OTR service should have the same data.
EXPECT_EQ(stats, GetStatsSync(otr_service()));
} }
{ {
...@@ -227,24 +267,49 @@ TEST_F(MediaHistoryStoreUnitTest, GetStats) { ...@@ -227,24 +267,49 @@ TEST_F(MediaHistoryStoreUnitTest, GetStats) {
{ {
// Check the tables have records in them. // Check the tables have records in them.
mojom::MediaHistoryStatsPtr stats = GetStatsSync(); mojom::MediaHistoryStatsPtr stats = GetStatsSync(service());
EXPECT_EQ(1, stats->table_row_counts[MediaHistoryOriginTable::kTableName]);
EXPECT_EQ(1, if (IsReadOnly()) {
stats->table_row_counts[MediaHistoryPlaybackTable::kTableName]); EXPECT_EQ(0,
EXPECT_EQ(0, stats->table_row_counts[MediaHistorySessionTable::kTableName]); stats->table_row_counts[MediaHistoryOriginTable::kTableName]);
EXPECT_EQ( EXPECT_EQ(0,
0, stats->table_row_counts[MediaHistorySessionImagesTable::kTableName]); stats->table_row_counts[MediaHistoryPlaybackTable::kTableName]);
EXPECT_EQ(0, stats->table_row_counts[MediaHistoryImagesTable::kTableName]); EXPECT_EQ(0,
stats->table_row_counts[MediaHistorySessionTable::kTableName]);
EXPECT_EQ(
0,
stats->table_row_counts[MediaHistorySessionImagesTable::kTableName]);
EXPECT_EQ(0,
stats->table_row_counts[MediaHistoryImagesTable::kTableName]);
} else {
EXPECT_EQ(1,
stats->table_row_counts[MediaHistoryOriginTable::kTableName]);
EXPECT_EQ(1,
stats->table_row_counts[MediaHistoryPlaybackTable::kTableName]);
EXPECT_EQ(0,
stats->table_row_counts[MediaHistorySessionTable::kTableName]);
EXPECT_EQ(
0,
stats->table_row_counts[MediaHistorySessionImagesTable::kTableName]);
EXPECT_EQ(0,
stats->table_row_counts[MediaHistoryImagesTable::kTableName]);
}
// The OTR service should have the same data.
EXPECT_EQ(stats, GetStatsSync(otr_service()));
} }
} }
TEST_F(MediaHistoryStoreUnitTest, UrlShouldBeUniqueForSessions) { TEST_P(MediaHistoryStoreUnitTest, UrlShouldBeUniqueForSessions) {
GURL url_a("https://www.google.com"); GURL url_a("https://www.google.com");
GURL url_b("https://www.example.org"); GURL url_b("https://www.example.org");
{ {
mojom::MediaHistoryStatsPtr stats = GetStatsSync(); mojom::MediaHistoryStatsPtr stats = GetStatsSync(service());
EXPECT_EQ(0, stats->table_row_counts[MediaHistorySessionTable::kTableName]); EXPECT_EQ(0, stats->table_row_counts[MediaHistorySessionTable::kTableName]);
// The OTR service should have the same data.
EXPECT_EQ(stats, GetStatsSync(otr_service()));
} }
// Save a couple of sessions on different URLs. // Save a couple of sessions on different URLs.
...@@ -256,17 +321,27 @@ TEST_F(MediaHistoryStoreUnitTest, UrlShouldBeUniqueForSessions) { ...@@ -256,17 +321,27 @@ TEST_F(MediaHistoryStoreUnitTest, UrlShouldBeUniqueForSessions) {
std::vector<media_session::MediaImage>()); std::vector<media_session::MediaImage>());
// Wait until the sessions have finished saving. // Wait until the sessions have finished saving.
content::RunAllTasksUntilIdle(); WaitForDB();
{ {
mojom::MediaHistoryStatsPtr stats = GetStatsSync(); mojom::MediaHistoryStatsPtr stats = GetStatsSync(service());
EXPECT_EQ(2, stats->table_row_counts[MediaHistorySessionTable::kTableName]);
if (IsReadOnly()) {
sql::Statement s(GetDB().GetUniqueStatement( EXPECT_EQ(0,
"SELECT id FROM playbackSession WHERE url = ?")); stats->table_row_counts[MediaHistorySessionTable::kTableName]);
s.BindString(0, url_a.spec()); } else {
ASSERT_TRUE(s.Step()); EXPECT_EQ(2,
EXPECT_EQ(1, s.ColumnInt(0)); stats->table_row_counts[MediaHistorySessionTable::kTableName]);
sql::Statement s(GetDB().GetUniqueStatement(
"SELECT id FROM playbackSession WHERE url = ?"));
s.BindString(0, url_a.spec());
ASSERT_TRUE(s.Step());
EXPECT_EQ(1, s.ColumnInt(0));
}
// The OTR service should have the same data.
EXPECT_EQ(stats, GetStatsSync(otr_service()));
} }
// Save a session on the first URL. // Save a session on the first URL.
...@@ -275,22 +350,33 @@ TEST_F(MediaHistoryStoreUnitTest, UrlShouldBeUniqueForSessions) { ...@@ -275,22 +350,33 @@ TEST_F(MediaHistoryStoreUnitTest, UrlShouldBeUniqueForSessions) {
std::vector<media_session::MediaImage>()); std::vector<media_session::MediaImage>());
// Wait until the sessions have finished saving. // Wait until the sessions have finished saving.
content::RunAllTasksUntilIdle(); WaitForDB();
{ {
mojom::MediaHistoryStatsPtr stats = GetStatsSync(); mojom::MediaHistoryStatsPtr stats = GetStatsSync(service());
EXPECT_EQ(2, stats->table_row_counts[MediaHistorySessionTable::kTableName]);
if (IsReadOnly()) {
// The row for |url_a| should have been replaced so we should have a new ID. EXPECT_EQ(0,
sql::Statement s(GetDB().GetUniqueStatement( stats->table_row_counts[MediaHistorySessionTable::kTableName]);
"SELECT id FROM playbackSession WHERE url = ?")); } else {
s.BindString(0, url_a.spec()); EXPECT_EQ(2,
ASSERT_TRUE(s.Step()); stats->table_row_counts[MediaHistorySessionTable::kTableName]);
EXPECT_EQ(3, s.ColumnInt(0));
// The OTR service should have the same data.
EXPECT_EQ(stats, GetStatsSync(otr_service()));
// The row for |url_a| should have been replaced so we should have a new
// ID.
sql::Statement s(GetDB().GetUniqueStatement(
"SELECT id FROM playbackSession WHERE url = ?"));
s.BindString(0, url_a.spec());
ASSERT_TRUE(s.Step());
EXPECT_EQ(3, s.ColumnInt(0));
}
} }
} }
TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) { TEST_P(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) {
GURL url("http://google.com/test"); GURL url("http://google.com/test");
GURL url_alt("http://example.org/test"); GURL url_alt("http://example.org/test");
...@@ -302,7 +388,7 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) { ...@@ -302,7 +388,7 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) {
url, url.GetOrigin(), base::TimeDelta::FromSeconds(30), url, url.GetOrigin(), base::TimeDelta::FromSeconds(30),
base::TimeDelta(), true /* has_video */, true /* has_audio */); base::TimeDelta(), true /* has_video */, true /* has_audio */);
service()->SavePlayback(watch_time); service()->SavePlayback(watch_time);
content::RunAllTasksUntilIdle(); WaitForDB();
} }
{ {
...@@ -311,7 +397,7 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) { ...@@ -311,7 +397,7 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) {
url, url.GetOrigin(), base::TimeDelta::FromSeconds(60), url, url.GetOrigin(), base::TimeDelta::FromSeconds(60),
base::TimeDelta(), true /* has_video */, true /* has_audio */); base::TimeDelta(), true /* has_video */, true /* has_audio */);
service()->SavePlayback(watch_time); service()->SavePlayback(watch_time);
content::RunAllTasksUntilIdle(); WaitForDB();
} }
{ {
...@@ -320,7 +406,7 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) { ...@@ -320,7 +406,7 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) {
url, url.GetOrigin(), base::TimeDelta::FromSeconds(30), url, url.GetOrigin(), base::TimeDelta::FromSeconds(30),
base::TimeDelta(), false /* has_video */, true /* has_audio */); base::TimeDelta(), false /* has_video */, true /* has_audio */);
service()->SavePlayback(watch_time); service()->SavePlayback(watch_time);
content::RunAllTasksUntilIdle(); WaitForDB();
} }
{ {
...@@ -329,7 +415,7 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) { ...@@ -329,7 +415,7 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) {
url, url.GetOrigin(), base::TimeDelta::FromSeconds(30), url, url.GetOrigin(), base::TimeDelta::FromSeconds(30),
base::TimeDelta(), true /* has_video */, false /* has_audio */); base::TimeDelta(), true /* has_video */, false /* has_audio */);
service()->SavePlayback(watch_time); service()->SavePlayback(watch_time);
content::RunAllTasksUntilIdle(); WaitForDB();
} }
const auto url_now_after = base::Time::Now().ToJsTime(); const auto url_now_after = base::Time::Now().ToJsTime();
...@@ -340,48 +426,74 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) { ...@@ -340,48 +426,74 @@ TEST_F(MediaHistoryStoreUnitTest, SavePlayback_IncrementAggregateWatchtime) {
url_alt, url_alt.GetOrigin(), base::TimeDelta::FromSeconds(30), url_alt, url_alt.GetOrigin(), base::TimeDelta::FromSeconds(30),
base::TimeDelta(), true /* has_video */, true /* has_audio */); base::TimeDelta(), true /* has_video */, true /* has_audio */);
service()->SavePlayback(watch_time); service()->SavePlayback(watch_time);
content::RunAllTasksUntilIdle(); WaitForDB();
} }
const auto url_alt_after = base::Time::Now().ToJsTime(); const auto url_alt_after = base::Time::Now().ToJsTime();
{ {
// Check the playbacks were recorded. // Check the playbacks were recorded.
mojom::MediaHistoryStatsPtr stats = GetStatsSync(); mojom::MediaHistoryStatsPtr stats = GetStatsSync(service());
EXPECT_EQ(2, stats->table_row_counts[MediaHistoryOriginTable::kTableName]);
EXPECT_EQ(5, if (IsReadOnly()) {
stats->table_row_counts[MediaHistoryPlaybackTable::kTableName]); EXPECT_EQ(0,
stats->table_row_counts[MediaHistoryOriginTable::kTableName]);
EXPECT_EQ(0,
stats->table_row_counts[MediaHistoryPlaybackTable::kTableName]);
} else {
EXPECT_EQ(2,
stats->table_row_counts[MediaHistoryOriginTable::kTableName]);
EXPECT_EQ(5,
stats->table_row_counts[MediaHistoryPlaybackTable::kTableName]);
}
// The OTR service should have the same data.
EXPECT_EQ(stats, GetStatsSync(otr_service()));
}
std::vector<mojom::MediaHistoryOriginRowPtr> origins =
GetOriginRowsSync(service());
if (IsReadOnly()) {
EXPECT_TRUE(origins.empty());
} else {
EXPECT_EQ(2u, origins.size());
EXPECT_EQ("http://google.com", origins[0]->origin.Serialize());
EXPECT_EQ(base::TimeDelta::FromSeconds(90),
origins[0]->cached_audio_video_watchtime);
EXPECT_NEAR(url_now_before, origins[0]->last_updated_time,
kTimeErrorMargin);
EXPECT_GE(url_now_after, origins[0]->last_updated_time);
EXPECT_EQ(origins[0]->cached_audio_video_watchtime,
origins[0]->actual_audio_video_watchtime);
EXPECT_EQ("http://example.org", origins[1]->origin.Serialize());
EXPECT_EQ(base::TimeDelta::FromSeconds(30),
origins[1]->cached_audio_video_watchtime);
EXPECT_NEAR(url_now_before, origins[1]->last_updated_time,
kTimeErrorMargin);
EXPECT_GE(url_alt_after, origins[1]->last_updated_time);
EXPECT_EQ(origins[1]->cached_audio_video_watchtime,
origins[1]->actual_audio_video_watchtime);
} }
std::vector<mojom::MediaHistoryOriginRowPtr> origins = GetOriginRowsSync(); // The OTR service should have the same data.
EXPECT_EQ(2u, origins.size()); EXPECT_EQ(origins, GetOriginRowsSync(otr_service()));
EXPECT_EQ("http://google.com", origins[0]->origin.Serialize());
EXPECT_EQ(base::TimeDelta::FromSeconds(90),
origins[0]->cached_audio_video_watchtime);
EXPECT_NEAR(url_now_before, origins[0]->last_updated_time, kTimeErrorMargin);
EXPECT_GE(url_now_after, origins[0]->last_updated_time);
EXPECT_EQ(origins[0]->cached_audio_video_watchtime,
origins[0]->actual_audio_video_watchtime);
EXPECT_EQ("http://example.org", origins[1]->origin.Serialize());
EXPECT_EQ(base::TimeDelta::FromSeconds(30),
origins[1]->cached_audio_video_watchtime);
EXPECT_NEAR(url_now_before, origins[1]->last_updated_time, kTimeErrorMargin);
EXPECT_GE(url_alt_after, origins[1]->last_updated_time);
EXPECT_EQ(origins[1]->cached_audio_video_watchtime,
origins[1]->actual_audio_video_watchtime);
} }
TEST_F(MediaHistoryStoreUnitTest, SaveMediaFeed_Noop) { TEST_P(MediaHistoryStoreUnitTest, SaveMediaFeed_Noop) {
service()->SaveMediaFeed(GURL("https://www.google.com/feed")); service()->SaveMediaFeed(GURL("https://www.google.com/feed"));
content::RunAllTasksUntilIdle(); WaitForDB();
{ {
// Check the feeds were not recorded. // Check the feeds were not recorded.
mojom::MediaHistoryStatsPtr stats = GetStatsSync(); mojom::MediaHistoryStatsPtr stats = GetStatsSync(service());
EXPECT_FALSE(base::Contains(stats->table_row_counts, EXPECT_FALSE(base::Contains(stats->table_row_counts,
MediaHistoryFeedsTable::kTableName)); MediaHistoryFeedsTable::kTableName));
// The OTR service should have the same data.
EXPECT_EQ(stats, GetStatsSync(otr_service()));
} }
} }
...@@ -397,32 +509,41 @@ class MediaHistoryStoreFeedsTest : public MediaHistoryStoreUnitTest { ...@@ -397,32 +509,41 @@ class MediaHistoryStoreFeedsTest : public MediaHistoryStoreUnitTest {
base::test::ScopedFeatureList features_; base::test::ScopedFeatureList features_;
}; };
TEST_F(MediaHistoryStoreFeedsTest, CreateDatabaseTables) { TEST_P(MediaHistoryStoreFeedsTest, CreateDatabaseTables) {
ASSERT_TRUE(GetDB().DoesTableExist("mediaFeed")); ASSERT_TRUE(GetDB().DoesTableExist("mediaFeed"));
} }
TEST_F(MediaHistoryStoreFeedsTest, SaveMediaFeed) { TEST_P(MediaHistoryStoreFeedsTest, SaveMediaFeed) {
GURL url_a("https://www.google.com/feed"); GURL url_a("https://www.google.com/feed");
GURL url_b("https://www.google.co.uk/feed"); GURL url_b("https://www.google.co.uk/feed");
GURL url_c("https://www.google.com/feed2"); GURL url_c("https://www.google.com/feed2");
service()->SaveMediaFeed(url_a); service()->SaveMediaFeed(url_a);
service()->SaveMediaFeed(url_b); service()->SaveMediaFeed(url_b);
content::RunAllTasksUntilIdle(); WaitForDB();
{ {
// Check the feeds were recorded. // Check the feeds were recorded.
mojom::MediaHistoryStatsPtr stats = GetStatsSync(); mojom::MediaHistoryStatsPtr stats = GetStatsSync(service());
EXPECT_EQ(2, stats->table_row_counts[MediaHistoryFeedsTable::kTableName]);
EXPECT_EQ(IsReadOnly() ? 0 : 2,
stats->table_row_counts[MediaHistoryFeedsTable::kTableName]);
// The OTR service should have the same data.
EXPECT_EQ(stats, GetStatsSync(otr_service()));
} }
service()->SaveMediaFeed(url_c); service()->SaveMediaFeed(url_c);
content::RunAllTasksUntilIdle(); WaitForDB();
{ {
// Check the feeds were recorded. // Check the feeds were recorded.
mojom::MediaHistoryStatsPtr stats = GetStatsSync(); mojom::MediaHistoryStatsPtr stats = GetStatsSync(service());
EXPECT_EQ(2, stats->table_row_counts[MediaHistoryFeedsTable::kTableName]); EXPECT_EQ(IsReadOnly() ? 0 : 2,
stats->table_row_counts[MediaHistoryFeedsTable::kTableName]);
// The OTR service should have the same data.
EXPECT_EQ(stats, GetStatsSync(otr_service()));
} }
} }
......
...@@ -3213,7 +3213,6 @@ test("unit_tests") { ...@@ -3213,7 +3213,6 @@ test("unit_tests") {
"../browser/media/android/router/media_router_android_unittest.cc", "../browser/media/android/router/media_router_android_unittest.cc",
"../browser/media/cast_mirroring_service_host_unittest.cc", "../browser/media/cast_mirroring_service_host_unittest.cc",
"../browser/media/feeds/media_feeds_service_unittest.cc", "../browser/media/feeds/media_feeds_service_unittest.cc",
"../browser/media/history/media_history_keyed_service_factory_unittest.cc",
"../browser/media/history/media_history_keyed_service_unittest.cc", "../browser/media/history/media_history_keyed_service_unittest.cc",
"../browser/media/history/media_history_store_unittest.cc", "../browser/media/history/media_history_store_unittest.cc",
"../browser/media/media_engagement_contents_observer_unittest.cc", "../browser/media/media_engagement_contents_observer_unittest.cc",
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment