This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new 849bbb1cc0 [python] Add read-only semantic view APIs to RESTCatalog 
(#11343)
849bbb1cc0 is described below

commit 849bbb1cc06212cb8f8640f3f9d451b69b05ec68
Author: QuakeWang <[email protected]>
AuthorDate: Sun Nov 22 18:51:39 2026 +0800

    [python] Add read-only semantic view APIs to RESTCatalog (#11343)
---
 paimon-python/pypaimon/api/api_response.py         |  39 ++++
 paimon-python/pypaimon/api/client.py               |  38 +++-
 paimon-python/pypaimon/api/resource_paths.py       |  22 ++
 paimon-python/pypaimon/api/rest_api.py             |  38 +++-
 .../pypaimon/catalog/rest/rest_catalog.py          |  19 +-
 .../pypaimon/tests/rest/rest_semantic_view_test.py | 227 +++++++++++++++++++++
 6 files changed, 370 insertions(+), 13 deletions(-)

diff --git a/paimon-python/pypaimon/api/api_response.py 
b/paimon-python/pypaimon/api/api_response.py
index 67609852af..9c895817b7 100644
--- a/paimon-python/pypaimon/api/api_response.py
+++ b/paimon-python/pypaimon/api/api_response.py
@@ -24,6 +24,7 @@ from pypaimon.common.identifier import Identifier
 from pypaimon.common.json_util import T, json_field, optional_json_field
 from pypaimon.common.options import Options
 from pypaimon.management.data_policy import DataPolicy
+from pypaimon.management.java_string import is_blank
 from pypaimon.management.permission_assignment import PermissionAssignment
 from pypaimon.schema.data_types import DataField
 from pypaimon.schema.schema import Schema
@@ -631,6 +632,44 @@ class 
ListFunctionsGloballyResponse(PagedResponse[Identifier]):
         return result
 
 
+@dataclass
+class SemanticViewDefinition:
+    format: str
+    content: str
+
+    def __post_init__(self):
+        if not isinstance(self.format, str) or is_blank(self.format):
+            raise ValueError("Semantic view format must not be blank")
+        if not isinstance(self.content, str) or is_blank(self.content):
+            raise ValueError("Semantic view content must not be blank")
+        if len(self.content.encode('utf-8')) > 1024 * 1024:
+            raise ValueError("Semantic view content must not exceed 1 MiB in 
UTF-8")
+
+
+@dataclass
+class GetSemanticViewResponse(RESTResponse):
+    name: str
+    definition: SemanticViewDefinition
+
+    def __post_init__(self):
+        if not isinstance(self.name, str) or is_blank(self.name):
+            raise ValueError("Semantic view name must not be blank")
+        if self.definition is None:
+            raise ValueError("Semantic view definition must not be null")
+
+
+@dataclass
+class ListSemanticViewsResponse(PagedResponse[str]):
+    semantic_views: Optional[List[str]] = json_field("semanticViews", 
default=None)
+    next_page_token: Optional[str] = 
json_field(PagedResponse.FIELD_NEXT_PAGE_TOKEN, default=None)
+
+    def data(self) -> List[str]:
+        return self.semantic_views or []
+
+    def get_next_page_token(self) -> Optional[str]:
+        return self.next_page_token
+
+
 @dataclass
 class AuthTableQueryRequest(RESTRequest):
     select: Optional[List[str]] = json_field("select", default=None)
diff --git a/paimon-python/pypaimon/api/client.py 
b/paimon-python/pypaimon/api/client.py
index d2c179e718..3a27b771f9 100644
--- a/paimon-python/pypaimon/api/client.py
+++ b/paimon-python/pypaimon/api/client.py
@@ -324,12 +324,19 @@ class HttpClient(RESTClient):
 
     def get_with_params(self, path: str, query_params: Dict[str, str],
                         response_type: Type[T],
-                        rest_auth_function: Callable[[RESTAuthParameter], 
Dict[str, str]]) -> T:
+                        rest_auth_function: Callable[[RESTAuthParameter], 
Dict[str, str]],
+                        *, preserve_encoded_dots: bool = False) -> T:
         auth_headers = _get_headers(path, "GET", query_params, None, 
rest_auth_function)
         url = self._get_request_url(path, query_params)
-
+        encoded_dot_segments = None
+        if preserve_encoded_dots:
+            encoded_dot_segments = {
+                offset: segment
+                for offset, segment in enumerate(reversed(path.split('/')), 
start=1)
+                if segment in ('%2E', '%2E%2E')
+            }
         return self._execute_request("GET", url, headers=auth_headers,
-                                     response_type=response_type)
+                                     response_type=response_type, 
encoded_dot_segments=encoded_dot_segments)
 
     def post(self, path: str, body: RESTRequest,
              rest_auth_function: Callable[[RESTAuthParameter], Dict[str, 
str]]) -> T:
@@ -386,16 +393,25 @@ class HttpClient(RESTClient):
     def _execute_request(self, method: str, url: str,
                          data: Optional[str] = None,
                          headers: Optional[Dict[str, str]] = None,
-                         response_type: Optional[Type[T]] = None) -> T:
+                         response_type: Optional[Type[T]] = None,
+                         encoded_dot_segments: Optional[Dict[int, str]] = 
None) -> T:
         try:
             start_time = int(time.time() * 1_000_000_000)
