Added more readability and a base implementation for a walk test

This commit is contained in:
Maximilien Rigaut 2022-06-25 05:46:59 +02:00
parent 7d344eb7b1
commit b83e1a8f78
No known key found for this signature in database
GPG Key ID: 4F14B23709ADA5B1
6 changed files with 89 additions and 28 deletions

View File

@ -24,8 +24,9 @@ if __name__ == "__main__":
db_path = ""
# print(" > No user database was found, the bundled one will be used.")
# Will always try to load discordHelper/discordHelper.json # TODO : Document this feature.
run_db = os.path.join(directory_path, "discordHelper_last_run.json")
argv = f"--all --autodetect --launch --continue --timeout 10 {db_path}--gen-data {run_db}.yaml".split(" ")
argv = rf"--all --autodetect --launch --continue --timeout 10 {db_path}--gen-data {run_db} --db discordHelper/discordHelper.json".split(" ")
# print(" > Starting the discordHelper with the following arguments:")
# print(" > " + " ".join(argv))

View File

@ -40,13 +40,13 @@ class AgnosticPaths:
platform = sys.platform
if platform.startswith('win'):
self.os = 'windows'
self.default_database = 'windows_base'
self.default_database = 'databases/windows_base.json'
elif platform.startswith('linux'):
self.os = 'linux'
self.default_database = 'linux_base'
self.default_database = 'databases/linux_base.json'
elif platform.startswith('darwin'):
self.os = 'mac'
self.default_database = 'mac_base'
self.default_database = 'databases/mac_base.json'
else:
raise OSError("This script can only check for Spideys on Windows, Linux and Mac.")
return self.os
@ -67,16 +67,16 @@ class AgnosticPaths:
if os.path.exists(ptb_path):
self.ptb = "PTB"
self.args.ptb = "PTB"
self.default_database = "windows_ptb"
self.default_database = "databases/windows_ptb.json"
return ptb_path
else:
self.default_database = "windows_base"
self.default_database = "databases/windows_base.json"
return base_path
if self.ptb == 'PTB':
self.default_database = "windows_base"
self.default_database = "databases/windows_bas.jsone"
return base_path+"PTB"
else:
self.default_database = "windows_ptb"
self.default_database = "databases/windows_ptb.json"
return base_path # Try to find the default version
elif self.os == 'linux':
return os.path.join("/", "opt", "discord")

View File

@ -27,7 +27,7 @@ def parse(_args):
parser.add_argument("--database", "--db", type=str, help="Alternative database for the analysis")
parser.add_argument("--pollrate", "--poll", default=0.1, type=float, help="Refresh rate of the status, 0.1 is the default")
parser.add_argument("--printrate", "-refresh", default=5, type=int, help="Print the tests every X seconds")
parser.add_argument("--size", "--window-size", default=90, type=int, help="Size of the message window")
parser.add_argument("--size", "--window-size", default=120, type=int, help="Size of the message window")
# Tests
parser.add_argument('--spidey', action='store_true', help='Runs the spidey test')
parser.add_argument('--line-count', action='store_true', help='Test all known files for line count')

View File

