File: Tester.cpp

package info (click to toggle)
medialibrary 0.13.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,820 kB
  • sloc: cpp: 49,393; sql: 26,604; ansic: 3,236; sh: 46; python: 36; makefile: 4
file content (1076 lines) | stat: -rw-r--r-- 40,737 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
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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "Tester.h"

#include "common/util.h"
#include "parser/Parser.h"
#include "Thumbnail.h"
#include "File.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "utils/Directory.h"
#include "factory/DeviceListerFactory.h"
#include "medialibrary/filesystem/IFile.h"
#include "medialibrary/filesystem/IDirectory.h"
#include "medialibrary/IShow.h"
#include "medialibrary/IShowEpisode.h"
#include "medialibrary/IMediaGroup.h"
#include "medialibrary/ISubscription.h"
#include "utils/Directory.h"
#include "filesystem/libvlc/FileSystemFactory.h"

#include <algorithm>

const std::string Tests::Directory = SRC_DIR "/test/samples/";

MockCallback::MockCallback()
    : m_thumbnailDone( false )
    , m_thumbnailSuccess( false )
    , m_parserDone( false )
    , m_discoveryCompleted( false )
    , m_removalCompleted( false )
    , m_nbRootsRemovalExpected( 0 )
{
}

void MockCallback::waitForParsingComplete()
{
    std::unique_lock<compat::Mutex> lock{ m_parsingMutex };
    // Wait for a while, generating snapshots can be heavy...
    m_parsingCompleteVar.wait( lock, [this]() {
        return m_parserDone && m_discoveryCompleted;
    });
}

bool MockCallback::waitForRemovalComplete()
{
    std::unique_lock<compat::Mutex> lock{ m_parsingMutex };
    return m_parsingCompleteVar.wait_for( lock, std::chrono::seconds{ 20 }, [this]() {
        return m_removalCompleted;
    });
}

void MockCallback::reinit()
{
    std::lock_guard<compat::Mutex> lock( m_parsingMutex );
    m_discoveryCompleted = false;
    m_parserDone = false;
}

void MockCallback::prepareWaitForThumbnail( MediaPtr media )
{
    m_thumbnailMutex.lock();
    m_thumbnailDone = false;
    m_thumbnailSuccess = false;
    m_thumbnailTarget = std::move( media );
}

bool MockCallback::waitForThumbnail()
{
    std::unique_lock<compat::Mutex> lock( m_thumbnailMutex, std::adopt_lock );
    if ( m_thumbnailCond.wait_for( lock, std::chrono::seconds{ 20 }, [this]() {
            return m_thumbnailDone;
        }) == false )
        return false;
    return m_thumbnailSuccess;
}


void MockCallback::onDiscoveryStarted()
{
    std::lock_guard<compat::Mutex> lock( m_parsingMutex );
    m_discoveryCompleted = false;
}

void MockCallback::onDiscoveryCompleted()
{
    std::lock_guard<compat::Mutex> lock( m_parsingMutex );
    m_discoveryCompleted = true;
}

void MockCallback::onParsingStatsUpdated( uint32_t done, uint32_t scheduled )
{
    std::lock_guard<compat::Mutex> lock( m_parsingMutex );

    m_parserDone = done == scheduled;
}

void MockCallback::onMediaThumbnailReady( MediaPtr media, ThumbnailSizeType,
                                          bool success )
{
    std::unique_lock<compat::Mutex> lock( m_thumbnailMutex );

    if ( m_thumbnailTarget == nullptr || media->id() != m_thumbnailTarget->id() )
        return;
    m_thumbnailDone = true;
    m_thumbnailSuccess = success;
    m_thumbnailCond.notify_all();
}

void MockCallback::onRootRemoved( const std::string& root, bool )
{
    assert( root.empty() == false ); (void)root;
    std::lock_guard<compat::Mutex> lock( m_parsingMutex );
    assert( m_nbRootsRemovalExpected > 0 );
    if ( --m_nbRootsRemovalExpected > 0 )
        return;
    m_removalCompleted = true;
}

void MockCallback::onBackgroundTasksIdleChanged( bool idle )
{
    if ( idle == false )
        return;
    m_parsingCompleteVar.notify_all();
}

void MockResumeCallback::onDiscoveryCompleted()
{
    std::lock_guard<compat::Mutex> lock( m_parsingMutex );
    m_discoveryCompleted = true;
    m_discoveryCompletedVar.notify_all();
}

void MockResumeCallback::reinit()
{
    std::lock_guard<compat::Mutex> lock( m_parsingMutex );
    m_discoveryCompleted = true;
    m_parserDone = false;
}

void MockResumeCallback::waitForDiscoveryComplete()
{
    std::unique_lock<compat::Mutex> lock{ m_parsingMutex };
    m_discoveryCompletedVar.wait( lock, [this]() {
        return m_discoveryCompleted;
    });
}

void MockResumeCallback::waitForParsingComplete()
{
    std::unique_lock<compat::Mutex> lock{ m_parsingMutex };
    // Reimplement without checking for discovery complete. This class is meant to be used
    // in 2 steps: waiting for discovery completed, then for parsing completed
    assert( m_discoveryCompleted == true );
    m_parsingCompleteVar.wait( lock, [this]() {
        return m_parserDone;
    });
}

