diff --git a/.coveragerc b/.coveragerc index 48aed0e..e3fd5b5 100644 --- a/.coveragerc +++ b/.coveragerc @@ -5,6 +5,7 @@ include = Main/** Users/** Instructor/** + CodeReview/load_env.py omit = */migrations/* */__pycache__/* diff --git a/CodeReview/load_env.py b/CodeReview/load_env.py new file mode 100644 index 0000000..61b3bcb --- /dev/null +++ b/CodeReview/load_env.py @@ -0,0 +1,42 @@ +""" + This file s used to load environment variables from a powershell file +""" + +import os +from typing import Optional + + +def get_env(filename: str) -> Optional[dict]: + """ + This function is used to get environment variables from a powershell file as a dictionary + + :param filename: The file to read + :type filename: str + :returns: The environment variables in the file as a dictionary + :rtype: dict + """ + + env = {} + if os.path.exists(filename): + with open(filename, 'r') as file: + for raw_line in file.readlines(): + if raw_line[0] != "#": + line = raw_line[5:].split('=') + env[line[0]] = line[1].replace('"', "")[:-1] + return env + else: + return None + + +def load_to_env(filename: str) -> None: + """ + This function is used to load a powershell file into the environment + + :param filename: The name/path of the powershell file to load + :type filename: str + """ + + env = get_env(filename) + if env is not None: + for key in env.keys(): + os.environ[key] = env[key] diff --git a/CodeReview/wsgi.py b/CodeReview/wsgi.py index 0a54c94..1092b8b 100644 --- a/CodeReview/wsgi.py +++ b/CodeReview/wsgi.py @@ -6,6 +6,9 @@ import os from django.core.wsgi import get_wsgi_application +from CodeReview.load_env import load_to_env + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CodeReview.settings') +load_to_env('env.ps1') application = get_wsgi_application() diff --git a/tests/test_misc.py b/tests/test_misc.py index fe3dc8f..65209ee 100644 --- a/tests/test_misc.py +++ b/tests/test_misc.py @@ -1,12 +1,42 @@ +import os + from django.test import TestCase, Client from django.urls import reverse +from CodeReview.load_env import load_to_env, get_env from Users.models import User +class EnvLoadTest(TestCase): + + def setUp(self) -> None: + with open('env_test.ps1', 'w+') as file: + file.writelines([ + '#This is a comment, it shouldn\'t load\n', + '$Env:TEST_VAR=\"Hello, World!\"\n' + ]) + + def test_get(self) -> None: + results = get_env('env_test.ps1') + self.assertDictEqual(results, {'TEST_VAR': "Hello, World!"}) + + def test_load(self) -> None: + load_to_env('env_test.ps1') + self.assertEqual(os.getenv('TEST_VAR'), "Hello, World!") + + def test_no_file(self) -> None: + results = get_env("not_a_file.ps1") + self.assertIsNone(results) + + def tearDown(self) -> None: + if os.path.exists('env_test.ps1'): + os.remove('env_test.ps1') + + class UserSetupTest(TestCase): - def get_url(self, user): + @staticmethod + def get_url(user): return reverse('user-setup', kwargs={'pk': user.id}) def create_users(self):