From 27a123c688e85adbae03bab2369e6282d9aca5c5 Mon Sep 17 00:00:00 2001 From: Safihre Date: Tue, 26 Feb 2019 08:15:24 +0100 Subject: [PATCH] Py3: Code-format tests-files --- tests/__init__.py | 2 +- tests/conftest.py | 20 +++++++++------ tests/test_encoding.py | 1 - tests/test_filesystem.py | 2 +- tests/test_functional_config.py | 50 ++++++++++++++++++-------------------- tests/test_functional_downloads.py | 22 +++++++++-------- tests/test_misc.py | 8 +++--- tests/testhelper.py | 50 ++++++++++++++++++++------------------ 8 files changed, 82 insertions(+), 73 deletions(-) diff --git a/tests/__init__.py b/tests/__init__.py index 54166df..94ba3ec 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1 +1 @@ -# Needed for correct test-detection \ No newline at end of file +# Needed for correct test-detection diff --git a/tests/conftest.py b/tests/conftest.py index cfd7372..a1d0aa5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -34,20 +34,26 @@ def start_sabnzbd(): # Copy basic config file with API key os.mkdir(SAB_CACHE_DIR) - shutil.copyfile(os.path.join(SAB_BASE_DIR, 'sabnzbd.basic.ini'), os.path.join(SAB_CACHE_DIR, 'sabnzbd.ini')) + shutil.copyfile(os.path.join(SAB_BASE_DIR, "sabnzbd.basic.ini"), os.path.join(SAB_CACHE_DIR, "sabnzbd.ini")) # Check if we have language files - if not os.path.exists(os.path.join(SAB_BASE_DIR, '..', 'locale')): + if not os.path.exists(os.path.join(SAB_BASE_DIR, "..", "locale")): # Compile and wait to complete - lang_command = '%s %s/../tools/make_mo.py' % (sys.executable, SAB_BASE_DIR) + lang_command = "%s %s/../tools/make_mo.py" % (sys.executable, SAB_BASE_DIR) subprocess.Popen(lang_command.split()).communicate(timeout=30) # Check if it exists now, fail otherwise - if not os.path.exists(os.path.join(SAB_BASE_DIR, '..', 'locale')): - raise FileNotFoundError('Failed to compile language files') + if not os.path.exists(os.path.join(SAB_BASE_DIR, "..", "locale")): + raise FileNotFoundError("Failed to compile language files") # Start SABnzbd and continue - sab_command = '%s %s/../SABnzbd.py --new -l2 -s %s:%s -b0 -f %s' % (sys.executable, SAB_BASE_DIR, SAB_HOST, SAB_PORT, SAB_CACHE_DIR) + sab_command = "%s %s/../SABnzbd.py --new -l2 -s %s:%s -b0 -f %s" % ( + sys.executable, + SAB_BASE_DIR, + SAB_HOST, + SAB_PORT, + SAB_CACHE_DIR, + ) subprocess.Popen(sab_command.split()) # Wait for SAB to respond @@ -73,7 +79,7 @@ def start_sabnzbd(): def shutdown_sabnzbd(): # Graceful shutdown request try: - get_url_result('shutdown') + get_url_result("shutdown") except requests.ConnectionError: pass diff --git a/tests/test_encoding.py b/tests/test_encoding.py index 5db8802..46377fa 100644 --- a/tests/test_encoding.py +++ b/tests/test_encoding.py @@ -23,7 +23,6 @@ import sabnzbd.encoding as enc class TestEncoding: - def test_correct_unknown_encoding(self): # Windows encoding in bytes assert "frènch_german_demö" == enc.correct_unknown_encoding(b"fr\xe8nch_german_dem\xf6") diff --git a/tests/test_filesystem.py b/tests/test_filesystem.py index 516a58b..8d43e4f 100644 --- a/tests/test_filesystem.py +++ b/tests/test_filesystem.py @@ -34,7 +34,7 @@ class TestFileFolderNameSanitizer: assert filesystem.sanitize_filename("test:aftertest") == "test-aftertest" # They should act the same assert filesystem.sanitize_filename("test:aftertest") == filesystem.sanitize_foldername("test:aftertest") - #TODO: Add a lot more tests here! + # TODO: Add a lot more tests here! @set_platform("darwin") def test_colon_handling_darwin(self): diff --git a/tests/test_functional_config.py b/tests/test_functional_config.py index e918be7..4091a46 100644 --- a/tests/test_functional_config.py +++ b/tests/test_functional_config.py @@ -24,31 +24,28 @@ from tests.testhelper import * class SABnzbdBasicPagesTest(SABnzbdBaseTest): - def test_base_pages(self): # Quick-check of all Config pages - test_urls = ['config', - 'config/server', - 'config/categories', - 'config/scheduling', - 'config/rss'] + test_urls = ["config", "config/server", "config/categories", "config/scheduling", "config/rss"] for test_url in test_urls: self.open_page("http://%s:%s/%s" % (SAB_HOST, SAB_PORT, test_url)) def test_base_submit_pages(self): - test_urls_with_submit = ['config/general', - 'config/folders', - 'config/switches', - 'config/sorting', - 'config/notify', - 'config/special'] + test_urls_with_submit = [ + "config/general", + "config/folders", + "config/switches", + "config/sorting", + "config/notify", + "config/special", + ] for test_url in test_urls_with_submit: self.open_page("http://%s:%s/%s" % (SAB_HOST, SAB_PORT, test_url)) # Can only click the visible buttons - submit_btns = self.driver.find_elements_by_class_name('saveButton') + submit_btns = self.driver.find_elements_by_class_name("saveButton") for submit_btn in submit_btns: if submit_btn.is_displayed(): break @@ -65,7 +62,7 @@ class SABnzbdBasicPagesTest(SABnzbdBaseTest): self.driver.switch_to.alert.dismiss() # For Specials page we get redirected after save, so check for no crash - if 'special' in test_url: + if "special" in test_url: self.no_page_crash() else: # For others if all is fine, button will be back to normal in 1 second @@ -114,7 +111,7 @@ class SABnzbdConfigRSS(SABnzbdBaseTest): assert tab_table_results == tab_results # Pause the queue do we don't download stuff - assert get_api_result('pause') == {'status': True} + assert get_api_result("pause") == {"status": True} # Download something download_btn = self.driver.find_element_by_xpath('//div[@id="rss-tab-matched"]/table/tbody//button') @@ -125,16 +122,16 @@ class SABnzbdConfigRSS(SABnzbdBaseTest): assert "Added NZB" in download_btn.text # Let's check the queue - queue_result_slots = get_api_result('queue')['queue']['slots'] + queue_result_slots = get_api_result("queue")["queue"]["slots"] assert len(queue_result_slots) == 1 # Let's remove this thing - get_api_result('queue', {'name': 'delete', 'value': queue_result_slots[0]['nzo_id']}) - queue_result_slots = get_api_result('queue')['queue']['slots'] + get_api_result("queue", {"name": "delete", "value": queue_result_slots[0]["nzo_id"]}) + queue_result_slots = get_api_result("queue")["queue"]["slots"] assert len(queue_result_slots) == 0 # Unpause - assert get_api_result('resume') == {'status': True} + assert get_api_result("resume") == {"status": True} @pytest.mark.skipif("SAB_NEWSSERVER_HOST" not in os.environ, reason="Test-server not specified") @@ -149,7 +146,7 @@ class SABnzbdConfigServers(SABnzbdBaseTest): # Show advanced options advanced_btn = self.driver.find_element_by_name("advanced-settings-button") - if not advanced_btn.get_attribute('checked'): + if not advanced_btn.get_attribute("checked"): advanced_btn.click() def add_test_server(self): @@ -167,16 +164,17 @@ class SABnzbdConfigServers(SABnzbdBaseTest): # With SSL ssl_imp = self.driver.find_element_by_name("ssl") - if not ssl_imp.get_attribute('checked'): + if not ssl_imp.get_attribute("checked"): ssl_imp.click() # Check that we filled the right port automatically - self.assertEqual(self.driver.find_element_by_id("port").get_attribute('value'), '563') + self.assertEqual(self.driver.find_element_by_id("port").get_attribute("value"), "563") # Test server-check self.driver.find_element_by_css_selector("#addServerContent .testServer").click() self.wait_for_ajax() - self.assertIn("Connection Successful", self.driver.find_element_by_css_selector('#addServerContent .result-box').text) + check_result = self.driver.find_element_by_css_selector("#addServerContent .result-box").text + assert "Connection Successful" in check_result # Set test-servername self.driver.find_element_by_id("displayname").send_keys(self.server_name) @@ -210,14 +208,14 @@ class SABnzbdConfigServers(SABnzbdBaseTest): pass_inp.clear() self.driver.find_elements_by_css_selector(".testServer")[1].click() self.wait_for_ajax() - check_result = self.driver.find_elements_by_css_selector('.result-box')[1].text.lower() + check_result = self.driver.find_elements_by_css_selector(".result-box")[1].text.lower() assert "authentication failed" in check_result or "invalid username or password" in check_result # Test server-check with bad password pass_inp.send_keys("bad") self.driver.find_elements_by_css_selector(".testServer")[1].click() self.wait_for_ajax() - check_result = self.driver.find_elements_by_css_selector('.result-box')[1].text.lower() + check_result = self.driver.find_elements_by_css_selector(".result-box")[1].text.lower() assert "authentication failed" in check_result or "invalid username or password" in check_result # Test no username and password @@ -226,7 +224,7 @@ class SABnzbdConfigServers(SABnzbdBaseTest): username_inp.clear() self.driver.find_elements_by_css_selector(".testServer")[1].click() self.wait_for_ajax() - check_result = self.driver.find_elements_by_css_selector('.result-box')[1].text.lower() + check_result = self.driver.find_elements_by_css_selector(".result-box")[1].text.lower() assert "server requires username and password" in check_result # Finish diff --git a/tests/test_functional_downloads.py b/tests/test_functional_downloads.py index 150b24c..1206dcc 100644 --- a/tests/test_functional_downloads.py +++ b/tests/test_functional_downloads.py @@ -26,12 +26,11 @@ from tests.testhelper import * @pytest.mark.skipif("SAB_NEWSSERVER_HOST" not in os.environ, reason="Test-server not specified") class SABnzbdDownloadFlow(SABnzbdBaseTest): - def is_server_configured(self): """ Check if the wizard was already performed. If not: run the wizard! """ - with open(os.path.join(SAB_CACHE_DIR, 'sabnzbd.ini'), 'r') as config_file: + with open(os.path.join(SAB_CACHE_DIR, "sabnzbd.ini"), "r") as config_file: if self.newsserver_host not in config_file.read(): self.start_wizard() @@ -39,7 +38,7 @@ class SABnzbdDownloadFlow(SABnzbdBaseTest): # Language-selection self.open_page("http://%s:%s/sabnzbd/wizard/" % (SAB_HOST, SAB_PORT)) self.driver.find_element_by_id("en").click() - self.driver.find_element_by_css_selector('.btn.btn-default').click() + self.driver.find_element_by_css_selector(".btn.btn-default").click() # Fill server-info self.no_page_crash() @@ -55,7 +54,7 @@ class SABnzbdDownloadFlow(SABnzbdBaseTest): # With SSL ssl_imp = self.driver.find_element_by_name("ssl") - if not ssl_imp.get_attribute('checked'): + if not ssl_imp.get_attribute("checked"): ssl_imp.click() # This will fail if the translations failed to compile! @@ -74,14 +73,15 @@ class SABnzbdDownloadFlow(SABnzbdBaseTest): # Final page done self.driver.find_element_by_id("next-button").click() self.no_page_crash() - self.assertIn("http://%s:%s/sabnzbd" % (SAB_HOST, SAB_PORT), self.driver.find_element_by_class_name("quoteBlock").text) + check_result = self.driver.find_element_by_class_name("quoteBlock").text + assert "http://%s:%s/sabnzbd" % (SAB_HOST, SAB_PORT) in check_result # Go to SAB! - self.driver.find_element_by_css_selector('.btn.btn-success').click() + self.driver.find_element_by_css_selector(".btn.btn-success").click() self.no_page_crash() def add_nzb_from_url(self, file_url, file_output): - test_job_name = 'testfile_%s' % random.randint(500, 1000) + test_job_name = "testfile_%s" % random.randint(500, 1000) self.open_page("http://%s:%s/sabnzbd/" % (SAB_HOST, SAB_PORT)) @@ -96,9 +96,11 @@ class SABnzbdDownloadFlow(SABnzbdBaseTest): for _ in range(120): try: # Locate resulting row - result_row = self.driver.find_element_by_xpath('//*[@id="history-tab"]//tr[td//text()[contains(., "%s")]]' % test_job_name) + result_row = self.driver.find_element_by_xpath( + '//*[@id="history-tab"]//tr[td//text()[contains(., "%s")]]' % test_job_name + ) # Did it complete? - if result_row.find_element_by_css_selector('td.status').text == 'Completed': + if result_row.find_element_by_css_selector("td.status").text == "Completed": break else: time.sleep(1) @@ -137,4 +139,4 @@ class SABnzbdDownloadFlow(SABnzbdBaseTest): @pytest.mark.skip(reason="Fails due to wrong par2-renaming. Needs fixing.") def test_download_win_unicode(self): self.is_server_configured() - self.add_nzb_from_url("http://sabnzbd.org/tests/unicode_rar_broken.nzb", u"\u4f60\u597d\u4e16\u754c.bin") + self.add_nzb_from_url("http://sabnzbd.org/tests/unicode_rar_broken.nzb", "\u4f60\u597d\u4e16\u754c.bin") diff --git a/tests/test_misc.py b/tests/test_misc.py index 3fba1d0..794b3f5 100644 --- a/tests/test_misc.py +++ b/tests/test_misc.py @@ -159,17 +159,17 @@ class TestMisc: assert "1 sec" == misc.format_time_string(1) assert "10 seconds" == misc.format_time_string(10) assert "1 min" == misc.format_time_string(60) - assert "1 hour 1 min 1 sec" == misc.format_time_string(60*60 + 60 + 1) + assert "1 hour 1 min 1 sec" == misc.format_time_string(60 * 60 + 60 + 1) assert "1 day 59 seconds" == misc.format_time_string(86400 + 59) - assert "2 days 2 hours 2 seconds" == misc.format_time_string(2*86400 + 2*60*60 + 2) + assert "2 days 2 hours 2 seconds" == misc.format_time_string(2 * 86400 + 2 * 60 * 60 + 2) def test_format_time_string_locale(self): # Have to set the languages, if it was compiled - locale_dir = os.path.join(SAB_BASE_DIR, '..', sabnzbd.constants.DEF_LANGUAGE) + locale_dir = os.path.join(SAB_BASE_DIR, "..", sabnzbd.constants.DEF_LANGUAGE) if not os.path.exists(locale_dir): pytest.mark.skip("No language files compiled") - lang.set_locale_info('SABnzbd', locale_dir) + lang.set_locale_info("SABnzbd", locale_dir) lang.set_language("de") assert "1 Sekunde" == misc.format_time_string(1) assert "10 Sekunden" == misc.format_time_string(10) diff --git a/tests/testhelper.py b/tests/testhelper.py index e16be1e..1727c7b 100644 --- a/tests/testhelper.py +++ b/tests/testhelper.py @@ -35,15 +35,16 @@ from selenium.webdriver.support.ui import WebDriverWait import sabnzbd import sabnzbd.cfg as cfg -SAB_HOST = 'localhost' +SAB_HOST = "localhost" SAB_PORT = 8081 SAB_BASE_DIR = os.path.dirname(os.path.abspath(__file__)) -SAB_CACHE_DIR = os.path.join(SAB_BASE_DIR, 'cache') -SAB_COMPLETE_DIR = os.path.join(SAB_CACHE_DIR, 'Downloads', 'complete') +SAB_CACHE_DIR = os.path.join(SAB_BASE_DIR, "cache") +SAB_COMPLETE_DIR = os.path.join(SAB_CACHE_DIR, "Downloads", "complete") def set_config(settings_dict): """ Change config-values on the fly, per test""" + def set_config_decorator(func): def wrapper_func(*args, **kwargs): # Setting up as requested @@ -57,12 +58,15 @@ def set_config(settings_dict): for item, val in settings_dict.items(): getattr(cfg, item).default() return value + return wrapper_func + return set_config_decorator def set_platform(platform): """ Change config-values on the fly, per test""" + def set_platform_decorator(func): def wrapper_func(*args, **kwargs): # Save original values @@ -70,13 +74,13 @@ def set_platform(platform): is_darwin = sabnzbd.DARWIN # Set current platform - if platform == 'win32': + if platform == "win32": sabnzbd.WIN32 = True sabnzbd.DARWIN = False - elif platform == 'darwin': + elif platform == "darwin": sabnzbd.WIN32 = False sabnzbd.DARWIN = True - elif platform == 'linux': + elif platform == "linux": sabnzbd.WIN32 = False sabnzbd.DARWIN = False @@ -88,34 +92,35 @@ def set_platform(platform): sabnzbd.DARWIN = is_darwin return value + return wrapper_func + return set_platform_decorator -def get_url_result(url=''): +def get_url_result(url=""): """ Do basic request to web page """ - arguments = {'session': 'apikey'} - return requests.get('http://%s:%s/%s/' % (SAB_HOST, SAB_PORT, url), params=arguments).text + arguments = {"session": "apikey"} + return requests.get("http://%s:%s/%s/" % (SAB_HOST, SAB_PORT, url), params=arguments).text def get_api_result(mode, extra_arguments={}): """ Build JSON request to SABnzbd """ - arguments = {'apikey': 'apikey', 'output': 'json', 'mode': mode} + arguments = {"apikey": "apikey", "output": "json", "mode": mode} arguments.update(extra_arguments) - r = requests.get('http://%s:%s/api' % (SAB_HOST, SAB_PORT), params=arguments) + r = requests.get("http://%s:%s/api" % (SAB_HOST, SAB_PORT), params=arguments) return r.json() def upload_nzb(filename): """ Upload file and return nzo_id reponse """ - files = {'name': open(filename, 'rb')} - arguments = {'apikey': 'apikey', 'mode': 'addfile', 'output': 'json'} - return requests.post('http://%s:%s/api' % (SAB_HOST, SAB_PORT), files=files, data=arguments).json() + files = {"name": open(filename, "rb")} + arguments = {"apikey": "apikey", "mode": "addfile", "output": "json"} + return requests.post("http://%s:%s/api" % (SAB_HOST, SAB_PORT), files=files, data=arguments).json() @pytest.mark.usefixtures("start_sabnzbd") class SABnzbdBaseTest(unittest.TestCase): - @classmethod def setUpClass(cls): # We try Chrome, fallback to Firefox @@ -136,9 +141,9 @@ class SABnzbdBaseTest(unittest.TestCase): # Get the newsserver-info, if available if "SAB_NEWSSERVER_HOST" in os.environ: - cls.newsserver_host = os.environ['SAB_NEWSSERVER_HOST'] - cls.newsserver_user = os.environ['SAB_NEWSSERVER_USER'] - cls.newsserver_password = os.environ['SAB_NEWSSERVER_PASSWORD'] + cls.newsserver_host = os.environ["SAB_NEWSSERVER_HOST"] + cls.newsserver_user = os.environ["SAB_NEWSSERVER_USER"] + cls.newsserver_password = os.environ["SAB_NEWSSERVER_PASSWORD"] @classmethod def tearDownClass(cls): @@ -147,7 +152,7 @@ class SABnzbdBaseTest(unittest.TestCase): def no_page_crash(self): # Do a base test if CherryPy did not report test - self.assertNotIn('500 Internal Server Error', self.driver.title) + self.assertNotIn("500 Internal Server Error", self.driver.title) def open_page(self, url): # Open a page and test for crash @@ -155,11 +160,10 @@ class SABnzbdBaseTest(unittest.TestCase): self.no_page_crash() def scroll_to_top(self): - self.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.HOME) + self.driver.find_element_by_tag_name("body").send_keys(Keys.CONTROL + Keys.HOME) time.sleep(2) def wait_for_ajax(self): wait = WebDriverWait(self.driver, 15) - wait.until(lambda driver_wait: self.driver.execute_script('return jQuery.active') == 0) - wait.until(lambda driver_wait: self.driver.execute_script('return document.readyState') == 'complete') - + wait.until(lambda driver_wait: self.driver.execute_script("return jQuery.active") == 0) + wait.until(lambda driver_wait: self.driver.execute_script("return document.readyState") == "complete")