SickRage/tests/test_lib.py

262 lines
7.8 KiB
Python
Raw Normal View History

# coding=UTF-8
# Author: Dennis Lutter <lad1337@gmail.com>
# URL: http://code.google.com/p/sickbeard/
#
2014-05-23 08:37:22 -04:00
# This file is part of SickRage.
#
2014-05-23 08:37:22 -04:00
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
2014-05-23 08:37:22 -04:00
# SickRage 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
2014-05-23 08:37:22 -04:00
# along with SickRage. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import unittest
import sqlite3
import sys
import os.path
from configobj import ConfigObj
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('../lib'))
import sickbeard
import shutil
2014-12-13 18:53:50 -05:00
from sickbeard import providers, tvcache
from sickbeard import db
from sickbeard.databases import mainDB
from sickbeard.databases import cache_db, failed_db
2014-12-13 18:53:50 -05:00
from sickbeard.tv import TVEpisode
#=================
# test globals
#=================
TESTDIR = os.path.abspath('.')
TESTDBNAME = "sickbeard.db"
TESTCACHEDBNAME = "cache.db"
TESTFAILEDDBNAME = "failed.db"
SHOWNAME = u"show name"
SEASON = 4
EPISODE = 2
FILENAME = u"show name - s0" + str(SEASON) + "e0" + str(EPISODE) + ".mkv"
FILEDIR = os.path.join(TESTDIR, SHOWNAME)
FILEPATH = os.path.join(FILEDIR, FILENAME)
SHOWDIR = os.path.join(TESTDIR, SHOWNAME + " final")
#=================
# prepare env functions
#=================
def createTestLogFolder():
if not os.path.isdir(sickbeard.LOG_DIR):
os.mkdir(sickbeard.LOG_DIR)
Fixed issues with editing/saving custom scene exceptions. Fixed charmap issues for anime show names. Fixed issues with display show page and epCat key errors. Fixed duplicate log messages for clearing provider caches. Fixed issues with email notifier ep names not properly being encoded to UTF-8. TVDB<->TVRAGE Indexer ID mapping is now performed on demand to be used when needed such as newznab providers can be searched with tvrage_id's and some will return tvrage_id's that later can be used to create show objects from for faster and more accurate name parsing, mapping is done via Trakt API calls. Added stop event signals to schedualed tasks, SR now waits indefinate till task has been fully stopped before completing a restart or shutdown event. NameParserCache is now persistent and stores 200 parsed results at any given time for quicker lookups and better performance, this helps maintain results between updates or shutdown/startup events. Black and White lists for anime now only get used for anime shows as intended, performance gain for non-anime shows that dont need to load these lists. Internal name cache now builds it self on demand when needed per show request plus checks if show is already in cache and if true exits routine to save time. Schedualer and QueueItems classes are now a sub-class of threading.Thread and a stop threading event signal has been added to each. If I forgot to list something it doesn't mean its not fixed so please test and report back if anything is wrong or has been corrected by this new release.
2014-07-14 22:00:53 -04:00
def createTestCacheFolder():
if not os.path.isdir(sickbeard.CACHE_DIR):
os.mkdir(sickbeard.CACHE_DIR)
# call env functions at appropriate time during sickbeard var setup
#=================
# sickbeard globals
#=================
sickbeard.SYS_ENCODING = 'UTF-8'
sickbeard.showList = []
sickbeard.QUALITY_DEFAULT = 4 # hdtv
sickbeard.FLATTEN_FOLDERS_DEFAULT = 0
sickbeard.NAMING_PATTERN = ''
sickbeard.NAMING_ABD_PATTERN = ''
sickbeard.NAMING_SPORTS_PATTERN = ''
sickbeard.NAMING_MULTI_EP = 1
sickbeard.PROVIDER_ORDER = ["sick_beard_index"]
sickbeard.newznabProviderList = providers.getNewznabProviderList("'Sick Beard Index|http://lolo.sickbeard.com/|0|5030,5040,5060|0|eponly|0!!!NZBs.org|https://nzbs.org/||5030,5040,5060,5070,5090|0|eponly|0!!!Usenet-Crawler|https://www.usenet-crawler.com/||5030,5040,5060|0|eponly|0'")
sickbeard.providerList = providers.makeProviderList()
sickbeard.PROG_DIR = os.path.abspath('..')
sickbeard.DATA_DIR = sickbeard.PROG_DIR
sickbeard.CONFIG_FILE = os.path.join(sickbeard.DATA_DIR, "config.ini")
sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE)
sickbeard.BRANCG = sickbeard.config.check_setting_str(sickbeard.CFG, 'General', 'branch', '')
sickbeard.CUR_COMMIT_HASH = sickbeard.config.check_setting_str(sickbeard.CFG, 'General', 'cur_commit_hash', '')
sickbeard.GIT_USERNAME = sickbeard.config.check_setting_str(sickbeard.CFG, 'General', 'git_username', '')
sickbeard.GIT_PASSWORD = sickbeard.config.check_setting_str(sickbeard.CFG, 'General', 'git_password', '', censor_log=True)
sickbeard.LOG_DIR = os.path.join(TESTDIR, 'Logs')
sickbeard.logger.logFile = os.path.join(sickbeard.LOG_DIR, 'test_sickbeard.log')
createTestLogFolder()
Fixed issues with editing/saving custom scene exceptions. Fixed charmap issues for anime show names. Fixed issues with display show page and epCat key errors. Fixed duplicate log messages for clearing provider caches. Fixed issues with email notifier ep names not properly being encoded to UTF-8. TVDB<->TVRAGE Indexer ID mapping is now performed on demand to be used when needed such as newznab providers can be searched with tvrage_id's and some will return tvrage_id's that later can be used to create show objects from for faster and more accurate name parsing, mapping is done via Trakt API calls. Added stop event signals to schedualed tasks, SR now waits indefinate till task has been fully stopped before completing a restart or shutdown event. NameParserCache is now persistent and stores 200 parsed results at any given time for quicker lookups and better performance, this helps maintain results between updates or shutdown/startup events. Black and White lists for anime now only get used for anime shows as intended, performance gain for non-anime shows that dont need to load these lists. Internal name cache now builds it self on demand when needed per show request plus checks if show is already in cache and if true exits routine to save time. Schedualer and QueueItems classes are now a sub-class of threading.Thread and a stop threading event signal has been added to each. If I forgot to list something it doesn't mean its not fixed so please test and report back if anything is wrong or has been corrected by this new release.
2014-07-14 22:00:53 -04:00
sickbeard.CACHE_DIR = os.path.join(TESTDIR, 'cache')
createTestCacheFolder()
sickbeard.logger.initLogging(False, True)
#=================
# dummy functions
#=================
def _dummy_saveConfig():
return True
# this overrides the sickbeard save_config which gets called during a db upgrade
# this might be considered a hack
mainDB.sickbeard.save_config = _dummy_saveConfig
# the real one tries to contact tvdb just stop it from getting more info on the ep
def _fake_specifyEP(self, season, episode):
pass
2014-12-13 18:53:50 -05:00
TVEpisode.specifyEpisode = _fake_specifyEP
#=================
# test classes
#=================
class SickbeardTestDBCase(unittest.TestCase):
def setUp(self):
sickbeard.showList = []
setUp_test_db()
setUp_test_episode_file()
setUp_test_show_dir()
def tearDown(self):
sickbeard.showList = []
tearDown_test_db()
tearDown_test_episode_file()
tearDown_test_show_dir()
class TestDBConnection(db.DBConnection, object):
def __init__(self, dbFileName=TESTDBNAME):
dbFileName = os.path.join(TESTDIR, dbFileName)
super(TestDBConnection, self).__init__(dbFileName)
class TestCacheDBConnection(TestDBConnection, object):
def __init__(self, providerName):
db.DBConnection.__init__(self, os.path.join(TESTDIR, TESTCACHEDBNAME))
# Create the table if it's not already there
try:
sql = "CREATE TABLE " + providerName + " (name TEXT, season NUMERIC, episodes TEXT, indexerid NUMERIC, url TEXT, time NUMERIC, quality TEXT);"
self.connection.execute(sql)
self.connection.commit()
except sqlite3.OperationalError, e:
if str(e) != "table " + providerName + " already exists":
raise
# Create the table if it's not already there
try:
sql = "CREATE TABLE lastUpdate (provider TEXT, time NUMERIC);"
self.connection.execute(sql)
self.connection.commit()
except sqlite3.OperationalError, e:
if str(e) != "table lastUpdate already exists":
raise
# this will override the normal db connection
sickbeard.db.DBConnection = TestDBConnection
sickbeard.tvcache.CacheDBConnection = TestCacheDBConnection
#=================
# test functions
#=================
def setUp_test_db():
"""upgrades the db to the latest version
"""
# upgrading the db
db.upgradeDatabase(db.DBConnection(), mainDB.InitialSchema)
# fix up any db problems
db.sanityCheckDatabase(db.DBConnection(), mainDB.MainSanityCheck)
# and for cachedb too
db.upgradeDatabase(db.DBConnection("cache.db"), cache_db.InitialSchema)
# and for faileddb too
db.upgradeDatabase(db.DBConnection("failed.db"), failed_db.InitialSchema)
def tearDown_test_db():
"""Deletes the test db
although this seams not to work on my system it leaves me with an zero kb file
"""
# uncomment next line so leave the db intact between test and at the end
# return False
try:
if os.path.exists(os.path.join(TESTDIR, TESTDBNAME)):
os.remove(os.path.join(TESTDIR, TESTDBNAME))
except:
pass
try:
if os.path.exists(os.path.join(TESTDIR, TESTCACHEDBNAME)):
os.remove(os.path.join(TESTDIR, TESTCACHEDBNAME))
except:
pass
try:
if os.path.exists(os.path.join(TESTDIR, TESTFAILEDDBNAME)):
os.remove(os.path.join(TESTDIR, TESTFAILEDDBNAME))
except:
pass
def setUp_test_episode_file():
if not os.path.exists(FILEDIR):
os.makedirs(FILEDIR)
try:
with open(FILEPATH, 'w') as f:
f.write("foo bar")
except EnvironmentError:
print "Unable to set up test episode"
raise
def tearDown_test_episode_file():
if os.path.exists(FILEDIR):
shutil.rmtree(FILEDIR)
def setUp_test_show_dir():
if not os.path.exists(SHOWDIR):
os.makedirs(SHOWDIR)
def tearDown_test_show_dir():
if os.path.exists(SHOWDIR):
shutil.rmtree(SHOWDIR)
tearDown_test_db()
if __name__ == '__main__':
print "=================="
print "Dont call this directly"
print "=================="
print "you might want to call"
dirList = os.listdir(TESTDIR)
for fname in dirList:
if (fname.find("_test") > 0) and (fname.find("pyc") < 0):
print "- " + fname
print "=================="
print "or just call all_tests.py"