def init_environment(self, initial, sub_dependencies=None): if sub_dependencies is None: sub_dependencies = list() self.initial = initial dep = sub_dependencies self.result = list() uname = platform.uname() self.result.append(('Platform', '{0.system} {0.release} {0.version} {0.processor} {0.machine}'.format(uname), 'Basic')) p = process_open([initial, "-V"], [0]) p.wait() lines = ''.join(p.stdout.readlines()) pVersion = re.findall('(\d+\.\d+\.\d+)', lines)[0] self.result.append(('Python', pVersion, 'Basic')) p = process_open([initial, "-m", "pip", "freeze"], [0]) p.wait() dists = [str(d).strip().split("==") for d in p.stdout.readlines()] with open(os.path.join(CALIBRE_WEB_PATH, 'requirements.txt'), 'r') as f: for line in f: if not line.startswith('#') and not line == '\n' and not line.startswith('git'): dep.append(line.split('=', 1)[0].strip('>')) with open(os.path.join(CALIBRE_WEB_PATH, 'optional-requirements.txt'), 'r') as f: for line in f: if not line.startswith('#') and not line == '\n' and not line.startswith('git'): dep.append(line.split('=', 1)[0].split('>', 1)[0]) normalized_dep = [name.replace('_', '-').upper() for name in dep] for element in dists: if element[0].replace('_', '-').upper() in normalized_dep: self.result.append((element[0], element[1], 'Basic'))
def test_settingsdb_not_writeable(self): # check unconfigured database os.chdir(CALIBRE_WEB_PATH) p1 = process_open([self.py_version, "-B", u'cps.py'], [1]) time.sleep(BOOT_TIME) p1.terminate() p1.stdout.close() p1.stderr.close() time.sleep(BOOT_TIME) p1.poll() os.chmod("app.db", 0o400) p2 = process_open([self.py_version, "-B", u'cps.py'], [1]) time.sleep(BOOT_TIME) result = p2.poll() if result is None: p2.terminate() p2.poll() self.assertTrue( '2nd process not terminated, port is already in use') p2.stdout.close() p2.stderr.close() self.assertEqual(result, 2) os.chmod("app.db", 0o644) # configure and check again p1 = process_open([self.py_version, "-B", u'cps.py'], [1]) time.sleep(BOOT_TIME) try: # navigate to the application home page self.driver.get("http://127.0.0.1:8083") # Wait for config screen to show up self.fill_db_config({'config_calibre_dir': TEST_DB}) # wait for cw to reboot time.sleep(2) except Exception: self.assertFalse( True, "Inital config failed with nonwriteable database") p1.terminate() p1.stdout.close() p1.stderr.close() time.sleep(BOOT_TIME) p1.poll() os.chmod("app.db", 0o400) p2 = process_open([self.py_version, "-B", u'cps.py'], [1]) time.sleep(BOOT_TIME) result = p2.poll() if result is None: p2.terminate() p2.poll() self.assertTrue( '2nd process not terminated, port is already in use') p2.stdout.close() p2.stderr.close() self.assertEqual(result, 2) os.chmod("app.db", 0o644) os.chdir(base_path)
def test_enable_reconnect(self): my_env = os.environ.copy() my_env["CALIBRE_RECONNECT"] = '1' p = process_open( [self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py')], [1], env=my_env) time.sleep(BOOT_TIME) # navigate to the application home page self.driver.get("http://127.0.0.1:8083") # Wait for config screen to show up self.fill_db_config({'config_calibre_dir': TEST_DB}) # wait for cw to reboot time.sleep(2) self.assertTrue(self.check_element_on_page((By.ID, 'flash_success'))) r = requests.get("http://127.0.0.1:8083/reconnect") self.assertEqual(200, r.status_code) self.assertDictEqual({}, r.json()) self.stop_calibre_web(p) try: self.driver.switch_to.alert.accept() except Exception: pass my_env = os.environ.copy() p = process_open( [self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py')], [1], env=my_env) time.sleep(BOOT_TIME) r = requests.get("http://127.0.0.1:8083/reconnect") self.assertEqual(404, r.status_code) self.stop_calibre_web(p) try: self.driver.switch_to.alert.accept() except Exception: pass p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), "-r" ], [1]) time.sleep(BOOT_TIME) r = requests.get("http://127.0.0.1:8083/reconnect") self.assertEqual(200, r.status_code) self.assertDictEqual({}, r.json()) self.stop_calibre_web(p) try: self.driver.switch_to.alert.accept() except Exception: pass os.remove(os.path.join(CALIBRE_WEB_PATH, u'app.db'))
def test_gdrive_db_nonwrite(self): self.start_cw(os.path.join(CALIBRE_WEB_PATH, u'cps.py')) self.fill_db_config({'config_use_google_drive': 1}) time.sleep(BOOT_TIME) self.fill_db_config({'config_google_drive_folder': 'test'}) time.sleep(BOOT_TIME) self.driver.get("http://127.0.0.1:8083") self.stop_calibre_web() time.sleep(5) # shutdowntime self.p.terminate() try: self.driver.switch_to.alert.accept() except Exception: pass gdrive_db = os.path.join(CALIBRE_WEB_PATH, "gdrive.db") self.assertTrue(os.path.exists(gdrive_db)) os.chmod(gdrive_db, 0o400) self.p = process_open( [self.py_version, os.path.join(CALIBRE_WEB_PATH, u'cps.py')], [1]) # create a new Firefox session time.sleep(BOOT_TIME) # navigate to the application home page self.driver.get("http://127.0.0.1:8083") os.chmod(gdrive_db, 0o654) self.stop_calibre_web() self.p.terminate() try: self.driver.switch_to.alert.accept() except Exception: pass
def test_cli_different_folder(self): os.chdir(CALIBRE_WEB_PATH) self.p = process_open([self.py_version, "-B", u'cps.py'], [1]) os.chdir(os.path.dirname(__file__)) try: # create a new Firefox session time.sleep(15) # navigate to the application home page self.driver.get("http://127.0.0.1:8083") # Wait for config screen to show up self.fill_db_config({'config_calibre_dir': TEST_DB}) # wait for cw to reboot time.sleep(BOOT_TIME) # Wait for config screen with login button to show up login_button = self.check_element_on_page((By.NAME, "login")) self.assertTrue(login_button) login_button.click() # login self.login("admin", "admin123") time.sleep(3) self.assertTrue(self.check_element_on_page((By.NAME, "query"))) self.stop_calibre_web(self.p) except Exception: pass self.p.stdout.close() self.p.stderr.close() self.p.terminate()
def test_writeonly_static_files(self): p = process_open( [self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py')], [1]) time.sleep(BOOT_TIME) # navigate to the application home page self.driver.get("http://127.0.0.1:8083") # Wait for config screen to show up self.fill_db_config({'config_calibre_dir': TEST_DB}) # wait for cw to reboot time.sleep(2) self.assertTrue(self.check_element_on_page((By.ID, 'flash_success'))) # readonly template "tasks.html" mode = os.path.join(CALIBRE_WEB_PATH, "cps", "templates", "tasks.html") os.chmod(mode, 0o200) r = requests.session() login_page = r.get('http://127.0.0.1:8083/login') token = re.search( '<input type="hidden" name="csrf_token" value="(.*)">', login_page.text) payload = { 'username': '******', 'password': '******', 'submit': "", 'next': "/", "csrf_token": token.group(1) } r.post('http://127.0.0.1:8083/login', data=payload) resp = r.get("http://127.0.0.1:8083/tasks") self.assertEqual(403, resp.status_code) os.chmod(mode, 0o644) resp = r.get("http://127.0.0.1:8083/tasks") self.assertEqual(200, resp.status_code) # readonly "static" folder mode = os.path.join(CALIBRE_WEB_PATH, "cps", "static") os.chmod(mode, 0o200) resp = r.get("http://127.0.0.1:8083/static/js/main.js") self.assertEqual(404, resp.status_code) resp = r.get("http://127.0.0.1:8083/tasks") self.assertEqual(200, resp.status_code) os.chmod(mode, 0o755) resp = r.get("http://127.0.0.1:8083/static/js/main.js") self.assertEqual(200, resp.status_code) # readonly "main.js" folder mode = os.path.join(CALIBRE_WEB_PATH, "cps", "static", "js", "main.js") os.chmod(mode, 0o200) resp = r.get("http://127.0.0.1:8083/static/js/main.js") self.assertEqual(500, resp.status_code) resp = r.get("http://127.0.0.1:8083/tasks") self.assertEqual(200, resp.status_code) os.chmod(mode, 0o644) resp = r.get("http://127.0.0.1:8083/static/js/main.js") self.assertEqual(200, resp.status_code) self.stop_calibre_web(p) try: self.driver.switch_to.alert.accept() except Exception: pass os.remove(os.path.join(CALIBRE_WEB_PATH, u'app.db'))
def test_environ_port_setting(self): my_env = os.environ.copy() my_env["CALIBRE_PORT"] = '8082' p = process_open( [self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py')], [1], env=my_env) time.sleep(BOOT_TIME) # navigate to the application home page try: self.driver.switch_to.alert.accept() except Exception: pass try: error = "" self.driver.get("http://127.0.0.1:8082") except WebDriverException as e: error = e.msg self.assertFalse( re.findall( 'Reached error page:\sabout:neterror\?e=connectionFailure', error)) self.assertTrue(self.check_element_on_page((By.ID, "username"))) p.terminate() time.sleep(3) p.poll()
def test_bind_to_single_interface(self): address = get_Host_IP() p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-i', 'http://' + address ], [1]) time.sleep(2) if p.poll() is None: p.kill() p.stdout.close() p.stderr.close() nextline = p.communicate()[0] self.assertIsNotNone(re.findall('Illegal IP address string', nextline)) p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-i', address ], [1]) time.sleep(BOOT_TIME) # navigate to the application home page try: self.driver.switch_to.alert.accept() except Exception: pass try: error = "" self.driver.get("http://127.0.0.1:8083") except WebDriverException as e: error = e.msg self.assertTrue( re.findall( 'Reached error page:\sabout:neterror\?e=connectionFailure', error)) try: self.driver.get("http://" + address + ":8083") except WebDriverException: self.assertIsNone('Limit listening address not working') self.assertTrue(self.check_element_on_page((By.ID, "username"))) p.stdout.close() p.stderr.close() p.terminate() time.sleep(3) p.poll()
def help_dry_run(self): p1 = process_open([self.py_version, "-B", u'cps.py', "-d"], [1]) output = list() while p1.poll() is None: output.append(p1.stdout.readline()) self.assertEqual(0, p1.returncode) p1.stdout.close() p1.stderr.close() p1.kill() return "".join(output)
def test_already_started(self): os.chdir(CALIBRE_WEB_PATH) p1 = process_open([self.py_version, "-B", u'cps.py'], [1]) time.sleep(BOOT_TIME) p2 = process_open([self.py_version, "-B", u'cps.py'], [1]) time.sleep(BOOT_TIME) time.sleep(2) result = p2.poll() if result is None: p2.terminate() self.assertTrue( '2nd process not terminated, port is already in use') self.assertEqual(result, 1) p1.terminate() time.sleep(3) p1.poll() p1.stdout.close() p1.stderr.close() p2.stdout.close() p2.stderr.close()
def check_password_change(self, parameter, expectation): p = process_open([self.py_version, "-B", 'cps.py', "-s", parameter], [1]) time.sleep(2) if p.poll() is None: p.kill() nextline = p.communicate()[0] self.assertIsNotNone(re.findall(expectation, nextline)) p.terminate() p.stdout.close() p.stderr.close()
def remove_dependency(names): for name in names: if name.startswith('git|'): name = name[4:] if name.startswith('local|'): name = name.split('|')[2] with process_open([VENV_PYTHON, "-m", "pip", "uninstall", "-y", name], (0, 5)) as q: if os.name == 'nt': while q.poll() == None: q.stdout.readline() else: q.wait()
def create_python_environment(): # install requirements and optional requirements in venv of calibre-web print("* Creating virtual environment for executable") try: venv.create(VENV_PATH, clear=True, with_pip=True) except CalledProcessError: print("## Error Creating virtual environment ##") venv.create(VENV_PATH, system_site_packages=True, with_pip=False) print("* Adding dependencies for executable from requirements file") requirements_file = os.path.join(FILEPATH, 'requirements.txt') p = process_open([VENV_PYTHON, "-m", "pip", "install", "-r", requirements_file], (0, 5)) while p.poll() is None: out = p.stdout.readline() out != "" and print(out.strip("\n")) # Adding precompiled dependencies for Windows if os.name == "nt": print("* Adding precompiled dependencies for executable for Windows") add_dependency(["local|LDAP_WHL|python-ldap", "local|LEVENSHTEIN_WHL|python-Levenshtein"], "") print("* Adding dependencies for executable from optional_requirements file") optional_requirements_file = os.path.join(FILEPATH, 'optional-requirements.txt') p = process_open([VENV_PYTHON, "-m", "pip", "install", "-r", optional_requirements_file], (0, 5)) while p.poll() is None: out = p.stdout.readline() out != "" and print(out.strip("\n")) print("* Saving installed requirement versions") environment.init_environment(VENV_PYTHON) environment.save_environment(os.path.join(FILEPATH, '.pip_installed')) print("Adding pyinstaller to virtual environment") p = process_open([VENV_PYTHON, "-m", "pip", "install", "pyinstaller"], (0,)) while p.poll() is None: out = p.stdout.readline() out != "" and print(out.strip("\n"))
def add_environment(self, test, extension): if self.initial: try: p = process_open([self.initial, "-m", "pip", "freeze"], [0]) p.wait() dists = [str(d).strip().split("==") for d in p.stdout.readlines()] normalized_Ext = [name.replace('_', '-').upper() for name in extension] for element in dists: if element[0].replace('_', '-').upper() in normalized_Ext: self.result.append((element[0], element[1], test)) except Exception: pass else: for testdep in extension: self.result.append((extension, '', testdep))
def test_foldername_database_location(self): package_command = os.path.join(self.package_path, "bin", "cps") p = process_open([package_command, "-p",self.package_path]) # create a new Firefox session time.sleep(BOOT_TIME) # navigate to the application home page self.driver.get("http://127.0.0.1:8083") self.login("admin", "admin123") self.fill_db_config({'config_calibre_dir': TEST_DB}) self.assertTrue(self.check_element_on_page((By.ID, "flash_success"))) self.stop_calibre_web(p) time.sleep(1) try: self.driver.switch_to.alert.accept() except Exception: pass
def test_module_start(self): package_python = os.path.join(self.package_path, "bin", "python3") app_db = os.path.join(self.package_path, "app.db") p = process_open([package_python, "-m", "calibreweb", "-p", app_db]) # create a new Firefox session time.sleep(BOOT_TIME) # navigate to the application home page self.driver.get("http://127.0.0.1:8083") self.login("admin", "admin123") self.fill_db_config({'config_calibre_dir': TEST_DB}) self.assertTrue(self.check_element_on_page((By.ID, "flash_success"))) self.stop_calibre_web(p) time.sleep(1) try: self.driver.switch_to.alert.accept() except Exception: pass
def start_cw(self, cw_path, gdrive_path=None): parameter = [self.py_version, cw_path] quotes = [1] if gdrive_path: parameter.extend(['-g', gdrive_path]) quotes.extend([3]) self.p = process_open(parameter, quotes) # create a new Firefox session time.sleep(BOOT_TIME) # navigate to the application home page self.driver.get("http://127.0.0.1:8083") # Wait for config screen to show up self.fill_db_config({'config_calibre_dir': TEST_DB}) # wait for cw to be ready time.sleep(2) self.assertTrue(self.check_element_on_page((By.ID, "flash_success"))) self.assertTrue(self.check_element_on_page((By.NAME, "query")))
def setUpClass(cls): # startup function is not called, therefore direct print print("\n%s - %s: " % (cls.py_version, cls.__name__)) cls.driver = webdriver.Firefox() cls.driver.implicitly_wait(10) cls.driver.maximize_window() shutil.rmtree(TEST_DB, ignore_errors=True) shutil.copytree('./Calibre_db', TEST_DB) #generate pypi install package args = make_release.parse_arguments(['-p']) make_release.main(args) result = glob.glob(os.path.join(CALIBRE_WEB_PATH, "dist", "*.whl")) # generate new venv python cls.package_path = CALIBRE_WEB_PATH + "_pack" venv.create(cls.package_path, clear=True, with_pip=True) package_python = os.path.join(cls.package_path, "bin", "python3") with process_open([package_python, "-m", "pip", "install", result[0]]) as p: p.wait() p.stdout.readlines()
def test_cli_different_settings_database(self): new_db = os.path.join(CALIBRE_WEB_PATH, 'hü go.app') self.p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-p', new_db ], [1, 3]) time.sleep(15) # navigate to the application home page try: self.driver.switch_to.alert.accept() except Exception: pass self.driver.refresh() try: self.driver.switch_to.alert.accept() except Exception: pass self.driver.get("http://127.0.0.1:8083") # Wait for config screen to show up self.check_element_on_page((By.ID, "username")) self.fill_db_config({'config_calibre_dir': TEST_DB}) self.assertTrue( self.check_element_on_page((By.ID, "calibre_modal_path"))) # wait for cw to reboot time.sleep(2) # Wait for config screen with login button to show up self.stop_calibre_web(self.p) self.p.stdout.close() self.p.stderr.close() self.p.terminate() time.sleep(3) self.assertTrue(os.path.isfile(new_db), "New settingsfile location not accepted") os.remove(new_db) try: self.driver.switch_to.alert.accept() except Exception: pass
def add_dependency(name, testclass_name): print("Adding dependencies") element_version = list() with open(os.path.join(CALIBRE_WEB_PATH, 'optional-requirements.txt'), 'r') as f: requirements = f.readlines() for element in name: if element.lower().startswith('local|'): # full_module_name = ".config_test." + element.split('|')[1] # The file gets executed upon import, as expected. # tmp = __import__('pkg', fromlist=['mod', 'mod2']) whl = importlib.__import__("config_test", fromlist=[element.split('|')[1]]) element_version.append(whl.__dict__[element.split('|')[1]]) for line in requirements: if element.lower().startswith('git|') \ and not line.startswith('#') \ and not line == '\n' \ and line.lower().startswith('git') \ and line.lower().endswith('#egg=' + element.lower().lstrip('git|')+'\n'): element_version.append(line.strip('\n')) elif not line.startswith('#') \ and not line == '\n' \ and not line.startswith('git') \ and not line.startswith('local') \ and line.upper().startswith(element.upper()): element_version.append(line.split('=', 1)[0].strip('>')) break for indx, element in enumerate(element_version): with process_open([VENV_PYTHON, "-m", "pip", "install", element], (0, 4)) as r: while r.poll() == None: r.stdout.readline().strip("\n") #if os.name == 'nt': # while r.poll() == None: # r.stdout.readline() #else: # r.wait() if element.lower().startswith('git'): element_version[indx] = element[element.rfind('#egg=')+5:] environment.add_environment(testclass_name, element_version)
def main(): quotes = [1, 2] format_new_ext = '.mobi' format_old_ext = '.epub' file_path = '/home/matthias/Dokumente/bücher/Bettina Szramah/Die Giftmischerin TCP_IP (10)/Die Giftmischerin TCP_IP - Bettina, Szrama' command = ['/opt/calibre/ebook-convert', (file_path + format_old_ext), (file_path + format_new_ext)] #print(command) #p1 = cmdlineCall(command[0],command[1:]) #time.sleep(10) #print(p1) p = process_open(command, quotes) while p.poll() is None: nextline = p.stdout.readline() if os.name == 'nt' and sys.version_info < (3, 0): nextline = nextline.decode('windows-1252') elif os.name == 'posix' and sys.version_info < (3, 0): nextline = nextline.decode('utf-8') # log.debug(nextline.strip('\r\n')) # parse progress string from calibre-converter progress = re.search(r"(\d+)%\s.*", nextline) if progress: print('Progress:' + str(progress)) # self.UIqueue[index]['progress'] = progress.group(1) + ' % # process returncode check = p.returncode calibre_traceback = p.stderr.readlines() for ele in calibre_traceback: if sys.version_info < (3, 0): ele = ele.decode('utf-8') print(ele.strip('\n')) if not ele.startswith('Traceback') and not ele.startswith(' File'): print( "Calibre failed with error: %s" % ele.strip('\n')) print(str(check))
def test_change_password(self): os.chdir(CALIBRE_WEB_PATH) self.check_password_change("admin:admin12", "Password for user 'admin' changed") self.check_password_change("admin:adm:in12", "Password for user 'admin' changed") self.check_password_change("admin.kolo", "No valid username:password.*") self.check_password_change("admin:", "Empty password") p1 = process_open([self.py_version, "-B", u'cps.py'], [1]) time.sleep(BOOT_TIME) try: # navigate to the application home page self.driver.get("http://127.0.0.1:8083") # Wait for config screen to show up self.login("admin", "adm:in12") self.fill_db_config({'config_calibre_dir': TEST_DB}) # wait for cw to reboot time.sleep(2) self.logout() except Exception as e: self.assertFalse(e) self.check_password_change("admin:@hukl", "Password for user 'admin' changed") if os.name != "nt": self.assertFalse(self.login("admin", "admin123")) self.assertTrue(self.login("admin", "@hukl")) self.check_password_change("admin:admin123", "Password for user 'admin' changed") p1.terminate() time.sleep(3) p1.stdout.close() p1.stderr.close() os.remove("app.db")
retry = 0 power = input('Power off after finishing tests? [y/N]').lower() == 'y' if power: print('!!!! PC will shutdown after tests finished !!!!') # check pip ist installed found = False python_exe = "" pversion = [ "python3.8", "python3", "c:\\python39\\python.exe", "c:\\python310\\python.exe" ] for python in pversion: try: p = process_open([python, "-m", "pip", "-V"]) except (FileNotFoundError, Exception): print("{} not found".format(python)) continue p.wait() res = (p.stdout.readlines()) try: pip = re.match(("pip\s(.*)\sfrom\s(.*)\s\((.*)\).*"), res[0]) except IndexError as e: continue except TypeError as e: pip = re.match(("pip\s(.*)\sfrom\s(.*)\s\((.*)\).*"), res[0].decode('utf-8')) if pip: print("Found Pip for {} in {}".format(pip[3], pip[2])) found = True
def test_no_database(self): # check unconfigured database os.chdir(CALIBRE_WEB_PATH) p1 = process_open([self.py_version, u'cps.py'], [1]) time.sleep(BOOT_TIME) try: # navigate to the application home page self.driver.get("http://127.0.0.1:8083") # Wait for config screen to show up self.fill_db_config({'config_calibre_dir': TEST_DB}) # wait for cw to reboot time.sleep(5) self.assertTrue( self.check_element_on_page((By.ID, 'flash_success'))) except Exception: self.assertFalse(True, "Inital config failed with normal database") # create shelf, add book to shelf self.create_shelf("database") self.assertTrue(self.check_element_on_page((By.ID, 'flash_success'))) self.get_book_details(1) self.check_element_on_page((By.ID, "add-to-shelf")).click() self.check_element_on_page( (By.XPATH, "//ul[@id='add-to-shelves']/li/a[contains(.,'database')]" )).click() self.list_shelfs("database")['ele'].click() book_shelf = self.get_shelf_books_displayed() self.assertEqual(1, len(book_shelf)) # rename database file and restart os.rename(os.path.join(TEST_DB, "metadata.db"), os.path.join(TEST_DB, "_metadata.db")) self.restart_calibre_web() self.goto_page("user_setup") database_dir = self.check_element_on_page( (By.ID, "config_calibre_dir")) self.assertTrue(database_dir) self.assertEqual(TEST_DB, database_dir.get_attribute("value")) self.check_element_on_page((By.ID, "config_back")).click() time.sleep(2) self.check_element_on_page((By.ID, "config_calibre_dir")) self.check_element_on_page((By.ID, "db_submit")).click() self.assertTrue(self.check_element_on_page((By.ID, 'flash_danger'))) database_dir = self.check_element_on_page( (By.ID, "config_calibre_dir")) self.assertTrue(database_dir) self.assertEqual(TEST_DB, database_dir.get_attribute("value")) os.rename(os.path.join(TEST_DB, "_metadata.db"), os.path.join(TEST_DB, "metadata.db")) self.check_element_on_page((By.ID, "db_submit")).click() self.assertTrue(self.check_element_on_page((By.ID, 'flash_success'))) # check shelf is still there self.list_shelfs("database")['ele'].click() book_shelf = self.get_shelf_books_displayed() self.assertEqual(1, len(book_shelf)) # copy database to different location, move location, check shelf is still there alt_location = os.path.abspath(os.path.join(TEST_DB, "..", "alternate")) os.makedirs(alt_location, exist_ok=True) shutil.copy(os.path.join(TEST_DB, "metadata.db"), os.path.join(alt_location, "metadata.db")) self.fill_db_config({'config_calibre_dir': alt_location}) self.assertTrue(self.check_element_on_page((By.ID, 'flash_success'))) # check shelf is still there self.list_shelfs("database")['ele'].click() book_shelf = self.get_shelf_books_displayed() self.assertEqual(1, len(book_shelf)) os.remove(os.path.join(alt_location, "metadata.db")) os.rmdir(alt_location) self.delete_shelf("database") self.assertTrue(self.check_element_on_page((By.ID, 'flash_success'))) self.stop_calibre_web(p1) try: self.driver.switch_to.alert.accept() except Exception: pass
def test_cli_SSL_files(self): os.chdir(os.path.dirname(__file__)) shutil.rmtree(os.path.join(CALIBRE_WEB_PATH, 'hü lo'), ignore_errors=True) path_like_file = CALIBRE_WEB_PATH only_path = CALIBRE_WEB_PATH + os.sep real_key_file = os.path.join(CALIBRE_WEB_PATH, 'hü lo', 'lö g.key') real_crt_file = os.path.join(CALIBRE_WEB_PATH, 'hü lo', 'lö g.crt') p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-c', path_like_file ], [1, 3]) time.sleep(2) nextline = p.communicate()[0] if p.poll() is None: p.kill() self.assertIsNotNone( re.findall('Certfilepath is invalid. Exiting', nextline)) p.terminate() p.stdout.close() p.stderr.close() p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-k', path_like_file ], [1, 3]) time.sleep(2) nextline = p.communicate()[0] if p.poll() is None: p.kill() self.assertIsNotNone( re.findall('Keyfilepath is invalid. Exiting', nextline)) p.terminate() p.stdout.close() p.stderr.close() p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-c', only_path ], [1, 3]) time.sleep(2) nextline = p.communicate()[0] if p.poll() is None: p.kill() self.assertIsNotNone( re.findall('Certfilepath is invalid. Exiting', nextline)) p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-k', only_path ], [1, 3]) time.sleep(2) nextline = p.communicate()[0] if p.poll() is None: p.kill() self.assertIsNotNone( re.findall('Keyfilepath is invalid. Exiting', nextline)) p.terminate() p.stdout.close() p.stderr.close() p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-c', real_crt_file ], (1, 3)) time.sleep(2) if p.poll() is None: p.kill() nextline = p.communicate()[0] self.assertIsNotNone( re.findall('Certfilepath is invalid. Exiting', nextline)) p.terminate() p.stdout.close() p.stderr.close() p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-k', real_key_file ], (1, 3)) time.sleep(2) if p.poll() is None: p.kill() nextline = p.communicate()[0] self.assertIsNotNone( re.findall('Keyfilepath is invalid. Exiting', nextline)) p.terminate() p.stdout.close() p.stderr.close() os.makedirs(os.path.join(CALIBRE_WEB_PATH, 'hü lo')) with open(real_key_file, 'wb') as fout: fout.write(os.urandom(124)) with open(real_crt_file, 'wb') as fout: fout.write(os.urandom(124)) p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-c', real_crt_file ], (1, 3)) time.sleep(2) if p.poll() is None: p.kill() nextline = p.communicate()[0] self.assertIsNotNone( re.findall( 'Certfile and Keyfile have to be used together. Exiting', nextline)) p.terminate() p.stdout.close() p.stderr.close() p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-k', real_key_file ], (1, 3)) time.sleep(2) if p.poll() is None: p.kill() nextline = p.communicate()[0] self.assertIsNotNone( re.findall( 'Certfile and Keyfile have to be used together. Exiting', nextline)) p.terminate() p.stdout.close() p.stderr.close() p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-c', real_crt_file, '-k', real_key_file ], (1, 3, 5)) if p.poll() is not None: self.assertIsNone('Fail', 'Unexpected error') p.kill() p.terminate() p.stdout.close() p.stderr.close() time.sleep(10) p.poll() # navigate to the application home page try: self.driver.get("https://127.0.0.1:8083") self.assertIsNone( "Error", "HTTPS Connection could established with wrong key/cert file") except WebDriverException as e: self.assertIsNotNone( re.findall('Reached error page: about:neterror?nssFailure', e.msg)) p.kill() p.stdout.close() p.stderr.close() shutil.rmtree(os.path.join(CALIBRE_WEB_PATH, 'hü lo'), ignore_errors=True) shutil.copytree('./files', os.path.join(CALIBRE_WEB_PATH, 'hü lo')) real_crt_file = os.path.join(CALIBRE_WEB_PATH, 'hü lo', 'server.crt') real_key_file = os.path.join(CALIBRE_WEB_PATH, 'hü lo', 'server.key') p = process_open([ self.py_version, "-B", os.path.join(CALIBRE_WEB_PATH, u'cps.py'), '-c', real_crt_file, '-k', real_key_file ], (1, 3, 5)) if p.poll() is not None: self.assertIsNone('Fail', 'Unexpected error') time.sleep(10) # navigate to the application home page try: self.driver.get("https://127.0.0.1:8083") except WebDriverException: self.assertIsNone( "Error", "HTTPS Connection could not established with key/cert file") shutil.rmtree(os.path.join(CALIBRE_WEB_PATH, 'hü lo'), ignore_errors=True) self.assertTrue(self.check_element_on_page((By.ID, "username"))) p.terminate() p.stdout.close() p.stderr.close() time.sleep(3) p.poll()
def startup(inst, pyVersion, config, login=True, host="http://127.0.0.1:8083", env=None, parameter=None, work_path=None, only_startup=False, only_metadata=False): print("\n%s - %s: " % (inst.py_version, inst.__name__)) try: os.remove(os.path.join(CALIBRE_WEB_PATH, 'app.db')) except PermissionError: kill_dead_cps() time.sleep(5) try: os.remove(os.path.join(CALIBRE_WEB_PATH, 'app.db')) except Exception as e: print(e) except Exception as ex: print(ex) try: os.remove(os.path.join(CALIBRE_WEB_PATH, 'gdrive.db')) except PermissionError: time.sleep(5) try: os.remove(os.path.join(CALIBRE_WEB_PATH, 'gdrive.db')) except Exception as e: print(e) except Exception as ex: print(ex) try: os.chmod(TEST_DB, 0o764) except Exception: pass shutil.rmtree(TEST_DB, ignore_errors=True) thumbail_cache_path = os.path.join(CALIBRE_WEB_PATH, 'cps', 'cache') try: os.chmod(thumbail_cache_path, 0o764) except Exception as e: pass shutil.rmtree(thumbail_cache_path, ignore_errors=True) if not only_metadata: try: shutil.copytree(os.path.join(base_path, 'Calibre_db'), TEST_DB) except FileExistsError: print('Test DB already present, might not be a clean version') else: try: os.makedirs(TEST_DB) shutil.copy(os.path.join(base_path, 'Calibre_db', 'metadata.db'), os.path.join(TEST_DB, 'metadata.db')) except FileExistsError: print('Metadata.db already present, might not be a clean version') command = [pyVersion, os.path.join(CALIBRE_WEB_PATH, u'cps.py')] if parameter: command.extend(parameter) inst.p = process_open(command, [1], sout=None, env=env, cwd=work_path) # create a new Firefox session inst.driver = webdriver.Firefox() # inst.driver = webdriver.Chrome() time.sleep(BOOT_TIME) if inst.p.poll(): kill_old_cps() inst.p = process_open(command, [1], sout=None, env=env, cwd=work_path) print('Calibre-Web restarted...') time.sleep(BOOT_TIME) inst.driver.maximize_window() # navigate to the application home page inst.driver.get(host) WebDriverWait(inst.driver, 5).until(EC.title_contains("Calibre-Web")) if not only_startup: # Wait for config screen to show up inst.fill_db_config(dict(config_calibre_dir=config['config_calibre_dir'])) del config['config_calibre_dir'] # wait for cw to reboot time.sleep(5) try: WebDriverWait(inst.driver, 5).until(EC.presence_of_element_located((By.ID, "flash_success"))) except Exception: pass if config: inst.fill_basic_config(config) time.sleep(BOOT_TIME) try: WebDriverWait(inst.driver, 5).until(EC.presence_of_element_located((By.ID, "flash_success"))) except Exception: pass # login if not login: inst.logout()