diff --git a/stdnum/util.py b/stdnum/util.py index 11b58dd7..6c9571d1 100644 --- a/stdnum/util.py +++ b/stdnum/util.py @@ -237,7 +237,7 @@ def get_cc_module(cc, name): mod = __import__('stdnum.%s' % cc, globals(), locals(), [str(name)]) return getattr(mod, name, None) except ImportError: - return + return None # this is a cache of SOAP clients diff --git a/stdnum/vatin.py b/stdnum/vatin.py index a8553d2c..5a5bdb58 100644 --- a/stdnum/vatin.py +++ b/stdnum/vatin.py @@ -44,7 +44,7 @@ >>> validate('XX') Traceback (most recent call last): ... -InvalidComponent: ... +ImportError: ... """ import re @@ -53,6 +53,10 @@ from stdnum.util import clean, get_cc_module +# regular expression for matching country codes. +_country_code_re = re.compile(r'^[a-z]{2}$') + + # Cache of country code modules _country_modules = dict() @@ -61,12 +65,12 @@ def _get_cc_module(cc): """Get the VAT number module based on the country code.""" # Greece uses a "wrong" country code, special case for Northern Ireland cc = cc.lower().replace('el', 'gr').replace('xi', 'gb') - if not re.match(r'^[a-z]{2}$', cc): - raise InvalidFormat() + if not _country_code_re.match(cc): + raise ImportError() if cc not in _country_modules: _country_modules[cc] = get_cc_module(cc, 'vat') if not _country_modules[cc]: - raise InvalidComponent() # unknown/unsupported country code + raise ImportError() return _country_modules[cc] @@ -94,5 +98,7 @@ def is_valid(number): """Check if the number is a valid VAT number.""" try: return bool(validate(number)) + except ImportError: + return False except ValidationError: return False diff --git a/tests/test_vatin.doctest b/tests/test_vatin.doctest index 4d785c31..f0d9e0ba 100644 --- a/tests/test_vatin.doctest +++ b/tests/test_vatin.doctest @@ -61,11 +61,11 @@ Try validating not specifying a country: >>> vatin.validate('') Traceback (most recent call last): ... -InvalidFormat: ... +ImportError: ... >>> vatin.validate('00') Traceback (most recent call last): ... -InvalidFormat: ... +ImportError: ... Try to validate for countries with no VAT validation: @@ -73,8 +73,26 @@ Try to validate for countries with no VAT validation: >>> vatin.validate('XX') Traceback (most recent call last): ... -InvalidComponent: ... +ImportError: ... >>> vatin.validate('US') Traceback (most recent call last): ... -InvalidComponent: ... +ImportError: ... + + +Check is_valid for several scenarios: + +>>> vatin.is_valid('FR 40 303 265 045') +True +>>> vatin.is_valid('FR 40 303') +False +>>> vatin.is_valid('FR') +False +>>> vatin.is_valid('') +False +>>> vatin.is_valid('00') +False +>>> vatin.is_valid('XX') +False +>>> vatin.is_valid('US') +False