File: testing.py

package info (click to toggle)
python-pyfunceble 4.2.29.dev-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 4,108 kB
  • sloc: python: 27,413; sh: 142; makefile: 27
file content (288 lines) | stat: -rw-r--r-- 10,184 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""
The tool to check the availability or syntax of domain, IP or URL.

::


    ██████╗ ██╗   ██╗███████╗██╗   ██╗███╗   ██╗ ██████╗███████╗██████╗ ██╗     ███████╗
    ██╔══██╗╚██╗ ██╔╝██╔════╝██║   ██║████╗  ██║██╔════╝██╔════╝██╔══██╗██║     ██╔════╝
    ██████╔╝ ╚████╔╝ █████╗  ██║   ██║██╔██╗ ██║██║     █████╗  ██████╔╝██║     █████╗
    ██╔═══╝   ╚██╔╝  ██╔══╝  ██║   ██║██║╚██╗██║██║     ██╔══╝  ██╔══██╗██║     ██╔══╝
    ██║        ██║   ██║     ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
    ╚═╝        ╚═╝   ╚═╝      ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝

Provides some testing related utilities

Author:
    Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom

Special thanks:
    https://pyfunceble.github.io/#/special-thanks

Contributors:
    https://pyfunceble.github.io/#/contributors

Project link:
    https://github.com/funilrys/PyFunceble

Project documentation:
    https://docs.pyfunceble.com

Project homepage:
    https://pyfunceble.github.io/

License:
::


    Copyright 2017, 2018, 2019, 2020, 2022, 2023, 2024 Nissar Chababy

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

import os
from typing import List, Optional, Union

from sqlalchemy.orm import Session

import PyFunceble.storage
from PyFunceble.converter.adblock_input_line2subject import AdblockInputLine2Subject
from PyFunceble.converter.cidr2subject import CIDR2Subject
from PyFunceble.converter.input_line2subject import InputLine2Subject
from PyFunceble.converter.rpz_input_line2subject import RPZInputLine2Subject
from PyFunceble.converter.rpz_policy2subject import RPZPolicy2Subject
from PyFunceble.converter.subject2complements import Subject2Complements
from PyFunceble.converter.url2netloc import Url2Netloc
from PyFunceble.converter.wildcard2subject import Wildcard2Subject
from PyFunceble.dataset.autocontinue.csv import CSVContinueDataset
from PyFunceble.dataset.autocontinue.sql import SQLDBContinueDataset
from PyFunceble.dataset.base import DatasetBase
from PyFunceble.dataset.csv_base import CSVDatasetBase
from PyFunceble.dataset.db_base import DBDatasetBase
from PyFunceble.dataset.inactive.csv import CSVInactiveDataset
from PyFunceble.dataset.inactive.sql import SQLDBInactiveDataset
from PyFunceble.helpers.list import ListHelper
from PyFunceble.helpers.regex import RegexHelper


def get_testing_mode() -> str:
    """
    Tries to provides the testing mode to apply to the CLI.
    """

    if PyFunceble.storage.CONFIGURATION.cli_testing.testing_mode.syntax:
        return "SYNTAX"
    if PyFunceble.storage.CONFIGURATION.cli_testing.testing_mode.reputation:
        return "REPUTATION"

    if PyFunceble.storage.CONFIGURATION.cli_testing.testing_mode.availability:
        return "AVAILABILITY"
    return "UNKNOWN"


def get_continue_databaset_object(
    db_session: Optional[Session] = None,
) -> Union[DatasetBase, CSVDatasetBase, DBDatasetBase]:
    """
    Provides the continue object to work with.

    :param db_session:
        A database session to use.

    :raise ValueError:
        When the given database type is unkown.
    """

    result = None

    if PyFunceble.storage.CONFIGURATION.cli_testing.db_type in "csv":
        result = CSVContinueDataset()
    elif PyFunceble.storage.CONFIGURATION.cli_testing.db_type in (
        "mariadb",
        "mysql",
        "postgresql",
    ):
        result = SQLDBContinueDataset(db_session=db_session)

    if result:
        result.set_authorized(
            bool(PyFunceble.storage.CONFIGURATION.cli_testing.autocontinue)
        )

        return result

    raise ValueError(
        "<config.db_type> "
        f"({PyFunceble.storage.CONFIGURATION.cli_testing.db_type}) is unknown."
    )


