import pathlib import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure from rest_client.env_file import parse_env, read_env KEYS = ("SITE", "USER", "TOKEN") class ReadEnv(unittest.TestCase): def setUp(self) -> None: self.path = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / ".env" def write(self, text: str, mode: int = 0o600) -> None: self.path.write_text(text) self.path.chmod(mode) def test_reads_the_keys_asked_for_and_no_other(self): self.write("SITE=https://a.example\nUSER=me\nTOKEN=s3cret\nOTHER=x\n") self.assertEqual(read_env(self.path, KEYS, "a token"), {"SITE": "https://a.example", "USER": "me", "TOKEN": "s3cret"}) def test_a_missing_file_fails_naming_every_key_it_needs(self): self.assertEqual(read_env(self.path, KEYS, "a token"), Failure(f"{self.path} does not exist; it needs SITE, USER and TOKEN")) def test_a_file_lacking_keys_or_holding_empty_ones_fails_naming_them(self): self.write("SITE=https://a.example\nUSER=\n") self.assertEqual(read_env(self.path, KEYS, "a token"), Failure(f"{self.path} lacks USER and TOKEN")) def test_a_file_that_group_or_others_may_read_fails_naming_the_secret(self): for mode in (0o640, 0o604, 0o610): with self.subTest(mode=oct(mode)): self.write("SITE=a\nUSER=b\nTOKEN=c\n", mode) self.assertEqual(read_env(self.path, KEYS, "a token"), Failure(f"{self.path} holds a token, so only its owner may read it; run chmod 600 {self.path}")) def test_a_file_that_cannot_be_read_as_text_fails(self): self.path.write_bytes(b"TOKEN=\xff\n") self.path.chmod(0o600) failed = read_env(self.path, KEYS, "a token") self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith(f"cannot read {self.path}: "), failed) def test_parses_quotes_comments_and_spaces(self): self.assertEqual(parse_env("# note\nA = 1 \nB=\"two words\"\nC='3'\nnot a pair\n#D=4\nE=a=b\nF=\"\"\nG='\n # H=5\nI=XaX\n"), {"A": "1", "B": "two words", "C": "3", "E": "a=b", "F": "", "G": "'", "I": "XaX"}) if __name__ == "__main__": unittest.main()