Compare commits

...

21 Commits
v1.0.9 ... main

Author SHA1 Message Date
Maximilien Rigaut 03a49e049b
Merge pull request #36 from idle-org/develop
Develop
2022-06-27 18:44:53 +02:00
Maximilien Rigaut 9f00fd8b7e
Merge pull request #35 from idle-org/features/fast_access
Features/fast access
2022-06-27 18:35:58 +02:00
Maximilien Rigaut c8772e0f9b
Actually activated the cache 2022-06-27 18:34:50 +02:00
Maximilien Rigaut ee77507bc9
Implementation of file caching 2022-06-27 18:10:46 +02:00
Maximilien Rigaut 0df5970a41
Skipped the first message 2022-06-27 17:22:45 +02:00
Maximilien Rigaut 854ce93430
Merge pull request #34 from idle-org/features/ptb
Updated with ptb data
2022-06-27 17:06:20 +02:00
Maximilien Rigaut 87bcc47af1
Updated with ptb data 2022-06-27 17:04:09 +02:00
Maximilien Rigaut 53d751e3bb
Merge pull request #33 from idle-org/features/typehunts
Features/typehunts
2022-06-27 14:54:31 +02:00
Maximilien Rigaut 7af44900d3
Type hinting followup 2022-06-27 14:51:52 +02:00
Maximilien Rigaut 079a5e69be
More type hinting 2022-06-27 04:40:41 +02:00
Maximilien Rigaut cfe76ca497
Type hinting 2022-06-27 04:24:41 +02:00
Maximilien Rigaut 22952cd871
Merge pull request #32 from idle-org/features/test_centralisation
Correction of the auto test data generation
2022-06-27 04:13:56 +02:00
Maximilien Rigaut 8333c4daa7
Correction of the auto test data generation 2022-06-27 04:09:00 +02:00
Maximilien Rigaut 1c32e30533
Merge pull request #31 from idle-org/features/test_centralisation
Added spidey test data
2022-06-27 04:06:47 +02:00
Maximilien Rigaut 16ef468fcc
Added spidey test data 2022-06-27 04:06:09 +02:00
Maximilien Rigaut bf09d81afb
Merge pull request #30 from idle-org/features/test_centralisation
Features/test centralisation
2022-06-27 04:04:33 +02:00
Maximilien Rigaut c8292f498b
Cleanup of some tests and base tests methods 2022-06-27 04:01:40 +02:00
Maximilien Rigaut 335d7fc967
Changed some default parameters 2022-06-27 03:01:31 +02:00
Maximilien Rigaut 2741329afc
Changed tests names 2022-06-27 03:00:57 +02:00
Maximilien Rigaut cd38817742
Changed test data 2022-06-27 02:59:36 +02:00
Maximilien Rigaut aa249aad51
Renamed tests and added a fast class for function interaction 2022-06-27 02:59:16 +02:00
18 changed files with 17993 additions and 12013 deletions

View File

@ -3,13 +3,13 @@
A python script to detect whether your discord was tempered with in any noticeable way. A python script to detect whether your discord was tempered with in any noticeable way.
## Functionnement ## Functionnement
DiscordHelper will provide a fast analysis over known malwares and progress it's analysis toward a complete sha1 checksum comparison against a known good install. DiscordHelper will provide a fast analysis over known malwares and progress its analysis toward a complete sha1 checksum comparison against a known good installation.
If the integrity can't be verified, the helper will propose to upload a new database with all computed data as a new staple to compare to (this functionnality is mostly useful if you have a custom/modded Discord). If the integrity can't be verified, the helper will propose to upload a new database with all computed data as a new staple to compare to (this functionnality is mostly useful if you have a custom/modded Discord).
### Windows ### Windows
DiscordHelper is configured to run every tests and save the result in a folder named "DiscordHelper" in the same directory as the script. DiscordHelper is configured to run every test and save the result in a folder named "DiscordHelper" in the same directory as the script.
This file, named test_results_found.json, contains a snapshot of your current install. If you change it's name to test_results.json, DiscordHelper will use this snapshot instead of the bundled databases. (This feature is mostly useful if you have a custom/modded Discord). This file, named test_results_found.json, contains a snapshot of your current installation. If you change its name to test_results.json, DiscordHelper will use this snapshot instead of the bundled databases. (This feature is mostly useful if you have a custom/modded Discord).
### What to do if the integrity can't be verified? ### What to do if the integrity can't be verified?
Open a new issue, upload the test_results_found.json file and any details surrounding the problem. Open a new issue, upload the test_results_found.json file and any details surrounding the problem.
@ -17,7 +17,7 @@ Open a new issue, upload the test_results_found.json file and any details surrou
If this isn't a bug in DiscordHelper, you may want to reinstall Discord, and possibly your whole operating system. If this isn't a bug in DiscordHelper, you may want to reinstall Discord, and possibly your whole operating system.
# WARNING # WARNING
Due to the evolutive nature of viruses, only a new, clean install of DiscordHelper will warranty a total detection of all threats, since a virus will always try to temper all methods of detecting it. Due to the evolutive nature of viruses, only a new, clean installation of DiscordHelper will warranty a total detection of all threats, since a virus will always try to temper all methods of detecting it.
# DISCLAMER # DISCLAMER
While this program aims to provide a complete coverage over Discord Threats, there are many ways to temper with discord that cannot be covered in this program, mainly side-dll tempering and all forms of RAT and keyloggers. DiscordHelper cannot and will not try to analyse the rest of your operating system, we leave this intrusive behaviour to other anti-viruses. While this program aims to provide a complete coverage over Discord Threats, there are many ways to temper with discord that cannot be covered in this program, mainly side-dll tempering and all forms of RAT and keyloggers. DiscordHelper cannot and will not try to analyse the rest of your operating system, we leave this intrusive behaviour to other anti-viruses.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,16 @@
#!/usr/bin/python3 #!/usr/bin/python3
""" Main program """ """ Main program """
import argparse
from modules import main_runner, agnostic_paths, argument_parser from modules import main_runner, agnostic_paths, argument_parser
import sys import sys
def main(argm): def main(argm: argparse.Namespace):
""" """
Main program Main program
:param argm: List of arguments :param argm: List of arguments
:type argm: argparse.Namespace
""" """
agnostic_path = agnostic_paths.AgnosticPaths(argm) agnostic_path = agnostic_paths.AgnosticPaths(argm)
main_runner.run_check(argm, agnostic_path) main_runner.run_check(argm, agnostic_path)

View File

@ -7,7 +7,7 @@ import discordHelper
import time import time
# All modules must be loaded before the main program is run. # All modules must be loaded before the main program is run.
from modules import spidey_test, test_template # noqa # Set for pyinstaller from modules import test_size, test_adler, test_sha, test_spidey, test_line_count # noqa # Set for pyinstaller
if __name__ == "__main__": if __name__ == "__main__":
try: try:
@ -26,7 +26,7 @@ if __name__ == "__main__":
# Will always try to load discordHelper/discordHelper.json # Will always try to load discordHelper/discordHelper.json
run_db = os.path.join(directory_path, "test_results_found.json") run_db = os.path.join(directory_path, "test_results_found.json")
argv = rf"--all --autodetect --launch --continue --timeout 25 {db_path}--gen-data {run_db} --db discordHelper/test_results.json".split(" ") # noqa E501 argv = rf"--all --autodetect --printrate 2 --launch --continue --timeout 25 {db_path}--gen-data {run_db} --db discordHelper/test_results.json".split(" ") # noqa E501
# print(" > Starting the discordHelper with the following arguments:") # print(" > Starting the discordHelper with the following arguments:")
# print(" > " + " ".join(argv)) # print(" > " + " ".join(argv))