@ -20,6 +20,7 @@ os.system('color')
_TEST_MODULES = {
"spidey": ["spidey_test", "SpideyTest"],
# "test_walk": ["test_template", "TestWalkTemplate"],
"size_test": ["size_test", "SizeTest"],
}
PROGRAM_VERSION = "1.0.0"
@ -95,16 +96,27 @@ class TestRunner:
"""
Opens the base data file
"""
print(self.args.database)
default_database = resource_path(self.agnostic_path.default_database)
if not self.args.database:
self.args.database = default_database
if os.path.exists(self.args.database):
with open(resource_path(self.args.database), "r") as f:
db_data = f.read()
# print(db_data)
else: # Try opening the default database
print(colored("\n > The database file does not exist, trying to open the default one...\n", "yellow"))
with open(resource_path('databases/windows_base.json'), "r") as f:
db_data = f.read()
# print(db_data)
self.base_data = json.load(f)
elif os.path.exists(default_database): # Try opening the default database
# print(colored(
# "\n > The database file specified does not exist, "
# "trying to open the default one for your os...\n", "yellow"
# ))
with open(resource_path(default_database), "r") as f:
self.base_data = json.load(f)
else:
print(colored(
"\n > The database file does not exist, and the default "
"one for your os does not exist either.\n", "red"
))
self.base_data = {}
def update_module_list(self):
"""

41
modules/size_test.py Normal file
View File

@ -0,0 +1,41 @@
import asyncio
import os
import time
from modules import test_template
class SizeTest(test_template.TestWalkTemplate):
def __init__(self, args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock):
"""
Simple test runner, compare file size to known good values.
"""
super().__init__(args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock)
def run_test(self):
"""
Walk all files and check their size.
:return: Whether any of the files are larger than the expected size.
:rtype: bool
"""
self.set_status("running")
size = len(self.walk())
error_msg = ""
for path in self.walk():
if os.path.isfile(path):
if not self.compare(path, "size", os.path.getsize, (), {}):
self.add_failure(path, f"Test {self.name()} failed on {path}")
error_msg += f"{path} is " \
f"({self.get_expected_result(path, 'size')} b) not ({os.path.getsize(path)} b).\n"
self.is_infected = True
if not self.args.continue_on_error:
return self.finish("failure", f"{path} is supposed to be {self.get_expected_result(path, 'size')} bytes, but it is {os.path.getsize(path)} bytes.")
if self.is_infected:
return self.finish(
"failure",
error_msg
)
self.progress = 100
return self.finish("success", "Your discord is not infected.")

View File

@ -51,6 +51,7 @@ class TestTemplate:
self.dict_process_lock.acquire()
self.dict_process[self.name()] = self
self.dict_process_lock.release()
self.init_test_data()
def run_test(self):
"""
@ -60,6 +61,11 @@ class TestTemplate:
self.set_status("running", "The test will begin shortly, please wait...")
self.set_status("sucess", "The test was a success but kinda not a success.")
def init_test_data(self):
if self.test_data is None and not self.args.continue_on_error:
self.set_status("problem", "No test data given.")
return self.finish()
def name(self):
"""
:return: Name of the test
@ -159,8 +165,8 @@ class TestWalkTemplate(TestTemplate):
:type test_data: str
"""
super().__init__(args, agnpath, test_data, queue, queue_lock, dict_process, dict_process_lock)
if test_data is None:
self.set_status("problem", "No test data given.")
# if test_data is None:
# self.set_status("problem", "No test data given.")
def add_test_result(self, path, testname, result):
"""
@ -217,13 +223,7 @@ class TestWalkTemplate(TestTemplate):
"""
self.set_status("running", "The test will begin shortly, please wait...")
if self.test_data is None and not self.args.continue_on_error:
self.set_status("problem", "No test data given.")
return self.finish()
self.set_status("running", "The test will begin shortly, please wait...")
for path in self.walk():
print(path)
if not self.compare(path, "test", lambda x: True, [], {}):
self.add_failure(path, f"Test {self.name()} failed on {path}")
if not self.args.continue_on_error:
@ -245,7 +245,7 @@ class TestWalkTemplate(TestTemplate):
"""
return self.agnostic_path.walk_all_files(self.agnostic_path())
def compare(self, path, entry_name, function, args, kwargs):
def compare(self, path, entry_name, function, args, kwargs, cmp_function=None):
"""
Use the function on the given path, with given arguments and compare it with the entry in the test data.
:param path: Path to the file or directory
@ -258,6 +258,8 @@ class TestWalkTemplate(TestTemplate):
:type args: list
:param kwargs: Keyword arguments to use on the function
:type kwargs: dict
:param cmp_function: Function compare both results
:type cmp_function: function
"""
data_origin = self.add_test_result(path, entry_name, function(path, *args, **kwargs))
@ -266,7 +268,12 @@ class TestWalkTemplate(TestTemplate):
self.set_status("problem", f"No expected data found for {path}")
return False
if data_origin != expected_data:
if cmp_function is None:
if data_origin == expected_data:
return True
return False
else:
if cmp_function(data_origin, expected_data):
return True
return False
return True