def test_base64(self): hello = "aGVsbG8gd29ybGQ=" self.assertEqual(Envelope.load(f"\n{hello}").message(), hello) self.assertEqual( Envelope.load( f"Content-Transfer-Encoding: base64\n\n{hello}").message(), "hello world")
def test_default(self): self.assertEqual(Envelope().subject(), "") Envelope.default.subject("bar") self.assertEqual(Envelope().subject("foo").subject(), "foo") self.assertEqual(Envelope().subject(), "bar") Envelope.default.subject("") # restore previous state
def test_different_order(self): e = Envelope() \ .attach(Path(self.text_attachment), "text/csv", "foo") \ .attach(mimetype="text/csv", name="foo", path=self.text_attachment) \ .attach(Path(self.text_attachment), "foo", "text/csv") model = repr(e.attachments()[0]) self.assertTrue(all(repr(a) == model for a in e.attachments()))
def __init__(self, target, exp_dir=None, sim_dir=None, policy_dir='PolicyFn', ni=1, nd=2): super(SlowDgame, self).__init__(target, exp_dir=exp_dir, sim_dir=sim_dir, ni=ni, nd=nd) # print('!!!!!!!!!!!!!! f*****g SlowDgame !!!!!!!!!!!!!!!') self.policies = dict() for role, p in self.players.items(): self.policies[role] = load_model('Policies/' + policy_dir + '_' + role + '.h5') # print(self.a) self.s_lb = -asin(self.a) self.gmm_lb = acos(self.a) self.analytic_traj = Envelope(self.vi, self.vd, self.r) self.policy_dict['nn'] = self.nn_strategy self.policy_dict['w'] = self.w_strategy self.policy_dict['h'] = self.h_strategy self.strategy = closeWrapper(self.policy_dict[self.dstrategy], self.policy_dict[self.istrategy])
def test_multiple_recipients(self): from M2Crypto import SMIME msg = "dumb message" msg_b = bytes(msg, "utf-8") def decrypt(key, cert, text): try: return Parser(key=key, cert=cert).smime_decrypt(text) except SMIME.PKCS7_Error: return False # encrypt for both keys output = (Envelope(msg).smime().reply_to( "*****@*****.**").subject("my message").encrypt([ Path(self.smime_cert), Path("tests/smime/[email protected]") ])) self.assertEqual( msg_b, decrypt('tests/smime/[email protected]', 'tests/smime/[email protected]', output)) self.assertEqual(msg_b, decrypt(self.smime_key, self.smime_cert, output)) # encrypt for single key only output = (Envelope(msg).smime().reply_to( "*****@*****.**").subject("my message").encrypt( [Path(self.smime_cert)])) self.assertFalse( decrypt('tests/smime/[email protected]', 'tests/smime/[email protected]', output)) self.assertEqual(msg_b, decrypt(self.smime_key, self.smime_cert, output))
def test_gpg_auto_sign(self): # mail from "*****@*****.**" is in ring self.check_lines( Envelope("dumb message").gpg("tests/gpg_ring/").from_( "*****@*****.**").sign("auto"), ( 'dumb message', '-----BEGIN PGP SIGNATURE-----', '-----END PGP SIGNATURE-----', ), 10) # mail from "*****@*****.**" should not be signed output = str( Envelope("dumb message").gpg("tests/gpg_ring/").from_( "*****@*****.**"). sign("auto")).splitlines() self.assertNotIn('-----BEGIN PGP SIGNATURE-----', output) # force-signing without specifying a key nor sending address should produce a message signed with a first-found key output = str( Envelope("dumb message").gpg("tests/gpg_ring/").sign( True)).splitlines() self.assertIn('-----BEGIN PGP SIGNATURE-----', output) # force-signing without specifying a key and with sending from an e-mail which is not in the keyring must fail self.check_lines(Envelope("dumb message").gpg("tests/gpg_ring/").from_( "*****@*****.**"). signature(True), raises=RuntimeError)
def test_cache_recreation(self): s1 = "Test" s2 = "Another" e = Envelope("dumb message").subject(s1) self.check_lines(e, f"Subject: {s1}") e.subject(s2) self.check_lines(e, f"Subject: {s2}")
def test_contents_fetching(self): t = "Small sample text attachment.\n" with open("tests/eml/generic.txt") as f: e1 = Envelope(f) e2 = e1.copy() # stays intact even if copied to another instance self.assertEqual(e1.message(), t) self.assertEqual(e2.message(), t) self.assertEqual(e2.copy().message(), t)
def _quoted_message(self, e: Envelope): self.assertEqual(self.long_text, e.message()) self.assertIn( self.long_text, e.preview()) # when using preview, we receive original text output = str( e.send(False)) # but when sending, quoted text is got instead self.assertNotIn(self.long_text, output) self.assertIn(self.quoted, output)
def test_internationalized(self): self.assertEqual("Žluťoučký kůň", Envelope.load(self.internationalized).subject()) # when using preview, we do not want to end up with "Subject: =?utf-8?b?xb1sdcWlb3XEjWvDvSBrxa/FiA==?=" # which could appear even when .subject() shows decoded version self.assertIn( "Subject: Žluťoučký kůň", Envelope.load(self.internationalized).preview().splitlines())
def test_only_2_alternatives_allowed(self): e1 = Envelope().message("He<b>llo</b>").message("Hello", alternative="plain") # we can replace alternative e1.copy().message("Test").message("Test", alternative="plain") # but in the moment we set all three and call send or preview, we should fail self.assertRaises( ValueError, e1.copy().message("Test", alternative="html").preview)
def test_invalid_email_addresses(self): """ If we discard silently every invalid e-mail address received, the user would not know their recipients are not valid. """ e = (Envelope().to( '[email protected], [invalid!email], [email protected]')) self.assertEqual(3, len(e.to())) self.assertFalse(e.check(check_mx=False, check_smtp=False)) e = (Envelope().to('[email protected], [email protected]')) self.assertTrue(e.check(check_mx=False, check_smtp=False))
def to_pcm_audio(self): oscillator = Oscillator(self._frequency, self._phase) envelope = Envelope() for point in self._amplitude_envelope_points: envelope.add_point(point) samples = oscillator.get_output(self._sample_times) samples *= envelope.get_output(self._sample_times) if self._base_pcm_audio: samples += self._base_pcm_audio.samples return PcmAudio(self._reference_pcm_audio.sampling_rate, samples)
def test_nl2br(self): nobr = "Second" br = "Second<br>" self.check_lines( Envelope().message(self.html), nobr ) # there already is a <br> tag so nl2br "auto" should not convert it self.check_lines(Envelope().message(self.html).mime(nl2br=True), br) self.check_lines(Envelope().message(self.html_without_line_break), br) self.check_lines(Envelope().message(self.html_without_line_break).mime( "plain", True), nobr) # nl2br disabled in "plain" self.check_lines( Envelope().message(self.html_without_line_break).mime(nl2br=False), nobr)
def test_alternative_and_related(self): e = Envelope.load(path=self.inline_image) self.assertEqual("Hi <img src='cid:image.gif'/>", e.message()) self.assertEqual("Inline image message", e.subject()) self.assertEqual("Plain alternative", e.message(alternative=PLAIN)) self.assertEqual(self.image_file.read_bytes(), bytes(e.attachments()[0]))
def test_email_addresses(self): e = ( Envelope().cc("*****@*****.**").to( "*****@*****.**") # add as string .to(["*****@*****.**", "*****@*****.**"]) # add as list .to("*****@*****.**").to( "Duplicated <*****@*****.**>" ) # duplicated person should be ignored without any warning # we can delimit both by comma (standard) and semicolon (invalid but usual) .to([ "[email protected]; Sixth <*****@*****.**>, Seventh <*****@*****.**>" ]) # even invalid delimiting works .to([ "[email protected], , ; Ninth <*****@*****.**>, Seventh <*****@*****.**>" ]).to("Named person 1 again <*****@*****.**>" ) # appeared twice –> will be discarded .bcc("*****@*****.**")) self.assertEqual(9, len(e.to())) self.assertEqual(1, len(e.cc())) self.assertEqual(10, len(e.recipients())) self.assertEqual(str, type(",".join( e.to()))) # we can join elements as strings self.assertIn("Sixth <*****@*****.**>", e.to()) # we can compare look up specific recipient
def test_smime_sign(self): # Message will look that way: # MIME-Version: 1.0 # Content-Type: multipart/signed; protocol="application/x-pkcs7-signature"; micalg="sha1"; boundary="----DD291FCCF0F9F19D858D1A9200251EA5" # # This is an S/MIME signed message # # ------DD291FCCF0F9F19D858D1A9200251EA5 # # dumb message # ------DD291FCCF0F9F19D858D1A9200251EA5 # Content-Type: application/x-pkcs7-signature; name="smime.p7s" # Content-Transfer-Encoding: base64 # Content-Disposition: attachment; filename="smime.p7s" # # MIIEggYJKoZIhvcNAQcCoIIEczCCBG8CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3 # DQEHAaCCAmwwggJoMIIB0aADAgECAhROmwkIH63oarp3NpQqFoKTy1Q3tTANBgkq # ... other lines changes every time self.check_lines( Envelope("dumb message").smime().subject("my subject").reply_to( "*****@*****.**").signature( Path("tests/smime/key.pem"), cert=Path(self.smime_cert)).send(False), ( "Subject: my subject", "Reply-To: [email protected]", "dumb message", 'Content-Disposition: attachment; filename="smime.p7s"', "MIIEggYJKoZIhvcNAQcCoIIEczCCBG8CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3", ), 10)
def test_smime_key_cert_together(self): self.check_lines( Envelope("dumb message").smime().signature( self.key_cert_together).sign(), ('Content-Disposition: attachment; filename="smime.p7s"', "MIIEggYJKoZIhvcNAQcCoIIEczCCBG8CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3" ))
def test_alternative(self): boundary = "=====envelope-test====" # alternative="auto" can become both "html" and "plain" e1 = Envelope().message("He<b>llo</b>").message("Hello", alternative="plain", boundary=boundary) e2 = Envelope().message("He<b>llo</b>", alternative="html").message("Hello", boundary=boundary) self.assertEqual(e1, e2) # HTML variant is always the last even if defined before plain variant self.check_lines( e1, ('Content-Type: text/plain; charset="utf-8"', "Hello", 'Content-Type: text/html; charset="utf-8"', "He<b>llo</b>"))
def play(self): """ function that finds the envelope with the biggest amount of money by replacing the current max envelope since the start of the list n times :return: the envelope with biggest amount of money after n times of replacing the max """ # the biggest amount found - for start 0 max_sum_of_money = 0 # the envelope with the biggest amount of money that was found - just for start random envelope for sure will be # replaced max_envelope = Envelope() # the number of times that the max had changed - for start 0 times_max_was_changed = 0 for envelope in self.env_arr: if times_max_was_changed < self.N: # checking if the envelope was not opened if not envelope.used: envelope.used = True # checking if there is a new maximum since last one if envelope.money > max_sum_of_money: max_sum_of_money = envelope.money max_envelope = envelope # one more maximum changed - getting closer to N times maximum needs to change to stop times_max_was_changed += 1 # if the n of times to change max reached stop the loop - if that never happens and loop ends last maximum # will be returned else: break return max_envelope
def send_email_api_key(email: EmailStr, api_key: str, days_valid: int): """ function to send the api key to a user. Shamelessly stolen from the official docs """ subject = "API-key reset" hostname = baseurl smtp_from = config['MAIL_FROM'] body = """ Dear %s, you (or someone) requested a new api-key for the service at %s. Here is your new API key: %s This key is valid for %s days. You can find instructions on how to use it at %s. In case you did not request an API key, please ignore this email. Kind regards, the automatic API buttler """ % (email, hostname, api_key, days_valid, hostname) Envelope()\ .message(body)\ .subject(subject)\ .to(email)\ .sender(smtp_from)\ .smtp("localhost")\ .send()
def getEnvelope(self, i): ''' get specific envelope :param i: the index of the envelope :return: the envelope ''' env = Envelope(self.envelopes[i]) return env
def test_load_file(self): e = Envelope.load(self.eml.read_text()) self.assertEqual(e.subject(), "Hello world subject") # multiple headers returned as list and in the same order self.assertEqual(len(e.header("Received")), 2) self.assertEqual( e.header("Received")[1][:26], "from receiver2.example.com")
def test_1000_split(self): self.check_lines( Envelope().message("short text").subject("my subject").send(False), ('Content-Transfer-Encoding: 7bit', "Subject: my subject", "short text"), 10) # this should be no more 7bit but base64 (or quoted-printable which is however not guaranteed) e = Envelope().message("Longer than thousand chars. " * 1000).subject("my subject").send(False) self.check_lines(e, ( "Content-Transfer-Encoding: base64", "Subject: my subject", ), 100, not_in=('Content-Transfer-Encoding: 7bit', )) self.assertFalse( any(line for line in str(e).splitlines() if len(line) > 999))
def test_addresses(self): e = Envelope.load(path=self.eml) self.assertEqual(1, len(e.to())) contact = e.to()[0] self.assertEqual("Person <*****@*****.**>", contact) self.assertEqual("*****@*****.**", contact) self.assertEqual("*****@*****.**", contact.address) self.assertEqual("Person", contact.name)
def test_smime_key_cert_together_passphrase(self): self.check_lines( Envelope("dumb message").smime().signature( Path("tests/smime/key-cert-together-passphrase.pem"), passphrase=GPG_PASSPHRASE).sign(), ('Content-Disposition: attachment; filename="smime.p7s"', "MIIEggYJKoZIhvcNAQcCoIIEczCCBG8CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3" ), 10)
def test_gpg_encrypt(self): # Message will look like this: # **************************************************************************************************** # Have not been sent from [email protected] to [email protected] # Encrypted subject: None # Encrypted message: b'message' # # Subject: Encrypted message # MIME-Version: 1.0 # Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; # boundary="===============1001129828818615570==" # From: [email protected] # To: [email protected],[email protected] # Date: Wed, 11 Dec 2019 17:56:03 +0100 # Message-ID: <157608336314.13303.1097227818284823500@promyka> # # --===============1001129828818615570== # Content-Type: application/pgp-encrypted # # Version: 1 # --===============1001129828818615570== # Content-Type: application/octet-stream; name="encrypted.asc" # Content-Description: OpenPGP encrypted message # Content-Disposition: inline; filename="encrypted.asc" # # -----BEGIN PGP MESSAGE----- # ... # -----END PGP MESSAGE----- # # --===============1001129828818615570==-- e = str( Envelope("dumb message").to( "*****@*****.**").gpg( "tests/gpg_ring/").from_( "*****@*****.**").subject( "dumb subject").encryption()) self.check_lines(e, ( "Encrypted subject: dumb subject", "Encrypted message: dumb message", "Subject: Encrypted message", 'Content-Type: multipart/encrypted; protocol="application/pgp-encrypted";', "From: [email protected]", "To: [email protected]", ), 10, not_in='Subject: dumb subject') lines = e.splitlines() message = "\n".join(lines[lines.index("-----BEGIN PGP MESSAGE-----"):]) self.check_lines( self.bash("gpg", "--decrypt", piped=message, envelope=False), ('Content-Type: multipart/mixed; protected-headers="v1";', 'Subject: dumb subject', 'Content-Type: text/plain; charset="utf-8"', 'dumb message'))
def test_gpg_sign_passphrase(self): self.check_lines( Envelope("dumb message").to( "*****@*****.**").gpg( "tests/gpg_ring/").from_( "*****@*****.**").signature( "3C8124A8245618D286CF871E94CE2905DB00CDB7", GPG_PASSPHRASE), # passphrase needed ("-----BEGIN PGP SIGNATURE-----", ), 10)
def test_encrypted_gpg_subject(self): body = "just a body text" subject = "This is an encrypted subject" encrypted_eml = ( Envelope(body).gpg("tests/gpg_ring/").to( "*****@*****.**").from_( "*****@*****.**").subject( subject).encryption() # .attach(path=self.text_attachment) # .attach(self.image_file, inline=True) .as_message().as_string()) # subject has been encrypted self.assertIn("Subject: Encrypted message", encrypted_eml) self.assertNotIn(subject, encrypted_eml) # subject has been decrypted e = Envelope.load(encrypted_eml) self.assertEqual(body, e.message()) self.assertEqual(subject, e.subject())
def test_gpg_auto_encrypt(self): # mail `from` "*****@*****.**" is in ring self.check_lines(Envelope("dumb message").gpg("tests/gpg_ring/").from_( "*****@*****.**").to( "*****@*****.**").encrypt("auto"), ( '-----BEGIN PGP MESSAGE-----', '-----END PGP MESSAGE-----', ), (10, 15), not_in="dumb message") # mail `to` "*****@*****.**" unknown, must be both signed and encrypted self.check_lines(Envelope("dumb message").gpg("tests/gpg_ring/").from_( "*****@*****.**").to( "*****@*****.**").signature( "auto").encrypt("auto"), ( '-----BEGIN PGP MESSAGE-----', '-----END PGP MESSAGE-----', ), 20, not_in="dumb message") # mail `from` "*****@*****.**" unknown, must not be encrypted self.check_lines(Envelope("dumb message").gpg("tests/gpg_ring/").from_( "*****@*****.**").to( "*****@*****.**").encrypt("auto"), ('dumb message', ), (0, 2), not_in='-----BEGIN PGP MESSAGE-----') # mail `to` "*****@*****.**" unknown, must not be encrypted self.check_lines(Envelope("dumb message").gpg("tests/gpg_ring/").from_( "*****@*****.**").to( "*****@*****.**").encrypt("auto"), ('dumb message', ), (0, 2), not_in='-----BEGIN PGP MESSAGE-----') # force-encrypting without having key must return empty response self.check_lines(Envelope("dumb message").gpg("tests/gpg_ring/").from_( "*****@*****.**").to( "*****@*****.**").encryption(True), longer=(0, 1), result=False)
def send_msg_to_mq(self): envelope = str(Envelope(self.message, self.routing_key)) properties = pika.BasicProperties(app_id=self.app_id, content_type='text/plain', delivery_mode=2) self.channel.basic_publish(exchange=self.exchange, routing_key=self.routing_key, body=envelope, properties=properties)
def get_sound_factory(reference_pcm_audio, base_pcm_audio=None): class Sound(_Sound): _reference_pcm_audio = reference_pcm_audio _reference_spectrogram = Spectrogram(reference_pcm_audio.samples) _base_pcm_audio = base_pcm_audio _maximal_amplitude = numpy.max( [magnitudes.max() for magnitudes in _reference_spectrogram]) _sample_times = numpy.linspace( 0, reference_pcm_audio.duration, len(reference_pcm_audio.samples)) base_sound_spectrogram = ( Spectrogram(base_pcm_audio.samples) if base_pcm_audio else None) # Compute and overwrite maximal frequency minimal_significant_amplitude = 20.0 significant_frequency_indices = [ index for index, amplitudes in enumerate( zip(*Sound._reference_spectrogram)) if numpy.max(amplitudes) >= minimal_significant_amplitude] maximal_frequency_index = numpy.max(significant_frequency_indices) Sound._maximal_frequency = Sound._reference_spectrogram.get_frequencies( Sound._reference_pcm_audio.sampling_rate)[maximal_frequency_index] # Compute and overwrite minimal frequency # if base_pcm_audio: # significant_base_frequency_indices = [ # index for index, amplitudes in enumerate( # zip(*base_sound_spectrogram)) # if numpy.max(amplitudes) >= minimal_significant_amplitude] # minimal_frequency_index = numpy.min([ # index for index in significant_frequency_indices # if index not in significant_base_frequency_indices]) # Sound._minimal_frequency = base_sound_spectrogram.get_frequencies( # base_pcm_audio.sampling_rate)[minimal_frequency_index] # print Sound._minimal_frequency # Compute amplitude limit envelope envelope = Envelope() frame_length = ( Sound._reference_pcm_audio.duration / len(Sound._reference_spectrogram)) for frame_index, magnitudes in enumerate(Sound._reference_spectrogram): if base_sound_spectrogram: magnitudes = magnitudes - base_sound_spectrogram[frame_index] envelope.add_point( Envelope.Point( time=frame_length * (frame_index + 0.5), value=numpy.max(magnitudes) ) ) Sound._amplitude_limit_envelope = envelope # Compute weights by frequencies def weight_by_frequency(frequency): """ To calculate weights this function uses a technique called "A-weighting" """ return (12200 ** 2) * (frequency ** 4) / ( (frequency ** 2 + 20.6 ** 2) * numpy.sqrt(frequency ** 2 + 107.7 ** 2) * numpy.sqrt(frequency ** 2 + 737.9 ** 2) * (frequency ** 2 + 12200 ** 2) ) Sound._frequencies_weights = numpy.array( map(weight_by_frequency, Sound._reference_spectrogram.get_frequencies( Sound._reference_pcm_audio.sampling_rate))) return Sound