### Install SnapshotTest using pip Source: https://github.com/syrusakbary/snapshottest/blob/master/README.md This command installs the SnapshotTest library using pip, the Python package installer. It is a prerequisite for using SnapshotTest in your Python projects. ```shell pip install snapshottest ``` -------------------------------- ### Example Snapshot File Structure and Content in Python Source: https://context7.com/syrusakbary/snapshottest/llms.txt Illustrates the typical file structure for storing snapshots generated by Snapshottest, including the location of snapshot data files and directories for file snapshots. It also provides an example of the content within a snapshot file, showcasing how different data types like dictionaries, strings, and custom objects are represented. ```text project/ ├── tests/ │ ├── test_api.py │ └── snapshots/ │ ├── __init__.py │ ├── snap_test_api.py # Snapshot data file │ └── snap_test_api/ # File snapshots directory │ ├── test_file_output 1.txt │ └── test_csv_export users_export.csv ``` ```python # -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import GenericRepr, Snapshot snapshots = Snapshot() snapshots['test_api_endpoint 1'] = { 'url': '/users/me', 'status': 'success', 'data': { 'user_id': 123 } } snapshots['test_unicode_content 1'] = 'Héllo Wörld! 日本語' snapshots['CustomObjectTestCase::test_database_connection 1'] = GenericRepr("DatabaseConnection(host='localhost', port=5432)") ``` -------------------------------- ### Develop SnapshotTest Dependencies Source: https://github.com/syrusakbary/snapshottest/blob/master/README.md This command installs the development dependencies for SnapshotTest, typically used by contributors. It ensures that the necessary tools and libraries are available for local development and testing. ```shell make develop ``` -------------------------------- ### Running Django Tests and Updating Snapshots Source: https://context7.com/syrusakbary/snapshottest/llms.txt Provides bash commands to execute Django tests and update snapshots. The `--snapshot-update` flag is used when the expected output has changed, typically after modifying templates or API structures. Ensure Django and Snapshottest are installed. ```bash # Run tests normally python manage.py test # Update snapshots when templates change python manage.py test --snapshot-update ``` -------------------------------- ### Django Test Case with Snapshot Testing Source: https://context7.com/syrusakbary/snapshottest/llms.txt Demonstrates how to use Snapshottest within a Django TestCase to snapshot the content of views and API responses. It requires Django and Snapshottest to be installed. The tests assert that the rendered HTML or JSON output matches the stored snapshot. ```python from django.test import Client from snapshottest.django import TestCase from myapp.models import Article class ArticleViewTestCase(TestCase): def setUp(self): """Create test data""" Article.objects.create( title="Test Article", content="This is test content", published=True ) def test_article_list_view(self): """Test the article list page renders correctly""" response = self.client.get("/articles/") self.assertMatchSnapshot(response.content.decode()) def test_article_api_response(self): """Test API JSON response""" response = self.client.get("/api/articles/") self.assertMatchSnapshot(response.json()) def test_article_detail_view(self): """Test article detail page""" article = Article.objects.first() response = self.client.get(f"/articles/{article.pk}/வதாக") self.assertMatchSnapshot(response.content.decode(), "article_detail_html") class SimpleViewTestCase(TestCase): def test_home_page(self): """Test home page content""" response = self.client.get("/") self.assertMatchSnapshot(response.content.decode()) ``` -------------------------------- ### Test SnapshotTest Locally with Tox Source: https://github.com/syrusakbary/snapshottest/blob/master/README.md This command uses Tox to test the SnapshotTest library across multiple Python versions locally. It requires Tox to be installed and helps ensure compatibility with different Python environments. ```shell pip install tox # (if you haven't before) tox ``` -------------------------------- ### Unittest Integration: Assert API Responses Source: https://context7.com/syrusakbary/snapshottest/llms.txt Demonstrates using the snapshottest.TestCase base class for snapshot assertions within standard Python unittest test classes. Includes examples for basic assertions, custom snapshot names, multiple assertions, and list responses. ```python # test_unittest_example.py import unittest import snapshottest def get_user_data(user_id): """Mock function returning user data""" return { "id": user_id, "username": f"user_{user_id}", "email": f"user_{user_id}@example.com", "preferences": {"theme": "dark", "notifications": True}, } class UserAPITestCase(snapshottest.TestCase): def setUp(self): """Setup test fixtures""" self.api_base_url = "/api/v1" def test_get_user_profile(self): """Test user profile endpoint response""" user_data = get_user_data(123) self.assertMatchSnapshot(user_data) def test_get_user_with_custom_name(self): """Test with explicit snapshot name""" user_data = get_user_data(456) self.assertMatchSnapshot(user_data, "user_456_profile") def test_multiple_assertions(self): """Multiple snapshot assertions in one test""" user1 = get_user_data(1) user2 = get_user_data(2) self.assertMatchSnapshot(user1) # Snapshot name: 1 self.assertMatchSnapshot(user2) # Snapshot name: 2 def test_list_response(self): """Test list/collection responses""" users = [get_user_data(i) for i in range(3)] self.assertMatchSnapshot(users) if __name__ == "__main__": unittest.main() ``` -------------------------------- ### Pytest Integration: Assert API Responses Source: https://context7.com/syrusakbary/snapshottest/llms.txt Demonstrates using the pytest 'snapshot' fixture to assert API responses against stored snapshots. Includes examples for basic assertions, custom snapshot names, multiple assertions in a single test, unicode content, complex nested data, and file snapshots. ```python # test_api.py from snapshottest.file import FileSnapshot def api_client_get(url): """Mock API client for demonstration""" return {"url": url, "status": "success", "data": {"user_id": 123}} def test_api_endpoint(snapshot): """Test API response against stored snapshot""" response = api_client_get("/users/me") snapshot.assert_match(response) def test_api_with_custom_name(snapshot): """Test with custom snapshot name for clarity""" response = api_client_get("/users/me") snapshot.assert_match(response, "user_profile_response") # Multiple snapshots in single test error_response = {"error": "Not found", "code": 404} snapshot.assert_match(error_response, "error_response") def test_unicode_content(snapshot): """Test unicode string handling""" content = u"Héllo Wörld! 日本語" snapshot.assert_match(content) def test_complex_nested_data(snapshot): """Test complex nested data structures""" data = { "users": [ {"id": 1, "name": "Alice", "roles": ["admin", "user"]}, {"id": 2, "name": "Bob", "roles": ["user"]}, ], "metadata": { "total": 2, "page": 1, }, "tags": {"active", "verified"}, } snapshot.assert_match(data) def test_file_snapshot(snapshot, tmpdir): """Test binary/text file content against snapshot""" temp_file = tmpdir.join("output.txt") temp_file.write("Generated content: Hello, World!") snapshot.assert_match(FileSnapshot(str(temp_file))) ``` -------------------------------- ### FileSnapshot for Binary and Text File Testing Source: https://context7.com/syrusakbary/snapshottest/llms.txt Demonstrates using `FileSnapshot` to test the content of generated files, including text and potentially binary files. This involves creating temporary files, writing content to them, and then using `snapshot.assert_match` with `FileSnapshot`. The `FileSnapshot` class handles reading the file content for comparison. ```python # test_file_generation.py import os import tempfile from snapshottest.file import FileSnapshot def test_text_file_generation(snapshot): """Test generated text file content""" with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f: f.write("Report Generated\n") f.write("================\n") f.write("Total: 100\n") f.write("Average: 50.5\n") temp_path = f.name try: snapshot.assert_match(FileSnapshot(temp_path)) finally: os.unlink(temp_path) def test_csv_export(snapshot): """Test CSV file export functionality""" with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f: f.write("id,name,email\n") f.write("1,Alice,alice@example.com\n") f.write("2,Bob,bob@example.com\n") temp_path = f.name try: snapshot.assert_match(FileSnapshot(temp_path), "users_export") finally: os.unlink(temp_path) def test_multiple_file_outputs(snapshot, tmpdir): """Test multiple file outputs in single test""" # Generate first file file1 = tmpdir.join("report1.txt") file1.write("Report 1 content") snapshot.assert_match(FileSnapshot(str(file1))) # Generate second file file2 = tmpdir.join("report2.txt") file2.write("Report 2 content") snapshot.assert_match(FileSnapshot(str(file2))) ``` -------------------------------- ### Snapshot Testing with pytest Source: https://github.com/syrusakbary/snapshottest/blob/master/README.md Illustrates snapshot testing using the pytest framework. It shows how to use the `snapshot` fixture to assert API responses against snapshots and how to name custom snapshots. ```python def test_mything(snapshot): """Testing the API for /me""" my_api_response = api.client.get('/me') snapshot.assert_match(my_api_response) # Set custom snapshot name: `gpg_response` my_gpg_response = api.client.get('/me?gpg_key') snapshot.assert_match(my_gpg_response, 'gpg_response') ``` -------------------------------- ### Run SnapshotTest Linting and Tests Source: https://github.com/syrusakbary/snapshottest/blob/master/README.md These commands run the linter to check for code style issues and then execute the full test suite to ensure the library is functioning correctly. They are essential for verifying code quality and stability. ```shell make lint ``` ```shell make test ``` -------------------------------- ### Snapshot Testing with unittest/nose Source: https://github.com/syrusakbary/snapshottest/blob/master/README.md Demonstrates how to use SnapshotTest with Python's built-in unittest framework or the nose test runner. It shows how to assert that an API response matches a stored snapshot, and how to specify custom snapshot names. ```python from snapshottest import TestCase class APITestCase(TestCase): def test_api_me(self): """Testing the API for /me""" my_api_response = api.client.get('/me') self.assertMatchSnapshot(my_api_response) # Set custom snapshot name: `gpg_response` my_gpg_response = api.client.get('/me?gpg_key') self.assertMatchSnapshot(my_gpg_response, 'gpg_response') ``` -------------------------------- ### Unittest Integration: Running and Updating Snapshots Source: https://context7.com/syrusakbary/snapshottest/llms.txt Commands to run unittest tests with snapshottest, including execution via pytest and nosetests. Shows how to update snapshots using the '--snapshot-update' flag with nosetests. ```bash # Run tests python -m pytest test_unittest_example.py # Or with nose nosetests test_unittest_example.py # Update snapshots with nose nosetests --snapshot-update test_unittest_example.py ``` -------------------------------- ### Format SnapshotTest Code Source: https://github.com/syrusakbary/snapshottest/blob/master/README.md This command formats the code according to the project's style guidelines, ensuring consistency and readability. It's a crucial step in the development workflow to maintain code quality. ```shell make format-fix ``` -------------------------------- ### Snapshot Testing with Django Source: https://github.com/syrusakbary/snapshottest/blob/master/README.md Explains how to integrate SnapshotTest with Django projects. It involves configuring the Django test runner and using the provided TestCase to perform snapshot assertions on API responses. ```python TEST_RUNNER = 'snapshottest.django.TestRunner' ``` ```python from snapshottest.django import TestCase class APITestCase(TestCase): def test_api_me(self): """Testing the API for /me""" my_api_response = api.client.get('/me') self.assertMatchSnapshot(my_api_response) ``` -------------------------------- ### Pytest Integration: Running and Updating Snapshots Source: https://context7.com/syrusakbary/snapshottest/llms.txt Commands to run pytest tests with snapshottest. Includes options for normal execution, updating snapshots, and enabling verbose output for detailed comparison information. ```bash # Run tests normally pytest test_api.py # Update snapshots when API changes pytest test_api.py --snapshot-update # Enable verbose snapshot output pytest test_api.py --snapshot-verbose ``` -------------------------------- ### Django Integration: Configure Test Runner Source: https://context7.com/syrusakbary/snapshottest/llms.txt Configuration snippet for Django projects to enable snapshot testing by setting the TEST_RUNNER to 'snapshottest.django.TestRunner' in the settings.py file. ```python # settings.py - Configure Django test runner TEST_RUNNER = 'snapshottest.django.TestRunner' ``` -------------------------------- ### Register Custom Formatter for Money Objects in Python Source: https://context7.com/syrusakbary/snapshottest/llms.txt Demonstrates how to register a custom formatter for a domain-specific object (Money) in Python using Snapshottest. This allows for specialized serialization and comparison of custom types within snapshots. It involves defining a formatter class that inherits from BaseFormatter and implementing methods like can_format, format, get_imports, normalize, and assert_value_matches_snapshot. ```python from snapshottest.formatter import Formatter from snapshottest.formatters import BaseFormatter import snapshottest class Money: """Domain object representing monetary values""" def __init__(self, amount, currency): self.amount = amount self.currency = currency class MoneyFormatter(BaseFormatter): """Custom formatter for Money objects""" def can_format(self, value): return isinstance(value, Money) def format(self, value, indent, formatter): return f"Money({value.amount!r}, {value.currency!r})" def get_imports(self): return [("myapp.models", "Money")] def normalize(self, value, formatter): return (value.amount, value.currency) def assert_value_matches_snapshot(self, test, test_value, snapshot_value, formatter): test.assert_equals( (test_value.amount, test_value.currency), snapshot_value ) # Register the custom formatter Formatter.register_formatter(MoneyFormatter()) class MoneyTestCase(snapshottest.TestCase): def test_money_snapshot(self): """Test Money objects with custom formatter""" price = Money(99.99, "USD") self.assertMatchSnapshot(price) def test_order_total(self): """Test complex structure with Money""" order = { "items": ["Widget", "Gadget"], "subtotal": Money(150.00, "USD"), "tax": Money(12.00, "USD"), "total": Money(162.00, "USD"), } self.assertMatchSnapshot(order) ``` -------------------------------- ### GenericRepr for Custom Object Snapshot Testing Source: https://context7.com/syrusakbary/snapshottest/llms.txt Illustrates how to use `GenericRepr` from Snapshottest to snapshot custom Python objects. This is useful for objects that don't have standard serialization methods. The `TestCase` from `snapshottest` is used, and objects are automatically wrapped in `GenericRepr` for snapshotting. ```python # test_custom_objects.py import snapshottest from snapshottest import GenericRepr class DatabaseConnection: """Custom object with memory address in repr""" def __init__(self, host, port): self.host = host self.port = port def __repr__(self): return f"DatabaseConnection(host='{self.host}', port={self.port})" class CacheEntry: """Another custom object""" def __init__(self, key, value, ttl): self.key = key self.value = value self.ttl = ttl def __repr__(self): return f"CacheEntry(key={self.key!r}, value={self.value!r}, ttl={self.ttl})" class CustomObjectTestCase(snapshottest.TestCase): def test_database_connection(self): """Custom objects are serialized using GenericRepr""" conn = DatabaseConnection("localhost", 5432) # Object is automatically wrapped in GenericRepr for snapshot storage self.assertMatchSnapshot(conn) def test_nested_custom_objects(self): """Test custom objects nested in collections""" cache_entries = { "user_cache": CacheEntry("user:123", {"name": "Alice"}, 3600), "session_cache": CacheEntry("session:abc", "token_data", 1800), } self.assertMatchSnapshot(cache_entries) def test_manual_generic_repr(self): """Manually create GenericRepr for explicit control""" # Useful when you want to normalize object representations obj = DatabaseConnection("db.example.com", 3306) normalized = GenericRepr.from_value(obj) self.assertMatchSnapshot(normalized) ``` -------------------------------- ### Disable Terminal Colors for SnapshotTest Source: https://github.com/syrusakbary/snapshottest/blob/master/README.md This command shows how to disable ANSI color codes in the terminal output, which can be useful for CI environments or when color codes interfere with logging. It involves setting the ANSI_COLORS_DISABLED environment variable. ```shell ANSI_COLORS_DISABLED=1 pytest ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.