def test_verbose_logging(caplog): client = Client(VERBOSE_RESPONSE_LOGGING=True, VERIFY_WEBUI_CERTIFICATE=False) with caplog.at_level(logging.DEBUG, logger="qbittorrentapi"): with pytest.raises(exceptions.NotFound404Error): client.torrents_rename(hash="asdf", new_torrent_name="erty") assert "Response status" in caplog.text
def user_login(self): try: ip = self.var_ip.get() port = self.var_port.get() name = self.var_name.get() pwd = self.var_pwd.get() qb = Client(host='http://{ip}:{port}'.format(ip=ip, port=port), username=name, password=pwd) # 测试是否通过 qb.app_version() self.controller.qb = qb self.controller.login_statu = True with open(USER_INFO_PATH, "wb") as usr_file: # with open with语句可以自动关闭资源 usrs_info = { "ip": ip, 'port': port, 'name': name, 'pwd': pwd } # 以字典的形式保存账户和密码 pickle.dump(usrs_info, usr_file) except Exception as exc: tk.messagebox.showerror('Error', '登录失败:%s' % exc)
def test_request_retry_skip(caplog): client = Client(VERIFY_WEBUI_CERTIFICATE=False) _ = client.app.version # do the login first with caplog.at_level(logging.DEBUG, logger="qbittorrentapi"): with pytest.raises(exceptions.MissingRequiredParameters400Error): client.torrents_rename() assert "Retry attempt" not in caplog.text
def test_http401(): client = Client(VERIFY_WEBUI_CERTIFICATE=False) _ = client.app.version # ensure cross site scripting protection is enabled client.app.preferences = dict(web_ui_csrf_protection_enabled=True) # simulate a XSS request with pytest.raises(Unauthorized401Error): client.app_version(headers={"X-Forwarded-Host": "http://example.com"})
def test_http401(): client = Client() _ = client.app.version # ensure cross site scripting protection is enabled client.app.preferences = dict(web_ui_csrf_protection_enabled=True) # simulate a XSS request with pytest.raises(Unauthorized401Error): client.app_version(headers={'X-Forwarded-Host': 'http://example.com'})
def __init__(self, host, username, password, name): self.host = host self.username = username self.password = password self._name = name self.qb = Client(host=self.host, username=self.username, password=self.password) self.signin()
def pytest_sessionfinish(session, exitstatus): try: if 'TRAVIS' not in environ: client = Client() # remove all torrents for torrent in client.torrents_info(): client.torrents_delete(delete_files=True, torrent_hashes=torrent.hash) except: pass
def __init__(self, config): self.config = config self.torrents = None self.client = Client( host=config["host"], port=config["port"], username=config["username"], password=config["password"], )
def test_disable_logging(): _ = Client(DISABLE_LOGGING_DEBUG_OUTPUT=False) assert logging.getLogger("qbittorrentapi").level == logging.NOTSET assert logging.getLogger("requests").level == logging.NOTSET assert logging.getLogger("urllib3").level == logging.NOTSET _ = Client(DISABLE_LOGGING_DEBUG_OUTPUT=True) assert logging.getLogger("qbittorrentapi").level == logging.INFO assert logging.getLogger("requests").level == logging.INFO assert logging.getLogger("urllib3").level == logging.INFO
def pytest_sessionfinish(session, exitstatus): try: if environ.get("CI") != "true": client = Client() # remove all torrents for torrent in client.torrents_info(): client.torrents_delete(delete_files=True, torrent_hashes=torrent.hash) except: pass
def test_api_connection_error(): with pytest.raises(APIConnectionError): Client(host="localhost:8081").auth_log_in(_retries=0) with pytest.raises(APIConnectionError): Client(host="localhost:8081").auth_log_in(_retries=1) with pytest.raises(APIConnectionError): Client(host="localhost:8081").auth_log_in(_retries=2) with pytest.raises(APIConnectionError): Client(host="localhost:8081").auth_log_in(_retries=3)
def test_request_retry_success(monkeypatch, caplog): def request500(*arg, **kwargs): raise exceptions.HTTP500Error() client = Client(VERIFY_WEBUI_CERTIFICATE=False) _ = client.app.version # do the login first with monkeypatch.context() as m: m.setattr(client, "_request", request500) with caplog.at_level(logging.DEBUG, logger="qbittorrentapi"): with pytest.raises(exceptions.HTTP500Error): client.app_version() assert "Retry attempt" in caplog.text
def test_login_required(caplog, app_version): client = Client( RAISE_NOTIMPLEMENTEDERROR_FOR_UNIMPLEMENTED_API_ENDPOINTS=True) with caplog.at_level(logging.DEBUG, logger='qbittorrentapi'): qbt_version = client.app.version assert 'Not logged in...attempting login' in caplog.text assert qbt_version == app_version client.auth_log_out() with caplog.at_level(logging.DEBUG, logger='qbittorrentapi'): qbt_version = client.app.version assert 'Not logged in...attempting login' in caplog.text assert qbt_version == app_version
def test_verify_cert(api_version): client = Client(VERIFY_WEBUI_CERTIFICATE=False) assert client._VERIFY_WEBUI_CERTIFICATE is False assert client.app.web_api_version == api_version client = Client(VERIFY_WEBUI_CERTIFICATE=True) assert client._VERIFY_WEBUI_CERTIFICATE is True assert client.app.web_api_version == api_version environ['PYTHON_QBITTORRENTAPI_DO_NOT_VERIFY_WEBUI_CERTIFICATE'] = 'true' client = Client(VERIFY_WEBUI_CERTIFICATE=True) assert client._VERIFY_WEBUI_CERTIFICATE is False assert client.app.web_api_version == api_version
def test_requests_timeout(): # timeouts are weird on python 2...just skip it... if sys.version_info[0] < 3: return class MyTimeoutError(Exception): pass logger = logging.getLogger("test_requests_timeout") timeout = 1e-100 loops = 1000 client = Client(VERIFY_WEBUI_CERTIFICATE=False) with pytest.raises(MyTimeoutError): try: for _ in range(loops): client.torrents_info(requests_args={"timeout": timeout}) except exceptions.APIConnectionError as exp: logger.error("%r", exp) if "ReadTimeoutError" in str(exp) or "RemoteDisconnected" in str( exp): raise MyTimeoutError client = Client(VERIFY_WEBUI_CERTIFICATE=False, REQUESTS_ARGS={"timeout": timeout}) with pytest.raises(MyTimeoutError): try: for _ in range(loops): client.torrents_info() except exceptions.APIConnectionError as exp: logger.error("%r", exp) if "ReadTimeoutError" in str(exp) or "RemoteDisconnected" in str( exp): raise MyTimeoutError
def test_unsupported_version_error(): client = Client( MOCK_WEB_API_VERSION="0.0.0", VERIFY_WEBUI_CERTIFICATE=False, RAISE_ERROR_FOR_UNSUPPORTED_QBITTORRENT_VERSIONS=True, ) with pytest.raises(exceptions.UnsupportedQbittorrentVersion): _ = client.app.version client = Client( VERIFY_WEBUI_CERTIFICATE=False, RAISE_ERROR_FOR_UNSUPPORTED_QBITTORRENT_VERSIONS=True, ) _ = client.app.version
def test_verify_cert(api_version): client = Client(VERIFY_WEBUI_CERTIFICATE=False) assert client._VERIFY_WEBUI_CERTIFICATE is False assert client.app.web_api_version == api_version # this is only ever going to work with a trusted cert....disabling for now # client = Client(VERIFY_WEBUI_CERTIFICATE=True) # assert client._VERIFY_WEBUI_CERTIFICATE is True # assert client.app.web_api_version == api_version environ["PYTHON_QBITTORRENTAPI_DO_NOT_VERIFY_WEBUI_CERTIFICATE"] = "true" client = Client(VERIFY_WEBUI_CERTIFICATE=True) assert client._VERIFY_WEBUI_CERTIFICATE is False assert client.app.web_api_version == api_version
def test_login_required(caplog, app_version): client = Client( RAISE_NOTIMPLEMENTEDERROR_FOR_UNIMPLEMENTED_API_ENDPOINTS=True, VERIFY_WEBUI_CERTIFICATE=False, ) with caplog.at_level(logging.DEBUG, logger="qbittorrentapi"): qbt_version = client.app.version assert "Not logged in...attempting login" in caplog.text assert qbt_version == app_version client.auth_log_out() with caplog.at_level(logging.DEBUG, logger="qbittorrentapi"): qbt_version = client.app.version assert "Not logged in...attempting login" in caplog.text assert qbt_version == app_version
def test_hostname_format(app_version, hostname): client = Client(host=hostname, VERIFY_WEBUI_CERTIFICATE=False, REQUESTS_ARGS={"timeout": 1}) assert client.app.version == app_version # ensure the base URL is always normalized assert re.match(r"(http|https)://localhost:8080/", client._API_BASE_URL)
def test_hostname_user_base_path(hostname): client = Client(host=hostname, VERIFY_WEBUI_CERTIFICATE=False) # the command will fail but the URL will be built with pytest.raises(APIConnectionError): _ = client.app.version # ensure user provided base paths are preserved assert re.match(r"(http|https)://localhost:8080/qbt/", client._API_BASE_URL)
def _get_client(self): with DBSession() as db: cred = db.query(QBittorrentCredentials).first() if not cred: return False if not cred.port: cred.port = self.DEFAULT_PORT address = self.ADDRESS_FORMAT.format(cred.host, cred.port) client = Client(host=address, username=cred.username, password=cred.password) client.app_version() return client
def test_log_in(): client_good = Client() client_bad = Client(username='******', password='******') assert client_good.auth_log_in() is None with pytest.raises(LoginFailed): client_bad.auth_log_in()
def test_log_in(): client_good = Client(VERIFY_WEBUI_CERTIFICATE=False) client_bad = Client( username="******", password="******", VERIFY_WEBUI_CERTIFICATE=False ) assert client_good.auth_log_in() is None with pytest.raises(LoginFailed): client_bad.auth_log_in()
def test_log_in_via_auth(): client_good = Client() client_bad = Client(username='******', password='******') assert client_good.auth_log_in( username=environ.get('PYTHON_QBITTORRENTAPI_USERNAME'), password=environ.get('PYTHON_QBITTORRENTAPI_PASSWORD')) is None with pytest.raises(LoginFailed): client_bad.auth_log_in(username='******', password='******')
def test_force_user_scheme(client, app_version, use_https): default_host = environ["PYTHON_QBITTORRENTAPI_HOST"] _enable_disable_https(client, use_https) client = Client( host="http://" + default_host, VERIFY_WEBUI_CERTIFICATE=False, FORCE_SCHEME_FROM_HOST=True, REQUESTS_ARGS={"timeout": 3}, ) if use_https: with pytest.raises(exceptions.APIConnectionError): assert client.app.version == app_version else: assert client.app.version == app_version assert client._API_BASE_URL.startswith("http://") client = Client( host=default_host, VERIFY_WEBUI_CERTIFICATE=False, FORCE_SCHEME_FROM_HOST=True, REQUESTS_ARGS={"timeout": 3}, ) assert client.app.version == app_version if use_https: assert client._API_BASE_URL.startswith("https://") else: assert client._API_BASE_URL.startswith("http://") client = Client( host="https://" + default_host, VERIFY_WEBUI_CERTIFICATE=False, FORCE_SCHEME_FROM_HOST=True, REQUESTS_ARGS={"timeout": 3}, ) if not use_https: with pytest.raises(exceptions.APIConnectionError): assert client.app.version == app_version else: assert client.app.version == app_version assert client._API_BASE_URL.startswith("https://")
def get_client(self): """ Returns a client to qbittorrent """ client = Client(host=self.host, port=self.port, username=self.user, password=self.password) try: client.auth_log_in() LOGGER.info("Successfully connected to qbittorrent") except exceptions.LoginFailed as login_exn: LOGGER.error("Failed to login to qbittorrent") raise QbitError except exceptions.Forbidden403Error as forbid_exn: LOGGER.error("403 error on qbittorrent") raise QbitError except exceptions.APIConnectionError: LOGGER.error("Failed to connect to Qbittorrent") raise QbitError return client
class qbittorrent_alternative_speed(SwitchEntity): def __init__(self, host, username, password, name): self.host = host self.username = username self.password = password self._name = name self.qb = Client(host=self.host, username=self.username, password=self.password) self.signin() def signin(self): self.qb.auth_log_in() self._state = int(self.qb.transfer.speed_limits_mode) @property def name(self): return self._name @property def is_on(self): return (self._state == 1) def update(self): try: self._state = int(self.qb.transfer.speed_limits_mode) except: self.signin() return def turn_on(self): self.update() if (self._state == 0): self.qb.transfer.toggle_speed_limits_mode() def turn_off(self): self.update() if (self._state == 1): self.qb.transfer.toggle_speed_limits_mode()
def test_log_in_via_auth(): client_good = Client(VERIFY_WEBUI_CERTIFICATE=False) client_bad = Client(username="******", password="******", VERIFY_WEBUI_CERTIFICATE=False) assert (client_good.auth_log_in( username=environ.get("PYTHON_QBITTORRENTAPI_USERNAME"), password=environ.get("PYTHON_QBITTORRENTAPI_PASSWORD"), ) is None) with pytest.raises(exceptions.LoginFailed): client_bad.auth_log_in(username="******", password="******")
def test_both_https_http_not_working(client, app_version, scheme): default_host = environ["PYTHON_QBITTORRENTAPI_HOST"] _enable_disable_https(client, use_https=True) # rerun with verify=True test_client = Client( host=scheme + default_host, REQUESTS_ARGS={"timeout": 3}, ) with pytest.raises(exceptions.APIConnectionError): assert test_client.app.version == app_version assert test_client._API_BASE_URL.startswith("https://") _enable_disable_https(client, use_https=False)
def __init__(self): super().__init__() with open(Path(__file__).parent / 'qbittorrent_config.txt') as file: qbt_config = json.load(file) self.qbt_client = Client(**qbt_config) self.log_path = Path(gettempdir()) / 'znp_logs/' self.free_space_w = urwid.Filler(urwid.Text('')) self.torrents_stats_w = urwid.Text('') self.transiting_torrents_column1 = urwid.Text('', wrap=urwid.CLIP) self.transiting_torrents_column2 = urwid.Text('', align=urwid.RIGHT, wrap=urwid.CLIP) self.footer_w = urwid.Filler( urwid.Text('', align=urwid.RIGHT, wrap=urwid.CLIP))