"Test cases for util.gpg module."

import unittest
import json

from hm_pyhelper.util.pgp import get_payload_from_clearsigned_message


SAMPLE_CLEARSIGNED_MESSAGE = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

{
  "key1": "value1",
  "key2": [1, 2, 3, 4]
}

-----BEGIN PGP SIGNATURE-----

<KEY>MBjHZ49oZd2GZKBl
vo5u8szs
=i6qt
-----END PGP SIGNATURE-----
"""

SAMPLE_CLEARSIGNED_MESSAGE_NO_NEWLINE_AT_END = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

{
  "key1": "value1",
  "key2": [1, 2, 3, 4]
}
-----BEGIN PGP SIGNATURE-----

<KEY>LRok1MBjHZ49oZd2GZKBl
vo5u8szs
=i6qt
-----END PGP SIGNATURE-----
"""


class TestUtilPGP(unittest.TestCase):

    def test_empty_file(self):
        with self.assertRaises(RuntimeError) as exp:
            get_payload_from_clearsigned_message("")

        assert str(exp.exception) == \
            'Invalid message format, no --BEGIN PGP SIGNED MESSAGE-- header'

    def test_invalid_clearsigned_payload(self):
        with self.assertRaises(RuntimeError) as exp:
            get_payload_from_clearsigned_message("Just\nSome\nMessage\na\nb\nc")

        assert str(exp.exception) == \
            'Invalid message format, no --BEGIN PGP SIGNED MESSAGE-- header'

    def test_payload_extraction(self):
        payload = get_payload_from_clearsigned_message(SAMPLE_CLEARSIGNED_MESSAGE)
        d = json.loads(payload)
        assert d['key1'] == 'value1'
        assert d['key2'] == [1, 2, 3, 4]

        payload = get_payload_from_clearsigned_message(
            SAMPLE_CLEARSIGNED_MESSAGE_NO_NEWLINE_AT_END)
        d = json.loads(payload)
        assert d['key1'] == 'value1'
        assert d['key2'] == [1, 2, 3, 4]
