Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/unit testing #44

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Config/check_config_validity.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import configparser

config = configparser.ConfigParser()
config.read('Config/logger.ini')

def read_config():
return config.read('Config/logger.ini')



# check if the required sections are present
if 'loggers' not in config.sections() or 'handlers' not in config.sections():
Expand All @@ -21,3 +25,5 @@
if not isinstance(config.getint('loggers', 'keys.suspicious.level'), int):
raise ValueError('Invalid value for keys.suspicious.level in config.ini')

if __name__ == "__main__":
read_config()
2 changes: 1 addition & 1 deletion Config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def get_logging_config(file_location="Config/logger.ini"):
open(file_location, "r")
except FileNotFoundError:
logging.critical(f"File location invalid: {file_location}")
sys.exit(1)
raise FileNotFoundError

config = get_config('Config/logger.ini')
return config
Expand Down
Empty file.
Empty file added tests/Common/test_utils.py
Empty file.
22 changes: 22 additions & 0 deletions tests/Config/test_check_config_validity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import configparser
import unittest
import sys
import os
sys.path.insert(0, os.getcwd())
from Config import check_config_validity


class TestConfigValid(unittest.TestCase):
def setUp(self):
check_config_validity.read_config()
self.config = configparser.ConfigParser()

def test_key_value_format(self):
self.assertIsInstance(self.config.getint('handlers', 'console.level'), int)
self.assertIsInstance(self.config.getint('loggers', 'keys.suspicious.level'), int)

def test_keys_present_in_handlers(self):
assert self.config['loggers'] or 'suspicious' in self.config ['loggers']

def test_sections_present(self):
assert 'loggers' in self.config.sections() or 'handlers' in self.config.sections()
22 changes: 22 additions & 0 deletions Tests/Config/test_config.py → tests/Config/test_config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import os
import unittest

import sys

sys.path.insert(0, os.getcwd())

from requests.api import get
from Config.config import configure_logging, get_config, get_logging_config
from configparser import ConfigParser

class TestConfig(unittest.TestCase):
Expand Down Expand Up @@ -30,6 +37,21 @@ def test_config_is_valid(self):
self.assertIn('keys', parser['formatters'])
self.assertIn('level', parser['handler_console'])

def test_directory_structure(self):
""" Check that config module is where it's supposed to be """

self.assertTrue(os.path.exists(os.path.join("Config", "config.py")))

def test_get_config(self):
self.assertIn("property", get_logging_config.__builtins__.keys())

def test_get_logging_config(self):
with self.assertRaises(FileNotFoundError) as _:
get_logging_config("random_path.txt")
self.assertIsInstance(get_logging_config(), ConfigParser)

def test_configure_logging(self):
self.assertIsInstance(configure_logging(), ConfigParser)

if __name__ == "__main__":
unittest.main()
45 changes: 45 additions & 0 deletions tests/Config/test_formatter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import os
import sys
import unittest
import logging
sys.path.insert(0, os.getcwd())
from Config.formatter import Formatter
from Config.config import configure_logging


class TestFormatter(unittest.TestCase):
def setUp(self):
# Ensure file paths are all set up
if not os.path.split(os.path.basename(os.getcwd()))[1] == "HackAlert":
print("Pathname invalid, ensure you're in the base directory.")
sys.exit(1)
if not os.path.isdir(os.path.join("logs")) or not os.path.isdir(os.path.join("logs", "tests")):
os.makedirs(os.path.join('logs', 'tests'))
files = [os.path.join("logs/tests/test_critical.log"),
os.path.join("logs/tests/test_error.log"),
os.path.join("logs/tests/test_warning.log"),
os.path.join("logs/tests/test_debug.log"),
os.path.join("logs/tests/test_info.log")]
for file_ in files:
if not os.path.exists(file_):
with open(file_, "w") as file:
file.write(f"Created {file_} for tests.")
file.close()

configure_logging()
self.formatter = Formatter()
self.logger = logging.getLogger()

def test_records(self):
self.records = {
"critical": self.logger.makeRecord( "test_critical", logging.CRITICAL, "logs/tests/test_critical.log", 50, "[test] critical message", (), None,),
"error": self.logger.makeRecord( "test_error", logging.ERROR, "logs/tests/test_error.log", 40, "[test] error message", (), None,),
"warning": self.logger.makeRecord( "test_warning", logging.WARNING, "logs/tests/test_warning.log", 30, "[test] warning message", (), None,),
"debug": self.logger.makeRecord( "test_debug", logging.DEBUG, "logs/tests/test_debug.log", 20, "[test] debug message", (), None,),
"info": self.logger.makeRecord( "test_info", logging.INFO, "logs/tests/test_info.log", 10, "[test] info message", (), None,),
}

for record in self.records.keys():
if self.assertIsInstance(self.records[record], logging.LogRecord) is not False:
self.assertIn(record, self.records[record].msg)

Empty file.
Empty file.
Empty file.