0
modules/__init__.py Normal file
View File

View File

@ -1,70 +0,0 @@
"""
Fast adler32 checksum implementation.
"""
import os
from modules import test_template
from zlib import adler32
def apply_adler(path):
"""
Apply the adler32 checksum to a file.
:param path: The path to the file.
:type path: str
:return: The adler32 checksum.
:rtype: int
"""
with open(path, "rb") as f:
return hex(adler32(f.read()))
class AdlerTest(test_template.TestWalkTemplateNoLogs):
def __init__(self, thread_parameters):
"""
Simple test runner, compare adler32 to known good values.
"""
super().__init__(thread_parameters)
def run_test(self):
self.set_status("running")
size = len(self.walk())
error_msg = ""
for i, path in enumerate(self.walk()):
self.progress = int(100*i/size)
short_path = self.agnostic_path.get_short_path(path)
if os.path.isfile(path):
if not self.compare(path, "adler32", apply_adler, (), {}):
res = self.get_test_data(path, "adler32")
self.add_failure(path, f"Test {self.name()} failed on {short_path}")
error_msg += f"{short_path} is " \
f"({res}) not ({self.get_expected_result(path, 'adler32')} b).\n"
if not self.bad_database:
self.is_infected = True
if not self.args.continue_on_error:
return self.finish(
"failure",
f"{short_path} is supposed to be {self.get_expected_result(path, 'adler32')} "
f"bytes, but it is {adler32(open(path, 'rb').read())} bytes."
)
else:
self.is_unknown = True
if not self.args.continue_on_error:
return self.finish(
"problem",
f"{short_path} is supposed to be {self.get_expected_result(path, 'adler32')} "
f"bytes, but it is {adler32(open(path, 'rb').read())} bytes."
)
self.progress = 100
if self.is_infected:
return self.finish(
"failure",
error_msg
)
elif self.is_unknown:
return self.finish(
"problem",
error_msg
)
return self.finish("success", "Your discord is not infected.")

View File

@ -5,6 +5,9 @@ import os
import re import re
import sys import sys
import random import random
import argparse
from typing import List, Dict
class AgnosticPaths: class AgnosticPaths:
@ -12,10 +15,9 @@ class AgnosticPaths:
An agnostic path object, containing all methods to access the files and folders in a standard discord install An agnostic path object, containing all methods to access the files and folders in a standard discord install
""" """
def __init__(self, args): def __init__(self, args: argparse.Namespace):
""" """
:param args: The arguments passed to the script :param args: The arguments passed to the script
:type args: argparse.Namespace
""" """
self.args = args self.args = args
self.ptb = args.ptb self.ptb = args.ptb
@ -31,14 +33,40 @@ class AgnosticPaths:
self.all_files = self.walk_all_files() self.all_files = self.walk_all_files()
random.shuffle(self.all_files) random.shuffle(self.all_files)
self.size = len(self.all_files) self.size = len(self.all_files)
self.cached_files = {}
self.cached_dirs = {}
self._precache_files()
def get_os(self): def walk_cached(self) -> Dict[str, bytes]:
"""
Returns the cached files and directories
:return: The list of files and directories
"""
return self.cached_files
def walk_files(self) -> List[str]:
"""
Returns the list of all files in the discord install
:return: The list of all files in the discord install
"""
return self.all_files
def cached_file(self, path: str) -> bytes:
"""
Returns the file at the given path, if it is cached, otherwise it will return None
:param path: The path to the file
:return: The file at the given path, if it is cached, otherwise it will return None
"""
if path in self.cached_files:
return self.cached_files[path]
return None
def get_os(self) -> str:
""" """
Get the os string in a short, spydey-detector way. Get the os string in a short, spydey-detector way.
For now only windows and linux are supported, note that due to the nature of linux builds, strings will likely become For now only windows and linux are supported, note that due to the nature of linux builds,
linux-arch-deb, linux-arch-snap etc... strings will likely become linux-arch-deb, linux-arch-snap etc...
:return: ("windows", "linux", "mac") :return: ("windows", "linux", "mac")
:rtype: str
""" """
platform = sys.platform platform = sys.platform
if platform.startswith('win'): if platform.startswith('win'):
@ -54,18 +82,17 @@ class AgnosticPaths:
raise OSError("This script can only check for Spideys on Windows, Linux and Mac.") raise OSError("This script can only check for Spideys on Windows, Linux and Mac.")
return self.os return self.os
def _get_path(self): def _get_path(self) -> str:
""" """
Return the base path of the install, note that the self.main_path is not returned, Return the base path of the installation, note that the self.main_path is not returned,
and this method is meant to be used at init only and this method is meant to be used at init only
:return: Base path of the install (minus the version on Windows) :return: Base path of the installation (minus the version on Windows)
:rtype: str
""" """
if self.force_path is not None: if self.force_path is not None:
return self.force_path return self.force_path
if self.os == 'windows': if self.os == 'windows':
base_path = os.path.join(os.path.expanduser('~'), "AppData", "Local", "Discord") base_path = os.path.join(os.path.expanduser('~'), "AppData", "Local", "Discord")
ptb_path = base_path+"PTB" ptb_path = base_path + "PTB"
if self.args.autodetect: if self.args.autodetect:
if os.path.exists(ptb_path): if os.path.exists(ptb_path):
self.ptb = "PTB" self.ptb = "PTB"
@ -77,7 +104,7 @@ class AgnosticPaths:
return base_path return base_path
if self.ptb == 'PTB': if self.ptb == 'PTB':
self.default_database = "databases/windows_ptb.jsone" self.default_database = "databases/windows_ptb.jsone"
return base_path+"PTB" return base_path + "PTB"
else: else:
self.default_database = "databases/windows_base.json" self.default_database = "databases/windows_base.json"
return base_path # Try to find the default version return base_path # Try to find the default version
@ -88,12 +115,11 @@ class AgnosticPaths:
return "" return ""
raise OSError("Cannot detect discord PATH") raise OSError("Cannot detect discord PATH")
def get_version(self): def get_version(self) -> str:
""" """
Looks for the version file in the discord folder Looks for the version file in the discord folder
and return the latest version of the discord build and return the latest version of the discord build
:return: The version build :return: The version build
:rtype: str
""" """
versions = [] versions = []
if self.os == 'windows': if self.os == 'windows':
@ -112,14 +138,14 @@ class AgnosticPaths:
else: else:
raise OSError("Can't find for version on your OS.") raise OSError("Can't find for version on your OS.")
def _update_path(self): def _update_path(self) -> None:
""" """
Update the main path with the version, if needed (windows & mac only) Update the main path with the version, if needed (windows & mac only)
""" """
if self.os == 'windows': if self.os == 'windows':
self.main_path = os.path.join(self.main_path, self.version) self.main_path = os.path.join(self.main_path, self.version)
def list(self, *args): def list(self, *args: str) -> List[float]:
""" """
Lists all files in the path /discord_path/args[0]/args[1].../args[n] Lists all files in the path /discord_path/args[0]/args[1].../args[n]
:param args: The path as a list of parameters list("folder1", "folder2", ..., "foldern") :param args: The path as a list of parameters list("folder1", "folder2", ..., "foldern")
@ -129,7 +155,7 @@ class AgnosticPaths:
""" """
return os.listdir(self(*args)) return os.listdir(self(*args))
def list_dir_files(self, *args): def list_dir_files(self, *args: str) -> List[str]:
""" """
Lists all files and directories in the given path. Lists all files and directories in the given path.
:param args: The path :param args: The path
@ -145,58 +171,60 @@ class AgnosticPaths:
files.append(element) files.append(element)
return dirs, files return dirs, files
def __call__(self, *args): def __call__(self, *args: str) -> str:
""" """
Tries to open the path /discord_path/args[0]/args[1].../args[n] Tries to open the path /discord_path/args[0]/args[1].../args[n]
:param args: The path of the file or directory as a list of parameters __call__("folder1", "folder2", ..., "foldern") :param args: The path of the file or directory as a list of parameters __call__("folder_1", ..., "folder_n")
:type args: str
:return: The path is it exists :return: The path is it exists
:rtype: str :raises: FileNotFoundError if the path doesn't exist
:raises: FileNotFoundError if the path doesn't exists
""" """
_path = os.path.join(self.main_path, *args) _path = os.path.join(self.main_path, *args)
if not os.path.exists(_path): if not os.path.exists(_path):
raise FileNotFoundError(f"Could not find {_path}") raise FileNotFoundError(f"Could not find {_path}")
return _path return _path
def get_path(self): def get_path(self) -> str:
""" """
The main path of the discord install The main path of the discord install
:return: self.main_path :return: self.main_path
:rtype: str
""" """
return self.main_path return self.main_path
def walk_all_files(self, *args): def walk_all_files(self, *args: str) -> List[str]:
""" """
Walks all files in the given path Walks all files in the given path
:param args: The path :param args: The path
:return: A list of all files in the given path :return: A list of all files in the given path
:rtype: list[str]
""" """
return [os.path.join(dirpath, filename) return [os.path.join(dirpath, filename)
for dirpath, dirnames, filenames in os.walk(self(*args)) for dirpath, dirnames, filenames in os.walk(self(*args))
for filename in filenames] for filename in filenames]
def get_short_path(self, path): def get_short_path(self, path: str) -> str:
""" """
Get the short path of the given path Get the short path of the given path
:param path: The path :param path: The path
:return: The short path :return: The short path
:rtype: str
""" """
return os.path.relpath(path, self.main_path) return os.path.relpath(path, self.main_path)
def __repr__(self): def _precache_files(self) -> None:
"""
Precache all files in the discord folder
"""
self.cached_files = {}
for file in self.all_files:
with open(file, "rb") as f:
self.cached_files[file] = f.read()
def __repr__(self) -> str:
""" """
:return: A representation of the AgnosticPath :return: A representation of the AgnosticPath
:rtype: str
""" """
return f"AgnosticPaths(ptb={self.ptb}, os={self.os}, main_path={self.main_path}, version={self.version})" return f"AgnosticPaths(ptb={self.ptb}, os={self.os}, main_path={self.main_path}, version={self.version})"
def __str__(self): def __str__(self) -> str:
""" """
:return: The main path of the discord install :return: The main path of the discord install
:rtype: str
""" """
return self.main_path return self.main_path

