def test_notifier_from_config(self): with mock.patch.dict(os.environ, DSS_NOTIFY_DELAYS="", DSS_NOTIFY_WORKERS="", DSS_NOTIFY_ATTEMPTS=""): self.assertFalse(Config.notification_is_async()) self.assertEqual(Config.notification_attempts(), 0) self.assertEqual(Config.notification_delays(), []) with mock.patch.dict(os.environ, DSS_NOTIFY_DELAYS="0"): self.assertTrue(Config.notification_is_async()) self.assertEqual(Config.notification_attempts(), 1) self.assertEqual(Config.notification_delays(), [0]) with mock.patch.dict(os.environ, DSS_NOTIFY_ATTEMPTS="0"): self.assertEqual(Config.notification_attempts(), 0) self.assertFalse(Config.notification_is_async()) with mock.patch.dict(os.environ, DSS_NOTIFY_DELAYS="3 2 1 .5", DSS_NOTIFY_WORKERS="7"): notifier = Notifier.from_config() self.assertEqual([3.0, 2.0, 1.0, .5], notifier._delays) self.assertEqual(7, notifier._num_workers) self.assertTrue(Config.notification_is_async()) self.assertEqual(Config.notification_attempts(), 4)
def create(cls, notification_id: str, subscription_id: str, url: str, method: str, encoding: str, body: JSON, attempts: Optional[int] = None, hmac_key: Optional[bytes] = None, hmac_key_id: Optional[str] = None, correlation_id: Optional[str] = None) -> 'Notification': allowed_schemes = {'https'} if DeploymentStage.IS_PROD() else { 'https', 'http' } scheme = urlparse(url).scheme require( scheme in allowed_schemes, f"The scheme '{scheme}' of URL '{url}' is prohibited. Allowed schemes are {allowed_schemes}." ) if DeploymentStage.IS_PROD(): hostname = urlparse(url).hostname for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( hostname, port=None): require( ipaddress.ip_address(sockaddr[0]).is_global, f"The hostname in URL '{url}' resolves to a private IP") if attempts is None: attempts = Config.notification_attempts() return cls( notification_id=notification_id, subscription_id=subscription_id, url=url, method=method, encoding=encoding, body=cls._bin2sqs(json.dumps(body).encode()), attempts=attempts, hmac_key=None if hmac_key is None else cls._bin2sqs(hmac_key), hmac_key_id=hmac_key_id, queued_at= None, # this field will be set when the message comes out of the queue correlation_id=correlation_id)