-            response = self.session.request(
-                method=method,
-                url=url,
-                data=data.encode('utf-8') if data else None,
-                headers=headers,
-                timeout=self._timeout,
-            )
+            payload = data.encode('utf-8') if data else None
+            if encoded_dot_segments:
+                prepared = 
self.session.prepare_request(requests.Request(method, url, headers=headers, 
data=payload))
+                prepared_url = urllib.parse.urlsplit(prepared.url)
+                segments = prepared_url.path.split('/')
+                # Requests unescapes encoded dots. Restore only the signed 
resource segments,
+                # counting from the end so normalization of the base URI 
remains intact.
+                for offset, segment in encoded_dot_segments.items():
+                    segments[-offset] = segment
+                prepared.url = 
prepared_url._replace(path='/'.join(segments)).geturl()
+                settings = 
self.session.merge_environment_settings(prepared.url, {}, None, None, None)
+                response = self.session.send(prepared, timeout=self._timeout, 
**settings)
+            else:
+                response = self.session.request(method=method, url=url, 
data=payload, headers=headers,
+                                                timeout=self._timeout)
             duration_ms = (int(time.time() * 1_000_000_000) - start_time) // 
1_000_000
             response_request_id = response.headers.get(self.REQUEST_ID_KEY, 
self.DEFAULT_REQUEST_ID)
 
diff --git a/paimon-python/pypaimon/api/resource_paths.py 
b/paimon-python/pypaimon/api/resource_paths.py
index 807744132a..ce100a320e 100644
--- a/paimon-python/pypaimon/api/resource_paths.py
+++ b/paimon-python/pypaimon/api/resource_paths.py
@@ -21,6 +21,7 @@ from typing import Optional
 from pypaimon.api.rest_util import RESTUtil
 from pypaimon.common.options import Options
 from pypaimon.common.options.config import CatalogOptions
+from pypaimon.management.java_string import is_blank
 
 
 class ResourcePaths:
@@ -33,6 +34,7 @@ class ResourcePaths:
     FUNCTIONS = "functions"
     FUNCTION_DETAILS = "function-details"
     MODELS = "models"
+    SEMANTIC_VIEWS = "semantic-views"
     TAGS = "tags"
     BRANCHES = "branches"
     FORWARD = "forward"
@@ -45,6 +47,8 @@ class ResourcePaths:
         if prefix:
             prefix = urllib.parse.quote_plus(prefix, safe="*~", 
errors="replace")
         self.base_path = "/{}/{}".format(self.V1, prefix).rstrip("/")
+        # Semantic view requests preserve encoded dot segments in the HTTP 
client.
+        self._semantic_view_base_path = "/{}/{}".format(self.V1, 
self._escape_dot_segment(prefix)).rstrip("/")
 
     @classmethod
     def for_catalog_properties(
@@ -132,6 +136,24 @@ class ResourcePaths:
             self.models(database_name), RESTUtil.encode_string(model_name)
         )
 
