File: last_download_finder_unittest.cc

package info (click to toggle)
chromium-browser 41.0.2272.118-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 2,189,132 kB
  • sloc: cpp: 9,691,462; ansic: 3,341,451; python: 712,689; asm: 518,779; xml: 208,926; java: 169,820; sh: 119,353; perl: 68,907; makefile: 28,311; yacc: 13,305; objc: 11,385; tcl: 3,186; cs: 2,225; sql: 2,217; lex: 2,215; lisp: 1,349; pascal: 1,256; awk: 407; ruby: 155; sed: 53; php: 14; exp: 11
file content (343 lines) | stat: -rw-r--r-- 13,251 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// Copyright 2014 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/safe_browsing/incident_reporting/last_download_finder.h"

#include <string>
#include <vector>

#include "base/bind.h"
#include "base/callback.h"
#include "base/files/file_util.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/history/chrome_history_client.h"
#include "chrome/browser/history/chrome_history_client_factory.h"
#include "chrome/browser/history/download_row.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/history/web_history_service_factory.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/safe_browsing/csd.pb.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_pref_service_syncable.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/history/core/browser/history_constants.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

// A BrowserContextKeyedServiceFactory::TestingFactoryFunction that creates a
// HistoryService for a TestingProfile.
KeyedService* BuildHistoryService(content::BrowserContext* context) {
  TestingProfile* profile = static_cast<TestingProfile*>(context);

  // Delete the file before creating the service.
  base::FilePath history_path(
      profile->GetPath().Append(history::kHistoryFilename));
  if (!base::DeleteFile(history_path, false) ||
      base::PathExists(history_path)) {
    ADD_FAILURE() << "failed to delete history db file "
                  << history_path.value();
    return NULL;
  }

  HistoryService* history_service = new HistoryService(
      ChromeHistoryClientFactory::GetForProfile(profile), profile);
  if (history_service->Init(profile->GetPath()))
    return history_service;

  ADD_FAILURE() << "failed to initialize history service";
  delete history_service;
  return NULL;
}

}  // namespace

namespace safe_browsing {

class LastDownloadFinderTest : public testing::Test {
 public:
  void NeverCalled(scoped_ptr<ClientIncidentReport_DownloadDetails> download) {
    FAIL();
  }

  // Creates a new profile that participates in safe browsing and adds a
  // download to its history.
  void CreateProfileWithDownload() {
    TestingProfile* profile = CreateProfile(SAFE_BROWSING_OPT_IN);
    HistoryService* history_service =
        HistoryServiceFactory::GetForProfile(profile, Profile::EXPLICIT_ACCESS);
    history_service->CreateDownload(
        CreateTestDownloadRow(),
        base::Bind(&LastDownloadFinderTest::OnDownloadCreated,
                   base::Unretained(this)));
  }

  // LastDownloadFinder::LastDownloadCallback implementation that
  // passes the found download to |result| and then runs a closure.
  void OnLastDownload(
      scoped_ptr<ClientIncidentReport_DownloadDetails>* result,
      const base::Closure& quit_closure,
      scoped_ptr<ClientIncidentReport_DownloadDetails> download) {
    *result = download.Pass();
    quit_closure.Run();
  }

 protected:
  // A type for specifying whether or not a profile created by CreateProfile
  // participates in safe browsing.
  enum SafeBrowsingDisposition {
    SAFE_BROWSING_OPT_OUT,
    SAFE_BROWSING_OPT_IN,
  };

  LastDownloadFinderTest() : profile_number_() {}