void Tests::InitTestCase( const std::string& testName )
{
    auto casePath = Directory + "testcases/" + testName + ".json";
    std::unique_ptr<FILE, int(*)(FILE*)> f( fopen( casePath.c_str(), "rb" ), &fclose );
    ASSERT_NE( nullptr, f );
    char buff[65536];
    auto ret = fread( buff, sizeof(buff[0]), sizeof(buff), f.get() );
    ASSERT_NE( 0u, ret );
    buff[ret] = 0;
    doc.Parse( buff );

    /*
     * We don't support subscriptions + regular input for now, and since
     * subscriptions don't have an associated discovery phase, we have to cheat
     * a little and force the discovery to be considered as completed.
     */
    ASSERT_TRUE( doc.HasMember( "input" ) != doc.HasMember( "subscriptions" ) );

    if ( doc.HasMember( "banned" ) == true )
    {
        const auto& banned = doc["banned"];
        for ( auto i = 0u; i < banned.Size(); ++i )
        {
            auto bannedDir = Directory + "samples/" + banned[i].GetString();
            ASSERT_TRUE( utils::fs::isDirectory( bannedDir ) );
            bannedDir = utils::fs::toAbsolute( bannedDir );
            m_ml->banFolder( utils::file::toMrl( bannedDir ) );
        }
    }

    ASSERT_TRUE( doc.HasMember( "input" ) || doc.HasMember( "subscriptions" ) );
    if ( doc.HasMember( "input" ) )
    {
        input = doc["input"];
        for ( auto i = 0u; i < input.Size(); ++i )
        {
            // Quick and dirty check to ensure we're discovering something that exists
            auto samplesDir = Directory + "samples/" + input[i].GetString();
            ASSERT_TRUE( utils::fs::isDirectory( samplesDir ) );
            samplesDir = utils::fs::toAbsolute( samplesDir );

            m_ml->discover( utils::file::toMrl( samplesDir ) );
        }
    }

    if ( doc.HasMember( "subscriptions" ) )
    {
        subscriptions = doc["subscriptions"];
        for ( auto i = 0u; i < subscriptions.Size(); ++i )
        {
            auto& sub = subscriptions[i];
            ASSERT_TRUE( sub.HasMember( "service" ) && sub.HasMember( "mrl" ) );
            addSubscription( static_cast<IService::Type>( sub["service"].GetUint() ),
                    sub["mrl"].GetString() );
        }
        m_cb->onDiscoveryCompleted();
    }
}

void Tests::SetUp( const std::string& testSuite, const std::string& testName )
{
    InitializeCallback();
    m_testDir = getTempPath( testSuite + "." + testName );
    auto dbPath = m_testDir + "/test.db";
    InitializeMediaLibrary( dbPath, m_testDir );

    auto res = m_ml->initialize( m_cb.get() );
    ASSERT_EQ( InitializeResult::Success, res );

    InitTestCase( testName );
}

void Tests::TearDown()
{
    /* Ensure we are closing our database connection before we try to delete it */
    m_ml.reset();
    ASSERT_TRUE( utils::fs::rmdir( m_testDir ) );
}

void Tests::InitializeCallback()
{
    m_cb.reset( new MockCallback );
}

namespace
{
class MediaLibraryTester : public MediaLibrary
{
    using MediaLibrary::MediaLibrary;
    virtual ~MediaLibraryTester()
    {
        stopBackgroundJobs();
    }
    virtual void onDbConnectionReady( sqlite::Connection* dbConn ) override
    {
        sqlite::Connection::DisableForeignKeyContext ctx{ m_dbConnection.get() };
        auto t = m_dbConnection->newTransaction();
        deleteAllTables( dbConn );
        t->commit();
        m_dbConnection->flushAll();
    }
};
}

void Tests::InitializeMediaLibrary( const std::string& dbPath,
                                    const std::string& mlFolderDir )

{
    m_ml.reset( new MediaLibraryTester{ dbPath, mlFolderDir } );
}

void Tests::addSubscription( IService::Type s, std::string mrl )
{
    /*
     * We need an absolute path, and we definitely can't compute it from the json
     * test case, so replace a placeholder from here.
     * The code is sprinkled with some WIN32 specific hacks because we can't use
     * the regular utils::file::toUrl which handles the backward to forward slash
     * conversions and the leading '/' that's expected by VLC from here, as the
     * util function will just overwrite the scheme, and we need the scheme to
     * force the podcast demux (ie. be 'file/podcast:///Z:/path/to/podcast.xml)
     */
    const std::string pattern = "@SAMPLES_DIR@";
    auto pos = mrl.find( pattern );
    if ( pos != std::string::npos )
    {
        auto replacement = utils::fs::toAbsolute( Directory + "/samples/" );
#ifdef _WIN32
        replacement = "/" + replacement;
#endif
        mrl.replace( pos, pattern.size(), replacement );
    }
    mrl = utils::url::encode( mrl );
#ifdef _WIN32
    std::replace( begin( mrl ), end( mrl ), '\\', '/' );
#endif
    auto service = m_ml->service( s );
    service->addSubscription( std::move( mrl ) );
}

