From 8d03b993a0c4ec4bff88b533987df2b482d7c4a9 Mon Sep 17 00:00:00 2001 From: drew2a Date: Wed, 15 Mar 2023 08:37:04 +0100 Subject: [PATCH 1/2] Apply autoformat + optimise imports --- .github/ISSUE_TEMPLATE/bug_report.md | 6 +- .github/workflows/docker-image.yml | 40 ++-- .pylintrc | 184 +++++++++--------- .readthedocs.yml | 8 +- build/mac/licenseDMG.py | 3 +- doc/conf.py | 1 - doc/development/qt.rst | 3 +- doc/index.rst | 6 +- .../run_bandwidth_crawler.py | 2 +- scripts/exit_node/run_exit_node.py | 4 +- .../tunnel_community/hidden_peer_discovery.py | 1 - scripts/seedbox/README.md | 5 +- src/README.md | 5 +- src/run_tribler.py | 7 +- .../bandwidth_accounting/db/transaction.py | 6 +- .../restapi/bandwidth_endpoint.py | 3 - .../test_bandwidth_accounting_component.py | 5 +- .../tests/test_bandwidth_endpoint.py | 3 +- .../tests/test_database.py | 4 +- .../trust_calculation/graph_positioning.py | 6 +- .../test_graph_positioning.py | 1 - .../trust_calculation/trust_graph.py | 2 +- .../community/gigachannel_community.py | 32 ++- .../gigachannel/community/request.py | 2 - .../gigachannel/community/sync_strategy.py | 1 - .../tests/test_gigachannel_community.py | 2 +- .../gigachannel/gigachannel_component.py | 2 +- .../gui_process_watcher.py | 2 - .../core/components/ipv8/ipv8_component.py | 1 - .../components/ipv8/ipv8_health_monitor.py | 3 +- .../components/ipv8/protocol_decorator.py | 2 + src/tribler/core/components/ipv8/settings.py | 1 + .../ipv8/tests/test_discovery_booster.py | 2 +- .../ipv8/tests/test_ipv8_component.py | 4 +- .../ipv8/tests/test_ipv8_health_manager.py | 4 +- .../core/components/key/key_component.py | 1 + src/tribler/core/components/key/settings.py | 1 + .../download_manager/dht_health_manager.py | 1 - .../download_manager/download_manager.py | 3 +- .../restapi/create_torrent_endpoint.py | 3 - .../libtorrent/restapi/libtorrent_endpoint.py | 3 - .../restapi/tests/test_libtorrent_endpoint.py | 3 +- .../libtorrent/tests/test_download_api.py | 2 - .../tests/test_libtorrent_component.py | 4 +- .../libtorrent/tests/test_seeding.py | 1 - .../libtorrent/tests/test_torrent_def.py | 4 +- .../core/components/libtorrent/torrentdef.py | 6 +- .../libtorrent/utils/torrent_utils.py | 6 + .../category_filter/family_filter.py | 2 +- .../db/orm_bindings/binary_node.py | 4 +- .../db/orm_bindings/channel_metadata.py | 15 +- .../db/orm_bindings/channel_node.py | 1 - .../db/orm_bindings/collection_node.py | 19 +- .../db/orm_bindings/json_node.py | 4 +- .../db/orm_bindings/metadata_node.py | 4 +- .../db/orm_bindings/torrent_state.py | 1 + .../metadata_store/db/serialization.py | 140 ++++++------- .../db/tests/test_tracker_state.py | 3 +- .../metadata_store_component.py | 2 +- .../remote_query_community/payload_checker.py | 15 +- .../restapi/channels_endpoint.py | 7 +- .../restapi/remote_query_endpoint.py | 6 +- .../metadata_store/restapi/search_endpoint.py | 1 - .../metadata_store/restapi/tests/conftest.py | 4 +- .../restapi/tests/test_channels_endpoint.py | 5 +- .../tests/test_remote_query_endpoint.py | 9 +- .../metadata_store/tests/gen_test_data.py | 2 - .../tests/test_channel_download.py | 2 +- .../metadata_store/tests/test_metadata.py | 6 +- .../tests/test_metadata_store_component.py | 7 +- .../core/components/metadata_store/utils.py | 4 +- .../components/payout/payout_component.py | 1 - .../payout/tests/test_payout_component.py | 3 +- .../payout/tests/test_payout_manager.py | 6 +- .../popularity/community/payload.py | 3 +- .../community/popularity_community.py | 1 - .../tests/test_popularity_community.py | 2 +- .../tests/test_version_community_mixin.py | 3 +- .../community/version_community_mixin.py | 1 + .../popularity/popularity_component.py | 2 +- .../tests/test_popularity_component.py | 2 +- .../reporter/tests/test_exception_handler.py | 1 + .../restapi/tests/test_restapi_component.py | 1 + .../socks_servers/socks5/conversion.py | 1 - .../components/socks_servers/socks5/server.py | 2 + .../socks5/tests/test_conversion.py | 3 +- .../socks_servers/socks5/tests/test_server.py | 4 +- .../tests/test_torrent_checker_component.py | 6 +- .../torrent_checker/dataclasses.py | 1 - .../tests/test_health_info_should_update.py | 8 +- .../tests/test_torrentchecker.py | 4 +- .../tests/test_torrentchecker_session.py | 1 - .../torrent_checker/torrent_checker.py | 8 +- .../torrent_checker/torrent_checker/utils.py | 3 +- .../tunnel/tests/test_dispatcher.py | 3 +- .../tunnel/tests/test_tunnel_component.py | 4 +- .../core/components/watch_folder/settings.py | 1 + .../tests/test_tribler_config_section.py | 2 - .../core/config/tribler_config_section.py | 1 + src/tribler/core/logger/logger.py | 1 + src/tribler/core/logger/logger.yaml | 90 ++++----- src/tribler/core/setup.py | 1 + src/tribler/core/start_core.py | 2 +- src/tribler/core/tests/test_configparser.py | 1 - src/tribler/core/tests/test_search_utils.py | 5 +- .../core/tests/tools/tracker/http_tracker.py | 2 - src/tribler/core/upgrade/db8_to_db10.py | 4 +- src/tribler/core/utilities/bencodecheck.py | 2 - src/tribler/core/utilities/dependencies.py | 1 - src/tribler/core/utilities/instrumentation.py | 1 - .../core/utilities/limited_ordered_dict.py | 1 + src/tribler/core/utilities/maketorrent.py | 1 - src/tribler/core/utilities/notifier.py | 4 +- src/tribler/core/utilities/osutils.py | 14 +- src/tribler/core/utilities/patch_import.py | 1 - .../utilities/process_manager/__init__.py | 4 +- .../core/utilities/process_manager/manager.py | 4 +- .../core/utilities/process_manager/process.py | 2 +- .../process_manager/tests/test_manager.py | 2 +- .../core/utilities/process_manager/utils.py | 1 + src/tribler/core/utilities/sentinels.py | 4 +- .../core/utilities/tests/test_dependencies.py | 1 + .../utilities/tests/test_network_utils.py | 1 + .../core/utilities/tests/test_notifier.py | 9 +- .../utilities/tests/test_torrent_utils.py | 2 - .../core/utilities/tests/test_utilities.py | 27 +-- src/tribler/gui/code_executor.py | 1 + src/tribler/gui/core_manager.py | 1 - .../gui/dialogs/startdownloaddialog.py | 2 +- src/tribler/gui/event_request_manager.py | 2 +- src/tribler/gui/i18n/README.md | 31 ++- src/tribler/gui/resource_monitor.py | 1 + src/tribler/gui/start_gui.py | 3 +- src/tribler/gui/tests/conftest.py | 2 +- src/tribler/gui/tests/test_gui.py | 1 + src/tribler/gui/tribler_app.py | 1 - .../gui/widgets/channelsmenulistwidget.py | 2 - src/tribler/gui/widgets/clickablewidgets.py | 1 - src/tribler/gui/widgets/downloadspage.py | 3 +- .../gui/widgets/graphs/timeseriesplot.py | 1 + src/tribler/gui/widgets/lazytableview.py | 11 +- src/tribler/gui/widgets/qtbug.py | 1 + .../gui/widgets/subscriptionswidget.py | 4 +- .../gui/widgets/tablecontentdelegate.py | 4 +- src/tribler/gui/widgets/tagbutton.py | 7 +- src/tribler/gui/widgets/tagslineedit.py | 18 +- src/tribler/gui/widgets/timeoutprogressbar.py | 1 - .../gui/widgets/triblertablecontrollers.py | 3 +- tribler.spec | 59 +++--- 149 files changed, 529 insertions(+), 561 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index d56bb7a815e..43e5f4ff0e6 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -12,6 +12,7 @@ A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: + 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' @@ -24,8 +25,9 @@ A clear and concise description of what you expected to happen. If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - - OS: [e.g. Windows 11] - - Tribler's version [e.g. 7.10.0] + +- OS: [e.g. Windows 11] +- Tribler's version [e.g. 7.10.0] **Additional context** Add any other context about the problem here. diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 998f2faaff2..0f02a4a6795 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -3,31 +3,31 @@ name: Docker Image CI on: workflow_call: secrets: - DOCKER_USER: - required: true - DOCKER_PASSWORD: - required: true + DOCKER_USER: + required: true + DOCKER_PASSWORD: + required: true jobs: build: runs-on: ubuntu-latest steps: - - name: Checkout repository and submodules - uses: actions/checkout@v2 + - name: Checkout repository and submodules + uses: actions/checkout@v2 - - name: Docker login - env: - DOCKER_USER: ${{secrets.DOCKER_USER}} - DOCKER_PASSWORD: ${{secrets.DOCKER_PASSWORD}} - run: | - docker login -u $DOCKER_USER -p $DOCKER_PASSWORD + - name: Docker login + env: + DOCKER_USER: ${{secrets.DOCKER_USER}} + DOCKER_PASSWORD: ${{secrets.DOCKER_PASSWORD}} + run: | + docker login -u $DOCKER_USER -p $DOCKER_PASSWORD - - name: Build the Docker image - run: | - docker build . --file Dockerfile --tag triblercore/triblercore:latest + - name: Build the Docker image + run: | + docker build . --file Dockerfile --tag triblercore/triblercore:latest - - name: Push to Docker Hub - env: - DOCKER_USER: ${{secrets.DOCKER_USER}} - run: | - docker push $DOCKER_USER/triblercore:latest + - name: Push to Docker Hub + env: + DOCKER_USER: ${{secrets.DOCKER_USER}} + run: | + docker push $DOCKER_USER/triblercore:latest diff --git a/.pylintrc b/.pylintrc index 59fbd266d6a..32d60d095d5 100644 --- a/.pylintrc +++ b/.pylintrc @@ -5,14 +5,14 @@ # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). -init-hook='import sys; import os;' +init-hook = 'import sys; import os;' # Add files or directories to the blacklist. They should be base names, not # paths. -ignore=.git,libnacl,data,.pylint.rc +ignore = .git,libnacl,data,.pylint.rc # Pickle collected data for later comparisons. -persistent=yes +persistent = yes # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. @@ -23,16 +23,16 @@ persistent=yes # Use multiple processes to speed up Pylint. -jobs=8 +jobs = 8 # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no +unsafe-load-any-extension = no # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code -extension-pkg-whitelist=PyQt5 +extension-pkg-whitelist = PyQt5 # Allow optimization of some AST trees. This will activate a peephole AST # optimizer, which will apply various small optimizations. For instance, it can @@ -40,14 +40,14 @@ extension-pkg-whitelist=PyQt5 # operator. Joining a lot of strings can lead to a maximum recursion error in # Pylint and this flag can prevent that. It has one side effect, the resulting # AST will be different than the one from reality. -optimize-ast=yes +optimize-ast = yes [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= +confidence = # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option @@ -64,11 +64,11 @@ confidence= # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" #disable=import-star-module-level,old-octal-literal,oct-method,print-statement,unpacking-in-except,parameter-unpacking,backtick,old-raise-syntax,old-ne-operator,long-suffix,dict-view-method,dict-iter-method,metaclass-assignment,next-method-called,raising-string,indexing-exception,raw_input-builtin,long-builtin,file-builtin,execfile-builtin,coerce-builtin,cmp-builtin,buffer-builtin,basestring-builtin,apply-builtin,filter-builtin-not-iterating,using-cmp-argument,useless-suppression,range-builtin-not-iterating,suppressed-message,no-absolute-import,old-division,cmp-method,reload-builtin,zip-builtin-not-iterating,intern-builtin,unichr-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,input-builtin,round-builtin,hex-method,nonzero-method,map-builtin-not-iterating -disable=C0321,W0142,invalid-name,missing-docstring,no-member,no-name-in-module, - no-self-use,too-few-public-methods,C0330,W1203,too-many-ancestors, - too-many-arguments,too-many-public-methods,too-many-statements, - too-many-instance-attributes,too-many-locals,too-many-branches, - too-many-return-statements, E5110 +disable = C0321,W0142,invalid-name,missing-docstring,no-member,no-name-in-module, + no-self-use,too-few-public-methods,C0330,W1203,too-many-ancestors, + too-many-arguments,too-many-public-methods,too-many-statements, + too-many-instance-attributes,too-many-locals,too-many-branches, + too-many-return-statements, E5110 #missing-type-doc @@ -78,71 +78,71 @@ disable=C0321,W0142,invalid-name,missing-docstring,no-member,no-name-in-module, # Set the output format. Available formats are text, parseable, colorized, msvs # (visual studio) and html. You can also give a reporter class, eg # mypackage.mymodule.MyReporterClass. -output-format=text +output-format = text # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". -files-output=no +files-output = no # Tells whether to display a full report or only the messages -reports=no +reports = no # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) +evaluation = 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details -msg-template="{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}" +msg-template = "{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}" [VARIABLES] # Tells whether we should check for unused import in __init__ files. -init-import=no +init-import = no # A regular expression matching the name of dummy variables (i.e. expectedly # not used). -dummy-variables-rgx=_$|dummy +dummy-variables-rgx = _$|dummy # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. -additional-builtins= +additional-builtins = # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. -callbacks=cb_,_cb,on_ +callbacks = cb_,_cb,on_ # List of qualified module names which can have objects that can redefine # builtins. -redefining-builtins-modules=six.moves +redefining-builtins-modules = six.moves [TYPECHECK] # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes +ignore-mixin-members = yes # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis. It # supports qualified module names, as well as Unix pattern matching. -ignored-modules= +ignored-modules = # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). This supports can work # with qualified names. -ignored-classes=ephem,libtorrent +ignored-classes = ephem,libtorrent # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. -generated-members= +generated-members = [SPELLING] @@ -155,241 +155,241 @@ generated-members= # sudo apt install aspell-en # List of comma separated words that should not be checked. -spelling-ignore-words=Tribler,tribler +spelling-ignore-words = Tribler,tribler # A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= +spelling-private-dict-file = # Tells whether to store unknown words to indicated private dictionary in # --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no +spelling-store-unknown-words = no [SIMILARITIES] # Minimum lines number of a similarity. -min-similarity-lines=4 +min-similarity-lines = 4 # Ignore comments when computing similarities. -ignore-comments=yes +ignore-comments = yes # Ignore docstrings when computing similarities. -ignore-docstrings=yes +ignore-docstrings = yes # Ignore imports when computing similarities. -ignore-imports=no +ignore-imports = no [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. -notes=FIXME,XXX,TODO +notes = FIXME,XXX,TODO [LOGGING] # Logging modules to check that the string format arguments are in logging # function parameter format -logging-modules=logging +logging-modules = logging [FORMAT] # Maximum number of characters on a single line. -max-line-length=120 +max-line-length = 120 # Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ +ignore-long-lines = ^\s*(# )??$ # Allow the body of an if to be on the same line as the test if there is no # else. -single-line-if-stmt=no +single-line-if-stmt = no # List of optional constructs for which whitespace checking is disabled. `dict- # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. # `trailing-comma` allows a space between comma and closing bracket: (a, ). # `empty-line` allows space-only lines. -no-space-check=trailing-comma,dict-separator +no-space-check = trailing-comma,dict-separator # Maximum number of lines in a module -max-module-lines=2000 +max-module-lines = 2000 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). -indent-string=' ' +indent-string = ' ' # Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 +indent-after-paren = 4 # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -expected-line-ending-format=LF +expected-line-ending-format = LF [BASIC] # List of builtins function names that should not be used, separated by a comma -bad-functions=map,filter,input +bad-functions = map,filter,input # Good variable names which should always be accepted, separated by a comma -good-names=i,j,k,ex,Run,_,d +good-names = i,j,k,ex,Run,_,d # Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata +bad-names = foo,bar,baz,toto,tutu,tata # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. -name-group= +name-group = # Include a hint for the correct naming format with invalid-name -include-naming-hint=yes +include-naming-hint = yes # Regular expression matching correct function names -function-rgx=[a-z_][a-z0-9_]{2,30}$ +function-rgx = [a-z_][a-z0-9_]{2,30}$ # Naming hint for function names -function-name-hint=[a-z_][a-z0-9_]{2,30}$ +function-name-hint = [a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct variable names -variable-rgx=[a-z_][a-z0-9_]{2,30}$ +variable-rgx = [a-z_][a-z0-9_]{2,30}$ # Naming hint for variable names -variable-name-hint=[a-z_][a-z0-9_]{2,30}$ +variable-name-hint = [a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ +const-rgx = (([A-Z_][A-Z0-9_]*)|(__.*__))$ # Naming hint for constant names -const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ +const-name-hint = (([A-Z_][A-Z0-9_]*)|(__.*__))$ # Regular expression matching correct attribute names -attr-rgx=[a-z_][a-z0-9_]{2,30}$ +attr-rgx = [a-z_][a-z0-9_]{2,30}$ # Naming hint for attribute names -attr-name-hint=[a-z_][a-z0-9_]{2,30}$ +attr-name-hint = [a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct argument names -argument-rgx=[a-z_][a-z0-9_]{2,30}$ +argument-rgx = [a-z_][a-z0-9_]{2,30}$ # Naming hint for argument names -argument-name-hint=[a-z_][a-z0-9_]{2,30}$ +argument-name-hint = [a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ +class-attribute-rgx = ([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ # Naming hint for class attribute names -class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ +class-attribute-name-hint = ([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ # Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ +inlinevar-rgx = [A-Za-z_][A-Za-z0-9_]*$ # Naming hint for inline iteration names -inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ +inlinevar-name-hint = [A-Za-z_][A-Za-z0-9_]*$ # Regular expression matching correct class names -class-rgx=[A-Z_][a-zA-Z0-9]+$ +class-rgx = [A-Z_][a-zA-Z0-9]+$ # Naming hint for class names -class-name-hint=[A-Z_][a-zA-Z0-9]+$ +class-name-hint = [A-Z_][a-zA-Z0-9]+$ # Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ +module-rgx = (([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Naming hint for module names -module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ +module-name-hint = (([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression matching correct method names -method-rgx=[a-z_][a-z0-9_]{2,30}$ +method-rgx = [a-z_][a-z0-9_]{2,30}$ # Naming hint for method names -method-name-hint=[a-z_][a-z0-9_]{2,30}$ +method-name-hint = [a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match function or class names that do # not require a docstring. -no-docstring-rgx=^_ +no-docstring-rgx = ^_ # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. -docstring-min-length=5 +docstring-min-length = 5 [ELIF] # Maximum number of nested blocks for function / method body -max-nested-blocks=5 +max-nested-blocks = 5 [IMPORTS] # Deprecated modules which should not be used, separated by a comma -deprecated-modules=regsub,TERMIOS,Bastion,rexec +deprecated-modules = regsub,TERMIOS,Bastion,rexec # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) -import-graph= +import-graph = # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) -ext-import-graph= +ext-import-graph = # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) -int-import-graph= +int-import-graph = [DESIGN] # Maximum number of arguments for function / method -max-args=6 +max-args = 6 # Argument names that match this expression will be ignored. Default to name # with leading underscore -ignored-argument-names=_.* +ignored-argument-names = _.* # Maximum number of locals for function / method body -max-locals=15 +max-locals = 15 # Maximum number of return / yield for function / method body -max-returns=8 +max-returns = 8 # Maximum number of branch for function / method body -max-branches=12 +max-branches = 12 # Maximum number of statements in function / method body -max-statements=50 +max-statements = 50 # Maximum number of parents for a class (see R0901). -max-parents=7 +max-parents = 7 # Maximum number of attributes for a class (see R0902). -max-attributes=10 +max-attributes = 10 # Minimum number of public methods for a class (see R0903). -min-public-methods=2 +min-public-methods = 2 # Maximum number of public methods for a class (see R0904). -max-public-methods=20 +max-public-methods = 20 # Maximum number of boolean expressions in a if statement -max-bool-expr=5 +max-bool-expr = 5 [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp +defining-attr-methods = __init__,__new__,setUp # List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls +valid-classmethod-first-arg = cls # List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs +valid-metaclass-classmethod-first-arg = mcs # List of member names, which should be excluded from the protected access # warning. -exclude-protected=_asdict,_fields,_replace,_source,_make +exclude-protected = _asdict,_fields,_replace,_source,_make [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception" -overgeneral-exceptions=Exception +overgeneral-exceptions = Exception diff --git a/.readthedocs.yml b/.readthedocs.yml index 649725d3064..642f9a4f057 100644 --- a/.readthedocs.yml +++ b/.readthedocs.yml @@ -6,7 +6,7 @@ version: 2 # Build documentation in the docs/ directory with Sphinx sphinx: - configuration: doc/conf.py + configuration: doc/conf.py build: image: latest @@ -16,6 +16,6 @@ submodules: include: all python: - version: "3.8" - install: - - requirements: doc/requirements.txt \ No newline at end of file + version: "3.8" + install: + - requirements: doc/requirements.txt \ No newline at end of file diff --git a/build/mac/licenseDMG.py b/build/mac/licenseDMG.py index 47d1a0d6aa3..c7676e4998c 100644 --- a/build/mac/licenseDMG.py +++ b/build/mac/licenseDMG.py @@ -27,12 +27,13 @@ THE SOFTWARE. """ from __future__ import unicode_literals -from subprocess import check_call, check_output, call, CalledProcessError + import argparse import logging as logger import os import sys import tempfile +from subprocess import CalledProcessError, call, check_call, check_output logger.basicConfig(format='%(message)s', level=logger.DEBUG) diff --git a/doc/conf.py b/doc/conf.py index 5b3dfeb3b2c..46f37a5aefc 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -20,7 +20,6 @@ import logging import os import sys -from pathlib import Path logging.basicConfig(level=logging.INFO) logging.info('Start to execute conf.py') diff --git a/doc/development/qt.rst b/doc/development/qt.rst index fba1c87ccf3..8fc764a3874 100644 --- a/doc/development/qt.rst +++ b/doc/development/qt.rst @@ -1,5 +1,4 @@ - -Our GUI uses QT toolkit. It can be quite tricky at times. Also, PyQt have LOTS of bugs, so be warned! +Our GUI uses QT toolkit. It can be quite tricky at times. Also, PyQt have LOTS of bugs, so be warned! For the beginner, the best way to develop QT is to just copy-paste stuff around, looking for examples in our codebase. diff --git a/doc/index.rst b/doc/index.rst index 03dd0e060d1..e4dc7afa7a8 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -1,7 +1,7 @@ .. Tribler documentation master file, created by - sphinx-quickstart on Wed Jun 15 19:59:31 2016. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. +sphinx-quickstart on Wed Jun 15 19:59:31 2016. +You can adapt this file completely to your liking, but it should at least +contain the root `toctree` directive. Welcome to Tribler's documentation! =================================== diff --git a/scripts/bandwidth_crawler/run_bandwidth_crawler.py b/scripts/bandwidth_crawler/run_bandwidth_crawler.py index 025618b03dd..4561e3f8360 100644 --- a/scripts/bandwidth_crawler/run_bandwidth_crawler.py +++ b/scripts/bandwidth_crawler/run_bandwidth_crawler.py @@ -36,7 +36,7 @@ async def crawler_session(session_config: TriblerConfig): parser.add_argument('--statedir', '-s', default='bw_crawler', type=str, help='Use an alternate statedir') parser.add_argument('--restapi', '-p', default=20100, type=int, help='Use an alternate port for the REST API', action=PortAction, metavar='{0..65535}') - parser.add_argument('--fragile', '-f', help='Fail at the first error', action='store_true') + parser.add_argument('--fragile', '-f', help='Fail at the first error', action='store_true') args = parser.parse_args(sys.argv[1:]) logging.basicConfig(level=logging.INFO) diff --git a/scripts/exit_node/run_exit_node.py b/scripts/exit_node/run_exit_node.py index ebccf90232a..373431b9700 100644 --- a/scripts/exit_node/run_exit_node.py +++ b/scripts/exit_node/run_exit_node.py @@ -16,11 +16,11 @@ from tribler.core import notifications from tribler.core.components.bandwidth_accounting.bandwidth_accounting_component import BandwidthAccountingComponent -from tribler.core.components.session import Session from tribler.core.components.ipv8.ipv8_component import Ipv8Component from tribler.core.components.key.key_component import KeyComponent from tribler.core.components.resource_monitor.resource_monitor_component import ResourceMonitorComponent from tribler.core.components.restapi.restapi_component import RESTComponent +from tribler.core.components.session import Session from tribler.core.components.socks_servers.socks_servers_component import SocksServersComponent from tribler.core.components.tunnel.tunnel_component import TunnelsComponent from tribler.core.config.tribler_config import TriblerConfig @@ -224,7 +224,7 @@ def main(): parser.add_argument('--log-rejects', action='store_const', default=False, const=True, help='Log rejects') parser.add_argument('--log-circuits', action='store_const', default=False, const=True, help='Log information about circuits') - parser.add_argument('--fragile', '-f', help='Fail at the first error', action='store_true') + parser.add_argument('--fragile', '-f', help='Fail at the first error', action='store_true') args = parser.parse_args(sys.argv[1:]) service = TunnelHelperService() diff --git a/scripts/experiments/tunnel_community/hidden_peer_discovery.py b/scripts/experiments/tunnel_community/hidden_peer_discovery.py index 26e4cc27833..ecb2334d39a 100644 --- a/scripts/experiments/tunnel_community/hidden_peer_discovery.py +++ b/scripts/experiments/tunnel_community/hidden_peer_discovery.py @@ -1,5 +1,4 @@ import argparse -import asyncio import os import time from binascii import hexlify, unhexlify diff --git a/scripts/seedbox/README.md b/scripts/seedbox/README.md index 9835d3d2044..c85ed69dbb2 100644 --- a/scripts/seedbox/README.md +++ b/scripts/seedbox/README.md @@ -21,7 +21,7 @@ The seedbox consists of two parts: ```shell export PYTHONPATH=${PYTHONPATH}:./src ``` - + ## Torrent seeding To start torrents' seeding run the following script: @@ -70,10 +70,11 @@ source folder ``` Above you can see two "special" files: + * thumbnail.png * description.md -The channel will be created with description based on these files. +The channel will be created with description based on these files. As the channel name, the source folder's name will be used. ### Error reporting diff --git a/src/README.md b/src/README.md index 9c5d9cf4c97..f3216e4ad6f 100644 --- a/src/README.md +++ b/src/README.md @@ -17,10 +17,12 @@ tribler.sh # Run Tests Install all necessary dependencies: + ``` python3 -m pip install -r requirements-test.txt ``` -Note: `requirements-test.txt` already contains all requirements + +Note: `requirements-test.txt` already contains all requirements from` requirements.txt`. ## @@ -28,6 +30,7 @@ from` requirements.txt`. Export the `src` directory to `PYTHONPATH` Execute: + ``` python3 -m pytest src python3 -m pytest src --guitests diff --git a/src/run_tribler.py b/src/run_tribler.py index 3ddd09baff3..6ae31538dcf 100644 --- a/src/run_tribler.py +++ b/src/run_tribler.py @@ -1,12 +1,13 @@ import argparse +import logging.config +import os +import sys + # A fix for "LookupError: unknown encoding: idna" error. # Adding encodings.idna to hiddenimports is not enough. # https://github.com/pyinstaller/pyinstaller/issues/1113 # noinspection PyUnresolvedReferences import encodings.idna # pylint: disable=unused-import -import logging.config -import os -import sys from tribler.core.sentry_reporter.sentry_reporter import SentryReporter, SentryStrategy from tribler.core.sentry_reporter.sentry_scrubber import SentryScrubber diff --git a/src/tribler/core/components/bandwidth_accounting/db/transaction.py b/src/tribler/core/components/bandwidth_accounting/db/transaction.py index f73c79fa2ab..8db476b320b 100644 --- a/src/tribler/core/components/bandwidth_accounting/db/transaction.py +++ b/src/tribler/core/components/bandwidth_accounting/db/transaction.py @@ -14,13 +14,13 @@ from ipv8.keyvault.crypto import default_eccrypto from ipv8.keyvault.keys import Key from ipv8.messaging.serialization import default_serializer - from pony.orm import PrimaryKey, Required, db_session from tribler.core.components.bandwidth_accounting.community.payload import BandwidthTransactionPayload EMPTY_SIGNATURE = b'0' * 64 + @dataclass class BandwidthTransactionData: """ @@ -151,8 +151,8 @@ def insert(cls, transaction: BandwidthTransaction) -> None: if not bandwidth_database.store_all_transactions: # Make sure to only store the latest pairwise transaction. for tx in cls.select( - lambda c: c.public_key_a == transaction.public_key_a and - c.public_key_b == transaction.public_key_b): + lambda c: c.public_key_a == transaction.public_key_a and + c.public_key_b == transaction.public_key_b): tx.delete() db.commit() cls(**transaction.get_db_kwargs()) diff --git a/src/tribler/core/components/bandwidth_accounting/restapi/bandwidth_endpoint.py b/src/tribler/core/components/bandwidth_accounting/restapi/bandwidth_endpoint.py index 903acdaf9e0..90e0e394c68 100644 --- a/src/tribler/core/components/bandwidth_accounting/restapi/bandwidth_endpoint.py +++ b/src/tribler/core/components/bandwidth_accounting/restapi/bandwidth_endpoint.py @@ -1,9 +1,6 @@ from aiohttp import web - from aiohttp_apispec import docs - from ipv8.REST.schema import schema - from marshmallow.fields import Integer, String from tribler.core.components.bandwidth_accounting.community.bandwidth_accounting_community import ( diff --git a/src/tribler/core/components/bandwidth_accounting/tests/test_bandwidth_accounting_component.py b/src/tribler/core/components/bandwidth_accounting/tests/test_bandwidth_accounting_component.py index 8c4146e5767..5d9dd822e28 100644 --- a/src/tribler/core/components/bandwidth_accounting/tests/test_bandwidth_accounting_component.py +++ b/src/tribler/core/components/bandwidth_accounting/tests/test_bandwidth_accounting_component.py @@ -1,9 +1,8 @@ -import pytest - from tribler.core.components.bandwidth_accounting.bandwidth_accounting_component import BandwidthAccountingComponent -from tribler.core.components.session import Session from tribler.core.components.ipv8.ipv8_component import Ipv8Component from tribler.core.components.key.key_component import KeyComponent +from tribler.core.components.session import Session + # pylint: disable=protected-access diff --git a/src/tribler/core/components/bandwidth_accounting/tests/test_bandwidth_endpoint.py b/src/tribler/core/components/bandwidth_accounting/tests/test_bandwidth_endpoint.py index ecb3e4a0d2b..05cb22574e1 100644 --- a/src/tribler/core/components/bandwidth_accounting/tests/test_bandwidth_endpoint.py +++ b/src/tribler/core/components/bandwidth_accounting/tests/test_bandwidth_endpoint.py @@ -1,9 +1,8 @@ +import pytest from ipv8.keyvault.crypto import default_eccrypto from ipv8.peer import Peer from ipv8.test.mocking.ipv8 import MockIPv8 -import pytest - from tribler.core.components.bandwidth_accounting.community.bandwidth_accounting_community import ( BandwidthAccountingCommunity, ) diff --git a/src/tribler/core/components/bandwidth_accounting/tests/test_database.py b/src/tribler/core/components/bandwidth_accounting/tests/test_database.py index f03dbc7dbf3..5026b58f5a5 100644 --- a/src/tribler/core/components/bandwidth_accounting/tests/test_database.py +++ b/src/tribler/core/components/bandwidth_accounting/tests/test_database.py @@ -1,11 +1,9 @@ import random +import pytest from ipv8.keyvault.crypto import default_eccrypto - from pony.orm import db_session -import pytest - from tribler.core.components.bandwidth_accounting.db.database import BandwidthDatabase from tribler.core.components.bandwidth_accounting.db.transaction import BandwidthTransactionData, EMPTY_SIGNATURE from tribler.core.utilities.utilities import MEMORY_DB diff --git a/src/tribler/core/components/bandwidth_accounting/trust_calculation/graph_positioning.py b/src/tribler/core/components/bandwidth_accounting/trust_calculation/graph_positioning.py index 18605894d35..694b20054ce 100644 --- a/src/tribler/core/components/bandwidth_accounting/trust_calculation/graph_positioning.py +++ b/src/tribler/core/components/bandwidth_accounting/trust_calculation/graph_positioning.py @@ -62,12 +62,12 @@ def _hierarchy_pos(G, root, width=1., vert_gap=0.2, vert_loc=0, xcenter=0.5, pos if not isinstance(G, nx.DiGraph) and parent is not None: children.remove(parent) if children: - dx = width/len(children) - nextx = xcenter - width/2 - dx/2 + dx = width / len(children) + nextx = xcenter - width / 2 - dx / 2 for child in children: nextx += dx pos = _hierarchy_pos(G, child, width=dx, vert_gap=vert_gap, - vert_loc=vert_loc-vert_gap, + vert_loc=vert_loc - vert_gap, xcenter=nextx, pos=pos, parent=root) return pos diff --git a/src/tribler/core/components/bandwidth_accounting/trust_calculation/test_graph_positioning.py b/src/tribler/core/components/bandwidth_accounting/trust_calculation/test_graph_positioning.py index 3d2349bcb14..cf664b21215 100644 --- a/src/tribler/core/components/bandwidth_accounting/trust_calculation/test_graph_positioning.py +++ b/src/tribler/core/components/bandwidth_accounting/trust_calculation/test_graph_positioning.py @@ -1,5 +1,4 @@ import networkx as nx - import pytest from tribler.core.components.bandwidth_accounting.trust_calculation.graph_positioning import GraphPositioning diff --git a/src/tribler/core/components/bandwidth_accounting/trust_calculation/trust_graph.py b/src/tribler/core/components/bandwidth_accounting/trust_calculation/trust_graph.py index fb1a1a37abb..698c12eef06 100644 --- a/src/tribler/core/components/bandwidth_accounting/trust_calculation/trust_graph.py +++ b/src/tribler/core/components/bandwidth_accounting/trust_calculation/trust_graph.py @@ -4,8 +4,8 @@ import networkx as nx -from tribler.core.exceptions import TrustGraphException from tribler.core.components.bandwidth_accounting.trust_calculation.graph_positioning import GraphPositioning +from tribler.core.exceptions import TrustGraphException from tribler.core.utilities.unicode import hexlify MAX_NODES = 500 diff --git a/src/tribler/core/components/gigachannel/community/gigachannel_community.py b/src/tribler/core/components/gigachannel/community/gigachannel_community.py index ac194153d06..06bd7f74899 100644 --- a/src/tribler/core/components/gigachannel/community/gigachannel_community.py +++ b/src/tribler/core/components/gigachannel/community/gigachannel_community.py @@ -5,9 +5,7 @@ from random import sample from anyio import Event, create_task_group, move_on_after - from ipv8.types import Peer - from pony.orm import db_session from tribler.core import notifications @@ -73,14 +71,14 @@ class GigaChannelCommunity(RemoteQueryCommunity): community_id = unhexlify('d3512d0ff816d8ac672eab29a9c1a3a32e17cb13') def create_introduction_response( - self, - lan_socket_address, - socket_address, - identifier, - introduction=None, - extra_bytes=b'', - prefix=None, - new_style=False, + self, + lan_socket_address, + socket_address, + identifier, + introduction=None, + extra_bytes=b'', + prefix=None, + new_style=False, ): # ACHTUNG! We add extra_bytes here to identify the newer, 7.6+ version RemoteQuery/GigaChannel community # dialect, so that other 7.6+ are able to distinguish between the older and newer versions. @@ -94,7 +92,7 @@ def create_introduction_response( ) def __init__( - self, *args, notifier: Notifier = None, **kwargs + self, *args, notifier: Notifier = None, **kwargs ): # pylint: disable=unused-argument # ACHTUNG! We create a separate instance of Network for this community because it # walks aggressively and wants lots of peers, which can interfere with other communities @@ -124,9 +122,9 @@ def introduction_response_callback(self, peer, dist, payload): # to ourselves (peer's public_key is not sent along with the introduction). To prevent querying # ourselves, we add the check for blacklist_mids here, which by default contains our own peer. if ( - peer.address in self.network.blacklist - or peer.mid in self.queried_peers - or peer.mid in self.network.blacklist_mids + peer.address in self.network.blacklist + or peer.mid in self.queried_peers + or peer.mid in self.network.blacklist_mids ): return if len(self.queried_peers) >= self.settings.queried_peers_limit: @@ -147,9 +145,9 @@ def on_packet_callback(_, processing_results): r.md_obj.to_simple_dict() for r in processing_results if ( - r.obj_state == ObjState.NEW_OBJECT - and r.md_obj.metadata_type == CHANNEL_TORRENT - and r.md_obj.origin_id == 0 + r.obj_state == ObjState.NEW_OBJECT + and r.md_obj.metadata_type == CHANNEL_TORRENT + and r.md_obj.origin_id == 0 ) ] if self.notifier and results: diff --git a/src/tribler/core/components/gigachannel/community/request.py b/src/tribler/core/components/gigachannel/community/request.py index 970345e5006..11bd2d4d22c 100644 --- a/src/tribler/core/components/gigachannel/community/request.py +++ b/src/tribler/core/components/gigachannel/community/request.py @@ -1,7 +1,5 @@ from ipv8.requestcache import RandomNumberCache -from tribler.core.utilities.unicode import hexlify - class SearchRequestCache(RandomNumberCache): """ diff --git a/src/tribler/core/components/gigachannel/community/sync_strategy.py b/src/tribler/core/components/gigachannel/community/sync_strategy.py index c6fc1b3a300..a1ef37fb3be 100644 --- a/src/tribler/core/components/gigachannel/community/sync_strategy.py +++ b/src/tribler/core/components/gigachannel/community/sync_strategy.py @@ -2,7 +2,6 @@ from ipv8.peerdiscovery.discovery import DiscoveryStrategy - TARGET_PEERS_NUMBER = 20 diff --git a/src/tribler/core/components/gigachannel/community/tests/test_gigachannel_community.py b/src/tribler/core/components/gigachannel/community/tests/test_gigachannel_community.py index 24d57cbfe2a..2beaaceade5 100644 --- a/src/tribler/core/components/gigachannel/community/tests/test_gigachannel_community.py +++ b/src/tribler/core/components/gigachannel/community/tests/test_gigachannel_community.py @@ -16,7 +16,7 @@ from tribler.core.components.gigachannel.community.settings import ChantSettings from tribler.core.components.metadata_store.db.store import MetadataStore from tribler.core.components.metadata_store.remote_query_community.remote_query_community import EvaSelectRequest, \ - RemoteQueryCommunity, SelectRequest + SelectRequest from tribler.core.components.metadata_store.remote_query_community.settings import RemoteQueryCommunitySettings from tribler.core.components.metadata_store.utils import RequestTimeoutException from tribler.core.utilities.notifier import Notifier diff --git a/src/tribler/core/components/gigachannel/gigachannel_component.py b/src/tribler/core/components/gigachannel/gigachannel_component.py index a8ef91b8bc9..3a5891c1c35 100644 --- a/src/tribler/core/components/gigachannel/gigachannel_component.py +++ b/src/tribler/core/components/gigachannel/gigachannel_component.py @@ -7,9 +7,9 @@ ) from tribler.core.components.gigachannel.community.sync_strategy import RemovePeers from tribler.core.components.ipv8.ipv8_component import INFINITE, Ipv8Component +from tribler.core.components.knowledge.knowledge_component import KnowledgeComponent from tribler.core.components.metadata_store.metadata_store_component import MetadataStoreComponent from tribler.core.components.reporter.reporter_component import ReporterComponent -from tribler.core.components.knowledge.knowledge_component import KnowledgeComponent class GigaChannelComponent(Component): diff --git a/src/tribler/core/components/gui_process_watcher/gui_process_watcher.py b/src/tribler/core/components/gui_process_watcher/gui_process_watcher.py index 99e4f9af16e..17a07640df3 100644 --- a/src/tribler/core/components/gui_process_watcher/gui_process_watcher.py +++ b/src/tribler/core/components/gui_process_watcher/gui_process_watcher.py @@ -5,11 +5,9 @@ import psutil from ipv8.taskmanager import TaskManager - GUI_PID_ENV_KEY = 'TRIBLER_GUI_PID' CHECK_INTERVAL = 10 - logger = logging.getLogger(__name__) diff --git a/src/tribler/core/components/ipv8/ipv8_component.py b/src/tribler/core/components/ipv8/ipv8_component.py index 4e5d96a4e3b..cf8ecddc0aa 100644 --- a/src/tribler/core/components/ipv8/ipv8_component.py +++ b/src/tribler/core/components/ipv8/ipv8_component.py @@ -12,7 +12,6 @@ from ipv8.peerdiscovery.community import DiscoveryCommunity, PeriodicSimilarity from ipv8.peerdiscovery.discovery import RandomWalk from ipv8.taskmanager import TaskManager - from ipv8_service import IPv8 from tribler.core.components.component import Component diff --git a/src/tribler/core/components/ipv8/ipv8_health_monitor.py b/src/tribler/core/components/ipv8/ipv8_health_monitor.py index 8284d582337..4f5cacedfff 100644 --- a/src/tribler/core/components/ipv8/ipv8_health_monitor.py +++ b/src/tribler/core/components/ipv8/ipv8_health_monitor.py @@ -4,7 +4,6 @@ from ipv8.REST.asyncio_endpoint import DriftMeasurementStrategy from ipv8.taskmanager import TaskManager - from ipv8_service import IPv8 @@ -40,7 +39,7 @@ def __init__(self, self.interval = 5.0 # 5 steps from slowest to fastest (with the default interval of 5 seconds, this takes 25 seconds). - self.speedup_step = (self.max_update_rate - self.min_update_rate)/5.0 + self.speedup_step = (self.max_update_rate - self.min_update_rate) / 5.0 self.logger = logging.getLogger(self.__class__.__name__) diff --git a/src/tribler/core/components/ipv8/protocol_decorator.py b/src/tribler/core/components/ipv8/protocol_decorator.py index 3670b339c05..5f96b76458b 100644 --- a/src/tribler/core/components/ipv8/protocol_decorator.py +++ b/src/tribler/core/components/ipv8/protocol_decorator.py @@ -67,5 +67,7 @@ def outer(protocol, peer, payload): raise TypeError(f'Incorrect payload type: {payload.__class__.__name__}') return outer + return actual_decorator + return protocol_decorator diff --git a/src/tribler/core/components/ipv8/settings.py b/src/tribler/core/components/ipv8/settings.py index 446b60211f5..69055d82a91 100644 --- a/src/tribler/core/components/ipv8/settings.py +++ b/src/tribler/core/components/ipv8/settings.py @@ -5,6 +5,7 @@ from tribler.core.config.tribler_config_section import TriblerConfigSection from tribler.core.utilities.network_utils import NetworkUtils + # pylint: disable=no-self-argument diff --git a/src/tribler/core/components/ipv8/tests/test_discovery_booster.py b/src/tribler/core/components/ipv8/tests/test_discovery_booster.py index 12c42220588..6465137f583 100644 --- a/src/tribler/core/components/ipv8/tests/test_discovery_booster.py +++ b/src/tribler/core/components/ipv8/tests/test_discovery_booster.py @@ -29,7 +29,7 @@ def __init__(self): self.tasks = [] def register_task( - self, name, task, *args, delay=None, interval=None, ignore=() + self, name, task, *args, delay=None, interval=None, ignore=() ): # pylint: disable=unused-argument self.tasks.append(name) diff --git a/src/tribler/core/components/ipv8/tests/test_ipv8_component.py b/src/tribler/core/components/ipv8/tests/test_ipv8_component.py index 391592b5041..d9fb12f9c0e 100644 --- a/src/tribler/core/components/ipv8/tests/test_ipv8_component.py +++ b/src/tribler/core/components/ipv8/tests/test_ipv8_component.py @@ -1,8 +1,6 @@ -import pytest - -from tribler.core.components.session import Session from tribler.core.components.ipv8.ipv8_component import Ipv8Component from tribler.core.components.key.key_component import KeyComponent +from tribler.core.components.session import Session # pylint: disable=protected-access diff --git a/src/tribler/core/components/ipv8/tests/test_ipv8_health_manager.py b/src/tribler/core/components/ipv8/tests/test_ipv8_health_manager.py index 22cccbbabb6..be8591e8fe8 100644 --- a/src/tribler/core/components/ipv8/tests/test_ipv8_health_manager.py +++ b/src/tribler/core/components/ipv8/tests/test_ipv8_health_manager.py @@ -7,18 +7,16 @@ import time import pytest - from ipv8.taskmanager import TaskManager from tribler.core.components.ipv8.ipv8_health_monitor import IPv8Monitor - DEFAULT_WALK_INTERVAL = 0.5 @pytest.fixture(name="ipv8") def fixture_ipv8(): - return type("IPv8", (object, ), { + return type("IPv8", (object,), { "strategies": [], "overlay_lock": threading.RLock(), "walk_interval": DEFAULT_WALK_INTERVAL diff --git a/src/tribler/core/components/key/key_component.py b/src/tribler/core/components/key/key_component.py index ff7a54588a4..49811f50b12 100644 --- a/src/tribler/core/components/key/key_component.py +++ b/src/tribler/core/components/key/key_component.py @@ -1,4 +1,5 @@ from ipv8.keyvault.private.libnaclkey import LibNaCLSK + from tribler.core.components.component import Component from tribler.core.config.tribler_config import TriblerConfig from tribler.core.utilities.path_util import Path diff --git a/src/tribler/core/components/key/settings.py b/src/tribler/core/components/key/settings.py index ae2502a3b7b..2b1fc5a5451 100644 --- a/src/tribler/core/components/key/settings.py +++ b/src/tribler/core/components/key/settings.py @@ -2,6 +2,7 @@ from tribler.core.config.tribler_config_section import TriblerConfigSection + # pylint: disable=no-self-argument diff --git a/src/tribler/core/components/libtorrent/download_manager/dht_health_manager.py b/src/tribler/core/components/libtorrent/download_manager/dht_health_manager.py index 673b6f0df54..e06031a1c15 100644 --- a/src/tribler/core/components/libtorrent/download_manager/dht_health_manager.py +++ b/src/tribler/core/components/libtorrent/download_manager/dht_health_manager.py @@ -1,5 +1,4 @@ import math -import time from asyncio import Future from typing import Awaitable diff --git a/src/tribler/core/components/libtorrent/download_manager/download_manager.py b/src/tribler/core/components/libtorrent/download_manager/download_manager.py index b2ee9b4ced2..962dba0125b 100644 --- a/src/tribler/core/components/libtorrent/download_manager/download_manager.py +++ b/src/tribler/core/components/libtorrent/download_manager/download_manager.py @@ -36,8 +36,7 @@ scheme_from_url, url_to_path, ) -from tribler.core.utilities.simpledefs import MAX_LIBTORRENT_RATE_LIMIT, STATEDIR_CHECKPOINT_DIR, \ - DownloadStatus +from tribler.core.utilities.simpledefs import DownloadStatus, MAX_LIBTORRENT_RATE_LIMIT, STATEDIR_CHECKPOINT_DIR from tribler.core.utilities.unicode import hexlify from tribler.core.utilities.utilities import bdecode_compat, has_bep33_support, parse_magnetlink from tribler.core.version import version_id diff --git a/src/tribler/core/components/libtorrent/restapi/create_torrent_endpoint.py b/src/tribler/core/components/libtorrent/restapi/create_torrent_endpoint.py index 5b343d22e2a..da7a54806a2 100644 --- a/src/tribler/core/components/libtorrent/restapi/create_torrent_endpoint.py +++ b/src/tribler/core/components/libtorrent/restapi/create_torrent_endpoint.py @@ -2,11 +2,8 @@ import json from aiohttp import web - from aiohttp_apispec import docs, json_schema - from ipv8.REST.schema import schema - from marshmallow.fields import String from tribler.core.components.libtorrent.download_manager.download_config import DownloadConfig diff --git a/src/tribler/core/components/libtorrent/restapi/libtorrent_endpoint.py b/src/tribler/core/components/libtorrent/restapi/libtorrent_endpoint.py index 180affa4c21..0c2a54d9690 100644 --- a/src/tribler/core/components/libtorrent/restapi/libtorrent_endpoint.py +++ b/src/tribler/core/components/libtorrent/restapi/libtorrent_endpoint.py @@ -1,11 +1,8 @@ from asyncio import Future from aiohttp import web - from aiohttp_apispec import docs - from ipv8.REST.schema import schema - from marshmallow.fields import Integer from tribler.core.components.libtorrent.download_manager.download_manager import DownloadManager diff --git a/src/tribler/core/components/libtorrent/restapi/tests/test_libtorrent_endpoint.py b/src/tribler/core/components/libtorrent/restapi/tests/test_libtorrent_endpoint.py index 777821e2be2..fa29ec336a9 100644 --- a/src/tribler/core/components/libtorrent/restapi/tests/test_libtorrent_endpoint.py +++ b/src/tribler/core/components/libtorrent/restapi/tests/test_libtorrent_endpoint.py @@ -1,8 +1,7 @@ from unittest.mock import Mock -from aiohttp.web_app import Application - import pytest +from aiohttp.web_app import Application from tribler.core.components.libtorrent.restapi.libtorrent_endpoint import LibTorrentEndpoint from tribler.core.components.restapi.rest.base_api_test import do_request diff --git a/src/tribler/core/components/libtorrent/tests/test_download_api.py b/src/tribler/core/components/libtorrent/tests/test_download_api.py index 1e21fd0136f..292863261be 100644 --- a/src/tribler/core/components/libtorrent/tests/test_download_api.py +++ b/src/tribler/core/components/libtorrent/tests/test_download_api.py @@ -1,7 +1,5 @@ import shutil -import pytest - from tribler.core.components.libtorrent.download_manager.download_config import DownloadConfig from tribler.core.tests.tools.common import TORRENT_UBUNTU_FILE from tribler.core.utilities.rest_utils import path_to_url diff --git a/src/tribler/core/components/libtorrent/tests/test_libtorrent_component.py b/src/tribler/core/components/libtorrent/tests/test_libtorrent_component.py index 4d15a1f677a..cb93101a106 100644 --- a/src/tribler/core/components/libtorrent/tests/test_libtorrent_component.py +++ b/src/tribler/core/components/libtorrent/tests/test_libtorrent_component.py @@ -1,8 +1,6 @@ -import pytest - -from tribler.core.components.session import Session from tribler.core.components.key.key_component import KeyComponent from tribler.core.components.libtorrent.libtorrent_component import LibtorrentComponent +from tribler.core.components.session import Session from tribler.core.components.socks_servers.socks_servers_component import SocksServersComponent diff --git a/src/tribler/core/components/libtorrent/tests/test_seeding.py b/src/tribler/core/components/libtorrent/tests/test_seeding.py index 030acea5331..4764ffe39c3 100644 --- a/src/tribler/core/components/libtorrent/tests/test_seeding.py +++ b/src/tribler/core/components/libtorrent/tests/test_seeding.py @@ -3,7 +3,6 @@ Author(s): Arno Bakker, Niels Zeilemaker """ -import pytest from tribler.core.components.libtorrent.download_manager.download_config import DownloadConfig from tribler.core.tests.tools.common import TESTS_DATA_DIR diff --git a/src/tribler/core/components/libtorrent/tests/test_torrent_def.py b/src/tribler/core/components/libtorrent/tests/test_torrent_def.py index b3b32abf86d..90def1736ab 100644 --- a/src/tribler/core/components/libtorrent/tests/test_torrent_def.py +++ b/src/tribler/core/components/libtorrent/tests/test_torrent_def.py @@ -1,11 +1,9 @@ import shutil +import pytest from aiohttp import ClientResponseError - from libtorrent import bencode -import pytest - from tribler.core.components.libtorrent.torrentdef import TorrentDef, TorrentDefNoMetainfo from tribler.core.tests.tools.common import TESTS_DATA_DIR, TORRENT_UBUNTU_FILE from tribler.core.utilities.path_util import Path diff --git a/src/tribler/core/components/libtorrent/torrentdef.py b/src/tribler/core/components/libtorrent/torrentdef.py index acbb8565fa8..89d9961c531 100644 --- a/src/tribler/core/components/libtorrent/torrentdef.py +++ b/src/tribler/core/components/libtorrent/torrentdef.py @@ -302,7 +302,9 @@ def filter_character(char): return chr(char) self._logger.debug("Bad character 0x%X", char) return "?" + return "".join([filter_character(char) for char in name]) + return filter_characters(self.metainfo[b"info"][b"name"]) except UnicodeError: pass @@ -379,7 +381,9 @@ def filter_character(char): return chr(char) self._logger.debug("Bad character 0x%X", char) return "?" + return "".join([filter_character(char) for char in name]) + yield (Path(*[filter_characters(element) for element in file_dict[b"path"]]), file_dict[b"length"]) continue @@ -501,7 +505,7 @@ def get_name_utf8(self): """ Not all names are utf-8, attempt to construct it as utf-8 anyway. """ - return escape_as_utf8(self.name.encode('utf-8 ')if isinstance(self.name, str) else self.name) + return escape_as_utf8(self.name.encode('utf-8 ') if isinstance(self.name, str) else self.name) def get_name_as_unicode(self): return ensure_unicode(self.name, 'utf-8') diff --git a/src/tribler/core/components/libtorrent/utils/torrent_utils.py b/src/tribler/core/components/libtorrent/utils/torrent_utils.py index c2bf32c8e03..ec9634750e2 100644 --- a/src/tribler/core/components/libtorrent/utils/torrent_utils.py +++ b/src/tribler/core/components/libtorrent/utils/torrent_utils.py @@ -15,13 +15,16 @@ def check_handle(default=None): Return the libtorrent handle if it's available, else return the default value. Author(s): Egbert Bouman """ + def wrap(f): def invoke_func(*args, **kwargs): download = args[0] if download.handle and download.handle.is_valid(): return f(*args, **kwargs) return default + return invoke_func + return wrap @@ -30,6 +33,7 @@ def require_handle(func): Invoke the function once the handle is available. Returns a future that will fire once the function has completed. Author(s): Egbert Bouman """ + def invoke_func(*args, **kwargs): result_future = Future() @@ -38,10 +42,12 @@ def done_cb(fut): handle = fut.result() if not fut.cancelled() and not result_future.done() and handle == download.handle and handle.is_valid(): result_future.set_result(func(*args, **kwargs)) + download = args[0] handle_future = download.get_handle() handle_future.add_done_callback(done_cb) return result_future + return invoke_func diff --git a/src/tribler/core/components/metadata_store/category_filter/family_filter.py b/src/tribler/core/components/metadata_store/category_filter/family_filter.py index c0df67a2ad9..7c760ee0d11 100644 --- a/src/tribler/core/components/metadata_store/category_filter/family_filter.py +++ b/src/tribler/core/components/metadata_store/category_filter/family_filter.py @@ -10,7 +10,7 @@ WORDS_REGEXP = re.compile('[a-zA-Z0-9]+') -termfilename = get_lib_path() / 'components' / 'metadata_store' /'category_filter' / 'filter_terms.filter' +termfilename = get_lib_path() / 'components' / 'metadata_store' / 'category_filter' / 'filter_terms.filter' def initTerms(filename): diff --git a/src/tribler/core/components/metadata_store/db/orm_bindings/binary_node.py b/src/tribler/core/components/metadata_store/db/orm_bindings/binary_node.py index 28f2de5d233..279237c663a 100644 --- a/src/tribler/core/components/metadata_store/db/orm_bindings/binary_node.py +++ b/src/tribler/core/components/metadata_store/db/orm_bindings/binary_node.py @@ -19,8 +19,8 @@ class BinaryNode(db.ChannelNode): # Special class-level properties _payload_class = BinaryNodePayload payload_arguments = _payload_class.__init__.__code__.co_varnames[ - : _payload_class.__init__.__code__.co_argcount - ][1:] + : _payload_class.__init__.__code__.co_argcount + ][1:] nonpersonal_attributes = db.ChannelNode.nonpersonal_attributes + ('binary_data', 'data_type') return BinaryNode diff --git a/src/tribler/core/components/metadata_store/db/orm_bindings/channel_metadata.py b/src/tribler/core/components/metadata_store/db/orm_bindings/channel_metadata.py index c85891aec3c..4cfc4d650c9 100644 --- a/src/tribler/core/components/metadata_store/db/orm_bindings/channel_metadata.py +++ b/src/tribler/core/components/metadata_store/db/orm_bindings/channel_metadata.py @@ -3,7 +3,6 @@ from datetime import datetime from lz4.frame import LZ4FrameCompressor - from pony import orm from pony.orm import db_session, raw_sql, select @@ -231,8 +230,8 @@ class ChannelMetadata(db.TorrentMetadata, db.CollectionNode): _category_filter = None _CHUNK_SIZE_LIMIT = 1 * 1024 * 1024 # We use 1MB chunks as a workaround for Python's lack of string pointers payload_arguments = _payload_class.__init__.__code__.co_varnames[ - : _payload_class.__init__.__code__.co_argcount - ][1:] + : _payload_class.__init__.__code__.co_argcount + ][1:] # As channel metadata depends on the public key, we can't include the infohash in nonpersonal_attributes nonpersonal_attributes = set(db.CollectionNode.nonpersonal_attributes) @@ -376,11 +375,11 @@ def update_channel_torrent(self, metadata_list): torrent_date = datetime.utcfromtimestamp(torrent[b'creation date']) return { - "infohash": infohash, - "timestamp": last_existing_blob_number, - "torrent_date": torrent_date, - "reserved_flags": flags, - }, torrent + "infohash": infohash, + "timestamp": last_existing_blob_number, + "torrent_date": torrent_date, + "reserved_flags": flags, + }, torrent def commit_channel_torrent(self, new_start_timestamp=None, commit_list=None): """ diff --git a/src/tribler/core/components/metadata_store/db/orm_bindings/channel_node.py b/src/tribler/core/components/metadata_store/db/orm_bindings/channel_node.py index 81c9650d1a4..7dcb636ff91 100644 --- a/src/tribler/core/components/metadata_store/db/orm_bindings/channel_node.py +++ b/src/tribler/core/components/metadata_store/db/orm_bindings/channel_node.py @@ -2,7 +2,6 @@ from datetime import datetime from ipv8.keyvault.crypto import default_eccrypto - from pony import orm from pony.orm.core import DEFAULT, db_session diff --git a/src/tribler/core/components/metadata_store/db/orm_bindings/collection_node.py b/src/tribler/core/components/metadata_store/db/orm_bindings/collection_node.py index aa4c6b7da44..2b02b4d0d9b 100644 --- a/src/tribler/core/components/metadata_store/db/orm_bindings/collection_node.py +++ b/src/tribler/core/components/metadata_store/db/orm_bindings/collection_node.py @@ -25,6 +25,7 @@ from tribler.core.utilities.simpledefs import CHANNEL_STATE from tribler.core.utilities.utilities import random_infohash + # pylint: disable=too-many-statements @@ -46,8 +47,8 @@ class CollectionNode(db.MetadataNode): # Special class-level properties _payload_class = CollectionNodePayload payload_arguments = _payload_class.__init__.__code__.co_varnames[ - : _payload_class.__init__.__code__.co_argcount - ][1:] + : _payload_class.__init__.__code__.co_argcount + ][1:] nonpersonal_attributes = db.MetadataNode.nonpersonal_attributes + ('num_entries',) @property @@ -58,8 +59,8 @@ def state(self): toplevel_parent = self.get_parent_nodes()[0] if ( - toplevel_parent.metadata_type == CHANNEL_TORRENT - and toplevel_parent.local_version == toplevel_parent.timestamp + toplevel_parent.metadata_type == CHANNEL_TORRENT + and toplevel_parent.local_version == toplevel_parent.timestamp ): return CHANNEL_STATE.COMPLETE.value @@ -259,6 +260,7 @@ def get_children_dict_to_commit(): db.CollectionNode.collapse_deleted_subtrees() upd_dict = {} children = {} + # Remark: it should be possible to optimize this by rewriting in pure SQL with recursive CTEs def update_node_info(n): @@ -272,8 +274,8 @@ def update_node_info(n): dead_parents = set() # First we traverse the tree upwards from changed leaves to find all nodes affected by changes for node in db.ChannelNode.select( - lambda g: g.public_key == db.ChannelNode._my_key.pub().key_to_bin()[10:] # pylint: disable=W0212 - and g.status in DIRTY_STATUSES + lambda g: g.public_key == db.ChannelNode._my_key.pub().key_to_bin()[10:] # pylint: disable=W0212 + and g.status in DIRTY_STATUSES ): update_node_info(node) # This process resolves the parents completely. @@ -293,7 +295,7 @@ def update_node_info(n): # Delete orphans db.ChannelNode.select( lambda g: db.ChannelNode._my_key.pub().key_to_bin()[10:] == g.public_key # pylint: disable=W0212 - and g.origin_id in dead_parents + and g.origin_id in dead_parents ).delete() orm.flush() # Just in case... if not children or 0 not in children: @@ -379,6 +381,7 @@ def collapse_deleted_subtrees(): in the future. This procedure should be always run _before_ committing personal channels. """ + # Remark: it should be possible to optimize this by rewriting in pure SQL with recursive CTEs def get_highest_deleted_parent(node, highest_deleted_parent=None): @@ -395,7 +398,7 @@ def get_highest_deleted_parent(node, highest_deleted_parent=None): get_highest_deleted_parent(node, highest_deleted_parent=node).rowid for node in db.CollectionNode.select( lambda g: g.public_key == db.CollectionNode._my_key.pub().key_to_bin()[10:] # pylint: disable=W0212 - and g.status == TODELETE + and g.status == TODELETE ) if node } diff --git a/src/tribler/core/components/metadata_store/db/orm_bindings/json_node.py b/src/tribler/core/components/metadata_store/db/orm_bindings/json_node.py index 79f67b966cf..b6dae083aa9 100644 --- a/src/tribler/core/components/metadata_store/db/orm_bindings/json_node.py +++ b/src/tribler/core/components/metadata_store/db/orm_bindings/json_node.py @@ -18,8 +18,8 @@ class JsonNode(db.ChannelNode): # Special class-level properties _payload_class = JsonNodePayload payload_arguments = _payload_class.__init__.__code__.co_varnames[ - : _payload_class.__init__.__code__.co_argcount - ][1:] + : _payload_class.__init__.__code__.co_argcount + ][1:] nonpersonal_attributes = db.ChannelNode.nonpersonal_attributes + ('json_text',) def to_simple_dict(self): diff --git a/src/tribler/core/components/metadata_store/db/orm_bindings/metadata_node.py b/src/tribler/core/components/metadata_store/db/orm_bindings/metadata_node.py index 2812b8e03ab..dc9d6470ace 100644 --- a/src/tribler/core/components/metadata_store/db/orm_bindings/metadata_node.py +++ b/src/tribler/core/components/metadata_store/db/orm_bindings/metadata_node.py @@ -25,8 +25,8 @@ class MetadataNode(db.ChannelNode): # Special class-level properties _payload_class = MetadataNodePayload payload_arguments = _payload_class.__init__.__code__.co_varnames[ - : _payload_class.__init__.__code__.co_argcount - ][1:] + : _payload_class.__init__.__code__.co_argcount + ][1:] nonpersonal_attributes = db.ChannelNode.nonpersonal_attributes + ('title', 'tags') def to_simple_dict(self): diff --git a/src/tribler/core/components/metadata_store/db/orm_bindings/torrent_state.py b/src/tribler/core/components/metadata_store/db/orm_bindings/torrent_state.py index 38e7b3e9bf6..a744a1af021 100644 --- a/src/tribler/core/components/metadata_store/db/orm_bindings/torrent_state.py +++ b/src/tribler/core/components/metadata_store/db/orm_bindings/torrent_state.py @@ -1,6 +1,7 @@ from __future__ import annotations from pony import orm + from tribler.core.components.torrent_checker.torrent_checker.dataclasses import HealthInfo diff --git a/src/tribler/core/components/metadata_store/db/serialization.py b/src/tribler/core/components/metadata_store/db/serialization.py index a9ee8ee713c..58be16a695e 100644 --- a/src/tribler/core/components/metadata_store/db/serialization.py +++ b/src/tribler/core/components/metadata_store/db/serialization.py @@ -113,7 +113,8 @@ def __init__(self, metadata_type, reserved_flags, public_key, **kwargs): elif "signature" in kwargs: # This check ensures that an entry with a wrong signature will not proliferate further if not default_eccrypto.is_valid_signature( - default_eccrypto.key_from_public_bin(b"LibNaCLPK:" + self.public_key), serialized_data, self.signature + default_eccrypto.key_from_public_bin(b"LibNaCLPK:" + self.public_key), serialized_data, + self.signature ): raise InvalidSignatureException("Tried to create payload with wrong signature") else: @@ -171,7 +172,7 @@ class ChannelNodePayload(SignedPayload): def __init__( self, metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + id_, origin_id, timestamp, # ChannelNodePayload **kwargs): self.id_ = id_ self.origin_id = origin_id @@ -188,14 +189,14 @@ def to_pack_list(self): return data @classmethod - def from_unpack_list( # pylint: disable=arguments-differ + def from_unpack_list( # pylint: disable=arguments-differ cls, metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + id_, origin_id, timestamp, # ChannelNodePayload **kwargs): return ChannelNodePayload( metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + id_, origin_id, timestamp, # ChannelNodePayload **kwargs) def to_dict(self): @@ -214,13 +215,13 @@ class JsonNodePayload(ChannelNodePayload): def __init__( self, metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - json_text, # JsonNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + json_text, # JsonNodePayload **kwargs): self.json_text = json_text.decode('utf-8') if isinstance(json_text, bytes) else json_text super().__init__( metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + id_, origin_id, timestamp, # ChannelNodePayload **kwargs ) @@ -230,17 +231,17 @@ def to_pack_list(self): return data @classmethod - def from_unpack_list( # pylint: disable=arguments-differ + def from_unpack_list( # pylint: disable=arguments-differ cls, metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - json_text, # JsonNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + json_text, # JsonNodePayload **kwargs ): return cls( metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - json_text, # JsonNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + json_text, # JsonNodePayload **kwargs ) @@ -256,14 +257,14 @@ class BinaryNodePayload(ChannelNodePayload): def __init__( self, metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - binary_data, data_type, # BinaryNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + binary_data, data_type, # BinaryNodePayload **kwargs): self.binary_data = binary_data self.data_type = data_type.decode('utf-8') if isinstance(data_type, bytes) else data_type super().__init__( metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + id_, origin_id, timestamp, # ChannelNodePayload **kwargs ) @@ -274,17 +275,17 @@ def to_pack_list(self): return data @classmethod - def from_unpack_list( # pylint: disable=arguments-differ + def from_unpack_list( # pylint: disable=arguments-differ cls, metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - binary_data, data_type, # BinaryNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + binary_data, data_type, # BinaryNodePayload **kwargs ): return cls( metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - binary_data, data_type, # BinaryNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + binary_data, data_type, # BinaryNodePayload **kwargs ) @@ -296,20 +297,19 @@ def to_dict(self): class MetadataNodePayload(ChannelNodePayload): - format_list = ChannelNodePayload.format_list + ['varlenI', 'varlenI'] def __init__( self, metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - title, tags, # MetadataNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + title, tags, # MetadataNodePayload **kwargs): self.title = title.decode('utf-8') if isinstance(title, bytes) else title self.tags = tags.decode('utf-8') if isinstance(tags, bytes) else tags super().__init__( metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + id_, origin_id, timestamp, # ChannelNodePayload **kwargs ) @@ -320,17 +320,17 @@ def to_pack_list(self): return data @classmethod - def from_unpack_list( # pylint: disable=arguments-differ - cls, - metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - title, tags, # MetadataNodePayload - **kwargs + def from_unpack_list( # pylint: disable=arguments-differ + cls, + metadata_type, reserved_flags, public_key, # SignedPayload + id_, origin_id, timestamp, # ChannelNodePayload + title, tags, # MetadataNodePayload + **kwargs ): return MetadataNodePayload( metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - title, tags, # MetadataNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + title, tags, # MetadataNodePayload **kwargs ) @@ -352,16 +352,16 @@ class CollectionNodePayload(MetadataNodePayload): def __init__( self, metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - title, tags, # MetadataNodePayload - num_entries, # CollectionNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + title, tags, # MetadataNodePayload + num_entries, # CollectionNodePayload **kwargs ): self.num_entries = num_entries super().__init__( metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - title, tags, # MetadataNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + title, tags, # MetadataNodePayload **kwargs ) @@ -371,19 +371,19 @@ def to_pack_list(self): return data @classmethod - def from_unpack_list( # pylint: disable=arguments-differ + def from_unpack_list( # pylint: disable=arguments-differ cls, metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - title, tags, # MetadataNodePayload - num_entries, # CollectionNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + title, tags, # MetadataNodePayload + num_entries, # CollectionNodePayload **kwargs ): return CollectionNodePayload( metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - title, tags, # MetadataNodePayload - num_entries, # CollectionNodePayload + id_, origin_id, timestamp, # ChannelNodePayload + title, tags, # MetadataNodePayload + num_entries, # CollectionNodePayload **kwargs ) @@ -402,8 +402,8 @@ class TorrentMetadataPayload(ChannelNodePayload): def __init__( self, - metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + metadata_type, reserved_flags, public_key, # SignedPayload + id_, origin_id, timestamp, # ChannelNodePayload infohash, size, torrent_date, title, tags, tracker_info, # TorrentMetadataPayload **kwargs): self.infohash = bytes(infohash) @@ -429,15 +429,15 @@ def to_pack_list(self): return data @classmethod - def from_unpack_list( # pylint: disable=arguments-differ + def from_unpack_list( # pylint: disable=arguments-differ cls, - metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + metadata_type, reserved_flags, public_key, # SignedPayload + id_, origin_id, timestamp, # ChannelNodePayload infohash, size, torrent_date, title, tags, tracker_info, # TorrentMetadataPayload **kwargs): return TorrentMetadataPayload( - metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + metadata_type, reserved_flags, public_key, # SignedPayload + id_, origin_id, timestamp, # ChannelNodePayload infohash, size, torrent_date, title, tags, tracker_info, # TorrentMetadataPayload **kwargs) @@ -470,17 +470,17 @@ class ChannelMetadataPayload(TorrentMetadataPayload): def __init__( self, - metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + metadata_type, reserved_flags, public_key, # SignedPayload + id_, origin_id, timestamp, # ChannelNodePayload infohash, size, torrent_date, title, tags, tracker_info, # TorrentMetadataPayload - num_entries, start_timestamp, # ChannelMetadataPayload + num_entries, start_timestamp, # ChannelMetadataPayload **kwargs): self.num_entries = num_entries self.start_timestamp = start_timestamp super().__init__( - metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload - infohash, size, torrent_date, title, tags, tracker_info, # TorrentMetadataPayload + metadata_type, reserved_flags, public_key, # SignedPayload + id_, origin_id, timestamp, # ChannelNodePayload + infohash, size, torrent_date, title, tags, tracker_info, # TorrentMetadataPayload **kwargs) def to_pack_list(self): @@ -490,18 +490,18 @@ def to_pack_list(self): return data @classmethod - def from_unpack_list( # pylint: disable=arguments-differ + def from_unpack_list( # pylint: disable=arguments-differ cls, - metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + metadata_type, reserved_flags, public_key, # SignedPayload + id_, origin_id, timestamp, # ChannelNodePayload infohash, size, torrent_date, title, tags, tracker_info, # TorrentMetadataPayload - num_entries, start_timestamp, # ChannelMetadataPayload + num_entries, start_timestamp, # ChannelMetadataPayload **kwargs): return ChannelMetadataPayload( - metadata_type, reserved_flags, public_key, # SignedPayload - id_, origin_id, timestamp, # ChannelNodePayload + metadata_type, reserved_flags, public_key, # SignedPayload + id_, origin_id, timestamp, # ChannelNodePayload infohash, size, torrent_date, title, tags, tracker_info, # TorrentMetadataPayload - num_entries, start_timestamp, # ChannelMetadataPayload + num_entries, start_timestamp, # ChannelMetadataPayload **kwargs) def to_dict(self): @@ -523,7 +523,7 @@ class DeletedMetadataPayload(SignedPayload): def __init__( self, metadata_type, reserved_flags, public_key, # SignedPayload - delete_signature, # DeletedMetadataPayload + delete_signature, # DeletedMetadataPayload **kwargs): self.delete_signature = bytes(delete_signature) super().__init__( @@ -536,20 +536,22 @@ def to_pack_list(self): return data @classmethod - def from_unpack_list( # pylint: disable=arguments-differ + def from_unpack_list( # pylint: disable=arguments-differ cls, metadata_type, reserved_flags, public_key, # SignedPayload - delete_signature, # DeletedMetadataPayload + delete_signature, # DeletedMetadataPayload **kwargs): return DeletedMetadataPayload( metadata_type, reserved_flags, public_key, # SignedPayload - delete_signature, # DeletedMetadataPayload + delete_signature, # DeletedMetadataPayload **kwargs) def to_dict(self): dct = super().to_dict() dct.update({"delete_signature": self.delete_signature}) return dct + + # fmt: on diff --git a/src/tribler/core/components/metadata_store/db/tests/test_tracker_state.py b/src/tribler/core/components/metadata_store/db/tests/test_tracker_state.py index 0b8572c27a8..5376e420a67 100644 --- a/src/tribler/core/components/metadata_store/db/tests/test_tracker_state.py +++ b/src/tribler/core/components/metadata_store/db/tests/test_tracker_state.py @@ -1,6 +1,5 @@ -from pony.orm import db_session - import pytest +from pony.orm import db_session from tribler.core.utilities.tracker_utils import MalformedTrackerURLException diff --git a/src/tribler/core/components/metadata_store/metadata_store_component.py b/src/tribler/core/components/metadata_store/metadata_store_component.py index 5024d75f37d..477d682480b 100644 --- a/src/tribler/core/components/metadata_store/metadata_store_component.py +++ b/src/tribler/core/components/metadata_store/metadata_store_component.py @@ -1,8 +1,8 @@ from tribler.core import notifications from tribler.core.components.component import Component from tribler.core.components.key.key_component import KeyComponent -from tribler.core.components.metadata_store.db.store import MetadataStore from tribler.core.components.knowledge.rules.tag_rules_processor import KnowledgeRulesProcessor +from tribler.core.components.metadata_store.db.store import MetadataStore from tribler.core.utilities.simpledefs import STATEDIR_DB_DIR diff --git a/src/tribler/core/components/metadata_store/remote_query_community/payload_checker.py b/src/tribler/core/components/metadata_store/remote_query_community/payload_checker.py index 93be96aef12..278f4ee6340 100644 --- a/src/tribler/core/components/metadata_store/remote_query_community/payload_checker.py +++ b/src/tribler/core/components/metadata_store/remote_query_community/payload_checker.py @@ -101,7 +101,8 @@ def reject_payload_with_offending_words(self): Otherwise, CONTINUE control to further checks. """ if is_forbidden( - " ".join([getattr(self.payload, attr) for attr in ("title", "tags", "text") if hasattr(self.payload, attr)]) + " ".join( + [getattr(self.payload, attr) for attr in ("title", "tags", "text") if hasattr(self.payload, attr)]) ): return [] return CONTINUE @@ -126,11 +127,11 @@ def add_node(self): If it is impossible, CONTINUE control to further checks (there should not be any more, really). """ for orm_class in ( - self.mds.TorrentMetadata, - self.mds.ChannelMetadata, - self.mds.CollectionNode, - self.mds.ChannelThumbnail, - self.mds.ChannelDescription, + self.mds.TorrentMetadata, + self.mds.ChannelMetadata, + self.mds.CollectionNode, + self.mds.ChannelThumbnail, + self.mds.ChannelDescription, ): if orm_class._discriminator_ == self.payload.metadata_type: # pylint: disable=W0212 obj = orm_class.from_payload(self.payload) @@ -237,7 +238,7 @@ def request_missing_dependencies(self, node_list): """ for r in node_list: updated_local_channel_node = ( - r.obj_state == ObjState.UPDATED_LOCAL_VERSION and r.md_obj.metadata_type == CHANNEL_TORRENT + r.obj_state == ObjState.UPDATED_LOCAL_VERSION and r.md_obj.metadata_type == CHANNEL_TORRENT ) r.missing_deps.extend( self.requests_for_child_dependencies(r.md_obj, include_newer=updated_local_channel_node) diff --git a/src/tribler/core/components/metadata_store/restapi/channels_endpoint.py b/src/tribler/core/components/metadata_store/restapi/channels_endpoint.py index 2543e9ec873..8df58a3e768 100644 --- a/src/tribler/core/components/metadata_store/restapi/channels_endpoint.py +++ b/src/tribler/core/components/metadata_store/restapi/channels_endpoint.py @@ -1,18 +1,13 @@ import base64 -import codecs import json from asyncio import CancelledError from binascii import unhexlify from pathlib import Path from aiohttp import ClientSession, ContentTypeError, web - from aiohttp_apispec import docs, json_schema - from ipv8.REST.schema import schema - from marshmallow.fields import Boolean, Integer, String - from pony.orm import db_session from tribler.core.components.gigachannel.community.gigachannel_community import GigaChannelCommunity @@ -28,7 +23,7 @@ from tribler.core.components.restapi.rest.schema import HandledErrorSchema from tribler.core.utilities.simpledefs import CHANNEL_STATE from tribler.core.utilities.unicode import hexlify -from tribler.core.utilities.utilities import froze_it, is_infohash, parse_magnetlink +from tribler.core.utilities.utilities import froze_it, parse_magnetlink ERROR_INVALID_MAGNET_LINK = "Invalid magnet link: %s" diff --git a/src/tribler/core/components/metadata_store/restapi/remote_query_endpoint.py b/src/tribler/core/components/metadata_store/restapi/remote_query_endpoint.py index 87fa1ab3428..3951bfb3129 100644 --- a/src/tribler/core/components/metadata_store/restapi/remote_query_endpoint.py +++ b/src/tribler/core/components/metadata_store/restapi/remote_query_endpoint.py @@ -2,13 +2,9 @@ from binascii import unhexlify from aiohttp import web - from aiohttp_apispec import docs, querystring_schema - from ipv8.REST.schema import schema - from marshmallow.fields import String - from pony.orm import db_session from tribler.core.components.gigachannel.community.gigachannel_community import GigaChannelCommunity @@ -25,7 +21,7 @@ class RemoteQueryEndpoint(MetadataEndpointBase): This endpoint fires a remote search in the IPv8 GigaChannel Community. """ - def __init__(self, gigachannel_community: GigaChannelCommunity, *args, **kwargs): + def __init__(self, gigachannel_community: GigaChannelCommunity, *args, **kwargs): MetadataEndpointBase.__init__(self, *args, **kwargs) self.gigachannel_community = gigachannel_community diff --git a/src/tribler/core/components/metadata_store/restapi/search_endpoint.py b/src/tribler/core/components/metadata_store/restapi/search_endpoint.py index be79578160f..4ea00c95d4a 100644 --- a/src/tribler/core/components/metadata_store/restapi/search_endpoint.py +++ b/src/tribler/core/components/metadata_store/restapi/search_endpoint.py @@ -14,7 +14,6 @@ from tribler.core.components.metadata_store.restapi.metadata_endpoint import MetadataEndpointBase from tribler.core.components.metadata_store.restapi.metadata_schema import MetadataParameters, MetadataSchema from tribler.core.components.restapi.rest.rest_endpoint import HTTP_BAD_REQUEST, RESTResponse -from tribler.core.components.knowledge.db.knowledge_db import ResourceType from tribler.core.utilities.pony_utils import run_threaded from tribler.core.utilities.utilities import froze_it diff --git a/src/tribler/core/components/metadata_store/restapi/tests/conftest.py b/src/tribler/core/components/metadata_store/restapi/tests/conftest.py index 6d5da68b940..56d7d5fbc6c 100644 --- a/src/tribler/core/components/metadata_store/restapi/tests/conftest.py +++ b/src/tribler/core/components/metadata_store/restapi/tests/conftest.py @@ -1,12 +1,10 @@ import hashlib from time import time +import pytest from ipv8.keyvault.crypto import default_eccrypto - from pony.orm import db_session -import pytest - from tribler.core.components.metadata_store.db.orm_bindings.channel_node import NEW from tribler.core.components.metadata_store.utils import tag_torrent from tribler.core.utilities.utilities import random_infohash diff --git a/src/tribler/core/components/metadata_store/restapi/tests/test_channels_endpoint.py b/src/tribler/core/components/metadata_store/restapi/tests/test_channels_endpoint.py index 9ab690b2353..0f3f8b1e54e 100644 --- a/src/tribler/core/components/metadata_store/restapi/tests/test_channels_endpoint.py +++ b/src/tribler/core/components/metadata_store/restapi/tests/test_channels_endpoint.py @@ -3,15 +3,12 @@ from binascii import unhexlify from unittest.mock import Mock, patch +import pytest from aiohttp.web_app import Application - from ipv8.keyvault.crypto import default_eccrypto from ipv8.util import succeed - from pony.orm import db_session -import pytest - from tribler.core.components.gigachannel.community.gigachannel_community import NoChannelSourcesException from tribler.core.components.knowledge.db.knowledge_db import ResourceType from tribler.core.components.libtorrent.torrentdef import TorrentDef diff --git a/src/tribler/core/components/metadata_store/restapi/tests/test_remote_query_endpoint.py b/src/tribler/core/components/metadata_store/restapi/tests/test_remote_query_endpoint.py index a5fa83c2559..fc0676a1a6e 100644 --- a/src/tribler/core/components/metadata_store/restapi/tests/test_remote_query_endpoint.py +++ b/src/tribler/core/components/metadata_store/restapi/tests/test_remote_query_endpoint.py @@ -1,15 +1,12 @@ import uuid from unittest.mock import Mock +import pytest from aiohttp.web_app import Application - from ipv8.keyvault.crypto import default_eccrypto from ipv8.peer import Peer - from pony.orm import db_session -import pytest - from tribler.core.components.gigachannel.community.gigachannel_community import ChannelsPeersMapping from tribler.core.components.metadata_store.restapi.remote_query_endpoint import RemoteQueryEndpoint from tribler.core.components.restapi.rest.base_api_test import do_request @@ -17,6 +14,7 @@ from tribler.core.utilities.unicode import hexlify from tribler.core.utilities.utilities import random_infohash + # pylint: disable=unused-argument @@ -71,7 +69,8 @@ def mock_send(**kwargs): assert hexlify(sent['channel_pk']) == channel_pk -async def test_get_channels_peers(rest_api, endpoint, metadata_store, mock_gigachannel_community): # pylint: disable=W0621, C0321 +async def test_get_channels_peers(rest_api, endpoint, metadata_store, + mock_gigachannel_community): # pylint: disable=W0621, C0321 """ Test getting debug info about the state of channels to peers mapping """ diff --git a/src/tribler/core/components/metadata_store/tests/gen_test_data.py b/src/tribler/core/components/metadata_store/tests/gen_test_data.py index 1608fa1ed4a..e56001f463f 100644 --- a/src/tribler/core/components/metadata_store/tests/gen_test_data.py +++ b/src/tribler/core/components/metadata_store/tests/gen_test_data.py @@ -3,7 +3,6 @@ from datetime import datetime from ipv8.keyvault.crypto import default_eccrypto - from pony.orm import db_session from tribler.core.components.libtorrent.torrentdef import TorrentDef @@ -24,7 +23,6 @@ my_key = default_eccrypto.generate_key("curve25519") - ALL_PRINTABLE_CHARS = ''.join(tuple(chr(i) for i in range(32, 0x110000) if chr(i).isprintable())) diff --git a/src/tribler/core/components/metadata_store/tests/test_channel_download.py b/src/tribler/core/components/metadata_store/tests/test_channel_download.py index a771e663d85..aa9b165a805 100644 --- a/src/tribler/core/components/metadata_store/tests/test_channel_download.py +++ b/src/tribler/core/components/metadata_store/tests/test_channel_download.py @@ -57,7 +57,7 @@ async def gigachannel_manager(metadata_store, download_manager): async def test_channel_update_and_download( - channel_tdef, channel_seeder, metadata_store, download_manager, gigachannel_manager + channel_tdef, channel_seeder, metadata_store, download_manager, gigachannel_manager ): """ Test whether we can successfully update a channel and download the new version diff --git a/src/tribler/core/components/metadata_store/tests/test_metadata.py b/src/tribler/core/components/metadata_store/tests/test_metadata.py index 434c28ab94d..299fe33e7ef 100644 --- a/src/tribler/core/components/metadata_store/tests/test_metadata.py +++ b/src/tribler/core/components/metadata_store/tests/test_metadata.py @@ -1,11 +1,8 @@ +import pytest from ipv8.keyvault.crypto import default_eccrypto - from pony import orm from pony.orm import db_session -import pytest - -from tribler.core.exceptions import InvalidChannelNodeException, InvalidSignatureException from tribler.core.components.metadata_store.db.serialization import ( CHANNEL_NODE, ChannelNodePayload, @@ -13,6 +10,7 @@ NULL_KEY, NULL_SIG, ) +from tribler.core.exceptions import InvalidChannelNodeException, InvalidSignatureException from tribler.core.utilities.unicode import hexlify diff --git a/src/tribler/core/components/metadata_store/tests/test_metadata_store_component.py b/src/tribler/core/components/metadata_store/tests/test_metadata_store_component.py index 20bb7eec1ac..fdde51ffe50 100644 --- a/src/tribler/core/components/metadata_store/tests/test_metadata_store_component.py +++ b/src/tribler/core/components/metadata_store/tests/test_metadata_store_component.py @@ -1,10 +1,9 @@ -import pytest - -from tribler.core.components.session import Session from tribler.core.components.ipv8.ipv8_component import Ipv8Component from tribler.core.components.key.key_component import KeyComponent -from tribler.core.components.metadata_store.metadata_store_component import MetadataStoreComponent from tribler.core.components.knowledge.knowledge_component import KnowledgeComponent +from tribler.core.components.metadata_store.metadata_store_component import MetadataStoreComponent +from tribler.core.components.session import Session + # pylint: disable=protected-access diff --git a/src/tribler/core/components/metadata_store/utils.py b/src/tribler/core/components/metadata_store/utils.py index de799e72f71..53636ae45eb 100644 --- a/src/tribler/core/components/metadata_store/utils.py +++ b/src/tribler/core/components/metadata_store/utils.py @@ -5,10 +5,10 @@ from ipv8.keyvault.crypto import default_eccrypto from pony.orm import db_session -from tribler.core.components.metadata_store.db.store import MetadataStore from tribler.core.components.knowledge.community.knowledge_payload import StatementOperation -from tribler.core.components.knowledge.db.knowledge_db import Operation, ResourceType, KnowledgeDatabase +from tribler.core.components.knowledge.db.knowledge_db import KnowledgeDatabase, Operation, ResourceType from tribler.core.components.knowledge.knowledge_constants import MIN_RESOURCE_LENGTH +from tribler.core.components.metadata_store.db.store import MetadataStore from tribler.core.tests.tools.common import PNG_FILE from tribler.core.utilities.unicode import hexlify from tribler.core.utilities.utilities import random_infohash diff --git a/src/tribler/core/components/payout/payout_component.py b/src/tribler/core/components/payout/payout_component.py index 9456a7c6c41..4a6ceee29f6 100644 --- a/src/tribler/core/components/payout/payout_component.py +++ b/src/tribler/core/components/payout/payout_component.py @@ -28,7 +28,6 @@ async def run(self): self.session.notifier.add_observer(notifications.peer_disconnected, self.payout_manager.on_peer_disconnected) self.session.notifier.add_observer(notifications.tribler_torrent_peer_update, self.payout_manager.update_peer) - async def shutdown(self): await super().shutdown() if self.payout_manager: diff --git a/src/tribler/core/components/payout/tests/test_payout_component.py b/src/tribler/core/components/payout/tests/test_payout_component.py index fc0ed41e475..4786a6355dc 100644 --- a/src/tribler/core/components/payout/tests/test_payout_component.py +++ b/src/tribler/core/components/payout/tests/test_payout_component.py @@ -1,11 +1,10 @@ # pylint: disable=protected-access -import pytest from tribler.core.components.bandwidth_accounting.bandwidth_accounting_component import BandwidthAccountingComponent -from tribler.core.components.session import Session from tribler.core.components.ipv8.ipv8_component import Ipv8Component from tribler.core.components.key.key_component import KeyComponent from tribler.core.components.payout.payout_component import PayoutComponent +from tribler.core.components.session import Session async def test_payout_component(tribler_config): diff --git a/src/tribler/core/components/payout/tests/test_payout_manager.py b/src/tribler/core/components/payout/tests/test_payout_manager.py index b5ba23fdca8..aa587128a2f 100644 --- a/src/tribler/core/components/payout/tests/test_payout_manager.py +++ b/src/tribler/core/components/payout/tests/test_payout_manager.py @@ -1,8 +1,7 @@ from unittest.mock import Mock -from ipv8.util import succeed - import pytest +from ipv8.util import succeed from tribler.core.components.payout.payout_manager import PayoutManager @@ -43,6 +42,7 @@ async def test_do_payout_dht_error(payout_manager): """ Test whether we are not doing a payout when the DHT lookup fails """ + def err_connect_peer(_): raise RuntimeError("test") @@ -56,6 +56,7 @@ async def test_do_payout_no_dht_peers(payout_manager): """ Test whether we are not doing a payout when there are no peers returned by the DHT """ + def connect_peer(_): return succeed([]) @@ -69,6 +70,7 @@ async def test_do_payout_error(payout_manager): """ Test whether we are not doing a payout when the payout fails """ + def connect_peer(_): return succeed([b"abc"]) diff --git a/src/tribler/core/components/popularity/community/payload.py b/src/tribler/core/components/popularity/community/payload.py index c53411bd1de..74956f9f075 100644 --- a/src/tribler/core/components/popularity/community/payload.py +++ b/src/tribler/core/components/popularity/community/payload.py @@ -18,13 +18,12 @@ def to_tuple(self): @classmethod def from_list_bytes(cls, serialized): - return default_serializer.unpack_serializable_list([cls] * (len(serialized)//cls.length), + return default_serializer.unpack_serializable_list([cls] * (len(serialized) // cls.length), serialized, consume_all=False)[:-1] @vp_compile class TorrentsHealthPayload(VariablePayload): - msg_id = 1 format_list = ['I', 'I', 'varlenI', 'raw'] # Number of random torrents, number of torrents checked by you names = ['random_torrents_length', 'torrents_checked_length', 'random_torrents', 'torrents_checked'] diff --git a/src/tribler/core/components/popularity/community/popularity_community.py b/src/tribler/core/components/popularity/community/popularity_community.py index bad582fa216..aad18d6741f 100644 --- a/src/tribler/core/components/popularity/community/popularity_community.py +++ b/src/tribler/core/components/popularity/community/popularity_community.py @@ -15,7 +15,6 @@ from tribler.core.utilities.unicode import hexlify from tribler.core.utilities.utilities import get_normally_distributed_positive_integers - if TYPE_CHECKING: from tribler.core.components.torrent_checker.torrent_checker.torrent_checker import TorrentChecker diff --git a/src/tribler/core/components/popularity/community/tests/test_popularity_community.py b/src/tribler/core/components/popularity/community/tests/test_popularity_community.py index 650de81c1af..78415f61ed8 100644 --- a/src/tribler/core/components/popularity/community/tests/test_popularity_community.py +++ b/src/tribler/core/components/popularity/community/tests/test_popularity_community.py @@ -6,7 +6,6 @@ from ipv8.keyvault.crypto import default_eccrypto from ipv8.test.base import TestBase from ipv8.test.mocking.ipv8 import MockIPv8 - from pony.orm import db_session from tribler.core.components.metadata_store.db.store import MetadataStore @@ -25,6 +24,7 @@ def _generate_single_checked_torrent(status: str = None) -> HealthInfo: POPULAR -> Peers: [101, 1000] DEFAULT -> peers: [1, 100] # alive """ + def get_peers_for(health_status): if health_status == 'DEAD': return 0 diff --git a/src/tribler/core/components/popularity/community/tests/test_version_community_mixin.py b/src/tribler/core/components/popularity/community/tests/test_version_community_mixin.py index 74588171304..57d788458c8 100644 --- a/src/tribler/core/components/popularity/community/tests/test_version_community_mixin.py +++ b/src/tribler/core/components/popularity/community/tests/test_version_community_mixin.py @@ -6,7 +6,8 @@ from ipv8.messaging.serialization import default_serializer from ipv8.test.base import TestBase from ipv8.test.mocking.ipv8 import MockIPv8 -from tribler.core.components.popularity.community.version_community_mixin import VersionResponse, VersionCommunityMixin + +from tribler.core.components.popularity.community.version_community_mixin import VersionCommunityMixin, VersionResponse from tribler.core.version import version_id diff --git a/src/tribler/core/components/popularity/community/version_community_mixin.py b/src/tribler/core/components/popularity/community/version_community_mixin.py index d87a119cccf..a6314d4b543 100644 --- a/src/tribler/core/components/popularity/community/version_community_mixin.py +++ b/src/tribler/core/components/popularity/community/version_community_mixin.py @@ -2,6 +2,7 @@ from ipv8.lazy_community import lazy_wrapper from ipv8.messaging.lazy_payload import VariablePayload, vp_compile + from tribler.core.version import version_id diff --git a/src/tribler/core/components/popularity/popularity_component.py b/src/tribler/core/components/popularity/popularity_component.py index f1d1058def1..bbc54a5ac86 100644 --- a/src/tribler/core/components/popularity/popularity_component.py +++ b/src/tribler/core/components/popularity/popularity_component.py @@ -4,9 +4,9 @@ from tribler.core.components.gigachannel.community.sync_strategy import RemovePeers from tribler.core.components.ipv8.ipv8_component import INFINITE, Ipv8Component from tribler.core.components.metadata_store.metadata_store_component import MetadataStoreComponent +from tribler.core.components.popularity.community.popularity_community import PopularityCommunity from tribler.core.components.reporter.reporter_component import ReporterComponent from tribler.core.components.torrent_checker.torrent_checker_component import TorrentCheckerComponent -from tribler.core.components.popularity.community.popularity_community import PopularityCommunity class PopularityComponent(Component): diff --git a/src/tribler/core/components/popularity/tests/test_popularity_component.py b/src/tribler/core/components/popularity/tests/test_popularity_component.py index 822493bf8d0..b267d3f4eb2 100644 --- a/src/tribler/core/components/popularity/tests/test_popularity_component.py +++ b/src/tribler/core/components/popularity/tests/test_popularity_component.py @@ -1,11 +1,11 @@ from tribler.core.components.ipv8.ipv8_component import Ipv8Component from tribler.core.components.key.key_component import KeyComponent +from tribler.core.components.knowledge.knowledge_component import KnowledgeComponent from tribler.core.components.libtorrent.libtorrent_component import LibtorrentComponent from tribler.core.components.metadata_store.metadata_store_component import MetadataStoreComponent from tribler.core.components.popularity.popularity_component import PopularityComponent from tribler.core.components.session import Session from tribler.core.components.socks_servers.socks_servers_component import SocksServersComponent -from tribler.core.components.knowledge.knowledge_component import KnowledgeComponent from tribler.core.components.torrent_checker.torrent_checker_component import TorrentCheckerComponent diff --git a/src/tribler/core/components/reporter/tests/test_exception_handler.py b/src/tribler/core/components/reporter/tests/test_exception_handler.py index ee981efa582..1835d0040b9 100644 --- a/src/tribler/core/components/reporter/tests/test_exception_handler.py +++ b/src/tribler/core/components/reporter/tests/test_exception_handler.py @@ -7,6 +7,7 @@ from tribler.core.sentry_reporter import sentry_reporter from tribler.core.sentry_reporter.sentry_reporter import SentryReporter + # pylint: disable=protected-access, redefined-outer-name # fmt: off diff --git a/src/tribler/core/components/restapi/tests/test_restapi_component.py b/src/tribler/core/components/restapi/tests/test_restapi_component.py index 3bb97a23fc4..5854193a372 100644 --- a/src/tribler/core/components/restapi/tests/test_restapi_component.py +++ b/src/tribler/core/components/restapi/tests/test_restapi_component.py @@ -54,6 +54,7 @@ def rest_component(): component.root_endpoint = MagicMock() return component + def test_maybe_add_check_args(rest_component, endpoint_cls): # test that in case `*args` in `maybe_add` function contains `NoneComponent` instance # no root_endpoint methods are called diff --git a/src/tribler/core/components/socks_servers/socks5/conversion.py b/src/tribler/core/components/socks_servers/socks5/conversion.py index 9b1ed3d935d..3147059c36f 100644 --- a/src/tribler/core/components/socks_servers/socks5/conversion.py +++ b/src/tribler/core/components/socks_servers/socks5/conversion.py @@ -30,7 +30,6 @@ REP_COMMAND_NOT_SUPPORTED = 0x07 REP_ADDRESS_TYPE_NOT_SUPPORTED = 0x08 - logger = logging.getLogger(__name__) diff --git a/src/tribler/core/components/socks_servers/socks5/server.py b/src/tribler/core/components/socks_servers/socks5/server.py index 27153e94961..a0ecd8698b8 100644 --- a/src/tribler/core/components/socks_servers/socks5/server.py +++ b/src/tribler/core/components/socks_servers/socks5/server.py @@ -22,10 +22,12 @@ async def start(self): """ Start the socks5 server by listening on the specified TCP ports. """ + def build_protocol(): socks5connection = Socks5Connection(self) self.sessions.append(socks5connection) return socks5connection + self.server = await get_event_loop().create_server(build_protocol, '127.0.0.1', self.port) server_socket = self.server.sockets[0] _, bind_port = server_socket.getsockname()[:2] diff --git a/src/tribler/core/components/socks_servers/socks5/tests/test_conversion.py b/src/tribler/core/components/socks_servers/socks5/tests/test_conversion.py index 2a00d26284b..bcf536a558a 100644 --- a/src/tribler/core/components/socks_servers/socks5/tests/test_conversion.py +++ b/src/tribler/core/components/socks_servers/socks5/tests/test_conversion.py @@ -1,10 +1,9 @@ import struct +import pytest from ipv8.messaging.interfaces.udp.endpoint import DomainAddress from ipv8.messaging.serialization import PackError -import pytest - from tribler.core.components.socks_servers.socks5.conversion import ( CommandRequest, CommandResponse, diff --git a/src/tribler/core/components/socks_servers/socks5/tests/test_server.py b/src/tribler/core/components/socks_servers/socks5/tests/test_server.py index ac7ccf5ef22..7ebbbbe9335 100644 --- a/src/tribler/core/components/socks_servers/socks5/tests/test_server.py +++ b/src/tribler/core/components/socks_servers/socks5/tests/test_server.py @@ -1,9 +1,8 @@ from asyncio import sleep from unittest.mock import Mock -from aiohttp import ClientSession - import pytest +from aiohttp import ClientSession from tribler.core.components.socks_servers.socks5.aiohttp_connector import Socks5Connector from tribler.core.components.socks_servers.socks5.client import Socks5Client, Socks5Error @@ -106,6 +105,7 @@ def return_data(conn, target, _): assert target == ('localhost', 80) conn.transport.write(b'HTTP/1.1 200\r\nContent-Type: text/html\r\n\r\nHello') conn.transport.close() + socks5_server.output_stream.on_socks5_tcp_data = return_data async with ClientSession(connector=Socks5Connector(('127.0.0.1', socks5_server.port))) as session: diff --git a/src/tribler/core/components/torrent_checker/tests/test_torrent_checker_component.py b/src/tribler/core/components/torrent_checker/tests/test_torrent_checker_component.py index f2809ce067e..28ef90bb1de 100644 --- a/src/tribler/core/components/torrent_checker/tests/test_torrent_checker_component.py +++ b/src/tribler/core/components/torrent_checker/tests/test_torrent_checker_component.py @@ -1,12 +1,10 @@ -import pytest - -from tribler.core.components.session import Session from tribler.core.components.ipv8.ipv8_component import Ipv8Component from tribler.core.components.key.key_component import KeyComponent +from tribler.core.components.knowledge.knowledge_component import KnowledgeComponent from tribler.core.components.libtorrent.libtorrent_component import LibtorrentComponent from tribler.core.components.metadata_store.metadata_store_component import MetadataStoreComponent +from tribler.core.components.session import Session from tribler.core.components.socks_servers.socks_servers_component import SocksServersComponent -from tribler.core.components.knowledge.knowledge_component import KnowledgeComponent from tribler.core.components.torrent_checker.torrent_checker_component import TorrentCheckerComponent diff --git a/src/tribler/core/components/torrent_checker/torrent_checker/dataclasses.py b/src/tribler/core/components/torrent_checker/torrent_checker/dataclasses.py index 18dbab65ce0..7cb15dbe206 100644 --- a/src/tribler/core/components/torrent_checker/torrent_checker/dataclasses.py +++ b/src/tribler/core/components/torrent_checker/torrent_checker/dataclasses.py @@ -8,7 +8,6 @@ from tribler.core.utilities.unicode import hexlify - MINUTE = 60 HOUR = MINUTE * 60 TOLERABLE_TIME_DRIFT = MINUTE # When receiving health from another peer, how far the timestamp can be in the future? diff --git a/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_health_info_should_update.py b/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_health_info_should_update.py index 8e5f169e771..ff633a402a1 100644 --- a/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_health_info_should_update.py +++ b/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_health_info_should_update.py @@ -75,11 +75,11 @@ def test_more_recent_more_seeders(): t = now() - 100 prev_health = HealthInfo(INFOHASH, 1, 2, last_check=t) - health = HealthInfo(INFOHASH, 2, 1, last_check=t-1) + health = HealthInfo(INFOHASH, 2, 1, last_check=t - 1) assert abs(prev_health.last_check - health.last_check) <= TOLERABLE_TIME_DRIFT assert health.should_replace(prev_health) - health.last_check = t+1 + health.last_check = t + 1 assert abs(prev_health.last_check - health.last_check) <= TOLERABLE_TIME_DRIFT assert health.should_replace(prev_health) @@ -88,11 +88,11 @@ def test_more_recent_fewer_seeders(): t = now() - 100 prev_health = HealthInfo(INFOHASH, 2, 1, last_check=t) - health = HealthInfo(INFOHASH, last_check=t-1, seeders=1, leechers=2) + health = HealthInfo(INFOHASH, last_check=t - 1, seeders=1, leechers=2) assert abs(prev_health.last_check - health.last_check) <= TOLERABLE_TIME_DRIFT assert not health.should_replace(prev_health) - health.last_check = t+1 + health.last_check = t + 1 assert abs(prev_health.last_check - health.last_check) <= TOLERABLE_TIME_DRIFT assert not health.should_replace(prev_health) diff --git a/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_torrentchecker.py b/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_torrentchecker.py index d054a8daccd..a72837e5845 100644 --- a/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_torrentchecker.py +++ b/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_torrentchecker.py @@ -14,12 +14,12 @@ import tribler.core.components.torrent_checker.torrent_checker.torrent_checker as torrent_checker_module from tribler.core.components.torrent_checker.torrent_checker.dataclasses import HealthInfo, TOLERABLE_TIME_DRIFT, \ TrackerResponse -from tribler.core.components.torrent_checker.torrent_checker.utils import aggregate_responses_for_infohash, \ - filter_non_exceptions from tribler.core.components.torrent_checker.torrent_checker.torrent_checker import TorrentChecker from tribler.core.components.torrent_checker.torrent_checker.torrentchecker_session import \ HttpTrackerSession, UdpSocketManager from tribler.core.components.torrent_checker.torrent_checker.tracker_manager import TrackerManager +from tribler.core.components.torrent_checker.torrent_checker.utils import aggregate_responses_for_infohash, \ + filter_non_exceptions # pylint: disable=protected-access diff --git a/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_torrentchecker_session.py b/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_torrentchecker_session.py index 20d9529f1ed..923ffd5567f 100644 --- a/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_torrentchecker_session.py +++ b/src/tribler/core/components/torrent_checker/torrent_checker/tests/test_torrentchecker_session.py @@ -1,6 +1,5 @@ import socket import struct -import time from asyncio import CancelledError, DatagramProtocol, Future, ensure_future, get_event_loop, sleep, start_server from unittest.mock import Mock diff --git a/src/tribler/core/components/torrent_checker/torrent_checker/torrent_checker.py b/src/tribler/core/components/torrent_checker/torrent_checker/torrent_checker.py index cc7b7bfcef7..0125c2c08a2 100644 --- a/src/tribler/core/components/torrent_checker/torrent_checker/torrent_checker.py +++ b/src/tribler/core/components/torrent_checker/torrent_checker/torrent_checker.py @@ -17,11 +17,11 @@ from tribler.core.components.torrent_checker.torrent_checker import DHT from tribler.core.components.torrent_checker.torrent_checker.dataclasses import HEALTH_FRESHNESS_SECONDS, HealthInfo, \ TrackerResponse -from tribler.core.components.torrent_checker.torrent_checker.utils import aggregate_responses_for_infohash, \ - filter_non_exceptions, gather_coros from tribler.core.components.torrent_checker.torrent_checker.torrentchecker_session import \ FakeBep33DHTSession, FakeDHTSession, TrackerSession, UdpSocketManager, create_tracker_session from tribler.core.components.torrent_checker.torrent_checker.tracker_manager import MAX_TRACKER_FAILURES, TrackerManager +from tribler.core.components.torrent_checker.torrent_checker.utils import aggregate_responses_for_infohash, \ + filter_non_exceptions, gather_coros from tribler.core.config.tribler_config import TriblerConfig from tribler.core.utilities.notifier import Notifier from tribler.core.utilities.tracker_utils import MalformedTrackerURLException @@ -175,7 +175,7 @@ async def get_tracker_response(self, session: TrackerSession) -> TrackerResponse await self.clean_session(session) t2 = time.time() - self._logger.info(f"Got response from {session.__class__.__name__} in {t2-t1:.3f} seconds: {result}") + self._logger.info(f"Got response from {session.__class__.__name__} in {t2 - t1:.3f} seconds: {result}") with db_session: for health in result.torrent_health_list: @@ -199,7 +199,7 @@ def load_torrents_checked_from_db(self) -> Dict[bytes, HealthInfo]: last_fresh_time = now - HEALTH_FRESHNESS_SECONDS checked_torrents = list(self.mds.TorrentState .select(lambda g: g.has_data and g.self_checked - and between(g.last_check, last_fresh_time, now)) + and between(g.last_check, last_fresh_time, now)) .order_by(lambda g: (desc(g.seeders), g.last_check)) .limit(TORRENTS_CHECKED_RETURN_SIZE)) diff --git a/src/tribler/core/components/torrent_checker/torrent_checker/utils.py b/src/tribler/core/components/torrent_checker/torrent_checker/utils.py index 30dc8857ebc..c1250d2a907 100644 --- a/src/tribler/core/components/torrent_checker/torrent_checker/utils.py +++ b/src/tribler/core/components/torrent_checker/torrent_checker/utils.py @@ -1,11 +1,10 @@ from __future__ import annotations from asyncio import gather -from typing import Awaitable, Dict, Iterable, List, TypeVar, Union, cast +from typing import Awaitable, Iterable, List, TypeVar, Union, cast from tribler.core.components.torrent_checker.torrent_checker.dataclasses import HealthInfo, TrackerResponse - T = TypeVar("T") diff --git a/src/tribler/core/components/tunnel/tests/test_dispatcher.py b/src/tribler/core/components/tunnel/tests/test_dispatcher.py index 063cc667cc6..c31c5cea7e2 100644 --- a/src/tribler/core/components/tunnel/tests/test_dispatcher.py +++ b/src/tribler/core/components/tunnel/tests/test_dispatcher.py @@ -1,10 +1,9 @@ from unittest.mock import Mock +import pytest from ipv8.messaging.anonymization.tunnel import CIRCUIT_STATE_EXTENDING, CIRCUIT_STATE_READY, CIRCUIT_TYPE_DATA from ipv8.util import succeed -import pytest - from tribler.core.components.tunnel.community.dispatcher import TunnelDispatcher diff --git a/src/tribler/core/components/tunnel/tests/test_tunnel_component.py b/src/tribler/core/components/tunnel/tests/test_tunnel_component.py index edcfded4d76..c09a3d6590a 100644 --- a/src/tribler/core/components/tunnel/tests/test_tunnel_component.py +++ b/src/tribler/core/components/tunnel/tests/test_tunnel_component.py @@ -1,8 +1,6 @@ -import pytest - -from tribler.core.components.session import Session from tribler.core.components.ipv8.ipv8_component import Ipv8Component from tribler.core.components.key.key_component import KeyComponent +from tribler.core.components.session import Session from tribler.core.components.tunnel.tunnel_component import TunnelsComponent diff --git a/src/tribler/core/components/watch_folder/settings.py b/src/tribler/core/components/watch_folder/settings.py index 11096c15975..6f0c677d448 100644 --- a/src/tribler/core/components/watch_folder/settings.py +++ b/src/tribler/core/components/watch_folder/settings.py @@ -1,5 +1,6 @@ from tribler.core.config.tribler_config_section import TriblerConfigSection + # pylint: disable=no-self-argument diff --git a/src/tribler/core/config/tests/test_tribler_config_section.py b/src/tribler/core/config/tests/test_tribler_config_section.py index c804940484e..e1db4cb5d73 100644 --- a/src/tribler/core/config/tests/test_tribler_config_section.py +++ b/src/tribler/core/config/tests/test_tribler_config_section.py @@ -1,8 +1,6 @@ from pathlib import Path from typing import Optional -import pytest - from tribler.core.config.tribler_config_section import TriblerConfigSection diff --git a/src/tribler/core/config/tribler_config_section.py b/src/tribler/core/config/tribler_config_section.py index b2c10f5f595..d56562e65bf 100644 --- a/src/tribler/core/config/tribler_config_section.py +++ b/src/tribler/core/config/tribler_config_section.py @@ -12,6 +12,7 @@ class TriblerConfigSection(BaseSettings): We are waiting https://github.com/samuelcolvin/pydantic/pull/2625 for proper and native manipulations with relative and absolute paths. """ + class Config: extra = Extra.ignore diff --git a/src/tribler/core/logger/logger.py b/src/tribler/core/logger/logger.py index 57575b4a6ca..9ce3fa2f368 100644 --- a/src/tribler/core/logger/logger.py +++ b/src/tribler/core/logger/logger.py @@ -48,6 +48,7 @@ def setup_logging(app_mode, log_dir: Path, config_path: Path): """ Setup logging configuration with the given YAML file. """ + def record_factory(*args, **kwargs): record = log_factory(*args, **kwargs) record.app_mode = app_mode diff --git a/src/tribler/core/logger/logger.yaml b/src/tribler/core/logger/logger.yaml index e56852eaf94..272aae8f411 100644 --- a/src/tribler/core/logger/logger.yaml +++ b/src/tribler/core/logger/logger.yaml @@ -1,65 +1,65 @@ version: 1 disable_existing_loggers: false filters: - stdout_filter: - () : tribler.core.logger.logger.StdoutFilter + stdout_filter: + (): tribler.core.logger.logger.StdoutFilter # Logging formatter formatters: - standard: - format: "[%(app_mode)s PID:%(process)d] %(asctime)s - %(levelname)s - %(name)s(%(lineno)d) - %(message)s" - error: - format: "[%(app_mode)s PID:%(process)d] %(asctime)s - %(levelname)s <%(module)s:%(lineno)d> %(name)s.%(funcName)s(): %(message)s" + standard: + format: "[%(app_mode)s PID:%(process)d] %(asctime)s - %(levelname)s - %(name)s(%(lineno)d) - %(message)s" + error: + format: "[%(app_mode)s PID:%(process)d] %(asctime)s - %(levelname)s <%(module)s:%(lineno)d> %(name)s.%(funcName)s(): %(message)s" # Logging handlers handlers: - info_file_handler: - class: logging.handlers.RotatingFileHandler - level: INFO - formatter: standard - filename: TRIBLER_INFO_LOG_FILE - maxBytes: 102400 # 100KB - backupCount: 1 - encoding: utf8 + info_file_handler: + class: logging.handlers.RotatingFileHandler + level: INFO + formatter: standard + filename: TRIBLER_INFO_LOG_FILE + maxBytes: 102400 # 100KB + backupCount: 1 + encoding: utf8 - info_memory_handler: - class: logging.handlers.MemoryHandler - level: INFO - target: info_file_handler - capacity: 1024 + info_memory_handler: + class: logging.handlers.MemoryHandler + level: INFO + target: info_file_handler + capacity: 1024 - error_file_handler: - class: logging.handlers.RotatingFileHandler - level: ERROR - formatter: error - filename: TRIBLER_ERROR_LOG_FILE - maxBytes: 102400 # 100KB - backupCount: 1 - encoding: utf8 + error_file_handler: + class: logging.handlers.RotatingFileHandler + level: ERROR + formatter: error + filename: TRIBLER_ERROR_LOG_FILE + maxBytes: 102400 # 100KB + backupCount: 1 + encoding: utf8 - error_memory_handler: - class: logging.handlers.MemoryHandler - level: ERROR - target: error_file_handler - capacity: 1024 + error_memory_handler: + class: logging.handlers.MemoryHandler + level: ERROR + target: error_file_handler + capacity: 1024 - stdout_handler: - class: logging.StreamHandler - level: INFO - formatter: standard - filters: [stdout_filter] - stream: ext://tribler.core.logger.logger_streams.stdout_wrapper + stdout_handler: + class: logging.StreamHandler + level: INFO + formatter: standard + filters: [ stdout_filter ] + stream: ext://tribler.core.logger.logger_streams.stdout_wrapper - stderr_handler: - class: logging.StreamHandler - level: ERROR - formatter: error - stream: ext://tribler.core.logger.logger_streams.stderr_wrapper + stderr_handler: + class: logging.StreamHandler + level: ERROR + formatter: error + stream: ext://tribler.core.logger.logger_streams.stderr_wrapper # Root Logger Configuration root: - level: NOTSET - handlers: [stdout_handler, stderr_handler, info_memory_handler, error_memory_handler] + level: NOTSET + handlers: [ stdout_handler, stderr_handler, info_memory_handler, error_memory_handler ] # Module level configuration: # The following is an example of how you can reduce the verbosity of some specific loggers: diff --git a/src/tribler/core/setup.py b/src/tribler/core/setup.py index 4b87eb06603..5df208cef5f 100644 --- a/src/tribler/core/setup.py +++ b/src/tribler/core/setup.py @@ -1,4 +1,5 @@ from tribler.core.setuptools import find_packages, setup + from tribler.core.version import version_id with open('README.rst') as f: diff --git a/src/tribler/core/start_core.py b/src/tribler/core/start_core.py index 0ee3db3d213..51d99eafc57 100644 --- a/src/tribler/core/start_core.py +++ b/src/tribler/core/start_core.py @@ -20,6 +20,7 @@ from tribler.core.components.gui_process_watcher.gui_process_watcher_component import GuiProcessWatcherComponent from tribler.core.components.ipv8.ipv8_component import Ipv8Component from tribler.core.components.key.key_component import KeyComponent +from tribler.core.components.knowledge.knowledge_component import KnowledgeComponent from tribler.core.components.libtorrent.libtorrent_component import LibtorrentComponent from tribler.core.components.metadata_store.metadata_store_component import MetadataStoreComponent from tribler.core.components.payout.payout_component import PayoutComponent @@ -30,7 +31,6 @@ from tribler.core.components.restapi.restapi_component import RESTComponent from tribler.core.components.session import Session from tribler.core.components.socks_servers.socks_servers_component import SocksServersComponent -from tribler.core.components.knowledge.knowledge_component import KnowledgeComponent from tribler.core.components.torrent_checker.torrent_checker_component import TorrentCheckerComponent from tribler.core.components.tunnel.tunnel_component import TunnelsComponent from tribler.core.components.version_check.version_check_component import VersionCheckComponent diff --git a/src/tribler/core/tests/test_configparser.py b/src/tribler/core/tests/test_configparser.py index 3ad11c5c101..abccd4956c7 100644 --- a/src/tribler/core/tests/test_configparser.py +++ b/src/tribler/core/tests/test_configparser.py @@ -6,7 +6,6 @@ from tribler.core.utilities.configparser import CallbackConfigParser from tribler.core.utilities.install_dir import get_lib_path - CONFIG_FILES_DIR = get_lib_path() / "tests/tools/data/config_files/" diff --git a/src/tribler/core/tests/test_search_utils.py b/src/tribler/core/tests/test_search_utils.py index 3832345fa79..dd532d8a15e 100644 --- a/src/tribler/core/tests/test_search_utils.py +++ b/src/tribler/core/tests/test_search_utils.py @@ -2,9 +2,8 @@ import pytest -from tribler.core.utilities.search_utils import filter_keywords, find_word_and_rotate_title, freshness_rank, item_rank,\ - seeders_rank, split_into_keywords, torrent_rank, title_rank - +from tribler.core.utilities.search_utils import filter_keywords, find_word_and_rotate_title, freshness_rank, item_rank, \ + seeders_rank, split_into_keywords, title_rank, torrent_rank DAY = 60 * 60 * 24 diff --git a/src/tribler/core/tests/tools/tracker/http_tracker.py b/src/tribler/core/tests/tools/tracker/http_tracker.py index 42ded896507..a9390680071 100644 --- a/src/tribler/core/tests/tools/tracker/http_tracker.py +++ b/src/tribler/core/tests/tools/tracker/http_tracker.py @@ -1,6 +1,4 @@ - from aiohttp import web - from libtorrent import bencode from tribler.core.components.restapi.rest.rest_endpoint import HTTP_BAD_REQUEST, RESTResponse diff --git a/src/tribler/core/upgrade/db8_to_db10.py b/src/tribler/core/upgrade/db8_to_db10.py index ead9d0524cf..a6ee17ae250 100644 --- a/src/tribler/core/upgrade/db8_to_db10.py +++ b/src/tribler/core/upgrade/db8_to_db10.py @@ -178,7 +178,7 @@ def index_callback_handler(): index_percentage = calc_progress(t2 - t1, base_duration / 8.0) total_percentage = (index_num * 100.0 + index_percentage) / index_total self.notification_callback(f"recreating indexes\n" - f"{total_percentage:.2f}% done") + f"{total_percentage:.2f}% done") except Exception as e: self._logger.error(f"Error in SQLite callback handler: {type(e).__name__}:{str(e)}") self.shutting_down = True @@ -208,7 +208,7 @@ def fts_callback_handler(): try: t2 = now() self.notification_callback("adding full text search index...\n" - f"{calc_progress(t2 - t1, base_duration):.2f}% done") + f"{calc_progress(t2 - t1, base_duration):.2f}% done") except Exception as e: self._logger.error(f"Error in SQLite callback handler: {type(e).__name__}:{str(e)}") self.shutting_down = True diff --git a/src/tribler/core/utilities/bencodecheck.py b/src/tribler/core/utilities/bencodecheck.py index 7f68c396ea2..e9db516d0d6 100644 --- a/src/tribler/core/utilities/bencodecheck.py +++ b/src/tribler/core/utilities/bencodecheck.py @@ -1,5 +1,3 @@ - - def is_bencoded(x: bytes) -> bool: """ Returns True is x appears to be valid bencoded byte string. diff --git a/src/tribler/core/utilities/dependencies.py b/src/tribler/core/utilities/dependencies.py index af6173f0f20..8c3355260e4 100644 --- a/src/tribler/core/utilities/dependencies.py +++ b/src/tribler/core/utilities/dependencies.py @@ -11,7 +11,6 @@ import tribler - # fmt: off logger = logging.getLogger(__name__) diff --git a/src/tribler/core/utilities/instrumentation.py b/src/tribler/core/utilities/instrumentation.py index ddd9e5ef92d..b21457c3cd2 100644 --- a/src/tribler/core/utilities/instrumentation.py +++ b/src/tribler/core/utilities/instrumentation.py @@ -38,7 +38,6 @@ def synchronized(wrapped, instance, *args, **kwargs): class WatchDog(Thread): - """ Watchdog thread, will periodically check if all registered events are set and clear them. If any if them is still cleared on the next iteration, a big fat diff --git a/src/tribler/core/utilities/limited_ordered_dict.py b/src/tribler/core/utilities/limited_ordered_dict.py index 9471fdcec14..f59e68c8482 100644 --- a/src/tribler/core/utilities/limited_ordered_dict.py +++ b/src/tribler/core/utilities/limited_ordered_dict.py @@ -6,6 +6,7 @@ class LimitedOrderedDict(OrderedDict): If the size of the dict exceeds the limit, the oldest entries will be deleted. """ + def __init__(self, *args, limit: int = 200, **kwargs): self.limit = limit super().__init__(*args, **kwargs) diff --git a/src/tribler/core/utilities/maketorrent.py b/src/tribler/core/utilities/maketorrent.py index 5aef404167a..77a2cabc375 100644 --- a/src/tribler/core/utilities/maketorrent.py +++ b/src/tribler/core/utilities/maketorrent.py @@ -3,7 +3,6 @@ Author(s): Arno Bakker, Bram Cohen """ -from tribler.core.utilities import path_util from tribler.core.utilities.path_util import Path from tribler.core.utilities.unicode import ensure_unicode_detect_encoding diff --git a/src/tribler/core/utilities/notifier.py b/src/tribler/core/utilities/notifier.py index c7b7d2d2843..b5695ac014e 100644 --- a/src/tribler/core/utilities/notifier.py +++ b/src/tribler/core/utilities/notifier.py @@ -5,7 +5,6 @@ from threading import Lock from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, cast - FuncT = TypeVar("FuncT", bound=Callable[..., Any]) @@ -136,7 +135,7 @@ def add_observer(self, topic: FuncT, observer: FuncT, synchronous: Optional[bool """ synchronous = self._check_synchronous(synchronous) - empty = inspect._empty # pylint: disable=protected-access + empty = inspect._empty # pylint: disable=protected-access # ignore types of return values, as during the notification call the return values are ignored topic_signature = inspect.signature(topic).replace(return_annotation=empty) callback_signature = inspect.signature(observer).replace(return_annotation=empty) @@ -199,6 +198,7 @@ def remove_generic_observer(self, observer: Callable): def __getitem__(self, topic: FuncT) -> FuncT: def wrapper(*args, **kwargs): self.notify(topic, *args, **kwargs) + return cast(FuncT, wrapper) def notify_by_topic_name(self, topic_name: str, *args, **kwargs): diff --git a/src/tribler/core/utilities/osutils.py b/src/tribler/core/utilities/osutils.py index 8b7bdd705d9..229104b4048 100644 --- a/src/tribler/core/utilities/osutils.py +++ b/src/tribler/core/utilities/osutils.py @@ -33,24 +33,28 @@ def is_android(): try: from win32com.shell import shell, shellcon + def get_home_dir(): # http://www.mvps.org/access/api/api0054.htm # CSIDL_PROFILE = &H28 # C:\Documents and Settings\username return path_util.Path(shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_PROFILE)) + def get_appstate_dir(): # http://www.mvps.org/access/api/api0054.htm # CSIDL_APPDATA = &H1A # C:\Documents and Settings\username\Application Data return path_util.Path(shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_APPDATA)) + def get_picture_dir(): # http://www.mvps.org/access/api/api0054.htm # CSIDL_MYPICTURES = &H27 # C:\Documents and Settings\username\My Documents\My Pictures return path_util.Path(shell.SHGetSpecialFolderPath(0, 0x27)) + def get_desktop_dir(): # http://www.mvps.org/access/api/api0054.htm # CSIDL_DESKTOPDIRECTORY = &H10 @@ -63,6 +67,7 @@ def get_home_dir(): # This will always succeed on python 3.x return Path("~").expanduser() + def get_appstate_dir(): homedir = get_home_dir() # 5 = XP, 6 = Vista @@ -76,9 +81,11 @@ def get_appstate_dir(): appdir = homedir / "Application Data" return appdir + def get_picture_dir(): return get_home_dir() + def get_desktop_dir(): home = get_home_dir() return home / "Desktop" @@ -89,12 +96,15 @@ def get_desktop_dir(): def get_home_dir(): return Path(str(os.environ['EXTERNAL_STORAGE'])).resolve() + def get_appstate_dir(): return Path(os.environ['ANDROID_PRIVATE'] / '../.Tribler').resolve() + def get_picture_dir(): return get_home_dir() / 'DCIM' + def get_desktop_dir(): return get_home_dir() @@ -104,18 +114,20 @@ def get_desktop_dir(): def get_home_dir(): return Path("~").expanduser() + def get_appstate_dir(): return get_home_dir() + def get_picture_dir(): return get_desktop_dir() + def get_desktop_dir(): home = get_home_dir() desktop = home / "Desktop" return desktop if desktop.exists() else home - invalidwinfilenamechars = '' for i in range(32): invalidwinfilenamechars += chr(i) diff --git a/src/tribler/core/utilities/patch_import.py b/src/tribler/core/utilities/patch_import.py index f6d9f058c82..291f1bff71c 100644 --- a/src/tribler/core/utilities/patch_import.py +++ b/src/tribler/core/utilities/patch_import.py @@ -12,7 +12,6 @@ __all__ = ['patch_import'] - _builtins_import = builtins.__import__ diff --git a/src/tribler/core/utilities/process_manager/__init__.py b/src/tribler/core/utilities/process_manager/__init__.py index b117f4e2f33..f4448fa3d2a 100644 --- a/src/tribler/core/utilities/process_manager/__init__.py +++ b/src/tribler/core/utilities/process_manager/__init__.py @@ -1,3 +1,3 @@ -from tribler.core.utilities.process_manager.process import ProcessKind, TriblerProcess -from tribler.core.utilities.process_manager.manager import get_global_process_manager, ProcessManager,\ +from tribler.core.utilities.process_manager.manager import ProcessManager, get_global_process_manager, \ set_global_process_manager +from tribler.core.utilities.process_manager.process import ProcessKind, TriblerProcess diff --git a/src/tribler/core/utilities/process_manager/manager.py b/src/tribler/core/utilities/process_manager/manager.py index 031913247fe..0c0921dbe36 100644 --- a/src/tribler/core/utilities/process_manager/manager.py +++ b/src/tribler/core/utilities/process_manager/manager.py @@ -3,12 +3,11 @@ import logging import sqlite3 import sys +from contextlib import contextmanager from pathlib import Path from threading import Lock from typing import ContextManager, List, Optional -from contextlib import contextmanager - from tribler.core.utilities.process_manager import sql_scripts from tribler.core.utilities.process_manager.process import ProcessKind, TriblerProcess from tribler.core.utilities.process_manager.utils import with_retry @@ -17,7 +16,6 @@ DB_FILENAME = 'processes.sqlite' - global_process_manager: Optional[ProcessManager] = None _lock = Lock() diff --git a/src/tribler/core/utilities/process_manager/process.py b/src/tribler/core/utilities/process_manager/process.py index ea9a648be0d..f60c4e3e2c3 100644 --- a/src/tribler/core/utilities/process_manager/process.py +++ b/src/tribler/core/utilities/process_manager/process.py @@ -77,7 +77,7 @@ def save(self): def from_row(cls, manager: ProcessManager, row: tuple) -> TriblerProcess: """Constructs an object from the database row""" rowid, row_version, pid, kind, primary, canceled, app_version, started_at, creator_pid, api_port, \ - finished_at, exit_code, error_msg = row + finished_at, exit_code, error_msg = row return TriblerProcess(manager=manager, rowid=rowid, row_version=row_version, pid=pid, kind=ProcessKind(kind), primary=primary, canceled=canceled, app_version=app_version, started_at=started_at, diff --git a/src/tribler/core/utilities/process_manager/tests/test_manager.py b/src/tribler/core/utilities/process_manager/tests/test_manager.py index 55f109706d2..bde44928717 100644 --- a/src/tribler/core/utilities/process_manager/tests/test_manager.py +++ b/src/tribler/core/utilities/process_manager/tests/test_manager.py @@ -1,8 +1,8 @@ import time from unittest.mock import Mock, patch +from tribler.core.utilities.process_manager.manager import ProcessManager, logger from tribler.core.utilities.process_manager.process import ProcessKind, TriblerProcess -from tribler.core.utilities.process_manager.manager import logger, ProcessManager def test_become_primary(process_manager: ProcessManager): diff --git a/src/tribler/core/utilities/process_manager/utils.py b/src/tribler/core/utilities/process_manager/utils.py index 63f1ec9f986..90e1b731c61 100644 --- a/src/tribler/core/utilities/process_manager/utils.py +++ b/src/tribler/core/utilities/process_manager/utils.py @@ -18,6 +18,7 @@ def with_retry(method): re-creates the database structure. The content of the database is not critical for Tribler's functioning, so it is OK for Tribler to re-create it in such cases. """ + @wraps(method) def new_method(self: ClassWithOptionalConnection, *args, **kwargs): if self.connection: diff --git a/src/tribler/core/utilities/sentinels.py b/src/tribler/core/utilities/sentinels.py index 9243a1fb88e..a8d9310b61e 100644 --- a/src/tribler/core/utilities/sentinels.py +++ b/src/tribler/core/utilities/sentinels.py @@ -55,6 +55,7 @@ def sentinel( def __new__(cls): return sentinel + __new__.__qualname__ = f'{class_name}.__new__' cls.__new__ = __new__ @@ -62,7 +63,8 @@ def __new__(cls): if hasattr(_sys, '_getframe'): - def _get_parent_frame(): return _sys._getframe(2) + def _get_parent_frame(): + return _sys._getframe(2) else: # pragma: no cover def _get_parent_frame(): """Return the frame object for the caller's parent stack frame.""" diff --git a/src/tribler/core/utilities/tests/test_dependencies.py b/src/tribler/core/utilities/tests/test_dependencies.py index 27e0cca49be..aab6d42dbc9 100644 --- a/src/tribler/core/utilities/tests/test_dependencies.py +++ b/src/tribler/core/utilities/tests/test_dependencies.py @@ -23,6 +23,7 @@ def test_extract_libraries_from_requirements(): ) assert list(_extract_libraries_from_requirements(text)) == ['PyQt5', 'psutil', 'configobj'] + def test_pip_dependencies_gen(): # check that libraries extracts from file correctly path = Path(tribler.__file__).parent.parent.parent / 'requirements.txt' diff --git a/src/tribler/core/utilities/tests/test_network_utils.py b/src/tribler/core/utilities/tests/test_network_utils.py index 12ad569ec3b..7eb8ae5e140 100644 --- a/src/tribler/core/utilities/tests/test_network_utils.py +++ b/src/tribler/core/utilities/tests/test_network_utils.py @@ -2,6 +2,7 @@ from tribler.core.utilities.network_utils import FreePortNotFoundError, NetworkUtils + # fmt: off @pytest.fixture(name="network_utils") diff --git a/src/tribler/core/utilities/tests/test_notifier.py b/src/tribler/core/utilities/tests/test_notifier.py index 53877bab53c..0032719fc35 100644 --- a/src/tribler/core/utilities/tests/test_notifier.py +++ b/src/tribler/core/utilities/tests/test_notifier.py @@ -88,7 +88,6 @@ async def async1(x: int): with pytest.raises(TypeError, match=r'^Topic and observer cannot be the same function. Got: $'): notifier.add_observer(topic1, topic1) - def observer7(x: int): pass @@ -197,7 +196,7 @@ def generic_2(*args, **kwargs): notifier = Notifier() notifier.add_observer(topic_a, observer_a1) # add an observer notifier.add_observer(topic_a, observer_a1) # adding the same observer multiple times should affect nothing - notifier.add_generic_observer(generic_1) # add a generic observer + notifier.add_generic_observer(generic_1) # add a generic observer with pytest.raises(TypeError): notifier[topic_a](123) @@ -211,7 +210,7 @@ def generic_2(*args, **kwargs): notifier.add_observer(topic_a, observer_a2) # add a second observer to the same topic notifier.add_observer(topic_b, observer_b1) # observer to a different topic - notifier.add_generic_observer(generic_2) # a second generic observer + notifier.add_generic_observer(generic_2) # a second generic observer notifier[topic_a](2, 'bbb') @@ -268,7 +267,7 @@ def generic_2(*args, **kwargs): notifier = Notifier(loop=event_loop) notifier.add_observer(topic_a, observer_a1) # add an observer notifier.add_observer(topic_a, observer_a1) # adding the same observer multiple times should affect nothing - notifier.add_generic_observer(generic_1) # add a generic observer + notifier.add_generic_observer(generic_1) # add a generic observer # An attempt to add the same observer with different `synchronous` option value should raise an error with pytest.raises(NotifierError, match=r'^Cannot register the same observer ' @@ -289,7 +288,7 @@ def generic_2(*args, **kwargs): notifier.add_observer(topic_a, observer_a2) # add a second observer to the same topic notifier.add_observer(topic_b, observer_b1) # observer to a different topic - notifier.add_generic_observer(generic_2) # a second generic observer + notifier.add_generic_observer(generic_2) # a second generic observer notifier[topic_a](2, 'bbb') diff --git a/src/tribler/core/utilities/tests/test_torrent_utils.py b/src/tribler/core/utilities/tests/test_torrent_utils.py index d371014b154..4f2f1f5c219 100644 --- a/src/tribler/core/utilities/tests/test_torrent_utils.py +++ b/src/tribler/core/utilities/tests/test_torrent_utils.py @@ -1,7 +1,5 @@ from unittest.mock import Mock -import pytest - from tribler.core.components.libtorrent.utils.torrent_utils import ( common_prefix, create_torrent_file, diff --git a/src/tribler/core/utilities/tests/test_utilities.py b/src/tribler/core/utilities/tests/test_utilities.py index d1533b83fc5..bcf0483a77a 100644 --- a/src/tribler/core/utilities/tests/test_utilities.py +++ b/src/tribler/core/utilities/tests/test_utilities.py @@ -1,28 +1,18 @@ import binascii -import logging -from unittest.mock import MagicMock, patch, Mock - -from aiohttp import ClientSession +from unittest.mock import MagicMock, Mock, patch import pytest +from aiohttp import ClientSession from scipy.stats import shapiro from tribler.core.logger.logger import load_logger_config from tribler.core.utilities.patch_import import patch_import from tribler.core.utilities.tracker_utils import add_url_params -from tribler.core.utilities.utilities import ( - Query, - extract_tags, - is_channel_public_key, - is_infohash, - is_simple_match_query, - is_valid_url, - parse_magnetlink, - parse_query, - random_infohash, - show_system_popup, - to_fts_query, get_normally_distributed_number_with_zero_mean, get_normally_distributed_positive_integers, -) +from tribler.core.utilities.utilities import (Query, extract_tags, get_normally_distributed_number_with_zero_mean, + get_normally_distributed_positive_integers, is_channel_public_key, + is_infohash, is_simple_match_query, is_valid_url, parse_magnetlink, + parse_query, random_infohash, show_system_popup, to_fts_query) + # pylint: disable=import-outside-toplevel, import-error # fmt: off @@ -58,7 +48,8 @@ def test_parse_invalid_magnetlink_long(): """ Test if a magnet link with invalid and long infohash (v1) can be parsed """ - _, hashed, _ = parse_magnetlink('magnet:?xt=urn:btih:APCTQFWNOWUBXZOIDAZGAJ2BA6FS6JUCAPCTQFWNOWUBXZOIDAZGAJ2BA6FS6JUC') + _, hashed, _ = parse_magnetlink( + 'magnet:?xt=urn:btih:APCTQFWNOWUBXZOIDAZGAJ2BA6FS6JUCAPCTQFWNOWUBXZOIDAZGAJ2BA6FS6JUC') assert hashed is None diff --git a/src/tribler/gui/code_executor.py b/src/tribler/gui/code_executor.py index 68ecb2477f1..062a195126b 100644 --- a/src/tribler/gui/code_executor.py +++ b/src/tribler/gui/code_executor.py @@ -105,6 +105,7 @@ def _on_socket_read_ready(self): def _on_socket_disconnect(self, socket): def on_socket_disconnect_handler(): self.sockets.remove(socket) + return on_socket_disconnect_handler diff --git a/src/tribler/gui/core_manager.py b/src/tribler/gui/core_manager.py index 624140f3505..cd60e54db98 100644 --- a/src/tribler/gui/core_manager.py +++ b/src/tribler/gui/core_manager.py @@ -18,7 +18,6 @@ from tribler.gui.network.request_manager import request_manager from tribler.gui.utilities import connect - API_PORT_CHECK_INTERVAL = 100 # 0.1 seconds between attempts to retrieve Core API port API_PORT_CHECK_TIMEOUT = 30 # Stop trying to determine API port after 30 seconds diff --git a/src/tribler/gui/dialogs/startdownloaddialog.py b/src/tribler/gui/dialogs/startdownloaddialog.py index 1aefb732a4e..3c9aceb3844 100644 --- a/src/tribler/gui/dialogs/startdownloaddialog.py +++ b/src/tribler/gui/dialogs/startdownloaddialog.py @@ -278,7 +278,7 @@ def on_download_clicked(self, checked): text = tr("Please specify the path to the download directory") title = tr("The path is not specified") ConfirmationDialog.show_message(self.dialog_widget, title, text, "OK") - return + return is_writable, error = is_dir_writable(download_dir) if not is_writable: gui_error_message = tr( diff --git a/src/tribler/gui/event_request_manager.py b/src/tribler/gui/event_request_manager.py index ee4b1eb6361..ab6e1a60955 100644 --- a/src/tribler/gui/event_request_manager.py +++ b/src/tribler/gui/event_request_manager.py @@ -102,7 +102,7 @@ def on_low_space(self, disk_usage_data: dict): def on_remote_query_results(self, data: dict): self.received_remote_query_results.emit(data) - def on_tribler_shutdown_state(self,state: str): + def on_tribler_shutdown_state(self, state: str): self.tribler_shutdown_signal.emit(state) def on_report_config_error(self, error): diff --git a/src/tribler/gui/i18n/README.md b/src/tribler/gui/i18n/README.md index eedb7841ce1..568341201fa 100644 --- a/src/tribler/gui/i18n/README.md +++ b/src/tribler/gui/i18n/README.md @@ -1,26 +1,39 @@ # Internationalization -This app uses the QT multi language feature to provide internationalization. +This app uses the QT multi language feature to provide internationalization. ## Improving a translation -If you find a mistake for an existing language, a missing translation or any other problem, you can help us. Just find right `` key in the respective TS file and change the value of the `` key. +If you find a mistake for an existing language, a missing translation or any other problem, you can help us. Just find +right `` key in the respective TS file and change the value of the `` key. ## New translations -If you want to translate Tribler to a new language, you need to create a new TS file. The file is named according to [rfc1766](https://tools.ietf.org/html/rfc1766.html) (pt_BR, for example). You can easily create a new file by adding a new line in the script `extract-messages` and then running it. +If you want to translate Tribler to a new language, you need to create a new TS file. The file is named according +to [rfc1766](https://tools.ietf.org/html/rfc1766.html) (pt_BR, for example). You can easily create a new file by adding +a new line in the script `extract-messages` and then running it. -Running `extract-messages` is going to update all the existing translatable strings in Tribler, creating new keys and marking obsolete ones. *Run this when you change the interface and need to update translations.* +Running `extract-messages` is going to update all the existing translatable strings in Tribler, creating new keys and +marking obsolete ones. *Run this when you change the interface and need to update translations.* ## Releasing a new translation -QT expects a binary file to load new translations. So we need a tool to convert a .ts file to a .qm file. That tool is encapsulated in the `update_translations` script. Change the translations, run the scripts and Voilà, nueva traducción disponible! +QT expects a binary file to load new translations. So we need a tool to convert a .ts file to a .qm file. That tool is +encapsulated in the `update_translations` script. Change the translations, run the scripts and Voilà, nueva traducción +disponible! -You need to remove the tag `type="unfinished"` once you consider the translation finished and then run the `update_translations` script. QT can handle partially translated TS files, so don't shy away if you cannot translate 100% of the app. +You need to remove the tag `type="unfinished"` once you consider the translation finished and then run +the `update_translations` script. QT can handle partially translated TS files, so don't shy away if you cannot translate +100% of the app. ## Caveats + * Don't use Python f-strings. They don't work correctly with `tr()` magic. Use classic `%`-syntax instead. -* Class-level variables are correctly extracted, but not translated in the GUI. Every translatable thing must be initialized in instance properties (e.g. in `__init__`) +* Class-level variables are correctly extracted, but not translated in the GUI. Every translatable thing must be + initialized in instance properties (e.g. in `__init__`) * Be aware of `%i %s` - placeholders in translatable strings. -* If something is not translated, look for `notr="true""` in the corresponding `.ui` file. However, it should be there for a reason. -* Many strings defined in `*.ui`-files should not be translated at all, since these are just placeholders that should be later set dynamically in Python code. Mark those `notr` to prevent them from being extracted and distracting the translator. +* If something is not translated, look for `notr="true""` in the corresponding `.ui` file. However, it should be there + for a reason. +* Many strings defined in `*.ui`-files should not be translated at all, since these are just placeholders that should be + later set dynamically in Python code. Mark those `notr` to prevent them from being extracted and distracting the + translator. diff --git a/src/tribler/gui/resource_monitor.py b/src/tribler/gui/resource_monitor.py index 59985d7a0b7..61186d813de 100644 --- a/src/tribler/gui/resource_monitor.py +++ b/src/tribler/gui/resource_monitor.py @@ -12,6 +12,7 @@ class GuiResourceMonitor(ResourceMonitor, QWidget): Implementation class of ResourceMonitor by the GUI process. The GUI process uses QTimer to implement start() and stop() methods. """ + def __init__(self): QWidget.__init__(self) ResourceMonitor.__init__(self, history_size=GUI_RESOURCE_HISTORY_SIZE) diff --git a/src/tribler/gui/start_gui.py b/src/tribler/gui/start_gui.py index b06307a01ef..0fb3d222e4b 100644 --- a/src/tribler/gui/start_gui.py +++ b/src/tribler/gui/start_gui.py @@ -10,7 +10,6 @@ check_free_space, enable_fault_handler ) -from tribler.core.exceptions import TriblerException from tribler.core.logger.logger import load_logger_config from tribler.core.sentry_reporter.sentry_reporter import SentryStrategy from tribler.core.utilities.process_manager import ProcessKind, ProcessManager, TriblerProcess, \ @@ -40,7 +39,7 @@ def run_gui(api_port, api_key, root_state_dir, parsed_args): current_process = TriblerProcess.current_process(ProcessKind.GUI) process_manager = ProcessManager(root_state_dir, current_process) - set_global_process_manager(process_manager) # to be able to add information about exception to the process info + set_global_process_manager(process_manager) # to be able to add information about exception to the process info current_process_is_primary = process_manager.current_process.become_primary() load_logger_config('tribler-gui', root_state_dir, current_process_is_primary) diff --git a/src/tribler/gui/tests/conftest.py b/src/tribler/gui/tests/conftest.py index 076231ce4e7..bbf201e0095 100644 --- a/src/tribler/gui/tests/conftest.py +++ b/src/tribler/gui/tests/conftest.py @@ -3,7 +3,7 @@ def pytest_addoption(parser): parser.addoption('--guitests', action='store_true', dest="guitests", - default=False, help="enable longrundecorated tests") + default=False, help="enable longrundecorated tests") def pytest_collection_modifyitems(config, items): diff --git a/src/tribler/gui/tests/test_gui.py b/src/tribler/gui/tests/test_gui.py index d593644b9de..0698a7d5272 100644 --- a/src/tribler/gui/tests/test_gui.py +++ b/src/tribler/gui/tests/test_gui.py @@ -404,6 +404,7 @@ def test_search(window): test_subscribe=False, ) + @pytest.mark.guitest def test_add_download_url(window): go_to_and_wait_for_downloads(window) diff --git a/src/tribler/gui/tribler_app.py b/src/tribler/gui/tribler_app.py index a9926c94f6a..bf889a747f9 100644 --- a/src/tribler/gui/tribler_app.py +++ b/src/tribler/gui/tribler_app.py @@ -53,7 +53,6 @@ def parse_sys_args(self, args): connect(self.tribler_window.events_manager.core_connected, self.code_executor.on_core_connected) connect(self.tribler_window.tribler_crashed, self.code_executor.on_crash) - if '--testnet' in sys.argv[1:]: os.environ['TESTNET'] = "YES" if '--trustchain-testnet' in sys.argv[1:]: diff --git a/src/tribler/gui/widgets/channelsmenulistwidget.py b/src/tribler/gui/widgets/channelsmenulistwidget.py index 243403704c8..dead62c5279 100644 --- a/src/tribler/gui/widgets/channelsmenulistwidget.py +++ b/src/tribler/gui/widgets/channelsmenulistwidget.py @@ -1,5 +1,3 @@ -import json - from PyQt5.QtCore import QSize, Qt from PyQt5.QtGui import QBrush, QColor, QIcon, QPixmap from PyQt5.QtWidgets import QAbstractItemView, QAbstractScrollArea, QAction, QListWidget, QListWidgetItem diff --git a/src/tribler/gui/widgets/clickablewidgets.py b/src/tribler/gui/widgets/clickablewidgets.py index 1d1d8111f8d..af51158bd7d 100644 --- a/src/tribler/gui/widgets/clickablewidgets.py +++ b/src/tribler/gui/widgets/clickablewidgets.py @@ -3,7 +3,6 @@ class ClickableLabel(QLabel): - clicked = pyqtSignal() def mousePressEvent(self, event): diff --git a/src/tribler/gui/widgets/downloadspage.py b/src/tribler/gui/widgets/downloadspage.py index 5ee2d71528a..3acb1cd1a29 100644 --- a/src/tribler/gui/widgets/downloadspage.py +++ b/src/tribler/gui/widgets/downloadspage.py @@ -18,8 +18,7 @@ DOWNLOADS_FILTER_COMPLETED, DOWNLOADS_FILTER_DEFINITION, DOWNLOADS_FILTER_DOWNLOADING, - DOWNLOADS_FILTER_INACTIVE, STATUS_STRING, -) + DOWNLOADS_FILTER_INACTIVE, ) from tribler.gui.dialogs.confirmationdialog import ConfirmationDialog from tribler.gui.network.request_manager import request_manager from tribler.gui.sentry_mixin import AddBreadcrumbOnShowMixin diff --git a/src/tribler/gui/widgets/graphs/timeseriesplot.py b/src/tribler/gui/widgets/graphs/timeseriesplot.py index 2146a04eb16..4bbc563dc73 100644 --- a/src/tribler/gui/widgets/graphs/timeseriesplot.py +++ b/src/tribler/gui/widgets/graphs/timeseriesplot.py @@ -1,4 +1,5 @@ import time + import numpy as np import pyqtgraph as pg from pyqtgraph import DateAxisItem diff --git a/src/tribler/gui/widgets/lazytableview.py b/src/tribler/gui/widgets/lazytableview.py index a626ccaa2ed..9b3167c76e1 100644 --- a/src/tribler/gui/widgets/lazytableview.py +++ b/src/tribler/gui/widgets/lazytableview.py @@ -1,5 +1,5 @@ import json -from typing import List, Dict +from typing import Dict, List from PyQt5.QtCore import QEvent, QModelIndex, QRect, QTimer, Qt, pyqtSignal from PyQt5.QtGui import QGuiApplication, QMouseEvent, QMovie @@ -8,7 +8,6 @@ from tribler.core.components.metadata_store.db.orm_bindings.channel_node import LEGACY_ENTRY from tribler.core.components.metadata_store.db.serialization import CHANNEL_TORRENT, COLLECTION_NODE, REGULAR_TORRENT, \ SNIPPET - from tribler.gui.defs import COMMIT_STATUS_COMMITTED from tribler.gui.dialogs.editmetadatadialog import EditMetadataDialog from tribler.gui.network.request_manager import request_manager @@ -213,8 +212,8 @@ def on_table_item_clicked(self, item, doubleclick=False): # Skip emitting click event when the user clicked on some specific columns column_position = self.model().column_position if item.column() in ( - column_position.get(cname, False) - for cname in (Column.ACTIONS, Column.STATUS, Column.VOTES, Column.SUBSCRIBED, Column.HEALTH) + column_position.get(cname, False) + for cname in (Column.ACTIONS, Column.STATUS, Column.VOTES, Column.SUBSCRIBED, Column.HEALTH) ): return @@ -238,8 +237,8 @@ def on_torrent_status_updated(self, json_result, index): # Note: this should instead use signal and do not address the widget globally # and properly handle entry removal self.window().personal_channel_page.channel_dirty = ( - self.table_view.window().edit_channel_page.channel_dirty - or json_result['new_status'] != COMMIT_STATUS_COMMITTED + self.table_view.window().edit_channel_page.channel_dirty + or json_result['new_status'] != COMMIT_STATUS_COMMITTED ) self.window().personal_channel_page.update_channel_commit_views(deleted_index=index) diff --git a/src/tribler/gui/widgets/qtbug.py b/src/tribler/gui/widgets/qtbug.py index 1972911d3a9..7db42727155 100644 --- a/src/tribler/gui/widgets/qtbug.py +++ b/src/tribler/gui/widgets/qtbug.py @@ -3,6 +3,7 @@ from tribler.gui.utilities import get_ui_file_path + # This file is a result of a nasty QT bug that PREVENTS US from loading some custom # widgets WITHOUT custom subwidgets. # Total crazyness. diff --git a/src/tribler/gui/widgets/subscriptionswidget.py b/src/tribler/gui/widgets/subscriptionswidget.py index 980d312cde4..a86725f2063 100644 --- a/src/tribler/gui/widgets/subscriptionswidget.py +++ b/src/tribler/gui/widgets/subscriptionswidget.py @@ -43,8 +43,8 @@ def update_subscribe_button_if_channel_matches(self, changed_channels_list): return for channel_info in changed_channels_list: if ( - self.contents_widget.model.channel_info["public_key"] == channel_info["public_key"] - and self.contents_widget.model.channel_info["id"] == channel_info["id"] + self.contents_widget.model.channel_info["public_key"] == channel_info["public_key"] + and self.contents_widget.model.channel_info["id"] == channel_info["id"] ): self.update_subscribe_button(remote_response=channel_info) return diff --git a/src/tribler/gui/widgets/tablecontentdelegate.py b/src/tribler/gui/widgets/tablecontentdelegate.py index 47553016cd5..90ea1fab6f1 100644 --- a/src/tribler/gui/widgets/tablecontentdelegate.py +++ b/src/tribler/gui/widgets/tablecontentdelegate.py @@ -33,8 +33,8 @@ TAG_TOP_MARGIN, WINDOWS, ) -from tribler.gui.utilities import format_votes, get_color, get_gui_setting, get_health, get_image_path, tr, \ - get_objects_with_predicate +from tribler.gui.utilities import format_votes, get_color, get_gui_setting, get_health, get_image_path, \ + get_objects_with_predicate, tr from tribler.gui.widgets.tablecontentmodel import Column, RemoteTableModel from tribler.gui.widgets.tableiconbuttons import DownloadIconButton diff --git a/src/tribler/gui/widgets/tagbutton.py b/src/tribler/gui/widgets/tagbutton.py index 7b000bf9a85..89a8f7596ac 100644 --- a/src/tribler/gui/widgets/tagbutton.py +++ b/src/tribler/gui/widgets/tagbutton.py @@ -1,10 +1,9 @@ -from PyQt5.QtCore import Qt, QSize +from PyQt5.QtCore import QSize, Qt from PyQt5.QtGui import QCursor from PyQt5.QtWidgets import QPushButton -from tribler.gui.defs import SUGGESTED_TAG_TEXT_COLOR, TAG_HEIGHT, SUGGESTED_TAG_BACKGROUND_COLOR, \ - SUGGESTED_TAG_BORDER_COLOR, \ - TAG_TEXT_HORIZONTAL_PADDING +from tribler.gui.defs import SUGGESTED_TAG_BACKGROUND_COLOR, SUGGESTED_TAG_BORDER_COLOR, SUGGESTED_TAG_TEXT_COLOR, \ + TAG_HEIGHT, TAG_TEXT_HORIZONTAL_PADDING class TagButton(QPushButton): diff --git a/src/tribler/gui/widgets/tagslineedit.py b/src/tribler/gui/widgets/tagslineedit.py index 41e7331a734..ba0e6de8c50 100644 --- a/src/tribler/gui/widgets/tagslineedit.py +++ b/src/tribler/gui/widgets/tagslineedit.py @@ -95,7 +95,7 @@ def in_cross_area(self, tag_index: int, point: QPoint) -> bool: Return whether the provided point is within the cross rect of the tag with a particular index. """ return TagsLineEdit.compute_cross_rect(self.tags[tag_index].rect).adjusted(-2, 0, 0, 0).contains(point) and ( - not self.cursor_is_visible() or tag_index != self.editing_index + not self.cursor_is_visible() or tag_index != self.editing_index ) def resizeEvent(self, _) -> None: @@ -231,9 +231,9 @@ def compute_tag_rects(self) -> None: self.compute_tag_rects_with_range(lt, TAG_HEIGHT, (0, self.editing_index)) w = ( - self.fontMetrics().horizontalAdvance(self.text_layout.text()) - + TAG_TEXT_HORIZONTAL_PADDING - + TAG_TEXT_HORIZONTAL_PADDING + self.fontMetrics().horizontalAdvance(self.text_layout.text()) + + TAG_TEXT_HORIZONTAL_PADDING + + TAG_TEXT_HORIZONTAL_PADDING ) # Check if we overflow and if so, move the editor rect to the next line in the input field. @@ -278,7 +278,7 @@ def has_selection_active(self) -> bool: def remove_selection(self) -> None: self.cursor_ind = self.select_start txt = self.tags[self.editing_index].text - self.tags[self.editing_index].text = txt[: self.cursor_ind] + txt[self.cursor_ind + self.select_size :] + self.tags[self.editing_index].text = txt[: self.cursor_ind] + txt[self.cursor_ind + self.select_size:] self.deselectAll() def remove_backwards_character(self) -> None: @@ -287,7 +287,7 @@ def remove_backwards_character(self) -> None: else: self.cursor_ind -= 1 txt = self.tags[self.editing_index].text - txt = txt[: self.cursor_ind] + txt[self.cursor_ind + 1 :] + txt = txt[: self.cursor_ind] + txt[self.cursor_ind + 1:] self.tags[self.editing_index].text = txt def selectAll(self) -> None: @@ -441,8 +441,8 @@ def keyPressEvent(self, event: QKeyEvent) -> None: event.accept() elif event.key() == Qt.Key_End: if ( - self.cursor_ind == len(self.tags[self.editing_index].text) - and self.editing_index < len(self.tags) - 1 + self.cursor_ind == len(self.tags[self.editing_index].text) + and self.editing_index < len(self.tags) - 1 ): self.edit_tag(len(self.tags) - 1) else: @@ -476,7 +476,7 @@ def keyPressEvent(self, event: QKeyEvent) -> None: if self.has_selection_active(): self.remove_selection() txt = self.tags[self.editing_index].text - txt = txt[: self.cursor_ind] + event.text().lower() + txt[self.cursor_ind :] + txt = txt[: self.cursor_ind] + event.text().lower() + txt[self.cursor_ind:] self.tags[self.editing_index].text = txt self.cursor_ind += len(event.text()) event.accept() diff --git a/src/tribler/gui/widgets/timeoutprogressbar.py b/src/tribler/gui/widgets/timeoutprogressbar.py index 2d50a3d1b04..c12a1d38529 100644 --- a/src/tribler/gui/widgets/timeoutprogressbar.py +++ b/src/tribler/gui/widgets/timeoutprogressbar.py @@ -5,7 +5,6 @@ class TimeoutProgressBar(QProgressBar): - timeout = pyqtSignal() def __init__(self, parent=None, timeout=10000): diff --git a/src/tribler/gui/widgets/triblertablecontrollers.py b/src/tribler/gui/widgets/triblertablecontrollers.py index 238b770a7c2..41219a18316 100644 --- a/src/tribler/gui/widgets/triblertablecontrollers.py +++ b/src/tribler/gui/widgets/triblertablecontrollers.py @@ -4,7 +4,6 @@ """ import json import logging -import time from PyQt5.QtCore import QObject, QTimer, Qt from PyQt5.QtGui import QCursor @@ -16,7 +15,7 @@ from tribler.gui.defs import HEALTH_CHECKING, HEALTH_UNCHECKED from tribler.gui.network.request_manager import request_manager from tribler.gui.tribler_action_menu import TriblerActionMenu -from tribler.gui.utilities import connect, dict_item_is_any_of, get_health, tr +from tribler.gui.utilities import connect, dict_item_is_any_of, tr from tribler.gui.widgets.tablecontentmodel import Column HEALTHCHECK_DELAY_MS = 500 diff --git a/tribler.spec b/tribler.spec index 9b1cd071d25..34a6ce60491 100644 --- a/tribler.spec +++ b/tribler.spec @@ -3,12 +3,11 @@ block_cipher = None import imp import os import pkgutil -import sys import shutil +import sys import aiohttp_apispec import sentry_sdk - from PyInstaller.utils.hooks import collect_data_files, collect_submodules root_dir = os.path.abspath(os.path.dirname(__name__)) @@ -16,6 +15,7 @@ src_dir = os.path.join(root_dir, "src") sys.path.append(src_dir) from tribler.core.version import version_id + version_str = version_id.split('-')[0] # On macOS, we always show the console to prevent the double-dock bug (although the OS does not actually show the console). @@ -69,6 +69,7 @@ excluded_libs = ['wx', 'PyQt4', 'FixTk', 'tcl', 'tk', '_tkinter', 'tkinter', 'Tk # Pony dependencies; each packages need to be added separatedly; added as hidden import pony_deps = ['pony', 'pony.orm', 'pony.orm.dbproviders', 'pony.orm.dbproviders.sqlite'] + # Sentry hidden imports def get_sentry_hooks(): package = sentry_sdk.integrations @@ -79,27 +80,29 @@ def get_sentry_hooks(): sentry_hooks.append(modname) return sentry_hooks + # Hidden imports hiddenimports = [ - 'csv', - 'dataclasses', # https://github.com/pyinstaller/pyinstaller/issues/5432 - 'ecdsa', - 'ipv8', - 'PIL', - 'pkg_resources', # 'pkg_resources.py2_warn', # Workaround PyInstaller & SetupTools, https://github.com/pypa/setuptools/issues/1963 - 'pyaes', - 'pydantic', - 'pyqtgraph', - 'pyqtgraph.graphicsItems.PlotItem.plotConfigTemplate_pyqt5', - 'pyqtgraph.graphicsItems.ViewBox.axisCtrlTemplate_pyqt5', - 'pyqtgraph.imageview.ImageViewTemplate_pyqt5', - 'PyQt5.QtTest', - 'requests', - 'scrypt', '_scrypt', - 'sqlalchemy', 'sqlalchemy.ext.baked', 'sqlalchemy.ext.declarative', - 'tribler.core.logger.logger_streams', - 'typing_extensions', -] + widget_files + pony_deps + get_sentry_hooks() + 'csv', + 'dataclasses', # https://github.com/pyinstaller/pyinstaller/issues/5432 + 'ecdsa', + 'ipv8', + 'PIL', + 'pkg_resources', + # 'pkg_resources.py2_warn', # Workaround PyInstaller & SetupTools, https://github.com/pypa/setuptools/issues/1963 + 'pyaes', + 'pydantic', + 'pyqtgraph', + 'pyqtgraph.graphicsItems.PlotItem.plotConfigTemplate_pyqt5', + 'pyqtgraph.graphicsItems.ViewBox.axisCtrlTemplate_pyqt5', + 'pyqtgraph.imageview.ImageViewTemplate_pyqt5', + 'PyQt5.QtTest', + 'requests', + 'scrypt', '_scrypt', + 'sqlalchemy', 'sqlalchemy.ext.baked', 'sqlalchemy.ext.declarative', + 'tribler.core.logger.logger_streams', + 'typing_extensions', + ] + widget_files + pony_deps + get_sentry_hooks() # https://github.com/pyinstaller/pyinstaller/issues/5359 hiddenimports += collect_submodules('pydantic') @@ -108,7 +111,6 @@ hiddenimports += collect_submodules('pydantic') # https://issueexplorer.com/issue/pyqtgraph/pyqtgraph/1811 hiddenimports += collect_submodules("pyqtgraph", filter=lambda name: "Template" in name) - sys.modules['FixTk'] = None a = Analysis(['src/run_tribler.py'], pathex=[''], @@ -123,12 +125,12 @@ a = Analysis(['src/run_tribler.py'], cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, - cipher=block_cipher) + cipher=block_cipher) # Add libsodium.dylib on OS X if sys.platform == 'darwin': - a.binaries = a.binaries - TOC([('/usr/local/lib/libsodium.so', None, None),]) - a.binaries = a.binaries + TOC([('libsodium.dylib', '/usr/local/lib/libsodium.dylib', None),]) + a.binaries = a.binaries - TOC([('/usr/local/lib/libsodium.so', None, None), ]) + a.binaries = a.binaries + TOC([('libsodium.dylib', '/usr/local/lib/libsodium.dylib', None), ]) exe = EXE(pyz, a.scripts, @@ -152,7 +154,9 @@ app = BUNDLE(coll, name='Tribler.app', icon='build/mac/resources/tribler.icns', bundle_identifier='nl.tudelft.tribler', - info_plist={'CFBundleName': 'Tribler', 'CFBundleDisplayName': 'Tribler', 'NSHighResolutionCapable': 'True', 'CFBundleInfoDictionaryVersion': 1.0, 'CFBundleVersion': version_str, 'CFBundleShortVersionString': version_str}, + info_plist={'CFBundleName': 'Tribler', 'CFBundleDisplayName': 'Tribler', 'NSHighResolutionCapable': 'True', + 'CFBundleInfoDictionaryVersion': 1.0, 'CFBundleVersion': version_str, + 'CFBundleShortVersionString': version_str}, console=show_console) # Replace the Info.plist file on MacOS @@ -161,4 +165,5 @@ if sys.platform == 'darwin': # On Windows 10, we have to make sure that qwindows.dll is in the right path if sys.platform == 'win32': - shutil.copytree(os.path.join('dist', 'tribler', 'PyQt5', 'Qt', 'plugins', 'platforms'), os.path.join('dist', 'tribler', 'platforms')) + shutil.copytree(os.path.join('dist', 'tribler', 'PyQt5', 'Qt', 'plugins', 'platforms'), + os.path.join('dist', 'tribler', 'platforms')) From e17d3ba552ce8530aec0a0c1ba7c64723d62ef04 Mon Sep 17 00:00:00 2001 From: drew2a Date: Wed, 15 Mar 2023 09:26:33 +0100 Subject: [PATCH 2/2] Fix linter issues --- .../restapi/tests/test_remote_query_endpoint.py | 11 +++++------ src/tribler/core/tests/test_search_utils.py | 4 ++-- src/tribler/core/utilities/sentinels.py | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/tribler/core/components/metadata_store/restapi/tests/test_remote_query_endpoint.py b/src/tribler/core/components/metadata_store/restapi/tests/test_remote_query_endpoint.py index fc0676a1a6e..0be36a73a30 100644 --- a/src/tribler/core/components/metadata_store/restapi/tests/test_remote_query_endpoint.py +++ b/src/tribler/core/components/metadata_store/restapi/tests/test_remote_query_endpoint.py @@ -15,7 +15,7 @@ from tribler.core.utilities.utilities import random_infohash -# pylint: disable=unused-argument +# pylint: disable=unused-argument,redefined-outer-name,multiple-statements @pytest.fixture @@ -24,19 +24,19 @@ def mock_gigachannel_community(): @pytest.fixture -def endpoint(mock_gigachannel_community, metadata_store): # pylint: disable=W0621 +def endpoint(mock_gigachannel_community, metadata_store): return RemoteQueryEndpoint(mock_gigachannel_community, metadata_store) @pytest.fixture -def rest_api(event_loop, aiohttp_client, endpoint): # pylint: disable=unused-argument +def rest_api(event_loop, aiohttp_client, endpoint): app = Application(middlewares=[error_middleware]) app.add_subapp('/remote_query', endpoint.app) yield event_loop.run_until_complete(aiohttp_client(app)) app.shutdown() -async def test_create_remote_search_request(rest_api, endpoint, mock_gigachannel_community): # pylint: disable=W0621 +async def test_create_remote_search_request(rest_api, endpoint, mock_gigachannel_community): """ Test that remote search call is sent on a REST API search request """ @@ -69,8 +69,7 @@ def mock_send(**kwargs): assert hexlify(sent['channel_pk']) == channel_pk -async def test_get_channels_peers(rest_api, endpoint, metadata_store, - mock_gigachannel_community): # pylint: disable=W0621, C0321 +async def test_get_channels_peers(rest_api, endpoint, metadata_store, mock_gigachannel_community): """ Test getting debug info about the state of channels to peers mapping """ diff --git a/src/tribler/core/tests/test_search_utils.py b/src/tribler/core/tests/test_search_utils.py index dd532d8a15e..046ab0ce8d8 100644 --- a/src/tribler/core/tests/test_search_utils.py +++ b/src/tribler/core/tests/test_search_utils.py @@ -2,8 +2,8 @@ import pytest -from tribler.core.utilities.search_utils import filter_keywords, find_word_and_rotate_title, freshness_rank, item_rank, \ - seeders_rank, split_into_keywords, title_rank, torrent_rank +from tribler.core.utilities.search_utils import filter_keywords, find_word_and_rotate_title, freshness_rank, \ + item_rank, seeders_rank, split_into_keywords, title_rank, torrent_rank DAY = 60 * 60 * 24 diff --git a/src/tribler/core/utilities/sentinels.py b/src/tribler/core/utilities/sentinels.py index a8d9310b61e..ad18d8618d4 100644 --- a/src/tribler/core/utilities/sentinels.py +++ b/src/tribler/core/utilities/sentinels.py @@ -64,7 +64,7 @@ def __new__(cls): if hasattr(_sys, '_getframe'): def _get_parent_frame(): - return _sys._getframe(2) + return _sys._getframe(2) # pylint: disable=protected-access else: # pragma: no cover def _get_parent_frame(): """Return the frame object for the caller's parent stack frame."""