From c70b65dea6f463a491a622a38f0793d247521815 Mon Sep 17 00:00:00 2001 From: andrey-canon Date: Fri, 26 Apr 2024 13:56:51 -0500 Subject: [PATCH] test: blockstore_api backport Two files backport from https://github.com/openedx/edx-platform/pull/31903 --- openedx/core/lib/blockstore_api/tests/base.py | 42 +++++++++++++++++++ .../tests/test_blockstore_api.py | 2 +- 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 openedx/core/lib/blockstore_api/tests/base.py diff --git a/openedx/core/lib/blockstore_api/tests/base.py b/openedx/core/lib/blockstore_api/tests/base.py new file mode 100644 index 00000000000..0888e8c81dc --- /dev/null +++ b/openedx/core/lib/blockstore_api/tests/base.py @@ -0,0 +1,42 @@ +""" +Common code for tests that work with Blockstore +""" +from unittest import mock, skipUnless +from urllib.parse import urlparse + +from django.conf import settings +from django.test.client import RequestFactory + +# Decorators for tests that require the blockstore service/app +requires_blockstore = skipUnless(settings.RUN_BLOCKSTORE_TESTS, "Requires a running Blockstore server") + +requires_blockstore_app = skipUnless(settings.BLOCKSTORE_USE_BLOCKSTORE_APP_API, "Requires blockstore app") + + +class BlockstoreAppTestMixin: + """ + Sets up the environment for tests to be run using the installed Blockstore app. + """ + def setUp(self): + """ + Ensure there's an active request, so that bundle file URLs can be made absolute. + """ + super().setUp() + + # Patch the blockstore get_current_request to use our live_server_url + mock.patch('blockstore.apps.api.methods.get_current_request', + mock.Mock(return_value=self._get_current_request())).start() + self.addCleanup(mock.patch.stopall) + + def _get_current_request(self): + """ + Returns a request object using the live_server_url, if available. + """ + request_args = {} + if hasattr(self, 'live_server_url'): + live_server_url = urlparse(self.live_server_url) + name, port = live_server_url.netloc.split(':') + request_args['SERVER_NAME'] = name + request_args['SERVER_PORT'] = port or '80' + request_args['wsgi.url_scheme'] = live_server_url.scheme + return RequestFactory().request(**request_args) diff --git a/openedx/core/lib/blockstore_api/tests/test_blockstore_api.py b/openedx/core/lib/blockstore_api/tests/test_blockstore_api.py index a1239d5a006..9c15e16668d 100644 --- a/openedx/core/lib/blockstore_api/tests/test_blockstore_api.py +++ b/openedx/core/lib/blockstore_api/tests/test_blockstore_api.py @@ -8,7 +8,7 @@ from django.test import TestCase from openedx.core.lib import blockstore_api as api -from openedx.core.djangoapps.content_libraries.tests.base import ( +from openedx.core.lib.blockstore_api.tests.base import ( BlockstoreAppTestMixin, requires_blockstore, requires_blockstore_app,