void Tests::runChecks()
{
    if ( doc.HasMember( "expected" ) == false )
    {
        // That's a lousy test case with no assumptions, but ok.
        return;
    }
    const auto& expected = doc["expected"];

    if ( expected.HasMember( "albums" ) == true )
    {
        checkAlbums( expected["albums" ], m_ml->albums( nullptr )->all() );
    }
    if ( expected.HasMember( "media" ) == true )
        checkMedias( expected["media"] );
    if ( expected.HasMember( "nbVideos" ) == true )
    {
        const auto videos = m_ml->videoFiles( nullptr )->all();
        ASSERT_EQ( expected["nbVideos"].GetUint(), videos.size() );
    }
    if ( expected.HasMember( "nbAudios" ) == true )
    {
        const auto audios = m_ml->audioFiles( nullptr )->all();
        ASSERT_EQ( expected["nbAudios"].GetUint(), audios.size() );
    }
    if ( expected.HasMember( "nbPlaylists" ) == true )
    {
        const auto playlists = m_ml->playlists( PlaylistType::All, nullptr )->all();
        ASSERT_EQ( expected["nbPlaylists"].GetUint(), playlists.size() );
    }
    if ( expected.HasMember( "playlists" ) == true )
    {
        checkPlaylists( expected["playlists"], m_ml->playlists( PlaylistType::All,
                                                                nullptr )->all() );
    }
    if ( expected.HasMember( "artists" ) )
    {
        checkArtists( expected["artists"], m_ml->artists( ArtistIncluded::All, nullptr )->all() );
    }
    if ( expected.HasMember( "nbThumbnails" ) )
    {
        auto ml = static_cast<MediaLibrary*>( m_ml.get() );
        OPEN_READ_CONTEXT( ctx, ml->getConn() );
        sqlite::Statement stmt{
            "SELECT COUNT(*) FROM " + Thumbnail::Table::Name
        };
        uint32_t nbThumbnails;
        stmt.execute();
        auto row = stmt.row();
        row >> nbThumbnails;
        ASSERT_EQ( expected["nbThumbnails"].GetUint(), nbThumbnails );
    }
    if ( expected.HasMember( "shows" ) == true )
    {
        checkShows( expected["shows"], m_ml->shows( nullptr )->all() );
    }
    if ( expected.HasMember( "mediaGroups" ) == true )
    {
        checkMediaGroups( expected["mediaGroups"],
                m_ml->mediaGroups( IMedia::Type::Unknown, nullptr )->all() );
    }
    if ( expected.HasMember( "subscriptions" ) == true )
    {
        auto service = m_ml->service( IService::Type::Podcast );
        checkSubscriptions( expected["subscriptions"],
                service->subscriptions( nullptr )->all() );
    }
}

void Tests::checkVideoTracks( const rapidjson::Value& expectedTracks, const std::vector<VideoTrackPtr>& tracks )
{
    // There is no reliable way of discriminating between tracks, so we just assume the test case will
    // only check for simple cases... like a single track?
    ASSERT_TRUE( expectedTracks.IsArray() );
    ASSERT_EQ( expectedTracks.Size(), tracks.size() );
    for ( auto i = 0u; i < expectedTracks.Size(); ++i )
    {
        const auto& track = tracks[i];
        const auto& expectedTrack = expectedTracks[i];
        ASSERT_TRUE( expectedTrack.IsObject() );
        if ( expectedTrack.HasMember( "codec" ) )
        {
            ASSERT_EQ( strcasecmp( expectedTrack["codec"].GetString(),
                                   track->codec().c_str() ), 0 );
        }
        if ( expectedTrack.HasMember( "width" ) )
        {
            ASSERT_EQ( expectedTrack["width"].GetUint(), track->width() );
        }
        if ( expectedTrack.HasMember( "height" ) )
        {
            ASSERT_EQ( expectedTrack["height"].GetUint(), track->height() );
        }
        if ( expectedTrack.HasMember( "fps" ) )
        {
            ASSERT_EQ( expectedTrack["fps"].GetDouble(), track->fps() );
        }
    }
}

/**
 * Check if a string value occur in a string list delimited by the '|' character.
 */
static bool isInStringList( const std::string& val, const std::string& strList )
{
    static constexpr char DELIMITER = '|';
    std::istringstream input( strList );
    std::string current;
    while ( std::getline( input, current, DELIMITER ) )
        if ( current == val )
            return true;
    return false;
}

void Tests::checkAudioTracks(const rapidjson::Value& expectedTracks, const std::vector<AudioTrackPtr>& tracks)
{
    ASSERT_TRUE( expectedTracks.IsArray() );
    ASSERT_EQ( expectedTracks.Size(), tracks.size() );
    for ( auto i = 0u; i < expectedTracks.Size(); ++i )
    {
        const auto& track = tracks[i];
        const auto& expectedTrack = expectedTracks[i];
        ASSERT_TRUE( expectedTrack.IsObject() );
        if ( expectedTrack.HasMember( "codec" ) )
        {
            // XXX: There should be no need to check against a list here. Unfortunately codecs are
            // returned nonhomogeneously between libvlc3 and 4 for some mp3 audio tracks
            // exclusively.
            // TODO: This should be reverted back to a simple string check once we drop libvlc3
            // support.
            ASSERT_TRUE( isInStringList( track->codec(), expectedTrack["codec"].GetString() ) );
        }
        if ( expectedTrack.HasMember( "sampleRate" ) )
        {
            ASSERT_EQ( expectedTrack["sampleRate"].GetUint(), track->sampleRate() );
        }
        if ( expectedTrack.HasMember( "nbChannels" ) )
        {
            ASSERT_EQ( expectedTrack["nbChannels"].GetUint(), track->nbChannels() );
        }
        if ( expectedTrack.HasMember( "bitrate" ) )
        {
            ASSERT_EQ( expectedTrack["bitrate"].GetUint(), track->bitrate() );
        }
    }
}

