Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Use pytest-xdist for testing (#337)

Madison Swain-Bowden760eab51dffd
diff --git a/.github/workflows/ci_cd.yml b/.github/workflows/ci_cd.yml
index 5afd00e03..0b51dbb4f 100644
--- a/.github/workflows/ci_cd.yml
+++ b/.github/workflows/ci_cd.yml
@@ -75,10 +75,9 @@ jobs:
run: chmod -R 777 openverse_catalog/ tests/
- name: Test
- # Randomize test order to suss out any unseen dependencies
run: |
just build
- just test --random-order
+ just test
push:
name: Publish Docker images
diff --git a/justfile b/justfile
index a06f7c32d..012c328cc 100644
--- a/justfile
+++ b/justfile
@@ -57,6 +57,7 @@ lint:
# The test directory is mounted into the container only during testing
docker-compose {{ DOCKER_FILES }} run \
-v {{ justfile_directory() }}/tests:/usr/local/airflow/tests/ \
+ -v {{ justfile_directory() }}/pytest.ini:/usr/local/airflow/pytest.ini \
--rm \
{{ SERVICE }} \
{{ command }}
diff --git a/pytest.ini b/pytest.ini
new file mode 100644
index 000000000..1db956565
--- /dev/null
+++ b/pytest.ini
@@ -0,0 +1,2 @@
+[pytest]
+addopts = --no-success-flaky-report -n auto
diff --git a/requirements_dev.txt b/requirements_dev.txt
index 60d5eb9d0..411f44fce 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -1,6 +1,8 @@
-r requirements_prod.txt
+flaky==3.7.0
ipython
pytest-mock==3.6.1
pytest-raises==0.11
-pytest-random-order==1.0.4
+pytest-sugar==0.9.4
+pytest-xdist==2.5.0
diff --git a/tests/dags/common/conftest.py b/tests/dags/common/conftest.py
new file mode 100644
index 000000000..a7b4a43c5
--- /dev/null
+++ b/tests/dags/common/conftest.py
@@ -0,0 +1,40 @@
+import boto3
+import pytest
+
+from tests.dags.common.loader.test_s3 import ACCESS_KEY, S3_LOCAL_ENDPOINT, SECRET_KEY
+
+
+def empty_s3_bucket(request):
+ # Bucket names can't be longer than 63 characters or have strange characters
+ bucket_name = f"bucket-{hash(request.node.name)}"
+ print(f"{bucket_name=}")
+ bucket = boto3.resource(
+ "s3",
+ aws_access_key_id=ACCESS_KEY,
+ aws_secret_access_key=SECRET_KEY,
+ endpoint_url=S3_LOCAL_ENDPOINT,
+ ).Bucket(bucket_name)
+
+ def _delete_all_objects():
+ key_list = [{"Key": obj.key} for obj in bucket.objects.all()]
+ if len(list(bucket.objects.all())) > 0:
+ bucket.delete_objects(Delete={"Objects": key_list})
+
+ if bucket.creation_date:
+ _delete_all_objects()
+ else:
+ bucket.create()
+ yield bucket
+ _delete_all_objects()
+
+
+def identifier(request):
+ return f"{hash(request.node.name)}".replace("-", "_")
+
+
+def image_table(identifier):
+ # Parallelized tests need to use distinct database tables
+ return f"image_{identifier}"
diff --git a/tests/dags/common/loader/test_s3.py b/tests/dags/common/loader/test_s3.py
index 51e39d1c3..40fca64fa 100644
--- a/tests/dags/common/loader/test_s3.py
+++ b/tests/dags/common/loader/test_s3.py
@@ -1,9 +1,6 @@
import os
-import socket
from unittest.mock import patch
-from urllib.parse import urlparse
-import boto3
import pytest
from common.loader import s3
@@ -16,29 +13,6 @@ S3_LOCAL_ENDPOINT = os.getenv("S3_LOCAL_ENDPOINT")
S3_TEST_BUCKET = f"cccatalog-storage-{TEST_ID}"
ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")
SECRET_KEY = os.getenv("AWS_SECRET_KEY")
-S3_HOST = socket.gethostbyname(urlparse(S3_LOCAL_ENDPOINT).hostname)
-
-
-def empty_s3_bucket():
- bucket = boto3.resource(
- "s3",
- aws_access_key_id=ACCESS_KEY,
- aws_secret_access_key=SECRET_KEY,
- endpoint_url=S3_LOCAL_ENDPOINT,
- ).Bucket(S3_TEST_BUCKET)
-
- def _delete_all_objects():
- key_list = [{"Key": obj.key} for obj in bucket.objects.all()]
- if len(list(bucket.objects.all())) > 0:
- bucket.delete_objects(Delete={"Objects": key_list})
-
- if bucket.creation_date:
- _delete_all_objects()
- else:
- bucket.create()
- yield bucket
- _delete_all_objects()
def test_copy_file_to_s3_staging_uses_connection_id():
@@ -112,7 +86,6 @@ def test_copy_file_to_s3_staging_given_bucket_name():
)
[email protected]_hosts([S3_HOST])
def test_get_staged_s3_object_finds_object_with_defaults(empty_s3_bucket):
media_prefix = s3.DEFAULT_MEDIA_PREFIX
staging_prefix = s3.STAGING_PREFIX
@@ -124,7 +97,6 @@ def test_get_staged_s3_object_finds_object_with_defaults(empty_s3_bucket):
assert actual_key == test_key
[email protected]_hosts([S3_HOST])
def test_get_staged_s3_object_finds_object_with_givens(empty_s3_bucket):
media_prefix = TEST_MEDIA_PREFIX
staging_prefix = TEST_STAGING_PREFIX
@@ -142,7 +114,6 @@ def test_get_staged_s3_object_finds_object_with_givens(empty_s3_bucket):
assert actual_key == test_key
[email protected]_hosts([S3_HOST])
def test_get_staged_s3_object_complains_with_multiple_keys(empty_s3_bucket):
media_prefix = TEST_MEDIA_PREFIX
staging_prefix = TEST_STAGING_PREFIX
diff --git a/tests/dags/common/loader/test_sql.py b/tests/dags/common/loader/test_sql.py
index e16013acd..b5170f6b0 100644
--- a/tests/dags/common/loader/test_sql.py
+++ b/tests/dags/common/loader/test_sql.py
@@ -1,13 +1,10 @@
import json
import logging
import os
-import socket
import time
from collections import namedtuple
from unittest import mock
-from urllib.parse import urlparse
-import boto3
import psycopg2
import pytest
from airflow.models import TaskInstance
@@ -16,49 +13,40 @@ from common.loader import sql
from common.loader.sql import TSV_COLUMNS, create_column_definitions
from common.storage import columns as col
from common.storage.db_columns import IMAGE_TABLE_COLUMNS
+from flaky import flaky
from psycopg2.errors import InvalidTextRepresentation
-TEST_ID = "testing"
POSTGRES_CONN_ID = os.getenv("TEST_CONN_ID")
POSTGRES_TEST_URI = os.getenv("AIRFLOW_CONN_POSTGRES_OPENLEDGER_TESTING")
-TEST_LOAD_TABLE = f"provider_data_image_{TEST_ID}"
-TEST_IMAGE_TABLE = f"image_{TEST_ID}"
S3_LOCAL_ENDPOINT = os.getenv("S3_LOCAL_ENDPOINT")
-S3_TEST_BUCKET = f"cccatalog-storage-{TEST_ID}"
ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")
SECRET_KEY = os.getenv("AWS_SECRET_KEY")
-S3_HOST = socket.gethostbyname(urlparse(S3_LOCAL_ENDPOINT).hostname)
RESOURCES = os.path.join(os.path.abspath(os.path.dirname(__file__)), "test_resources")
-DROP_LOAD_TABLE_QUERY = f"DROP TABLE IF EXISTS {TEST_LOAD_TABLE} CASCADE;"
-DROP_IMAGE_TABLE_QUERY = f"DROP TABLE IF EXISTS {TEST_IMAGE_TABLE} CASCADE;"
-
LOADING_TABLE_COLUMN_DEFINITIONS = create_column_definitions(
TSV_COLUMNS[IMAGE], is_loading=True
)
-CREATE_LOAD_TABLE_QUERY = f"""CREATE TABLE public.{TEST_LOAD_TABLE} (
+CREATE_LOAD_TABLE_QUERY = f"""CREATE TABLE public.{{}} (
{LOADING_TABLE_COLUMN_DEFINITIONS}
);"""
-UUID_FUNCTION_QUERY = 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;'
-
IMAGE_TABLE_COLUMN_DEFINITIONS = create_column_definitions(IMAGE_TABLE_COLUMNS)
-CREATE_IMAGE_TABLE_QUERY = f"""CREATE TABLE public.{TEST_IMAGE_TABLE} (
+CREATE_IMAGE_TABLE_QUERY = f"""CREATE TABLE public.{{}} (
{IMAGE_TABLE_COLUMN_DEFINITIONS}
);"""
UNIQUE_CONDITION_QUERY = (
- f"CREATE UNIQUE INDEX {TEST_IMAGE_TABLE}_provider_fid_idx"
- f" ON public.{TEST_IMAGE_TABLE}"
+ "CREATE UNIQUE INDEX {table}_provider_fid_idx"
+ " ON public.{table}"
" USING btree (provider, md5(foreign_identifier));"
)
-DROP_IMAGE_INDEX_QUERY = f"DROP INDEX IF EXISTS {TEST_IMAGE_TABLE}_provider_fid_idx;"
+PostgresRef = namedtuple("PostgresRef", ["cursor", "connection"])
ti = mock.Mock(spec=TaskInstance)
ti.xcom_pull.return_value = None
@@ -106,15 +94,20 @@ def create_query_values(
@pytest.fixture
-def postgres():
- Postgres = namedtuple("Postgres", ["cursor", "connection"])
+def load_table(identifier):
+ # Parallelized tests need to use distinct database tables
+ return f"provider_data_image_{identifier}"
+
+
+def postgres(load_table) -> PostgresRef:
conn = psycopg2.connect(POSTGRES_TEST_URI)
cur = conn.cursor()
- drop_command = f"DROP TABLE IF EXISTS {TEST_LOAD_TABLE}"
+ drop_command = f"DROP TABLE IF EXISTS {load_table}"
cur.execute(drop_command)
conn.commit()
- yield Postgres(cursor=cur, connection=conn)
+ yield PostgresRef(cursor=cur, connection=conn)
cur.execute(drop_command)
cur.close()
@@ -123,76 +116,45 @@ def postgres():
@pytest.fixture
-def postgres_with_load_table():
- Postgres = namedtuple("Postgres", ["cursor", "connection"])
- conn = psycopg2.connect(POSTGRES_TEST_URI)
- cur = conn.cursor()
- drop_command = f"DROP TABLE IF EXISTS {TEST_LOAD_TABLE}"
- cur.execute(drop_command)
- conn.commit()
- create_command = CREATE_LOAD_TABLE_QUERY
- cur.execute(create_command)
- conn.commit()
+def postgres_with_load_table(postgres: PostgresRef, load_table) -> PostgresRef:
+ create_command = CREATE_LOAD_TABLE_QUERY.format(load_table)
+ postgres.cursor.execute(create_command)
+ postgres.connection.commit()
- yield Postgres(cursor=cur, connection=conn)
-
- cur.execute(drop_command)
- cur.close()
- conn.commit()
- conn.close()
+ yield postgres
@pytest.fixture
-def postgres_with_load_and_image_table():
- Postgres = namedtuple("Postgres", ["cursor", "connection"])
+def postgres_with_load_and_image_table(load_table, image_table):
conn = psycopg2.connect(POSTGRES_TEST_URI)
cur = conn.cursor()
-
- logging.info(f"dropping load table: {DROP_LOAD_TABLE_QUERY}")
- logging.info(f"dropping image table: {DROP_IMAGE_TABLE_QUERY}")
- cur.execute(DROP_LOAD_TABLE_QUERY)
- cur.execute(DROP_IMAGE_TABLE_QUERY)
- cur.execute(DROP_IMAGE_INDEX_QUERY)
- cur.execute(CREATE_LOAD_TABLE_QUERY)
- cur.execute(UUID_FUNCTION_QUERY)
- cur.execute(CREATE_IMAGE_TABLE_QUERY)
- cur.execute(UNIQUE_CONDITION_QUERY)
+ drop_load_table_query = f"DROP TABLE IF EXISTS {load_table} CASCADE;"
+ drop_image_table_query = f"DROP TABLE IF EXISTS {image_table} CASCADE;"
+ drop_image_index_query = f"DROP INDEX IF EXISTS {image_table}_provider_fid_idx;"
+
+ logging.info(f"dropping load table: {drop_load_table_query}")
+ logging.info(f"dropping image table: {drop_image_table_query}")
+ cur.execute(drop_load_table_query)
+ cur.execute(drop_image_table_query)
+ cur.execute(drop_image_index_query)
+ cur.execute(CREATE_LOAD_TABLE_QUERY.format(load_table))
+ cur.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;')
+ cur.execute(CREATE_IMAGE_TABLE_QUERY.format(image_table))
+ cur.execute(UNIQUE_CONDITION_QUERY.format(table=image_table))
conn.commit()
- yield Postgres(cursor=cur, connection=conn)
+ yield PostgresRef(cursor=cur, connection=conn)
- cur.execute(DROP_LOAD_TABLE_QUERY)
- cur.execute(DROP_IMAGE_TABLE_QUERY)
- cur.execute(DROP_IMAGE_INDEX_QUERY)
+ cur.execute(drop_load_table_query)
+ cur.execute(drop_image_table_query)
+ cur.execute(drop_image_index_query)
cur.close()
conn.commit()
conn.close()
-def empty_s3_bucket():
- bucket = boto3.resource(
- "s3",
- aws_access_key_id=ACCESS_KEY,
- aws_secret_access_key=SECRET_KEY,
- endpoint_url=S3_LOCAL_ENDPOINT,
- ).Bucket(S3_TEST_BUCKET)
-
- def _delete_all_objects():
- key_list = [{"Key": obj.key} for obj in bucket.objects.all()]
- if len(list(bucket.objects.all())) > 0:
- bucket.delete_objects(Delete={"Objects": key_list})
-
- if bucket.creation_date:
- _delete_all_objects()
- else:
- bucket.create()
- yield bucket
- _delete_all_objects()
-
-
-def _load_local_tsv(tmpdir, bucket, tsv_file_name):
+def _load_local_tsv(tmpdir, bucket, tsv_file_name, identifier):
"""
This wraps sql.load_local_data_to_intermediate_table so we can test it
under various conditions.
@@ -205,47 +167,49 @@ def _load_local_tsv(tmpdir, bucket, tsv_file_name):
path = tmpdir.join(test_tsv)
path.write(f_data)
- sql.load_local_data_to_intermediate_table(POSTGRES_CONN_ID, str(path), TEST_ID)
+ sql.load_local_data_to_intermediate_table(POSTGRES_CONN_ID, str(path), identifier)
-def _load_s3_tsv(tmpdir, bucket, tsv_file_name):
+def _load_s3_tsv(tmpdir, bucket, tsv_file_name, identifier):
tsv_file_path = os.path.join(RESOURCES, tsv_file_name)
key = "path/to/object/{tsv_file_name}"
bucket.upload_file(tsv_file_path, key)
sql.load_s3_data_to_intermediate_table(
- POSTGRES_CONN_ID, S3_TEST_BUCKET, key, TEST_ID
+ POSTGRES_CONN_ID, bucket.name, key, identifier
)
-def test_create_loading_table_creates_table(postgres):
+def test_create_loading_table_creates_table(postgres, load_table, identifier):
postgres_conn_id = POSTGRES_CONN_ID
- identifier = TEST_ID
- load_table = TEST_LOAD_TABLE
sql.create_loading_table(postgres_conn_id, identifier, ti)
check_query = (
- f"SELECT EXISTS (" f"SELECT FROM pg_tables WHERE tablename='{load_table}');"
+ f"SELECT EXISTS (SELECT FROM pg_tables WHERE tablename='{load_table}');"
)
postgres.cursor.execute(check_query)
check_result = postgres.cursor.fetchone()[0]
assert check_result
-def test_create_loading_table_errors_if_run_twice_with_same_id(postgres):
+def test_create_loading_table_errors_if_run_twice_with_same_id(postgres, identifier):
postgres_conn_id = POSTGRES_CONN_ID
- identifier = TEST_ID
sql.create_loading_table(postgres_conn_id, identifier, ti)
with pytest.raises(Exception):
sql.create_loading_table(postgres_conn_id, identifier, ti)
+@flaky
@pytest.mark.parametrize("load_function", [_load_local_tsv, _load_s3_tsv])
[email protected]_hosts([S3_HOST])
def test_loaders_load_good_tsv(
- postgres_with_load_table, tmpdir, empty_s3_bucket, load_function
+ postgres_with_load_table,
+ tmpdir,
+ empty_s3_bucket,
+ load_function,
+ load_table,
+ identifier,
):
- load_function(tmpdir, empty_s3_bucket, "none_missing.tsv")
- check_query = f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE};"
+ load_function(tmpdir, empty_s3_bucket, "none_missing.tsv", identifier)
+ check_query = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(check_query)
num_rows = postgres_with_load_table.cursor.fetchone()[0]
assert num_rows == 10
@@ -253,10 +217,17 @@ def test_loaders_load_good_tsv(
@pytest.mark.parametrize("load_function", [_load_local_tsv])
def test_delete_less_than_max_malformed_rows(
- postgres_with_load_table, tmpdir, empty_s3_bucket, load_function
+ postgres_with_load_table,
+ tmpdir,
+ empty_s3_bucket,
+ load_function,
+ load_table,
+ identifier,
):
- load_function(tmpdir, empty_s3_bucket, "malformed_less_than_max_rows.tsv")
- check_query = f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE};"
+ load_function(
+ tmpdir, empty_s3_bucket, "malformed_less_than_max_rows.tsv", identifier
+ )
+ check_query = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(check_query)
num_rows = postgres_with_load_table.cursor.fetchone()[0]
assert num_rows == 6
@@ -264,10 +235,15 @@ def test_delete_less_than_max_malformed_rows(
@pytest.mark.parametrize("load_function", [_load_local_tsv])
def test_delete_max_malformed_rows(
- postgres_with_load_table, tmpdir, empty_s3_bucket, load_function
+ postgres_with_load_table,
+ tmpdir,
+ empty_s3_bucket,
+ load_function,
+ load_table,
+ identifier,
):
- load_function(tmpdir, empty_s3_bucket, "malformed_max_rows.tsv")
- check_query = f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE};"
+ load_function(tmpdir, empty_s3_bucket, "malformed_max_rows.tsv", identifier)
+ check_query = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(check_query)
num_rows = postgres_with_load_table.cursor.fetchone()[0]
assert num_rows == 3
@@ -275,22 +251,29 @@ def test_delete_max_malformed_rows(
@pytest.mark.parametrize("load_function", [_load_local_tsv])
def test_delete_more_than_max_malformed_rows(
- postgres_with_load_table, tmpdir, empty_s3_bucket, load_function
+ postgres_with_load_table, tmpdir, empty_s3_bucket, load_function, identifier
):
with pytest.raises(InvalidTextRepresentation):
- load_function(tmpdir, empty_s3_bucket, "malformed_more_than_max_rows.tsv")
+ load_function(
+ tmpdir, empty_s3_bucket, "malformed_more_than_max_rows.tsv", identifier
+ )
+@flaky
@pytest.mark.parametrize("load_function", [_load_local_tsv, _load_s3_tsv])
[email protected]_hosts([S3_HOST])
def test_loaders_delete_null_url_rows(
- postgres_with_load_table, tmpdir, empty_s3_bucket, load_function
+ postgres_with_load_table,
+ tmpdir,
+ empty_s3_bucket,
+ load_function,
+ load_table,
+ identifier,
):
- load_function(tmpdir, empty_s3_bucket, "url_missing.tsv")
- null_url_check = f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE} WHERE url IS NULL;"
+ load_function(tmpdir, empty_s3_bucket, "url_missing.tsv", identifier)
+ null_url_check = f"SELECT COUNT (*) FROM {load_table} WHERE url IS NULL;"
postgres_with_load_table.cursor.execute(null_url_check)
null_url_num_rows = postgres_with_load_table.cursor.fetchone()[0]
- remaining_row_count = f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE};"
+ remaining_row_count = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(remaining_row_count)
remaining_rows = postgres_with_load_table.cursor.fetchone()[0]
@@ -298,16 +281,21 @@ def test_loaders_delete_null_url_rows(
assert remaining_rows == 2
+@flaky
@pytest.mark.parametrize("load_function", [_load_local_tsv, _load_s3_tsv])
[email protected]_hosts([S3_HOST])
def test_loaders_delete_null_license_rows(
- postgres_with_load_table, tmpdir, empty_s3_bucket, load_function
+ postgres_with_load_table,
+ tmpdir,
+ empty_s3_bucket,
+ load_function,
+ load_table,
+ identifier,
):
- load_function(tmpdir, empty_s3_bucket, "license_missing.tsv")
- license_check = f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE} WHERE license IS NULL;"
+ load_function(tmpdir, empty_s3_bucket, "license_missing.tsv", identifier)
+ license_check = f"SELECT COUNT (*) FROM {load_table} WHERE license IS NULL;"
postgres_with_load_table.cursor.execute(license_check)
null_license_num_rows = postgres_with_load_table.cursor.fetchone()[0]
- remaining_row_count = f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE};"
+ remaining_row_count = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(remaining_row_count)
remaining_rows = postgres_with_load_table.cursor.fetchone()[0]
@@ -315,19 +303,25 @@ def test_loaders_delete_null_license_rows(
assert remaining_rows == 2
+@flaky
@pytest.mark.parametrize("load_function", [_load_local_tsv, _load_s3_tsv])
[email protected]_hosts([S3_HOST])
def test_loaders_delete_null_foreign_landing_url_rows(
- postgres_with_load_table, tmpdir, empty_s3_bucket, load_function
+ postgres_with_load_table,
+ tmpdir,
+ empty_s3_bucket,
+ load_function,
+ load_table,
+ identifier,
):
- load_function(tmpdir, empty_s3_bucket, "foreign_landing_url_missing.tsv")
+ load_function(
+ tmpdir, empty_s3_bucket, "foreign_landing_url_missing.tsv", identifier
+ )
foreign_landing_url_check = (
- f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE} "
- f"WHERE foreign_landing_url IS NULL;"
+ f"SELECT COUNT (*) FROM {load_table} " f"WHERE foreign_landing_url IS NULL;"
)
postgres_with_load_table.cursor.execute(foreign_landing_url_check)
null_foreign_landing_url_num_rows = postgres_with_load_table.cursor.fetchone()[0]
- remaining_row_count = f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE};"
+ remaining_row_count = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(remaining_row_count)
remaining_rows = postgres_with_load_table.cursor.fetchone()[0]
@@ -336,17 +330,21 @@ def test_loaders_delete_null_foreign_landing_url_rows(
@pytest.mark.parametrize("load_function", [_load_local_tsv, _load_s3_tsv])
[email protected]_hosts([S3_HOST])
def test_data_loaders_delete_null_foreign_identifier_rows(
- postgres_with_load_table, tmpdir, empty_s3_bucket, load_function
+ postgres_with_load_table,
+ tmpdir,
+ empty_s3_bucket,
+ load_function,
+ load_table,
+ identifier,
):
- load_function(tmpdir, empty_s3_bucket, "foreign_identifier_missing.tsv")
+ load_function(tmpdir, empty_s3_bucket, "foreign_identifier_missing.tsv", identifier)
foreign_identifier_check = (
- f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE} " f"WHERE foreign_identifier IS NULL;"
+ f"SELECT COUNT (*) FROM {load_table} " f"WHERE foreign_identifier IS NULL;"
)
postgres_with_load_table.cursor.execute(foreign_identifier_check)
null_foreign_identifier_num_rows = postgres_with_load_table.cursor.fetchone()[0]
- remaining_row_count = f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE};"
+ remaining_row_count = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(remaining_row_count)
remaining_rows = postgres_with_load_table.cursor.fetchone()[0]
@@ -355,18 +353,23 @@ def test_data_loaders_delete_null_foreign_identifier_rows(
@pytest.mark.parametrize("load_function", [_load_local_tsv, _load_s3_tsv])
[email protected]_hosts([S3_HOST])
def test_import_data_deletes_duplicate_foreign_identifier_rows(
- postgres_with_load_table, tmpdir, empty_s3_bucket, load_function
+ postgres_with_load_table,
+ tmpdir,
+ empty_s3_bucket,
+ load_function,
+ load_table,
+ identifier,
):
- load_function(tmpdir, empty_s3_bucket, "foreign_identifier_duplicate.tsv")
+ load_function(
+ tmpdir, empty_s3_bucket, "foreign_identifier_duplicate.tsv", identifier
+ )
foreign_id_duplicate_check = (
- f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE} "
- f"WHERE foreign_identifier='135257';"
+ f"SELECT COUNT (*) FROM {load_table} " f"WHERE foreign_identifier='135257';"
)
postgres_with_load_table.cursor.execute(foreign_id_duplicate_check)
foreign_id_duplicate_num_rows = postgres_with_load_table.cursor.fetchone()[0]
- remaining_row_count = f"SELECT COUNT (*) FROM {TEST_LOAD_TABLE};"
+ remaining_row_count = f"SELECT COUNT (*) FROM {load_table};"
postgres_with_load_table.cursor.execute(remaining_row_count)
remaining_rows = postgres_with_load_table.cursor.fetchone()[0]
@@ -375,12 +378,9 @@ def test_import_data_deletes_duplicate_foreign_identifier_rows(
def test_upsert_records_inserts_one_record_to_empty_image_table(
- postgres_with_load_and_image_table, tmpdir
+ postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID = "a"
LAND_URL = "https://images.com/a"
@@ -454,12 +454,9 @@ def test_upsert_records_inserts_one_record_to_empty_image_table(
def test_upsert_records_inserts_two_records_to_image_table(
- postgres_with_load_and_image_table, tmpdir
+ postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID_A = "a"
FID_B = "b"
@@ -494,12 +491,9 @@ def test_upsert_records_inserts_two_records_to_image_table(
def test_upsert_records_replaces_updated_on_and_last_synced_with_source(
- postgres_with_load_and_image_table, tmpdir
+ postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID = "a"
LAND_URL = "https://images.com/a"
@@ -545,11 +539,10 @@ def test_upsert_records_replaces_updated_on_and_last_synced_with_source(
assert updated_last_synced > original_last_synced
-def test_upsert_records_replaces_data(postgres_with_load_and_image_table, tmpdir):
+def test_upsert_records_replaces_data(
+ postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID = "a"
PROVIDER = "images_provider"
@@ -662,12 +655,9 @@ def test_upsert_records_replaces_data(postgres_with_load_and_image_table, tmpdir
def test_upsert_records_does_not_replace_with_nulls(
- postgres_with_load_and_image_table, tmpdir
+ postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID = "a"
PROVIDER = "images_provider"
@@ -762,11 +752,10 @@ def test_upsert_records_does_not_replace_with_nulls(
assert actual_row[height_idx] == HEIGHT_A
-def test_upsert_records_merges_meta_data(postgres_with_load_and_image_table, tmpdir):
+def test_upsert_records_merges_meta_data(
+ postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID = "a"
PROVIDER = "images_provider"
@@ -821,12 +810,9 @@ def test_upsert_records_merges_meta_data(postgres_with_load_and_image_table, tmp
def test_upsert_records_does_not_replace_with_null_values_in_meta_data(
- postgres_with_load_and_image_table, tmpdir
+ postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID = "a"
PROVIDER = "images_provider"
@@ -882,11 +868,10 @@ def test_upsert_records_does_not_replace_with_null_values_in_meta_data(
assert actual_row[metadata_idx] == expected_meta_data
-def test_upsert_records_merges_tags(postgres_with_load_and_image_table, tmpdir):
+def test_upsert_records_merges_tags(
+ postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID = "a"
PROVIDER = "images_provider"
@@ -954,12 +939,9 @@ def test_upsert_records_merges_tags(postgres_with_load_and_image_table, tmpdir):
def test_upsert_records_does_not_replace_tags_with_null(
- postgres_with_load_and_image_table, tmpdir
+ postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID = "a"
PROVIDER = "images_provider"
@@ -1019,11 +1001,10 @@ def test_upsert_records_does_not_replace_tags_with_null(
assert all([t in actual_tags for t in expect_tags])
-def test_upsert_records_replaces_null_tags(postgres_with_load_and_image_table, tmpdir):
+def test_upsert_records_replaces_null_tags(
+ postgres_with_load_and_image_table, tmpdir, load_table, image_table, identifier
+):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID = "a"
PROVIDER = "images_provider"
@@ -1083,10 +1064,8 @@ def test_upsert_records_replaces_null_tags(postgres_with_load_and_image_table, t
assert all([t in actual_tags for t in expect_tags])
-def test_drop_load_table_drops_table(postgres_with_load_table):
+def test_drop_load_table_drops_table(postgres_with_load_table, load_table, identifier):
postgres_conn_id = POSTGRES_CONN_ID
- identifier = TEST_ID
- load_table = TEST_LOAD_TABLE
sql.drop_load_table(postgres_conn_id, identifier, ti)
check_query = (
f"SELECT EXISTS (" f"SELECT FROM pg_tables WHERE tablename='{load_table}');"
@@ -1096,11 +1075,10 @@ def test_drop_load_table_drops_table(postgres_with_load_table):
assert not check_result
-def test_image_expiration(postgres_with_load_and_image_table):
+def test_image_expiration(
+ postgres_with_load_and_image_table, load_table, image_table, identifier
+):
postgres_conn_id = POSTGRES_CONN_ID
- load_table = TEST_LOAD_TABLE
- image_table = TEST_IMAGE_TABLE
- identifier = TEST_ID
FID_A = "a"
FID_B = "b"
diff --git a/tests/dags/common/popularity/test_sql.py b/tests/dags/common/popularity/test_sql.py
index ec1c3f324..f5b52c290 100644
--- a/tests/dags/common/popularity/test_sql.py
+++ b/tests/dags/common/popularity/test_sql.py
@@ -1,159 +1,197 @@
import os
from collections import namedtuple
from textwrap import dedent
+from typing import NamedTuple
import psycopg2
import pytest
from common.popularity import sql
-TEST_ID = "testing"
POSTGRES_CONN_ID = os.getenv("TEST_CONN_ID")
POSTGRES_TEST_URI = os.getenv("AIRFLOW_CONN_POSTGRES_OPENLEDGER_TESTING")
-TEST_IMAGE_VIEW = f"image_view_{TEST_ID}"
-TEST_CONSTANTS = f"image_popularity_constants_{TEST_ID}"
-TEST_METRICS = f"image_popularity_metrics_{TEST_ID}"
-TEST_IMAGE_TABLE = f"image_{TEST_ID}"
-TEST_STANDARDIZED_POPULARITY = f"standardized_popularity_{TEST_ID}"
-TEST_POPULARITY_PERCENTILE = f"popularity_percentile_{TEST_ID}"
-TEST_POPULARITY_CONSTANTS_IDX = "test_popularity_constants_idx"
-TEST_IMAGE_VIEW_ID_IDX = "test_view_id_idx"
-TEST_IMAGE_VIEW_PROVIDER_FID_IDX = "test_view_provider_fid_idx"
-
-UUID_FUNCTION_QUERY = 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;'
-
-DROP_IMAGE_TABLE_QUERY = f"DROP TABLE IF EXISTS {TEST_IMAGE_TABLE} CASCADE;"
-
-CREATE_IMAGE_TABLE_QUERY = (
- f"CREATE TABLE public.{TEST_IMAGE_TABLE} ("
- "identifier uuid PRIMARY KEY DEFAULT public.uuid_generate_v4(),"
- "created_on timestamp with time zone NOT NULL,"
- "updated_on timestamp with time zone NOT NULL,"
- "ingestion_type character varying(80),"
- "provider character varying(80),"
- "source character varying(80),"
- "foreign_identifier character varying(3000),"
- "foreign_landing_url character varying(1000),"
- "url character varying(3000) NOT NULL,"
- "thumbnail character varying(3000),"
- "width integer,"
- "height integer,"
- "filesize integer,"
- "license character varying(50) NOT NULL,"
- "license_version character varying(25),"
- "creator character varying(2000),"
- "creator_url character varying(2000),"
- "title character varying(5000),"
- "meta_data jsonb,"
- "tags jsonb,"
- "watermarked boolean,"
- "last_synced_with_source timestamp with time zone,"
- "removed_from_source boolean NOT NULL"
- ");"
-)
-
-UNIQUE_CONDITION_QUERY = (
- f"CREATE UNIQUE INDEX {TEST_IMAGE_TABLE}_provider_fid_idx"
- f" ON public.{TEST_IMAGE_TABLE}"
- " USING btree (provider, md5(foreign_identifier));"
-)
-
-DROP_TEST_RELATIONS_QUERY = f"""
- DROP MATERIALIZED VIEW IF EXISTS {TEST_IMAGE_VIEW} CASCADE;
- DROP MATERIALIZED VIEW IF EXISTS {TEST_CONSTANTS} CASCADE;
- DROP TABLE IF EXISTS {TEST_METRICS} CASCADE;
- DROP TABLE IF EXISTS {TEST_IMAGE_TABLE} CASCADE;
- DROP FUNCTION IF EXISTS {TEST_STANDARDIZED_POPULARITY} CASCADE;
- DROP FUNCTION IF EXISTS {TEST_POPULARITY_PERCENTILE} CASCADE;
- """
+
+
+class TableInfo(NamedTuple):
+ image: str
+ image_view: str
+ constants: str
+ metrics: str
+ standardized_popularity: str
+ popularity_percentile: str
+ pop_constants_idx: str
+ image_view_idx: str
+ provider_fid_idx: str
+
+
+def table_info(
+ image_table,
+ identifier,
+) -> TableInfo:
+ return TableInfo(
+ image=image_table,
+ image_view=f"image_view_{identifier}",
+ constants=f"image_popularity_constants_{identifier}",
+ metrics=f"image_popularity_metrics_{identifier}",
+ standardized_popularity=f"standardized_popularity_{identifier}",
+ popularity_percentile=f"popularity_percentile_{identifier}",
+ pop_constants_idx=f"test_popularity_constants_{identifier}_idx",
+ image_view_idx=f"test_view_id_{identifier}_idx",
+ provider_fid_idx=f"test_view_provider_fid_{identifier}_idx",
+ )
@pytest.fixture
-def postgres_with_image_table():
+def postgres_with_image_table(table_info):
Postgres = namedtuple("Postgres", ["cursor", "connection"])
conn = psycopg2.connect(POSTGRES_TEST_URI)
cur = conn.cursor()
- cur.execute(DROP_TEST_RELATIONS_QUERY)
- cur.execute(UUID_FUNCTION_QUERY)
- cur.execute(CREATE_IMAGE_TABLE_QUERY)
- cur.execute(UNIQUE_CONDITION_QUERY)
+ drop_test_relations_query = f"""
+ DROP MATERIALIZED VIEW IF EXISTS {table_info.image_view} CASCADE;
+ DROP MATERIALIZED VIEW IF EXISTS {table_info.constants} CASCADE;
+ DROP TABLE IF EXISTS {table_info.metrics} CASCADE;
+ DROP TABLE IF EXISTS {table_info.image} CASCADE;
+ DROP FUNCTION IF EXISTS {table_info.standardized_popularity} CASCADE;
+ DROP FUNCTION IF EXISTS {table_info.popularity_percentile} CASCADE;
+ """
+
+ cur.execute(drop_test_relations_query)
+ cur.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;')
+ cur.execute(
+ f"""
+CREATE TABLE public.{table_info.image} (
+identifier uuid PRIMARY KEY DEFAULT public.uuid_generate_v4(),
+created_on timestamp with time zone NOT NULL,
+updated_on timestamp with time zone NOT NULL,
+ingestion_type character varying(80),
+provider character varying(80),
+source character varying(80),
+foreign_identifier character varying(3000),
+foreign_landing_url character varying(1000),
+url character varying(3000) NOT NULL,
+thumbnail character varying(3000),
+width integer,
+height integer,
+filesize integer,
+license character varying(50) NOT NULL,
+license_version character varying(25),
+creator character varying(2000),
+creator_url character varying(2000),
+title character varying(5000),
+meta_data jsonb,
+tags jsonb,
+watermarked boolean,
+last_synced_with_source timestamp with time zone,
+removed_from_source boolean NOT NULL
+);
+"""
+ )
+ cur.execute(
+ f"""
+CREATE UNIQUE INDEX {table_info.image}_provider_fid_idx
+ON public.{table_info.image}
+USING btree (provider, md5(foreign_identifier));
+"""
+ )
conn.commit()
yield Postgres(cursor=cur, connection=conn)
- cur.execute(DROP_TEST_RELATIONS_QUERY)
+ cur.execute(drop_test_relations_query)
cur.close()
conn.commit()
conn.close()
-def _set_up_image_view(pg, data_query, metrics_dict):
+def _set_up_popularity_metrics(metrics_dict, table_info):
conn_id = POSTGRES_CONN_ID
- _set_up_std_popularity_func(pg, data_query, metrics_dict)
- sql.create_media_view(
+ sql.create_media_popularity_metrics(
conn_id,
- standardized_popularity_func=TEST_STANDARDIZED_POPULARITY,
- table_name=TEST_IMAGE_TABLE,
- db_view_name=TEST_IMAGE_VIEW,
- db_view_id_idx=TEST_IMAGE_VIEW_ID_IDX,
- db_view_provider_fid_idx=TEST_IMAGE_VIEW_PROVIDER_FID_IDX,
+ popularity_metrics_table=table_info.metrics,
+ )
+ sql.update_media_popularity_metrics(
+ conn_id,
+ popularity_metrics=metrics_dict,
+ popularity_metrics_table=table_info.metrics,
)
-def _set_up_std_popularity_func(pg, data_query, metrics_dict):
+def _set_up_popularity_percentile_function(table_info):
conn_id = POSTGRES_CONN_ID
- _set_up_popularity_constants(pg, data_query, metrics_dict)
- sql.create_standardized_media_popularity_function(
+ sql.create_media_popularity_percentile_function(
conn_id,
- function_name=TEST_STANDARDIZED_POPULARITY,
- popularity_constants=TEST_CONSTANTS,
+ popularity_percentile=table_info.popularity_percentile,
+ media_table=table_info.image,
)
-def _set_up_popularity_constants(pg, data_query, metrics_dict):
+def _set_up_popularity_constants(
+ pg,
+ data_query,
+ metrics_dict,
+ table_info,
+):
conn_id = POSTGRES_CONN_ID
- _set_up_popularity_percentile_function()
- _set_up_popularity_metrics(metrics_dict)
+ _set_up_popularity_percentile_function(table_info)
+ _set_up_popularity_metrics(metrics_dict, table_info)
pg.cursor.execute(data_query)
pg.connection.commit()
sql.create_media_popularity_constants_view(
conn_id,
- popularity_constants=TEST_CONSTANTS,
- popularity_constants_idx=TEST_POPULARITY_CONSTANTS_IDX,
- popularity_metrics=TEST_METRICS,
- popularity_percentile=TEST_POPULARITY_PERCENTILE,
+ popularity_constants=table_info.constants,
+ popularity_constants_idx=table_info.pop_constants_idx,
+ popularity_metrics=table_info.metrics,
+ popularity_percentile=table_info.popularity_percentile,
)
-def _set_up_popularity_percentile_function():
+def _set_up_std_popularity_func(
+ pg,
+ data_query,
+ metrics_dict,
+ table_info,
+):
conn_id = POSTGRES_CONN_ID
- sql.create_media_popularity_percentile_function(
+ _set_up_popularity_constants(
+ pg,
+ data_query,
+ metrics_dict,
+ table_info,
+ )
+ sql.create_standardized_media_popularity_function(
conn_id,
- popularity_percentile=TEST_POPULARITY_PERCENTILE,
- media_table=TEST_IMAGE_TABLE,
+ function_name=table_info.standardized_popularity,
+ popularity_constants=table_info.constants,
)
-def _set_up_popularity_metrics(metrics_dict):
+def _set_up_image_view(
+ pg,
+ data_query,
+ metrics_dict,
+ table_info,
+):
conn_id = POSTGRES_CONN_ID
- sql.create_media_popularity_metrics(
- conn_id,
- popularity_metrics_table=TEST_METRICS,
- )
- sql.update_media_popularity_metrics(
+ _set_up_std_popularity_func(pg, data_query, metrics_dict, table_info)
+ sql.create_media_view(
conn_id,
- popularity_metrics=metrics_dict,
- popularity_metrics_table=TEST_METRICS,
+ standardized_popularity_func=table_info.standardized_popularity,
+ table_name=table_info.image,
+ db_view_name=table_info.image_view,
+ db_view_id_idx=table_info.image_view_idx,
+ db_view_provider_fid_idx=table_info.provider_fid_idx,
)
-def test_popularity_percentile_function_calculates(postgres_with_image_table):
- image_table = TEST_IMAGE_TABLE
+def test_popularity_percentile_function_calculates(
+ postgres_with_image_table, table_info
+):
data_query = dedent(
f"""
- INSERT INTO {image_table} (
+ INSERT INTO {table_info.image} (
created_on, updated_on, provider, foreign_identifier, url,
meta_data, license, removed_from_source
)
@@ -187,10 +225,10 @@ def test_popularity_percentile_function_calculates(postgres_with_image_table):
)
postgres_with_image_table.cursor.execute(data_query)
postgres_with_image_table.connection.commit()
- _set_up_popularity_percentile_function()
+ _set_up_popularity_percentile_function(table_info)
mp_perc_1 = dedent(
f"""
- SELECT {TEST_POPULARITY_PERCENTILE}('my_provider', 'views', 0.5);
+ SELECT {table_info.popularity_percentile}('my_provider', 'views', 0.5);
"""
)
postgres_with_image_table.cursor.execute(mp_perc_1)
@@ -199,7 +237,7 @@ def test_popularity_percentile_function_calculates(postgres_with_image_table):
assert actual_percentile_val == expect_percentile_val
mp_perc_2 = dedent(
f"""
- SELECT {TEST_POPULARITY_PERCENTILE}('diff_provider', 'comments', 0.3);
+ SELECT {table_info.popularity_percentile}('diff_provider', 'comments', 0.3);
"""
)
postgres_with_image_table.cursor.execute(mp_perc_2)
@@ -209,12 +247,11 @@ def test_popularity_percentile_function_calculates(postgres_with_image_table):
def test_popularity_percentile_function_nones_when_missing_type(
- postgres_with_image_table,
+ postgres_with_image_table, table_info
):
- image_table = TEST_IMAGE_TABLE
data_query = dedent(
f"""
- INSERT INTO {image_table} (
+ INSERT INTO {table_info.image} (
created_on, updated_on, provider, foreign_identifier, url,
meta_data, license, removed_from_source
)
@@ -232,10 +269,10 @@ def test_popularity_percentile_function_nones_when_missing_type(
)
postgres_with_image_table.cursor.execute(data_query)
postgres_with_image_table.connection.commit()
- _set_up_popularity_percentile_function()
+ _set_up_popularity_percentile_function(table_info)
mp_perc_3 = dedent(
f"""
- SELECT {TEST_POPULARITY_PERCENTILE}('diff_provider', 'views', 0.3);
+ SELECT {table_info.popularity_percentile}('diff_provider', 'views', 0.3);
"""
)
postgres_with_image_table.cursor.execute(mp_perc_3)
@@ -243,11 +280,12 @@ def test_popularity_percentile_function_nones_when_missing_type(
assert actual_percentile_val is None
-def test_constants_view_adds_values_and_constants(postgres_with_image_table):
- image_table = TEST_IMAGE_TABLE
+def test_constants_view_adds_values_and_constants(
+ postgres_with_image_table, table_info
+):
data_query = dedent(
f"""
- INSERT INTO {image_table} (
+ INSERT INTO {table_info.image} (
created_on, updated_on, provider, foreign_identifier, url,
meta_data, license, removed_from_source
)
@@ -283,9 +321,11 @@ def test_constants_view_adds_values_and_constants(postgres_with_image_table):
"my_provider": {"metric": "views", "percentile": 0.5},
"diff_provider": {"metric": "comments", "percentile": 0.8},
}
- _set_up_popularity_constants(postgres_with_image_table, data_query, metrics)
+ _set_up_popularity_constants(
+ postgres_with_image_table, data_query, metrics, table_info
+ )
- check_query = f"SELECT * FROM {TEST_CONSTANTS};"
+ check_query = f"SELECT * FROM {table_info.constants};"
postgres_with_image_table.cursor.execute(check_query)
expect_rows = [
("diff_provider", "comments", 0.8, 50.0, 50.0, 12.5),
@@ -296,11 +336,12 @@ def test_constants_view_adds_values_and_constants(postgres_with_image_table):
assert expect_row == pytest.approx(sorted_row)
-def test_constants_view_handles_zeros_and_missing(postgres_with_image_table):
- image_table = TEST_IMAGE_TABLE
+def test_constants_view_handles_zeros_and_missing(
+ postgres_with_image_table, table_info
+):
data_query = dedent(
f"""
- INSERT INTO {image_table} (
+ INSERT INTO {table_info.image} (
created_on, updated_on, provider, foreign_identifier, url,
meta_data, license, removed_from_source
)
@@ -336,9 +377,11 @@ def test_constants_view_handles_zeros_and_missing(postgres_with_image_table):
"my_provider": {"metric": "views", "percentile": 0.8},
"diff_provider": {"metric": "comments", "percentile": 0.8},
}
- _set_up_popularity_constants(postgres_with_image_table, data_query, metrics)
+ _set_up_popularity_constants(
+ postgres_with_image_table, data_query, metrics, table_info
+ )
- check_query = f"SELECT * FROM {TEST_CONSTANTS};"
+ check_query = f"SELECT * FROM {table_info.constants};"
postgres_with_image_table.cursor.execute(check_query)
expect_rows = [
("diff_provider", "comments", 0.8, None, None, None),
@@ -349,11 +392,12 @@ def test_constants_view_handles_zeros_and_missing(postgres_with_image_table):
assert expect_row == pytest.approx(sorted_row)
-def test_standardized_popularity_function_calculates(postgres_with_image_table):
- image_table = TEST_IMAGE_TABLE
+def test_standardized_popularity_function_calculates(
+ postgres_with_image_table, table_info
+):
data_query = dedent(
f"""
- INSERT INTO {image_table} (
+ INSERT INTO {table_info.image} (
created_on, updated_on, provider, foreign_identifier, url,
meta_data, license, removed_from_source
)
@@ -378,8 +422,10 @@ def test_standardized_popularity_function_calculates(postgres_with_image_table):
"diff_provider": {"metric": "comments", "percentile": 0.5},
"other_provider": {"metric": "likes", "percentile": 0.5},
}
- _set_up_std_popularity_func(postgres_with_image_table, data_query, metrics)
- check_query = f"SELECT * FROM {TEST_CONSTANTS};"
+ _set_up_std_popularity_func(
+ postgres_with_image_table, data_query, metrics, table_info
+ )
+ check_query = f"SELECT * FROM {table_info.constants};"
postgres_with_image_table.cursor.execute(check_query)
print(list(postgres_with_image_table.cursor))
arg_list = [
@@ -398,7 +444,7 @@ def test_standardized_popularity_function_calculates(postgres_with_image_table):
print(arg_list[i])
std_pop_query = dedent(
f"""
- SELECT {TEST_STANDARDIZED_POPULARITY}(
+ SELECT {table_info.standardized_popularity}(
'{arg_list[i][0]}',
'{arg_list[i][1]}'::jsonb
);
@@ -410,12 +456,10 @@ def test_standardized_popularity_function_calculates(postgres_with_image_table):
assert actual_std_pop_val == expect_std_pop_val
-def test_image_view_calculates_std_pop(postgres_with_image_table):
- image_table = TEST_IMAGE_TABLE
- image_view = TEST_IMAGE_VIEW
+def test_image_view_calculates_std_pop(postgres_with_image_table, table_info):
data_query = dedent(
f"""
- INSERT INTO {image_table} (
+ INSERT INTO {table_info.image} (
created_on, updated_on, provider, foreign_identifier, url,
meta_data, license, removed_from_source
)
@@ -439,11 +483,11 @@ def test_image_view_calculates_std_pop(postgres_with_image_table):
"""
)
metrics = {"my_provider": {"metric": "views", "percentile": 0.5}}
- _set_up_image_view(postgres_with_image_table, data_query, metrics)
+ _set_up_image_view(postgres_with_image_table, data_query, metrics, table_info)
check_query = dedent(
f"""
SELECT foreign_identifier, standardized_popularity
- FROM {image_view};
+ FROM {table_info.image_view};
"""
)
postgres_with_image_table.cursor.execute(check_query)
diff --git a/tests/dags/providers/provider_api_scripts/test_freesound.py b/tests/dags/providers/provider_api_scripts/test_freesound.py
index 5a6953257..2eef8b745 100644
--- a/tests/dags/providers/provider_api_scripts/test_freesound.py
+++ b/tests/dags/providers/provider_api_scripts/test_freesound.py
@@ -56,7 +56,8 @@ def test_get_audio_pages_returns_correctly_with_no_results():
def test_get_audio_file_size_retries_and_does_not_raise(audio_data):
expected_result = None
- with patch("requests.head") as head_patch:
+ # Patch the sleep function so it doesn't take long
+ with patch("requests.head") as head_patch, patch("time.sleep"):
head_patch.side_effect = SSLError("whoops")
actual_result = freesound._extract_audio_data(audio_data)
diff --git a/tests/dags/providers/provider_api_scripts/test_jamendo.py b/tests/dags/providers/provider_api_scripts/test_jamendo.py
index f1b1659d0..e11951a61 100644
--- a/tests/dags/providers/provider_api_scripts/test_jamendo.py
+++ b/tests/dags/providers/provider_api_scripts/test_jamendo.py
@@ -3,6 +3,7 @@ import logging
from pathlib import Path
from unittest.mock import patch
+import pytest
from common.licenses import LicenseInfo
from providers.provider_api_scripts import jamendo
@@ -15,6 +16,14 @@ logging.basicConfig(
)
[email protected](autouse=True)
+def cleanse_url():
+ with patch("providers.provider_api_scripts.jamendo._cleanse_url") as mock_cleanse:
+ # Prevent calling out to Jamendo & speed up tests
+ mock_cleanse.side_effect = lambda x: x
+ yield
+
+
def test_get_image_pages_returns_correctly_with_none_json():
expect_result = None
with patch.object(