def get_inactive_dataset_object(
    db_session: Optional[Session] = None,
) -> Union[DatasetBase, CSVDatasetBase, DBDatasetBase]:
    """
    Provides the inactive object to work with.

    :param db_session:
        A database session to use.

    :raise ValueError:
        When the given database type is unkown.
    """

    result = None

    if PyFunceble.storage.CONFIGURATION.cli_testing.db_type == "csv":
        result = CSVInactiveDataset()
    elif PyFunceble.storage.CONFIGURATION.cli_testing.db_type in (
        "mariadb",
        "mysql",
        "postgresql",
    ):
        result = SQLDBInactiveDataset(db_session=db_session)

    if result:
        result.set_authorized(
            bool(PyFunceble.storage.CONFIGURATION.cli_testing.inactive_db)
        )

        return result

    raise ValueError(
        "<config.db_type> "
        f"({PyFunceble.storage.CONFIGURATION.cli_testing.db_type}) is unknown."
    )


def get_destination_from_origin(origin: str) -> str:
    """
    Given the origin, we provides the destination.
    """

    if "/" in origin:
        origin = origin.rsplit("/", 1)[-1]

    if os.sep in origin:
        origin = origin.rsplit(os.sep, 1)[-1]

    return RegexHelper("[^a-zA-Z0-9._-]").replace_match(origin, "_")


def get_subjects_from_line(
    line: str,
    checker_type: str,
    *,
    subject_type: str = "domain",
    adblock_inputline2subject: Optional[AdblockInputLine2Subject] = None,
    wildcard2subject: Optional[Wildcard2Subject] = None,
    rpz_policy2subject: Optional[RPZPolicy2Subject] = None,
    rpz_inputline2subject: Optional[RPZInputLine2Subject] = None,
    inputline2subject: Optional[InputLine2Subject] = None,
    subject2complements: Optional[Subject2Complements] = None,
    url2netloc: Optional[Url2Netloc] = None,
    cidr2subject: Optional[CIDR2Subject] = None,
) -> List[str]:
    """
    Provides the list of subject to test.
    """

    result = []

    if adblock_inputline2subject is None:
        adblock_inputline2subject = AdblockInputLine2Subject(
            aggressive=bool(PyFunceble.storage.CONFIGURATION.cli_decoding.aggressive)
        )

    if wildcard2subject is None:
        wildcard2subject = Wildcard2Subject(
            aggressive=bool(PyFunceble.storage.CONFIGURATION.cli_decoding.aggressive)
        )

    if rpz_policy2subject is None:
        rpz_policy2subject = RPZPolicy2Subject()

    if rpz_inputline2subject is None:
        rpz_inputline2subject = RPZInputLine2Subject(
            aggressive=bool(PyFunceble.storage.CONFIGURATION.cli_decoding.aggressive)
        )

    if inputline2subject is None:
        inputline2subject = InputLine2Subject(
            aggressive=bool(PyFunceble.storage.CONFIGURATION.cli_decoding.aggressive)
        )

    if subject2complements is None:
        subject2complements = Subject2Complements()

    if url2netloc is None:
        url2netloc = Url2Netloc(
            aggressive=bool(PyFunceble.storage.CONFIGURATION.cli_decoding.aggressive)
        )

    if cidr2subject is None:
        cidr2subject = CIDR2Subject()

    adblock_inputline2subject.aggressive = wildcard2subject.aggressive = (
        rpz_inputline2subject.aggressive
    ) = inputline2subject.aggressive = url2netloc.aggressive = bool(
        PyFunceble.storage.CONFIGURATION.cli_decoding.aggressive
    )

    if inputline2subject.aggressive and subject_type == "url":
        # URL Decoder doesn't have an aggressive mode.
        # Therefore, we fix the "misconfiguration"
        inputline2subject.aggressive = not inputline2subject.aggressive

    if PyFunceble.storage.CONFIGURATION.cli_decoding.adblock:
        result.extend(
            # pylint: disable=line-too-long
            adblock_inputline2subject.set_data_to_convert(line).get_converted()
        )
    elif PyFunceble.storage.CONFIGURATION.cli_decoding.wildcard:
        result.append(wildcard2subject.set_data_to_convert(line).get_converted())
    elif PyFunceble.storage.CONFIGURATION.cli_decoding.rpz:
        result.extend(
            [
                rpz_policy2subject.set_data_to_convert(x).get_converted()
                for x in rpz_inputline2subject.set_data_to_convert(line).get_converted()
            ]
        )
    else:
        result.extend(inputline2subject.set_data_to_convert(line).get_converted())

    if PyFunceble.storage.CONFIGURATION.cli_testing.complements:
        result.extend(
            [
                y
                for x in result
                for y in subject2complements.set_data_to_convert(x).get_converted()
            ]
        )

    if PyFunceble.storage.CONFIGURATION.cli_testing.cidr_expand:
        result = [
            y
            for x in result
            for y in cidr2subject.set_data_to_convert(x).get_converted()
        ]

    if checker_type.lower() != "syntax":
        for index, subject in enumerate(result):
            if not subject:
                continue

            netloc = url2netloc.set_data_to_convert(subject).get_converted()

            result[index] = subject.replace(netloc, netloc.lower())

    return ListHelper(result).remove_duplicates().remove_empty().subject