void Tests::checkSubtitleTracks( const rapidjson::Value& expectedTracks,
                                 const std::vector<SubtitleTrackPtr>& tracks )
{
    ASSERT_TRUE( expectedTracks.IsArray() );
    ASSERT_EQ( expectedTracks.Size(), tracks.size() );
    for ( auto i = 0u; i < expectedTracks.Size(); ++i )
    {
        const auto& track = tracks[i];
        const auto& expectedTrack = expectedTracks[i];
        ASSERT_TRUE( expectedTrack.IsObject() );
        if ( expectedTrack.HasMember( "codec" ) )
        {
            ASSERT_EQ( strcasecmp( expectedTrack["codec"].GetString(),
                                   track->codec().c_str() ), 0 );
        }
        if ( expectedTrack.HasMember( "encoding" ) )
        {
            ASSERT_EQ( strcasecmp( expectedTrack["encoding"].GetString(),
                                   track->encoding().c_str() ), 0 );
        }
    }
}

void Tests::checkMediaFiles( const IMedia *media, const rapidjson::Value& expectedFiles )
{
    ASSERT_TRUE( expectedFiles.IsArray() );
    auto files = media->files();
    ASSERT_EQ( expectedFiles.Size(), files.size() );
    for ( auto i = 0u; i < expectedFiles.Size(); ++i )
    {
        const auto& expectedFile = expectedFiles[i];
        ASSERT_TRUE( expectedFile.HasMember( "filename" ) );
        auto it = std::find_if( begin( files ), end( files ), [&expectedFile]( FilePtr f ) {
            return utils::file::fileName( f->mrl() ) == expectedFile["filename"].GetString();
        });
        ASSERT_TRUE( it != end( files ) );

        if ( expectedFile.HasMember( "type" ) )
        {
            auto expectedType = expectedFile["type"].GetInt();
            ASSERT_EQ( expectedType,
                       static_cast<std::underlying_type_t<IFile::Type>>( (*it)->type() ) );
        }
        files.erase( it );
}
}

void Tests::checkSubscriptions( const rapidjson::Value& expectedSubscriptions,
                                std::vector<SubscriptionPtr> subscriptions )
{
    ASSERT_TRUE( expectedSubscriptions.IsArray() );
    for ( auto i = 0u; i < expectedSubscriptions.Size(); ++i )
    {
        const auto& expectedSubscription = expectedSubscriptions[i];
        ASSERT_TRUE( expectedSubscription.HasMember( "name" ) );
        auto it = std::find_if( begin( subscriptions ), end( subscriptions ),
                                [&expectedSubscription]( SubscriptionPtr s ) {
            return s->name() == expectedSubscription["name"].GetString();
        });
        ASSERT_TRUE( it != end( subscriptions ) );
        if ( expectedSubscription.HasMember( "nbItems" ) )
        {
            ASSERT_EQ( expectedSubscription["nbItems"].GetUint64(),
                       (*it)->media( nullptr )->count() );
        }
        subscriptions.erase( it );
    }
}

void Tests::checkMedias(const rapidjson::Value& expectedMediaList)
{
    ASSERT_TRUE( expectedMediaList.IsArray() );
    auto media_list = m_ml->audioFiles( nullptr )->all();
    auto videos = m_ml->videoFiles( nullptr )->all();
    media_list.insert( begin( media_list ), begin( videos ), end( videos ) );
    for ( auto i = 0u; i < expectedMediaList.Size(); ++i )
    {
        const auto& expectedMedia = expectedMediaList[i];
        ASSERT_TRUE( expectedMedia.HasMember( "title" ) );
        const auto expectedTitle = expectedMedia["title"].GetString();
        auto it = std::find_if( begin( media_list ), end( media_list ), [expectedTitle](const MediaPtr& m) {
            return strcasecmp( expectedTitle, m->title().c_str() ) == 0;
        });
        ASSERT_TRUE( end( media_list ) != it );
        const auto media = *it;
        media_list.erase( it );
        if ( expectedMedia.HasMember( "nbVideoTracks" ) || expectedMedia.HasMember( "videoTracks" ) )
        {
            auto videoTracks = media->videoTracks()->all();
            if ( expectedMedia.HasMember( "nbVideoTracks" ) )
            {
                ASSERT_EQ( expectedMedia[ "nbVideoTracks" ].GetUint(), videoTracks.size() );
            }
            if ( expectedMedia.HasMember( "videoTracks" ) )
            {
                checkVideoTracks( expectedMedia["videoTracks"], videoTracks );
            }
        }
        if ( expectedMedia.HasMember( "nbAudioTracks" ) || expectedMedia.HasMember( "audioTracks" ) )
        {
            auto audioTracks = media->audioTracks()->all();
            if ( expectedMedia.HasMember( "nbAudioTracks" ) )
            {
                ASSERT_EQ( expectedMedia[ "nbAudioTracks" ].GetUint(), audioTracks.size() );
            }
            if ( expectedMedia.HasMember( "audioTracks" ) )
                checkAudioTracks( expectedMedia[ "audioTracks" ], audioTracks );
        }
        if ( expectedMedia.HasMember( "nbSubtitleTracks" ) || expectedMedia.HasMember( "subtitleTracks" ) )
        {
            auto subtitleTracks = media->subtitleTracks()->all();
            if ( expectedMedia.HasMember( "nbSubtitleTracks" ) )
            {
                ASSERT_EQ( expectedMedia[ "nbSubtitleTracks" ].GetUint(), subtitleTracks.size() );
            }
            if ( expectedMedia.HasMember( "subtitleTracks" ) )
                checkSubtitleTracks( expectedMedia[ "subtitleTracks" ], subtitleTracks );
        }
        if ( expectedMedia.HasMember( "snapshotExpected" ) == true )
        {
            auto snapshotExpected = expectedMedia["snapshotExpected"].GetBool();
            if ( snapshotExpected && media->thumbnailMrl( ThumbnailSizeType::Thumbnail ).empty() == true )
            {
                m_cb->prepareWaitForThumbnail( media );
                media->requestThumbnail( ThumbnailSizeType::Thumbnail, 320, 200, .3f );
                auto res = m_cb->waitForThumbnail();
                ASSERT_TRUE( res );
            }
            ASSERT_EQ( !snapshotExpected, media->thumbnailMrl( ThumbnailSizeType::Thumbnail ).empty() );
        }
        if ( expectedMedia.HasMember( "files" ) )
        {
            checkMediaFiles( media.get(), expectedMedia["files"] );
        }
    }
}

