class test_Methodheap_MythDB_101(unittest.TestCase):
    """Test method 'getMasterBackend' from MythTV.MythDB() inherited from DBCache."""

    def setUp(self):
        self.mydb = MythDB()

    def test_Methodheap_MythDB_101_getMasterBackend_01(self):
        """Test 'getMasterBackend' method from MythTV.MythDB() inherited from DBCache.
        """

        master = self.mydb.getMasterBackend()
        #print(master, type(master))
        self.assertGreater(len(master), 0)
class test_Methodheap_MythDB_102(unittest.TestCase):
    """Test method 'getStorageGroup' from MythTV.MythDB() inherited from DBCache."""

    def setUp(self):
        self.mydb = MythDB()

    def test_Methodheap_MythDB_102_getStorageGroup_01(self):
        """Test 'getStorageGroup' method from MythTV.MythDB() inherited from DBCache.
        """

        sgroups = self.mydb.getStorageGroup(hostname = self.mydb.getMasterBackend())
        sg = next(sgroups)
        sgname = sg[u'groupname']
        #print(sgname, type(sgname))
        self.assertGreater(len(sgname), 0)
class test_Dataheap_Job_001(unittest.TestCase):
    """Test class 'Job 'dataheap'.
       This test uses hardcoded values from the file '.testenv'.
    """
    @classmethod
    def setUpClass(cls):
        # get the global test environment
        global TestEnv
        cls.testenv = TestEnv

    def setUp(self):
        with add_log_flags():
            self.mydb = MythDB()

    def tearDown(self):
        if os.path.exists('/tmp/my_logfile'):
            os.remove('/tmp/my_logfile')

    def test_Dataheap_Job_001_01(self):
        """Test classmethod Job.fromRecorded() from 'dataheap'.
        This test triggers a job to rebuild the the seek table of a recording.
        Note: I did not realized that this is possible, it is not mentioned
        in the wiki. You have to grep the source code for the flag 'JOB_REBUILD'.
        Additional note: The log does not say anything about rebuilding the seektable.
        """
        chanid = self.testenv['DOWNCHANID']
        starttimemyth = self.testenv['DOWNSTARTTIME']

        hostname = self.mydb.getMasterBackend()
        rec = Recorded((chanid, starttimemyth), db=self.mydb)
        myjob = Job.fromRecorded(rec,
                                 JOBTYPE.COMMFLAG,
                                 hostname=hostname,
                                 flags=JOBFLAG.REBUILD)

        loopnr = 0
        while (myjob.status < JOBSTATUS.FINISHED):
            time.sleep(10)
            myjob._pull()  # this re-reads the jobqueue table
            loopnr += 1
            if (loopnr > 60):
                break

        self.assertEqual(myjob.status, JOBSTATUS.FINISHED)
