import unittest
from io import StringIO

from magicgen import read_magics, write_magics


class TestReadMagics(unittest.TestCase):
    def test_simple(self):
        self.assertDictEqual(
            read_magics(StringIO("#define TEST 0xbc614e")), {"TEST": 12345678}
        )

    def test_duplicate(self):
        self.assertDictEqual(
            read_magics(
                StringIO(
                    "#define TEST 0xbc614e\n#define V1 1\n#define TEST_COPY TEST\n#define RAW 0x0"
                )
            ),
            {"V1": 1, "TEST": 12345678, "RAW": 0},
        )


class TestWriteMagics(unittest.TestCase):
    prefix = """// Code generated by magicgen. DO NOT EDIT.

package magic

type MagicMap struct {
\tByName  map[string]uint64
\tByValue map[uint64]string
}

func LoadMagic() MagicMap {
\tmagicMap := MagicMap{
\t\tByName:  make(map[string]uint64),
\t\tByValue: make(map[uint64]string),
\t}"""
    suffix = "\n\treturn magicMap\n}\n"

    def test_simple(self):
        f = StringIO()
        write_magics(f, {"TEST": 12345678})
        self.assertEqual(
            f.getvalue(),
            self.prefix
            + '\n\tmagicMap.ByName["TEST"] = 12345678\n\tmagicMap.ByValue[12345678] = "TEST"'
            + self.suffix,
        )

    def test_suffix(self):
        f = StringIO()
        write_magics(f, {"TEST_MAGIC": 12345678})
        self.assertEqual(
            f.getvalue(),
            self.prefix
            + '\n\tmagicMap.ByName["TEST"] = 12345678\n\tmagicMap.ByValue[12345678] = "TEST"'
            + self.suffix,
        )

    def test_ignored(self):
        f = StringIO()
        write_magics(f, {"V1": 1, "TEST": 12345678, "RAW": 0})
        self.assertEqual(
            f.getvalue(),
            self.prefix
            + '\n\tmagicMap.ByName["TEST"] = 12345678\n\tmagicMap.ByValue[12345678] = "TEST"'
            + self.suffix,
        )


if __name__ == "__main__":
    unittest.main(verbosity=2)
