_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q270300 | Production._does_require_deprecation | test | def _does_require_deprecation(self):
"""
Check if we have to put the previous version into the deprecated list.
"""
for index, version_number in enumerate(self.current_version[0][:2]):
# We loop through the 2 last elements of the version.
if version_number > self.version_yaml[index]:
| python | {
"resource": ""
} |
q270301 | AutoContinue.backup | test | def backup(self):
"""
Backup the current execution state.
"""
if PyFunceble.CONFIGURATION["auto_continue"]:
# The auto_continue subsystem is activated.
# We initiate the location where we are going to save the data to backup.
data_to_backup = {}
# We get the current counter states.
configuration_counter = PyFunceble.INTERN["counter"]["number"]
# We initiate the data we have to backup.
data_to_backup[PyFunceble.INTERN["file_to_test"]] = {
# We backup the number of tested.
"tested": configuration_counter["tested"],
# We backup the number of up.
"up": configuration_counter["up"],
# We backup the number of down.
"down": configuration_counter["down"],
# We backup the number of invalid.
"invalid": configuration_counter["invalid"],
}
| python | {
"resource": ""
} |
q270302 | AutoContinue.restore | test | def restore(self):
"""
Restore data from the given path.
"""
if PyFunceble.CONFIGURATION["auto_continue"] and self.backup_content:
# The auto_continue subsystem is activated and the backup_content
# is not empty.
# We get the file we have to restore.
file_to_restore = PyFunceble.INTERN["file_to_test"]
if file_to_restore in self.backup_content:
# The file we are working with is already into the backup content.
# We initiate the different status to set.
to_initiate = ["up", "down", "invalid", "tested"]
# Because at some time it was not the current status, we have to map
# the new with the old. This way, if someone is running the latest
# version | python | {
"resource": ""
} |
q270303 | AdBlock._is_to_ignore | test | def _is_to_ignore(cls, line):
"""
Check if we have to ignore the given line.
:param line: The line from the file.
:type line: str
"""
# We set the list of regex to match to be
# considered as ignored.
to_ignore = [r"(^!|^@@|^\/|^\[|^\.|^-|^_|^\?|^&)"] # , r"(\$|,)(image)"]
for element in to_ignore:
# We loop through the list of regex.
if Regex(line, element, return_data=False).match():
# The currently | python | {
"resource": ""
} |
q270304 | AdBlock._handle_options | test | def _handle_options(self, options):
"""
Handle the data from the options.
:param options: The list of options from the rule.
:type options: list
:return: The list of domains to return globally.
:rtype: list
"""
# We initiate a variable which will save our result
result = []
# We initiate the regex which will be used to extract the domain listed
# under the option domain=
regex_domain_option = r"domain=(.*)"
for option in options:
# We loop through the list of option.
try:
# We try to extract the list of domains from the currently read
# option.
domains = Regex(
option, regex_domain_option, return_data=True, rematch=True, group=0
).match()[-1]
if domains:
| python | {
"resource": ""
} |
q270305 | AdBlock._extract_base | test | def _extract_base(self, element):
"""
Extract the base of the given element.
.. example:
given "hello/world?world=beautiful" return "hello"
:param element: The element we are working with.
:type element: str|list
"""
if isinstance(element, list):
# The given element is a list.
# We get the base of each element of the list.
return [self._extract_base(x) for x in element]
# We get the base if it is an URL.
base = self.checker.is_url_valid(url=element, return_base=True)
if base:
| python | {
"resource": ""
} |
q270306 | AdBlock._format_decoded | test | def _format_decoded(self, to_format, result=None): # pragma: no cover
"""
Format the exctracted adblock line before passing it to the system.
:param to_format: The extracted line from the file.
:type to_format: str
:param result: A list of the result of this method.
:type result: list
:return: The list of domains or IP to test.
:rtype: list
"""
if not result:
# The result is not given.
# We set the result as an empty list.
result = []
for data in List(to_format).format():
# We loop through the different lines to format.
if data:
# The currently read line is not empty.
if "^" in data:
# There is an accent in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("^"), result)
if "#" in data:
# There is a dash in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("#"), result)
if "," in data:
# There is a comma in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split(","), result)
if "!" in data:
# There is an exclamation mark in the currently read line.
# We recall this method but with the current result state
# and splited data.
return self._format_decoded(data.split("!"), result)
if "|" in data:
# There is a vertival bar in the currently read line.
# We recall this method but with the current | python | {
"resource": ""
} |
q270307 | HTTPCode._access | test | def _access(self): # pragma: no cover
"""
Get the HTTP code status.
:return: The matched HTTP status code.
:rtype: int|None
"""
try:
# We try to get the HTTP status code.
if PyFunceble.INTERN["to_test_type"] == "url":
# We are globally testing a URL.
# We get the head of the URL.
req = PyFunceble.requests.head(
self.to_get,
timeout=PyFunceble.CONFIGURATION["seconds_before_http_timeout"],
headers=self.headers,
verify=PyFunceble.CONFIGURATION["verify_ssl_certificate"],
)
else:
# We are not globally testing a URL.
# We get the head of the constructed URL.
req = PyFunceble.requests.head(
self.to_get,
timeout=PyFunceble.CONFIGURATION["seconds_before_http_timeout"],
| python | {
"resource": ""
} |
q270308 | HTTPCode.get | test | def get(self):
"""
Return the HTTP code status.
:return: The matched and formatted status code.
:rtype: str|int|None
"""
if PyFunceble.HTTP_CODE["active"]:
# The http status code extraction is activated.
# We get the http status code.
http_code = self._access()
# We initiate a variable which will save the list of allowed
# http status code.
list_of_valid_http_code = []
for codes in [
PyFunceble.HTTP_CODE["list"]["up"],
PyFunceble.HTTP_CODE["list"]["potentially_down"],
PyFunceble.HTTP_CODE["list"]["potentially_up"],
]:
# We loop throught the list of http status code.
# We extend the list of valid with the currently read
# codes.
list_of_valid_http_code.extend(codes)
if http_code not in list_of_valid_http_code or http_code is None:
# * The extracted http code | python | {
"resource": ""
} |
q270309 | syntax_check | test | def syntax_check(domain): # pragma: no cover
"""
Check the syntax of the given domain.
:param domain: The domain to check the syntax for.
:type domain: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`.
"""
if domain and isinstance(domain, str):
# * The given domain is not | python | {
"resource": ""
} |
q270310 | is_subdomain | test | def is_subdomain(domain): # pragma: no cover
"""
Check if the given domain is a subdomain.
:param domain: The domain we are checking.
:type domain: str
:return: The subdomain state.
:rtype: bool
.. warning::
If an empty or a non-string :code:`domain` is given, we return :code:`None`.
"""
if domain and isinstance(domain, str):
# * The given domain is not | python | {
"resource": ""
} |
q270311 | ipv4_syntax_check | test | def ipv4_syntax_check(ip): # pragma: no cover
"""
Check the syntax of the given IPv4.
:param ip: The IPv4 to check the syntax for.
:type ip: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is | python | {
"resource": ""
} |
q270312 | is_ipv4_range | test | def is_ipv4_range(ip): # pragma: no cover
"""
Check if the given IP is an IP range.
:param ip: The IP we are checking.
:type ip: str
:return: The IPv4 range state.
:rtype: bool
.. warning::
If an empty or a non-string :code:`ip` is given, we | python | {
"resource": ""
} |
q270313 | url_syntax_check | test | def url_syntax_check(url): # pragma: no cover
"""
Check the syntax of the given URL.
:param url: The URL to check the syntax for.
:type url: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`url` is given, we return :code:`None`.
"""
if url and isinstance(url, str):
# The given URL is not | python | {
"resource": ""
} |
q270314 | load_config | test | def load_config(under_test=False, custom=None): # pragma: no cover
"""
Load the configuration.
:param under_test:
Tell us if we only have to load the configuration file (True)
or load the configuration file and initate the output directory
if it does not exist (False).
:type under_test: bool
:param custom:
A dict with the configuration index (from .PyFunceble.yaml) to update.
:type custom: dict
.. warning::
If :code:`custom` is given, the given :code:`dict` overwrite
the last value of the given configuration indexes. | python | {
"resource": ""
} |
q270315 | stay_safe | test | def stay_safe(): # pragma: no cover
"""
Print a friendly message.
"""
random = int(choice(str(int(time()))))
if not CONFIGURATION["quiet"] and random % 3 == 0:
print("\n" + Fore.GREEN + Style.BRIGHT + "Thanks for using PyFunceble!")
print(
Fore.YELLOW
+ Style.BRIGHT
+ "Share your experience on "
+ Fore.CYAN
+ "Twitter"
+ Fore.YELLOW
+ " with "
+ Fore.CYAN
+ "#PyFunceble"
+ Fore.YELLOW
+ "!"
)
print(
| python | {
"resource": ""
} |
q270316 | Core._entry_management_url_download | test | def _entry_management_url_download(self, passed):
"""
Check if the given information is a URL.
If it is the case, it download and update the location of file to test.
:param passed: The url passed to the system.
:type passed: str
:return: The state of the check.
:rtype: bool
"""
if passed and self.checker.is_url_valid(passed):
# The passed string is an URL.
# We get the file name based on the URL.
# We actually just get the string after the last `/` in the URL.
file_to_test = passed.split("/")[-1]
if (
not PyFunceble.path.isfile(file_to_test)
or PyFunceble.INTERN["counter"]["number"]["tested"] == 0
):
# The filename does not exist in the current directory
# or the currently number of tested is equal to 0.
| python | {
"resource": ""
} |
q270317 | Core._entry_management_url | test | def _entry_management_url(self):
"""
Manage the loading of the url system.
"""
if (
self.url_file # pylint: disable=no-member
and not self._entry_management_url_download(
| python | {
"resource": ""
} |
q270318 | Core._print_header | test | def _print_header(cls):
"""
Decide if we print or not the header.
"""
if (
not PyFunceble.CONFIGURATION["quiet"]
and not PyFunceble.CONFIGURATION["header_printed"]
):
# * The quiet mode is not activated.
# and
# * The header has not been already printed.
# We print a new line.
print("\n")
if PyFunceble.CONFIGURATION["less"]:
# We have to show less informations on screen.
# We print the `Less` header.
| python | {
"resource": ""
} |
q270319 | Core._file_decision | test | def _file_decision(self, current, last, status=None):
"""
Manage the database, autosave and autocontinue systems for the case that we are reading
a file.
:param current: The currently tested element.
:type current: str
:param last: The last element of the list.
:type last: str
:param status: The status of the currently tested element.
:type status: str
"""
if (
status
and not PyFunceble.CONFIGURATION["simple"]
and PyFunceble.INTERN["file_to_test"]
):
# * The status is given.
# and
# * The simple mode is deactivated.
# and
# * A file to test is set.
# We run the mining logic.
self.mining.process()
# We delete the currently tested element from the mining
# database.
# Indeed, as it is tested, it is already in our
# testing process which means that we don't need it into
# the mining database.
self.mining.remove()
if (
status.lower() in PyFunceble.STATUS["list"]["up"]
or status.lower() in PyFunceble.STATUS["list"]["valid"]
):
# The status is in the list of up status.
if self.inactive_database.is_present():
# The currently tested element is in the database.
# We generate the suspicious file(s).
Generate(PyFunceble.STATUS["official"]["up"]).analytic_file(
"suspicious"
)
# We remove the currently tested element from the
# database.
self.inactive_database.remove()
else:
# The status is not in the list of up status.
# We add the currently tested element to the
# database.
| python | {
"resource": ""
} |
q270320 | Core.domain | test | def domain(self, domain=None, last_domain=None):
"""
Manage the case that we want to test only a domain.
:param domain: The domain or IP to test.
:type domain: str
:param last_domain:
The last domain to test if we are testing a file.
:type last_domain: str
:param return_status: Tell us if we need to return the status.
:type return_status: bool
"""
# We print the header.
self._print_header()
if domain:
# A domain is given.
# We format and set the domain we are testing and treating.
PyFunceble.INTERN["to_test"] = self._format_domain(domain)
else:
# A domain is not given.
# We set the domain we are testing and treating to None.
PyFunceble.INTERN["to_test"] = None
if PyFunceble.INTERN["to_test"]:
# The domain is given (Not None).
if PyFunceble.CONFIGURATION["syntax"]:
# The syntax mode is activated.
# We get the status from Syntax.
| python | {
"resource": ""
} |
q270321 | Core.url | test | def url(self, url_to_test=None, last_url=None):
"""
Manage the case that we want to test only a given url.
:param url_to_test: The url to test.
:type url_to_test: str
:param last_url:
The last url of the file we are testing
(if exist)
:type last_url: str
"""
# We print the header.
self._print_header()
if url_to_test:
# An url to test is given.
# We set the url we are going to test.
PyFunceble.INTERN["to_test"] = url_to_test
else:
# An URL to test is not given.
# We set the url we are going to test to None.
PyFunceble.INTERN["to_test"] = None
if PyFunceble.INTERN["to_test"]:
# An URL to test is given.
if PyFunceble.CONFIGURATION["syntax"]:
# The syntax mode is activated.
# We get the status from Syntax.
status = self.syntax_status.get()
else:
| python | {
"resource": ""
} |
q270322 | Core.colorify_logo | test | def colorify_logo(cls, home=False):
"""
Print the colored logo based on global results.
:param home: Tell us if we have to print the initial coloration.
:type home: bool
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# The quiet mode is not activated.
to_print = []
if home:
# We have to print the initial logo.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
# And we append to the data to print the currently read
# line with the right coloration.
to_print.append(
PyFunceble.Fore.YELLOW + line + PyFunceble.Fore.RESET
)
elif PyFunceble.INTERN["counter"]["percentage"]["up"] >= 50:
# The percentage of up is greater or equal to 50%.
for line in PyFunceble.ASCII_PYFUNCEBLE.split("\n"):
# We loop through each lines of the ASCII representation
# of PyFunceble.
| python | {
"resource": ""
} |
q270323 | Core._format_domain | test | def _format_domain(cls, extracted_domain):
"""
Format the extracted domain before passing it to the system.
:param extracted_domain: The extracted domain.
:type extracted_domain: str
:return: The formatted domain or IP to test.
:rtype: str
.. note:
Understand by formating the fact that we get rid
of all the noises around the domain we want to test.
"""
if not extracted_domain.startswith("#"):
# The line is not a commented line.
if "#" in extracted_domain:
# There is a comment at the end of the line.
# We delete the comment from the line.
extracted_domain = extracted_domain[
: extracted_domain.find("#")
].strip()
if " " in extracted_domain or "\t" in extracted_domain:
# A space or a tabs is in the line.
# We remove all whitestring from the extracted line.
splited_line = extracted_domain.split()
# As there was a space or a tab in the string, we consider
# that we are working with the hosts file format which means
# that the domain we have to test is after the first string.
# So we set the index to 1.
index = 1
while index < len(splited_line):
# We loop until the index is greater than the length of
# the splited line.
| python | {
"resource": ""
} |
q270324 | Core._extract_domain_from_file | test | def _extract_domain_from_file(cls):
"""
Extract all non commented lines from the file we are testing.
:return: The elements to test.
:rtype: list
"""
# We initiate the variable which will save what we are going to return.
result = []
if PyFunceble.path.isfile(PyFunceble.INTERN["file_to_test"]):
# The give file to test exist.
try:
with open(PyFunceble.INTERN["file_to_test"]) as file:
# We open and read the file.
for line in file:
# We loop through each lines.
if not line.startswith("#"):
# The currently read line is not a commented line.
# We append the current read line to the result.
result.append(line.rstrip("\n").strip())
except UnicodeDecodeError:
with open(PyFunceble.INTERN["file_to_test"], encoding="utf-8") as file:
| python | {
"resource": ""
} |
q270325 | Core.file | test | def file(self):
"""
Manage the case that need to test each domain of a given file path.
.. note::
1 domain per line.
"""
# We get, format, filter, clean the list to test.
list_to_test = self._file_list_to_test_filtering()
if PyFunceble.CONFIGURATION["idna_conversion"]:
# We have to convert domains to idna.
# We convert if we need to convert.
list_to_test = domain2idna(list_to_test)
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is desired by the user.
# We format the list.
list_to_test = List(list_to_test).custom_format(Sort.hierarchical)
else:
# The hierarchical sorting is not desired by the user.
# We format the list.
list_to_test = List(list_to_test).custom_format(Sort.standard)
# We initiate a local variable which will save the current state of the list.
not_filtered = list_to_test
try:
# We remove the element which are in the database from the
# current list to test.
list_to_test = List(
list(
set(
list_to_test[PyFunceble.INTERN["counter"]["number"]["tested"] :]
)
- set(PyFunceble.INTERN["flatten_inactive_db"])
)
).format()
_ = list_to_test[-1]
except IndexError:
# Our list to test is the one with the element from the database.
| python | {
"resource": ""
} |
q270326 | Core.file_url | test | def file_url(self):
"""
Manage the case that we have to test a file
.. note::
1 URL per line.
"""
# We get, format, clean the list of URL to test.
list_to_test = self._file_list_to_test_filtering()
# We initiate a local variable which will save the current state of the list.
not_filtered = list_to_test
try:
# We remove the element which are in the database from the
# current list to test.
list_to_test = List(
list(
set(
list_to_test[PyFunceble.INTERN["counter"]["number"]["tested"] :]
)
- set(PyFunceble.INTERN["flatten_inactive_db"])
)
).format()
_ = list_to_test[-1]
except IndexError:
# Our list to test is the one with the element from the database.
list_to_test = not_filtered[
| python | {
"resource": ""
} |
q270327 | Core.switch | test | def switch(
cls, variable, custom=False
): # pylint: disable=inconsistent-return-statements
"""
Switch PyFunceble.CONFIGURATION variables to their opposite.
:param variable:
The variable name to switch.
The variable should be an index our configuration system.
If we want to switch a bool variable, we should parse
it here.
:type variable: str|bool
:param custom:
Let us know if have to switch the parsed variable instead
of our configuration index.
:type custom: bool
:return:
The opposite of the configuration index or the given variable.
:rtype: bool
:raises:
:code:`Exception`
When the configuration is not valid. In other words,
if the PyFunceble.CONFIGURATION[variable_name] is not a bool.
"""
if not custom:
# We are not working with custom variable which is not into
# the configuration.
# We get the current state.
current_state = dict.get(PyFunceble.CONFIGURATION, variable)
else:
# We | python | {
"resource": ""
} |
q270328 | Status.get | test | def get(cls):
"""
Get the status while testing for an IP or domain.
.. note::
We consider that the domain or IP we are currently testing
is into :code:`PyFunceble.INTERN["to_test"]`.
"""
if "to_test" in PyFunceble.INTERN and PyFunceble.INTERN["to_test"]:
| python | {
"resource": ""
} |
q270329 | URLStatus.handle | test | def handle(self):
"""
Handle the backend of the given status.
"""
# We initiate the source we are going to parse to the Generate class.
source = "URL"
if self.catched.lower() not in PyFunceble.STATUS["list"]["invalid"]:
# The parsed status is not in | python | {
"resource": ""
} |
q270330 | DirectoryStructure._get_structure | test | def _get_structure(self):
"""
Get the structure we are going to work with.
:return: The structure we have to work with.
:rtype: dict
"""
# We initiate an empty variable which is going to save the location of
# file we are going to download.
structure_file = ""
# We initiate the variable which will save the request instance.
req = ""
if PyFunceble.path.isfile(self.structure):
# The structure path file exist.
# We set it as the destination file.
structure_file = self.structure
elif PyFunceble.path.isfile(self.base + "dir_structure_production.json"):
# * The structure path file does not exist.
# but
# * The production structure path file exist.
# We set it as the destination file
structure_file = self.base + "dir_structure_production.json"
else:
# * The structure path file does not exist.
# and
# * The production structure path file does not exist.
if "dev" not in PyFunceble.VERSION:
# `dev` is not into the local version name.
# We get the production file from the master branch.
req = PyFunceble.requests.get(
PyFunceble.LINKS["dir_structure"].replace("dev", "master")
)
else:
# `dev` is into the local version name.
# We get the production file from the dev branch.
req = PyFunceble.requests.get(
PyFunceble.LINKS["dir_structure"].replace("master", "dev")
)
if structure_file.endswith("_production.json"):
# The destination is the production file.
# And we return the updated the structure from the | python | {
"resource": ""
} |
q270331 | DirectoryStructure._create_directory | test | def _create_directory(cls, directory, loop=False):
"""
Creates the given directory if it does not exists.
:param directory: The directory to create.
:type directory: str
:param loop: Tell us if we are in the creation loop or not.
:type loop: bool
"""
if not loop and PyFunceble.directory_separator in directory:
# * We are not in the loop.
# and
# * The directory separator in the given directory.
# We split the directories separator.
splited_directory = directory.split(PyFunceble.directory_separator)
# We initiate a variable which will save the full path to create.
full_path_to_create = ""
for single_directory in splited_directory:
# We loop through each directory.
# We append the currently read directory to the full path.
full_path_to_create += single_directory + PyFunceble.directory_separator
# And we create the directory | python | {
"resource": ""
} |
q270332 | DirectoryStructure.delete_uneeded | test | def delete_uneeded(self):
"""
Delete the directory which are not registered into our structure.
"""
# We get the structure we have to apply.
structure = self._get_structure()
# We get the list of key which is implicitly the list of directory we do not bave to delete.
list_of_key = list(structure.keys())
# We move to the content of the parent as we know that we are creating only one directory.
# Note: if one day we will have to create multiple directory, we will have to change
# the following.
structure = structure[list_of_key[0]]
# We also set the parent directory as we are going to construct its childen.
parent_path = list_of_key[0]
if not | python | {
"resource": ""
} |
q270333 | Load._set_path_to_configs | test | def _set_path_to_configs(cls, path_to_config):
"""
Set the paths to the configuration files.
:param path_to_config: The possible path to the config to load.
:type path_to_config: str
:return:
The path to the config to read (0), the path to the default
configuration to read as fallback.(1)
:rtype: tuple
"""
if not path_to_config.endswith(PyFunceble.directory_separator):
# The path to the config does not ends with the directory separator.
# We initiate the default and the parsed variable with the directory separator.
default = parsed = path_to_config + PyFunceble.directory_separator
else:
# The path to | python | {
"resource": ""
} |
q270334 | Load._load_config_file | test | def _load_config_file(self):
"""
Load .PyFunceble.yaml into the system.
"""
try:
# We try to load the configuration file.
PyFunceble.CONFIGURATION.update(
Dict.from_yaml(File(self.path_to_config).read())
)
# We install the latest iana configuration file.
self._install_iana_config()
# We install the latest public suffix configuration file.
self._install_psl_config()
# We install the latest directory structure file.
self._install_directory_structure_file()
except FileNotFoundError as exception:
# But if the configuration file is not found.
if PyFunceble.path.isfile(self.path_to_default_config):
| python | {
"resource": ""
} |
q270335 | Load._install_production_config | test | def _install_production_config(self):
"""
Download the production configuration and install it in the
current directory.
"""
# We initiate the link to the production configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
production_config_link = "https://raw.githubusercontent.com/funilrys/PyFunceble/master/.PyFunceble_production.yaml" # pylint: disable=line-too-long
# We update the link according to our current version.
production_config_link = Version(True).right_url_from_version(
production_config_link
)
if not Version(True).is_cloned():
| python | {
"resource": ""
} |
q270336 | Load._install_iana_config | test | def _install_iana_config(cls):
"""
Download `iana-domains-db.json` if not present.
"""
# We initiate the link to the iana configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
iana_link = PyFunceble.CONFIGURATION["links"]["iana"]
# We update the link according to our current version.
| python | {
"resource": ""
} |
q270337 | Load._install_psl_config | test | def _install_psl_config(cls):
"""
Download `public-suffix.json` if not present.
"""
# We initiate the link to the public suffix configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
psl_link = PyFunceble.CONFIGURATION["links"]["psl"]
# We update the link according to our current version.
psl_link = Version(True).right_url_from_version(psl_link)
# We set the destination of the downloaded file.
destination = (
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["public_suffix"]
)
| python | {
"resource": ""
} |
q270338 | Load._install_directory_structure_file | test | def _install_directory_structure_file(cls):
"""
Download the latest version of `dir_structure_production.json`.
"""
# We initiate the link to the public suffix configuration.
# It is not hard coded because this method is called only if we
# are sure that the configuration file exist.
dir_structure_link = PyFunceble.CONFIGURATION["links"]["dir_structure"]
# We update the link according to our current version.
dir_structure_link = Version(True).right_url_from_version(dir_structure_link)
# We set the destination of the downloaded file.
destination = (
PyFunceble.CURRENT_DIRECTORY
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["dir_structure"]
)
| python | {
"resource": ""
} |
q270339 | Merge._merge_values | test | def _merge_values(self):
"""
Simply merge the older into the new one.
"""
| python | {
"resource": ""
} |
q270340 | Merge._load | test | def _load(self):
"""
Execute the logic behind the merging.
"""
if "PYFUNCEBLE_AUTO_CONFIGURATION" not in PyFunceble.environ:
# The auto configuration environment variable is not set.
while True:
# We infinitly loop until we get a reponse which is `y|Y` or `n|N`.
# We ask the user if we should install and load the default configuration.
response = input(
PyFunceble.Style.BRIGHT
+ PyFunceble.Fore.RED
+ "A configuration key is missing.\n"
+ PyFunceble.Fore.RESET
+ "Try to merge upstream configuration file into %s ? [y/n] "
% (
PyFunceble.Style.BRIGHT
+ self.path_to_config
+ PyFunceble.Style.RESET_ALL
)
)
if isinstance(response, str):
# The response is a string
if response.lower() == "y":
# The response is a `y` or `Y`.
# We merge the old values inside the new one.
self._merge_values()
# And we save.
self._save()
print(
| python | {
"resource": ""
} |
q270341 | Version.split_versions | test | def split_versions(cls, version, return_non_digits=False):
"""
Convert the versions to a shorter one.
:param version: The version to split.
:type version: str
:param return_non_digits:
Activate the return of the non-digits parts of the splitted
version.
:type return_non_digits: bool
:return: The splitted version name/numbers.
:rtype: list
"""
# We split the version.
splited_version = version.split(".")
# We split the parsed version and keep the digits.
digits = [x for x in splited_version if x.isdigit()]
if not return_non_digits:
# | python | {
"resource": ""
} |
q270342 | Version.check_versions | test | def check_versions(cls, local, upstream):
"""
Compare the given versions.
:param local: The local version converted by split_versions().
:type local: list
:param upstream: The upstream version converted by split_versions().
:type upstream: list
:return:
- True: local < upstream
- None: local == upstream
- False: local > upstream
:rtype: bool|None
"""
# A version should be in format [1,2,3] which is actually the version `1.2.3`
# So as we only have 3 elements in the versioning,
# we initiate the following variable in order to get the status of each parts.
status = [None, None, None]
for index, version_number in enumerate(local):
# We loop through the local version.
if int(version_number) < int(upstream[index]):
# The local version is less than the upstream version.
# We initiate its status to True which means that we are in
# an old version (for the current version part).
status[index] = True
elif int(version_number) > int(upstream[index]):
# The | python | {
"resource": ""
} |
q270343 | Version.is_cloned | test | def is_cloned(cls):
"""
Let us know if we are currently in the cloned version of
PyFunceble which implicitly mean that we are in developement mode.
"""
if not PyFunceble.path.isdir(".git"):
# The git directory does not exist.
# We return False, the current version is not the cloned version.
return False
# We list the list of file which can be found only in a cloned version.
list_of_file = [
".coveragerc",
".coveralls.yml",
".gitignore",
".PyFunceble_production.yaml",
".travis.yml",
"CODE_OF_CONDUCT.md",
"CONTRIBUTING.md",
"dir_structure_production.json",
"MANIFEST.in",
"README.rst",
"requirements.txt",
"setup.py",
"version.yaml",
]
# We list the list of directory which can be found only in a cloned
# version.
list_of_dir = ["docs", "PyFunceble", "tests"]
for file in list_of_file:
# We loop through the list of file.
| python | {
"resource": ""
} |
q270344 | Generate._handle_non_existant_index | test | def _handle_non_existant_index(cls):
"""
Handle and check that some configuration index exists.
"""
try:
# We try to call the http code.
PyFunceble.INTERN["http_code"]
except KeyError:
# If it is not found.
# We initiate an empty http code.
PyFunceble.INTERN["http_code"] = "*" * 3
try:
# We try | python | {
"resource": ""
} |
q270345 | Generate._analytic_host_file_directory | test | def _analytic_host_file_directory(self):
"""
Return the analytic directory to write depending of the matched
status.
"""
# We construct the path to the analytic directory.
output_dir = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["analytic"]["directories"]["parent"]
)
if self.domain_status.lower() in PyFunceble.STATUS["list"]["potentially_up"]:
# The status is in the list of analytic up status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"][
"potentially_up"
]
elif (
self.domain_status.lower() in PyFunceble.STATUS["list"]["potentially_down"]
):
# The status is in the list of analytic down status.
# We complete the output directory.
output_dir += PyFunceble.OUTPUTS["analytic"]["directories"][
"potentially_down"
| python | {
"resource": ""
} |
q270346 | Generate.unified_file | test | def unified_file(self):
"""
Generate unified file. Understand by that that we use an unified table
instead of a separate table for each status which could result into a
misunderstanding.
"""
if (
"file_to_test" in PyFunceble.INTERN
and PyFunceble.INTERN["file_to_test"]
and PyFunceble.CONFIGURATION["unified"]
):
# * We are not testing as an imported module.
# and
# * The unified file generation is activated.
# We construct the path of the unified file.
output = (
self.output_parent_dir + PyFunceble.OUTPUTS["default_files"]["results"]
)
if PyFunceble.CONFIGURATION["less"]:
# We have to print less information.
if PyFunceble.HTTP_CODE["active"]:
# The http status code request is activated.
# We construct what we have to print.
to_print = [
self.tested,
self.domain_status,
PyFunceble.INTERN["http_code"],
]
else:
# The http status code request is not activated.
# We construct what we have to print.
to_print = [self.tested, self.domain_status, self.source]
| python | {
"resource": ""
} |
q270347 | Generate.status_file | test | def status_file(self): # pylint: disable=inconsistent-return-statements
"""
Generate a file according to the domain status.
"""
if "file_to_test" in PyFunceble.INTERN:
# We are not testing as an imported module.
# We generate the hosts file.
Generate(self.domain_status, self.source, self.expiration_date).info_files()
# We are testing a file content.
# We increase the percentage count.
Percentage(self.domain_status).count()
# We print on screen if needed.
self._prints_status_screen()
if self._do_not_produce_file():
return None
if (
not PyFunceble.CONFIGURATION["no_files"]
and PyFunceble.CONFIGURATION["split"]
):
# * The | python | {
"resource": ""
} |
q270348 | Generate._do_not_produce_file | test | def _do_not_produce_file(self):
"""
Check if we are allowed to produce a file based from the given
information.
:return:
The state of the production.
True: We do not produce file.
False: We do produce file.
:rtype: bool
"""
if (
Inactive().is_present()
and self.domain_status
in [
| python | {
"resource": ""
} |
q270349 | PublicSuffix._extensions | test | def _extensions(self, line):
"""
Extract the extension from the given line.
:param line: The line from the official public suffix repository.
:type line: str
"""
# We strip the parsed line.
line = line.strip()
if not line.startswith("//") and "." in line:
# * The parsed line is not a commented line.
# and
# * There is a point in the parsed line.
line = line.encode("idna").decode("utf-8")
if line.startswith("*."):
# The parsed line start with `*.`.
# We remove the first two characters.
line = line[2:]
# We we split the points and we get the last element.
# Explanation: The idea behind this action is to
# always get the extension.
extension = line.split(".")[-1]
if extension in self.public_suffix_db:
# The extension is alrady in our database.
| python | {
"resource": ""
} |
q270350 | PublicSuffix.load | test | def load(self):
"""
Load the public suffix database into the system.
"""
if not PyFunceble.INTERN["psl_db"]:
# The public database was not already loaded.
# * We read, convert to dict and return the file content.
| python | {
"resource": ""
} |
q270351 | Sort.standard | test | def standard(cls, element):
"""
Implement the standard and alphabetical sorting.
:param element: The element we are currently reading.
:type element: str
:return: The formatted element.
:rtype: str
"""
# We remove all special | python | {
"resource": ""
} |
q270352 | Sort.hierarchical | test | def hierarchical(cls, element):
"""
The idea behind this method is to sort a list of domain hierarchicaly.
:param element: The element we are currently reading.
:type element: str
:return: The formatted element.
:rtype: str
.. note::
For a domain like :code:`aaa.bbb.ccc.tdl`.
A normal sorting is done in the following order:
1. :code:`aaa`
2. :code:`bbb`
3. :code:`ccc`
4. :code:`tdl`
This method allow the sorting to be done in the following order:
1. :code:`tdl`
2. :code:`ccc`
3. :code:`bbb`
4. :code:`aaa`
"""
# We initiate a variable which will save the element to sort without
# the extension.
to_sort = ""
# We initiate a variable which will save the full extension.
full_extension = ""
# We convert the parsed element to lower case.
element = element.lower()
# We try to get the url base.
url_base = Check().is_url_valid(element, return_base=True)
if not isinstance(url_base, str):
# The url base is not found.
if "." in element:
# There is point in the parsed element.
# We get the position of the first letter of the extension.
extension_index = element.rindex(".") + 1
# We get the extension from the position of the first letter
# of the extension.
extension = element[extension_index:]
if extension in PyFunceble.INTERN["psl_db"]:
# The extension is in the public suffix database.
for suffix in PyFunceble.INTERN["psl_db"][extension]:
# We loop through the list of suffix of the extracted extension.
# We suffix the sufix with a point.
formatted_suffix = "." + suffix
if element.endswith(formatted_suffix):
# The elements ends with the suffix.
# We get the position of the first character of the suffix in
# the parsed element.
suffix_index = element.rindex(formatted_suffix)
# We update the to_sort variable with the element without the suffix.
to_sort = element[:suffix_index]
# We replace the full extension with the currently read suffix.
full_extension = suffix
# We break the loop, we got what we wanted.
break
if not full_extension:
# The full extension is empty.
# We initiate it with the extension.
full_extension = element[extension_index:]
# We update the to_sort variable with the element without the extension.
to_sort = element[: extension_index - 1]
# We append a point to the full extension because the point has to be
# at the end and not at the begining of the extension.
# To understand: Imagine a miror.
full_extension += "."
# We reverse the to_sort string.
tros_ot = to_sort[::-1]
| python | {
"resource": ""
} |
q270353 | IANA.load | test | def load(self):
"""
Initiate the IANA database if it is not the case.
"""
if "iana_db" not in PyFunceble.INTERN or not PyFunceble.INTERN["iana_db"]:
# The global | python | {
"resource": ""
} |
q270354 | IANA._referer | test | def _referer(self, extension):
"""
Return the referer for the given extension.
:param extension: A valid domain extension.
:type extension: str
:return: The whois server to use to get the WHOIS record.
:rtype: str
"""
# We get the a copy of the page.
iana_record = self.lookup.whois(
PyFunceble.CONFIGURATION["iana_whois_server"], "hello.%s" % extension
)
if iana_record and "refer" in iana_record:
# The record is not empty.
# We initiate a regex which will extract the referer.
regex_referer = r"(?s)refer\:\s+([a-zA-Z0-9._-]+)\n"
# We try to extract the referer.
matched = Regex(
iana_record, regex_referer, return_data=True, group=1
).match()
if matched:
# The referer was extracted successfully.
# We return the matched referer. | python | {
"resource": ""
} |
q270355 | IANA._extensions | test | def _extensions(self):
"""
Extract the extention from the given block.
Plus get its referer.
"""
upstream_lines = (
Download(self.iana_url, return_data=True)
.text()
.split('<span class="domain tld">')
)
# We extract the different extension from the currently readed line.
regex_valid_extension = r"(/domains/root/db/)(.*)(\.html)"
| python | {
"resource": ""
} |
q270356 | IANA.update | test | def update(self):
"""
Update the content of the `iana-domains-db` file.
"""
if not PyFunceble.CONFIGURATION["quiet"]:
# * The quiet mode is not activated.
# We print on screen what we are doing.
print("Update of iana-domains-db", end=" ")
# We loop through the line of the iana website.
for extension, referer in self._extensions():
if extension not in self.iana_db or self.iana_db[extension] != referer:
# We add the extension to the databae.
self.iana_db[extension] = referer
| python | {
"resource": ""
} |
q270357 | Mining.mine | test | def mine(self): # pragma: no cover
"""
Search for domain or URL related to the original URL or domain.
:return: The mined domains or URL.
:rtype: dict
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
try:
# We get the history.
history = PyFunceble.requests.get(
self.to_get,
timeout=PyFunceble.CONFIGURATION["seconds_before_http_timeout"],
headers=self.headers,
).history
# We initiate a dictionnary which will save the
# list of mined links.
mined = {self.to_get_bare: []}
for element in history:
# We loop through the history.
# We update the element.
element = element.url
if PyFunceble.INTERN["to_test_type"] == "url":
# We are testing a full url.
# We get the element to append.
to_append = Check().is_url_valid(element, return_base=False)
elif PyFunceble.INTERN["to_test_type"] == "domain":
# We are testing a domain.
# We get the element to append.
to_append = Check().is_url_valid(element, return_base=True)
else:
raise Exception("Unknown tested.")
if to_append:
# There is something to append.
if to_append.endswith(":80"):
# The port is present.
# We get rid of it.
| python | {
"resource": ""
} |
q270358 | Mining._retrieve | test | def _retrieve(self):
"""
Retrieve the mining informations.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if "mined" not in PyFunceble.INTERN:
PyFunceble.INTERN["mined"] = {}
if PyFunceble.path.isfile(self.file):
# Our backup file exist.
# We return the information from our backup.
data = Dict().from_json(File(self.file).read())
# We clean the empty elements.
for file_path in data:
PyFunceble.INTERN["mined"][file_path] = {}
for element in data[file_path]:
if data[file_path][element]:
| python | {
"resource": ""
} |
q270359 | Mining._backup | test | def _backup(self):
"""
Backup the mined informations.
"""
if PyFunceble.CONFIGURATION["mining"]:
| python | {
"resource": ""
} |
q270360 | Mining._add | test | def _add(self, to_add):
"""
Add the currently mined information to the
mined "database".
:param to_add: The element to add.
:type to_add: dict
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if PyFunceble.INTERN["file_to_test"] not in PyFunceble.INTERN["mined"]:
# Our tested file path is not into our mined database.
# We initiate it.
PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]] = {}
for element in to_add:
# We loop through the element to add.
if (
element
in PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]]
):
# The element is already into the tested file path database.
# We extent it with our element to add.
PyFunceble.INTERN["mined"][PyFunceble.INTERN["file_to_test"]][
element
].extend(to_add[element])
| python | {
"resource": ""
} |
q270361 | Mining.remove | test | def remove(self):
"""
Remove the currently tested element from the mining
data.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["mined"]:
# The currently tested file is in our mined database.
for element in PyFunceble.INTERN["mined"][
PyFunceble.INTERN["file_to_test"]
]:
# We loop through the mined index.
if (
self.to_get_bare
in PyFunceble.INTERN["mined"][
PyFunceble.INTERN["file_to_test"]
| python | {
"resource": ""
} |
q270362 | Mining.list_of_mined | test | def list_of_mined(cls):
"""
Provide the list of mined so they can be added to the list
queue.
:return: The list of mined domains or URL.
:rtype: list
"""
# We initiate a variable which will return the result.
result = []
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
if PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["mined"]:
# The file we are testing is into our | python | {
"resource": ""
} |
q270363 | Mining.process | test | def process(self): # pragma: no cover
"""
Process the logic and structuration of the mining database.
"""
if PyFunceble.CONFIGURATION["mining"]:
# The mining is activated.
# We load the mining logic.
mined = self.mine()
if mined:
# The mined data is not empty or None.
| python | {
"resource": ""
} |
q270364 | Logs._get_content | test | def _get_content(cls, file):
"""
Get and return the content of the given log file.
:param file: The file we have to get the content from.
:type file: str
:return The content of the given file.
| python | {
"resource": ""
} |
q270365 | Logs._write_content | test | def _write_content(cls, content, file):
"""
Write the content into the given file.
:param content: The dict to write.
:type content: dict
:param file: The file to write.
:type file: str
"""
| python | {
"resource": ""
} |
q270366 | Logs.whois | test | def whois(self, record):
"""
Logs the WHOIS record if needed.
:param record: The record to log.
:type record: str
"""
if PyFunceble.CONFIGURATION["debug"] and PyFunceble.CONFIGURATION["logs"]:
# The debug and the logs subsystem are activated.
if PyFunceble.INTERN["referer"]:
referer = PyFunceble.INTERN["referer"]
else:
referer = None
to_write = {
self.current_time: {
"domain": PyFunceble.INTERN["to_test"],
"record": record,
"referer": referer,
}
}
if self.output:
output | python | {
"resource": ""
} |
q270367 | Logs.expiration_date | test | def expiration_date(self, extracted):
"""
Logs the extracted expiration date.
:param extracted: The extracted expiration date (from WHOIS record).
:type extracted: str
"""
if PyFunceble.CONFIGURATION["logs"]:
# The logs subsystem is activated.
if PyFunceble.INTERN["referer"]:
referer = PyFunceble.INTERN["referer"]
else:
referer = None
to_write = {
self.current_time: {
"domain": PyFunceble.INTERN["to_test"],
"expiration_date": extracted,
"whois_server": referer,
}
}
if self.output:
output = self.output
else:
output = PyFunceble.OUTPUT_DIRECTORY
output += PyFunceble.OUTPUTS["parent_directory"]
| python | {
"resource": ""
} |
q270368 | Logs.referer_not_found | test | def referer_not_found(self, extension):
"""
Logs the case that the referer was not found.
:param extension: The extension of the domain we are testing.
:type extension: str
"""
if PyFunceble.CONFIGURATION["logs"]:
# The logs subsystem is activated.
to_write = {
self.current_time: {
"domain": PyFunceble.INTERN["to_test"],
"extension": extension,
}
}
if self.output:
| python | {
"resource": ""
} |
q270369 | Prints._before_header | test | def _before_header(self):
"""
Print informations about PyFunceble and the date of generation of a file
into a given path, if doesn't exist.
"""
if (
not PyFunceble.CONFIGURATION["no_files"]
and self.output
and not PyFunceble.path.isfile(self.output)
):
# * We are allowed to generate files.
# and
# * And output is given.
# and
# * The given output does not exist.
# We initiate the information about what generated the file.
link = "# File generated by %s\n" % PyFunceble.LINKS["repo"]
# We initiate the information about the generation date of this file.
date_of_generation = (
"# Date of generation: %s \n\n" % PyFunceble.CURRENT_TIME
)
# We initiate a variable which will save the list of
# templates which have to meet in order to write the before
# header informations.
authorized_templates = [
"Generic_File",
PyFunceble.STATUS["official"]["up"],
PyFunceble.STATUS["official"]["down"],
| python | {
"resource": ""
} |
q270370 | Prints._header_constructor | test | def _header_constructor(
cls, data_to_print, header_separator="-", column_separator=" "
):
"""
Construct header of the table according to template.
:param data_to_print:
The list of data to print into the header of the table.
:type data_to_print: list
:param header_separator:
The separator to use between the table header and our data.
:type header_separator: str
:param colomn_separator: The separator to use between each colomns.
:type colomn_separator: str
:return: The data to print in a list format.
:rtype: list
"""
# We initiate a variable which will save the header data.
header_data = []
# We initiate a variable which will save the header sizes.
header_size = ""
# We initiate the glue to set before the size.
before_size = "%-"
# We initiate the glue to set after the size.
after_size = "s"
if header_separator:
# The header separator is not empty.
# We initiate a variable which will save the list of
# separator data.
header_separator_data = []
# We get the length of the data to print.
length_data_to_print = len(data_to_print) - 1
# We initiate an iterator.
i = 0
for data in data_to_print:
# We loop through the list of data.
# We get the size of the currently read data.
size = data_to_print[data]
# We append the data to the header data list.
header_data.append(data)
# We construct the header size.
# Note: our header size is formatted line %s-sizes
# (the s at the end is part of the formatting.)
header_size += before_size + str(size) + after_size
if i < length_data_to_print:
# The iterator | python | {
"resource": ""
} |
q270371 | Prints.header | test | def header(
self, do_not_print=False
): # pragma: no cover pylint: disable=too-many-branches
"""
Management and creation of templates of header.
Please consider as "header" the title of each columns.
:param do_not_print:
Tell us if we have to print the header or not.
:type do_not_print: bool
"""
if (
not PyFunceble.CONFIGURATION["header_printed"]
or self.template == "Percentage"
or do_not_print
):
# * The header has not been already printed.
# or
# * The template is the `Percentage template`.
# or
# * We are authorized to print something.
if (
self.template.lower() in PyFunceble.STATUS["list"]["generic"]
or self.template == "Generic_File"
):
# * The template is into the list of generic status.
# or
# * The template is equal to `Generic_File`.
# The data to print is the Generic header.
to_print = self.headers["Generic"]
if (
self.template.lower() in PyFunceble.STATUS["list"]["generic"]
and PyFunceble.HTTP_CODE["active"]
):
# * The template is in the list of generic status.
# and
# * the http status code extraction is activated.
# We remove the Analyze Date colomn from the data to print.
to_print = Dict(to_print).remove_key("Analyze Date")
elif self.template.lower() in PyFunceble.STATUS["list"]["up"]:
# The template is in the list of up status.
# We informations to print is the up header.
to_print = self.headers[PyFunceble.STATUS["official"]["up"]]
elif self.template.lower() in PyFunceble.STATUS["list"]["valid"]:
# The template is in the list of valid status.
| python | {
"resource": ""
} |
q270372 | Prints._data_constructor | test | def _data_constructor(self, size):
"""
Construct the table of data according to given size.
:param size: The maximal length of each string in the table.
:type size: list
:return:
A dict with all information about the data and how to which what
maximal size to print it.
:rtype: OrderedDict
:raises:
:code:`Exception`
If the data and the size does not have the same length.
"""
# We initiate a variable which will save what we are going to
# return.
result = PyFunceble.OrderedDict()
if len(self.data_to_print) == len(size):
# The length of the data to print is equal to the length of the given size.
for i in range(len(self.data_to_print)):
# We loop until our iterator is less or equal to the length of the data
# to print.
| python | {
"resource": ""
} |
q270373 | Prints._size_from_header | test | def _size_from_header(cls, header):
"""
Get the size of each columns from the header.
:param header:
The header template we have to get the size from.
:type header: dict
:return: The maximal size of the each data to print.
:rtype: list
"""
# We initiate the result we are going to return.
result = []
for data in header:
| python | {
"resource": ""
} |
q270374 | Prints._colorify | test | def _colorify(self, data):
"""
Retun colored string.
:param data: The string to colorify.
:type data: str
:return: A colored string.
:rtype: str
"""
if self.template in ["Generic", "Less"]:
# The template is in the list of template that need the coloration.
if (
self.data_to_print[1].lower() in PyFunceble.STATUS["list"]["up"]
or self.data_to_print[1].lower() in PyFunceble.STATUS["list"]["valid"]
):
# The status is in the list of up status.
# We print the data with a green background.
data = PyFunceble.Fore.BLACK + PyFunceble.Back.GREEN + data
elif self.data_to_print[1].lower() in PyFunceble.STATUS["list"]["down"]:
# The status is in the list of down status.
| python | {
"resource": ""
} |
q270375 | Prints._json_print | test | def _json_print(self): # pragma: no cover
"""
Management of the json template.
"""
if self.output:
# The given output is not empty.
if PyFunceble.path.isfile(self.output):
# The given output already exist.
# We get the content of the output.
content = Dict().from_json(File(self.output).read())
if isinstance(content, list):
# The content is a list.
# We extend the content with our data to print.
content.extend(self.data_to_print)
# We format our list.
content = List(content).custom_format(Sort.standard)
if PyFunceble.CONFIGURATION["hierarchical_sorting"]:
# The hierarchical sorting is activated.
# We format our content hierarchicaly
content = List(content).custom_format(Sort.hierarchical)
# We finally save our content into the file.
Dict(content).to_json(self.output)
| python | {
"resource": ""
} |
q270376 | Prints.data | test | def data(self): # pragma: no cover pylint: disable=inconsistent-return-statements
"""
Management and input of data to the table.
:raises:
:code:`Exception`
When self.data_to_print is not a list.
"""
if isinstance(self.data_to_print, list):
# The data to print is a list.
# We initiate the data we are going to print.
to_print = {}
# We initiate the size we are going to print.
to_print_size = []
# We initiate a variable which will list the list of
# alone case.
alone_cases = ["Percentage", "HTTP"]
# we initiate a variable which will list the list of
# template which does not need a header.
without_header = ["FullHosts", "PlainDomain"]
if self.template.lower() == "json":
# The template is the json template.
if not PyFunceble.CONFIGURATION["no_files"] and self.output:
# * We are allowed to generate file.
# and
# * The given output is not empty.
# We print the json file.
return self._json_print()
# We return nothing.
return None
if self.template not in alone_cases and self.template not in without_header:
# * The template is not in the list of alone case.
# and
# * THe template is not in the list of template without header.
# We get the template we should use.
# Note: We basically only need the self.currently_used_header to be filled.
self.header(True)
# And we get the size from the header.
to_print_size = self._size_from_header(self.currently_used_header)
elif self.template in without_header:
# The template is in the list of template which does not need a header.
for data in self.data_to_print:
# We loop through the list of data to print.
# And we construct the (spacement) size of the data to print.
to_print_size.append(str(len(data)))
else:
| python | {
"resource": ""
} |
q270377 | ExecutionTime._save | test | def _save(self, last=False): # pragma: no cover
"""
Save the current time to the file.
:param last:
Tell us if we are at the very end of the file testing.
:type last: bool
"""
if (
self._authorization()
and PyFunceble.CONFIGURATION["logs"]
and "file_to_test" in PyFunceble.INTERN
and PyFunceble.INTERN["file_to_test"]
):
# * We are authorized to work.
# and
# * The generation of logs is activated.
# and
# * We are not testing as an imported module.
# We set the location of the file we are working with.
self.file = (
PyFunceble.OUTPUT_DIRECTORY
+ PyFunceble.OUTPUTS["parent_directory"]
+ PyFunceble.OUTPUTS["logs"]["directories"]["parent"]
+ PyFunceble.OUTPUTS["logs"]["filenames"]["execution_time"]
)
if PyFunceble.path.isfile(self.file):
# The file we are working with exist.
# We get its content so we can directly work with it.
content = Dict().from_json(File(self.file).read())
else:
# The file we are working with does not exist.
# We generate a dummy content.
content = {}
if self.action == "start":
# The action is equal to `start`.
if "final_total" in content and content["final_total"]:
# The final total index exist.
# We delete it.
del content["final_total"]
if "data" in content:
# The data index exist.
# We append the current start time inside it at
# a new sublist.
content["data"].append([PyFunceble.INTERN["start"]])
else:
# The data index does not exist.
# We create the index along with the current start time.
content["data"] = [[PyFunceble.INTERN["start"]]]
elif self.action == "stop":
# The action is equal to `stop`.
try:
# We try to work with the data index.
# We append the end time at the end of the last element
# of data.
#
# Note: It is at the end because we should have as first
# the star time.
content["data"][-1].append(PyFunceble.INTERN["end"])
# We get the start time.
start = content["data"][0][0]
# We get the end time.
end = content["data"][-1][-1]
# We calculate the execution time of the test.
| python | {
"resource": ""
} |
q270378 | ExecutionTime._calculate | test | def _calculate(cls, start=None, end=None):
"""
calculate the difference between starting and ending time.
:param start: A starting time.
:type start: int|str
:param stop: A ending time.
:type stop: int|str
:return:
A dict with following as index.
* :code:`days`
* :code:`hours`
* :code:`minutes`
* :code:`seconds`
as index.
:rtype: dict
"""
if start and end:
# The start and end time is explicitly given.
# We get the difference between the ending and the starting time.
time_difference = int(end) - int(start)
else:
# The start and end time is not explicitly given.
# We get the difference between the ending and the starting time.
time_difference = PyFunceble.INTERN["end"] - PyFunceble.INTERN["start"]
# We initiate an OrderedDict.
# Indeed, we use an ordered dict because we want the structuration and the
# order to stay always the same.
# As a dictionnary is always unordered, we can use it. Otherwise the time will
# not be shown correctly.
| python | {
"resource": ""
} |
q270379 | ExecutionTime.format_execution_time | test | def format_execution_time(self, start=None, end=None):
"""
Format the calculated time into a human readable format.
:param start: A starting time.
:type start: int|str
:param stop: A ending time.
:type stop: int|str
| python | {
"resource": ""
} |
q270380 | Clean.file_to_delete | test | def file_to_delete(cls):
"""
Return the list of file to delete.
"""
# We initiate the directory we have to look for.
directory = PyFunceble.OUTPUT_DIRECTORY + PyFunceble.OUTPUTS["parent_directory"]
if not directory.endswith(PyFunceble.directory_separator): # pragma: no cover
# For safety, if it does not ends with the directory separator, we append it
# to its end.
directory += PyFunceble.directory_separator
# We initiate a variable which will save the list of file to delete.
result = []
for root, _, files in PyFunceble.walk(directory):
# We walk in the directory and get all files and sub-directories.
for file in files:
# If there is files in the current sub-directory, we loop
# through the list of files.
if file not in [".gitignore", ".keep"]:
# The file is not into our list of file we do not have to delete.
if root.endswith(PyFunceble.directory_separator):
| python | {
"resource": ""
} |
q270381 | Clean.databases_to_delete | test | def databases_to_delete(cls): # pragma: no cover
"""
Set the databases files to delete.
"""
# We initiate the directory we have to look for.
directory = PyFunceble.CURRENT_DIRECTORY
# We initate the result variable.
result = []
# We append the dir_structure file.
result.append(
directory
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["dir_structure"]
)
# We append the iana file.
result.append(
directory + PyFunceble.CONFIGURATION["outputs"]["default_files"]["iana"]
)
# We append the public suffix file.
result.append(
directory
+ PyFunceble.CONFIGURATION["outputs"]["default_files"]["public_suffix"]
| python | {
"resource": ""
} |
q270382 | Clean.almost_everything | test | def almost_everything(self, clean_all=False):
"""
Delete almost all discovered files.
:param clean_all:
Tell the subsystem if we have to clean everything instesd
of almost everything.
:type clean_all: bool
"""
# We get the list of file | python | {
"resource": ""
} |
q270383 | Hash._hash_file | test | def _hash_file(self, algo):
"""Get the hash of the given file
:param algo: The algorithm to use.
:type algo: str
:return: The hexdigest of the data.
:rtype: str
"""
# We het the algorithm function.
hash_data = getattr(hashlib, algo)()
with open(self.path, "rb") as file:
# We open an read the parsed path.
# We read the content.
| python | {
"resource": ""
} |
q270384 | Hash._hash_data | test | def _hash_data(self, algo):
"""
Get hash of the given data.
:param algo: The algorithm to use.
:type algo: str
"""
# We het the algorithm function.
hash_data = getattr(hashlib, algo)()
# We set the data into our | python | {
"resource": ""
} |
q270385 | Hash.get | test | def get(self):
"""
Return the hash of the given file
"""
# We initiate a variable which will save the result we are going
# to return.
result = {}
if self.algorithm in self.valid_algorithms:
# * The parsed path exist.
# and
# * The parsed algorithm is in the list of valid algorithms.
if self.algorithm == "all":
# The parsed algorithm is `all`.
# We remove `all` (the first element of the list) from
# the list of valid algorithms because we are going to
# loop through the list of valid algorithms.
del self.valid_algorithms[0]
for algo in self.valid_algorithms:
# We loop through the list of valid algorithms.
if self.path and path.isfile(self.path):
# The file path exist.
# We save the hash into the result variable.
result[algo] = self._hash_file(algo)
elif self.data:
# * The path does not exist.
# and
# * The given data is not empty.
# We save the hash into the result variable.
result[algo] = self._hash_data(algo)
else: # pragma: no cover
# All other case are met.
# We return None.
return None
else:
# The parsed algorithm is a specific one.
if self.path and path.isfile(self.path):
| python | {
"resource": ""
} |
q270386 | Command.execute | test | def execute(self):
"""
Execute the given command.
:return: The output of the command.
:rtype: str
"""
# We initiate a process and parse the command to it.
process = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=True)
# We communicate the command and get the output and the error.
(output, error) = process.communicate()
if process.returncode != 0: # pragma: no cover
# The return code is different to 0.
# We | python | {
"resource": ""
} |
q270387 | Dict.remove_key | test | def remove_key(self, key_to_remove):
"""
Remove a given key from a given dictionary.
:param key_to_remove: The key(s) to delete.
:type key_to_remove: list|str
:return: The dict without the given key(s).
:rtype: dict|None
"""
if isinstance(self.main_dictionnary, dict):
# The main dictionnary is a dictionnary
if isinstance(key_to_remove, list):
# The parsed key to remove is a list.
for key in key_to_remove:
# We loop through the list of key to remove.
# We delete the key from the dictionnary.
del self.main_dictionnary[key]
else:
# The parsed key to remove is not a list.
| python | {
"resource": ""
} |
q270388 | Dict.rename_key | test | def rename_key(self, key_to_rename, strict=True):
"""
Rename the given keys from the given dictionary.
:param key_to_rename:
The key(s) to rename.
Expected format: :code:`{old:new}`
:type key_to_rename: dict
:param strict:
Tell us if we have to rename the exact index or
the index which looks like the given key(s)
:return: The well formatted dict.
:rtype: dict|None
"""
if isinstance(self.main_dictionnary, dict) and isinstance(key_to_rename, dict):
# * The given main directory is a dictionnary.
# and
# * The given key to rename is a dictionnary.
for old, new in key_to_rename.items():
# We loop through the key to raname.
if strict:
# The strict method is activated.
if old in self.main_dictionnary:
# The old key is in the main dictionnary.
# We initiate the new with the old and remove the old content.
self.main_dictionnary[new] = self.main_dictionnary.pop(old)
else:
# The strict method is not activated.
# We initiate the elements to rename.
to_rename = {}
for index in self.main_dictionnary:
# We loop throught the indexes of the main dictionnary.
if old in index:
| python | {
"resource": ""
} |
q270389 | Dict.merge | test | def merge(self, to_merge, strict=True):
"""
Merge the content of to_merge into the given main dictionnary.
:param to_merge: The dictionnary to merge.
:type to_merge: dict
:param strict:
Tell us if we have to strictly merge lists.
:code:`True`: We follow index
:code`False`: We follow element (content)
:type strict: bool
:return: The merged dict.
:rtype: dict
"""
# We initiate a variable which will save our result.
result = {}
for element in to_merge:
# We loop throught the given dict to merge.
if element in self.main_dictionnary:
# The currently read element is in the main dict.
if isinstance(to_merge[element], dict) and isinstance(
self.main_dictionnary[element], dict
):
# They are in both side dict.
# We merge the dict tree and save into result.
result[element] = Dict(self.main_dictionnary[element]).merge(
to_merge[element]
)
elif isinstance(to_merge[element], list) and isinstance(
self.main_dictionnary[element], list
):
# They are in both side list.
# We merge the lists and save into result.
result[element] = List(self.main_dictionnary[element]).merge(
to_merge[element], strict
)
else:
| python | {
"resource": ""
} |
q270390 | Dict.to_json | test | def to_json(self, destination):
"""
Save a dictionnary into a JSON file.
:param destination:
A path to a file where we're going to
write the converted dict into a JSON format.
:type destination: str
"""
try:
with open(destination, "w") as file:
# We open the file we are going to write.
# Note: We always overwrite the destination.
# We save the current dictionnary into a json format.
dump(
self.main_dictionnary,
file,
ensure_ascii=False,
indent=4,
sort_keys=True,
)
| python | {
"resource": ""
} |
q270391 | Dict.to_yaml | test | def to_yaml(self, destination, flow_style=False):
"""
Save a dictionnary into a YAML file.
:param destination:
A path to a file where we're going to write the
converted dict into a JSON format.
:type destination: str
"""
with open(destination, "w") as file:
# We open the file we are going to write.
# Note: We always overwrite the destination.
# We save the current dictionnary into a json format.
| python | {
"resource": ""
} |
q270392 | Directory.fix_path | test | def fix_path(self, splited_path=None):
"""
Fix the path of the given path.
:param splited_path: A list to convert to the right path.
:type splited_path: list
:return: The fixed path.
:rtype: str
"""
if not splited_path:
# A splited path is parsed.
# We initate a variable which will save the splited path.
split_path = []
if self.directory:
# The parsed directory is not empty or equal to None.
if "/" in self.directory:
# We split the separator.
split_path = self.directory.split("/")
elif "\\" in self.directory:
# We split the separator.
split_path = self.directory.split("\\")
| python | {
"resource": ""
} |
q270393 | File.write | test | def write(self, data_to_write, overwrite=False):
"""
Write or append data into the given file path.
:param data_to_write: The data to write.
:type data_to_write: str
:param overwrite:
Tell us if we have to overwrite the
content of the file we are working with.
:type overwrite: bool
"""
if overwrite or not path.isfile(self.file):
# * We have to overwrite the file data.
# or
# * The file path does not already exist.
with open(self.file, "w", encoding="utf-8", newline="\n") as file:
# We prepare the file for writting.
if data_to_write and isinstance(data_to_write, str):
# * A data to write is given.
# and
# * The data to write is a string
# We | python | {
"resource": ""
} |
q270394 | File.read | test | def read(self):
"""
Read a given file path and return its content.
:return: The content of the given file path.
:rtype: str
"""
try:
with open(self.file, "r", encoding="utf-8") as file:
# We open and read a file.
# We get the file content.
funilrys = file.read()
except UnicodeDecodeError: # pragma: no cover
| python | {
"resource": ""
} |
q270395 | List.format | test | def format(self):
"""
Return a well formatted list. Basicaly, it's sort a list and remove duplicate.
:return: A sorted, without duplicate, list.
:rtype: list
"""
try:
| python | {
"resource": ""
} |
q270396 | List.merge | test | def merge(self, to_merge, strict=True):
"""
Merge to_merge into the given main list.
:param to_merge: The list to merge.
:type to_merge: list
:param strict:
Tell us if we have to respect index (True)
or not (False).
:type strict: bool
:return: The merged list.
:rtype: list
"""
# We initiate a variable which will save the
# result
result = []
if strict:
# We are in strict mode.
for index, element in enumerate(to_merge):
# We loop through each element of the list to merge
# to the main dict.
try:
if isinstance(element, dict) and isinstance(
self.main_list[index], dict
):
# The currently read element is a dict.
# We merge its content into the main dict
# and append into the result.
result.append(Dict(self.main_list[index]).merge(element))
elif isinstance(element, list) and isinstance(
self.main_list[index], list
):
# The currently read element is a list.
# We loop through this method.
result.append(List(self.main_list[index]).merge(element))
else:
# The currently read element is not a list
# nor a dict.
| python | {
"resource": ""
} |
q270397 | Regex.not_matching_list | test | def not_matching_list(self):
"""
Return a list of string which don't match the
given regex.
""" | python | {
"resource": ""
} |
q270398 | Regex.match | test | def match(self):
"""
Used to get exploitable result of re.search
:return: The data of the match status.
:rtype: mixed
"""
# We initate this variable which gonna contain the returned data
result = []
# We compile the regex string
to_match = comp(self.regex)
# In case we have to use the implementation of ${BASH_REMATCH} we use
# re.findall otherwise, we use re.search
if self.rematch: # pylint: disable=no-member
pre_result = to_match.findall(self.data)
else:
pre_result = to_match.search(self.data)
if self.return_data and pre_result: # pylint: disable=no-member
if self.rematch: # pylint: disable=no-member
for data in pre_result:
if isinstance(data, tuple):
result.extend(list(data))
| python | {
"resource": ""
} |
q270399 | Regex.replace | test | def replace(self):
"""
Used to replace a matched string with another.
:return: The data after replacement.
:rtype: str
"""
if self.replace_with: # pylint: disable=no-member
return substrings(
self.regex,
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.