class test_Dataheap_Job_002(unittest.TestCase):
    """Test class 'Job 'dataheap'.
       This test uses hardcoded values from the file '.testenv'.
    """

    @classmethod
    def setUpClass(cls):
        # get the global test environment
        global TestEnv
        cls.testenv = TestEnv

    def setUp(self):
        with add_log_flags():
            self.mydb = MythDB()

    def tearDown(self):
        if os.path.exists('/tmp/my_logfile'):
            os.remove('/tmp/my_logfile')


    def test_Dataheap_Job_002_01(self):
        """Test classmethod Job.fromProgram() from 'dataheap'.
        This test triggers a job to rebuild the the seek table of program.
        Note: I did not realized that this is possible, it is not mentioned
        in the wiki:
        You have to grep the source code for the flag 'JOB_REBUILD'.
        Additional note: The log does not say anything about rebuilding the seektable.
        """
        chanid        = self.testenv['DOWNCHANID']
        starttimemyth = self.testenv['DOWNSTARTTIME']

        hostname = self.mydb.getMasterBackend()
        rec = Recorded((chanid, starttimemyth), db = self.mydb)
        prgrm = rec.getProgram()
        self.assertEqual(RECSTATUS.rsRecorded, prgrm.recstatus)

        myjob = Job.fromProgram(prgrm, JOBTYPE.COMMFLAG, hostname=hostname,
                                flags=JOBFLAG.REBUILD)

        loopnr = 0
        while (myjob.status < JOBSTATUS.FINISHED):
            time.sleep(10)
            myjob._pull()     # this re-reads the jobqueue table
            loopnr += 1
            if (loopnr > 60):
                break

        self.assertEqual(myjob.status, JOBSTATUS.FINISHED)

        # test '__repr__' and '__str__'
        print()
        print(repr(myjob))
        print(str(myjob))


    def test_Dataheap_Job_002_02(self):
        """Test exception of classmethod Job.fromProgram() from 'dataheap'.
        """
        chanid        = self.testenv['DOWNCHANID']
        starttimemyth = self.testenv['DOWNSTARTTIME']

        hostname = self.mydb.getMasterBackend()
        rec = Recorded((chanid, starttimemyth), db = self.mydb)
        prgrm = rec.getProgram()
        self.assertEqual(RECSTATUS.rsRecorded, prgrm.recstatus)

        # set recstatus to 'rsUnknown' and capture the error:
        prgrm.recstatus = RECSTATUS.rsUnknown
        with self.assertRaises(MythError):
            myjob = Job.fromProgram(prgrm, JOBTYPE.COMMFLAG,
                                    hostname=hostname, flags=JOBFLAG.REBUILD)
class test_Dataheap_Video_004(unittest.TestCase):
    """Test creation of a Video and
       writing/reading to the videocategory table.
       This test uses hardcoded values from the file '.testenv'.
    """
    @classmethod
    def setUpClass(cls):
        # get the global test environment
        global TestEnv
        cls.testenv = TestEnv

    def setUp(self):
        with add_log_flags():
            self.mydb = MythDB()

    def tearDown(self):
        if os.path.exists('/tmp/my_logfile'):
            os.remove('/tmp/my_logfile')

    def test_Dataheap_Video_004_01(self):
        """Test creation of a Video and
           writing/reading to the videocategory table.
           This test assumes, that there are no entries
           in the videocategory table! All entries in that
           table will be deleted!
        """
        class VideoCategory(DBDataWrite):
            """
            VideoCategory(data=None, db=None) --> VideoCategory object to
            database table 'videocategory', data is a `videocategory` string.

            - get information about the table:
              $ mysql -h <master-backend-ip> -u mythtv -p<password-from-config.xml> mythconverg

              MariaDB [mythconverg]> describe videocategory;
                +-------------+-------------+------+-----+---------+----------------+
                | Field       | Type        | Null | Key | Default | Extra          |
                +-------------+-------------+------+-----+---------+----------------+
                | intid       | int(10)     | NO   | PRI | NULL    | auto_increment |
                | category    | varchar(128)| NO   |     |         |                |
                +-------------+-------------+------+-----+---------+----------------+
                2 rows in set (0.00 sec)

            """
            _table = 'videocategory'
            _key = ['category']
            _defaults = {'category': ''}

            ### end class VideoCategory

        title = u"Le Dernier Métro"
        filename = title + u".mkv"

        vid = Video(db=self.mydb).create({
            'title': title,
            'filename': filename,
            'host': self.mydb.getMasterBackend()
        })

        vid.category = u"python_test"
        vid.update()

        # find this video and check it
        vids = self.mydb.searchVideos(title=title)
        vid_r = next(vids)
        # print(vid_r.category)
        self.assertEqual(vid.category, vid_r.category)
        print(repr(vid_r))
        print(str(vid_r))

        # delete the video previously created
        vid.delete()

        # delete the previously assigned category
        vid_category = VideoCategory(u"python_test", db=self.mydb)
        vid_category.delete()
