From 92962ea51154a685349fea753a2957d611f03030 Mon Sep 17 00:00:00 2001 From: Petter Friberg Date: Sun, 15 Sep 2024 17:44:11 +0200 Subject: [PATCH] Add `TypeGuard` to `is_formatted_phone_number` (#297) I added an `assert_type` row since it seems that you are checking types with `pytest-mypy-plugins` but I figured using `assert_type` is probably preferable --- src/phantom/ext/phonenumbers.py | 3 ++- tests/ext/test_phonenumbers.py | 7 +++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/phantom/ext/phonenumbers.py b/src/phantom/ext/phonenumbers.py index de792fd..23444aa 100644 --- a/src/phantom/ext/phonenumbers.py +++ b/src/phantom/ext/phonenumbers.py @@ -13,6 +13,7 @@ from typing import cast import phonenumbers +from typing_extensions import TypeGuard from phantom import Phantom from phantom.bounds import parse_str @@ -67,7 +68,7 @@ def normalize_phone_number( is_phone_number = excepts(InvalidPhoneNumber)(_deconstruct_phone_number) -def is_formatted_phone_number(number: str) -> bool: +def is_formatted_phone_number(number: str) -> TypeGuard[FormattedPhoneNumber]: try: return number == normalize_phone_number(number) except InvalidPhoneNumber: diff --git a/tests/ext/test_phonenumbers.py b/tests/ext/test_phonenumbers.py index 9602559..e265866 100644 --- a/tests/ext/test_phonenumbers.py +++ b/tests/ext/test_phonenumbers.py @@ -1,4 +1,5 @@ import pytest +from typing_extensions import assert_type from phantom.errors import BoundError from phantom.ext.phonenumbers import FormattedPhoneNumber @@ -103,8 +104,10 @@ def test_returns_false_for_invalid_number(self): class TestIsFormattedPhoneNumber: - def test_returns_true_for_formatted_number(self): - assert is_formatted_phone_number("+46123456789") is True + def test_returns_true_for_formatted_number(self) -> None: + value = "+46123456789" + assert is_formatted_phone_number(value) + assert_type(value, FormattedPhoneNumber) def test_returns_false_for_unformatted_number(self): assert is_formatted_phone_number("+46 (123) 456 789") is False