void Tests::checkPlaylists( const rapidjson::Value& expectedPlaylists, std::vector<PlaylistPtr> playlists )
{
    ASSERT_TRUE( expectedPlaylists.IsArray() );
    for ( auto i = 0u; i < expectedPlaylists.Size(); ++i )
    {
        const auto& expectedPlaylist = expectedPlaylists[i];
        ASSERT_TRUE( expectedPlaylist.HasMember( "name" ) );
        const auto expectedName = expectedPlaylist["name"].GetString();
        auto it = std::find_if( begin( playlists ), end( playlists ), [expectedName](const PlaylistPtr& p) {
            return strcasecmp( expectedName, p->name().c_str() ) == 0;
        });
        ASSERT_TRUE( end( playlists ) != it );

        const auto playlist = *it;
        playlists.erase( it );
        const auto& items = playlist->media( nullptr )->all();

        ASSERT_TRUE( playlist->isReadOnly() );
        ASSERT_FALSE( playlist->mrl().empty() );

        if ( expectedPlaylist.HasMember( "nbItems" ) )
        {
            ASSERT_EQ( expectedPlaylist["nbItems"].GetUint(), items.size() );
        }
        if ( expectedPlaylist.HasMember( "nbAudio" ) )
        {
            ASSERT_EQ( expectedPlaylist["nbAudio"].GetUint(), playlist->nbAudio() );
        }
        if ( expectedPlaylist.HasMember( "nbDurationUnknown" ) )
        {
            ASSERT_EQ( expectedPlaylist["nbDurationUnknown"].GetUint(),
                    playlist->nbDurationUnknown() );
        }

        if ( expectedPlaylist.HasMember( "items" ) )
        {
            ASSERT_TRUE( expectedPlaylist["items"].IsArray() );
            ASSERT_EQ( items.size(), expectedPlaylist["items"].Size() );
            for ( auto j = 0u; j < items.size(); ++j )
            {
                if ( expectedPlaylist["items"][j].HasMember( "index" ) )
                {
                    ASSERT_EQ( expectedPlaylist["items"][j]["index"].GetUint(), j );
                }
                if ( expectedPlaylist["items"][j].HasMember( "title" ) )
                {
                    ASSERT_EQ( expectedPlaylist["items"][j]["title"].GetString(), items[j]->title() );
                }
                if ( expectedPlaylist["items"][j].HasMember( "mrl" ) )
                {
                    auto files = items[j]->files();
                    auto mainFileIt = std::find_if( cbegin( files ), cend( files ),
                        [](const FilePtr& f ) {
                            return f->isMain() == true;
                    });
                    ASSERT_TRUE( mainFileIt != cend( files ) );
                    ASSERT_EQ( expectedPlaylist["items"][j]["mrl"].GetString(),
                            (*mainFileIt)->mrl() );
                }
            }
        }
    }
}

