def from_url(cls, url: Union[str, EmailURL]) -> BaseTransport: url = EmailURL(url) if url.transport not in cls.mapping: raise NotRegisteredTransportError( f'No transport found with scheme "{url.transport}".') klass = cls.mapping[url.transport] if isinstance(klass, str): klass = import_from_string(klass) klass = cast(Type[BaseTransport], klass) factory = getattr(klass, "from_url", None) if factory is not None: return factory(url) return klass()
def test_raises_if_no_semicolon(): with pytest.raises(ImportFromStringError) as ex: import_from_string("some.module") assert str(ex.value) == ( 'Import string must be in format: "<module>:<attribute>". ' f'Given: "some.module"')
def test_imports_attribute(): klass = import_from_string("tempfile:TemporaryFile") assert klass is tempfile.TemporaryFile
def test_raises_if_attribute_not_found(): with pytest.raises(ImportFromStringError) as ex: import_from_string("tempfile:MissingTemporaryFile") assert (str(ex.value) == 'Attribute "MissingTemporaryFile" not found in module "tempfile".')
def test_raises_if_module_not_found(): with pytest.raises(ImportFromStringError) as ex: import_from_string("some.module:SomeClass") assert str(ex.value) == 'Could not import module: "some.module"'