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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
|
// Copyright (c) 2012 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.
// MediaFileSystemRegistry unit tests.
#include <algorithm>
#include <set>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "base/message_loop.h"
#include "base/stl_util.h"
#include "base/stringprintf.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/media_galleries/media_file_system_context.h"
#include "chrome/browser/media_galleries/media_file_system_registry.h"
#include "chrome/browser/media_galleries/media_galleries_preferences_factory.h"
#include "chrome/browser/media_galleries/media_galleries_test_util.h"
#include "chrome/browser/storage_monitor/media_storage_util.h"
#include "chrome/browser/storage_monitor/removable_device_constants.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
#include "chrome/browser/storage_monitor/test_storage_monitor.h"
#include "chrome/common/extensions/background_info.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/incognito_handler.h"
#include "chrome/common/extensions/manifest_handler.h"
#include "chrome/common/extensions/permissions/chrome_api_permissions.h"
#include "chrome/common/extensions/permissions/scoped_testing_permissions_info.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_process_host_factory.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/test_browser_thread.h"
#include "content/public/test/web_contents_tester.h"
#include "sync/api/string_ordinal.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_WIN)
#include "chrome/browser/storage_monitor/test_portable_device_watcher_win.h"
#include "chrome/browser/storage_monitor/test_storage_monitor_win.h"
#include "chrome/browser/storage_monitor/test_volume_mount_watcher_win.h"
#endif
namespace chrome {
// Not anonymous so it can be friends with MediaFileSystemRegistry.
class TestMediaFileSystemContext : public MediaFileSystemContext {
public:
struct FSInfo {
FSInfo() {}
FSInfo(const std::string& device_id, const base::FilePath& path,
const std::string& fsid);
bool operator<(const FSInfo& other) const;
std::string device_id;
base::FilePath path;
std::string fsid;
};
explicit TestMediaFileSystemContext(MediaFileSystemRegistry* registry);
virtual ~TestMediaFileSystemContext() {}
// MediaFileSystemContext implementation.
virtual std::string RegisterFileSystemForMassStorage(
const std::string& device_id, const base::FilePath& path) OVERRIDE;
#if defined(SUPPORT_MTP_DEVICE_FILESYSTEM)
virtual std::string RegisterFileSystemForMTPDevice(
const std::string& device_id, const base::FilePath& path,
scoped_refptr<ScopedMTPDeviceMapEntry>* entry) OVERRIDE;
#endif
virtual void RevokeFileSystem(const std::string& fsid) OVERRIDE;
virtual MediaFileSystemRegistry* GetMediaFileSystemRegistry() OVERRIDE;
base::FilePath GetPathForId(const std::string& fsid) const;
private:
std::string AddFSEntry(const std::string& device_id,
const base::FilePath& path);
MediaFileSystemRegistry* registry_;
// A counter used to construct mock FSIDs.
int fsid_;
// The currently allocated mock file systems.
std::map<std::string /*fsid*/, FSInfo> file_systems_by_id_;
};
TestMediaFileSystemContext::FSInfo::FSInfo(const std::string& device_id,
const base::FilePath& path,
const std::string& fsid)
: device_id(device_id),
path(path),
fsid(fsid) {
}
bool TestMediaFileSystemContext::FSInfo::operator<(const FSInfo& other) const {
if (device_id != other.device_id)
return device_id < other.device_id;
if (path.value() != other.path.value())
return path.value() < other.path.value();
return fsid < other.fsid;
}
TestMediaFileSystemContext::TestMediaFileSystemContext(
MediaFileSystemRegistry* registry)
: registry_(registry),
fsid_(0) {
registry_->file_system_context_.reset(this);
}
std::string TestMediaFileSystemContext::RegisterFileSystemForMassStorage(
const std::string& device_id, const base::FilePath& path) {
CHECK(MediaStorageUtil::IsMassStorageDevice(device_id));
return AddFSEntry(device_id, path);
}
#if defined(SUPPORT_MTP_DEVICE_FILESYSTEM)
std::string TestMediaFileSystemContext::RegisterFileSystemForMTPDevice(
const std::string& device_id, const base::FilePath& path,
scoped_refptr<ScopedMTPDeviceMapEntry>* entry) {
CHECK(!MediaStorageUtil::IsMassStorageDevice(device_id));
DCHECK(entry);
*entry = registry_->GetOrCreateScopedMTPDeviceMapEntry(path.value());
return AddFSEntry(device_id, path);
}
#endif
void TestMediaFileSystemContext::RevokeFileSystem(const std::string& fsid) {
if (!ContainsKey(file_systems_by_id_, fsid))
return;
EXPECT_EQ(1U, file_systems_by_id_.erase(fsid));
}
MediaFileSystemRegistry*
TestMediaFileSystemContext::GetMediaFileSystemRegistry() {
return registry_;
}
base::FilePath TestMediaFileSystemContext::GetPathForId(
const std::string& fsid) const {
std::map<std::string /*fsid*/, FSInfo>::const_iterator it =
file_systems_by_id_.find(fsid);
if (it == file_systems_by_id_.end())
return base::FilePath();
return it->second.path;
}
std::string TestMediaFileSystemContext::AddFSEntry(const std::string& device_id,
const base::FilePath& path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(path.IsAbsolute());
DCHECK(!path.ReferencesParent());
std::string fsid = base::StringPrintf("FSID:%d", ++fsid_);
FSInfo info(device_id, path, fsid);
file_systems_by_id_[fsid] = info;
return fsid;
}
namespace {
typedef std::map<MediaGalleryPrefId, MediaFileSystemInfo> FSInfoMap;
void GetGalleryInfoCallback(
FSInfoMap* results,
const std::vector<MediaFileSystemInfo>& file_systems) {
for (size_t i = 0; i < file_systems.size(); ++i) {
ASSERT_FALSE(ContainsKey(*results, file_systems[i].pref_id));
(*results)[file_systems[i].pref_id] = file_systems[i];
}
}
void CheckGalleryInfo(const MediaFileSystemInfo& info,
TestMediaFileSystemContext* fs_context,
const string16* name,
const base::FilePath& path,
bool removable,
bool media_device) {
if (name) {
EXPECT_EQ(*name, info.name);
} else {
EXPECT_EQ(path.LossyDisplayName(), info.name);
}
EXPECT_EQ(path, info.path);
EXPECT_EQ(removable, info.removable);
EXPECT_EQ(media_device, info.media_device);
EXPECT_NE(0UL, info.pref_id);
if (removable)
EXPECT_NE(0UL, info.transient_device_id.size());
else
EXPECT_EQ(0UL, info.transient_device_id.size());
base::FilePath fsid_path = fs_context->GetPathForId(info.fsid);
EXPECT_EQ(path, fsid_path);
}
class MockProfileSharedRenderProcessHostFactory
: public content::RenderProcessHostFactory {
public:
MockProfileSharedRenderProcessHostFactory() {}
virtual ~MockProfileSharedRenderProcessHostFactory();
// RPH created with this factory are owned by it. If the RPH is destroyed
// for testing purposes, it must be removed from the factory first.
content::MockRenderProcessHost* ReleaseRPH(
content::BrowserContext* browser_context);
virtual content::RenderProcessHost* CreateRenderProcessHost(
content::BrowserContext* browser_context) const OVERRIDE;
private:
typedef std::map<content::BrowserContext*, content::MockRenderProcessHost*>
ProfileRPHMap;
mutable ProfileRPHMap rph_map_;
DISALLOW_COPY_AND_ASSIGN(MockProfileSharedRenderProcessHostFactory);
};
class ProfileState {
public:
explicit ProfileState(
MockProfileSharedRenderProcessHostFactory* rph_factory);
~ProfileState();
MediaGalleriesPreferences* GetMediaGalleriesPrefs();
void CheckGalleries(
const std::string& test,
const std::vector<MediaFileSystemInfo>& regular_extension_galleries,
const std::vector<MediaFileSystemInfo>& all_extension_galleries);
FSInfoMap GetGalleriesInfo(extensions::Extension* extension);
extensions::Extension* all_permission_extension();
extensions::Extension* regular_permission_extension();
Profile* profile();
private:
void CompareResults(const std::string& test,
const std::vector<MediaFileSystemInfo>& expected,
const std::vector<MediaFileSystemInfo>& actual);
int GetAndClearComparisonCount();
int num_comparisons_;
scoped_ptr<TestingProfile> profile_;
scoped_refptr<extensions::Extension> all_permission_extension_;
scoped_refptr<extensions::Extension> regular_permission_extension_;
scoped_refptr<extensions::Extension> no_permissions_extension_;
scoped_ptr<content::WebContents> single_web_contents_;
scoped_ptr<content::WebContents> shared_web_contents1_;
scoped_ptr<content::WebContents> shared_web_contents2_;
// The RenderProcessHosts are freed when their respective WebContents /
// RenderViewHosts go away.
content::MockRenderProcessHost* single_rph_;
content::MockRenderProcessHost* shared_rph_;
DISALLOW_COPY_AND_ASSIGN(ProfileState);
};
} // namespace
class MediaFileSystemRegistryTest : public ChromeRenderViewHostTestHarness {
public:
MediaFileSystemRegistryTest();
virtual ~MediaFileSystemRegistryTest() {}
void CreateProfileState(size_t profile_count);
ProfileState* GetProfileState(size_t i);
base::FilePath empty_dir() {
return empty_dir_;
}
base::FilePath dcim_dir() {
return dcim_dir_;
}
TestMediaFileSystemContext* test_file_system_context() {
return test_file_system_context_;
}
// Create a user added gallery based on the information passed and add it to
// |profiles|. Returns the device id.
std::string AddUserGallery(MediaStorageUtil::Type type,
const std::string& unique_id,
const base::FilePath& path);
// Returns the device id.
std::string AttachDevice(MediaStorageUtil::Type type,
const std::string& unique_id,
const base::FilePath& location);
void DetachDevice(const std::string& device_id);
void SetGalleryPermission(ProfileState* profile_state,
extensions::Extension* extension,
const std::string& device_id,
bool has_access);
void AssertAllAutoAddedGalleries();
void InitForGalleriesInfoTest(FSInfoMap* galleries_info);
void CheckNewGalleryInfo(ProfileState* profile_state,
const FSInfoMap& galleries_info,
const base::FilePath& location,
bool removable,
bool media_device);
std::vector<MediaFileSystemInfo> GetAutoAddedGalleries(
ProfileState* profile_state);
// TODO(gbillock): Rework these once windows-specific code is gone.
void ProcessAttach(const std::string& id,
const string16& name,
const base::FilePath::StringType& location) {
StorageInfo info(id, name, location, string16(), string16(), string16(), 0);
StorageMonitor::GetInstance()->receiver()->ProcessAttach(info);
}
void ProcessDetach(const std::string& id) {
StorageMonitor::GetInstance()->receiver()->ProcessDetach(id);
}
MediaFileSystemRegistry* GetMediaFileSystemRegistry() {
return test_file_system_context_->GetMediaFileSystemRegistry();
}
protected:
virtual void SetUp() OVERRIDE;
virtual void TearDown() OVERRIDE;
private:
// This makes sure that at least one default gallery exists on the file
// system.
EnsureMediaDirectoriesExists media_directories_;
// Some test gallery directories.
base::ScopedTempDir galleries_dir_;
// An empty directory in |galleries_dir_|
base::FilePath empty_dir_;
// A directory in |galleries_dir_| with a DCIM directory in it.
base::FilePath dcim_dir_;
// MediaFileSystemRegistry owns this.
TestMediaFileSystemContext* test_file_system_context_;
// Needed for extension service & friends to work.
content::TestBrowserThread ui_thread_;
content::TestBrowserThread file_thread_;
extensions::ScopedTestingPermissionsInfo permissions_info_;
// TODO(gbillock): Eliminate windows-specific code from this test.
#if defined(OS_WIN)
scoped_ptr<test::TestStorageMonitorWin> monitor_;
#else
chrome::test::TestStorageMonitor monitor_;
#endif
MockProfileSharedRenderProcessHostFactory rph_factory_;
ScopedVector<ProfileState> profile_states_;
DISALLOW_COPY_AND_ASSIGN(MediaFileSystemRegistryTest);
};
namespace {
bool MediaFileSystemInfoComparator(const MediaFileSystemInfo& a,
const MediaFileSystemInfo& b) {
CHECK_NE(a.name, b.name); // Name must be unique.
return a.name < b.name;
}
///////////////////////////////////////////////
// MockProfileSharedRenderProcessHostFactory //
///////////////////////////////////////////////
MockProfileSharedRenderProcessHostFactory::
~MockProfileSharedRenderProcessHostFactory() {
STLDeleteValues(&rph_map_);
}
content::MockRenderProcessHost*
MockProfileSharedRenderProcessHostFactory::ReleaseRPH(
content::BrowserContext* browser_context) {
ProfileRPHMap::iterator existing = rph_map_.find(browser_context);
if (existing == rph_map_.end())
return NULL;
content::MockRenderProcessHost* result = existing->second;
rph_map_.erase(existing);
return result;
}
content::RenderProcessHost*
MockProfileSharedRenderProcessHostFactory::CreateRenderProcessHost(
content::BrowserContext* browser_context) const {
ProfileRPHMap::const_iterator existing = rph_map_.find(browser_context);
if (existing != rph_map_.end())
return existing->second;
rph_map_[browser_context] =
new content::MockRenderProcessHost(browser_context);
return rph_map_[browser_context];
}
//////////////////
// ProfileState //
//////////////////
ProfileState::ProfileState(
MockProfileSharedRenderProcessHostFactory* rph_factory)
: num_comparisons_(0),
profile_(new TestingProfile()) {
extensions::TestExtensionSystem* extension_system(
static_cast<extensions::TestExtensionSystem*>(
extensions::ExtensionSystem::Get(profile_.get())));
extension_system->CreateExtensionService(
CommandLine::ForCurrentProcess(), base::FilePath(), false);
std::vector<std::string> all_permissions;
all_permissions.push_back("allAutoDetected");
all_permissions.push_back("read");
std::vector<std::string> read_permissions;
read_permissions.push_back("read");
all_permission_extension_ =
AddMediaGalleriesApp("all", all_permissions, profile_.get());
regular_permission_extension_ =
AddMediaGalleriesApp("regular", read_permissions, profile_.get());
no_permissions_extension_ =
AddMediaGalleriesApp("no", read_permissions, profile_.get());
single_web_contents_.reset(
content::WebContentsTester::CreateTestWebContents(profile_.get(), NULL));
single_rph_ = rph_factory->ReleaseRPH(profile_.get());
shared_web_contents1_.reset(
content::WebContentsTester::CreateTestWebContents(profile_.get(), NULL));
shared_web_contents2_.reset(
content::WebContentsTester::CreateTestWebContents(profile_.get(), NULL));
shared_rph_ = rph_factory->ReleaseRPH(profile_.get());
}
ProfileState::~ProfileState() {
// TestExtensionSystem uses DeleteSoon, so we need to delete the profiles
// and then run the message queue to clean up. But first we have to
// delete everything that references the profile.
single_web_contents_.reset();
shared_web_contents1_.reset();
shared_web_contents2_.reset();
profile_.reset();
MessageLoop::current()->RunUntilIdle();
}
MediaGalleriesPreferences* ProfileState::GetMediaGalleriesPrefs() {
return MediaGalleriesPreferencesFactory::GetForProfile(profile_.get());
}
void ProfileState::CheckGalleries(
const std::string& test,
const std::vector<MediaFileSystemInfo>& regular_extension_galleries,
const std::vector<MediaFileSystemInfo>& all_extension_galleries) {
content::RenderViewHost* rvh = single_web_contents_->GetRenderViewHost();
MediaFileSystemRegistry* registry =
g_browser_process->media_file_system_registry();
// No Media Galleries permissions.
std::vector<MediaFileSystemInfo> empty_expectation;
registry->GetMediaFileSystemsForExtension(
rvh, no_permissions_extension_.get(),
base::Bind(&ProfileState::CompareResults, base::Unretained(this),
base::StringPrintf("%s (no permission)", test.c_str()),
base::ConstRef(empty_expectation)));
MessageLoop::current()->RunUntilIdle();
EXPECT_EQ(1, GetAndClearComparisonCount());
// Read permission only.
registry->GetMediaFileSystemsForExtension(
rvh, regular_permission_extension_.get(),
base::Bind(&ProfileState::CompareResults, base::Unretained(this),
base::StringPrintf("%s (regular permission)", test.c_str()),
base::ConstRef(regular_extension_galleries)));
MessageLoop::current()->RunUntilIdle();
EXPECT_EQ(1, GetAndClearComparisonCount());
// All galleries permission.
registry->GetMediaFileSystemsForExtension(
rvh, all_permission_extension_.get(),
base::Bind(&ProfileState::CompareResults, base::Unretained(this),
base::StringPrintf("%s (all permission)", test.c_str()),
base::ConstRef(all_extension_galleries)));
MessageLoop::current()->RunUntilIdle();
EXPECT_EQ(1, GetAndClearComparisonCount());
}
FSInfoMap ProfileState::GetGalleriesInfo(extensions::Extension* extension) {
content::RenderViewHost* rvh = single_web_contents_->GetRenderViewHost();
FSInfoMap results;
MediaFileSystemRegistry* registry =
g_browser_process->media_file_system_registry();
registry->GetMediaFileSystemsForExtension(
rvh, extension,
base::Bind(&GetGalleryInfoCallback, base::Unretained(&results)));
MessageLoop::current()->RunUntilIdle();
return results;
}
extensions::Extension* ProfileState::all_permission_extension() {
return all_permission_extension_.get();
}
extensions::Extension* ProfileState::regular_permission_extension() {
return regular_permission_extension_.get();
}
Profile* ProfileState::profile() {
return profile_.get();
}
void ProfileState::CompareResults(
const std::string& test,
const std::vector<MediaFileSystemInfo>& expected,
const std::vector<MediaFileSystemInfo>& actual) {
// Order isn't important, so sort the results. Assume that expected
// is already sorted.
std::vector<MediaFileSystemInfo> sorted(actual);
std::sort(sorted.begin(), sorted.end(), MediaFileSystemInfoComparator);
num_comparisons_++;
ASSERT_EQ(expected.size(), actual.size()) << test;
for (size_t i = 0; i < expected.size() && i < actual.size(); ++i) {
EXPECT_EQ(expected[i].path, actual[i].path) << test;
EXPECT_FALSE(actual[i].fsid.empty()) << test;
if (!expected[i].fsid.empty())
EXPECT_EQ(expected[i].fsid, actual[i].fsid) << test;
}
}
int ProfileState::GetAndClearComparisonCount() {
int result = num_comparisons_;
num_comparisons_ = 0;
return result;
}
} // namespace
/////////////////////////////////
// MediaFileSystemRegistryTest //
/////////////////////////////////
MediaFileSystemRegistryTest::MediaFileSystemRegistryTest()
: ui_thread_(content::BrowserThread::UI, MessageLoop::current()),
file_thread_(content::BrowserThread::FILE, MessageLoop::current()),
permissions_info_(extensions::ChromeAPIPermissions()) {
}
void MediaFileSystemRegistryTest::CreateProfileState(size_t profile_count) {
for (size_t i = 0; i < profile_count; ++i) {
ProfileState* state = new ProfileState(&rph_factory_);
profile_states_.push_back(state);
}
}
ProfileState* MediaFileSystemRegistryTest::GetProfileState(size_t i) {
return profile_states_[i];
}
std::string MediaFileSystemRegistryTest::AddUserGallery(
MediaStorageUtil::Type type,
const std::string& unique_id,
const base::FilePath& path) {
std::string device_id = MediaStorageUtil::MakeDeviceId(type, unique_id);
string16 name = path.LossyDisplayName();
DCHECK(!MediaStorageUtil::IsMediaDevice(device_id));
for (size_t i = 0; i < profile_states_.size(); ++i) {
profile_states_[i]->GetMediaGalleriesPrefs()->AddGalleryWithName(
device_id, name, base::FilePath(), true /*user_added*/);
}
return device_id;
}
std::string MediaFileSystemRegistryTest::AttachDevice(
MediaStorageUtil::Type type,
const std::string& unique_id,
const base::FilePath& location) {
std::string device_id = MediaStorageUtil::MakeDeviceId(type, unique_id);
DCHECK(MediaStorageUtil::IsRemovableDevice(device_id));
string16 name = location.LossyDisplayName();
ProcessAttach(device_id, name, location.value());
bool user_added = (type == MediaStorageUtil::REMOVABLE_MASS_STORAGE_NO_DCIM);
for (size_t i = 0; i < profile_states_.size(); ++i) {
profile_states_[i]->GetMediaGalleriesPrefs()->AddGalleryWithName(
device_id, name, base::FilePath(), user_added);
}
MessageLoop::current()->RunUntilIdle();
return device_id;
}
void MediaFileSystemRegistryTest::DetachDevice(const std::string& device_id) {
DCHECK(MediaStorageUtil::IsRemovableDevice(device_id));
ProcessDetach(device_id);
MessageLoop::current()->RunUntilIdle();
}
void MediaFileSystemRegistryTest::SetGalleryPermission(
ProfileState* profile_state, extensions::Extension* extension,
const std::string& device_id, bool has_access) {
MediaGalleriesPreferences* preferences =
profile_state->GetMediaGalleriesPrefs();
MediaGalleryPrefIdSet pref_id =
preferences->LookUpGalleriesByDeviceId(device_id);
ASSERT_EQ(1U, pref_id.size());
preferences->SetGalleryPermissionForExtension(*extension, *pref_id.begin(),
has_access);
}
void MediaFileSystemRegistryTest::AssertAllAutoAddedGalleries() {
for (size_t i = 0; i < profile_states_.size(); ++i) {
MediaGalleriesPreferences* prefs =
profile_states_[0]->GetMediaGalleriesPrefs();
// Make sure that we have at least one gallery and that they are all
// auto added galleries.
const MediaGalleriesPrefInfoMap& galleries = prefs->known_galleries();
#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
ASSERT_GT(galleries.size(), 0U);
#endif
for (MediaGalleriesPrefInfoMap::const_iterator it = galleries.begin();
it != galleries.end();
++it) {
ASSERT_EQ(MediaGalleryPrefInfo::kAutoDetected, it->second.type);
}
}
}
void MediaFileSystemRegistryTest::InitForGalleriesInfoTest(
FSInfoMap* galleries_info) {
CreateProfileState(1);
AssertAllAutoAddedGalleries();
// Get all existing gallery names.
ProfileState* profile_state = GetProfileState(0U);
*galleries_info = profile_state->GetGalleriesInfo(
profile_state->all_permission_extension());
#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
ASSERT_EQ(3U, galleries_info->size());
#else
ASSERT_EQ(0U, galleries_info->size());
#endif
}
void MediaFileSystemRegistryTest::CheckNewGalleryInfo(
ProfileState* profile_state,
const FSInfoMap& galleries_info,
const base::FilePath& location,
bool removable,
bool media_device) {
// Get new galleries.
FSInfoMap new_galleries_info = profile_state->GetGalleriesInfo(
profile_state->all_permission_extension());
ASSERT_EQ(galleries_info.size() + 1U, new_galleries_info.size());
bool found_new = false;
for (FSInfoMap::const_iterator it = new_galleries_info.begin();
it != new_galleries_info.end();
++it) {
if (ContainsKey(galleries_info, it->first))
continue;
ASSERT_FALSE(found_new);
CheckGalleryInfo(it->second, test_file_system_context_, NULL, location,
removable, media_device);
found_new = true;
}
ASSERT_TRUE(found_new);
}
std::vector<MediaFileSystemInfo>
MediaFileSystemRegistryTest::GetAutoAddedGalleries(
ProfileState* profile_state) {
const MediaGalleriesPrefInfoMap& galleries =
profile_state->GetMediaGalleriesPrefs()->known_galleries();
std::vector<MediaFileSystemInfo> result;
for (MediaGalleriesPrefInfoMap::const_iterator it = galleries.begin();
it != galleries.end();
++it) {
if (it->second.type == MediaGalleryPrefInfo::kAutoDetected) {
base::FilePath path = it->second.AbsolutePath();
MediaFileSystemInfo info(path.LossyDisplayName(), path, std::string(),
0, std::string(), false, false);
result.push_back(info);
}
}
std::sort(result.begin(), result.end(), MediaFileSystemInfoComparator);
return result;
}
void MediaFileSystemRegistryTest::SetUp() {
#if defined(OS_WIN)
test::TestPortableDeviceWatcherWin* portable_device_watcher =
new test::TestPortableDeviceWatcherWin;
portable_device_watcher->set_use_dummy_mtp_storage_info(true);
monitor_.reset(
new test::TestStorageMonitorWin(new test::TestVolumeMountWatcherWin,
portable_device_watcher));
monitor_->Init();
#endif
ChromeRenderViewHostTestHarness::SetUp();
DeleteContents();
SetRenderProcessHostFactory(&rph_factory_);
test_file_system_context_ = new TestMediaFileSystemContext(
g_browser_process->media_file_system_registry());
(new extensions::BackgroundManifestHandler)->Register();
(new extensions::IncognitoHandler)->Register();
ASSERT_TRUE(galleries_dir_.CreateUniqueTempDir());
empty_dir_ = galleries_dir_.path().AppendASCII("empty");
ASSERT_TRUE(file_util::CreateDirectory(empty_dir_));
dcim_dir_ = galleries_dir_.path().AppendASCII("with_dcim");
ASSERT_TRUE(file_util::CreateDirectory(dcim_dir_));
ASSERT_TRUE(file_util::CreateDirectory(dcim_dir_.Append(kDCIMDirectoryName)));
}
void MediaFileSystemRegistryTest::TearDown() {
profile_states_.clear();
ChromeRenderViewHostTestHarness::TearDown();
MediaFileSystemRegistry* registry =
g_browser_process->media_file_system_registry();
EXPECT_EQ(0U, registry->GetExtensionGalleriesHostCountForTests());
BrowserThread::GetBlockingPool()->FlushForTesting();
MessageLoop::current()->RunUntilIdle();
extensions::ManifestHandler::ClearRegistryForTesting();
}
///////////
// Tests //
///////////
TEST_F(MediaFileSystemRegistryTest, Basic) {
CreateProfileState(1);
AssertAllAutoAddedGalleries();
ProfileState* profile_state = GetProfileState(0);
std::vector<MediaFileSystemInfo> auto_galleries =
GetAutoAddedGalleries(profile_state);
std::vector<MediaFileSystemInfo> empty_expectation;
profile_state->CheckGalleries("basic", empty_expectation, auto_galleries);
}
TEST_F(MediaFileSystemRegistryTest, UserAddedGallery) {
CreateProfileState(1);
AssertAllAutoAddedGalleries();
ProfileState* profile_state = GetProfileState(0);
std::vector<MediaFileSystemInfo> auto_galleries =
GetAutoAddedGalleries(profile_state);
std::vector<MediaFileSystemInfo> added_galleries;
profile_state->CheckGalleries("user added init", added_galleries,
auto_galleries);
// Add a user gallery to the regular permission extension.
std::string device_id = AddUserGallery(MediaStorageUtil::FIXED_MASS_STORAGE,
empty_dir().AsUTF8Unsafe(),
empty_dir());
SetGalleryPermission(profile_state,
profile_state->regular_permission_extension(),
device_id,
true /*has access*/);
MediaFileSystemInfo added_info(empty_dir().LossyDisplayName(), empty_dir(),
std::string(), 0, std::string(), false, false);
added_galleries.push_back(added_info);
profile_state->CheckGalleries("user added regular", added_galleries,
auto_galleries);
// Add it to the all galleries extension.
SetGalleryPermission(profile_state,
profile_state->all_permission_extension(),
device_id,
true /*has access*/);
auto_galleries.push_back(added_info);
profile_state->CheckGalleries("user added all", added_galleries,
auto_galleries);
}
// Regression test to make sure erasing galleries does not result a crash.
TEST_F(MediaFileSystemRegistryTest, EraseGalleries) {
CreateProfileState(1);
AssertAllAutoAddedGalleries();
ProfileState* profile_state = GetProfileState(0);
std::vector<MediaFileSystemInfo> auto_galleries =
GetAutoAddedGalleries(profile_state);
std::vector<MediaFileSystemInfo> empty_expectation;
profile_state->CheckGalleries("erase", empty_expectation, auto_galleries);
MediaGalleriesPreferences* prefs = profile_state->GetMediaGalleriesPrefs();
MediaGalleriesPrefInfoMap galleries = prefs->known_galleries();
for (MediaGalleriesPrefInfoMap::const_iterator it = galleries.begin();
it != galleries.end(); ++it) {
prefs->ForgetGalleryById(it->first);
}
}
// Regression test to make sure calling GetPreferences() does not re-insert
// galleries on auto-detected removable devices that were blacklisted.
TEST_F(MediaFileSystemRegistryTest,
GetPreferencesDoesNotReinsertBlacklistedGalleries) {
CreateProfileState(1);
AssertAllAutoAddedGalleries();
ProfileState* profile_state = GetProfileState(0);
const size_t gallery_count = GetAutoAddedGalleries(profile_state).size();
// Attach a device.
const std::string device_id = AttachDevice(
MediaStorageUtil::REMOVABLE_MASS_STORAGE_WITH_DCIM,
"removable_dcim_fake_id",
dcim_dir());
EXPECT_EQ(gallery_count + 1, GetAutoAddedGalleries(profile_state).size());
// Forget the device.
bool forget_gallery = false;
MediaGalleriesPreferences* prefs =
GetMediaFileSystemRegistry()->GetPreferences(profile_state->profile());
const MediaGalleriesPrefInfoMap& galleries = prefs->known_galleries();
for (MediaGalleriesPrefInfoMap::const_iterator it = galleries.begin();
it != galleries.end(); ++it) {
if (it->second.device_id == device_id) {
prefs->ForgetGalleryById(it->first);
forget_gallery = true;
break;
}
}
EXPECT_TRUE(forget_gallery);
EXPECT_EQ(gallery_count, GetAutoAddedGalleries(profile_state).size());
// Call GetPreferences() and the gallery count should not change.
GetMediaFileSystemRegistry()->GetPreferences(profile_state->profile());
EXPECT_EQ(gallery_count, GetAutoAddedGalleries(profile_state).size());
}
TEST_F(MediaFileSystemRegistryTest, GalleryNameDefault) {
FSInfoMap galleries_info;
InitForGalleriesInfoTest(&galleries_info);
for (FSInfoMap::const_iterator it = galleries_info.begin();
it != galleries_info.end();
++it) {
CheckGalleryInfo(it->second, test_file_system_context(), &it->second.name,
it->second.path, false, false);
}
}
// TODO(gbillock): Put the platform-specific parts of this test in tests
// for those classes, not here. This test, internally, ends up creating an
// MTP delegate.
#if defined(SUPPORT_MTP_DEVICE_FILESYSTEM)
#if !defined(OS_MACOSX)
TEST_F(MediaFileSystemRegistryTest, GalleryNameMTP) {
FSInfoMap galleries_info;
InitForGalleriesInfoTest(&galleries_info);
#if defined(OS_WIN)
base::FilePath location(
PortableDeviceWatcherWin::GetStoragePathFromStorageId(
test::TestPortableDeviceWatcherWin::kStorageUniqueIdA));
#else
base::FilePath location(FILE_PATH_LITERAL("/mtp_bogus"));
#endif
AttachDevice(MediaStorageUtil::MTP_OR_PTP, "mtp_fake_id", location);
CheckNewGalleryInfo(GetProfileState(0U), galleries_info, location,
true /*removable*/, true /* media device */);
}
#endif
#endif
TEST_F(MediaFileSystemRegistryTest, GalleryNameDCIM) {
FSInfoMap galleries_info;
InitForGalleriesInfoTest(&galleries_info);
AttachDevice(MediaStorageUtil::REMOVABLE_MASS_STORAGE_WITH_DCIM,
"removable_dcim_fake_id",
dcim_dir());
CheckNewGalleryInfo(GetProfileState(0U), galleries_info, dcim_dir(),
true /*removable*/, true /* media device */);
}
TEST_F(MediaFileSystemRegistryTest, GalleryNameNoDCIM) {
FSInfoMap galleries_info;
InitForGalleriesInfoTest(&galleries_info);
std::string device_id =
AttachDevice(MediaStorageUtil::REMOVABLE_MASS_STORAGE_NO_DCIM,
empty_dir().AsUTF8Unsafe(),
empty_dir());
std::string device_id2 =
AddUserGallery(MediaStorageUtil::REMOVABLE_MASS_STORAGE_NO_DCIM,
empty_dir().AsUTF8Unsafe(),
empty_dir());
ASSERT_EQ(device_id, device_id2);
// Add permission for new non-default gallery.
ProfileState* profile_state = GetProfileState(0U);
SetGalleryPermission(profile_state,
profile_state->all_permission_extension(),
device_id,
true /*has access*/);
CheckNewGalleryInfo(profile_state, galleries_info, empty_dir(),
true /*removable*/, false /* media device */);
}
TEST_F(MediaFileSystemRegistryTest, GalleryNameUserAddedPath) {
FSInfoMap galleries_info;
InitForGalleriesInfoTest(&galleries_info);
std::string device_id = AddUserGallery(MediaStorageUtil::FIXED_MASS_STORAGE,
empty_dir().AsUTF8Unsafe(),
empty_dir());
// Add permission for new non-default gallery.
ProfileState* profile_state = GetProfileState(0U);
SetGalleryPermission(profile_state,
profile_state->all_permission_extension(),
device_id,
true /*has access*/);
CheckNewGalleryInfo(profile_state, galleries_info, empty_dir(),
false /*removable*/, false /* media device */);
}
TEST_F(MediaFileSystemRegistryTest, DetachedDeviceGalleryPath) {
const std::string device_id = AttachDevice(
MediaStorageUtil::REMOVABLE_MASS_STORAGE_WITH_DCIM,
"removable_dcim_fake_id",
dcim_dir());
MediaGalleryPrefInfo pref_info;
pref_info.device_id = device_id;
EXPECT_EQ(dcim_dir().value(), pref_info.AbsolutePath().value());
MediaGalleryPrefInfo pref_info_with_relpath;
pref_info_with_relpath.path =
base::FilePath(FILE_PATH_LITERAL("test_relpath"));
pref_info_with_relpath.device_id = device_id;
EXPECT_EQ(dcim_dir().Append(pref_info_with_relpath.path).value(),
pref_info_with_relpath.AbsolutePath().value());
DetachDevice(device_id);
EXPECT_TRUE(pref_info.AbsolutePath().empty());
EXPECT_TRUE(pref_info_with_relpath.AbsolutePath().empty());
}
} // namespace chrome
|