+    @staticmethod
+    def _escape_dot_segment(segment: str) -> str:
+        return segment.replace(".", "%2E") if segment in (".", "..") else 
segment
+
+    def _semantic_view_segment(self, name: str, label: str) -> str:
+        if not isinstance(name, str) or is_blank(name):
+            raise ValueError("{} cannot be blank".format(label))
+        # Requests leaves '~' unescaped on the wire, so sign it in that form.
+        return 
self._escape_dot_segment(RESTUtil.encode_string(name).replace("%7E", "~"))
+
+    def semantic_views(self, database_name: str) -> str:
+        database = self._semantic_view_segment(database_name, "Database name")
+        return "{}/{}/{}/{}".format(self._semantic_view_base_path, 
self.DATABASES, database, self.SEMANTIC_VIEWS)
+
+    def semantic_view(self, database_name: str, view_name: str) -> str:
+        view = self._semantic_view_segment(view_name, "Semantic view name")
+        return "{}/{}".format(self.semantic_views(database_name), view)
+
     def tags(self, database_name: str, table_name: str) -> str:
         return "{}/{}/{}/{}/{}/{}".format(
             self.base_path, self.DATABASES, 
RESTUtil.encode_string(database_name),
diff --git a/paimon-python/pypaimon/api/rest_api.py 
b/paimon-python/pypaimon/api/rest_api.py
index cdd608f29c..f6515fa384 100755
--- a/paimon-python/pypaimon/api/rest_api.py
+++ b/paimon-python/pypaimon/api/rest_api.py
@@ -33,6 +33,7 @@ from pypaimon.api.api_request import (AlterDatabaseRequest, 
AlterFunctionRequest
 from pypaimon.api.api_response import (CommitTableResponse, ConfigResponse,
                                        ErrorResponse,
                                        GetDatabaseResponse, 
GetFunctionResponse,
+                                       GetSemanticViewResponse,
                                        GetTableResponse,
                                        GetTableTokenResponse, GetTagResponse,
                                        ListBranchesResponse,
@@ -42,6 +43,7 @@ from pypaimon.api.api_response import (CommitTableResponse, 
ConfigResponse,
                                        ListFunctionsResponse,
                                        ListPermissionsResponse,
                                        ListPoliciesResponse,
+                                       ListSemanticViewsResponse,
                                        CreatePartitionsResponse,
                                        ListPartitionsResponse,
                                        ListTablesResponse, ListTagsResponse,
@@ -54,7 +56,7 @@ from pypaimon.api.auth import AuthProviderFactory, 
RESTAuthFunction
 from pypaimon.api.client import HttpClient
 from pypaimon.api.model import CreateModelRequest, GetModelResponse, 
ListModelsResponse
 from pypaimon.api.resource_paths import ResourcePaths
-from pypaimon.api.rest_exception import NoSuchResourceException
+from pypaimon.api.rest_exception import NoSuchResourceException, RESTException
 from pypaimon.api.rest_util import RESTUtil
 from pypaimon.api.typedef import T
 from pypaimon.common import user_agent
@@ -746,6 +748,40 @@ class RESTApi:
             self.rest_auth_function,
         )
 
+    def get_semantic_view(self, identifier: Identifier) -> 
GetSemanticViewResponse:
+        if identifier is None:
+            raise ValueError("Identifier cannot be None")
+        response = self.client.get_with_params(
+            self.resource_paths.semantic_view(identifier.get_database_name(), 
identifier.get_object_name()),
+            {},
+            GetSemanticViewResponse,
+            self.rest_auth_function,
+            preserve_encoded_dots=True,
+        )
+        if response is None:
+            raise RESTException("Semantic view response must not be null")
+        return response
+
+    def list_semantic_views_paged(
+            self,
+            database_name: str,
+            max_results: Optional[int] = None,
+            page_token: Optional[str] = None,
+    ) -> PagedList[str]:
+        if max_results is not None and (
+                isinstance(max_results, bool) or not isinstance(max_results, 
int) or not 1 <= max_results <= 1000):
+            raise ValueError("max_results must be an integer between 1 and 
1000")
+        response = self.client.get_with_params(
+            self.resource_paths.semantic_views(database_name),
+            self.__build_paged_query_params(max_results, page_token, {}),
+            ListSemanticViewsResponse,
+            self.rest_auth_function,
+            preserve_encoded_dots=True,
+        )
+        if response is None:
+            raise RESTException("Semantic view list response must not be null")
+        return PagedList(response.data(), response.get_next_page_token())
+
     def list_models(self, database_name: str) -> List[GetModelResponse]:
         self._validate_resource_path_component(database_name, "Database name")
         return self.__list_data_from_page_api(
diff --git a/paimon-python/pypaimon/catalog/rest/rest_catalog.py 
b/paimon-python/pypaimon/catalog/rest/rest_catalog.py
index 79016b910b..a1eb336cb7 100644
--- a/paimon-python/pypaimon/catalog/rest/rest_catalog.py
+++ b/paimon-python/pypaimon/catalog/rest/rest_catalog.py
@@ -18,7 +18,9 @@
 import logging
 from copy import deepcopy
 from typing import Any, Callable, Dict, List, Optional, Union
-from pypaimon.api.api_response import ErrorResponse, GetTableResponse, 
GetTagResponse, PagedList, Partition
+from pypaimon.api.api_response import (
+    ErrorResponse, GetSemanticViewResponse, GetTableResponse, GetTagResponse, 
PagedList, Partition,
+)
 from pypaimon.api.model import CreateModelRequest
 from pypaimon.api.rest_api import RESTApi
 from pypaimon.api.rest_permission_management import RESTPermissionManagement
@@ -629,6 +631,21 @@ class RESTCatalog(Catalog):
         except NoSuchResourceException as e:
             raise DatabaseNotExistException(database_name) from e
 
+    def get_semantic_view(self, identifier: Union[str, Identifier]) -> 
GetSemanticViewResponse:
+        """Read the name and complete stored definition of a semantic view."""
+        if not isinstance(identifier, Identifier):
+            identifier = Identifier.from_string(identifier)
+        return self.rest_api.get_semantic_view(identifier)
+
+    def list_semantic_views_paged(
+            self,
+            database_name: str,
+            max_results: Optional[int] = None,
+            page_token: Optional[str] = None,
+    ) -> PagedList[str]:
+        """List one page of visible semantic view names and its continuation 
token."""
+        return self.rest_api.list_semantic_views_paged(database_name, 
max_results, page_token)
+
     def create_model(
             self,
             identifier: Union[str, Identifier],
diff --git a/paimon-python/pypaimon/tests/rest/rest_semantic_view_test.py 
b/paimon-python/pypaimon/tests/rest/rest_semantic_view_test.py
new file mode 100644
index 0000000000..b3ac917c87
--- /dev/null
+++ b/paimon-python/pypaimon/tests/rest/rest_semantic_view_test.py
@@ -0,0 +1,227 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import json
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+
+from pypaimon.api.rest_exception import (
+    BadRequestException, ForbiddenException, NoSuchResourceException, 
NotAuthorizedException,
+    NotImplementedException, RESTException, ServiceFailureException,
+)
+from pypaimon.common.identifier import Identifier
+from pypaimon.tests.rest import rest_branch_transport_test as transport
+
+
+transport_server = transport.transport_server
+BASE_PATH = '/v1/catalog%2Fid/databases'
+
+
[email protected]
+def catalog(transport_server):
+    transport_server.require_v4 = True
+    catalog = transport.transport_catalog(transport_server, **{
+        'prefix': 'catalog/id', 'token.provider': 'dlf', 'dlf.region': 
'cn-hangzhou',
+        'dlf.signing-algorithm': 'openapi-v4', 'dlf.access-key-id': 'test-key',
+        'dlf.access-key-secret': 'test-secret', 'dlf.security-token': 
'test-sts',
+    })
+    transport_server.requests.clear()
+    transport_server.bodies.clear()
+    return catalog
+
+
[email protected]('identifier,path', [
+    ('sales.order.metrics', '/sales/semantic-views/order.metrics'),
+    (Identifier.create('sales /\u534e+%', 'model.a/b+% ?#~'),
+     '/sales+%2F%E5%8D%8E%2B%25/semantic-views/model.a%2Fb%2B%25+%3F%23~'),
+    (Identifier.create('.', '..'), '/%2E/semantic-views/%2E%2E'),
+    (Identifier.create('..', '%2E'), '/%2E%2E/semantic-views/%252E'),
+    (Identifier.create('\u00a0', 'revenue'), '/%C2%A0/semantic-views/revenue'),
+])
+def test_get_semantic_view(catalog, transport_server, identifier, path):
+    content = '# \u6307\u6807\r\nversion: 1\nfuture: {expr: "a + b\\c"}\n'
+    transport_server.respond = lambda *_: (200, json.dumps({
+        'name': 'returned-name', 'definition': {'format': 'provider-yaml', 
'content': content},
+    }))
+
+    view = catalog.get_semantic_view(identifier)
+
+    assert view.name == 'returned-name'
+    assert view.definition.format == 'provider-yaml'
+    assert view.definition.content == content
+    [(method, target, headers)] = transport_server.requests
+    assert (method, target) == ('GET', BASE_PATH + path)
+    assert headers['x-acs-action'] == 'GetSemanticView'
+    assert transport_server.bodies == [None]
+
+
+def 
test_dot_only_names_preserve_existing_gateway_path_normalization(transport_server):
+    def respond(method, target, body):
+        path = urlsplit(target).path
+        if path.endswith('/v1/config'):
+            return 200, '{"defaults":{"prefix":"test"}}'
+        if path.endswith('/databases'):
+            return 200, '{"databases":["sales"],"nextPageToken":null}'
+        return 200, 
'{"name":"..","definition":{"format":"provider-yaml","content":"model"}}'
+
+    transport_server.respond = respond
+    uri = 
'http://localhost:{}/old/../gateway/%2E/%7E'.format(transport_server.server_port)
+    catalog = transport.transport_catalog(transport_server, uri=uri)
+
+    assert catalog.list_databases_paged().elements == ['sales']
+    assert catalog.get_semantic_view(Identifier.create('.', '..')).name == '..'
+    assert [urlsplit(target).path for _, target, _ in 
transport_server.requests] == [
+        '/gateway/./~/v1/config',
+        '/gateway/./~/v1/test/databases',
+        '/gateway/./~/v1/test/databases/%2E/semantic-views/%2E%2E',
+    ]
+
+
[email protected]('prefix,encoded_prefix', [('.', '%2E'), ('..', 
'%2E%2E'), ('catalog/id', 'catalog%2Fid')])
[email protected]('operation', ['get_semantic_view', 
'list_semantic_views_paged'])
+def test_semantic_views_use_prefix_discovered_from_config(transport_server, 
prefix, encoded_prefix, operation):
+    collection_path = 
'/gateway/v1/{}/databases/sales/semantic-views'.format(encoded_prefix)
+    view_path = collection_path + '/revenue'
+
+    def respond(method, target, body):
+        path = urlsplit(target).path
+        if path == '/gateway/v1/config':
+            return 200, json.dumps({'defaults': {'prefix': prefix}})
+        if path == collection_path:
+            return 200, '{"semanticViews":["revenue"]}'
+        if path == view_path:
+            return 200, 
'{"name":"revenue","definition":{"format":"provider-yaml","content":"model"}}'
+        return 404, json.dumps({'message': 'Unexpected path: ' + path})
+
+    transport_server.respond = respond
+    uri = 'http://localhost:{}/gateway'.format(transport_server.server_port)
+    catalog = transport.transport_catalog(transport_server, uri=uri)
+
+    if operation == 'get_semantic_view':
+        assert catalog.get_semantic_view('sales.revenue').name == 'revenue'
+        resource_path = view_path
+    else:
+        assert catalog.list_semantic_views_paged('sales').elements == 
['revenue']
+        resource_path = collection_path
+    assert [(method, urlsplit(target).path) for method, target, _ in 
transport_server.requests] == [
+        ('GET', '/gateway/v1/config'), ('GET', resource_path),
+    ]
+
+
+def test_listed_semantic_view_name_can_be_used_to_read_definition(catalog, 
transport_server):
+    name = '\u00a0'
+    definition = {'format': '\u00a0', 'content': '\u2003'}
+    replies = iter([{'semanticViews': [name]}, {'name': name, 'definition': 
definition}])
+    transport_server.respond = lambda *_: (200, json.dumps(next(replies)))
+
+    page = catalog.list_semantic_views_paged('sales')
+    assert page.elements == [name]
+    view = catalog.get_semantic_view(Identifier.create('sales', 
page.elements[0]))
+
+    assert view.name == name
+    assert view.definition.format == definition['format']
+    assert view.definition.content == definition['content']
+    assert [target for _, target, _ in transport_server.requests] == [
+        BASE_PATH + '/sales/semantic-views', BASE_PATH + 
'/sales/semantic-views/%C2%A0',
+    ]
+
+
+def test_list_semantic_views_paged(catalog, transport_server):
+    token = 'next +/%?&\u534e'
+    replies = iter([
+        {'semanticViews': ['revenue', 'margin'], 'nextPageToken': token},
+        {'semanticViews': ['volume']},
+        {'semanticViews': []},
+        {'semanticViews': None},
+    ])
+    transport_server.respond = lambda *_: (200, json.dumps(next(replies)))
+
+    first = catalog.list_semantic_views_paged('..', max_results=1000)
+    last = catalog.list_semantic_views_paged('..', max_results=1, 
page_token=first.next_page_token)
+    empty = catalog.list_semantic_views_paged('..')
+    null_names = catalog.list_semantic_views_paged('..', page_token='')
+
+    assert (first.elements, first.next_page_token) == (['revenue', 'margin'], 
token)
+    assert (last.elements, last.next_page_token) == (['volume'], None)
+    assert (empty.elements, empty.next_page_token) == ([], None)
+    assert (null_names.elements, null_names.next_page_token) == ([], None)
+    assert len(transport_server.requests) == 4
+    for (method, target, headers), query in zip(transport_server.requests, [
+        {'maxResults': ['1000']}, {'maxResults': ['1'], 'pageToken': [token]}, 
{}, {'pageToken': ['']},
+    ]):
+        url = urlsplit(target)
+        assert (method, url.path) == ('GET', BASE_PATH + 
'/%2E%2E/semantic-views')
+        assert parse_qs(url.query, keep_blank_values=True) == query
+        assert headers['x-acs-action'] == 'ListSemanticViews'
+    assert transport_server.bodies == [None] * 4
+
+
[email protected]('status,exception', [
+    (400, BadRequestException), (401, NotAuthorizedException), (403, 
ForbiddenException),
+    (404, NoSuchResourceException), (500, ServiceFailureException), (501, 
NotImplementedException),
+])
+def test_semantic_view_rest_errors(catalog, transport_server, status, 
exception):
+    transport_server.respond = lambda *_: (status, json.dumps({
+        'resourceType': 'SEMANTIC_VIEW', 'resourceName': 'revenue', 'message': 
'rejected by catalog',
+    }))
+
+    for call in (lambda: catalog.get_semantic_view('sales.revenue'),
+                 lambda: catalog.list_semantic_views_paged('sales')):
+        with pytest.raises(exception, match='rejected by catalog') as error:
+            call()
+        if status == 404:
+            assert error.value.resource_type == 'SEMANTIC_VIEW'
+            assert error.value.resource_name == 'revenue'
+    assert [(method, urlsplit(target).path) for method, target, _ in 
transport_server.requests] == [
+        ('GET', BASE_PATH + '/sales/semantic-views/revenue'),
+        ('GET', BASE_PATH + '/sales/semantic-views'),
+    ]
+
+
+def test_invalid_semantic_view_response_is_rejected(catalog, transport_server):
+    oversized = '\u534e' * (1024 * 1024 // 3 + 1)
+    for response, message in (
+        (None, 'response must not be null'),
+        ({'name': 'revenue', 'definition': None}, 'definition must not be 
null'),
+        ({'name': '', 'definition': {'format': 'provider-yaml', 'content': 
'model'}}, 'name must not be blank'),
+        ({'name': 'revenue', 'definition': {'format': None, 'content': 
'model'}}, 'format must not be blank'),
+        ({'name': 'revenue', 'definition': {'format': 'provider-yaml', 
'content': ' '}}, 'content must not be blank'),
+        ({'name': 'revenue', 'definition': {'format': 'provider-yaml', 
'content': oversized}}, 'must not exceed 1 MiB'),
+    ):
+        transport_server.respond = lambda *_: (200, json.dumps(response))
+        with pytest.raises(RESTException) as error:
+            catalog.get_semantic_view('sales.revenue')
+        assert message in str(error.value.get_cause() or error.value)
+
+
+def test_null_semantic_view_page_is_rejected(catalog, transport_server):
+    transport_server.respond = lambda *_: (200, 'null')
+    with pytest.raises(RESTException, match='list response must not be null'):
+        catalog.list_semantic_views_paged('sales')
+
+
+def test_invalid_semantic_view_arguments_fail_before_http(catalog, 
transport_server):
+    for page_size in (-1, 0, 1001, 2.5, True):
+        with pytest.raises(ValueError, match='max_results'):
+            catalog.list_semantic_views_paged('sales', max_results=page_size)
+    with pytest.raises(ValueError, match='Database name'):
+        catalog.list_semantic_views_paged('  ')
+    for name in ('  ', '\x00\t'):
+        with pytest.raises(ValueError, match='Semantic view name'):
+            catalog.get_semantic_view(Identifier.create('sales', name))
+    assert not transport_server.requests

Reply via email to