class test_DBCache_001(unittest.TestCase):
    """Test settings from class 'DBCache in file 'database.py'.
       This test uses hardcoded values from the file '.testenv'.
    """
    @classmethod
    def setUpClass(cls):
        # get the global test environment
        global TestEnv
        cls.testenv = TestEnv

    def setUp(self):
        with add_log_flags():
            self.mydb = MythDB()

    def tearDown(self):
        if os.path.exists('/tmp/my_logfile'):
            os.remove('/tmp/my_logfile')

    def test_DBCache_001_01(self):
        """Get all settings from database.
           Create, read, and write a specific setting.
        """

        print("Python-Version: %d" % sys.version_info[0])

        host = self.mydb.getMasterBackend()

        # get all global settings:
        all_glob_settings = self.mydb.settings.NULL.getall()
        ip = 'blah'
        for k, v in list(all_glob_settings):
            if k == u'MasterServerIP':
                ip = v
                break
        #print(ip)   # --> '192.168.47.11'
        ipv4_valid = re.match(r'(?:\d{1,3}\.){3}\d{1,3}', ip)
        ipv6_valid = check_ipv6(ip)
        self.assertTrue(ipv4_valid or ipv6_valid)

        # get all settings from host:
        all_host_settings = self.mydb.settings[host].getall()
        setting_found = False
        for k, v in list(all_host_settings):
            if k == u'DateFormat':
                setting_found = True
                break
        #print(setting_found)
        self.assertTrue(setting_found)

        # create a setting:
        self.mydb.settings[host][u"mailTO"] = u"*****@*****.**"
        # update a setting:
        self.mydb.settings[host][u"mailTO"] = u"*****@*****.**"
        mailTo = self.mydb.settings[host][u"mailTO"]
        # check that setting
        self.assertEqual(mailTo, u"*****@*****.**")

        # delete a setting:
        del self.mydb.settings[host][u"mailTO"]

        #print(self.mydb.settings[host][u"mailTO"])  #   --> None
        self.assertIsNone(self.mydb.settings[host][u"mailTO"])
Exemple #7
0
class test_Dataheap_VideoGrabber_002(unittest.TestCase):
    """Test class 'VideoGrabber' from dataheap.
    """

    @classmethod
    def setUpClass(cls):
        # get the global test environment
        global TestEnv
        cls.testenv = TestEnv
        # moke INSTALL_PREFIX
        global INSTALL_PREFIX
        cls.INSTALL_PREFIX = INSTALL_PREFIX
        # clear 'pytmdb3.cache'
        pytmdb3_cache = os.path.expanduser('~/.mythtv/cache/pytmdb3.cache')
        if os.path.exists(pytmdb3_cache):
            os.remove(pytmdb3_cache)

    def setUp(self):
        # check INSTALL_PREFIX
        if (self.INSTALL_PREFIX != os.getcwd()):
            self.fail("Unable to rewrite 'INSTALL_PREFIX' in static.py!")

    def tearDown(self):
        if os.path.exists("/tmp/my_logfile"):
            os.remove("/tmp/my_logfile")
        if os.path.exists("/tmp/details.xml"):
            os.remove("/tmp/details.xml")

    def is_sublist(self, list1, list2):
       ls1 = [element for element in list1 if element in list2]
       ls2 = [element for element in list2 if element in list1]
       return ls1 == ls2


    def test_Dataheap_VideoGrabber_002_importMetadata_01(self):
        """Test 'VideoGrabber.grabInetref' method and 'Video.importMetadata'
           methods using predefined values. See 'mythvidexport.py' as well.
           See MythtTV trac tickets #12243 and #12245.
           Note: Use a video with French accents in title and cast.
        """
        from MythTV import MythDB, Video, VideoGrabber

        with add_log_flags():

            title      = u"Le Dernier Métro"
            castlist   = [u"Catherine Deneuve", u"Gérard Depardieu", u"Andréa Ferréol"]
            inetstr    = "tmdb3.py_1716"
            lang       = "fr"
            filename   = title + u".mkv"

            # create a new Video instance
            self.mydb = MythDB()
            vid  = Video(db=self.mydb).create ({'title'   : title,
                                                'filename': filename,
                                                'host'    : self.mydb.getMasterBackend()})
            # grab details from www.themoviedb.org
            grab = VideoGrabber('MOVIE', lang=lang, db=self.mydb)
            metadata = grab.grabInetref(inetstr)
            #print(type(metadata))   -->   <class 'MythTV.system.VideoMetadata'>
            # import metadata into Video instance
            vid.importMetadata(metadata)
            #print(vid.cast[1].cast)   ### --->  Gérard Depardieu
            # create a list of cast members from metadata
            vidcastmembers = [c.cast for c in vid.cast]
            # check for members in cast list
            self.assertTrue(self.is_sublist(castlist, vidcastmembers))
            # delete previously created Video object in database
            vid.delete()
            #print(metadata.inetref)   # --> 1716
            self.assertEqual(metadata.inetref, inetstr.split('_')[-1])
            # run the grabber again, but based on a 'VideoMetadata' object
            new_metadata = grab.grabInetref(metadata)
            # check if collected metadata are the equal
            self.assertEqual(new_metadata, metadata)

    def test_Dataheap_VideoGrabber_002_importMetadata_02(self):
        """Test 'VideoGrabber.grabInetref' method and 'Video.importMetadata'
           methods using predefined values. See 'mythvidexport.py' as well.
           See MythtTV trac tickets #12243 and #12245.
           Note: Use a TV series with season and episode.
        """
        from MythTV import MythDB, Video, VideoGrabber

        with add_log_flags():
            self.mydb =  MythDB()

            alf_metadata = { u'title'    : u'Alf',
                             u'subtitle' : u'Wedding Bell Blues',
                             u'season'   : 2,
                             u'episode'  : 4,
                             u'inetref'  : '78020'}

            grab = VideoGrabber('TV', lang='en', db=self.mydb)
            metadata = grab.grabInetref( alf_metadata['inetref'],
                                         alf_metadata['season'],
                                         alf_metadata['episode'])

            # print(metadata.collectionref)   # ---> '78020'
            self.assertEqual(metadata.collectionref, alf_metadata[u'inetref'])

            # run the grabber again, but based on a 'VideoMetadata' object
            new_metadata = grab.grabInetref(metadata)
            # check if collected metadata are the equal
            self.assertEqual(new_metadata, metadata)
