unit_tests

This commit is contained in:
sitisll 2023-06-02 12:36:32 +03:00
parent 13bad49747
commit 21e35bb78b
2 changed files with 100 additions and 47 deletions

29
hlna.py

@ -69,42 +69,29 @@ def hlna():
@click.argument('g', nargs=1)
@click.option('-d',required=True , help="Путь до zip архива")
def restore(g, d):
directory_to_extract_to = "*******"
"Получение пути к файлам внутри архива, может понадобиться при раскидывании по местам"
"==================================================================================="
"Получение пути к файлам внутри архива"
with zipfile.ZipFile(d, 'r') as zip_file:
files = zip_file.namelist()
"===================================================================================="
"Извлечение файлов"
"======================="
for i in files:
with zipfile.ZipFile(d, 'r') as zip_file:
s = i.split("/")
s.pop(-1)
s = "/"+'/'.join(s)+'/' # вот тут где-то еще надо начало пути проверить и если home_dir другой заменить
print(i,colorama.Fore.GREEN + "- перемещен" + colorama.Style.RESET_ALL )
zip_file.extract(i, '/')
"======================="
"Извлечение из архива всего, скорее всего не пригодится"
#with zipfile.ZipFile(d, 'r') as zip_file:
# zip_file.extractall(directory_to_extract_to)
"--------------------------"
path_extarct = "./" if g == 'test' else "/"
zip_file.extract(i, path_extarct)
print(i, colorama.Fore.GREEN + "- перемещен" + colorama.Style.RESET_ALL)
print_line(f"Бэкап {d} восстановлен", flag="GREEN")
@hlna.command(help='Бэкап серверов выбранной игры <hlna backup ark')
@click.argument('g', nargs=1)
def backup(g):
if g == "ark":
if g == "ark" or g == "ark_test":
source = [f"{dir_config}"]
backup_path = input("Введите конечный путь для бэкапа, по умолчанию ******")
#backup_path = input("Введите конечный путь для бэкапа, по умолчанию ******")
backup_path = f"{dir_server_ark}Backups" if g=="ark" else f"{dir_server_ark}Backups/test_backup"
if not backup_path:
backup_path = f"{dir_server_ark}Backups"
today = backup_path + os.sep + time.strftime('%Y_%m_%d')
target = f"{backup_path}/" + g + "_backup-" + time.strftime('%H_%M_%S') + '.zip'
target = f"{backup_path}/" + g + "_backup-" + time.strftime('%Y_%m_%d') + '.zip'
create_dir(backup_path)
with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED, True) as myzip:
for source_folder in source:

118
pytest.py

@ -1,38 +1,104 @@
#!/usr/bin/env python3
from colorama import Fore, Style
#!/usr/bin/env python3
import os
import time
from threading import Thread
from pathlib import Path
import hlna
import time
import unittest
from unittest.mock import patch
import zipfile
from click.testing import CliRunner
from pathlib import Path
home_dir = Path.home()
config_hlna = f"{home_dir}/.config/hlna/"
def config():
hlna.config()
def servers():
x = os.system("./hlna.py servers >> /dev/null")
if x == 0:
print("Servers - "+Fore.GREEN + "OK" + Style.RESET_ALL)
else:
print(Fore.RED + "Servers Fail" + Style.RESET_ALL)
def delete():
print("Delete - " + Fore.RED + "False" + Style.RESET_ALL)
class TestFindFile(unittest.TestCase):
def setUp(self):
self.test_dir = 'test_dir'
os.mkdir(self.test_dir)
self.test_files = ['foo.conf', 'bar.ini', 'qux.cfg', 'baz.txt', '.directory']
for f in self.test_files:
open(os.path.join(self.test_dir, f), 'w').close()
def tearDown(self):
for f in self.test_files:
os.remove(os.path.join(self.test_dir, f))
os.rmdir(self.test_dir)
def test_find_file(self):
res = hlna.find_file(self.test_dir)
self.assertEqual(sorted(res), sorted(['foo.conf', 'bar.ini', 'qux.cfg', 'baz.txt']))
def test_find_file_empty_dir(self):
res = hlna.find_file('empty_dir')
self.assertEqual(res, [])
class TestCreateDir(unittest.TestCase):
def test_create_dir(self):
testdir = 'testdir'
self.assertFalse(os.path.exists(testdir))
hlna.create_dir(testdir)
self.assertTrue(os.path.exists(testdir))
os.rmdir(testdir)
class TestRestore(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
self.zip_file_name = "test_backup.zip"
os.system("touch test_file1.txt test_file2.txt")
self.file_names = ["test_file1.txt", "test_file2.txt"]
with zipfile.ZipFile(self.zip_file_name, 'w') as zip_file:
for file_name in self.file_names:
zip_file.write(file_name)
def tearDown(self):
os.remove(self.zip_file_name)
for file_name in self.file_names:
os.remove(file_name)
def test_restore(self):
result = self.runner.invoke(hlna.restore, ["test", "-d", self.zip_file_name])
self.assertEqual(result.exit_code, 0)
for file_name in self.file_names:
self.assertTrue(os.path.exists("./"+file_name))
class TestBackup(unittest.TestCase):
def setUp(self):
data = hlna.read_yaml(g="path_server")
if data['path_server'] == "":
data['path_server'] = f"{home_dir}Servers/ARK/Backups/test_backup/"
else:
data['path_server'] = f"{data['path_server']}ARK/Backups/test_backup/"
self.backup_path = data['path_server']
self.runner = CliRunner()
with open(f"{config_hlna}/ARK/test_file.txt", "w") as file:
file.write("test content")
def tearDown(self):
os.remove(f"{config_hlna}ARK/test_file.txt")
for root, dirs, files in os.walk(self.backup_path):
for file in files:
os.remove(os.path.join(root, file))
os.rmdir(self.backup_path)
def test_backup(self):
result = self.runner.invoke(hlna.backup, ["ark_test"])
self.assertEqual(result.exit_code, 0)
self.assertTrue(os.path.exists(self.backup_path))
target = f"{self.backup_path}ark_test_backup-" + time.strftime('%Y_%m_%d') + '.zip'
self.assertTrue(os.path.exists(target))
with zipfile.ZipFile(target, 'r') as zip_file:
self.assertEqual(zip_file.testzip(), None)
self.assertTrue(os.path.exists(os.path.join(target, f"{config_hlna}ARK/test_file.txt")))
if __name__ == '__main__':
unittest.main()
if __name__ == "__main__":
servers()
delete()
config()
#print(f"{Fore.GREEN} + {text}")
#print(Fore.YELLOW + "-"*30 + Style.RESET_ALL)