Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(exceptions): separate failed signin error #1478

Open
wants to merge 3 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions tableauserverclient/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
PDFRequestOptions,
RequestOptions,
MissingRequiredFieldError,
FailedSignInError,
NotSignedInError,
ServerResponseError,
Filter,
Expand All @@ -79,6 +80,7 @@
"DatabaseItem",
"DataFreshnessPolicyItem",
"DatasourceItem",
"FailedSignInError",
"FavoriteItem",
"FlowItem",
"FlowRunItem",
Expand Down
8 changes: 3 additions & 5 deletions tableauserverclient/models/server_info_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,11 @@ def from_response(cls, resp, ns):
try:
parsed_response = fromstring(resp)
except xml.etree.ElementTree.ParseError as error:
logger.info(f"Unexpected response for ServerInfo: {resp}")
logger.info(error)
logger.exception(f"Unexpected response for ServerInfo: {resp}")
return cls("Unknown", "Unknown", "Unknown")
except Exception as error:
logger.info(f"Unexpected response for ServerInfo: {resp}")
logger.info(error)
return cls("Unknown", "Unknown", "Unknown")
logger.exception(f"Unexpected response for ServerInfo: {resp}")
raise error

product_version_tag = parsed_response.find(".//t:productVersion", namespaces=ns)
rest_api_version_tag = parsed_response.find(".//t:restApiVersion", namespaces=ns)
Expand Down
3 changes: 2 additions & 1 deletion tableauserverclient/server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from tableauserverclient.server.sort import Sort
from tableauserverclient.server.server import Server
from tableauserverclient.server.pager import Pager
from tableauserverclient.server.endpoint.exceptions import NotSignedInError
from tableauserverclient.server.endpoint.exceptions import FailedSignInError, NotSignedInError