class test_Dataheap_Video_005(unittest.TestCase):
    """Test creation of a Video with an existing file and host entry.
       This test uses hardcoded values from the file '.testenv'.
    """
    @classmethod
    def setUpClass(cls):
        # get the global test environment
        global TestEnv
        cls.testenv = TestEnv

    def setUp(self):
        # create a file with this name if it does not exist
        self.frtitle = self.testenv["VIDFRTITLE"]  # Le Dernier Métro"
        self.frfilename = self.testenv["VIDFRFILENAME"]
        self.frpath = self.testenv["VIDFRPATH"]
        self.frfullpath = os.path.join(self.frpath, self.frfilename)
        with add_log_flags():
            self.mydb = MythDB()
        self.master_backend_ip = self.mydb.settings['NULL']['MasterServerIP']
        shcmd = 'head -c 10M </dev/urandom > "%s"' % self.frfullpath
        cmd = "ssh mythtv@%s '%s'" % (self.master_backend_ip, shcmd)
        print(cmd)
        self.result = subprocess.call(cmd, shell=True)  # will be checked later

    def tearDown(self):
        # remove log file
        if os.path.exists('/tmp/my_logfile'):
            os.remove('/tmp/my_logfile')
        # remove temporary video file
        shcmd = 'rm "%s"' % self.frfullpath
        cmd = "ssh mythtv@%s '%s'" % (self.master_backend_ip, shcmd)
        print(cmd)
        subprocess.call(cmd, shell=True)

    def test_Dataheap_Video_005_01(self):
        """Test creation of a Video with an existing file and host entry.
        """

        # check the result of the file creation
        self.assertTrue(self.result == 0)

        host = self.mydb.getMasterBackend()

        v = Video(db=self.mydb)
        v.host = host
        v.filename = self.frfilename
        v.create({
            'title': self.frtitle,
            'filename': self.frfilename,
            'host': host
        })

        # check if hash is in hex:
        hex_set = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
            'd', 'e', 'f'
        }
        self.assertTrue(set(v.hash.lower()).issubset(hex_set))

        #remove video entry
        v.delete()