To unit-test a function that is decorated with anvil.server.http_endpoint
, I want to mock anvil.server.request
, as in the following minimal example:
import unittest
from unittest.mock import patch
import anvil.server
@anvil.server.http_endpoint("test-endpoint", methods=["POST"])
def function():
return anvil.server.request.body_json
class TestFunction(unittest.TestCase):
@patch("anvil.server.request")
def test_function(self, mock_request):
mock_request.return_value.body_json = [{"key": 1}]
self.assertEqual({"key": 1}, function())
This raises Exception: anvil.server.request is only available in http_endpoint calls
, however.
I have also tried the following:
- Patch
anvil.server
entirely. That solves this particular issue but any otheranvil.server
objects that are accessed by the function would need to be patched as well (e.g. accessinganvil.tables.app_tables
) which is not feasible. - Decorate the test function with
@patch("anvil.server.request", new=mock_request)
, withmock_request
being a simple object with abody_json
attribute. The problem with this approach is that we have not found a way to avoid having each individual mock request object in the global namespace of our test suite, which is not ideal.
Is there a way to mock anvil.server.request
as in my initial approach but not raise the exception? Because of all possible solutions, that would be the cleanest.