void Tests::checkAlbums( const rapidjson::Value& expectedAlbums, std::vector<AlbumPtr> albums )
{
    ASSERT_TRUE( expectedAlbums.IsArray() );
    ASSERT_EQ( expectedAlbums.Size(), albums.size() );
    for ( auto i = 0u; i < expectedAlbums.Size(); ++i )
    {
        const auto& expectedAlbum = expectedAlbums[i];
        ASSERT_TRUE( expectedAlbum.HasMember( "title" ) );
        // Start by checking if the album was found
        auto it = std::find_if( begin( albums ), end( albums ), [this, &expectedAlbum](const AlbumPtr& a) {
            const auto expectedTitle = expectedAlbum["title"].GetString();
            if ( strcasecmp( a->title().c_str(), expectedTitle ) != 0 )
                return false;
            if ( expectedAlbum.HasMember( "artist" ) )
            {
                const auto expectedArtist = expectedAlbum["artist"].GetString();
                auto artist = a->albumArtist();
                if ( artist != nullptr && strcasecmp( artist->name().c_str(), expectedArtist ) != 0 )
                    return false;
            }
            if ( expectedAlbum.HasMember( "artists" ) )
            {
                const auto& expectedArtists = expectedAlbum["artists"];
                auto artists = a->artists( nullptr )->all();
                if ( expectedArtists.Size() != artists.size() )
                    return false;
                for ( auto i = 0u; i < expectedArtists.Size(); ++i )
                {
                    auto expectedArtist = expectedArtists[i].GetString();
                    auto it = std::find_if( begin( artists ), end( artists), [expectedArtist](const ArtistPtr& a) {
                        return strcasecmp( expectedArtist, a->name().c_str() ) == 0;
                    });
                    if ( it == end( artists ) )
                        return false;
                }
            }
            if ( expectedAlbum.HasMember( "hasArtwork" ) )
            {
                if ( expectedAlbum["hasArtwork"].GetBool() ==
                     a->thumbnailMrl( ThumbnailSizeType::Thumbnail ).empty() ||
                     a->thumbnailMrl( ThumbnailSizeType::Thumbnail )
                        .compare( 0, 13, "attachment://") == 0 )
                    return false;
            }
            if ( expectedAlbum.HasMember( "nbTracks" ) || expectedAlbum.HasMember( "tracks" ) )
            {
                const auto tracks = a->tracks( nullptr )->all();
                if ( expectedAlbum.HasMember( "nbTracks" ) )
                {
                    if ( expectedAlbum["nbTracks"].GetUint() != tracks.size() )
                        return false;
                }
                if ( expectedAlbum.HasMember( "tracks" ) )
                {
                    bool tracksOk = false;
                    checkAlbumTracks( a.get(), tracks, expectedAlbum["tracks"], tracksOk );
                    if ( tracksOk == false )
                        return false;
                }
            }
            if ( expectedAlbum.HasMember( "releaseYear" ) )
            {
                const auto releaseYear = expectedAlbum["releaseYear"].GetUint();
                if ( a->releaseYear() != releaseYear )
                    return false;
            }
            if ( expectedAlbum.HasMember( "nbDiscs" ) )
            {
                const auto nbDiscs = expectedAlbum["nbDiscs"].GetUint();
                if ( a->nbDiscs() != nbDiscs )
                    return false;
            }
            return true;
        });
        ASSERT_TRUE( end( albums ) != it );
        albums.erase( it );
    }
}

void Tests::checkArtists(const rapidjson::Value& expectedArtists, std::vector<ArtistPtr> artists)
{
    ASSERT_TRUE( expectedArtists.IsArray() );
    ASSERT_EQ( expectedArtists.Size(), artists.size() );
    for ( auto i = 0u; i < expectedArtists.Size(); ++i )
    {
        const auto& expectedArtist = expectedArtists[i];
        auto it = std::find_if( begin( artists ), end( artists ), [&expectedArtist, this](const ArtistPtr& artist) {
            if ( expectedArtist.HasMember( "name" ) )
            {
                if ( strcasecmp( expectedArtist["name"].GetString(), artist->name().c_str() ) != 0 )
                    return false;
            }
            if ( expectedArtist.HasMember( "id" ) )
            {
                if ( expectedArtist["id"].GetUint() != artist->id() )
                    return false;
            }
            if ( expectedArtist.HasMember( "nbAlbums" ) )
            {
                if ( artist->nbAlbums() != expectedArtist["nbAlbums"].GetUint() )
                    return false;
            }
            if ( expectedArtist.HasMember( "albums" ) )
            {
                auto albums = artist->albums( nullptr )->all();
                checkAlbums( expectedArtist["albums"], albums );
            }
            if ( expectedArtist.HasMember( "nbTracks" ) )
            {
                auto expectedNbTracks = expectedArtist["nbTracks"].GetUint();
                auto tracks = artist->tracks( nullptr )->all();
                if ( expectedNbTracks != tracks.size() )
                    return false;
                if ( expectedNbTracks != artist->nbTracks() )
                    return false;
            }
            if ( expectedArtist.HasMember( "hasArtwork" ) )
            {
                auto artwork = artist->thumbnailMrl( ThumbnailSizeType::Thumbnail );
                if ( artwork.empty() == expectedArtist["hasArtwork"].GetBool() ||
                     artwork.compare( 0, 13, "attachment://" ) == 0 )
                    return false;
            }
            return true;
        });
        ASSERT_TRUE( it != end( artists ) );
    }
}

