From aeb9921aca91f9a048ed70e9d2fde6f3b7b99d0e Mon Sep 17 00:00:00 2001 From: pattersonlois Date: Thu, 5 Nov 2026 17:15:03 +0000 Subject: [PATCH 1/3] Fix email/phone normalization and typos in enhanced conversions examples --- .../upload_enhanced_conversions_for_leads.py | 35 ++++++++++-------- .../upload_enhanced_conversions_for_web.py | 37 ++++++++++--------- 2 files changed, 39 insertions(+), 33 deletions(-) diff --git a/examples/remarketing/upload_enhanced_conversions_for_leads.py b/examples/remarketing/upload_enhanced_conversions_for_leads.py index f8c6f3269..d2a27c237 100644 --- a/examples/remarketing/upload_enhanced_conversions_for_leads.py +++ b/examples/remarketing/upload_enhanced_conversions_for_leads.py @@ -99,11 +99,11 @@ def main( # a UserIdentifier with ONLY a hashed_phone_number: # # incorrectly_populated_user_identifier = client.get_type("UserIdentifier") - # incorrectly_populated_user_identifier.hashed_email = "..."" - # incorrectly_populated_user_identifier.hashed_phone_number = "..."" + # incorrectly_populated_user_identifier.hashed_email = "..." + # incorrectly_populated_user_identifier.hashed_phone_number = "..." raw_record: Dict[str, Union[str, float]] = { - # Email address that includes a period (.) before the Gmail domain. + # Email address that includes a period (.) before the email domain. "email": "alex.2@example.com", # Phone number to be converted to E.164 format, with a leading '+' as # required. @@ -143,7 +143,7 @@ def main( phone_identifier.hashed_phone_number = normalize_and_hash( raw_record["phone"] ) - # Adds the phone identifier to the conversion adjustment. + # Adds the phone identifier to the conversion. click_conversion.user_identifiers.append(phone_identifier) # [END add_user_identifiers] @@ -242,25 +242,28 @@ def normalize_and_hash_email_address(email_address: str) -> str: """Returns the result of normalizing and hashing an email address. For this use case, Google Ads requires removal of any '.' characters - preceding "gmail.com" or "googlemail.com" + and '+' suffixes preceding "gmail.com" or "googlemail.com". Args: email_address: An email address to normalize. Returns: - A normalized (lowercase, removed whitespace) and SHA-265 hashed string. + A normalized (lowercase, removed whitespace) and SHA-256 hashed string. """ normalized_email: str = email_address.strip().lower() email_parts: list[str] = normalized_email.split("@") # Check that there are at least two segments if len(email_parts) > 1: - # Removes any '.' and '+' characters from the portion of the email address - # before the domain - chars_to_remove = ".+" - translation_table = str.maketrans("", "", chars_to_remove) - email_parts[0] = email_parts[0].translate(translation_table) - normalized_email = "@".join(email_parts) + # Checks whether the domain of the email address is either "gmail.com" + # or "googlemail.com". If this regex does not match then this statement + # will evaluate to None. + if re.match(r"^(gmail|googlemail)\.com$", email_parts[1]): + # Removes any '.' characters and any '+' suffix from the portion of + # the email address before the domain. + email_parts[0] = email_parts[0].replace(".", "") + email_parts[0] = re.sub(r"\+.*$", "", email_parts[0]) + normalized_email = "@".join(email_parts) return normalize_and_hash(normalized_email) @@ -277,7 +280,7 @@ def normalize_and_hash(s: str) -> str: Returns: A normalized (lowercase, removed whitespace) and SHA-256 hashed string. """ - return hashlib.sha256(s.strip().lower().encode()).hexdigest() + return hashlib.sha256(re.sub(r"\s+", "", s).lower().encode()).hexdigest() # [END normalize_and_hash] @@ -289,8 +292,8 @@ def normalize_and_hash(s: str) -> str: ) parser: argparse.ArgumentParser = argparse.ArgumentParser( - description="Imports offline call conversion values for calls related " - "to your ads." + description="Uploads an enhanced conversion for leads by uploading a " + "ClickConversion." ) # The following argument(s) should be provided to run the example. parser.add_argument( @@ -398,7 +401,7 @@ def normalize_and_hash(s: str) -> str: ) except GoogleAdsException as ex: print( - f"Request with ID '{ex.request_id}'' failed with status " + f"Request with ID '{ex.request_id}' failed with status " f"'{ex.error.code().name}' and includes the following errors:" ) for error in ex.failure.errors: diff --git a/examples/remarketing/upload_enhanced_conversions_for_web.py b/examples/remarketing/upload_enhanced_conversions_for_web.py index aa2a3f578..7039022da 100644 --- a/examples/remarketing/upload_enhanced_conversions_for_web.py +++ b/examples/remarketing/upload_enhanced_conversions_for_web.py @@ -61,11 +61,11 @@ def main( # a UserIdentifier with ONLY a hashed_phone_number: # # incorrectly_populated_user_identifier = client.get_type("UserIdentifier") - # incorrectly_populated_user_identifier.hashed_email = "..."" - # incorrectly_populated_user_identifier.hashed_phone_number = "..."" + # incorrectly_populated_user_identifier.hashed_email = "..." + # incorrectly_populated_user_identifier.hashed_phone_number = "..." raw_record = { - # Email address that includes a period (.) before the Gmail domain. + # Email address that includes a period (.) before the email domain. "email": "alex.2@example.com", # Address that includes all four required elements: first name, last # name, country code, and postal code. @@ -129,7 +129,7 @@ def main( ] if len(missing_keys) > 0: print( - "Skipping addition of mailing address information because the" + "Skipping addition of mailing address information because the " f"following required keys are missing: {missing_keys}" ) else: @@ -210,7 +210,7 @@ def main( result = response.results[0] print( f"Uploaded conversion adjustment of {result.conversion_action} for " - f"order ID {result,order_id}." + f"order ID {result.order_id}." ) @@ -219,25 +219,28 @@ def normalize_and_hash_email_address(email_address): """Returns the result of normalizing and hashing an email address. For this use case, Google Ads requires removal of any '.' characters - preceding "gmail.com" or "googlemail.com" + and '+' suffixes preceding "gmail.com" or "googlemail.com". Args: email_address: An email address to normalize. Returns: - A normalized (lowercase, removed whitespace) and SHA-265 hashed string. + A normalized (lowercase, removed whitespace) and SHA-256 hashed string. """ normalized_email = email_address.strip().lower() email_parts = normalized_email.split("@") # Check that there are at least two segments if len(email_parts) > 1: - # Removes any '.' and '+' characters from the portion of the email address - # before the domain - chars_to_remove = ".+" - translation_table = str.maketrans("", "", chars_to_remove) - email_parts[0] = email_parts[0].translate(translation_table) - normalized_email = "@".join(email_parts) + # Checks whether the domain of the email address is either "gmail.com" + # or "googlemail.com". If this regex does not match then this statement + # will evaluate to None. + if re.match(r"^(gmail|googlemail)\.com$", email_parts[1]): + # Removes any '.' characters and any '+' suffix from the portion of + # the email address before the domain. + email_parts[0] = email_parts[0].replace(".", "") + email_parts[0] = re.sub(r"\+.*$", "", email_parts[0]) + normalized_email = "@".join(email_parts) return normalize_and_hash(normalized_email) @@ -254,14 +257,14 @@ def normalize_and_hash(s): Returns: A normalized (lowercase, removed whitespace) and SHA-256 hashed string. """ - return hashlib.sha256(s.strip().lower().encode()).hexdigest() + return hashlib.sha256(re.sub(r"\s+", "", s).lower().encode()).hexdigest() # [END normalize_and_hash] if __name__ == "__main__": parser = argparse.ArgumentParser( - description="Imports offline call conversion values for calls related " - "to your ads." + description="Enhances a web conversion by uploading a " + "ConversionAdjustment." ) # The following argument(s) should be provided to run the example. parser.add_argument( @@ -318,7 +321,7 @@ def normalize_and_hash(s): ) except GoogleAdsException as ex: print( - f"Request with ID '{ex.request_id}'' failed with status " + f"Request with ID '{ex.request_id}' failed with status " f"'{ex.error.code().name}' and includes the following errors:" ) for error in ex.failure.errors: From 2b2daf94748f207f233a4db29345879b7ed0197e Mon Sep 17 00:00:00 2001 From: pattersonlois Date: Mon, 16 Nov 2026 02:37:54 +0000 Subject: [PATCH 2/3] Address PR review feedback on normalization and add unit tests --- .../upload_enhanced_conversions_for_leads.py | 42 +-- .../upload_enhanced_conversions_for_web.py | 42 +-- tests/examples/remarketing/__init__.py | 0 ...oad_enhanced_conversions_for_leads_test.py | 260 ++++++++++++++++ ...pload_enhanced_conversions_for_web_test.py | 283 ++++++++++++++++++ 5 files changed, 587 insertions(+), 40 deletions(-) create mode 100644 tests/examples/remarketing/__init__.py create mode 100644 tests/examples/remarketing/upload_enhanced_conversions_for_leads_test.py create mode 100644 tests/examples/remarketing/upload_enhanced_conversions_for_web_test.py diff --git a/examples/remarketing/upload_enhanced_conversions_for_leads.py b/examples/remarketing/upload_enhanced_conversions_for_leads.py index d2a27c237..8266ff4c4 100644 --- a/examples/remarketing/upload_enhanced_conversions_for_leads.py +++ b/examples/remarketing/upload_enhanced_conversions_for_leads.py @@ -22,7 +22,6 @@ import argparse import hashlib -import re import sys from typing import Dict, Optional, Union @@ -103,8 +102,9 @@ def main( # incorrectly_populated_user_identifier.hashed_phone_number = "..." raw_record: Dict[str, Union[str, float]] = { - # Email address that includes a period (.) before the email domain. - "email": "alex.2@example.com", + # Email address that includes a period (.) and '+' suffix before the + # Gmail domain, both of which will be removed during normalization. + "email": "alex.2+myalias@gmail.com", # Phone number to be converted to E.164 format, with a leading '+' as # required. "phone": "+1 800 5550102", @@ -141,7 +141,7 @@ def main( if raw_record.get("phone") is not None: phone_identifier: UserIdentifier = client.get_type("UserIdentifier") phone_identifier.hashed_phone_number = normalize_and_hash( - raw_record["phone"] + raw_record["phone"], remove_all_whitespace=True ) # Adds the phone identifier to the conversion. click_conversion.user_identifiers.append(phone_identifier) @@ -250,25 +250,21 @@ def normalize_and_hash_email_address(email_address: str) -> str: Returns: A normalized (lowercase, removed whitespace) and SHA-256 hashed string. """ - normalized_email: str = email_address.strip().lower() + normalized_email: str = "".join(email_address.split()).lower() email_parts: list[str] = normalized_email.split("@") - # Check that there are at least two segments - if len(email_parts) > 1: - # Checks whether the domain of the email address is either "gmail.com" - # or "googlemail.com". If this regex does not match then this statement - # will evaluate to None. - if re.match(r"^(gmail|googlemail)\.com$", email_parts[1]): - # Removes any '.' characters and any '+' suffix from the portion of - # the email address before the domain. - email_parts[0] = email_parts[0].replace(".", "") - email_parts[0] = re.sub(r"\+.*$", "", email_parts[0]) - normalized_email = "@".join(email_parts) + # Checks that the email has exactly two segments (local and domain). + if len(email_parts) == 2: + local_part, domain = email_parts + if domain in ("gmail.com", "googlemail.com"): + # Removes any '+' suffix and '.' characters from the local part. + local_part = local_part.partition("+")[0].replace(".", "") + normalized_email = f"{local_part}@{domain}" - return normalize_and_hash(normalized_email) + return normalize_and_hash(normalized_email, remove_all_whitespace=True) -def normalize_and_hash(s: str) -> str: +def normalize_and_hash(s: str, remove_all_whitespace: bool = False) -> str: """Normalizes and hashes a string with SHA-256. Private customer data must be hashed during upload, as described at: @@ -276,11 +272,17 @@ def normalize_and_hash(s: str) -> str: Args: s: The string to perform this operation on. + remove_all_whitespace: If True, removes leading, trailing, and + intermediate whitespace before hashing (use for email and phone). + If False, removes only leading and trailing whitespace (use for + first_name, last_name, and street_address). Returns: - A normalized (lowercase, removed whitespace) and SHA-256 hashed string. + A normalized (lowercase, trimmed whitespace) and SHA-256 hashed + string. """ - return hashlib.sha256(re.sub(r"\s+", "", s).lower().encode()).hexdigest() + normalized: str = "".join(s.split()) if remove_all_whitespace else s.strip() + return hashlib.sha256(normalized.lower().encode()).hexdigest() # [END normalize_and_hash] diff --git a/examples/remarketing/upload_enhanced_conversions_for_web.py b/examples/remarketing/upload_enhanced_conversions_for_web.py index 7039022da..5188d5301 100644 --- a/examples/remarketing/upload_enhanced_conversions_for_web.py +++ b/examples/remarketing/upload_enhanced_conversions_for_web.py @@ -19,7 +19,6 @@ import argparse import hashlib -import re import sys from google.ads.googleads.client import GoogleAdsClient @@ -65,8 +64,9 @@ def main( # incorrectly_populated_user_identifier.hashed_phone_number = "..." raw_record = { - # Email address that includes a period (.) before the email domain. - "email": "alex.2@example.com", + # Email address that includes a period (.) and '+' suffix before the + # Gmail domain, both of which will be removed during normalization. + "email": "alex.2+myalias@gmail.com", # Address that includes all four required elements: first name, last # name, country code, and postal code. "first_name": "Alex", @@ -111,7 +111,7 @@ def main( if raw_record.get("phone") is not None: phone_identifier = client.get_type("UserIdentifier") phone_identifier.hashed_phone_number = normalize_and_hash( - raw_record["phone"] + raw_record["phone"], remove_all_whitespace=True ) # Adds the phone identifier to the conversion adjustment. conversion_adjustment.user_identifiers.append(phone_identifier) @@ -227,25 +227,21 @@ def normalize_and_hash_email_address(email_address): Returns: A normalized (lowercase, removed whitespace) and SHA-256 hashed string. """ - normalized_email = email_address.strip().lower() + normalized_email = "".join(email_address.split()).lower() email_parts = normalized_email.split("@") - # Check that there are at least two segments - if len(email_parts) > 1: - # Checks whether the domain of the email address is either "gmail.com" - # or "googlemail.com". If this regex does not match then this statement - # will evaluate to None. - if re.match(r"^(gmail|googlemail)\.com$", email_parts[1]): - # Removes any '.' characters and any '+' suffix from the portion of - # the email address before the domain. - email_parts[0] = email_parts[0].replace(".", "") - email_parts[0] = re.sub(r"\+.*$", "", email_parts[0]) - normalized_email = "@".join(email_parts) + # Checks that the email has exactly two segments (local and domain). + if len(email_parts) == 2: + local_part, domain = email_parts + if domain in ("gmail.com", "googlemail.com"): + # Removes any '+' suffix and '.' characters from the local part. + local_part = local_part.partition("+")[0].replace(".", "") + normalized_email = f"{local_part}@{domain}" - return normalize_and_hash(normalized_email) + return normalize_and_hash(normalized_email, remove_all_whitespace=True) -def normalize_and_hash(s): +def normalize_and_hash(s, remove_all_whitespace=False): """Normalizes and hashes a string with SHA-256. Private customer data must be hashed during upload, as described at: @@ -253,11 +249,17 @@ def normalize_and_hash(s): Args: s: The string to perform this operation on. + remove_all_whitespace: If True, removes leading, trailing, and + intermediate whitespace before hashing (use for email and phone). + If False, removes only leading and trailing whitespace (use for + first_name, last_name, and street_address). Returns: - A normalized (lowercase, removed whitespace) and SHA-256 hashed string. + A normalized (lowercase, trimmed whitespace) and SHA-256 hashed + string. """ - return hashlib.sha256(re.sub(r"\s+", "", s).lower().encode()).hexdigest() + normalized = "".join(s.split()) if remove_all_whitespace else s.strip() + return hashlib.sha256(normalized.lower().encode()).hexdigest() # [END normalize_and_hash] diff --git a/tests/examples/remarketing/__init__.py b/tests/examples/remarketing/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/examples/remarketing/upload_enhanced_conversions_for_leads_test.py b/tests/examples/remarketing/upload_enhanced_conversions_for_leads_test.py new file mode 100644 index 000000000..174ccdc7d --- /dev/null +++ b/tests/examples/remarketing/upload_enhanced_conversions_for_leads_test.py @@ -0,0 +1,260 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for upload_enhanced_conversions_for_leads example.""" + +import io +import unittest +from unittest import mock + +from examples.remarketing import upload_enhanced_conversions_for_leads +from google.ads.googleads.client import GoogleAdsClient + +# Precomputed UTF-8 SHA-256 hex digests for normalized test vectors. +SHA256_MARY_JANE = ( + "e3a62fcabda79e1b70db99ef77d0e0af36d27e3c48bce714fac085d5058d945a" +) +SHA256_MARYJANE_NO_SPACE = ( + "f08f448a5e7a9dc3619bb7c129f6a7d5fc6af002cea17ad71dfdc1c68f4d4e0e" +) +SHA256_DE_LA_CRUZ = ( + "341a715580af4bbc3c3bff363245177e84fbc38c4a77d3047edeb6bee38495aa" +) +SHA256_PHONE_E164 = ( + "c5383c2eeada28210d27f011bc127d4f9562cf38ff0c9bba33dd45ae79b9fe7c" +) +SHA256_ALEX2_GMAIL = ( + "3663dbed96fe29729d2e1ba646b09559bb3dec9c73124bb70a3bea135ee5546b" +) +SHA256_JANEDOE_GOOGLEMAIL = ( + "338abf9ef1c8793cadc7bcf51ed595338eb727ed9e06ce3d91d566d60b975937" +) +SHA256_NON_GMAIL = ( + "f109a2a632fbcea5fc82049f50beed3d8621bf9034399f437fb622222acccdac" +) +SHA256_GMAIL_COM_AU = ( + "c29fe01237251dc9819c62998ab22afa6ddb5561a92cc2f7532689c906857c46" +) +SHA256_SUB_GMAIL = ( + "ac235b1865e9771f525d8cf77753255f5b9b64a5e4d02cb1722534251da9e505" +) +SHA256_MULTI_AT = ( + "6f877fa31df550e08b64aba5566f94167dd7c50df37ed6e33e389b9ee7f62c80" +) +SHA256_NO_AT = ( + "a2598686ba7440dd1a92f18ab059cae1ff50982200a9350636b2bc8927398fbc" +) + + +class TestUploadEnhancedConversionsForLeads(unittest.TestCase): + """Tests for normalization helpers and main flow in leads example.""" + + def _create_client_with_mock_services( + self, conversion_action_service, conversion_upload_service + ): + client = GoogleAdsClient( + credentials=mock.MagicMock(), + developer_token="test_token", + version="v24", + use_proto_plus=True, + ) + + def get_service_side_effect(name): + if name == "ConversionActionService": + return conversion_action_service + if name == "ConversionUploadService": + return conversion_upload_service + raise AssertionError(f"Unexpected service requested: {name}") + + client.get_service = mock.MagicMock(side_effect=get_service_side_effect) + return client + + def test_normalize_and_hash_preserves_internal_spaces_by_default(self): + result_first = upload_enhanced_conversions_for_leads.normalize_and_hash( + " Mary Jane " + ) + result_last = upload_enhanced_conversions_for_leads.normalize_and_hash( + " De La Cruz\t" + ) + + self.assertEqual(result_first, SHA256_MARY_JANE) + self.assertNotEqual(result_first, SHA256_MARYJANE_NO_SPACE) + self.assertEqual(result_last, SHA256_DE_LA_CRUZ) + + def test_normalize_and_hash_removes_all_whitespace_when_requested(self): + result = upload_enhanced_conversions_for_leads.normalize_and_hash( + " +1 800\t5550102\n", remove_all_whitespace=True + ) + + self.assertEqual(result, SHA256_PHONE_E164) + + def test_normalize_and_hash_email_strips_dots_and_plus_for_gmail_domains( + self, + ): + gmail_hash = upload_enhanced_conversions_for_leads.normalize_and_hash_email_address( + " Alex.2+MyAlias@Gmail.com " + ) + googlemail_hash = upload_enhanced_conversions_for_leads.normalize_and_hash_email_address( + "Jane.Doe+Shopping+Extra@GOOGLEMAIL.COM" + ) + + self.assertEqual(gmail_hash, SHA256_ALEX2_GMAIL) + self.assertEqual(googlemail_hash, SHA256_JANEDOE_GOOGLEMAIL) + + def test_normalize_and_hash_email_strips_spaces_around_at_before_matching( + self, + ): + space_before_at = upload_enhanced_conversions_for_leads.normalize_and_hash_email_address( + "alex.2+tag @gmail.com" + ) + space_after_at = upload_enhanced_conversions_for_leads.normalize_and_hash_email_address( + "alex.2+tag@ gmail.com" + ) + + self.assertEqual(space_before_at, SHA256_ALEX2_GMAIL) + self.assertEqual(space_after_at, SHA256_ALEX2_GMAIL) + + def test_normalize_and_hash_email_preserves_dots_and_plus_for_other_domains( + self, + ): + example_hash = upload_enhanced_conversions_for_leads.normalize_and_hash_email_address( + "user.name+NYC@Example.com" + ) + cc_tld_hash = upload_enhanced_conversions_for_leads.normalize_and_hash_email_address( + "alex.2+tag@gmail.com.au" + ) + subdomain_hash = upload_enhanced_conversions_for_leads.normalize_and_hash_email_address( + "alex.2+tag@sub.gmail.com" + ) + + self.assertEqual(example_hash, SHA256_NON_GMAIL) + self.assertEqual(cc_tld_hash, SHA256_GMAIL_COM_AU) + self.assertEqual(subdomain_hash, SHA256_SUB_GMAIL) + + def test_normalize_and_hash_email_skips_gmail_rules_on_invalid_at_count( + self, + ): + multi_at_hash = upload_enhanced_conversions_for_leads.normalize_and_hash_email_address( + "alex.2+tag@gmail.com@example.com" + ) + no_at_hash = upload_enhanced_conversions_for_leads.normalize_and_hash_email_address( + "alex.2+tag" + ) + + self.assertEqual(multi_at_hash, SHA256_MULTI_AT) + self.assertEqual(no_at_hash, SHA256_NO_AT) + + def test_main_uploads_click_conversion_with_expected_identifiers(self): + mock_conversion_action_service = mock.MagicMock() + mock_conversion_action_service.conversion_action_path.return_value = ( + "customers/1234567890/conversionActions/456" + ) + mock_upload_service = mock.MagicMock() + client = self._create_client_with_mock_services( + mock_conversion_action_service, mock_upload_service + ) + + result_entry = client.get_type("ClickConversionResult") + result_entry.conversion_action = ( + "customers/1234567890/conversionActions/456" + ) + result_entry.conversion_date_time = "2026-06-01 12:32:45-08:00" + mock_upload_service.upload_click_conversions.return_value = ( + mock.MagicMock(partial_failure_error=None, results=[result_entry]) + ) + + stdout = io.StringIO() + with mock.patch("sys.stdout", stdout): + upload_enhanced_conversions_for_leads.main( + client=client, + customer_id="1234567890", + conversion_action_id="456", + conversion_date_time="2026-06-01 12:32:45-08:00", + conversion_value=42.5, + order_id="lead-order-1", + gclid="test-gclid", + ad_user_data_consent="GRANTED", + session_attributes_dict={"gad_source": "1"}, + ) + + mock_upload_service.upload_click_conversions.assert_called_once() + call_kwargs = ( + mock_upload_service.upload_click_conversions.call_args.kwargs + ) + self.assertEqual(call_kwargs["customer_id"], "1234567890") + self.assertTrue(call_kwargs["partial_failure"]) + self.assertEqual(len(call_kwargs["conversions"]), 1) + + conversion = call_kwargs["conversions"][0] + self.assertEqual( + conversion.conversion_action, + "customers/1234567890/conversionActions/456", + ) + self.assertEqual( + conversion.conversion_date_time, "2026-06-01 12:32:45-08:00" + ) + self.assertEqual(conversion.conversion_value, 42.5) + self.assertEqual(conversion.currency_code, "USD") + self.assertEqual(conversion.order_id, "lead-order-1") + self.assertEqual(conversion.gclid, "test-gclid") + self.assertEqual( + conversion.consent.ad_user_data, + client.enums.ConsentStatusEnum.GRANTED, + ) + self.assertEqual( + len(conversion.session_attributes_key_value_pairs.key_value_pairs), + 1, + ) + pair = conversion.session_attributes_key_value_pairs.key_value_pairs[0] + self.assertEqual(pair.session_attribute_key, "gad_source") + self.assertEqual(pair.session_attribute_value, "1") + + self.assertEqual(len(conversion.user_identifiers), 2) + email_id, phone_id = conversion.user_identifiers + self.assertEqual( + email_id.user_identifier_source, + client.enums.UserIdentifierSourceEnum.FIRST_PARTY, + ) + self.assertEqual(email_id.hashed_email, SHA256_ALEX2_GMAIL) + self.assertEqual(phone_id.hashed_phone_number, SHA256_PHONE_E164) + + self.assertEqual( + stdout.getvalue().strip(), + "Uploaded conversion that occurred at 2026-06-01 12:32:45-08:00 " + "to customers/1234567890/conversionActions/456.", + ) + + def test_main_raises_value_error_when_both_session_attribute_inputs_set( + self, + ): + client = self._create_client_with_mock_services( + mock.MagicMock(), mock.MagicMock() + ) + + with self.assertRaises(ValueError): + upload_enhanced_conversions_for_leads.main( + client=client, + customer_id="1234567890", + conversion_action_id="456", + conversion_date_time="2026-06-01 12:32:45-08:00", + conversion_value=10.0, + order_id=None, + gclid=None, + ad_user_data_consent=None, + session_attributes_encoded="encoded-token", + session_attributes_dict={"gad_source": "1"}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/examples/remarketing/upload_enhanced_conversions_for_web_test.py b/tests/examples/remarketing/upload_enhanced_conversions_for_web_test.py new file mode 100644 index 000000000..a5a9530d6 --- /dev/null +++ b/tests/examples/remarketing/upload_enhanced_conversions_for_web_test.py @@ -0,0 +1,283 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for upload_enhanced_conversions_for_web example.""" + +import io +import unittest +from unittest import mock + +from examples.remarketing import upload_enhanced_conversions_for_web +from google.ads.googleads.client import GoogleAdsClient + +# Precomputed UTF-8 SHA-256 hex digests for normalized test vectors. +SHA256_MARY_JANE = ( + "e3a62fcabda79e1b70db99ef77d0e0af36d27e3c48bce714fac085d5058d945a" +) +SHA256_MARYJANE_NO_SPACE = ( + "f08f448a5e7a9dc3619bb7c129f6a7d5fc6af002cea17ad71dfdc1c68f4d4e0e" +) +SHA256_DE_LA_CRUZ = ( + "341a715580af4bbc3c3bff363245177e84fbc38c4a77d3047edeb6bee38495aa" +) +SHA256_PHONE_E164 = ( + "c5383c2eeada28210d27f011bc127d4f9562cf38ff0c9bba33dd45ae79b9fe7c" +) +SHA256_ALEX2_GMAIL = ( + "3663dbed96fe29729d2e1ba646b09559bb3dec9c73124bb70a3bea135ee5546b" +) +SHA256_JANEDOE_GOOGLEMAIL = ( + "338abf9ef1c8793cadc7bcf51ed595338eb727ed9e06ce3d91d566d60b975937" +) +SHA256_NON_GMAIL = ( + "f109a2a632fbcea5fc82049f50beed3d8621bf9034399f437fb622222acccdac" +) +SHA256_GMAIL_COM_AU = ( + "c29fe01237251dc9819c62998ab22afa6ddb5561a92cc2f7532689c906857c46" +) +SHA256_SUB_GMAIL = ( + "ac235b1865e9771f525d8cf77753255f5b9b64a5e4d02cb1722534251da9e505" +) +SHA256_MULTI_AT = ( + "6f877fa31df550e08b64aba5566f94167dd7c50df37ed6e33e389b9ee7f62c80" +) +SHA256_NO_AT = ( + "a2598686ba7440dd1a92f18ab059cae1ff50982200a9350636b2bc8927398fbc" +) +SHA256_ALEX = "4135aa9dc1b842a653dea846903ddb95bfb8c5a10c504a7fa16e10bc31d1fdf0" +SHA256_QUINN = ( + "c512ca0c5c1e71be19f3356821e56732b5fb3ac894b0dbc5846d0b6920106fb3" +) + + +class TestUploadEnhancedConversionsForWeb(unittest.TestCase): + """Tests for normalization helpers and main flow in web example.""" + + def _create_client_with_mock_services( + self, conversion_action_service, adjustment_upload_service + ): + client = GoogleAdsClient( + credentials=mock.MagicMock(), + developer_token="test_token", + version="v24", + use_proto_plus=True, + ) + + def get_service_side_effect(name): + if name == "ConversionActionService": + return conversion_action_service + if name == "ConversionAdjustmentUploadService": + return adjustment_upload_service + raise AssertionError(f"Unexpected service requested: {name}") + + client.get_service = mock.MagicMock(side_effect=get_service_side_effect) + return client + + def test_normalize_and_hash_preserves_internal_spaces_for_multiword_names( + self, + ): + result_first = upload_enhanced_conversions_for_web.normalize_and_hash( + " Mary Jane " + ) + result_last = upload_enhanced_conversions_for_web.normalize_and_hash( + " De La Cruz\t" + ) + + self.assertEqual(result_first, SHA256_MARY_JANE) + self.assertNotEqual(result_first, SHA256_MARYJANE_NO_SPACE) + self.assertEqual(result_last, SHA256_DE_LA_CRUZ) + + def test_normalize_and_hash_removes_all_whitespace_when_requested(self): + result = upload_enhanced_conversions_for_web.normalize_and_hash( + " +1 800\t5550102\n", remove_all_whitespace=True + ) + + self.assertEqual(result, SHA256_PHONE_E164) + + def test_normalize_and_hash_email_strips_dots_and_plus_for_gmail_domains( + self, + ): + gmail_hash = upload_enhanced_conversions_for_web.normalize_and_hash_email_address( + " Alex.2+MyAlias@Gmail.com " + ) + googlemail_hash = upload_enhanced_conversions_for_web.normalize_and_hash_email_address( + "Jane.Doe+Shopping+Extra@GOOGLEMAIL.COM" + ) + + self.assertEqual(gmail_hash, SHA256_ALEX2_GMAIL) + self.assertEqual(googlemail_hash, SHA256_JANEDOE_GOOGLEMAIL) + + def test_normalize_and_hash_email_strips_spaces_around_at_before_matching( + self, + ): + space_before_at = upload_enhanced_conversions_for_web.normalize_and_hash_email_address( + "alex.2+tag @gmail.com" + ) + space_after_at = upload_enhanced_conversions_for_web.normalize_and_hash_email_address( + "alex.2+tag@ gmail.com" + ) + + self.assertEqual(space_before_at, SHA256_ALEX2_GMAIL) + self.assertEqual(space_after_at, SHA256_ALEX2_GMAIL) + + def test_normalize_and_hash_email_preserves_dots_and_plus_for_other_domains( + self, + ): + example_hash = upload_enhanced_conversions_for_web.normalize_and_hash_email_address( + "user.name+NYC@Example.com" + ) + cc_tld_hash = upload_enhanced_conversions_for_web.normalize_and_hash_email_address( + "alex.2+tag@gmail.com.au" + ) + subdomain_hash = upload_enhanced_conversions_for_web.normalize_and_hash_email_address( + "alex.2+tag@sub.gmail.com" + ) + + self.assertEqual(example_hash, SHA256_NON_GMAIL) + self.assertEqual(cc_tld_hash, SHA256_GMAIL_COM_AU) + self.assertEqual(subdomain_hash, SHA256_SUB_GMAIL) + + def test_normalize_and_hash_email_skips_gmail_rules_on_invalid_at_count( + self, + ): + multi_at_hash = upload_enhanced_conversions_for_web.normalize_and_hash_email_address( + "alex.2+tag@gmail.com@example.com" + ) + no_at_hash = upload_enhanced_conversions_for_web.normalize_and_hash_email_address( + "alex.2+tag" + ) + + self.assertEqual(multi_at_hash, SHA256_MULTI_AT) + self.assertEqual(no_at_hash, SHA256_NO_AT) + + @mock.patch( + "examples.remarketing.upload_enhanced_conversions_for_web.normalize_and_hash", + wraps=upload_enhanced_conversions_for_web.normalize_and_hash, + ) + def test_main_uploads_enhancement_and_preserves_name_whitespace_mode( + self, spy_normalize_and_hash + ): + mock_conversion_action_service = mock.MagicMock() + mock_conversion_action_service.conversion_action_path.return_value = ( + "customers/1234567890/conversionActions/456" + ) + mock_adjustment_service = mock.MagicMock() + client = self._create_client_with_mock_services( + mock_conversion_action_service, mock_adjustment_service + ) + + result_entry = client.get_type("ConversionAdjustmentResult") + result_entry.conversion_action = ( + "customers/1234567890/conversionActions/456" + ) + result_entry.order_id = "order-789" + mock_adjustment_service.upload_conversion_adjustments.return_value = ( + mock.MagicMock(partial_failure_error=None, results=[result_entry]) + ) + + stdout = io.StringIO() + with mock.patch("sys.stdout", stdout): + upload_enhanced_conversions_for_web.main( + client=client, + customer_id="1234567890", + conversion_action_id="456", + order_id="order-789", + conversion_date_time="2026-06-01 12:32:45-08:00", + user_agent="Mozilla/5.0", + ) + + mock_adjustment_service.upload_conversion_adjustments.assert_called_once() + call_kwargs = ( + mock_adjustment_service.upload_conversion_adjustments.call_args.kwargs + ) + self.assertEqual(call_kwargs["customer_id"], "1234567890") + self.assertTrue(call_kwargs["partial_failure"]) + self.assertEqual(len(call_kwargs["conversion_adjustments"]), 1) + + adjustment = call_kwargs["conversion_adjustments"][0] + self.assertEqual( + adjustment.adjustment_type, + client.enums.ConversionAdjustmentTypeEnum.ENHANCEMENT, + ) + self.assertEqual( + adjustment.conversion_action, + "customers/1234567890/conversionActions/456", + ) + self.assertEqual(adjustment.order_id, "order-789") + self.assertEqual( + adjustment.gclid_date_time_pair.conversion_date_time, + "2026-06-01 12:32:45-08:00", + ) + self.assertEqual(adjustment.user_agent, "Mozilla/5.0") + + self.assertEqual(len(adjustment.user_identifiers), 3) + email_id, phone_id, address_id = adjustment.user_identifiers + self.assertEqual( + email_id.user_identifier_source, + client.enums.UserIdentifierSourceEnum.FIRST_PARTY, + ) + self.assertEqual(email_id.hashed_email, SHA256_ALEX2_GMAIL) + self.assertEqual(phone_id.hashed_phone_number, SHA256_PHONE_E164) + self.assertEqual(address_id.address_info.hashed_first_name, SHA256_ALEX) + self.assertEqual(address_id.address_info.hashed_last_name, SHA256_QUINN) + self.assertEqual(address_id.address_info.country_code, "US") + self.assertEqual(address_id.address_info.postal_code, "94045") + + spy_normalize_and_hash.assert_any_call( + "+1 800 5550102", remove_all_whitespace=True + ) + spy_normalize_and_hash.assert_any_call("Alex") + spy_normalize_and_hash.assert_any_call("Quinn") + + self.assertEqual( + stdout.getvalue().strip(), + "Uploaded conversion adjustment of " + "customers/1234567890/conversionActions/456 for order ID order-789.", + ) + + def test_main_prints_partial_failure_error(self): + mock_conversion_action_service = mock.MagicMock() + mock_conversion_action_service.conversion_action_path.return_value = ( + "customers/1234567890/conversionActions/456" + ) + mock_adjustment_service = mock.MagicMock() + client = self._create_client_with_mock_services( + mock_conversion_action_service, mock_adjustment_service + ) + + response = client.get_type("UploadConversionAdjustmentsResponse") + response.partial_failure_error.code = 3 + response.partial_failure_error.message = "Invalid order ID." + mock_adjustment_service.upload_conversion_adjustments.return_value = ( + response + ) + + stdout = io.StringIO() + with mock.patch("sys.stdout", stdout): + upload_enhanced_conversions_for_web.main( + client=client, + customer_id="1234567890", + conversion_action_id="456", + order_id="bad-order", + conversion_date_time=None, + user_agent=None, + ) + + self.assertEqual( + stdout.getvalue().strip(), + "Partial error encountered: Invalid order ID.", + ) + + +if __name__ == "__main__": + unittest.main() From 192005a910a95179a126f98c5e87a19131d58ebc Mon Sep 17 00:00:00 2001 From: pattersonlois Date: Mon, 16 Nov 2026 16:12:30 +0000 Subject: [PATCH 3/3] Address review feedback in enhanced conversions unit tests --- .../remarketing/upload_enhanced_conversions_for_leads_test.py | 2 -- .../remarketing/upload_enhanced_conversions_for_web_test.py | 2 -- 2 files changed, 4 deletions(-) diff --git a/tests/examples/remarketing/upload_enhanced_conversions_for_leads_test.py b/tests/examples/remarketing/upload_enhanced_conversions_for_leads_test.py index 174ccdc7d..8a9101f5b 100644 --- a/tests/examples/remarketing/upload_enhanced_conversions_for_leads_test.py +++ b/tests/examples/remarketing/upload_enhanced_conversions_for_leads_test.py @@ -64,8 +64,6 @@ def _create_client_with_mock_services( ): client = GoogleAdsClient( credentials=mock.MagicMock(), - developer_token="test_token", - version="v24", use_proto_plus=True, ) diff --git a/tests/examples/remarketing/upload_enhanced_conversions_for_web_test.py b/tests/examples/remarketing/upload_enhanced_conversions_for_web_test.py index a5a9530d6..eec589b48 100644 --- a/tests/examples/remarketing/upload_enhanced_conversions_for_web_test.py +++ b/tests/examples/remarketing/upload_enhanced_conversions_for_web_test.py @@ -68,8 +68,6 @@ def _create_client_with_mock_services( ): client = GoogleAdsClient( credentials=mock.MagicMock(), - developer_token="test_token", - version="v24", use_proto_plus=True, )