View File

@ -1,7 +1,7 @@
import argparse import argparse
def parse(_args): def parse(_args: list) -> argparse.Namespace:
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
prog="Spidey Detector", prog="Spidey Detector",
description='Checks for corrupt discord install' description='Checks for corrupt discord install'
@ -27,16 +27,17 @@ def parse(_args):
parser.add_argument("--gen-data", "--generate-data", "--gen", nargs=1, default="", help="Generate data for the analysis") parser.add_argument("--gen-data", "--generate-data", "--gen", nargs=1, default="", help="Generate data for the analysis")
parser.add_argument("--database", "--db", type=str, help="Alternative database for the analysis") 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("--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("--printrate", "--refresh", default=5, type=float, help="Print the tests every X seconds")
parser.add_argument("--size", "--window-size", default=110, type=int, help="Size of the message window") parser.add_argument("--size", "--window-size", default=110, type=int, help="Size of the message window")
parser.add_argument("--max-shown", default=5, type=int, help="Maximum number of errors shown") parser.add_argument("--max-shown", default=5, type=int, help="Maximum number of errors shown")
# Tests # Tests
parser.add_argument('--spidey', action='store_true', help='Runs the spidey test') parser.add_argument('--spidey', action='store_true', help='Runs the spidey test')
parser.add_argument('--adler', "--adler32", action='store_true', help='Runs the adler32 test')
parser.add_argument('--line-count', action='store_true', help='Test all known files for line count') parser.add_argument('--line-count', action='store_true', help='Test all known files for line count')
parser.add_argument('--file-count', action='store_true', help="Test the number of files in the discord folder") parser.add_argument('--file-count', action='store_true', help="Test the number of files in the discord folder")
parser.add_argument('--file-size', action='store_true', help="Test the size of the files in the discord folder") parser.add_argument('--file-size', action='store_true', help="Test the size of the files in the discord folder")
parser.add_argument('--file-hash', action='store_true', help="Test the hash of the files in the discord folder") parser.add_argument('--file-hash', '--sha', action='store_true', help="Test the hash of the files in the discord folder")
parser.add_argument('--file-path', action='store_true', help="Test the path of the files in the discord folder") parser.add_argument('--file-path', action='store_true', help="Test the path of the files in the discord folder")
parser.add_argument('--file-name', action='store_true', help="Test the name of the files in the discord folder") parser.add_argument('--file-name', action='store_true', help="Test the name of the files in the discord folder")
parser.add_argument('--file-extension', action='store_true', help="Test the extension of the files in the discord folder") parser.add_argument('--file-extension', action='store_true', help="Test the extension of the files in the discord folder")
@ -47,7 +48,6 @@ def parse(_args):
parser.add_argument("--no-eval", action="store_true", help="Check for the eval function wich is a HUGE red flag") parser.add_argument("--no-eval", action="store_true", help="Check for the eval function wich is a HUGE red flag")
parser.add_argument("--const-abuse", "--no-const", action="store_true", parser.add_argument("--const-abuse", "--no-const", action="store_true",
help="Check for the abuse of the const: keyword, wich is massively used for obfucation") help="Check for the abuse of the const: keyword, wich is massively used for obfucation")
parser.add_argument("--test-walk", action="store_true", help="Test walk function")
parser.add_argument("--max-errors", default=5, type=int, help="Maximum number of errors before the analysis is stopped") parser.add_argument("--max-errors", default=5, type=int, help="Maximum number of errors before the analysis is stopped")
return parser.parse_args(_args) return parser.parse_args(_args)

View File

@ -1,3 +1,4 @@
import argparse
import json import json
import os import os
import subprocess import subprocess
@ -6,9 +7,10 @@ import importlib
import threading import threading
import time import time
from collections import deque from collections import deque
from typing import List
from modules.internal_io import global_status, thread_parameters from modules.internal_io import global_status, thread_parameters
from modules import size_test, adler_test # noqa # Used to force import of modules by pyinstaller from modules import agnostic_paths, internal_io
""" """
All modules that can be tested All modules that can be tested
@ -20,10 +22,11 @@ os.system('color')
# red, green, yellow, blue, magenta, cyan, white. # red, green, yellow, blue, magenta, cyan, white.
_TEST_MODULES = { _TEST_MODULES = {
"spidey": ["spidey_test", "SpideyTest"], "spidey": ["test_spidey", "SpideyTest"],
# "test_walk": ["test_template", "TestWalkTemplate"], "file_size": ["test_size", "SizeCheck"],
"size_test": ["size_test", "SizeTest"], "adler": ["test_adler", "Adler32"],
"adler_test": ["adler_test", "AdlerTest"], "file_hash": ["test_sha", "Sha256"],
"line_count": ["test_line_count", "LineCount"],
} }
PROGRAM_VERSION = "1.0.0" PROGRAM_VERSION = "1.0.0"
@ -70,15 +73,12 @@ LOGO = colored(r"""
class TestRunner: class TestRunner:
def __init__(self, args, agnpath, start_time): def __init__(self, args: argparse.Namespace, agnpath: agnostic_paths.AgnosticPaths, start_time: float):
""" """
Main spidey runner Main spidey runner
:param args: List of arguments :param args: List of arguments
:type args: argparse.Namespace
:param agnpath: The path to the discord folder :param agnpath: The path to the discord folder
:type agnpath: agnostic_path.AgnosticPath
:param start_time: The time the test started :param start_time: The time the test started
:type start_time: float
""" """
self.ptb = args.ptb self.ptb = args.ptb
self.args = args self.args = args
@ -87,9 +87,10 @@ class TestRunner:
self.main_path = agnpath.main_path self.main_path = agnpath.main_path
self.version = agnpath.version self.version = agnpath.version
self.start_time = start_time self.start_time = start_time
self.selected_tests = []
self.is_infected = 0 # Only set to 1 if the certainty is high enough self.is_infected = 0 # Only set to 1 if the certainty is high enough
self.is_unknown = 0 # Unknown if the file is infected or not self.is_unknown = 1 # Unknown if the file is infected or not
self.threat_level = 0 # The threat level of the infection, 0 is the lowest, can only be increased self.threat_level = 0 # The threat level of the infection, 0 is the lowest, can only be increased
self.errors = 0 self.errors = 0
self.bad_database = False # Set to true if the database is not valid self.bad_database = False # Set to true if the database is not valid
@ -107,17 +108,17 @@ class TestRunner:
self.open_base_data() self.open_base_data()
self.exec_all_tests() self.exec_all_tests()
def update_threat(self, threat_level): def update_threat(self, threat_level: int):
""" """
Updates the threat level Updates the threat level
:param threat_level: The new threat level :param threat_level: The new threat level
:type threat_level: int
""" """
self.threat_level = max(threat_level, self.threat_level) self.threat_level = max(threat_level, self.threat_level)
def open_base_data(self): def open_base_data(self) -> dict:
""" """
Opens the base data file Opens the base data file
:return: The base data (a json file)
""" """
default_database = resource_path(self.agnostic_path.default_database) default_database = resource_path(self.agnostic_path.default_database)
@ -149,9 +150,10 @@ class TestRunner:
self.base_data = {} self.base_data = {}
return self.base_data return self.base_data
def check_database(self): def check_database(self) -> bool: # TODO: All of this can be refactored with a function
""" """
Check if the database is valid set self.bad_database to True if it is not Check if the database is valid set self.bad_database to True if it is not
:return: True if the database is valid
""" """
if not self.base_data: if not self.base_data:
print(colored(" > The database is empty", "red")) print(colored(" > The database is empty", "red"))
@ -194,12 +196,21 @@ class TestRunner:
if "tests" not in self.base_data: if "tests" not in self.base_data:
print(colored(" > The database is missing the test results", "red")) print(colored(" > The database is missing the test results", "red"))
self.bad_database = True self.bad_database = True
else:
for test_name in self.selected_tests:
found_one_value = False
for file_name, test_names in self.base_data["tests"].items():
if test_name in test_names:
found_one_value = True
break # At least one test is in the database
if not found_one_value:
print(colored(f" > The database is missing the test {test_name}", "red"))
self.bad_database = True
def update_module_list(self): def update_module_list(self) -> List[str]:
""" """
Gets the list of modules to be loaded (in accordance to the config) Gets the list of modules to be loaded (in accordance to the config)
:return: List of modules :return: List of modules
:rtype: list
""" """
modules = {} modules = {}
classes = {} classes = {}
@ -209,6 +220,7 @@ class TestRunner:
if self.args.all or self.args.__getattribute__(module_name): if self.args.all or self.args.__getattribute__(module_name):
modules[values[0]] = importlib.import_module(f"modules.{values[0]}") modules[values[0]] = importlib.import_module(f"modules.{values[0]}")
classes[values[0]] = getattr(modules[values[0]], values[1]) classes[values[0]] = getattr(modules[values[0]], values[1])
self.selected_tests.append(values[1])
except AttributeError as e: except AttributeError as e:
print(f"The module {module_name} was not loaded because it was not specified in the config.") print(f"The module {module_name} was not loaded because it was not specified in the config.")
@ -217,7 +229,7 @@ class TestRunner:
self.loaded_test_modules.update(modules) self.loaded_test_modules.update(modules)
self.loaded_test_classes.update(classes) self.loaded_test_classes.update(classes)
def exec_all_tests(self): def exec_all_tests(self) -> None:
""" """
Executes all the tests, get their result as they finishes Executes all the tests, get their result as they finishes
""" """
@ -256,7 +268,7 @@ class TestRunner:
tc.daemon = True tc.daemon = True
tc.start() tc.start()
def controller_test(self): def controller_test(self) -> None:
""" """
Kills the tests if the user press enter Kills the tests if the user press enter
""" """
@ -277,7 +289,7 @@ class TestRunner:
except Exception: except Exception:
sys.exit() sys.exit()
def post_test_runner(self): def post_test_runner(self) -> None:
""" """
Runs the post test runner if all tests are finished Runs the post test runner if all tests are finished
""" """
@ -294,10 +306,9 @@ class TestRunner:
time.sleep(0.1) time.sleep(0.1)
return 0 return 0
def test_waiter(self): def test_waiter(self) -> None:
""" """
Waits for the end of the tests Waits for the end of the tests
:return:
""" """
for t in self.list_of_tests: # Can only proceed if all tests are finished for t in self.list_of_tests: # Can only proceed if all tests are finished
t.join() t.join()
@ -308,11 +319,10 @@ class TestRunner:
global POST_RUN_ALLOWED global POST_RUN_ALLOWED
POST_RUN_ALLOWED = True POST_RUN_ALLOWED = True
def get_exit_code(self): def get_exit_code(self) -> int: # TODO: Use a NamedTuple
""" """
Gets the exit code of the tests Gets the exit code of the tests
:return: The exit code :return: The exit code
:rtype: int
""" """
status = self.get_status() status = self.get_status()
if status.tests_finished == status.tests_total: if status.tests_finished == status.tests_total:
@ -333,11 +343,10 @@ class TestRunner:
exit_code = -1 # The tests are not finished exit_code = -1 # The tests are not finished
return exit_code return exit_code
def get_status(self): def get_status(self) -> internal_io.global_status:
""" """
Gets the status of the tests Gets the status of the tests
:return: The status :return: The status
:rtype: internal_io.global_status
""" """
queue_lock.acquire(timeout=0.5) queue_lock.acquire(timeout=0.5)
nb_tests = len(self.list_of_tests) nb_tests = len(self.list_of_tests)
@ -361,7 +370,10 @@ class TestRunner:
for test_name, test in self.dict_of_processes.items(): for test_name, test in self.dict_of_processes.items():
progress += test.progress progress += test.progress
progress = int(progress / nb_tests) if nb_tests == 0:
progress = 100
else:
progress = int(progress / nb_tests)
nb_tests_ran = nb_tests_success + nb_tests_failure + nb_tests_skipped + nb_tests_error nb_tests_ran = nb_tests_success + nb_tests_failure + nb_tests_skipped + nb_tests_error
nb_test_running = nb_tests - nb_tests_ran nb_test_running = nb_tests - nb_tests_ran
@ -376,11 +388,10 @@ class TestRunner:
progress=progress progress=progress
) )
def get_test_data(self): def get_test_data(self) -> dict:
""" """
Gets the test data Gets the test data
:return: The test data :return: The test data
:rtype: dict
""" """
data = {} data = {}
queue_lock.acquire() queue_lock.acquire()
@ -394,13 +405,11 @@ class TestRunner:
return data return data
def export_data(test_runner, data): def export_data(test_runner: TestRunner, data: dict) -> dict:
""" """
Exports the test data Exports the test data and returns it
:param test_runner: The test runner :param test_runner: The test runner
:type test_runner: TestRunner
:param data: The test data :param data: The test data
:type data: dict
""" """
main_data = { main_data = {
"global": "global":
@ -415,13 +424,11 @@ def export_data(test_runner, data):
return main_data return main_data
def print_status(status, timer_start): def print_status(status: internal_io.global_status, timer_start: float) -> None:
""" """
Prints the status Prints the status
:param status: The status :param status: The status
:type status: internal_io.global_status
:param timer_start: The start time of the tests :param timer_start: The start time of the tests
:type timer_start: float
""" """
if status.tests_failed != 0: if status.tests_failed != 0:
color = "red" color = "red"
@ -446,20 +453,20 @@ def print_status(status, timer_start):
else: else:
mon, sec = divmod(ellapsed_time * 100 / status.progress, 60) mon, sec = divmod(ellapsed_time * 100 / status.progress, 60)
hr, mon = divmod(mon, 60) hr, mon = divmod(mon, 60)
estimated_time = "%d:%02d:%02d" % (hr, mon, sec) sec = round(sec, 0) + 1
estimated_time = f"{hr:n}:{mon:02n}:{sec:02.0n}"
print(colored( print(colored(
f" > Overall progress: {status.progress}%" f" > Overall progress: {status.progress}%"
f" in {time.time() - timer_start:.2f} seconds" f" in {time.time() - timer_start:.2f} seconds"
f" estimaded time ({estimated_time})", color f" estimaded total time ({estimated_time})", color
)) ))
def run_check(args, agnpath): def run_check(args: argparse.Namespace, agnpath: agnostic_paths.AgnosticPaths) -> None:
""" """
Runs all operations selected in the config Runs all operations selected in the config
:param args: List of arguments :param args: List of arguments
:param agnpath: Annostic path to the discord folder :param agnpath: Annostic path to the discord folder
:return: None
""" """
# Initialize the test runner # Initialize the test runner
print(LOGO) print(LOGO)
@ -467,7 +474,7 @@ def run_check(args, agnpath):
tr = TestRunner(args, agnpath, start_time=start) # All operation are executed in parallel and the user can stop them tr = TestRunner(args, agnpath, start_time=start) # All operation are executed in parallel and the user can stop them
# Poll information from the tests # Poll information from the tests
POLLRATE, PRINT_RATE, COUNTER = args.pollrate, args.printrate, 0 POLLRATE, PRINT_RATE, COUNTER = args.pollrate, args.printrate, 1
COUNTER_MAX = int(PRINT_RATE / POLLRATE) COUNTER_MAX = int(PRINT_RATE / POLLRATE)
# Main test polling loop # Main test polling loop
@ -493,7 +500,7 @@ def run_check(args, agnpath):
sys.exit(tr.get_exit_code()) sys.exit(tr.get_exit_code())
def resource_path(relative_path): def resource_path(relative_path: str) -> str:
""" Get absolute path to resource, works for dev and for PyInstaller """ """ Get absolute path to resource, works for dev and for PyInstaller """
try: try:
# PyInstaller creates a temp folder and stores path in _MEIPASS # PyInstaller creates a temp folder and stores path in _MEIPASS
@ -503,12 +510,12 @@ def resource_path(relative_path):
return os.path.join(base_path, relative_path) return os.path.join(base_path, relative_path)
def print_final_status(testrunner, start_time, args): def print_final_status(testrunner: TestRunner, start_time: float, args: argparse.Namespace) -> None:
""" """
Prints the final status Prints the final status
""" """
status = testrunner.get_status() status = testrunner.get_status()
if status.tests_failed == 0 and status.tests_error == 0: if status.tests_failed == 0 and status.tests_error == 0 and status.tests_total != 0:
color = "green" color = "green"
print(CLEAR_CODE) print(CLEAR_CODE)
elif status.tests_failed > 0: elif status.tests_failed > 0:
@ -542,14 +549,15 @@ def print_final_status(testrunner, start_time, args):
print(colored(f"\nThe program executed {msg_error}, exiting in {args.timeout} seconds...", color)) print(colored(f"\nThe program executed {msg_error}, exiting in {args.timeout} seconds...", color))
def fill_it(size, string1, string2): def fill_it(size: int, string1: str, string2: str) -> str:
""" """
Fills a string with a character Makes a string with the format "string1......string2"
with as many "." as needed to fill the size
""" """
return string1 + max(size - len(string1)-len(string2), 0) * "." + string2 return string1 + max(size - len(string1) - len(string2), 0) * "." + string2
def at_max_elements(table, msize, fill): def at_max_elements(table: list, msize: int, fill: str) -> list:
""" """
Display at maximum msize elements, replace last with fill and return the table Display at maximum msize elements, replace last with fill and return the table
""" """
@ -558,13 +566,13 @@ def at_max_elements(table, msize, fill):
# if en(table) > lmsize: # if en(table) > lmsize:
table = table[:msize] + [ table = table[:msize] + [
fill+"..."+str(len(table)-msize)+" more lines" if len(table) > msize else ""] fill + "..." + str(len(table) - msize)+" more lines" if len(table) > msize else ""]
return table return table
def fit_it_under(message, size, start_line=""): def fit_it_under(message: str, size: int, start_line: str = "") -> list:
""" """
Fits a message under a size Fits a message under a size (split lines into multiple lines if needed) and returns the list of lines
""" """
final_message = [] final_message = []
for line in message.split('\n'): for line in message.split('\n'):
@ -576,9 +584,9 @@ def fit_it_under(message, size, start_line=""):
return final_message return final_message
def gen_save_data(args, test_runner): def gen_save_data(args: argparse.Namespace, test_runner: TestRunner) -> None:
""" """
Generates the save data Generates the save data and writes it to a file
""" """
print(colored("\n > Generating data...", "blue")) print(colored("\n > Generating data...", "blue"))
data = test_runner.get_test_data() data = test_runner.get_test_data()

View File

@ -1,60 +0,0 @@
import os
from modules import test_template
class SizeTest(test_template.TestWalkTemplateNoLogs):
def __init__(self, thread_parameters):
"""
Simple test runner, compare file size to known good values.
"""
super().__init__(thread_parameters)
self.is_unknown = False
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 = self.agnostic_path.size
error_msg = ""
for i, path in enumerate(self.walk()):
self.progress = int(100*i/size)
short_path = self.agnostic_path.get_short_path(path)
if os.path.isfile(path):
if not self.compare(path, "size", os.path.getsize, (), {}):
res = self.get_test_data(path, "adler32")
self.add_failure(path, f"Test {self.name()} failed on {short_path}")
error_msg += f"{short_path} is " \
f"({res} b) not ({self.get_expected_result(path, 'size')} b).\n"
# print(self.bad_database)
if not self.bad_database:
self.is_infected = True
if not self.args.continue_on_error:
return self.finish(
"failure",
f"{short_path} is supposed to be {self.get_expected_result(path, 'size')}"
f" bytes, but it is {os.path.getsize(path)} bytes.")
else:
self.is_unknown = True
if not self.args.continue_on_error:
return self.finish(
"problem",
f"{short_path} is supposed to be {self.get_expected_result(path, 'size')}"
f" bytes, but it is {os.path.getsize(path)} bytes.")
self.progress = 100
if self.is_infected:
return self.finish(
"failure",
error_msg
)
elif self.is_unknown:
return self.finish(
"problem",
error_msg
)
return self.finish("success", "Your discord is not infected.")

28
modules/test_adler.py Normal file
View File

@ -0,0 +1,28 @@
"""
Fast adler32 checksum implementation.
"""
from modules import test_template, internal_io
from zlib import adler32
def apply_adler(path: str, cached_data: bytes = None) -> hex:
"""
Apply the adler32 checksum to a string.
:param path: The path to the file.
:param cached_data: The cached data if it exists.
:return: The adler32 checksum.
"""
if cached_data is None:
with open(path, "rb") as f:
return hex(adler32(f.read()))
return hex(adler32(cached_data))
class Adler32(test_template.TestWalkTemplateSimpleFunction):
def __init__(self, thread_parameters: internal_io.thread_parameters):
"""
Simple test runner, compare adler32 to known good values.
"""
super().__init__(thread_parameters, apply_adler, "", use_cache=True)

View File

@ -0,0 +1,15 @@
"""
Test against the line count of the files in the discord folder.
"""
from modules import test_template, internal_io
class LineCount(test_template.TestWalkTemplateSimpleFunction):
def __init__(self, thread_parameters: internal_io.thread_parameters):
"""
Simple test runner, compare line count to known good values.
"""
super().__init__(thread_parameters,
lambda bstr, cached_data: len(open(bstr, "rb").readlines()),
" lines", use_cache=False)

34
modules/test_sha.py Normal file
View File

@ -0,0 +1,34 @@
"""
Sha256 hash function.
"""
from hashlib import sha256
from modules import test_template, internal_io
def sha256_hash(path: str, cached_data: bytes = None) -> hex:
"""
Returns the sha256 hash of the data.
"""
if cached_data is None:
with open(path, "rb") as f:
return sha256(f.read()).hexdigest()
return sha256(cached_data).hexdigest()
def sha256_hash_on_str(io_s: bytes) -> hex:
"""
Returns the sha256 hash of the data.
"""
return sha256(io_s).hexdigest()
class Sha256(test_template.TestWalkTemplateSimpleFunction):
"""
Sha256 hash function.
"""
def __init__(self, thread_parameters: internal_io.thread_parameters):
"""
Sha256 hash function.
"""
super().__init__(thread_parameters, sha256_hash, "", use_cache=True)

20
modules/test_size.py Normal file
View File

@ -0,0 +1,20 @@
import os
from modules import test_template, internal_io
def get_size(path: str, cached_data: bytes = None) -> int: # noqa: E501
"""
Get the size of a file.
:param path: The path to the file.
:return: The size of the file.
"""
return os.path.getsize(path)
class SizeCheck(test_template.TestWalkTemplateSimpleFunction):
def __init__(self, thread_parameters: internal_io.thread_parameters):
"""
Simple test runner, compare file size to known good values.
"""
super().__init__(thread_parameters, get_size, " bytes", use_cache=False)

View File

@ -1,21 +1,20 @@
import os import os
from modules import test_template from modules import test_template, internal_io
class SpideyTest(test_template.TestTemplate): class SpideyTest(test_template.TestTemplate):
def __init__(self, thread_parameters): def __init__(self, thread_parameters: internal_io.thread_parameters):
""" """
Simple test runner, for testing the detection of Spidey viruses. Simple test runner, for testing the detection of Spidey viruses.
""" """
super().__init__(thread_parameters) super().__init__(thread_parameters)
def run_test(self): def run_test(self) -> str:
""" """
Counts the number of lines in both index.js files. If it's more than one, it's almost certain your discord Counts the number of lines in both index.js files. If it's more than one, it's almost certain your discord
is corrupted. is corrupted.
:return: Whether any of the index.js is more than one line :return: The status of the test as a string.
:rtype: bool
""" """
self.set_status("running") self.set_status("running")
@ -48,15 +47,14 @@ class SpideyTest(test_template.TestTemplate):
"If you've recently downloaded a .exe directly sent from someone, " "If you've recently downloaded a .exe directly sent from someone, "
"do also consider a clean windows reinstall." "do also consider a clean windows reinstall."
) )
self.add_to_new_data("global_tests", self.name(), "passed")
self.progress = 100 self.progress = 100
return self.finish("success", "Your discord is not infected.") return self.finish("success", "Your discord is not infected.")
def get_path(self): def get_path(self) -> str:
""" """
Gets the path of the two folders we need to check Gets the path of the two folders we need to check
:return: Two paths. :return: Two paths.
:rtype: str
""" """
discord_modules = self.agnostic_path("modules", "discord_modules-1", "discord_modules") discord_modules = self.agnostic_path("modules", "discord_modules-1", "discord_modules")
discord_desktop_core = self.agnostic_path("modules", "discord_desktop_core-1", "discord_desktop_core") discord_desktop_core = self.agnostic_path("modules", "discord_desktop_core-1", "discord_desktop_core")

View File

@ -1,8 +1,10 @@
""" """
A global template for all tests. A global template for all tests.
""" """
import os
from typing import Callable, Union
from modules import internal_io from modules import internal_io, agnostic_paths
class TestDataError(Exception): class TestDataError(Exception):
@ -13,7 +15,7 @@ class TestDataError(Exception):
class TestTemplate: class TestTemplate:
def __init__(self, thread_parameters: internal_io.thread_parameters): def __init__(self, thread_parameters: internal_io.thread_parameters, use_cache: bool = True) -> None:
""" """
Simple test template. Simple test template.
:param thread_parameters.args: List of arguments :param thread_parameters.args: List of arguments
@ -48,6 +50,7 @@ class TestTemplate:
self.failure_dict = {} self.failure_dict = {}
self.new_data = {} self.new_data = {}
self.progress = 0 self.progress = 0
self.use_cache = use_cache
self.is_unknown = False self.is_unknown = False
self.dict_process = thread_parameters.dict_process self.dict_process = thread_parameters.dict_process
self.dict_process_lock = thread_parameters.dict_process_lock self.dict_process_lock = thread_parameters.dict_process_lock
@ -57,17 +60,17 @@ class TestTemplate:
self.dict_process_lock.release() self.dict_process_lock.release()
self.init_test_data() self.init_test_data()
def run(self): def run(self) -> None:
""" """
Runs the test. Runs the test.
""" """
try: try:
self.run_test() self.run_test()
except Exception as e: except Exception as e:
self.add_failure("problem", "DISCORD HELPER:"+str(e)) self.add_failure("problem", "DISCORD HELPER:" + str(e))
return self.finish("problem", str(e)) return self.finish("problem", str(e))
def run_test(self): def run_test(self) -> None:
""" """
The main runner function, must be implemented by the child class. The main runner function, must be implemented by the child class.
During the execution of the test, the status code and status MUST be updated. During the execution of the test, the status code and status MUST be updated.
@ -75,29 +78,26 @@ class TestTemplate:
self.set_status("running", "The test will begin shortly, please wait...") 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.") self.set_status("sucess", "The test was a success but kinda not a success.")
def init_test_data(self): def init_test_data(self) -> Union[str, None]:
if self.test_data is None and not self.args.continue_on_error: if self.test_data is None and not self.args.continue_on_error:
self.set_status("problem", "No test data given.") self.set_status("problem", "No test data given.")
return self.finish() return self.finish()
def name(self): def name(self) -> str:
""" """
:return: Name of the test :return: Name of the test
:rtype: str
""" """
return str(self.__class__.__name__) return str(self.__class__.__name__)
def get_status_code(self): def get_status_code(self) -> str:
""" """
:return: Status code at the time of call. :return: Status code at the time of call.
:rtype: str
""" """
return self.status_code return self.status_code
def get_status(self): def get_status(self) -> internal_io.test_status:
""" """
:return: Status at the time of call. :return: Status at the time of call.
:rtype: internal_io.test_status
""" """
return internal_io.test_status( return internal_io.test_status(
name=self.name(), name=self.name(),
@ -109,23 +109,19 @@ class TestTemplate:
) )
@staticmethod @staticmethod
def get_status_from_code(code): def get_status_from_code(code: str) -> str:
""" """
:param code: The status code to get the status from. :param code: The status code to get the status from.
:type code: str
:return: Description of the status code :return: Description of the status code
:rtype: str
""" """
return internal_io.return_code_dict[code] return internal_io.return_code_dict[code]
def set_status(self, statuscode: str, message: str = None): def set_status(self, statuscode: str, message: str = None) -> str:
""" """
Sets a new status code. Sets a new status code.
:param statuscode: Status code to set :param statuscode: Status code to set
:param message: Message to set :param message: Message to set
:type statuscode: str
:return: new status code :return: new status code
:rtype: str
""" """
self.status_code = statuscode self.status_code = statuscode
if message is not None: if message is not None:
@ -134,9 +130,12 @@ class TestTemplate:
self.status = self.get_status_from_code(statuscode) self.status = self.get_status_from_code(statuscode)
return self.status_code return self.status_code
def finish(self, statuscode: str = None, message: str = None): def finish(self, statuscode: str = None, message: str = None) -> str:
""" """
Finishes the test. Finishes the test.
:param statuscode: Status code to set
:param message: Message to set
:type statuscode: str
""" """
if message is not None: if message is not None:
self.status = message self.status = message
@ -149,88 +148,73 @@ class TestTemplate:
self.queue_lock.release() self.queue_lock.release()
return self.get_status_code() return self.get_status_code()
def add_failure(self, path, message): def add_failure(self, path: str, message: str) -> None:
""" """
Adds a failure to the failure dictionary. Adds a failure to the failure dictionary.
:param path: Path to the file that failed :param path: Path to the file that failed
:type path: str
:param message: Message to add :param message: Message to add
:type message: str
""" """
self.failure_dict[path] = message self.failure_dict[path] = message
def __del__(self): def __del__(self) -> None:
""" """
Destructor. Destructor.
""" """
if self.status_code == "running": if self.status_code == "running":
return self.finish("skipped") return self.finish("skipped")
def add_to_new_data(self, entry: str, testname: str, value: str) -> any:
"""
Adds a new entry to the database.
:param entry: The entry to add
:param testname: The name of the test
:param value: The value of the entry
:return: The value of the entry
"""
if entry not in self.new_data:
self.new_data[entry] = {}
self.new_data[entry][testname] = value
return value
def get_from_new_data(self, entry: str, testname: str) -> any:
"""
Gets the value of an entry from the database.
:param entry: The entry to get
:param testname: The name of the test
:return: The value of the entry
"""
if entry in self.new_data:
if testname in self.new_data[entry]:
return self.new_data[entry][testname]
return None
def get_from_database(self, entry: str, testname: str) -> any:
"""
Gets the value of an entry from the database.
:param entry: The entry to get
:param testname: The name of the test
:return: The value of the entry
"""
if self.test_data:
if "tests" in self.test_data:
if entry in self.test_data["tests"]:
if testname in self.test_data["tests"][entry]:
return self.test_data["tests"][entry][testname]
return None
class TestWalkTemplate(TestTemplate): class TestWalkTemplate(TestTemplate):
def __init__(self, thread_parameters): def __init__(self, thread_parameters: internal_io.thread_parameters, use_cache: bool = False):
""" """
Simple test template. Simple test template.
""" """
super().__init__(thread_parameters) super().__init__(thread_parameters, use_cache)
self.to_skip = [] self.to_skip = []
def add_test_result(self, path, testname, result): def run_test(self) -> str:
"""
Adds a test result to the data dictionary.
:param path: Path to the file that was tested
:type path: str
:param testname: Name of the test
:type testname: str
:param result: Result of the test
:type result: any
"""
path = self.agnostic_path.get_short_path(path)
if path not in self.new_data:
self.new_data[path] = {}
self.new_data[path][testname] = result
return result
def get_test_data(self, path, testname):
"""
Gets the test data from the data dictionary.
:param path: Path to the file that was tested
:type path: str
:param testname: Name of the test
:type testname: str
:return: Test data
:rtype: any
"""
path = self.agnostic_path.get_short_path(path)
if path in self.new_data:
if testname in self.new_data[path]:
return self.new_data[path][testname]
return None
def get_expected_result(self, path, testname):
"""
Gets the expected result from the data dictionary.
:param path: Path to the file that was tested
:type path: str
:param testname: Name of the test
:type testname: str
:return: Expected result
:rtype: any
"""
if self.test_data:
path = self.agnostic_path.get_short_path(path)
if "tests" in self.test_data:
if path in self.test_data["tests"]:
if testname in self.test_data["tests"][path]:
return self.test_data["tests"][path][testname]
return None
def run_test(self):
""" """
The main runner function, must be implemented by the child class. The main runner function, must be implemented by the child class.
Here is an example of how to use the add_test_result function. Here is an example of how to use the add_test_result function.
:return:
""" """
self.set_status("running", "The test will begin shortly, please wait...") self.set_status("running", "The test will begin shortly, please wait...")
@ -251,34 +235,60 @@ class TestWalkTemplate(TestTemplate):
return self.finish() return self.finish()
def walk(self): def walk(self) -> list:
""" """
Walks the given path and returns a list of all files and directories. Walks the given path and returns a list of all files and directories.
:return: List of all files :return: List of all files
:return:
""" """
return self.agnostic_path.all_files return self.agnostic_path.all_files
def compare(self, path, entry_name, function, args, kwargs, cmp_function=None): def add_test_result(self, path: str, testname: str, result: any) -> any:
"""
Adds a test result to the data dictionary.
:param path: Path to the file being tested
:param testname: Name of the test
:param result: Result of the test
:return: The result of the test
"""
path = self.agnostic_path.get_short_path(path)
return self.add_to_new_data(path, testname, result)
def get_test_data(self, path: str, testname: str) -> any:
"""
Gets the test data from the data dictionary.
:param path: Path to the file being tested
:param testname: Name of the test
"""
return self.get_from_new_data(self.agnostic_path.get_short_path(path), testname)
def get_expected_result(self, path: str, testname: str) -> Union[str, None]:
"""
Gets the expected result from the data dictionary.
:param path: Path to the file being tested
:param testname: Name of the test
"""
if self.test_data:
return self.get_from_database(self.agnostic_path.get_short_path(path), testname)
return None
def compare(self, path: agnostic_paths.AgnosticPaths, entry_name: str, function: Callable,
args: list, kwargs: dict, cmp_function: Callable = None):
""" """
Use the function on the given path, with given arguments and compare it with the entry in the test data. 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 :param path: Path to the file or directory
:type path: agnostic_path.AgnosticPath
:param entry_name: Name of the entry in the test data :param entry_name: Name of the entry in the test data
:type entry_name: str
:param function: Function to use on the path :param function: Function to use on the path
:type function: function
:param args: Arguments to use on the function :param args: Arguments to use on the function
:type args: list
:param kwargs: Keyword arguments to use on the function :param kwargs: Keyword arguments to use on the function
:type kwargs: dict
:param cmp_function: Function compare both results :param cmp_function: Function compare both results
:type cmp_function: function
""" """
if self.agnostic_path.get_short_path(path) in self.to_skip: if self.agnostic_path.get_short_path(path) in self.to_skip:
return True return True
if self.use_cache:
kwargs["cached_data"] = self.agnostic_path.cached_file(path)
else:
kwargs["cached_data"] = None
data_origin = self.add_test_result(path, entry_name, function(path, *args, **kwargs)) data_origin = self.add_test_result(path, entry_name, function(path, *args, **kwargs))
expected_data = self.get_expected_result(path, entry_name) expected_data = self.get_expected_result(path, entry_name)
@ -297,9 +307,73 @@ class TestWalkTemplate(TestTemplate):
class TestWalkTemplateNoLogs(TestWalkTemplate): class TestWalkTemplateNoLogs(TestWalkTemplate):
def __init__(self, thread_parameters): def __init__(self, thread_parameters: internal_io.thread_parameters, use_cache: bool = False):
""" """
Simple test template. Simple test template.
""" """
super().__init__(thread_parameters) super().__init__(thread_parameters, use_cache)
self.to_skip = [r"modules\discord_dispatch-1\discord_dispatch\dispatch.log"] self.to_skip = [r"modules\discord_dispatch-1\discord_dispatch\dispatch.log"]
class TestWalkTemplateSimpleFunction(TestWalkTemplateNoLogs):
def __init__(self, thread_parameters: internal_io.thread_parameters,
function: Callable, unit_test: str, use_cache: bool = False):
"""
A test template that runs a simple function on every file, and compares the result with the expected data.
:param thread_parameters: Thread parameters
:param function: Function to use on every file
:param unit_test: A descriptor of what the test returns
"""
super().__init__(thread_parameters, use_cache)
self.function = function
self.test_name = self.name()
self.unit_test = unit_test
def run_test(self) -> bool:
"""
Walk all files and check their size.
:return: Whether any of the files are larger than the expected size.
"""
self.set_status("running")
size = self.agnostic_path.size
error_msg = ""
for i, path in enumerate(self.walk()):
self.progress = int(100*i / size)
short_path = self.agnostic_path.get_short_path(path)
if os.path.isfile(path):
if not self.compare(path, self.test_name, self.function, (), {}):
res = self.get_test_data(path, self.test_name)
self.add_failure(path, f"Test {self.name()} failed on {short_path}")
error_msg += f"{short_path} is " \
f"({res}{self.unit_test}) not ({self.get_expected_result(path, self.test_name)}" \
f"{self.unit_test}).\n"
# print(self.bad_database)
if not self.bad_database:
self.is_infected = True
if not self.args.continue_on_error:
return self.finish(
"failure",
f"{short_path} is supposed to be {self.get_expected_result(path, self.test_name)}"
f" {self.unit_test}, but it is {self.get_expected_result(path, self.test_name)}"
f"{self.unit_test}.")
else:
self.is_unknown = True
if not self.args.continue_on_error:
return self.finish(
"problem",
f"{short_path} is supposed to be {self.get_expected_result(path, self.test_name)}"
f"{self.unit_test}, but it is {os.path.getsize(path)}{self.unit_test}")
self.progress = 100
if self.is_infected:
return self.finish(
"failure",
error_msg
)
elif self.is_unknown:
return self.finish(
"problem",
error_msg
)
return self.finish("success", "Your discord is not infected.")

11
tox.ini Normal file
View File

@ -0,0 +1,11 @@
[flake8]
ignore = D203, E226
exclude =
.git,
__pycache__,
docs/source/conf.py,
old,
build,
dist
max-complexity = 16
max_line_length = 127