Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Re-introduce pytest-socket (#467)
Madison Swain-Bowdendd57690a00a1
diff --git a/openverse_catalog/dags/common/urls.py b/openverse_catalog/dags/common/urls.pyindex c3269f50f..280b130e1 100644--- a/openverse_catalog/dags/common/urls.py+++ b/openverse_catalog/dags/common/urls.py@@ -7,9 +7,11 @@ import refrom functools import lru_cachefrom urllib.parse import urlparse-import requestsimport tldextract+# This import is aliased for easier test mocking+from requests import get as requests_get+logger = logging.getLogger(__name__)@@ -62,7 +64,7 @@ def rewrite_redirected_url(url_string):requests."""try:- response = requests.get(url_string)+ response = requests_get(url_string)if response.ok:rewritten_url = response.urlif rewritten_url != url_string:@@ -115,7 +117,7 @@ def _test_domain_for_tls_support(domain):logger.info(f"Testing {domain} for TLS support")tls_supported = Falsetry:- requests.get(f"https://{domain}", timeout=2)+ requests_get(f"https://{domain}", timeout=2)logger.info(f"{domain} supports TLS.")tls_supported = Trueexcept Exception as e:diff --git a/pytest.ini b/pytest.iniindex c5236078b..7d8e9e8ee 100644--- a/pytest.ini+++ b/pytest.ini@@ -1,2 +1,19 @@[pytest]-addopts = --no-success-flaky-report -n auto --dist=loadscope+#### Descriptions ####+# FLAKY+# https://github.com/box/flaky#shorter-flaky-report+# no-success-flaky-report: Suppress successful flaky tests+# XDIST+# https://pypi.org/project/pytest-xdist/#running-tests-across-multiple-cpus+# numprocesses: number of test workers to spin up+# dist: how to distribute tests across workers+# SOCKET+# https://github.com/miketheman/pytest-socket#usage+# disable-socket: turn off socket access by default to prevent HTTP requests during tests+# allow-unix-socket: allow system sockets (e.g. async) to be used+addopts =+ --no-success-flaky-report+ --numprocesses auto+ --dist loadscope+ --disable-socket+ --allow-unix-socketdiff --git a/requirements_dev.txt b/requirements_dev.txtindex 411f44fce..bcb84a1da 100644--- a/requirements_dev.txt+++ b/requirements_dev.txt@@ -4,5 +4,6 @@ flaky==3.7.0ipythonpytest-mock==3.6.1pytest-raises==0.11+pytest-socket==0.5.1pytest-sugar==0.9.4pytest-xdist==2.5.0diff --git a/tests/dags/common/conftest.py b/tests/dags/common/conftest.pyindex 44b6586e7..ed4758c42 100644--- a/tests/dags/common/conftest.py+++ b/tests/dags/common/conftest.py@@ -1,3 +1,6 @@+import socket+from urllib.parse import urlparse+import boto3import pytest@@ -11,6 +14,18 @@ def _delete_bucket(bucket):bucket.delete()+def pytest_configure(config):+ """+ Dynamically allow the S3 host during testing. This is required because:+ * Docker will use different internal ports depending on what's available+ * Boto3 will open a socket with the IP address directly rather than the hostname+ * We can't add the allow_hosts mark to the empty_s3_bucket fixture directly+ (see: https://github.com/pytest-dev/pytest/issues/1368)+ """+ s3_host = socket.gethostbyname(urlparse(S3_LOCAL_ENDPOINT).hostname)+ config.__socket_allow_hosts = ["s3", "postgres", s3_host]++@pytest.fixturedef empty_s3_bucket(request):# Bucket names can't be longer than 63 characters or have strange charactersdiff --git a/tests/dags/common/loader/test_smithsonian_unit_codes.py b/tests/dags/common/loader/test_smithsonian_unit_codes.pyindex 28ce4cb82..71f0d0f7b 100644--- a/tests/dags/common/loader/test_smithsonian_unit_codes.py+++ b/tests/dags/common/loader/test_smithsonian_unit_codes.py@@ -1,6 +1,6 @@import osfrom collections import namedtuple-from unittest.mock import patch+from unittest.mock import Mock, patchimport psycopg2import pytest@@ -52,10 +52,14 @@ def test_alert_new_unit_codes():def test_alert_unit_codes_from_api(postgres_with_test_unit_code_table):postgres_conn_id = POSTGRES_CONN_IDunit_code_table = SI_UNIT_CODE_TABLE+ response_mock = Mock()+ response_mock.json.return_value = {}with patch.object(si, "get_new_and_outdated_unit_codes", return_value=({"d"}, {"e"})- ) as mock_get_unit_codes:+ ) as mock_get_unit_codes, patch.object(+ si.requests, "get", return_value=response_mock+ ):with pytest.raises(Exception):si.alert_unit_codes_from_api(postgres_conn_id, unit_code_table)diff --git a/tests/dags/common/sensors/test_single_run_external_dags_sensor.py b/tests/dags/common/sensors/test_single_run_external_dags_sensor.pyindex efdb771d2..5c65f4054 100644--- a/tests/dags/common/sensors/test_single_run_external_dags_sensor.py+++ b/tests/dags/common/sensors/test_single_run_external_dags_sensor.py@@ -1,5 +1,6 @@import loggingimport unittest+import warningsimport pytestfrom airflow.exceptions import AirflowException@@ -100,7 +101,12 @@ class TestExternalDAGsSensor(unittest.TestCase):def test_fails_if_external_dag_missing_sensor_task(self):# Loads an example DAG which does not have a Sensor task.- dagbag = DagBag(dag_folder=DEV_NULL, include_examples=True)+ with warnings.catch_warnings():+ # TODO: As of 2.2.4, initializing the example DAGs emits deprecation+ # warnings for...(drumroll) Airflow operators 🙃 hopefully this is fixed+ # in 2.2.5 or something.+ warnings.simplefilter("ignore", category=DeprecationWarning)+ dagbag = DagBag(dag_folder=DEV_NULL, include_examples=True)bash_dag = dagbag.dags["example_bash_operator"]bash_dag.sync_to_db()diff --git a/tests/dags/common/test_urls.py b/tests/dags/common/test_urls.pyindex c85163286..65cbc0cd5 100644--- a/tests/dags/common/test_urls.py+++ b/tests/dags/common/test_urls.py@@ -29,7 +29,7 @@ def get_good(monkeypatch):def mock_get(url, timeout=60):return requests.Response()- monkeypatch.setattr(urls.requests, "get", mock_get)+ monkeypatch.setattr(urls, "requests_get", mock_get)@pytest.fixture@@ -37,7 +37,7 @@ def get_bad(monkeypatch):def mock_get(url, timeout=60):raise Exception- monkeypatch.setattr(urls.requests, "get", mock_get)+ monkeypatch.setattr(urls, "requests_get", mock_get)def test_validate_url_string_adds_http_without_scheme(clear_tls_cache, get_bad):@@ -86,7 +86,7 @@ def test_validate_url_string_handles_wmc_type_scheme(clear_tls_cache, get_good):def test_validate_url_string_caches_tls_support(clear_tls_cache, monkeypatch):url_string = "commons.wikimedia.org/wiki/User:potato"with patch.object(- urls.requests, "get", return_value=requests.Response()+ urls, "requests_get", return_value=requests.Response()) as mock_get:actual_validated_url_1 = urls.validate_url_string(url_string)actual_validated_url_2 = urls.validate_url_string(url_string)@@ -101,7 +101,7 @@ def test_rewrite_redirected_url_returns_when_ok(clear_rewriter_cache, monkeypatcr = requests.Response()r.status_code = 200r.url = expect_url- monkeypatch.setattr(urls.requests, "get", lambda *args: r)+ monkeypatch.setattr(urls, "requests_get", lambda *args: r)actual_url = urls.rewrite_redirected_url("https://input.url")assert actual_url == expect_url@@ -110,7 +110,7 @@ def test_rewrite_redirected_url_nones_when_not_ok(clear_rewriter_cache, monkeypar = requests.Response()r.status_code = 404r.url = "https://rewritten.url"- monkeypatch.setattr(urls.requests, "get", lambda *args: r)+ monkeypatch.setattr(urls, "requests_get", lambda *args: r)actual_url = urls.rewrite_redirected_url("https://input.url")assert actual_url is None@@ -121,7 +121,7 @@ def test_rewrite_redirected_url_nones_when_error_occurs(def mock_get(*args):raise Exception- monkeypatch.setattr(urls.requests, "get", mock_get)+ monkeypatch.setattr(urls, "requests_get", mock_get)actual_url = urls.rewrite_redirected_url("https://input.url")assert actual_url is None@@ -132,7 +132,7 @@ def test_rewrite_redirected_url_caches_results(clear_rewriter_cache, monkeypatchr.status_code = 200r.url = expect_urlinput_url = "https://rewritten.url"- with patch.object(urls.requests, "get", return_value=r) as mock_get:+ with patch.object(urls, "requests_get", return_value=r) as mock_get:actual_rewritten_url_1 = urls.rewrite_redirected_url(input_url)actual_rewritten_url_2 = urls.rewrite_redirected_url(input_url)assert actual_rewritten_url_1 == expect_urldiff --git a/tests/dags/conftest.py b/tests/dags/conftest.pyindex aa5d165c8..456858858 100644--- a/tests/dags/conftest.py+++ b/tests/dags/conftest.py@@ -2,6 +2,7 @@ from unittest import mockimport pytestfrom oauth2 import oauth2+from requests import ResponseFAKE_OAUTH_PROVIDER_NAME = "fakeprovider"@@ -31,3 +32,29 @@ def oauth_provider_var_mock():with mock.patch("oauth2.oauth2.Variable") as MockVariable:MockVariable.get.side_effect = _var_get_replacementyield MockVariable+++def _make_response(*args, **kwargs):+ """+ Mock the request used during license URL validation. Most times the results of this+ function are expected to end with a `/`, so if the URL provided does not we add it.+ """+ response: Response = mock.Mock(spec=Response)+ if args:+ response.ok = True+ url = args[0]+ if isinstance(url, str) and not url.endswith("/"):+ url += "/"+ response.url = url+ return response++[email protected](autouse=True)+def requests_get_mock():+ """+ Mock request.get calls that occur during testing done by the+ `common.urls.rewrite_redirected_url` function.+ """+ with mock.patch("common.urls.requests_get", autospec=True) as mock_get:+ mock_get.side_effect = _make_response+ yield