from tableauserverclient.server.endpoint import (
Auth,
Expand Down Expand Up @@ -57,6 +57,7 @@
"Sort",
"Server",
"Pager",
"FailedSignInError",
"NotSignedInError",
"Auth",
"CustomViews",
Expand Down
3 changes: 2 additions & 1 deletion tableauserverclient/server/endpoint/endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from tableauserverclient.server.request_options import RequestOptions

from tableauserverclient.server.endpoint.exceptions import (
FailedSignInError,
ServerResponseError,
InternalServerError,
NonXMLResponseError,
Expand Down Expand Up @@ -160,7 +161,7 @@ def _check_status(self, server_response: "Response", url: Optional[str] = None):
try:
if server_response.status_code == 401:
# TODO: catch this in server.py and attempt to sign in again, in case it's a session expiry
raise NotSignedInError(server_response.content, url)
raise FailedSignInError.from_response(server_response.content, self.parent_srv.namespace, url)

raise ServerResponseError.from_response(server_response.content, self.parent_srv.namespace, url)
except ParseError:
Expand Down
24 changes: 20 additions & 4 deletions tableauserverclient/server/endpoint/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
from defusedxml.ElementTree import fromstring
from typing import Optional
from typing import Mapping, Optional, TypeVar


def split_pascal_case(s: str) -> str:
return "".join([f" {c}" if c.isupper() else c for c in s]).strip()


class TableauError(Exception):
pass


class ServerResponseError(TableauError):
def __init__(self, code, summary, detail, url=None):
T = TypeVar("T")


class XMLError(TableauError):
def __init__(self, code: str, summary: str, detail: str, url: Optional[str] = None) -> None:
self.code = code
self.summary = summary
self.detail = detail
Expand All @@ -18,7 +25,7 @@ def __str__(self):
return f"\n\n\t{self.code}: {self.summary}\n\t\t{self.detail}"

@classmethod
def from_response(cls, resp, ns, url=None):
def from_response(cls, resp, ns, url):
# Check elements exist before .text
parsed_response = fromstring(resp)
try:
Expand All @@ -33,6 +40,10 @@ def from_response(cls, resp, ns, url=None):
return error_response


class ServerResponseError(XMLError):
pass


class InternalServerError(TableauError):
def __init__(self, server_response, request_url: Optional[str] = None):
self.code = server_response.status_code
Expand All @@ -51,6 +62,11 @@ class NotSignedInError(TableauError):
pass


class FailedSignInError(XMLError, NotSignedInError):
def __str__(self):
return f"{split_pascal_case(self.__class__.__name__)}: {super().__str__()}"


class ItemTypeNotAllowed(TableauError):
pass

Expand Down
56 changes: 56 additions & 0 deletions test/assets/server_info_wrong_site.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example website</title>
</head>

<body>
<table>
<th>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
<td>E</td>
</th>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
</body>

</html>
6 changes: 3 additions & 3 deletions test/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,23 +63,23 @@ def test_sign_in_error(self):
with requests_mock.mock() as m:
m.post(self.baseurl + "/signin", text=response_xml, status_code=401)
tableau_auth = TSC.TableauAuth("testuser", "wrongpassword")
self.assertRaises(TSC.NotSignedInError, self.server.auth.sign_in, tableau_auth)
self.assertRaises(TSC.FailedSignInError, self.server.auth.sign_in, tableau_auth)

def test_sign_in_invalid_token(self):
with open(SIGN_IN_ERROR_XML, "rb") as f:
response_xml = f.read().decode("utf-8")
with requests_mock.mock() as m:
m.post(self.baseurl + "/signin", text=response_xml, status_code=401)
tableau_auth = TSC.PersonalAccessTokenAuth(token_name="mytoken", personal_access_token="invalid")
self.assertRaises(TSC.NotSignedInError, self.server.auth.sign_in, tableau_auth)
self.assertRaises(TSC.FailedSignInError, self.server.auth.sign_in, tableau_auth)

def test_sign_in_without_auth(self):
with open(SIGN_IN_ERROR_XML, "rb") as f:
response_xml = f.read().decode("utf-8")
with requests_mock.mock() as m:
m.post(self.baseurl + "/signin", text=response_xml, status_code=401)
tableau_auth = TSC.TableauAuth("", "")
self.assertRaises(TSC.NotSignedInError, self.server.auth.sign_in, tableau_auth)
self.assertRaises(TSC.FailedSignInError, self.server.auth.sign_in, tableau_auth)

def test_sign_out(self):
with open(SIGN_IN_XML, "rb") as f:
Expand Down
10 changes: 10 additions & 0 deletions test/test_server_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
import requests_mock

import tableauserverclient as TSC
from tableauserverclient.server.endpoint.exceptions import NonXMLResponseError

TEST_ASSET_DIR = os.path.join(os.path.dirname(__file__), "assets")

SERVER_INFO_GET_XML = os.path.join(TEST_ASSET_DIR, "server_info_get.xml")
SERVER_INFO_25_XML = os.path.join(TEST_ASSET_DIR, "server_info_25.xml")
SERVER_INFO_404 = os.path.join(TEST_ASSET_DIR, "server_info_404.xml")
SERVER_INFO_AUTH_INFO_XML = os.path.join(TEST_ASSET_DIR, "server_info_auth_info.xml")
SERVER_INFO_WRONG_SITE = os.path.join(TEST_ASSET_DIR, "server_info_wrong_site.html")


class ServerInfoTests(unittest.TestCase):
Expand Down Expand Up @@ -63,3 +65,11 @@ def test_server_use_server_version_flag(self):
m.get("http://test/api/2.4/serverInfo", text=si_response_xml)
server = TSC.Server("http://test", use_server_version=True)
self.assertEqual(server.version, "2.5")

def test_server_wrong_site(self):
with open(SERVER_INFO_WRONG_SITE, "rb") as f:
response = f.read().decode("utf-8")
with requests_mock.mock() as m:
m.get(self.server.server_info.baseurl, text=response, status_code=404)
with self.assertRaises(NonXMLResponseError):
self.server.server_info.get()
Loading