Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

internal: request utils, make remote file send marimo user-agent (#5571)

Myles Scolnickbe6ec76d5e5d
diff --git a/marimo/_ai/text_to_notebook.py b/marimo/_ai/text_to_notebook.py
index 04e5b2a930..0bf302db24 100644
--- a/marimo/_ai/text_to_notebook.py
+++ b/marimo/_ai/text_to_notebook.py
@@ -5,9 +5,9 @@ import datetime
import urllib.error
import urllib.parse
import urllib.request
-from typing import Optional, cast
+from typing import Optional
-from marimo import __version__
+import marimo._utils.requests as requests
from marimo._cli.print import bold, green, muted
from marimo._config.cli_state import (
get_cli_state,
@@ -70,11 +70,8 @@ def text_to_notebook(prompt: str) -> str:
print_(muted("Generating notebook this may take a few seconds..."))
# Create a request with a proper User-Agent header
- headers = {"User-Agent": f"marimo-cli/{__version__}"}
- req = urllib.request.Request(url, headers=headers)
-
- with urllib.request.urlopen(req) as response:
- result = response.read().decode("utf-8") # type: ignore[attr-defined]
+ headers = {"User-Agent": requests.MARIMO_USER_AGENT}
+ result = requests.get(url, headers=headers).raise_for_status().text()
print_(green("Notebook generated successfully."))
@@ -84,7 +81,7 @@ def text_to_notebook(prompt: str) -> str:
"Invalid response from API: missing 'marimo.App' key"
)
- return cast(str, result)
+ return result
except Exception as e:
raise RuntimeError(f"Failed to generate notebook: {str(e)}") from e
diff --git a/marimo/_cli/convert/utils.py b/marimo/_cli/convert/utils.py
index 22848f8ca2..400df30316 100644
--- a/marimo/_cli/convert/utils.py
+++ b/marimo/_cli/convert/utils.py
@@ -1,11 +1,11 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import urllib.request
from pathlib import Path
import click
+import marimo._utils.requests as requests
from marimo._cli.file_path import get_github_src_url, is_github_src
from marimo._utils.url import is_url
@@ -14,12 +14,12 @@ def load_external_file(file_path: str, ext: str) -> str:
notebook: str = ""
if is_github_src(file_path, ext=ext):
notebook = (
- urllib.request.urlopen(get_github_src_url(file_path))
- .read()
- .decode("utf-8")
+ requests.get(get_github_src_url(file_path))
+ .raise_for_status()
+ .text()
)
elif is_url(file_path):
- notebook = urllib.request.urlopen(file_path).read().decode("utf-8")
+ notebook = requests.get(file_path).raise_for_status().text()
else:
if not Path(file_path).exists():
raise click.FileError(file_path, "File does not exist")
diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.py
index 643c5cd259..539140239f 100644
--- a/marimo/_cli/file_path.py
+++ b/marimo/_cli/file_path.py
@@ -2,23 +2,24 @@
from __future__ import annotations
import abc
-import json
import os
import re
import urllib.parse
-import urllib.request
from pathlib import Path
from tempfile import TemporaryDirectory
-from typing import Optional
+from typing import Any, Optional, cast
from urllib.error import HTTPError
-from marimo import __version__, _loggers
+import marimo._utils.requests as requests
+from marimo import _loggers
from marimo._cli.print import green
from marimo._utils.marimo_path import MarimoPath
from marimo._utils.url import is_url
LOGGER = _loggers.marimo_logger()
+USER_AGENT_HEADER = {"User-Agent": requests.MARIMO_USER_AGENT}
+
def is_github_src(url: str, ext: str) -> bool:
if not is_url(url):
@@ -73,14 +74,24 @@ class GitHubIssueReader(FileReader):
def read(self, name: str) -> tuple[str, str]:
issue_number = name.split("/")[-1]
api_url = f"https://api.github.com/repos/marimo-team/marimo/issues/{issue_number}"
- issue_response = urllib.request.urlopen(api_url).read().decode("utf-8")
- issue_json = json.loads(issue_response)
- body = issue_json["body"]
+ response = requests.get(api_url)
+ response.raise_for_status()
+ issue_response = cast(dict[str, Any], response.json())
+
+ if "body" not in issue_response:
+ raise ValueError(
+ f"Failed to read GitHub issue {name}. No 'body' in response {issue_response}"
+ )
+
+ body = issue_response["body"]
code = self._find_python_code_in_github_issue(body)
return code, f"issue_{issue_number}.py"
@staticmethod
def _find_python_code_in_github_issue(body: str) -> str:
+ if "```python" not in body:
+ raise ValueError(f"No Python code found in GitHub issue {body}")
+
return body.split("```python")[1].rsplit("```", 1)[0]
@@ -104,16 +115,12 @@ class StaticNotebookReader(FileReader):
def _is_static_marimo_notebook_url(url: str) -> tuple[bool, str]:
def download(url: str) -> tuple[bool, str]:
LOGGER.info("Downloading %s", url)
- request = urllib.request.Request(
- url,
- # User agent to avoid 403 Forbidden some bot protection
- headers={"User-Agent": f"marimo/{__version__}"},
- )
- file_contents = (
- urllib.request.urlopen(request).read().decode("utf-8")
- )
- return StaticNotebookReader.CODE_TAG in file_contents, str(
- file_contents
+ response = requests.get(url, headers=USER_AGENT_HEADER)
+ response.raise_for_status()
+ file_contents = response.text()
+ return (
+ StaticNotebookReader.CODE_TAG in file_contents,
+ file_contents,
)
# Not a URL
@@ -126,7 +133,8 @@ class StaticNotebookReader(FileReader):
# Starts with https://static.marimo.app/, append /download
if url.startswith("https://static.marimo.app/static"):
- return download(os.path.join(url, "download"))
+ normalized_url = url if url.endswith("/") else url + "/"
+ return download(urllib.parse.urljoin(normalized_url, "download"))
# Other marimo domains
DOMAINS = [
@@ -164,7 +172,9 @@ class GitHubSourceReader(FileReader):
def read(self, name: str) -> tuple[str, str]:
url = get_github_src_url(name)
- content = urllib.request.urlopen(url).read().decode("utf-8")
+ response = requests.get(url, headers=USER_AGENT_HEADER)
+ response.raise_for_status()
+ content = response.text()
return content, os.path.basename(url)
@@ -173,7 +183,9 @@ class GenericURLReader(FileReader):
return is_url(name)
def read(self, name: str) -> tuple[str, str]:
- content = urllib.request.urlopen(name).read().decode("utf-8")
+ response = requests.get(name, headers=USER_AGENT_HEADER)
+ response.raise_for_status()
+ content = response.text()
# Remove query parameters from the URL
url_without_query = name.split("?")[0]
return content, os.path.basename(url_without_query)
diff --git a/marimo/_cli/upgrade.py b/marimo/_cli/upgrade.py
index 57df82e179..03d6696079 100644
--- a/marimo/_cli/upgrade.py
+++ b/marimo/_cli/upgrade.py
@@ -6,8 +6,9 @@ import os
import urllib.error
import urllib.request
from datetime import datetime
-from typing import Any, Callable
+from typing import Any, Callable, cast
+import marimo._utils.requests as requests
from marimo import __version__ as current_version, _loggers
from marimo._cli.print import echo, green, orange
from marimo._config.cli_state import (
@@ -15,7 +16,6 @@ from marimo._config.cli_state import (
get_cli_state,
write_cli_state,
)
-from marimo._server.api.status import HTTPException
from marimo._tracer import server_tracer
FETCH_TIMEOUT = 3
@@ -107,17 +107,9 @@ def _update_with_latest_version(state: MarimoCLIState) -> MarimoCLIState:
def _fetch_data_from_url(url: str) -> dict[str, Any]:
try:
- with urllib.request.urlopen(url, timeout=FETCH_TIMEOUT) as response:
- status = response.status
- if status == 200:
- data = response.read()
- encoding = response.info().get_content_charset("utf-8")
- return json.loads(data.decode(encoding)) # type: ignore
- else:
- raise HTTPException(
- status_code=status,
- detail=f"HTTP request failed with status code {status}",
- )
+ response = requests.get(url, timeout=FETCH_TIMEOUT)
+ response.raise_for_status()
+ return cast(dict[str, Any], response.json())
except urllib.error.URLError as e:
LOGGER.warning(
f"Network error while checking for version updates: {e}"
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 00d18e8802..da9c8a98b2 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -569,15 +569,14 @@ def _create_notebook_cell(
def get_html_contents() -> str:
if GLOBAL_SETTINGS.DEVELOPMENT_MODE:
- import urllib.request
+ import marimo._utils.requests as requests
# Fetch from a CDN
LOGGER.info(
"Fetching index.html from jsdelivr because in development mode"
)
url = f"https://cdn.jsdelivr.net/npm/@marimo-team/frontend@{__version__}/dist/index.html"
- with urllib.request.urlopen(url) as response:
- return cast(str, response.read().decode("utf-8"))
+ return requests.get(url).text()
index_html = Path(ROOT) / "index.html"
return index_html.read_text(encoding="utf-8")
diff --git a/marimo/_utils/requests.py b/marimo/_utils/requests.py
new file mode 100644
index 0000000000..a32a3f23c7
--- /dev/null
+++ b/marimo/_utils/requests.py
@@ -0,0 +1,213 @@
+import json
+import urllib.error
+import urllib.parse
+import urllib.request
+from typing import Any, Optional, Union
+
+from marimo import __version__
+
+# Utility functions for making HTTP requests,
+# without using the requests library or any other external dependencies.
+
+MARIMO_USER_AGENT = f"marimo/{__version__}"
+
+
+class RequestError(Exception):
+ """Exception raised when a request fails."""
+
+ def __init__(self, message: str):
+ self.message = message
+ super().__init__(self.message)
+
+
+class Response:
+ """Simple response object similar to requests.Response."""
+
+ def __init__(
+ self,
+ status_code: int,
+ content: bytes,
+ headers: dict[str, str],
+ original_error: Optional[Exception] = None,
+ ):
+ self.status_code = status_code
+ self.content = content
+ self.headers = headers
+ self.original_error = original_error
+
+ def json(self) -> Any:
+ """Parse response content as JSON.
+
+ This assumes the response is UTF-8 encoded.
+ In future, we can infer the encoding from the headers.
+ """
+ return json.loads(self.text())
+
+ def text(self) -> str:
+ """Get response content as text.
+
+ This assumes the response is UTF-8 encoded.
+ In future, we can infer the encoding from the headers.
+ """
+ return self.content.decode("utf-8")
+
+ def raise_for_status(self) -> "Response":
+ """Raise an exception for non-2xx status codes.
+
+ Returns:
+ The response object for chaining.
+ """
+ if self.status_code >= 300:
+ if self.original_error:
+ raise self.original_error
+ raise RequestError(
+ f"Request failed: {self.status_code}. {self.text()}"
+ )
+ return self
+
+
+def _make_request(
+ method: str,
+ url: str,
+ *,
+ params: Optional[dict[str, str]] = None,
+ headers: Optional[dict[str, str]] = None,
+ data: Optional[Union[dict[str, Any], str]] = None,
+ json_data: Optional[dict[str, Any]] = None,
+ timeout: Optional[float] = None,
+) -> Response:
+ """Make an HTTP request and return a Response object.
+
+ If the URL already contains query parameters and new params are provided,
+ they will be merged with new params taking precedence over existing ones.
+ """
+ assert isinstance(url, str), "url must be a string"
+ has_data = data is not None
+ has_json_data = json_data is not None
+ assert not has_data or not has_json_data, (
+ "cannot pass both data and json_data"
+ )
+
+ # Handle URL parameters
+ if params:
+ parsed = urllib.parse.urlparse(url)
+ # Parse existing query parameters
+ existing_params = urllib.parse.parse_qs(parsed.query)
+ # Flatten existing params (parse_qs returns lists)
+ flattened_existing = {k: v[0] for k, v in existing_params.items()}
+ # Merge with new params (new params take precedence)
+ merged_params = {**flattened_existing, **params}
+ query = urllib.parse.urlencode(merged_params)
+ url = urllib.parse.urlunparse(
+ (
+ parsed.scheme,
+ parsed.netloc,
+ parsed.path,
+ parsed.params,
+ query,
+ parsed.fragment,
+ )
+ )
+
+ # Prepare headers
+ request_headers = headers or {}
+ if "User-Agent" not in request_headers:
+ request_headers["User-Agent"] = MARIMO_USER_AGENT
+
+ # Prepare body
+ body = None
+ if json_data is not None:
+ request_headers["Content-Type"] = "application/json"
+ body = json.dumps(json_data).encode("utf-8")
+ elif data is not None:
+ if isinstance(data, dict):
+ body = urllib.parse.urlencode(data).encode("utf-8")
+ request_headers["Content-Type"] = (
+ "application/x-www-form-urlencoded"
+ )
+ else:
+ body = str(data).encode("utf-8")
+
+ # Create request
+ req = urllib.request.Request(
+ url, data=body, headers=request_headers, method=method
+ )
+
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as response:
+ return Response(
+ status_code=response.getcode(),
+ content=response.read(),
+ headers=dict(response.headers),
+ )
+ except urllib.error.HTTPError as e:
+ # For HTTP errors, we still want to return a Response object
+ return Response(
+ status_code=e.code,
+ content=e.read(),
+ headers=dict(e.headers),
+ original_error=e,
+ )
+ except Exception as e:
+ raise RequestError(f"Request failed: {str(e)}") from e
+
+
+def get(
+ url: str,
+ *,
+ params: Optional[dict[str, str]] = None,
+ headers: Optional[dict[str, str]] = None,
+ timeout: Optional[float] = None,
+) -> Response:
+ """Make a GET request."""
+ return _make_request(
+ "GET", url, params=params, headers=headers, timeout=timeout
+ )
+
+
+def post(
+ url: str,
+ *,
+ data: Optional[Union[dict[str, Any], str]] = None,
+ json_data: Optional[dict[str, Any]] = None,
+ headers: Optional[dict[str, str]] = None,
+ timeout: Optional[float] = None,
+) -> Response:
+ """Make a POST request."""
+ return _make_request(
+ "POST",
+ url,
+ data=data,
+ json_data=json_data,
+ headers=headers,
+ timeout=timeout,
+ )
+
+
+def put(
+ url: str,
+ *,
+ data: Optional[Union[dict[str, Any], str]] = None,
+ json_data: Optional[dict[str, Any]] = None,
+ headers: Optional[dict[str, str]] = None,
+ timeout: Optional[float] = None,
+) -> Response:
+ """Make a PUT request."""
+ return _make_request(
+ "PUT",
+ url,
+ data=data,
+ json_data=json_data,
+ headers=headers,
+ timeout=timeout,
+ )
+
+
+def delete(
+ url: str,
+ *,
+ headers: Optional[dict[str, str]] = None,
+ timeout: Optional[float] = None,
+) -> Response:
+ """Make a DELETE request."""
+ return _make_request("DELETE", url, headers=headers, timeout=timeout)
diff --git a/tests/_cli/test_file_path.py b/tests/_cli/test_file_path.py
index 0b5251be98..011b8ae16f 100644
--- a/tests/_cli/test_file_path.py
+++ b/tests/_cli/test_file_path.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import tempfile
import urllib.error
from pathlib import Path
-from unittest.mock import mock_open, patch
+from unittest.mock import patch
import click
import pytest
@@ -19,6 +19,7 @@ from marimo._cli.file_path import (
is_github_src,
validate_name,
)
+from marimo._utils.requests import Response
temp_dir = tempfile.TemporaryDirectory()
@@ -79,13 +80,12 @@ def test_github_issue_reader() -> None:
assert reader.can_read(valid_url) is True
assert reader.can_read(invalid_url) is False
- with patch("urllib.request.urlopen") as mock_urlopen:
- mock_response = mock_open(
- read_data=b"""{
- "body": "Some content.```python\\nprint('Hello, world!')\\n```"}
- """ # noqa: E501
+ with patch("marimo._utils.requests.get") as mock_get:
+ mock_get.return_value = Response(
+ 200,
+ b'{"body": "Some content.```python\\nprint(\'Hello, world!\')```"}',
+ {},
)
- mock_urlopen.return_value = mock_response()
content, filename = reader.read(valid_url)
assert content.strip() == "print('Hello, world!')"
@@ -108,9 +108,12 @@ def test_github_source_reader() -> None:
assert reader.can_read(valid_url) is True
assert reader.can_read(invalid_url) is False
- with patch("urllib.request.urlopen") as mock_urlopen:
- mock_response = mock_open(read_data=b"print('Hello, world!')")
- mock_urlopen.return_value = mock_response()
+ with patch("marimo._utils.requests.get") as mock_get:
+ mock_get.return_value = Response(
+ 200,
+ b"print('Hello, world!')",
+ {},
+ )
content, filename = reader.read(valid_url)
assert content == "print('Hello, world!')"
@@ -155,9 +158,12 @@ def test_generic_url_reader() -> None:
assert reader.can_read("https://example.com/file.py") is True
assert reader.can_read("local_file.py") is False
- with patch("urllib.request.urlopen") as mock_urlopen:
- mock_response = mock_open(read_data=b"print('Hello, world!')")
- mock_urlopen.return_value = mock_response()
+ with patch("marimo._utils.requests.get") as mock_get:
+ mock_get.return_value = Response(
+ 200,
+ b"print('Hello, world!')",
+ {},
+ )
content, filename = reader.read("https://example.com/file.py")
assert content == "print('Hello, world!')"
@@ -221,9 +227,9 @@ def test_find_python_code_in_github_issue_multiple_codes() -> None:
"""
try:
GitHubIssueReader._find_python_code_in_github_issue(body)
- raise AssertionError("Expected an IndexError")
- except IndexError:
- # IndexError if there are no code blocks
+ raise AssertionError("Expected a ValueError")
+ except ValueError:
+ # ValueError if there are no code blocks
pass
body = """
@@ -263,9 +269,12 @@ def test_generic_url_reader_with_query_params():
reader = GenericURLReader()
url = "https://example.com/file.py?param=value"
assert reader.can_read(url) is True
- with patch("urllib.request.urlopen") as mock_urlopen:
- mock_response = mock_open(read_data=b"print('Hello, world!')")
- mock_urlopen.return_value = mock_response()
+ with patch("marimo._utils.requests.get") as mock_get:
+ mock_get.return_value = Response(
+ 200,
+ b"print('Hello, world!')",
+ {},
+ )
content, filename = reader.read(url)
assert content == "print('Hello, world!')"
assert filename == "file.py"
@@ -295,8 +304,8 @@ def test_static_notebook_reader_url_formats():
def test_github_issue_reader_nonexistent_issue():
reader = GitHubIssueReader()
url = "https://github.com/marimo-team/marimo/issues/999999" # noqa: E501
- with patch("urllib.request.urlopen") as mock_urlopen:
- mock_urlopen.side_effect = urllib.error.HTTPError(
+ with patch("marimo._utils.requests.get") as mock_get:
+ mock_get.side_effect = urllib.error.HTTPError(
url,
404,
"Not Found",
@@ -315,9 +324,12 @@ def test_github_source_reader_different_extensions():
]
for url in urls:
assert reader.can_read(url) is True
- with patch("urllib.request.urlopen") as mock_urlopen:
- mock_response = mock_open(read_data=b"content")
- mock_urlopen.return_value = mock_response()
+ with patch("marimo._utils.requests.get") as mock_get:
+ mock_get.return_value = Response(
+ 200,
+ b"content",
+ {},
+ )
content, filename = reader.read(url)
assert content == "content"
assert filename in ["example.py", "README.md"]
diff --git a/tests/_utils/test_utils_request.py b/tests/_utils/test_utils_request.py
new file mode 100644
index 0000000000..3a00a8dd08
--- /dev/null
+++ b/tests/_utils/test_utils_request.py
@@ -0,0 +1,323 @@
+from typing import Any, Optional, Union
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from marimo._utils.requests import (
+ RequestError,
+ Response,
+ _make_request,
+ delete,
+ get,
+ post,
+ put,
+)
+
+
+def test_response_object():
+ response = Response(
+ 200, b'{"key": "value"}', {"Content-Type": "application/json"}
+ )
+ assert response.status_code == 200
+ assert response.content == b'{"key": "value"}'
+ assert response.headers == {"Content-Type": "application/json"}
+ assert response.text() == '{"key": "value"}'
+ assert response.json() == {"key": "value"}
+
+
+def test_response_raise_for_status():
+ # Test that raise_for_status does not raise for success codes
+ success_response = Response(200, b"OK", {})
+ success_response.raise_for_status() # Should not raise
+ assert success_response is success_response.raise_for_status()
+
+ # Test that raise_for_status raises for error codes
+ error_response = Response(404, b"Not Found", {})
+ with pytest.raises(RequestError, match="Request failed: 404"):
+ error_response.raise_for_status()
+
+ # Test various error codes
+ for status_code in [300, 400, 401, 403, 404, 500, 502, 503]:
+ error_response = Response(status_code, b"Error", {})
+ with pytest.raises(
+ RequestError, match=f"Request failed: {status_code}"
+ ):
+ error_response.raise_for_status()
+
+ # Test that success codes (2xx) don't raise
+ for status_code in [200, 201, 202, 204]:
+ success_response = Response(status_code, b"Success", {})
+ success_response.raise_for_status() # Should not raise
+
+
+ (
+ "method",
+ "url",
+ "params",
+ "headers",
+ "data",
+ "json_data",
+ "expected_body",
+ "expected_headers",
+ ),
+ [
+ # GET request
+ (
+ "GET",
+ "https://api.example.com",
+ {"param": "value"},
+ {"Authorization": "Bearer token"},
+ None,
+ None,
+ None,
+ {"Authorization": "Bearer token"},
+ ),
+ # POST with form data
+ (
+ "POST",
+ "https://api.example.com",
+ None,
+ None,
+ {"key": "value"},
+ None,
+ b"key=value",
+ {"Content-Type": "application/x-www-form-urlencoded"},
+ ),
+ # POST with JSON data
+ (
+ "POST",
+ "https://api.example.com",
+ None,
+ None,
+ None,
+ {"key": "value"},
+ b'{"key": "value"}',
+ {"Content-Type": "application/json"},
+ ),
+ # POST with string data
+ (
+ "POST",
+ "https://api.example.com",
+ None,
+ None,
+ "raw data",
+ None,
+ b"raw data",
+ {},
+ ),
+ ],
+)
+def test_make_request(
+ method: str,
+ url: str,
+ params: Optional[dict[str, str]],
+ headers: Optional[dict[str, str]],
+ data: Optional[Union[dict[str, Any], str]],
+ json_data: Optional[dict[str, Any]],
+ expected_body: bytes,
+ expected_headers: dict[str, str],
+):
+ mock_response = MagicMock()
+ mock_response.getcode.return_value = 200
+ mock_response.read.return_value = b'{"key": "value"}'
+ mock_response.headers = {"Content-Type": "application/json"}
+ mock_response.__enter__.return_value = mock_response
+ mock_response.__exit__.return_value = None
+
+ with patch(
+ "urllib.request.urlopen", return_value=mock_response
+ ) as mock_urlopen:
+ response = _make_request(
+ method,
+ url,
+ params=params,
+ headers=headers,
+ data=data,
+ json_data=json_data,
+ )
+
+ # Verify request was made
+ mock_urlopen.assert_called_once()
+ request_arg = mock_urlopen.call_args[0][0]
+
+ # Check method and URL
+ assert request_arg.get_method() == method
+ if params:
+ assert "param=value" in request_arg.full_url
+
+ # Check body
+ assert request_arg.data == expected_body
+
+ # Check headers
+ for key, value in expected_headers.items():
+ # urllib.request.Request normalizes header names to Title-case
+ # We need to check the actual header values as they're stored
+ found_header = False
+ for header_name, header_value in request_arg.headers.items():
+ if header_name.lower() == key.lower():
+ assert header_value == value
+ found_header = True
+ break
+ assert found_header, f"Header {key} not found in request headers"
+
+ # Verify response
+ assert response.status_code == 200
+ assert response.content == b'{"key": "value"}'
+ assert response.headers == {"Content-Type": "application/json"}
+
+
+def test_invalid_url():
+ with pytest.raises(AssertionError, match="url must be a string"):
+ _make_request("GET", 123) # type: ignore
+
+
+def test_conflicting_data_and_json():
+ with pytest.raises(
+ AssertionError, match="cannot pass both data and json_data"
+ ):
+ _make_request(
+ "POST",
+ "https://api.example.com",
+ data={"key": "value"},
+ json_data={"key": "value"},
+ )
+
+
+def test_http_methods():
+ with patch("marimo._utils.requests._make_request") as mock_make_request:
+ # Test GET
+ get("https://api.example.com", params={"key": "value"})
+ mock_make_request.assert_called_with(
+ "GET",
+ "https://api.example.com",
+ params={"key": "value"},
+ headers=None,
+ timeout=None,
+ )
+
+ # Test POST
+ post("https://api.example.com", json_data={"key": "value"})
+ mock_make_request.assert_called_with(
+ "POST",
+ "https://api.example.com",
+ data=None,
+ json_data={"key": "value"},
+ headers=None,
+ timeout=None,
+ )
+
+ # Test PUT
+ put("https://api.example.com", data={"key": "value"})
+ mock_make_request.assert_called_with(
+ "PUT",
+ "https://api.example.com",
+ data={"key": "value"},
+ json_data=None,
+ headers=None,
+ timeout=None,
+ )
+
+ # Test DELETE
+ delete("https://api.example.com")
+ mock_make_request.assert_called_with(
+ "DELETE", "https://api.example.com", headers=None, timeout=None
+ )
+
+
+def test_http_error_handling():
+ """Test that HTTP errors return Response objects instead of raising exceptions."""
+ import urllib.error
+
+ # Mock an HTTP error
+ mock_fp = MagicMock()
+ mock_fp.read.return_value = b'{"error": "not found"}'
+
+ mock_error = urllib.error.HTTPError(
+ url="https://api.example.com",
+ code=404,
+ msg="Not Found",
+ hdrs={"Content-Type": "application/json"},
+ fp=mock_fp,
+ )
+
+ with patch("urllib.request.urlopen", side_effect=mock_error):
+ response = _make_request("GET", "https://api.example.com")
+
+ assert response.status_code == 404
+ assert response.content == b'{"error": "not found"}'
+ assert response.headers == {"Content-Type": "application/json"}
+
+
+def test_request_error_handling():
+ """Test that other exceptions are converted to RequestError."""
+ with patch(
+ "urllib.request.urlopen", side_effect=Exception("Network error")
+ ):
+ with pytest.raises(
+ RequestError, match="Request failed: Network error"
+ ):
+ _make_request("GET", "https://api.example.com")
+
+
+ ("url", "params", "expected_url"),
+ [
+ # URL with no existing params, add new params
+ (
+ "https://api.example.com/path",
+ {"new": "value"},
+ "https://api.example.com/path?new=value",
+ ),
+ # URL with existing params, add new params (merge)
+ (
+ "https://api.example.com/path?existing=param",
+ {"new": "value"},
+ "https://api.example.com/path?existing=param&new=value",
+ ),
+ # URL with existing params, no new params (preserve existing)
+ (
+ "https://api.example.com/path?existing=param",
+ None,
+ "https://api.example.com/path?existing=param",
+ ),
+ # URL with no params at all
+ ("https://api.example.com/path", None, "https://api.example.com/path"),
+ # URL with existing params, new params override existing
+ (
+ "https://api.example.com/path?key=old",
+ {"key": "new"},
+ "https://api.example.com/path?key=new",
+ ),
+ # URL with multiple existing params, add new params
+ (
+ "https://api.example.com/path?a=1&b=2",
+ {"c": "3"},
+ "https://api.example.com/path?a=1&b=2&c=3",
+ ),
+ # URL with multiple existing params, override some
+ (
+ "https://api.example.com/path?a=1&b=2",
+ {"b": "new", "c": "3"},
+ "https://api.example.com/path?a=1&b=new&c=3",
+ ),
+ ],
+)
+def test_url_parameter_handling(
+ url: str, params: Optional[dict[str, str]], expected_url: str
+):
+ mock_response = MagicMock()
+ mock_response.getcode.return_value = 200
+ mock_response.read.return_value = b'{"key": "value"}'
+ mock_response.headers = {"Content-Type": "application/json"}
+ mock_response.__enter__.return_value = mock_response
+ mock_response.__exit__.return_value = None
+
+ with patch(
+ "urllib.request.urlopen", return_value=mock_response
+ ) as mock_urlopen:
+ _make_request("GET", url, params=params)
+
+ # Verify the URL was constructed correctly
+ request_arg = mock_urlopen.call_args[0][0]
+ assert request_arg.full_url == expected_url