Skip to content

Commit

Permalink
Bunch of tests and fixing the default behaviour.
Browse files Browse the repository at this point in the history
  • Loading branch information
gcarrarom committed Jun 3, 2019
1 parent b3ec338 commit be9d3f5
Show file tree
Hide file tree
Showing 6 changed files with 151 additions and 9 deletions.
26 changes: 18 additions & 8 deletions kcleaner.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ def ask_yn(yn_question, default='n'):
return response

def check_and_cleanup_backups(filename):
if filename == None:
logging.error("Filename cannot be 'None'!")
exit(40)
logging.debug(f"Checking if there's not more than {backup_limit} backup files in this directory")
dirpath = os.path.dirname(os.path.abspath(filename))
logging.debug(f"Getting all the files in {dirpath}")
Expand All @@ -31,12 +34,14 @@ def check_and_cleanup_backups(filename):
logging.debug(f"Checking for all kcleaner backup files")
files = [item for item in files if "kcleaner.bak" in item]
logging.debug(f"These are the backup files in this folder:\n{files}")
if len(files) > 10:
logging.info(f"Cleaning up excess of backup files - we have {len(files)} already... - Removing the {len(files) - 10} oldest files")
if len(files) > backup_limit:
logging.info(f"Cleaning up excess of backup files - we have {len(files)} already... - Removing the {len(files) - backup_limit} oldest files")
files.sort()
for file in files[0:(len(files)-10)]:
for file in files[0:(len(files)-backup_limit)]:
logging.debug(f"Removing File {file}")
os.remove(f"{dirpath}/{file}")
else:
logging.debug(f'We are bellow the backup limit, nothing to do here.')

def update_file(filename, yamldoc):
file_exists(filename)
Expand All @@ -50,11 +55,15 @@ def update_file(filename, yamldoc):
elif yamldoc == "":
logging.error("Yaml Value cannot be empty!")
exit(31)
try:
yaml.safe_load(yamldoc)
except:
logging.exception("Yaml value is not valid!")
exit(32)
logging.debug(f'Checking the type of the yamldoc: {type(yamldoc)}')
if type(yamldoc) is not dict:
try:
yaml.safe_load(yamldoc)
except:
logging.exception("Yaml value is not valid!")
exit(32)
else:
logging.debug(f"This is a dict yaml doc object. Should be fine to convert as yaml. Content:\n{yamldoc}")
logging.debug(f"Opening write stream for file {filename}")
with open(filename, 'w') as stream:
try:
Expand Down Expand Up @@ -184,6 +193,7 @@ def cli(resource, name, kubeconfig, undo, debug):
"""
if debug:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('Running with Debug flag')
else:
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name='kcleaner',
version='0.2.0',
version='0.2.1',
author='Gui Martins',
url='https://fancywhale.ca/',
author_email='[email protected]',
Expand Down
70 changes: 70 additions & 0 deletions tests/kcleaner_check_and_cleanup_backups_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from kcleaner import check_and_cleanup_backups, backup_limit
from testfixtures import log_capture
import click
from click.testing import CliRunner
import pytest
import yaml

runner = CliRunner()
sample_yaml = """
something:
alist:
- item1: test
something: test
- item2: test
something: test
"""

@log_capture()
def test_none_parameters(capture):

with pytest.raises(SystemExit) as pytest_wrapped_e:
check_and_cleanup_backups(None)

assert pytest_wrapped_e.value.code == 40
capture.check_present(
('root', 'ERROR', "Filename cannot be 'None'!")
)

@log_capture()
def test_bellow_backup_limit(capture):
with runner.isolated_filesystem():

for i in range(backup_limit-1):
with open(f'./something_{i}_kcleaner.bak', 'w') as f:
f.write('lololol')

check_and_cleanup_backups("./something")

capture.check_present(
('root', 'DEBUG', 'We are bellow the backup limit, nothing to do here.')
)

@log_capture()
def test_1_over_backup_limit(capture):
with runner.isolated_filesystem():

for i in range(backup_limit+1):
with open(f'./something_{i}_kcleaner.bak', 'w') as f:
f.write('lololol')

check_and_cleanup_backups("./something")

capture.check_present(
('root', 'DEBUG', 'Removing File something_0_kcleaner.bak')
)

@log_capture()
def test_2_over_backup_limit(capture):
with runner.isolated_filesystem():

for i in range(backup_limit+2):
with open(f'./something_{i:03}_kcleaner.bak', 'w') as f:
f.write('lololol')

check_and_cleanup_backups("./something")

capture.check_present(
('root', 'DEBUG', 'Removing File something_000_kcleaner.bak'),
('root', 'DEBUG', 'Removing File something_001_kcleaner.bak')
)
18 changes: 18 additions & 0 deletions tests/kcleaner_cli_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from kcleaner import cli
from testfixtures import log_capture
import click
from click.testing import CliRunner
import pytest
import yaml

#cli(resource, name, kubeconfig, undo, debug)

runner = CliRunner()
sample_yaml = """
something:
alist:
- item1: test
something: test
- item2: test
something: test
"""
29 changes: 29 additions & 0 deletions tests/kcleaner_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,35 @@ def test_clean_empty_file(capture):
('root', 'ERROR', "Config File is empty! Can't use it.")
)

@log_capture()
def test_clean_empty_file_debug(capture):
with runner.isolated_filesystem():
with open('./config', 'w') as f:
f.write('')

result = runner.invoke(cli, ['-k', './config', '-d'])
assert result.exit_code == 11
capture.check_present(
('root', 'DEBUG', 'Running with Debug flag'),
('root', 'DEBUG', 'Trying to retrieve contents of file ./config'),
('root', 'DEBUG', 'checking if file ./config exists...'),
('root', 'DEBUG', 'File exists!'),
('root', 'DEBUG', "Type of the file contents: <class 'NoneType'>"),
('root', 'ERROR', "Config File is empty! Can't use it.")
)

@log_capture()
def test_clean_empty_file_undo(capture):
with runner.isolated_filesystem():
with open('./config', 'w') as f:
f.write('')

result = runner.invoke(cli, ['-k', './config', '-u'])
#assert result.exit_code == 11
capture.check_present(
('root', 'INFO', 'Undo flag was set! checking for the backup file...')
)

@log_capture()
def test_non_valid_yaml(capture):
with runner.isolated_filesystem():
Expand Down
15 changes: 15 additions & 0 deletions tests/kcleaner_update_file_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,19 @@ def test_existant_file_yaml_content(capture):
assert sample_yaml in result
capture.check_present(
('root', 'DEBUG', 'Writing new yaml doc into the config file')
)

@log_capture()
def test_backup_file_yaml_content(capture):
with runner.isolated_filesystem():
with open('./something_kcleaner.bak', 'w') as f:
f.write('lololol')
update_file("./something_kcleaner.bak", sample_yaml)

with open('./something_kcleaner.bak', 'r') as f:
result = yaml.safe_load(f)

assert sample_yaml in result
capture.check_present(
('root', 'DEBUG', 'Checking for all kcleaner backup files')
)

0 comments on commit be9d3f5

Please sign in to comment.