From a01689fd9f82e0bf8992cbd1144c79b87d643822 Mon Sep 17 00:00:00 2001 From: Artur Barseghyan Date: Wed, 25 Dec 2024 01:55:38 +0100 Subject: [PATCH] Clean up (#95) * Clean up --- .secrets.baseline | 6 +- .../marytts_mp3_generator/__init__.py | 61 ++++++--- .../django_example/project/settings/base.py | 5 +- .../faker_file_admin/alembic/__init__.py | 0 .../alembic/versions/__init__.py | 0 pyproject.toml | 68 +++++----- setup.py | 8 +- src/faker_file/base.py | 8 +- src/faker_file/cli/helpers.py | 2 +- src/faker_file/contrib/docx_file.py | 8 +- .../contrib/image/weasyprint_snippets.py | 26 +++- src/faker_file/contrib/odt_file.py | 14 +-- .../contrib/pdf_file/pdfkit_snippets.py | 12 +- .../contrib/pdf_file/pil_snippets.py | 10 +- .../contrib/pdf_file/reportlab_snippets.py | 8 +- src/faker_file/helpers.py | 6 +- .../providers/image/pil_generator.py | 2 +- .../providers/image/weasyprint_generator.py | 2 +- .../pdf_file/generators/pil_generator.py | 2 +- src/faker_file/tests/_conftest.py | 13 +- src/faker_file/tests/sftp_server.py | 5 +- src/faker_file/tests/test_sftp_server.py | 118 +++++++++--------- src/faker_file/tests/test_sftp_storage.py | 6 +- src/faker_file/tests/test_storages.py | 6 +- 24 files changed, 214 insertions(+), 182 deletions(-) create mode 100644 examples/sqlalchemy_example/faker_file_admin/alembic/__init__.py create mode 100644 examples/sqlalchemy_example/faker_file_admin/alembic/versions/__init__.py diff --git a/.secrets.baseline b/.secrets.baseline index 1c4914ec..17c3e669 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -161,7 +161,7 @@ "filename": "examples/django_example/project/settings/base.py", "hashed_secret": "2e56b31925af569c194d2cc738d1f1bc22b63df0", "is_verified": true, - "line_number": 66 + "line_number": 67 } ], "examples/sqlalchemy_example/faker_file_admin/alembic/versions/2695cb77cdf2_create_product_table.py": [ @@ -197,7 +197,7 @@ "filename": "src/faker_file/tests/test_sftp_server.py", "hashed_secret": "e8662cfb96bd9c7fe84c31d76819ec3a92c80e63", "is_verified": true, - "line_number": 84 + "line_number": 86 } ], "src/faker_file/tests/test_sftp_storage.py": [ @@ -219,5 +219,5 @@ } ] }, - "generated_at": "2024-11-14T22:15:37Z" + "generated_at": "2024-12-24T23:25:39Z" } diff --git a/examples/customizations/marytts_mp3_generator/__init__.py b/examples/customizations/marytts_mp3_generator/__init__.py index 4f8a7410..556541ec 100644 --- a/examples/customizations/marytts_mp3_generator/__init__.py +++ b/examples/customizations/marytts_mp3_generator/__init__.py @@ -48,23 +48,48 @@ def generate(self: "MaryTtsMp3Generator") -> bytes: # Initialize with args mary_tts = MaryTTS(locale=self.locale, voice=self.voice) - # Generate temporary filename for WAV file - filename = tempfile.NamedTemporaryFile( - prefix="_merytts_", suffix=".wav" - ).name - - # Write WAV file - with open(filename, "wb") as file: - file.write(mary_tts.speak(self.content)) - - # Convert WAV to MP3 - ffmpeg.input(filename).output(filename + ".mp3").run() - - with open(filename + ".mp3", "rb") as _fake_file: - return_value = _fake_file.read() + # Create temporary WAV file in memory + with tempfile.NamedTemporaryFile( + delete=False, + suffix=".wav", + ) as temp_wav: + temp_wav.write(mary_tts.speak(self.content)) + temp_wav_path = temp_wav.name + + # Convert WAV to MP3 and store in memory + with tempfile.NamedTemporaryFile( + delete=False, + suffix=".mp3", + ) as temp_mp3: + ffmpeg.input(temp_wav_path).output(temp_mp3.name).run() + + # Read the MP3 file content into memory + with open(temp_mp3.name, "rb") as mp3_file: + mp3_content = mp3_file.read() # Clean up temporary files - os.remove(filename) - os.remove(filename + ".mp3") - - return return_value + os.remove(temp_wav.name) + os.remove(temp_mp3.name) + + return mp3_content + + # # Generate temporary filename for WAV file + # filename = tempfile.NamedTemporaryFile( + # prefix="_merytts_", suffix=".wav" + # ).name + # + # # Write WAV file + # with open(filename, "wb") as file: + # file.write(mary_tts.speak(self.content)) + # + # # Convert WAV to MP3 + # ffmpeg.input(filename).output(filename + ".mp3").run() + # + # with open(filename + ".mp3", "rb") as _fake_file: + # return_value = _fake_file.read() + # + # # Clean up temporary files + # os.remove(filename) + # os.remove(filename + ".mp3") + # + # return return_value diff --git a/examples/django_example/project/settings/base.py b/examples/django_example/project/settings/base.py index 10f43975..902e2357 100755 --- a/examples/django_example/project/settings/base.py +++ b/examples/django_example/project/settings/base.py @@ -10,6 +10,7 @@ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os +from contextlib import suppress from .core import PROJECT_DIR @@ -200,7 +201,5 @@ # Do not put any settings below this line -try: +with suppress(ImportError): from .local_settings import * # noqa -except ImportError: - pass diff --git a/examples/sqlalchemy_example/faker_file_admin/alembic/__init__.py b/examples/sqlalchemy_example/faker_file_admin/alembic/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/sqlalchemy_example/faker_file_admin/alembic/versions/__init__.py b/examples/sqlalchemy_example/faker_file_admin/alembic/versions/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/pyproject.toml b/pyproject.toml index c5ea4564..421dcd07 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,54 +5,40 @@ # verbose regular expressions by Black. Use [ ] to denote a significant space # character. -#[tool.black] -#line-length = 80 -#target-version = ['py37', 'py38', 'py39', 'py310', 'py311'] -#include = '\.pyi?$' -#extend-exclude = ''' -#/( -# # The following are specific to Black, you probably don't want those. -# | blib2to3 -# | tests/data -# | profiling -# | migrations -#)/ -#''' - # Build system information below. # NOTE: You don't need this in your own Black configuration. [build-system] requires = ["setuptools>=41.0", "setuptools-scm", "wheel"] build-backend = "setuptools.build_meta" -#[tool.isort] -#profile = "black" -#combine_as_imports = true -#multi_line_output = 3 -#include_trailing_comma = true -#force_grid_wrap = 0 -#use_parentheses = true -#ensure_newline_before_comments = true -#line_length = 80 -##known_first_party = "faker_file" -#known_first_party = [ -# "upload", -# "factories", -# "project", -# "faker_file_admin", -# "instance", -# "sqlalchemy_factories", -# "marytts_mp3_generator", -#] -#known_third_party = ["django", "factory", "faker_file"] -#skip = ["wsgi.py", "builddocs/"] - [tool.ruff] line-length = 80 + # Enable Pyflakes `E` and `F` codes by default. -lint.select = ["E", "F", "I"] -lint.ignore = [] +lint.select = [ +# "ANN", # Annotations: missing (return) types + "B", # Bugbear: common bug patterns or design problems + "C4", # Complexity: McCabe complexity checker + "E", # Pycodesyle: Style guide enforcement + "F", # Pyflakes: Source files errors + "G", # Logging format: Basic logging format errors + "I", # Isort: import sorting + "ISC", # Naming: Variable naming convention + "INP", # Implicit namespace packages: Check if __init__.py is present + "N", # Naming: Variable naming convention + "PERF", # Perflint: Performance linting + "Q", + "SIM", # Simplify: Helps simplify your code + "TD", # TO DO: Format TO DO comments +] +lint.ignore = [ + "G004", # Allow use of f-string in logging + "ISC003", # Allow explicitly concatenated strings +# "N805", # Allow first argument of a method be named other than `self` + "TD002", # Allow to do without author + "TD003", # Allow to do without URL +] # Enable autofix for formatting and import sorting fix = true src = [ @@ -84,7 +70,6 @@ exclude = [ "examples/django_example/project/wsgi.py", "docs", ] -lint.per-file-ignores = {} # Allow unused variables when underscore-prefixed. lint.dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" @@ -92,6 +77,11 @@ lint.dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" # Assume Python 3.10. target-version = "py310" +[tool.ruff.lint.per-file-ignores] +"conftest.py" = [ + "PERF203" # Allow `try`-`except` within a loop incurs performance overhead +] + [tool.ruff.lint.isort] known-first-party = [ "upload", diff --git a/setup.py b/setup.py index 5be35c54..366f55d0 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,5 @@ -import os import re +from pathlib import Path from setuptools import find_packages, setup @@ -19,9 +19,9 @@ def clean_readme(text: str) -> str: version = "0.17.14" try: - readme = open(os.path.join(os.path.dirname(__file__), "README.rst")).read() - readme = clean_readme(readme) -except OSError: + readme_path = Path(__file__).parent / "README.rst" + readme = clean_readme(readme_path.read_text()) +except FileNotFoundError: readme = "" dependency_links = [] diff --git a/src/faker_file/base.py b/src/faker_file/base.py index f5a82ed4..c70d1682 100644 --- a/src/faker_file/base.py +++ b/src/faker_file/base.py @@ -177,11 +177,13 @@ def returns_list(func: Callable) -> bool: # If it's a list, check the type of its elements element_type = getattr(return_type, "__args__", [None])[0] element_origin = getattr(element_type, "__origin__", None) - if element_origin is Union: - if set(getattr(element_type, "__args__", [])) == { + if ( + element_origin is Union + and set(getattr(element_type, "__args__", [])) == { BytesValue, StringValue, - }: + } + ): return True return False diff --git a/src/faker_file/cli/helpers.py b/src/faker_file/cli/helpers.py index 7b0e1e25..f5573308 100644 --- a/src/faker_file/cli/helpers.py +++ b/src/faker_file/cli/helpers.py @@ -143,7 +143,7 @@ def get_method_kwargs( kwargs = deepcopy(method_specs.args[1:]) # Omit `self` defaults = deepcopy(method_specs.defaults if method_specs.defaults else []) - model_props = dict(zip(kwargs, defaults)) + model_props = dict(zip(kwargs, defaults, strict=False)) annotations = deepcopy(method_specs.annotations) # Override the type definition for mp3_generator_cls diff --git a/src/faker_file/contrib/docx_file.py b/src/faker_file/contrib/docx_file.py index 2495ac1e..8c44f56d 100644 --- a/src/faker_file/contrib/docx_file.py +++ b/src/faker_file/contrib/docx_file.py @@ -71,9 +71,9 @@ def add_page_break(provider, document, data, counter, **kwargs): def add_paragraph(provider, document, data, counter, **kwargs): """Callable responsible for the paragraph generation.""" - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 5_000) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) _content = provider._generate_text_content( @@ -94,9 +94,9 @@ def add_paragraph(provider, document, data, counter, **kwargs): def add_heading(provider, document, data, counter, **kwargs): """Callable responsible for the heading generation.""" - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 30) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) level = kwargs.get("level", 0) diff --git a/src/faker_file/contrib/image/weasyprint_snippets.py b/src/faker_file/contrib/image/weasyprint_snippets.py index 698ca032..e93487a0 100644 --- a/src/faker_file/contrib/image/weasyprint_snippets.py +++ b/src/faker_file/contrib/image/weasyprint_snippets.py @@ -8,6 +8,20 @@ __author__ = "Artur Barseghyan " __copyright__ = "2022-2023 Artur Barseghyan" __license__ = "MIT" +__all__ = ( + "add_h1_heading", + "add_h2_heading", + "add_h3_heading", + "add_h4_heading", + "add_h5_heading", + "add_h6_heading", + "add_heading", + "add_page_break", + "add_paragraph", + "add_picture", + "add_table", + "create_data_url", +) def create_data_url(image_bytes: bytes, image_format: str) -> str: @@ -31,10 +45,10 @@ def add_table( # Begin the HTML table table_html = "" - for row_num in range(rows): + for _row_num in range(rows): table_html += "" - for col_num in range(cols): + for _col_num in range(cols): text = provider.generator.paragraph() table_html += f"" @@ -93,9 +107,9 @@ def add_paragraph( **kwargs, ): """Callable responsible for paragraph generation using pdfkit.""" - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 5_000) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) _content = provider._generate_text_content( @@ -126,9 +140,9 @@ def add_heading( **kwargs, ): """Callable responsible for heading generation using pdfkit.""" - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 30) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) level = kwargs.get("level", 1) if level < 1 or level > 6: diff --git a/src/faker_file/contrib/odt_file.py b/src/faker_file/contrib/odt_file.py index 61e97389..4a4c03ea 100644 --- a/src/faker_file/contrib/odt_file.py +++ b/src/faker_file/contrib/odt_file.py @@ -56,13 +56,13 @@ def add_table(provider, document, data, counter, **kwargs): # Create table table = Table() - for i in range(rows): + for _row_num in range(rows): table.addElement(TableColumn(stylename=table_col_style)) - for row in range(cols): + for _row in range(cols): tr = TableRow(stylename=table_row_style) table.addElement(tr) - for col in range(4): + for _col in range(4): tc = TableCell(stylename=table_cell_style) tr.addElement(tc) text = provider.generator.paragraph() @@ -121,9 +121,9 @@ def add_page_break(provider, document, data, counter, **kwargs): def add_paragraph(provider, document, data, counter, **kwargs): """Callable responsible for the paragraph generation.""" - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 5_000) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) _content = provider._generate_text_content( @@ -146,9 +146,9 @@ def add_paragraph(provider, document, data, counter, **kwargs): def add_heading(provider, document, data, counter, **kwargs): """Callable responsible for the heading generation.""" - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 30) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) level = kwargs.get("level", 1) diff --git a/src/faker_file/contrib/pdf_file/pdfkit_snippets.py b/src/faker_file/contrib/pdf_file/pdfkit_snippets.py index 9eebbe7e..3bd9289a 100644 --- a/src/faker_file/contrib/pdf_file/pdfkit_snippets.py +++ b/src/faker_file/contrib/pdf_file/pdfkit_snippets.py @@ -41,10 +41,10 @@ def add_table( # Begin the HTML table table_html = "
{text}
" - for row_num in range(rows): + for _row_num in range(rows): table_html += "" - for col_num in range(cols): + for _col_num in range(cols): text = provider.generator.paragraph() table_html += f"" @@ -98,9 +98,9 @@ def add_paragraph( **kwargs, ): """Callable responsible for paragraph generation using pdfkit.""" - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 5_000) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) _content = provider._generate_text_content( @@ -130,9 +130,9 @@ def add_heading( **kwargs, ): """Callable responsible for heading generation using pdfkit.""" - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 30) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) level = kwargs.get("level", 1) if level < 1 or level > 6: diff --git a/src/faker_file/contrib/pdf_file/pil_snippets.py b/src/faker_file/contrib/pdf_file/pil_snippets.py index 481ee725..07d72e6c 100644 --- a/src/faker_file/contrib/pdf_file/pil_snippets.py +++ b/src/faker_file/contrib/pdf_file/pil_snippets.py @@ -225,9 +225,9 @@ def add_paragraph( # Extract margin values margin = kwargs.get("margin", (0, 0)) top_margin, right_margin, bottom_margin, left_margin = expand_margin(margin) - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 5_000) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") # X, Y coordinates where the text will be placed # position = kwargs.get("position", (0, 0)) # position = kwargs.get("position", (0, 0)) @@ -266,7 +266,7 @@ def add_paragraph( y_text = position[1] # LOGGER.debug(f"position: {position}") - for counter, line in enumerate(lines): + for _counter, line in enumerate(lines): # text_width, text_height = generator.draw.textsize( # line, font=font, spacing=generator.spacing # ) @@ -343,9 +343,9 @@ def add_heading( # Extract margin values margin = kwargs.get("margin", (0, 0)) top_margin, right_margin, bottom_margin, left_margin = expand_margin(margin) - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 30) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) # X, Y coordinates where the text will be placed # position = kwargs.get("position", (0, 0)) diff --git a/src/faker_file/contrib/pdf_file/reportlab_snippets.py b/src/faker_file/contrib/pdf_file/reportlab_snippets.py index a6121076..7d57025b 100644 --- a/src/faker_file/contrib/pdf_file/reportlab_snippets.py +++ b/src/faker_file/contrib/pdf_file/reportlab_snippets.py @@ -131,9 +131,9 @@ def add_paragraph( **kwargs, ): """Add paragraph function.""" - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 5_000) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) _content = provider._generate_text_content( @@ -169,9 +169,9 @@ def add_heading( **kwargs, ): """Add heading function.""" - content = kwargs.get("content", None) + content = kwargs.get("content") max_nb_chars = kwargs.get("max_nb_chars", 30) - wrap_chars_after = kwargs.get("wrap_chars_after", None) + wrap_chars_after = kwargs.get("wrap_chars_after") format_func = kwargs.get("format_func", DEFAULT_FORMAT_FUNC) level = kwargs.get("level", 1) if level < 1 or level > 6: diff --git a/src/faker_file/helpers.py b/src/faker_file/helpers.py index 0de90f9e..a25699c9 100644 --- a/src/faker_file/helpers.py +++ b/src/faker_file/helpers.py @@ -55,8 +55,10 @@ def load_class_from_path(full_path: str) -> Type: raise ImportError(f"'{full_path}' does not point to a class") return loaded_class - except ImportError as e: - raise ImportError(f"Error loading class from path '{full_path}': {e}") + except ImportError as err: + raise ImportError( + f"Error loading class from path '{full_path}': {err}" + ) from err def random_pop(lst: list) -> Any: diff --git a/src/faker_file/providers/image/pil_generator.py b/src/faker_file/providers/image/pil_generator.py index 95231d3c..f0672108 100644 --- a/src/faker_file/providers/image/pil_generator.py +++ b/src/faker_file/providers/image/pil_generator.py @@ -288,7 +288,7 @@ def generate( lines = textwrap.wrap(content, line_max_num_chars) y_text = 0 - for counter, line in enumerate(lines): + for _counter, line in enumerate(lines): # text_width, text_height = self.draw.textsize( # line, font=font, spacing=self.spacing # ) diff --git a/src/faker_file/providers/image/weasyprint_generator.py b/src/faker_file/providers/image/weasyprint_generator.py index f09b4e08..fa4b55f2 100644 --- a/src/faker_file/providers/image/weasyprint_generator.py +++ b/src/faker_file/providers/image/weasyprint_generator.py @@ -166,7 +166,7 @@ def create_image_instance( ) def wrap(self: "WeasyPrintImageGenerator", content: str) -> str: - return f"<{self.wrapper_tag}>" f"{content}" f"" + return f"<{self.wrapper_tag}>{content}" def generate( self: "WeasyPrintImageGenerator", diff --git a/src/faker_file/providers/pdf_file/generators/pil_generator.py b/src/faker_file/providers/pdf_file/generators/pil_generator.py index 452a3921..4b735fc1 100644 --- a/src/faker_file/providers/pdf_file/generators/pil_generator.py +++ b/src/faker_file/providers/pdf_file/generators/pil_generator.py @@ -189,7 +189,7 @@ def generate( lines = textwrap.wrap(content, line_max_num_chars) y_text = 0 - for counter, line in enumerate(lines): + for _counter, line in enumerate(lines): # text_width, text_height = self.draw.textsize( # line, font=font, spacing=self.spacing # ) diff --git a/src/faker_file/tests/_conftest.py b/src/faker_file/tests/_conftest.py index 289368ec..c4e4da73 100644 --- a/src/faker_file/tests/_conftest.py +++ b/src/faker_file/tests/_conftest.py @@ -4,6 +4,7 @@ running documentation tests. Therefore, this hook, which simply calls the `clean_up` method of the `FILE_REGISTRY` instance. """ +from contextlib import suppress import pytest from faker_file.registry import FILE_REGISTRY @@ -20,34 +21,28 @@ def pytest_collection_modifyitems(config, items): """Modify test items during collection.""" for item in items: - try: + with suppress(ImportError): from pytest_rst import RSTTestItem if isinstance(item, RSTTestItem): # Dynamically add marker to RSTTestItem tests item.add_marker(pytest.mark.documentation) - except ImportError: - pass def pytest_runtest_setup(item): """Setup before test runs.""" - try: + with suppress(ImportError): from pytest_rst import RSTTestItem if isinstance(item, RSTTestItem): # Insert the setup logic here pass # Replace with your desired setup actions - except ImportError: - pass def pytest_runtest_teardown(item, nextitem): """Clean up after test ends.""" - try: + with suppress(ImportError): from pytest_rst import RSTTestItem if isinstance(item, RSTTestItem): FILE_REGISTRY.clean_up() - except ImportError: - pass diff --git a/src/faker_file/tests/sftp_server.py b/src/faker_file/tests/sftp_server.py index fe96dbfe..cffc649a 100644 --- a/src/faker_file/tests/sftp_server.py +++ b/src/faker_file/tests/sftp_server.py @@ -4,6 +4,7 @@ import tempfile import threading from asyncio import Semaphore +from contextlib import suppress from typing import Type import asyncssh @@ -85,10 +86,8 @@ async def start_server_async( ) async with server: - try: + with suppress(asyncio.CancelledError): await server.wait_closed() - except asyncio.CancelledError: - pass def start_server(host: str = SFTP_HOST, port: int = SFTP_PORT) -> None: diff --git a/src/faker_file/tests/test_sftp_server.py b/src/faker_file/tests/test_sftp_server.py index 91992e9c..c5acf6ad 100644 --- a/src/faker_file/tests/test_sftp_server.py +++ b/src/faker_file/tests/test_sftp_server.py @@ -36,14 +36,14 @@ FAKER.add_provider(TxtFileProvider) -class __TestSFTPServerMixin: +class __TestSFTPServerMixin: # noqa: N801 """Test SFTP server mix-in.""" - assertIsInstance: Callable - assertRaises: Callable - assertEqual: Callable - assertTrue: Callable - assertFalse: Callable + assertIsInstance: Callable # noqa: N815 + assertRaises: Callable # noqa: N815 + assertEqual: Callable # noqa: N815 + assertTrue: Callable # noqa: N815 + assertFalse: Callable # noqa: N815 sftp_host: str sftp_port: int sftp_user: str @@ -65,15 +65,17 @@ def free_port(cls: "__TestSFTPServerMixin") -> None: time.sleep(1) async def test_successful_connection(self: "__TestSFTPServerMixin") -> None: - async with asyncssh.connect( - self.sftp_host, - port=self.sftp_port, - username=self.sftp_user, - password=self.sftp_pass, - known_hosts=None, - ) as conn: - async with conn.start_sftp_client() as sftp: - self.assertIsInstance(sftp, asyncssh.SFTPClient) + async with ( + asyncssh.connect( + self.sftp_host, + port=self.sftp_port, + username=self.sftp_user, + password=self.sftp_pass, + known_hosts=None, + ) as conn, + conn.start_sftp_client() as sftp + ): + self.assertIsInstance(sftp, asyncssh.SFTPClient) async def test_failed_connection(self: "__TestSFTPServerMixin") -> None: with self.assertRaises(asyncssh.PermissionDenied): @@ -87,49 +89,53 @@ async def test_failed_connection(self: "__TestSFTPServerMixin") -> None: pass async def test_file_upload(self: "__TestSFTPServerMixin") -> None: - async with asyncssh.connect( - self.sftp_host, - port=self.sftp_port, - username=self.sftp_user, - password=self.sftp_pass, - known_hosts=None, - ) as conn: - async with conn.start_sftp_client() as sftp: - test_file = FAKER.txt_file() - await sftp.put( - test_file.data["filename"], "/testfile_upload.txt" - ) - - # Read back the file and check its contents - async with sftp.open( - "/testfile_upload.txt", "r" - ) as uploaded_file: - uploaded_contents = await uploaded_file.read() - - self.assertEqual(test_file.data["content"], uploaded_contents) - FILE_REGISTRY.clean_up() + async with ( + asyncssh.connect( + self.sftp_host, + port=self.sftp_port, + username=self.sftp_user, + password=self.sftp_pass, + known_hosts=None, + ) as conn, + conn.start_sftp_client() as sftp + ): + test_file = FAKER.txt_file() + await sftp.put( + test_file.data["filename"], "/testfile_upload.txt" + ) + + # Read back the file and check its contents + async with sftp.open( + "/testfile_upload.txt", "r" + ) as uploaded_file: + uploaded_contents = await uploaded_file.read() + + self.assertEqual(test_file.data["content"], uploaded_contents) + FILE_REGISTRY.clean_up() async def test_file_delete(self: "__TestSFTPServerMixin") -> None: - async with asyncssh.connect( - self.sftp_host, - port=self.sftp_port, - username=self.sftp_user, - password=self.sftp_pass, - known_hosts=None, - ) as conn: - async with conn.start_sftp_client() as sftp: - test_file = FAKER.txt_file() - await sftp.put( - test_file.data["filename"], "/testfile_delete.txt" - ) - - # Ensure the file exists - self.assertTrue(await sftp.exists("/testfile_delete.txt")) - - # Delete the file and ensure it's gone - await sftp.remove("/testfile_delete.txt") - self.assertFalse(await sftp.exists("/testfile_delete.txt")) - FILE_REGISTRY.clean_up() + async with ( + asyncssh.connect( + self.sftp_host, + port=self.sftp_port, + username=self.sftp_user, + password=self.sftp_pass, + known_hosts=None, + ) as conn, + conn.start_sftp_client() as sftp + ): + test_file = FAKER.txt_file() + await sftp.put( + test_file.data["filename"], "/testfile_delete.txt" + ) + + # Ensure the file exists + self.assertTrue(await sftp.exists("/testfile_delete.txt")) + + # Delete the file and ensure it's gone + await sftp.remove("/testfile_delete.txt") + self.assertFalse(await sftp.exists("/testfile_delete.txt")) + FILE_REGISTRY.clean_up() class TestSFTPServerWithStartServerAsync( diff --git a/src/faker_file/tests/test_sftp_storage.py b/src/faker_file/tests/test_sftp_storage.py index 0bf471ec..bb856c75 100644 --- a/src/faker_file/tests/test_sftp_storage.py +++ b/src/faker_file/tests/test_sftp_storage.py @@ -200,11 +200,11 @@ def test_storage_generate_filename_exceptions( """Test storage `generate_filename` exceptions.""" storage = storage_cls(**kwargs) - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 # Generate filename storage.generate_filename(prefix=prefix, extension=extension) - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 # Generate filename storage.generate_filename(basename=prefix, extension=extension) @@ -289,7 +289,7 @@ def test_storage_initialization_exceptions( self: "TestSFTPStorageTestCase", kwargs: Dict[str, Any], ) -> None: - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 # Initialize the storage SFTPStorage(**kwargs) diff --git a/src/faker_file/tests/test_storages.py b/src/faker_file/tests/test_storages.py index e115e1ac..d36c8b8b 100644 --- a/src/faker_file/tests/test_storages.py +++ b/src/faker_file/tests/test_storages.py @@ -241,11 +241,11 @@ def test_storage_generate_filename_exceptions( """Test storage `generate_filename` exceptions.""" storage = storage_cls(**kwargs) - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 # Generate filename storage.generate_filename(prefix=prefix, extension=extension) - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 # Generate filename storage.generate_filename(basename=prefix, extension=extension) @@ -262,7 +262,7 @@ def test_storage_initialization_exceptions( kwargs: Dict[str, Any], ) -> None: """Test storage initialization exceptions.""" - with self.assertRaises(Exception): + with self.assertRaises(Exception): # noqa: B017 # Initialize the storage storage_cls(**kwargs)
{text}