### Setuptools Deprecation Warning Example Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/micro_features/build_system_migration.md This warning indicates that `setup.py install` is deprecated and suggests using modern tools like pypa/build or pypa/installer. Review the linked article for detailed explanations. ```text C:\Code\ApprovalTests.Python\.venv\lib\site-packages\setuptools\_distutils\cmd.py:66: SetuptoolsDeprecationWarning: setup.py install is deprecated. ******************************************************************************** Instead, use pypa/build, pypa/installer or other standards-based tools. See https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html for details. ******************************************************************************** ``` -------------------------------- ### Install Development Requirements Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/setting_up_a_dev_machine.md Use this command to install all necessary development dependencies. ```bash pip install -r requirements.dev.txt ``` -------------------------------- ### Install ApprovalTests and Pytest Source: https://github.com/approvals/approvaltests.python/blob/main/docs/tutorial/minimal-example.md Install the necessary libraries using pip. Ensure you have pytest and the pytest-approvaltests plugin. ```bash pip install pytest approvaltests pytest-approvaltests ``` -------------------------------- ### Example Combination Test Output Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/test_combinations_of_inputs.md This is an example of the output generated by `verify_all_combinations` before the lambda function is implemented. It lists all input combinations. ```txt args: ('input1.value1', 'input2.value1') => 'placeholder' args: ('input1.value1', 'input2.value2') => 'placeholder' args: ('input1.value1', 'input2.value3') => 'placeholder' args: ('input1.value2', 'input2.value1') => 'placeholder' args: ('input1.value2', 'input2.value2') => 'placeholder' args: ('input1.value2', 'input2.value3') => 'placeholder' ``` -------------------------------- ### Example Log Output for Method Inputs Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/log_method_parameter_values.md This is an example of the log output generated when logging only method input parameters. ```txt -> in: method_with_inputs(number = 1, name = Susan) in test_simple_logger <- out: method_with_inputs() ``` -------------------------------- ### Example Log Output for Method Inputs and Outputs Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/log_method_parameter_values.md This is an example of the log output generated when logging both method input and output parameters. ```txt -> in: method_with_inputs_and_outputs(number = 10, announcement = Blast off) in test_simple_logger <- out: method_with_inputs_and_outputs(number = 1, announcement = Blast off) ``` -------------------------------- ### Pytest Example for ApprovalTests Source: https://github.com/approvals/approvaltests.python/blob/main/README.md Use this snippet to verify simple string outputs with ApprovalTests within a pytest test function. Ensure pytest-approvaltests is installed and a reporter is configured. ```python from approvaltests.approvals import verify def test_simple() -> None: result = "Hello ApprovalTests" verify(result) ``` -------------------------------- ### Arlo's Git Notation Examples Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/commit_notation.md Examples demonstrating the application of Arlo's Git notation in commit messages. ```git . d Update TODO ``` ```git . t Add test for such-and-such ``` ```git - r extract function ``` ```git ! F add custom date format scrubbers ``` -------------------------------- ### Starter Code for Combination Testing Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/test_combinations_of_inputs.md This is a starting point for setting up combination tests. Define your input lists and pass them to `verify_all_combinations` with a placeholder lambda function. ```python inputs1 = ["input1.value1", "input1.value2"] inputs2 = ["input2.value1", "input2.value2", "input2.value3"] verify_all_combinations(lambda a, b: "placeholder", [inputs1, inputs2]) ``` -------------------------------- ### Mise Task Configuration Example Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/micro_features/repo_setup.md An example of how tasks are defined in `.mise.toml`. Tasks should execute a single command or delegate to other tasks, and use `--quiet` flags for minimal output. ```toml [tasks.build_and_test] script = "mise task --quiet run build_and_test" [tasks.tidy_code] script = "mise task --quiet run tidy_code" [tasks.update_docs] script = "mise task --quiet run update_docs" [tasks.run] script = "mise task --quiet run run" ``` -------------------------------- ### Example Approved File Content Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/multiple_approvals_per_test.md This is an example of an approved file content for a leap year test, showing the expected output format. ```txt is Leap 1992: True ``` -------------------------------- ### Sample ApprovalTests Configuration File Source: https://github.com/approvals/approvaltests.python/blob/main/docs/configuration.md An example of an approvaltests_config.json file used for directory-level configuration, specifying a subdirectory for approved files. ```json { "subdirectory": "approved_files" } ``` -------------------------------- ### Log Method Input Parameters with SimpleLogger Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/log_method_parameter_values.md Use SimpleLogger.use_markers with a formatted string to log input parameters at the start of a method. Ensure SimpleLogger is imported. ```python def method_with_inputs(number: int, name: str) -> None: with SimpleLogger.use_markers(f"number = {number}, name = {name}"): ``` -------------------------------- ### Python Exception Example Source: https://github.com/approvals/approvaltests.python/blob/main/tests/approved_files/test_simple_logger.test_warnings.approved.txt This example demonstrates raising a custom exception in Python, which would be caught and displayed by ApprovalTests. ```python raise Exception("EVERYTHING IS exceptionally AWFUL!!!!!!") ``` -------------------------------- ### Unittest Example for ApprovalTests Source: https://github.com/approvals/approvaltests.python/blob/main/README.md This snippet demonstrates how to use ApprovalTests with Python's built-in unittest framework. It provides the same verification functionality as the pytest example. ```python import unittest from approvaltests.approvals import verify class GettingStartedTest(unittest.TestCase): def test_simple(self) -> None: verify("Hello ApprovalTests") if __name__ == "__main__": unittest.main() ``` -------------------------------- ### Write Initial Test for Counting Vowels Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/inline_approvals_with_parse_input.md Start by writing an empty implementation with one input. This snippet sets up the initial test structure. ```python def count_vowels(s: str) -> int: return 0 def test_count_vowels(): """ Kody """ parse = Parse.doc_string(auto_approve=True) parse.verify_all(count_vowels) ``` -------------------------------- ### Extra Production Dependencies Source: https://github.com/approvals/approvaltests.python/blob/main/README.md Optional dependencies for specific features like clipboard reporting, HTML verification, pairwise combinations, and logging verification. Install 'approvaltests_minimal' for the bare minimum. ```txt # For reporters.clipboard_reporter.ClipboardReporter pyperclip>=1.5.29 # For approvals.verify_html() beautifulsoup4>=4.9.0 # For pairwise_combinations.get_best_covering_pairs() allpairspy>=2.1.0 # For utilities.logging.logging_approvals.verify_logging() testfixtures >= 7.1.0, < 12 mock >= 5.1.0 ``` -------------------------------- ### Bash Script Example for build_and_test Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/micro_features/repo_setup.md A typical bash script for build and test tasks. It ensures Mise is available and delegates the actual task execution to `mise task --quiet run NAME`. Scripts should have no extension. ```bash set -euo pipefail mise task --quiet run build_and_test ``` -------------------------------- ### Named Input Combination Test Output Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/test_combinations_of_inputs.md This is an example of the output generated by `verify_all_combinations_with_labeled_input`. It shows the input values paired with their corresponding argument names. ```txt (arg1: 1, arg2: 2) => 4 (arg1: 1, arg2: 4) => 6 (arg1: 3, arg2: 2) => 6 (arg1: 3, arg2: 4) => 8 ``` -------------------------------- ### Pytest Test Session Summary (Success) Source: https://github.com/approvals/approvaltests.python/blob/main/docs/tutorial/minimal-example.md Example output showing a successful test run after approving results, with all tests passing. ```bash ========================================================================================================= test session starts ========================================================================================================= platform win32 -- Python 3.6.7, pytest-7.0.1, pluggy-1.0.0 rootdir: C:\Code\approvaltests.minimal.example plugins: approvaltests-0.2.4 collected 1 item test_with_approvals.py . [100%] ========================================================================================================== 1 passed in 0.05s ========================================================================================================== ``` -------------------------------- ### Handle Two Parameters with Transformations Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/inline_approvals_with_parse_input.md Shows how to handle multiple parameters by using multiple transform calls. This example verifies a function that repeats a string a specified number of times. ```python def test_with_two_parameters() -> None: """ a, 3 -> aaa !, 7 -> !!!!!!! """ parse = Parse.doc_string(auto_approve=True) parse.transform2(str, int).verify_all(lambda s, i: s * i) ``` -------------------------------- ### Pytest Session Start Information Source: https://github.com/approvals/approvaltests.python/blob/main/docs/tutorial/minimal-example.md This section of the output provides details about the pytest session, including the platform, Python version, pytest version, and loaded plugins. ```text ========================================================================================================= test session starts ========================================================================================================= platform win32 -- Python 3.6.7, pytest-7.0.1, pluggy-1.0.0 rootdir: C:\Code\approvaltests.minimal.example plugins: approvaltests-0.2.4 collected 1 item ``` -------------------------------- ### Create a Verifiable Object for Markdown Verification Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/create_custom_verify_methods.md Implement the `Verifiable` interface to allow custom objects to control their verification. This example shows how to verify an object as a Markdown file. ```python def test_verifiable(self): class MarkdownParagraph(Verifiable): def __init__(self, title: str, text: str) -> None: self.title = title self.text = text @override def __str__(self) -> str: return remove_indentation_from( f""" # {self.title} {self.text} """ ) @override def get_verify_parameters(self, options: Options) -> VerifyParameters: return VerifyParameters(options.for_file.with_extension(".md")) verify( MarkdownParagraph("Paragraph Title", "This is where the paragraph text is.") ) ``` -------------------------------- ### Handling Exceptions with ApprovalTests Logger Source: https://github.com/approvals/approvaltests.python/blob/main/tests/approved_files/test_simple_logger.test_run_combinations_with_exception_handler.approved.txt This example shows how ApprovalTests captures and displays exceptions that occur during the execution of a function. ```python ******************************************************************************************* Exception: AHHHHHH! ******************************************************************************************* ``` -------------------------------- ### Verify Dictionary as JSON Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/verify_a_dictionary.md Use `verify_as_json()` to format dictionaries with one key per line for improved readability and cleaner diffs. This example uses `inline()` options for compact output. ```python def test_verify_dict() -> None: """ { "k1": "v1", "k2": "v2" } """ d = {"k1": "v1", "k2": "v2"} verify_as_json(d, options=Options().inline()) ``` -------------------------------- ### Python Type Hinting Example Source: https://github.com/approvals/approvaltests.python/blob/main/mob-sessions-retros/2023-08-13.md Demonstrates the use of type hints in a Python class constructor for improved code readability and auto-completion. Ensure type hints are used for better developer experience. ```python def __init__(self, template: str): ``` -------------------------------- ### Storyboard Approved Output Source: https://github.com/approvals/approvaltests.python/blob/main/docs/reference/storyboard.md This is an example of the approved output for a simple storyboard, showing the description and frame content. It is typically generated by ApprovalTests during verification. ```txt Spinning wheel Initial: - Frame #1: \ ``` -------------------------------- ### Pytest Test Session Summary (Failure) Source: https://github.com/approvals/approvaltests.python/blob/main/docs/tutorial/minimal-example.md Example output showing a failed test due to an ApprovalException, indicating a mismatch between received and approved results. ```bash ======================================================================================================= short test summary info ======================================================================================================= FAILED test_with_approvals.py::test_with_approvals - approvaltests.approval_exception.ApprovalException: Approval Mismatch, received != approved ========================================================================================================== 1 failed in 0.53s ========================================================================================================== ``` -------------------------------- ### Approved text output for date scrubbing Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/scrub_dates.md This is an example of the approved text output after a date has been scrubbed. The date is replaced with a generic placeholder like ``. ```txt created at ``` -------------------------------- ### Windows Batch Script Example Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/micro_features/repo_setup.md A Windows batch script that invokes the corresponding bash script using Git Bash. This ensures cross-platform compatibility for development tasks. ```batch @"%ProgramFiles%\Git\bin\bash.exe" %~dpn0 %* ``` -------------------------------- ### Python File Diff Example Source: https://github.com/approvals/approvaltests.python/blob/main/tests/reporters/approved_files/test_python_native_reporter.test_files_differ.approved.txt This snippet shows the content of two files, 'b.approved.txt' and 'a.received.txt', highlighting the difference detected by ApprovalTests. The diff indicates that the line 'def' was replaced with 'abc'. ```diff --- b.approved.txt +++ a.received.txt @@ -1 +1 @@ -def +abc ``` -------------------------------- ### Add Custom Date Scrubber Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/micro_features/add_date_scrubber.md Register a custom date format pattern with a regex. The regex is validated for syntax and its ability to match the provided example date. A message is displayed by default when a custom scrubber is added. ```python DateScrubber.add_scrubber("2023-Dec-25", r"\d{4}-[A-Za-z]{3}-\d{2}") ``` -------------------------------- ### Create and Verify a Storyboard Source: https://github.com/approvals/approvaltests.python/blob/main/docs/reference/storyboard.md Use this snippet to create a Storyboard, add descriptions and frames, and then verify its content. Ensure the necessary objects like `ascii_wheel` are defined and advanced before adding frames. ```python story = Storyboard() story.add_description("Spinning wheel") story.add_frame(ascii_wheel) ascii_wheel.advance() story.add_frame(ascii_wheel) verify(story) ``` -------------------------------- ### Configure ApprovalTests in __init__.py Source: https://github.com/approvals/approvaltests.python/blob/main/docs/configuration.md Initializes ApprovalTests configuration by calling the configure_approvaltests function. This is recommended for unittest frameworks. ```python # From __init__.py configure_approvaltests() ``` -------------------------------- ### Approve Sample Log Output Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/verify_both_logs_and_results.md This snippet shows the expected log output for a function call. It is used as a reference for verification. ```txt root INFO connecting to the database root INFO querying a table root INFO closing the database ``` -------------------------------- ### Log Method Input and Output Parameters with SimpleLogger Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/log_method_parameter_values.md To log parameters at both method entry and exit, use SimpleLogger.use_markers with a lambda function that returns a formatted string. This allows capturing values at different points. ```python def method_with_inputs_and_outputs(number: int, announcement: str) -> None: with SimpleLogger.use_markers( lambda: f"number = {number}, announcement = {announcement}" ): ``` -------------------------------- ### Temporary Directory Handling Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/code_style.md Use this pattern for creating and managing temporary directories, ensuring proper cleanup. ```python with tempfile.TemporaryDirectory() as _temporary_directory: temporary_directory = pathlib.Path(_temporary_directory) ``` -------------------------------- ### Verify with Inline Options (Spaces) Source: https://github.com/approvals/approvaltests.python/blob/main/tests/approved_files/test_split_code.test_splitting_code.approved.txt This snippet demonstrates using verify with inline options, specifically when spaces are used for indentation. ```python def other_code(): pass def testy_mctest(): after: verify(greeting(), options = Options().inline()) def greeting(): # start of greeting() method return "using spaces instead of tabs" ``` -------------------------------- ### Approve Result Command Line Source: https://github.com/approvals/approvaltests.python/blob/main/tests/reporters/approved_files/test_python_native_reporter.test_files_differ.approved.txt This is a placeholder for a command-line instruction to approve a test result. The exact command will vary based on the ApprovalTests setup and environment. ```bash ``` -------------------------------- ### Approve Sample Result Output Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/verify_both_logs_and_results.md This snippet displays the expected JSON output for a function call. It serves as a reference for verifying the returned data structure. ```txt { "first_name":"Britney", "last_name": "Spears", "profession":"Singer" } ``` -------------------------------- ### Python File Handling with Context Manager Source: https://github.com/approvals/approvaltests.python/blob/main/mob-sessions-retros/2023-09-24 Session Notes.md Demonstrates reading content from a file using Python's `with open()` statement, which ensures the file is automatically closed after the block. ```python with open('myfile.txt', 'r') as f: content = f.read() # Do something with the content... # File is automatically closed outside the "with" block ``` -------------------------------- ### Create Custom GenericDiffReporter On-the-Fly Source: https://github.com/approvals/approvaltests.python/blob/main/README.md Create a GenericDiffReporter instance dynamically for a custom diff utility. The utility must be invokable from the command line with the format 'utility.exe file1 file2'. ```python class GettingStartedTest(unittest.TestCase): def test_simple(self): verify( "Hello", options=Options().with_reporter( GenericDiffReporter.create(r"C:\my\favorite\diff\utility.exe") ), ) ``` -------------------------------- ### Format Code with Script Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/setting_up_a_dev_machine.md Execute this script to format your code according to project standards. This is also run automatically by the CI. ```bash ./format_code.sh ``` -------------------------------- ### Add Custom Date Scrubber with Message Suppression Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/micro_features/add_date_scrubber.md Register a custom date format pattern with a regex, suppressing the default informational message. The regex is validated for syntax and its ability to match the provided example date. ```python DateScrubber.add_scrubber("", "", display_message=False) ``` -------------------------------- ### PyPI Release Flowchart Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/micro_features/build_system_migration.md Visual representation of the PyPI release process for multiple packages from a single monorepo, highlighting dependencies and build methods. ```text ┌──────────────────────┐ │ Single Monorepo │ │ (ApprovalTests.Py) │ └──────────┬───────────┘ │ ┌──────────────────┼──────────────────┐ │ │ │ ▼ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ RELEASE 1 │ │ RELEASE 2 │ │ RELEASE 3 │ │ │ │ │ │ │ │ approval_ │ │ approvaltests │ │ approvaltests- │ │ utilities │ │ (full) │ │ minimal │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │ │ │ │ │ │ ┌────────▼────────┐ ┌────────▼────────┐ ┌────────▼────────┐ │ File Swapping │ │ Direct Build │ │ Direct Build │ │ (setup.py hack) │ │ (setup.approvaltests) │ │ (setup.approvaltests_minimal) │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ ┌────────▼────────┐ ┌────────▼────────┐ ┌────────▼────────┐ │ Source: │ │ Source: │ │ Source: │ │ approval_ │ │ approvaltests/ │ │ approvaltests/ │ │ utilities/ │ │ │ │ (same source!) │ │ │ │ Deps: required │ │ │ │ Deps: none │ │ + extras │ │ Deps: required │ │ │ │ + approval_ │ │ only │ │ │ │ utilities │ │ │ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │ │ │ │ │ │ └─────────┬─────────┴─────────┬─────────┘ │ │ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ │ PyPI Package │ │ PyPI Package │ │ approval_ │ │ approvaltests │ │ utilities │ │ (2 variants) │ └─────────────────┘ └─────────────────┘ ═══════════════════════════════════════════════════════════════════════ RELEASE CONSTRAINTS ═══════════════════════════════════════════════════════════════════════ Order Dependency: approval_utilities ──must publish before──► approvaltests (full) Same Source: approvaltests (full) ═══ same code ═══ approvaltests_minimal (only dependency configuration differs) ``` -------------------------------- ### Approve Rendered Images with verify_binary Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/verify-binary.md Use `verify_binary` to approve rendered images by reading the image file in binary mode and passing its content to the function. ```python name = "icon.png" filename = get_adjacent_file(name) with open(filename, mode="rb") as f: verify_binary(f.read(), ".png") ``` -------------------------------- ### AI Fixer Loop Sample Output Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/ai_fixer_loop.md Illustrates the expected output of the AI fixer loop, showing the progress of runs, problem detection, fixing attempts, and commit/revert status. ```text ✅ build working Run #1 ✅ found problems [0:21] ✅ fix problem [0:22] ✅ tcr: committed [0:23] ----------------------------- Run #2 ✅ found problems [0:21] ✅ fix problem [0:22] ❌ tcr: reverted [0:23] ----------------------------- Run #3 ✅ found problems [0:21] ✅ fix problem [0:22] ✅ tcr: committed [0:23] ---------------------------- Run #4 no more problems found. ``` -------------------------------- ### Required Production Dependencies Source: https://github.com/approvals/approvaltests.python/blob/main/README.md These are the core dependencies always required for ApprovalTests.Python. ```txt pytest>=9.0.3 empty-files>=0.0.3 ``` -------------------------------- ### Basic Approval Test Source: https://github.com/approvals/approvaltests.python/blob/main/tests/approved_files/test_options.test_list_of_modules.approved.txt Use this for standard file-based approvals. Ensure the output file is correctly generated and matches the expected result. ```python from approvaltests import approvals def test_basic_approval(): approvals.verify("Hello, ApprovalTests!") ``` -------------------------------- ### Publishing Workflow for PyPI Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/micro_features/build_system_migration.md GitHub Actions workflow for publishing multiple Python packages to PyPI. Ensures sequential publishing and version synchronization. ```yaml name: Publish to PyPI # Trigger: On GitHub release publication or manual dispatch # Process: # 1. Setup Environment # ├─► Python 3.x (latest) # ├─► Install: pip, setuptools, wheel, twine # └─► Extract version from git tag # # 2. Version Management # ├─► Update version.py with git tag # ├─► Copy to approvaltests/version.py # └─► Commit and push to main branch # # 3. Sequential Publishing (CRITICAL ORDER) # ├─► publish.approval_utilities.sh # │ └─► Auth: secrets.PYPI_APPROVAL_UTILITIES # │ # ├─► publish.approvaltests.sh # │ └─► Auth: secrets.PYPI_PASSWORD # │ # └─► publish.approvaltests_minimal.sh # └─► Auth: secrets.PYPI_APPROVALTESTS_MINIMAL # Key Points: # - 3 separate PyPI tokens (one per package) # - Sequential execution ensures `approval_utilities` publishes first # - Version synchronization across all packages from single git tag # - Uses deprecated `setup.py` commands (source of warnings) # This is a placeholder for the actual workflow file content. # The actual file would contain YAML steps for setup, versioning, and publishing. # Example structure: # on: [release, workflow_dispatch] # jobs: # publish: # runs-on: ubuntu-latest # steps: # - uses: actions/checkout@v3 # - name: Set up Python # uses: actions/setup-python@v3 # with: # python-version: '3.x' # - name: Install dependencies # run: pip install --upgrade pip setuptools wheel twine # - name: Extract version # run: | # # Logic to extract version from git tag and update version.py # - name: Publish approval_utilities # run: ./publish.approval_utilities.sh # env: # PYPI_TOKEN: ${{ secrets.PYPI_APPROVAL_UTILITIES }} # - name: Publish approvaltests # run: ./publish.approvaltests.sh # env: # PYPI_TOKEN: ${{ secrets.PYPI_PASSWORD }} # - name: Publish approvaltests_minimal # run: ./publish.approvaltests_minimal.sh # env: # PYPI_TOKEN: ${{ secrets.PYPI_APPROVALTESTS_MINIMAL }} ``` -------------------------------- ### Generate Separate Approved Files for Logs and Results Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/verify_both_logs_and_results.md This Python code uses `verify_logging` with `NamerFactory` to create two distinct approved files: one for logs and one for the function's result. This is ideal when you need to manage and review logs and results independently. ```python def test_load_person_logs_and_results_separately(): with verify_logging(options=NamerFactory.with_parameters("logging")): verify(load_person()) ``` -------------------------------- ### Mise Idiomatic Version File Configuration Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/micro_features/repo_setup.md Configuration in `.mise.toml` to enable the use of idiomatic version files (e.g., `.python-version`) for managing tool versions, particularly useful for CI. ```toml idiomatic_version_file_enable_tools = ["python", "node"] ``` -------------------------------- ### Verify with Inline Options (Tabs) Source: https://github.com/approvals/approvaltests.python/blob/main/tests/approved_files/test_split_code.test_splitting_code.approved.txt This snippet demonstrates using verify with inline options, specifically when the tab character is used for indentation. ```python def other_code(): pass def testy_mctest(): after: verify(greeting(), options = Options().inline()) def greeting(): # start of greeting() method return "using tabs" ``` -------------------------------- ### Approve NumPy Arrays with verify_binary and Custom Reporter Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/verify-binary.md Demonstrates approving NumPy arrays using `verify_binary` with serialization and a custom reporter for detailed diffing. This is useful for scientific applications. ```python def test_simulator_produces_correct_output() -> None: np_array = np.full(shape=(32, 16), fill_value=42, dtype=np.int64) verify_binary( serialize_ndarray(np_array), ".npy", options=Options().with_reporter(NDArrayDiffReporter()), ) ``` -------------------------------- ### Create Custom verify_as_json Method Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/create_custom_verify_methods.md Use this method to verify objects as JSON. It handles JSON deserialization and formats the output with a .json extension. ```python def verify_as_json( object_to_verify: Any, reporter: Reporter | None = None, *, deserialize_json_fields: bool = False, options: Options | None = None, ) -> None: if deserialize_json_fields: object_to_verify = utils.deserialize_json_fields(object_to_verify) options = initialize_options(options, reporter) json_text = utils.to_json(object_to_verify) + "\n" verify( json_text, None, encoding="utf-8", newline="\n", options=options.for_file.with_extension(".json"), ) ``` -------------------------------- ### Create and Verify Markdown Table Source: https://github.com/approvals/approvaltests.python/blob/main/docs/reference/markdown_table.md Use `MarkdownTable` to define headers and add rows for multiple inputs, applying different conversion functions. This is useful for testing the same inputs against various transformations. ```python inputs = ["verify json", "verify all", "verify parameters", "verify as json"] table = MarkdownTable.with_headers( "Input", "Camel Case", "Snake Case", "Kebab Case" ) table.add_rows_for_inputs(inputs, to_camel_case, to_snake_case, to_kebab_case) verify(table) ``` -------------------------------- ### Verify with Inline Options (No Docstring) Source: https://github.com/approvals/approvaltests.python/blob/main/tests/approved_files/test_split_code.test_splitting_code.approved.txt This snippet shows verification with inline options when the greeting function does not include a docstring. ```python def other_code(): pass def testy_mctest(): after: verify(greeting(), options = Options().inline()) def greeting(): # start of greeting() method return "not using docstring" ``` -------------------------------- ### Select Reporter Directly From Class Source: https://github.com/approvals/approvaltests.python/blob/main/README.md Use this method to directly specify a reporter class when configuring options. Ensure the reporter class is imported. ```python class TestSelectReporterFromClass(unittest.TestCase): def test_simple(self): verify("Hello", options=Options().with_reporter(ReportWithBeyondCompare())) ``` -------------------------------- ### Select Reporter Using GenericDiffReporterFactory Source: https://github.com/approvals/approvaltests.python/blob/main/README.md Utilize the GenericDiffReporterFactory to find and select the first available diff utility on your system. This allows for system-specific reporter configurations via reporters.json. ```python class TestSelectReporter(unittest.TestCase): @override def setUp(self): self.factory = GenericDiffReporterFactory() def test_simple(self): verify( "Hello", options=Options().with_reporter(self.factory.get("BeyondCompare")) ) ``` -------------------------------- ### Verify Simple Logger Context Manager Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/test_logs.md Use `verify_simple_logger` as a context manager to capture and verify all logs within the `with` block. This is suitable for testing simple logger outputs. ```python def test_variable() -> None: with verify_simple_logger(): SimpleLogger.variable("dalmatians", 101, show_types=True) SimpleLogger.variable("dalmatians", 101, show_types=False) ``` -------------------------------- ### Create a Basic Approval Test Source: https://github.com/approvals/approvaltests.python/blob/main/docs/tutorial/minimal-example.md Define a simple test function that uses `verify` to check a string. This is the core of an ApprovalTests test. ```python from approvaltests import verify def test_with_approvals(): verify("Hello World") ``` -------------------------------- ### Run Pytest with ApprovalTests Reporter Source: https://github.com/approvals/approvaltests.python/blob/main/docs/tutorial/minimal-example.md Execute pytest with the ApprovalTests plugin, specifying the reporter to use. This command initiates the test and generates received files. ```bash python -m pytest . --approvaltests-use-reporter='PythonNativeReporter' ``` -------------------------------- ### Set File Extension Option Source: https://github.com/approvals/approvaltests.python/blob/main/docs/features.md Demonstrates how to set a custom file extension for approval files using the Options API. This is useful for organizing approval files by type. ```python verify(content, options=Options().for_file.with_extension(".md")) ``` -------------------------------- ### Test Person Logs with verify_logging Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/verify_both_logs_and_results.md Use `verify_logging()` to test only the log output of a function. Ensure the `verify_logging` context manager is imported. ```python def test_load_person_logs(): with verify_logging(): load_person() ``` -------------------------------- ### Login to GitHub CLI Source: https://github.com/approvals/approvaltests.python/blob/main/internal_documentation/github_guidelines.md Authenticate with GitHub CLI using HTTPS, the default hostname, and enabling web-based login with clipboard support. This is the recommended method for interacting with GitHub repositories. ```bash gh auth login --git-protocol https --hostname github.com --web --clipboard ``` -------------------------------- ### Command Line Approvals Source: https://github.com/approvals/approvaltests.python/blob/main/tests/approved_files/test_options.test_list_of_modules.approved.txt Integrates ApprovalTests with command-line execution. Verifies the output of command-line tools or scripts. ```python from approvaltests.utilities import command_line_approvals def test_command_line(): command_line_approvals.verify("echo Hello World") ``` -------------------------------- ### Add Custom Date Scrubber Source: https://github.com/approvals/approvaltests.python/blob/main/tests/scrubbers/test_date_scrubber.test_unsupported_format.approved.txt Add a custom date scrubber to handle unsupported date formats. Provide a unique name for the scrubber and a regular expression to match the date pattern. ```python DateScrubber.add_scrubber("AN_UNSUPPORTED_DATE_FORMAT", "") ``` -------------------------------- ### Verify Logged String Output Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/test_logs.md Capture log output to a string using `SimpleLogger.log_to_string()` and then verify the captured string. This provides explicit control over when logging occurs and when verification happens. ```python def test_variable_explict() -> None: output = SimpleLogger.log_to_string() SimpleLogger.variable("dalmatians", 101, show_types=True) SimpleLogger.variable("dalmatians", 101, show_types=False) verify(output) ``` -------------------------------- ### Verify All Combinations of Inputs Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/test_combinations_of_inputs.md Use this function to generate and verify all possible combinations of inputs for a given function. Provide the function and a list of lists, where each inner list contains the values for one parameter. ```python verify_all_combinations(is_awake, [["Monday", "Sunday"], ["7:00", "9:00", "11:00"]]) ``` -------------------------------- ### Implement and Rerun with Multiple Test Cases Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/inline_approvals_with_parse_input.md Implement the function logic and rerun tests. Add more lines to the docstring to include additional test cases, such as 'Teresa' and 'Green'. ```python def count_vowels(s: str) -> int: return sum(1 for c in s if c in "aeo") def test_count_vowels(): """ Kody -> 1 Teresa -> 3 Green -> 2 """ parse = Parse.doc_string(auto_approve=True) parse.verify_all(count_vowels) ``` -------------------------------- ### Logging Function Output with ApprovalTests Source: https://github.com/approvals/approvaltests.python/blob/main/tests/approved_files/test_simple_logger.test_run_combinations_with_exception_handler.approved.txt This snippet demonstrates logging the input and output of a function using ApprovalTests. It captures variables before and after the function call. ```python -> in: function_to_run() in test_simple_logger variable: color = red variable: number = one <- out: function_to_run() ``` ```python -> in: function_to_run() in test_simple_logger variable: color = red variable: number = brie <- out: function_to_run() ``` -------------------------------- ### Transform Input Type for Function Source: https://github.com/approvals/approvaltests.python/blob/main/docs/how_to/inline_approvals_with_parse_input.md Demonstrates transforming input to a specific type before passing it to a function. Here, integers are transformed into their binary string representation. ```python def test_with_transformation() -> None: """ 1 -> 0b1 9 -> 0b1001 """ parse = Parse.doc_string(auto_approve=True) parse.transform(int).verify_all(bin) ```