more fixes

This commit is contained in:
Kenneth Kehl
2024-05-17 10:25:09 -07:00
parent 7302e4c811
commit 1b172553f5
28 changed files with 127 additions and 107 deletions
@@ -9,7 +9,7 @@ from notifications_utils.clients.antivirus.antivirus_client import (
)
@pytest.fixture(scope="function")
@pytest.fixture()
def antivirus(app, mocker):
client = AntivirusClient()
app.config["ANTIVIRUS_API_HOST"] = "https://antivirus"
@@ -39,25 +39,33 @@ def test_scan_document(antivirus, rmock):
def test_should_raise_for_status(antivirus, rmock):
with pytest.raises(AntivirusError) as excinfo:
rmock.request(
"POST",
"https://antivirus/scan",
json={"error": "Antivirus error"},
status_code=400,
)
antivirus.scan(io.BytesIO(b"document"))
_test_one_statement_for_status(antivirus, rmock)
assert excinfo.value.message == "Antivirus error"
assert excinfo.value.status_code == 400
def _test_one_statement_for_status(antivirus, rmock):
rmock.request(
"POST",
"https://antivirus/scan",
json={"error": "Antivirus error"},
status_code=400,
)
antivirus.scan(io.BytesIO(b"document"))
def test_should_raise_for_connection_errors(antivirus, rmock):
with pytest.raises(AntivirusError) as excinfo:
rmock.request(
"POST", "https://antivirus/scan", exc=requests.exceptions.ConnectTimeout
)
antivirus.scan(io.BytesIO(b"document"))
_test_one_statement_for_connection_errors(antivirus, rmock)
assert excinfo.value.message == "connection error"
assert excinfo.value.status_code == 503
def _test_one_statement_for_connection_errors(antivirus, rmock):
rmock.request(
"POST", "https://antivirus/scan", exc=requests.exceptions.ConnectTimeout
)
antivirus.scan(io.BytesIO(b"document"))
@@ -89,27 +89,27 @@ def test_should_raise_exception_if_raise_set_to_true(
):
with pytest.raises(KeyError) as e:
failing_redis_client.get("test", raise_exception=True)
assert str(e.value) == "get failed"
assert str(e.value) == "'get failed'"
with pytest.raises(KeyError) as e:
failing_redis_client.set("test", "test", raise_exception=True)
assert str(e.value) == "set failed"
assert str(e.value) == "'set failed'"
with pytest.raises(KeyError) as e:
failing_redis_client.incr("test", raise_exception=True)
assert str(e.value) == "incr failed"
assert str(e.value) == "'incr failed'"
with pytest.raises(KeyError) as e:
failing_redis_client.exceeded_rate_limit("test", 100, 200, raise_exception=True)
assert str(e.value) == "pipeline failed"
assert str(e.value) == "'pipeline failed'"
with pytest.raises(KeyError) as e:
failing_redis_client.delete("test", raise_exception=True)
assert str(e.value) == "delete failed"
assert str(e.value) == "'delete failed'"
with pytest.raises(KeyError) as e:
failing_redis_client.delete_by_pattern("pattern", raise_exception=True)
assert str(e.value) == "delete by pattern failed"
assert str(e.value) == "'delete by pattern failed'"
def test_should_not_call_if_not_enabled(mocked_redis_client, delete_mock):
@@ -200,7 +200,7 @@ def test_delete_multi(mocked_redis_client):
@pytest.mark.parametrize(
"input,output",
("input", "output"),
[
(b"asdf", b"asdf"),
("asdf", "asdf"),
@@ -4,7 +4,7 @@ from notifications_utils.clients.redis import RequestCache
from notifications_utils.clients.redis.redis_client import RedisClient
@pytest.fixture(scope="function")
@pytest.fixture()
def mocked_redis_client(app):
app.config["REDIS_ENABLED"] = True
redis_client = RedisClient()
@@ -12,19 +12,19 @@ def mocked_redis_client(app):
return redis_client
@pytest.fixture
@pytest.fixture()
def cache(mocked_redis_client):
return RequestCache(mocked_redis_client)
@pytest.mark.parametrize(
"args, kwargs, expected_cache_key",
(
("args", "kwargs", "expected_cache_key"),
[
([1, 2, 3], {}, "1-2-3-None-None-None"),
([1, 2, 3, 4, 5, 6], {}, "1-2-3-4-5-6"),
([1, 2, 3], {"x": 4, "y": 5, "z": 6}, "1-2-3-4-5-6"),
([1, 2, 3, 4], {"y": 5}, "1-2-3-4-5-None"),
),
],
)
def test_set(
mocker,
@@ -60,13 +60,13 @@ def test_set(
@pytest.mark.parametrize(
"cache_set_call, expected_redis_client_ttl",
(
("cache_set_call", "expected_redis_client_ttl"),
[
(0, 0),
(1, 1),
(1.111, 1),
("2000", 2_000),
),
],
)
def test_set_with_custom_ttl(
mocker,
@@ -9,7 +9,7 @@ from notifications_utils.clients.zendesk.zendesk_client import (
)
@pytest.fixture(scope="function")
@pytest.fixture()
def zendesk_client(app):
client = ZendeskClient()
@@ -67,8 +67,8 @@ def test_zendesk_client_send_ticket_to_zendesk_error(
@pytest.mark.parametrize(
"p1_arg, expected_tags, expected_priority",
(
("p1_arg", "expected_tags", "expected_priority"),
[
(
{},
["govuk_notify_support"],
@@ -88,7 +88,7 @@ def test_zendesk_client_send_ticket_to_zendesk_error(
["govuk_notify_emergency"],
"urgent",
),
),
],
)
def test_notify_support_ticket_request_data(p1_arg, expected_tags, expected_priority):
notify_ticket_form = NotifySupportTicket("subject", "message", "question", **p1_arg)
@@ -126,7 +126,7 @@ def test_notify_support_ticket_request_data_with_message_hidden_from_requester()
@pytest.mark.parametrize(
"name, zendesk_name", [("Name", "Name"), (None, "(no name supplied)")]
("name", "zendesk_name"), [("Name", "Name"), (None, "(no name supplied)")]
)
def test_notify_support_ticket_request_data_with_user_name_and_email(
name, zendesk_name
@@ -145,7 +145,14 @@ def test_notify_support_ticket_request_data_with_user_name_and_email(
@pytest.mark.parametrize(
"custom_fields, tech_ticket_tag, categories, org_id, org_type, service_id",
(
"custom_fields",
"tech_ticket_tag",
"categories",
"org_id",
"org_type",
"service_id",
),
[
(
{"technical_ticket": True},
+3 -3
View File
@@ -9,7 +9,7 @@ class FakeService:
id = "1234"
@pytest.fixture
@pytest.fixture()
def app():
flask_app = Flask(__name__)
ctx = flask_app.app_context()
@@ -20,7 +20,7 @@ def app():
ctx.pop()
@pytest.fixture
@pytest.fixture()
def celery_app(mocker):
app = Flask(__name__)
app.config["CELERY"] = {"broker_url": "foo"}
@@ -39,7 +39,7 @@ def sample_service():
return FakeService()
@pytest.fixture
@pytest.fixture()
def rmock():
with requests_mock.mock() as rmock:
yield rmock
@@ -38,7 +38,7 @@ def test_base64_converter_to_url(python_val):
@pytest.mark.parametrize(
"url_val,expectation",
("url_val", "expectation"),
[
(
"this_is_valid_base64_but_is_too_long_to_be_a_uuid",
@@ -80,7 +80,7 @@ def test_matches_keys_to_placeholder_names():
@pytest.mark.parametrize(
"template_content, template_subject, expected",
("template_content", "template_subject", "expected"),
[
("the quick brown fox", "jumps", []),
("the quick ((colour)) fox", "jumps", ["colour"]),
+2 -2
View File
@@ -34,7 +34,7 @@ def test_constants():
assert Postage.UK == "united-kingdom"
@pytest.mark.parametrize("synonym, canonical", ADDITIONAL_SYNONYMS)
@pytest.mark.parametrize(("synonym", "canonical"), ADDITIONAL_SYNONYMS)
def test_hand_crafted_synonyms_map_to_canonical_countries(synonym, canonical):
exceptions_to_canonical_countries = [
"Easter Island",
@@ -55,7 +55,7 @@ def test_hand_crafted_synonyms_map_to_canonical_countries(synonym, canonical):
assert Country(synonym).canonical_name == canonical
@pytest.mark.parametrize("welsh_name, canonical", WELSH_NAMES)
@pytest.mark.parametrize(("welsh_name", "canonical"), WELSH_NAMES)
def test_welsh_names_map_to_canonical_countries(welsh_name, canonical):
assert Country(canonical).canonical_name == canonical
assert Country(welsh_name).canonical_name == canonical
@@ -11,8 +11,8 @@ def _country_not_found(*test_case):
@pytest.mark.parametrize(
"alpha_2, expected_name",
(
("alpha_2", "expected_name"),
[
("AF", "Afghanistan"),
("AL", "Albania"),
("DZ", "Algeria"),
@@ -262,15 +262,15 @@ def _country_not_found(*test_case):
("ZM", "Zambia"),
("ZW", "Zimbabwe"),
("AX", "Åland Islands"),
),
],
)
def test_iso_alpha_2_country_codes(alpha_2, expected_name):
assert Country(alpha_2).canonical_name == expected_name
@pytest.mark.parametrize(
"alpha_3, expected_name",
(
("alpha_3", "expected_name"),
[
_country_not_found("AFG", "Afghanistan"),
_country_not_found("ALB", "Albania"),
_country_not_found("DZA", "Algeria"),
@@ -520,7 +520,7 @@ def test_iso_alpha_2_country_codes(alpha_2, expected_name):
_country_not_found("ZMB", "Zambia"),
_country_not_found("ZWE", "Zimbabwe"),
_country_not_found("ALA", "Åland Islands"),
),
],
)
def test_iso_alpha_3_country_codes(alpha_3, expected_name):
assert Country(alpha_3).canonical_name == expected_name
+5 -5
View File
@@ -23,7 +23,7 @@ def test_returns_a_string_without_placeholders(content):
@pytest.mark.parametrize(
"template_content,data,expected",
("template_content", "data", "expected"),
[
("((colour))", {"colour": "red"}, "red"),
("the quick ((colour)) fox", {"colour": "brown"}, "the quick brown fox"),
@@ -111,7 +111,7 @@ def test_replacement_of_placeholders(template_content, data, expected):
@pytest.mark.parametrize(
"template_content,data,expected",
("template_content", "data", "expected"),
[
(
"((code)) is your security code",
@@ -142,7 +142,7 @@ def test_optional_redacting_of_missing_values(template_content, data, expected):
@pytest.mark.parametrize(
"content,expected",
("content", "expected"),
[
("((colour))", "<span class='placeholder'>((colour))</span>"),
(
@@ -189,7 +189,7 @@ def test_formatting_of_placeholders(content, expected):
@pytest.mark.parametrize(
"content, values, expected",
("content", "values", "expected"),
[
(
"((name)) ((colour))",
@@ -244,7 +244,7 @@ def test_what_will_trigger_conditional_placeholder(value):
@pytest.mark.parametrize(
"values, expected, expected_as_markdown",
("values", "expected", "expected_as_markdown"),
[
(
{"placeholder": []},
@@ -4,7 +4,13 @@ from notifications_utils.field import Field
@pytest.mark.parametrize(
"content, values, expected_stripped, expected_escaped, expected_passthrough",
(
"content",
"values",
"expected_stripped",
"expected_escaped",
"expected_passthrough",
),
[
(
"string <em>with</em> html",
+1 -1
View File
@@ -571,7 +571,7 @@ def test_autolink_urls_applies_correct_attributes(extra_kwargs, expected_html):
@pytest.mark.parametrize(
"content", ("without link", "with link to https://example.com")
"content", ["without link", "with link to https://example.com"]
)
def test_autolink_urls_returns_markup(content):
assert isinstance(autolink_urls(content), Markup)
@@ -50,7 +50,7 @@ def test_missing_data():
],
)
@pytest.mark.parametrize(
"key, should_be_present",
("key", "should_be_present"),
[
("foo", True),
("f_o_o", True),
@@ -12,7 +12,7 @@ def test_international_billing_rates_exists():
@pytest.mark.parametrize(
"country_prefix, values", sorted(INTERNATIONAL_BILLING_RATES.items())
("country_prefix", "values"), sorted(INTERNATIONAL_BILLING_RATES.items())
)
def test_international_billing_rates_are_in_correct_format(country_prefix, values):
assert isinstance(country_prefix, str)
@@ -38,7 +38,7 @@ def test_country_codes():
@pytest.mark.parametrize(
"number, expected",
("number", "expected"),
[
("+48123654789", False), # Poland alpha: Yes
("+1-403-123-5687", True), # Canada alpha: No
@@ -12,7 +12,14 @@ from notifications_utils.letter_timings import (
@freeze_time("2017-07-14 13:59:59") # Friday, before print deadline (3PM EST)
@pytest.mark.parametrize(
"upload_time, expected_print_time, is_printed, first_class, expected_earliest, expected_latest",
(
"upload_time",
"expected_print_time",
"is_printed",
"first_class",
"expected_earliest",
"expected_latest",
),
[
# EST
# ==================================================================
@@ -319,7 +319,6 @@ def test_ordered_list(markdown_function, expected):
("*one\n" "*two\n" "*three\n"), # no space
("* one\n" "* two\n" "* three\n"), # single space
("* one\n" "* two\n" "* three\n"), # two spaces
("* one\n" "* two\n" "* three\n"), # tab
("- one\n" "- two\n" "- three\n"), # dash as bullet
pytest.param(
("+ one\n" "+ two\n" "+ three\n"), # plus as bullet
@@ -6,7 +6,7 @@ from notifications_utils.field import Placeholder
@pytest.mark.parametrize(
"body, expected",
("body", "expected"),
[
("((with-brackets))", "with-brackets"),
("without-brackets", "without-brackets"),
@@ -17,7 +17,7 @@ def test_placeholder_returns_name(body, expected):
@pytest.mark.parametrize(
"body, is_conditional",
("body", "is_conditional"),
[
("not a conditional", False),
("not? a conditional", False),
@@ -29,7 +29,7 @@ def test_placeholder_identifies_conditional(body, is_conditional):
@pytest.mark.parametrize(
"body, conditional_text",
("body", "conditional_text"),
[
("a??b", "b"),
("a?? b ", " b "),
@@ -41,12 +41,12 @@ def test_placeholder_gets_conditional_text(body, conditional_text):
def test_placeholder_raises_if_accessing_conditional_text_on_non_conditional():
with pytest.raises(ValueError):
with pytest.raises(ValueError): # noqa, flake8 says ValueError not specific enough
Placeholder("hello").conditional_text
@pytest.mark.parametrize(
"body, value, result",
("body", "value", "result"),
[
("a??b", "Yes", "b"),
("a??b", "No", ""),
@@ -57,7 +57,7 @@ def test_placeholder_gets_conditional_body(body, value, result):
def test_placeholder_raises_if_getting_conditional_body_on_non_conditional():
with pytest.raises(ValueError):
with pytest.raises(ValueError): # noqa, flake8 says ValueError not specific enough
Placeholder("hello").get_conditional_body("Yes")
@@ -716,7 +716,7 @@ def test_valid_with_international_parameter(address, international, expected_val
@pytest.mark.parametrize(
"address",
(
[
"""
Too short, valid postcode
SW1A 1AA
@@ -745,7 +745,7 @@ def test_valid_with_international_parameter(address, international, expected_val
7
Bhutan
""",
),
],
)
def test_valid_last_line_too_short_too_long(address):
postal_address = PostalAddress(address, allow_international_letters=True)
@@ -44,7 +44,7 @@ def _index_rows(rows):
@pytest.mark.parametrize(
("template_type", "expected"),
(
[
("email", ["email address"]),
("sms", ["phone number"]),
(
@@ -60,7 +60,7 @@ def _index_rows(rows):
"address line 7",
],
),
),
],
)
def test_recipient_column_headers(template_type, expected):
recipients = RecipientCSV("", template=_sample_template(template_type))
@@ -275,7 +275,7 @@ def test_get_rows_only_iterates_over_file_once(mocker):
@pytest.mark.parametrize(
("file_contents", "template_type,expected"),
("file_contents", "template_type", "expected"),
[
(
"""
@@ -1111,7 +1111,7 @@ def test_recipients_can_be_accessed_by_index(index, expected_row):
assert recipients[index][key].data == value
@pytest.mark.parametrize("international_sms", (True, False))
@pytest.mark.parametrize("international_sms", [True, False])
def test_multiple_sms_recipient_columns(international_sms):
recipients = RecipientCSV(
"""
@@ -153,7 +153,7 @@ def test_detect_us_phone_numbers(phone_number):
@pytest.mark.parametrize(
"phone_number, expected_info",
("phone_number", "expected_info"),
[
# (
# "+4407900900123",
@@ -285,13 +285,12 @@ def test_valid_us_phone_number_can_be_formatted_consistently(phone_number):
@pytest.mark.parametrize(
"phone_number, expected_formatted",
("phone_number", "expected_formatted"),
[
# ("+44071234567890", "+4471234567890"),
("1-202-555-0104", "+12025550104"),
("+12025550104", "+12025550104"),
("12025550104", "+12025550104"),
("+12025550104", "+12025550104"),
# ("+23051234567", "+23051234567"),
],
)
@@ -304,7 +303,7 @@ def test_valid_international_phone_number_can_be_formatted_consistently(
)
@pytest.mark.parametrize("phone_number, error_message", invalid_us_phone_numbers)
@pytest.mark.parametrize(("phone_number", "error_message"), invalid_us_phone_numbers)
@pytest.mark.parametrize(
"extra_args",
[
@@ -318,7 +317,7 @@ def test_phone_number_rejects_invalid_values(extra_args, phone_number, error_mes
assert error_message == str(e.value)
@pytest.mark.parametrize("phone_number, error_message", invalid_phone_numbers)
@pytest.mark.parametrize(("phone_number", "error_message"), invalid_phone_numbers)
def test_phone_number_rejects_invalid_international_values(phone_number, error_message):
with pytest.raises(InvalidPhoneError) as e:
validate_phone_number(phone_number, international=True)
@@ -384,7 +383,7 @@ def test_validates_against_guestlist_of_email_addresses(email_address):
@pytest.mark.parametrize(
"phone_number, expected_formatted",
("phone_number", "expected_formatted"),
[
# ("+4407900900123", "+44 7900 900123"), # UK
# ("+44(0)7900900123", "+44 7900 900123"), # UK
@@ -403,7 +402,7 @@ def test_format_us_and_international_phone_numbers(phone_number, expected_format
@pytest.mark.parametrize(
"recipient, expected_formatted",
("recipient", "expected_formatted"),
[
(True, ""),
(False, ""),
@@ -5,7 +5,7 @@ from notifications_utils.request_helper import NotifyRequest, _check_proxy_heade
@pytest.mark.parametrize(
"header,secrets,expected",
("header", "secrets", "expected"),
[
(
{"X-Custom-Forwarder": "right_key"},
@@ -48,7 +48,7 @@ def test_request_header_authorization(header, secrets, expected):
@pytest.mark.parametrize(
"secrets,expected",
("secrets", "expected"),
[
(["old_key", "right_key"], (False, "Header missing")),
],
@@ -7,7 +7,7 @@ from notifications_utils.safe_string import (
@pytest.mark.parametrize(
"unsafe_string, expected_safe",
("unsafe_string", "expected_safe"),
[
("name with spaces", "name.with.spaces"),
("singleword", "singleword"),
@@ -26,7 +26,7 @@ def test_email_safe_return_dot_separated_email_local_part(unsafe_string, expecte
@pytest.mark.parametrize(
"unsafe_string, expected_safe",
("unsafe_string", "expected_safe"),
[
("name with spaces", "name-with-spaces"),
("singleword", "singleword"),
@@ -42,7 +42,7 @@ params, ids = zip(
)
@pytest.mark.parametrize("char, expected", params, ids=ids)
@pytest.mark.parametrize(("char", "expected"), params, ids=ids)
@pytest.mark.parametrize("cls", [SanitiseSMS, SanitiseASCII])
def test_encode_chars_the_same_for_ascii_and_sms(char, expected, cls):
assert cls.encode_char(char) == expected
@@ -64,7 +64,7 @@ params, ids = zip(
)
@pytest.mark.parametrize("char, expected_sms, expected_ascii", params, ids=ids)
@pytest.mark.parametrize(("char", "expected_sms", "expected_ascii"), params, ids=ids)
def test_encode_chars_different_between_ascii_and_sms(
char, expected_sms, expected_ascii
):
@@ -73,7 +73,7 @@ def test_encode_chars_different_between_ascii_and_sms(
@pytest.mark.parametrize(
"codepoint, char",
("codepoint", "char"),
[
("0041", "A"),
("0061", "a"),
@@ -87,12 +87,12 @@ def test_get_unicode_char_from_codepoint(codepoint, char):
"bad_input", ["", "GJ", "00001", '0001";import sys;sys.exit(0)"']
)
def test_get_unicode_char_from_codepoint_rejects_bad_input(bad_input):
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=bad_input):
SanitiseText.get_unicode_char_from_codepoint(bad_input)
@pytest.mark.parametrize(
"content, expected",
("content", "expected"),
[
("Łōdź", "?odz"),
(
@@ -107,7 +107,7 @@ def test_encode_string(content, expected):
@pytest.mark.parametrize(
"content, cls, expected",
("content", "cls", "expected"),
[
("The quick brown fox jumps over the lazy dog", SanitiseSMS, set()),
(
@@ -132,7 +132,7 @@ def test_sms_encoding_get_non_compatible_characters(content, cls, expected):
@pytest.mark.parametrize(
"content, expected",
("content", "expected"),
[
("이것은 테스트입니다", True), # Korean
("Αυτό είναι ένα τεστ", True), # Greek
@@ -285,7 +285,7 @@ def test_sms_supporting_additional_languages(content, expected):
@pytest.mark.parametrize(
"content, expected",
("content", "expected"),
[
("이것은 테스트입니다", set()), # Korean
("Αυτό είναι ένα τεστ", set()), # Greek
@@ -87,10 +87,10 @@ def test_cant_override_custom_property_from_dict():
@pytest.mark.parametrize(
"json_response",
(
[
{},
{"foo": "bar"}, # Should still raise an exception
),
],
)
def test_model_raises_for_unknown_attributes(json_response):
class Custom(SerialisedModel):
@@ -118,10 +118,10 @@ def test_model_raises_keyerror_if_item_missing_from_dict():
@pytest.mark.parametrize(
"json_response",
(
[
{},
{"foo": "bar"}, # Should be ignored
),
],
)
def test_model_doesnt_swallow_attribute_errors(json_response):
class Custom(SerialisedModel):
@@ -3350,7 +3350,7 @@ def test_broadcast_message_content_count(
),
],
)
@pytest.mark.parametrize("content", ("^{}\\[~]|€"))
@pytest.mark.parametrize("content", ["^{}\\[~]|€"])
def test_broadcast_message_double_counts_extended_gsm(
content,
template_class,
@@ -3375,7 +3375,7 @@ def test_broadcast_message_double_counts_extended_gsm(
],
)
@pytest.mark.parametrize(
"content", ("ÁÍÓÚẂÝ" "ËÏẄŸ" "ÂÊÎÔÛŴŶ" "ÀÈÌÒẀÙỲ" "áíóúẃý" "ëïẅÿ" "âêîôûŵŷ" "ẁỳ")
"content", ["ÁÍÓÚẂÝ" "ËÏẄŸ" "ÂÊÎÔÛŴŶ" "ÀÈÌÒẀÙỲ" "áíóúẃý" "ëïẅÿ" "âêîôûŵŷ" "ẁỳ"]
)
def test_broadcast_message_single_counts_diacritics_in_extended_gsm(
content,
@@ -3394,10 +3394,8 @@ def test_broadcast_message_single_counts_diacritics_in_extended_gsm(
@pytest.mark.parametrize(
"template_class",
[
(
BroadcastMessageTemplate,
BroadcastPreviewTemplate,
),
BroadcastMessageTemplate,
BroadcastPreviewTemplate,
],
)
@pytest.mark.parametrize("content", ("ÄÖÜ" "É" "äöü" "é" "àèìòù"))
@@ -1,4 +1,5 @@
import urllib
import pytest
from itsdangerous import BadSignature, SignatureExpired