void Tests::checkAlbumTracks( const IAlbum* album, const std::vector<MediaPtr>& tracks, const rapidjson::Value& expectedTracks, bool& found ) const
{
    found = false;
    // Don't mandate all tracks to be defined
    for ( auto i = 0u; i < expectedTracks.Size(); ++i )
    {
        const auto& expectedTrack = expectedTracks[i];
        ASSERT_TRUE( expectedTrack.HasMember( "title" ) );
        auto expectedTitle = expectedTrack["title"].GetString();
        auto it = std::find_if( begin( tracks ), end( tracks ), [expectedTitle](const MediaPtr& media) {
            return strcasecmp( expectedTitle, media->title().c_str() ) == 0;
        });
        if ( it == end( tracks ) )
            return ;
        const auto track = *it;
        ASSERT_NE( nullptr, track );
        if ( expectedTrack.HasMember( "number" ) )
        {
            if ( expectedTrack["number"].GetUint() != track->trackNumber() )
                return ;
        }
        if ( expectedTrack.HasMember( "artist" ) )
        {
            auto artist = track->artist();
            if ( artist == nullptr )
                return ;
            if ( strlen( expectedTrack["artist"].GetString() ) == 0 &&
                 artist->id() != UnknownArtistID )
                return ;
            else if ( strcasecmp( expectedTrack["artist"].GetString(), artist->name().c_str() ) != 0 )
                return ;
        }
        if ( expectedTrack.HasMember( "genre" ) )
        {
            auto genre = track->genre();
            if ( genre == nullptr || strcasecmp( expectedTrack["genre"].GetString(), genre->name().c_str() ) != 0 )
                return ;
        }
        if ( expectedTrack.HasMember( "releaseYear" ) )
        {
            auto releaseDate = track->releaseDate();
            unsigned int releaseYear = 0;
            if ( releaseDate != 0 )
            {
                struct tm t{};
                gmtime_r(&releaseDate, &t);
                releaseYear = t.tm_year + 1900u;
            }
            if ( releaseYear != expectedTrack["releaseYear"].GetUint() )
                return;
        }
        if ( expectedTrack.HasMember( "cd" ) )
        {
            if ( expectedTrack["cd"].GetUint() != track->discNumber() )
                return;
        }
        if ( expectedTrack.HasMember( "hasArtwork" ) )
        {
            ASSERT_EQ( expectedTrack["hasArtwork"].GetBool(),
                       track->thumbnailMrl( ThumbnailSizeType::Thumbnail ).empty() == false );
            ASSERT_TRUE( track->thumbnailMrl( ThumbnailSizeType::Thumbnail )
                                    .compare(0, 13, "attachment://") != 0 );
        }
        // Always check if the album link is correct. This isn't part of finding the proper album, so just fail hard
        // if the check fails.
        const auto trackAlbum = track->album();
        ASSERT_NE( nullptr, trackAlbum );
        ASSERT_EQ( album->id(), trackAlbum->id() );
    }
    found = true;
}

void Tests::checkShows(const rapidjson::Value& expectedShows, std::vector<ShowPtr> shows)
{
    for ( auto i = 0u; i < expectedShows.Size(); ++i )
    {
        auto& expectedShow = expectedShows[i];
        ASSERT_TRUE( expectedShow.HasMember( "name" ) );
        auto showName = expectedShow["name"].GetString();
        auto showIt = std::find_if( cbegin( shows ), cend( shows ),
                                  [showName]( const ShowPtr& s ) {
            if ( strlen( showName ) == 0 )
                return s->id() == UnknownShowID;
            return s->title() == showName;
        });
        ASSERT_TRUE( showIt != cend( shows ) );
        auto show = *showIt;
        if ( expectedShow.HasMember( "nbEpisodes" ) == true )
        {
            ASSERT_EQ( expectedShow["nbEpisodes"].GetUint(), show->nbEpisodes() );
        }
        if ( expectedShow.HasMember( "episodes" ) == true )
        {
            auto episodes = show->episodes( nullptr )->all();
            ASSERT_FALSE( episodes.empty() );
            checkShowEpisodes( expectedShow["episodes"], std::move( episodes ) );
        }
    }
}

void Tests::checkShowEpisodes( const rapidjson::Value& expectedEpisodes,
                               std::vector<MediaPtr> episodes )
{
    for ( auto i = 0u; i < expectedEpisodes.Size(); ++i )
    {
        auto& expectedEpisode = expectedEpisodes[i];
        ASSERT_TRUE( expectedEpisode.HasMember( "seasonId" ) );
        ASSERT_TRUE( expectedEpisode.HasMember( "episodeId" ) );
        auto seasonId = expectedEpisode["seasonId"].GetUint();
        auto episodeId = expectedEpisode["episodeId"].GetUint();
        auto episodeIt = std::find_if( cbegin( episodes ), cend( episodes ),
                                       [seasonId, episodeId](const MediaPtr m) {
            auto showEp = m->showEpisode();
            if ( showEp == nullptr )
                return false;
            return showEp->seasonId() == seasonId && showEp->episodeId() == episodeId;
        });
        ASSERT_TRUE( episodeIt != cend( episodes ) );
        auto media = *episodeIt;
        auto showEp = media->showEpisode();
        if ( expectedEpisode.HasMember( "title" ) == true )
        {
            ASSERT_EQ( expectedEpisode["title"].GetString(), showEp->title() );
        }
        if ( expectedEpisode.HasMember( "mediaTitle" ) == true )
        {
            ASSERT_EQ( expectedEpisode["mediaTitle"].GetString(), media->title() );
        }
    }
}

