import os
import pathlib
import tempfile
import unittest

import no_store_http as web


def handler(directory, cast_dir):
    h = web.NoStoreHandler.__new__(web.NoStoreHandler)
    h.directory = directory
    web.NoStoreHandler.cast_dir = cast_dir
    return h


class CastDirTests(unittest.TestCase):
    def test_generated_descriptor_wins_over_the_app_tree(self):
        with tempfile.TemporaryDirectory() as app, tempfile.TemporaryDirectory() as cast:
            sha = "a" * 40
            pathlib.Path(cast, sha + ".json").write_text("{}")
            h = handler(app, cast)
            self.assertEqual(os.path.join(cast, sha + ".json"),
                             h.translate_path(f"/cast/{sha}.json?x=1"))
            # not generated -> the app tree (static demo descriptors)
            self.assertTrue(h.translate_path("/cast/demo-id.json").startswith(app))
            self.assertTrue(h.translate_path(f"/cast/{'b' * 40}.json").startswith(app))
            # only well-formed names leave the app tree
            self.assertTrue(h.translate_path("/cast/../etc/passwd").startswith(app))

    def test_without_cast_dir_nothing_changes(self):
        with tempfile.TemporaryDirectory() as app:
            h = handler(app, None)
            self.assertTrue(h.translate_path(f"/cast/{'a' * 40}.json").startswith(app))


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