  void SetUp() override {
    testing::Test::SetUp();
    profile_manager_.reset(
        new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
    ASSERT_TRUE(profile_manager_->SetUp());
  }

  void TearDown() override {
    // Shut down the history service on all profiles.
    std::vector<Profile*> profiles(
        profile_manager_->profile_manager()->GetLoadedProfiles());
    for (size_t i = 0; i < profiles.size(); ++i) {
      profiles[0]->AsTestingProfile()->DestroyHistoryService();
    }
    profile_manager_.reset();
    TestingBrowserProcess::DeleteInstance();
    testing::Test::TearDown();
  }

  TestingProfile* CreateProfile(SafeBrowsingDisposition safe_browsing_opt_in) {
    std::string profile_name("profile");
    profile_name.append(base::IntToString(++profile_number_));

    // Set up keyed service factories.
    TestingProfile::TestingFactories factories;
    // Build up a custom history service.
    factories.push_back(std::make_pair(HistoryServiceFactory::GetInstance(),
                                       &BuildHistoryService));
    // Suppress WebHistoryService since it makes network requests.
    factories.push_back(std::make_pair(
        WebHistoryServiceFactory::GetInstance(),
        static_cast<BrowserContextKeyedServiceFactory::TestingFactoryFunction>(
            NULL)));

    // Create prefs for the profile with safe browsing enabled or not.
    scoped_ptr<TestingPrefServiceSyncable> prefs(
        new TestingPrefServiceSyncable);
    chrome::RegisterUserProfilePrefs(prefs->registry());
    prefs->SetBoolean(prefs::kSafeBrowsingEnabled,
                      safe_browsing_opt_in == SAFE_BROWSING_OPT_IN);

    TestingProfile* profile = profile_manager_->CreateTestingProfile(
        profile_name,
        prefs.Pass(),
        base::UTF8ToUTF16(profile_name),  // user_name
        0,                                // avatar_id
        std::string(),                    // supervised_user_id
        factories);

    return profile;
  }

  LastDownloadFinder::DownloadDetailsGetter GetDownloadDetailsGetter() {
    return base::Bind(&LastDownloadFinderTest::GetDownloadDetails,
                      base::Unretained(this));
  }

  void AddDownload(Profile* profile, const history::DownloadRow& download) {
    base::RunLoop run_loop;

    HistoryService* history_service =
        HistoryServiceFactory::GetForProfile(profile, Profile::EXPLICIT_ACCESS);
    history_service->CreateDownload(
        download,
        base::Bind(&LastDownloadFinderTest::ContinueOnDownloadCreated,
                   base::Unretained(this),
                   run_loop.QuitClosure()));
    run_loop.Run();
  }

  // Wait for the history backend thread to process any outstanding tasks.
  // This is needed because HistoryService::QueryDownloads uses PostTaskAndReply
  // to do work on the backend thread and then invoke the caller's callback on
  // the originating thread. The PostTaskAndReplyRelay holds a reference to the
  // backend until its RunReplyAndSelfDestruct is called on the originating
  // thread. This reference MUST be released (on the originating thread,
  // remember) _before_ calling DestroyHistoryService in TearDown(). See the
  // giant comment in HistoryService::Cleanup explaining where the backend's
  // dtor must be run.
  void FlushHistoryBackend(Profile* profile) {
    base::RunLoop run_loop;
    HistoryServiceFactory::GetForProfile(profile, Profile::EXPLICIT_ACCESS)
        ->FlushForTest(run_loop.QuitClosure());
    run_loop.Run();
    // Then make sure anything bounced back to the main thread has been handled.
    base::RunLoop().RunUntilIdle();
  }

  // Runs the last download finder on all loaded profiles, returning the found
  // download or an empty pointer if none was found.
  scoped_ptr<ClientIncidentReport_DownloadDetails> RunLastDownloadFinder() {
    base::RunLoop run_loop;

    scoped_ptr<ClientIncidentReport_DownloadDetails> last_download;

    scoped_ptr<LastDownloadFinder> finder(LastDownloadFinder::Create(
        GetDownloadDetailsGetter(),
        base::Bind(&LastDownloadFinderTest::OnLastDownload,
                   base::Unretained(this),
                   &last_download,
                   run_loop.QuitClosure())));

    if (finder)
      run_loop.Run();

    return last_download.Pass();
  }

  history::DownloadRow CreateTestDownloadRow() {
    base::Time now(base::Time::Now());
    return history::DownloadRow(
        base::FilePath(FILE_PATH_LITERAL("spam.exe")),
        base::FilePath(FILE_PATH_LITERAL("spam.exe")),
        std::vector<GURL>(1, GURL("http://www.google.com")),  // url_chain
        GURL(),                                               // referrer
        "application/octet-stream",                           // mime_type
        "application/octet-stream",                   // original_mime_type
        now - base::TimeDelta::FromMinutes(10),       // start
        now - base::TimeDelta::FromMinutes(9),        // end
        std::string(),                                // etag
        std::string(),                                // last_modified
        47LL,                                         // received
        47LL,                                         // total
        content::DownloadItem::COMPLETE,              // download_state
        content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,  // danger_type
        content::DOWNLOAD_INTERRUPT_REASON_NONE,      // interrupt_reason,
        1,                                            // id
        false,                                        // download_opened
        std::string(),                                // ext_id
        std::string());                               // ext_name
  }

  void ExpectNoDownloadFound(
      scoped_ptr<ClientIncidentReport_DownloadDetails> download) {
    EXPECT_FALSE(download);
  }

  void ExpectFoundTestDownload(
      scoped_ptr<ClientIncidentReport_DownloadDetails> download) {
    ASSERT_TRUE(download);
  }

  content::TestBrowserThreadBundle browser_thread_bundle_;
  scoped_ptr<TestingProfileManager> profile_manager_;

 private:
  // A HistoryService::DownloadCreateCallback that asserts that the download was
  // created and runs |closure|.
  void ContinueOnDownloadCreated(const base::Closure& closure, bool created) {
    ASSERT_TRUE(created);
    closure.Run();
  }

  // A HistoryService::DownloadCreateCallback that asserts that the download was
  // created.
  void OnDownloadCreated(bool created) { ASSERT_TRUE(created); }

  void GetDownloadDetails(
      content::BrowserContext* context,
      const DownloadMetadataManager::GetDownloadDetailsCallback& callback) {
    callback.Run(scoped_ptr<ClientIncidentReport_DownloadDetails>());
  }

  int profile_number_;
};

// Tests that nothing happens if there are no profiles at all.
TEST_F(LastDownloadFinderTest, NoProfiles) {
  ExpectNoDownloadFound(RunLastDownloadFinder());
}

// Tests that nothing happens other than the callback being invoked if there are
// no profiles participating in safe browsing.
TEST_F(LastDownloadFinderTest, NoParticipatingProfiles) {
  // Create a profile with a history service that is opted-out
  TestingProfile* profile = CreateProfile(SAFE_BROWSING_OPT_OUT);

  // Add a download.
  AddDownload(profile, CreateTestDownloadRow());

  ExpectNoDownloadFound(RunLastDownloadFinder());
}

// Tests that a download is found from a single profile.
TEST_F(LastDownloadFinderTest, SimpleEndToEnd) {
  // Create a profile with a history service that is opted-in.
  TestingProfile* profile = CreateProfile(SAFE_BROWSING_OPT_IN);

  // Add a download.
  AddDownload(profile, CreateTestDownloadRow());

  ExpectFoundTestDownload(RunLastDownloadFinder());
}

// Tests that there is no crash if the finder is deleted before results arrive.
TEST_F(LastDownloadFinderTest, DeleteBeforeResults) {
  // Create a profile with a history service that is opted-in.
  TestingProfile* profile = CreateProfile(SAFE_BROWSING_OPT_IN);

  // Add a download.
  AddDownload(profile, CreateTestDownloadRow());

  // Start a finder and kill it before the search completes.
  LastDownloadFinder::Create(GetDownloadDetailsGetter(),
                             base::Bind(&LastDownloadFinderTest::NeverCalled,
                                        base::Unretained(this))).reset();

  // Flush tasks on the history backend thread.
  FlushHistoryBackend(profile);
}

// Tests that a download in profile added after the search is begun is found.
TEST_F(LastDownloadFinderTest, AddProfileAfterStarting) {
  // Create a profile with a history service that is opted-in.
  CreateProfile(SAFE_BROWSING_OPT_IN);

  scoped_ptr<ClientIncidentReport_DownloadDetails> last_download;
  base::RunLoop run_loop;

  // Post a task that will create a second profile once the main loop is run.
  base::MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&LastDownloadFinderTest::CreateProfileWithDownload,
                 base::Unretained(this)));

  // Create a finder that we expect will find a download in the second profile.
  scoped_ptr<LastDownloadFinder> finder(LastDownloadFinder::Create(
      GetDownloadDetailsGetter(),
      base::Bind(&LastDownloadFinderTest::OnLastDownload,
                 base::Unretained(this),
                 &last_download,
                 run_loop.QuitClosure())));

  run_loop.Run();

  ExpectFoundTestDownload(last_download.Pass());
}

}  // namespace safe_browsing