void Tests::checkMediaGroups( const rapidjson::Value &expectedMediaGroups,
                              std::vector<MediaGroupPtr> mediaGroups)
{
    ASSERT_EQ( expectedMediaGroups.Size(), mediaGroups.size() );
    for ( auto i = 0u; i < expectedMediaGroups.Size(); ++i )
    {
        auto& expectedGroup = expectedMediaGroups[i];
        ASSERT_TRUE( expectedGroup.HasMember( "name" ) );
        auto it = std::find_if( cbegin( mediaGroups ), cend( mediaGroups ),
                                [&expectedGroup]( const MediaGroupPtr grp ) {
            return strcasecmp( grp->name().c_str(), expectedGroup["name"].GetString() ) == 0;
        });
        ASSERT_TRUE( cend( mediaGroups ) != it );
        auto group = *it;
        if ( expectedGroup.HasMember( "nbAudio" ) )
        {
            ASSERT_EQ( expectedGroup["nbAudio"].GetUint(), group->nbPresentAudio() );
        }
        if ( expectedGroup.HasMember( "nbVideo" ) )
        {
            ASSERT_EQ( expectedGroup["nbVideo"].GetUint(), group->nbPresentVideo() );
        }
        if ( expectedGroup.HasMember( "nbUnknown" ) )
        {
            ASSERT_EQ( expectedGroup["nbUnknown"].GetUint(), group->nbPresentUnknown() );
        }
    }
}

void ResumeTests::InitializeMediaLibrary( const std::string& dbPath,
                                          const std::string& mlFolderDir )
{
    m_ml.reset( new MediaLibraryResumeTest( dbPath, mlFolderDir ) );
}

void ResumeTests::InitializeCallback()
{
    m_cb.reset( new MockResumeCallback );
}

MediaLibraryResumeTest::~MediaLibraryResumeTest()
{
    stopBackgroundJobs();
}

void MediaLibraryResumeTest::forceParserStart()
{
    m_allowParser = true;
    getParser()->start();
}

void MediaLibraryResumeTest::onDbConnectionReady( sqlite::Connection *dbConn )
{
    sqlite::Connection::DisableForeignKeyContext ctx{ m_dbConnection.get() };
    auto t = m_dbConnection->newTransaction();
    deleteAllTables( dbConn );
    t->commit();
    m_dbConnection->flushAll();
}

parser::Parser* MediaLibraryResumeTest::getParser() const
{
    if ( m_allowParser == false )
        return nullptr;
    return MediaLibrary::getParser();
}

void RefreshTests::forceRefresh()
{
    auto ml = static_cast<MediaLibrary*>( m_ml.get() );
    auto files = medialibrary::File::fetchAll( ml );
    for ( auto& f : files )
    {
        if ( f->isExternal() == true )
            continue;
        auto mrl = f->mrl();
        auto folder = Folder::fetch( ml, f->folderId() );
        auto fsFactory = ml->fsFactoryForMrl( mrl );
        auto folderMrl = utils::file::directory( mrl );
        auto fileName = utils::file::fileName( mrl );
        auto folderFs = fsFactory->createDirectory( folderMrl );
        auto filesFs = folderFs->files();
        auto fileFsIt = std::find_if( cbegin( filesFs ), cend( filesFs ),
            [&fileName]( const std::shared_ptr<fs::IFile> f ) {
                return f->name() == fileName;
            });
        assert( fileFsIt != cend( filesFs ) );
        ml->onUpdatedFile( std::move( f ), *fileFsIt, std::move( folder ), std::move( folderFs ) );
    }
    auto service = m_ml->service( IService::Type::Podcast );
    auto subscriptions = service->subscriptions( nullptr )->all();
    for ( auto& s : subscriptions )
        s->refresh();
}

void RefreshTests::InitializeCallback()
{
    m_cb.reset( new MockResumeCallback );
}

void MockCallback::prepareForPlaylistReload()
{
    // We need to force the discover to appear as complete, as we won't do any
    // discovery for this test. Otherwise, we'd receive the parsing completed
    // event and just ignore it.
    std::lock_guard<compat::Mutex> lock{ m_parsingMutex };
    m_discoveryCompleted = true;
    m_parserDone = false;
}

void MockCallback::waitForPlaylistReload()
{
    std::unique_lock<compat::Mutex> lock{ m_parsingMutex };
    // Wait for a while, generating snapshots can be heavy...
    m_parsingCompleteVar.wait( lock, [this]() {
        return m_parserDone;
    });
}

void MockCallback::prepareForRemoval( uint32_t nbRootsRemovalExpected )
{
    std::lock_guard<compat::Mutex> lock{ m_parsingMutex };
    m_nbRootsRemovalExpected = nbRootsRemovalExpected;
    m_removalCompleted = false;
}

void ReplaceExternalMediaByPlaylistTests::InitTestCase( const std::string& )
{
    /*
     * This test is about recovering from a playlist wrongly inserted as an
     * external media, which can happen if the user starts an unimported
     * playlist playback, only to discover the folder containing the playlist at
     * a later time.
     * After the initial playback, VLC will create an external media to save the
     * playback states & preferences.
     * When the playlist should be imported, there's already a file representing
     * that playlist so it fails to get imported.
     * See #400
     */
    auto playlistPath = utils::fs::toAbsolute( SRC_DIR );
    playlistPath += "test/samples/samples/playlist/mixed_content/playlist.xspf";
    playlistMrl = utils::file::toMrl( playlistPath );
    m_ml->addExternalMedia( playlistMrl, -1 );
    Tests::InitTestCase( "playlist_mixed_content" );
}