### Install mock-alchemy with pip Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst Instructions for installing the `mock-alchemy` package using pip. Includes general installation and a version-specific command for older Python environments. ```bash pip install mock-alchemy ``` ```bash pip install "mock-alchemy>=0.1.0,<0.2.0" ``` -------------------------------- ### Install Project Development Dependencies with Poetry Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/contributor_guide/index.rst This command uses Poetry to install all project dependencies, including development requirements, into a dedicated virtual environment, preparing the workspace for active development. ```console poetry install ``` -------------------------------- ### Install pre-commit Git hook for linting Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/contributor_guide/index.rst Installs the pre-commit framework as a Git hook. This enables automatic linting and code formatting checks before committing changes, helping maintain code quality. ```console $ nox --session=pre-commit -- install ``` -------------------------------- ### Install Python Development Dependencies with Poetry Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/CONTRIBUTING.rst This command installs the `mock-alchemy` package along with all its development requirements using Poetry, ensuring the environment is ready for development and testing. ```console $ poetry install ``` -------------------------------- ### Install Pre-commit Hooks with Nox Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/CONTRIBUTING.rst Installs pre-commit hooks using the 'pre-commit' Nox session. This command sets up Git hooks that automatically run linting and code formatting checks before each commit, helping maintain code quality and consistency. ```console $ nox --session=pre-commit -- install ``` -------------------------------- ### Install mock-alchemy using pip Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/README.rst Instructions for installing the mock-alchemy library using pip, including specific version requirements for compatibility with Python 2.7 and 3.6. ```Shell $ pip install mock-alchemy\n\n$ pip install \"mock-alchemy>=0.1.0,<0.2.0\" ``` -------------------------------- ### List available Nox sessions Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/contributor_guide/index.rst Displays a list of all available Nox sessions configured for the project, which can be useful for understanding available development tasks. ```console $ nox --list-sessions ``` -------------------------------- ### Install mock-alchemy Python package Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/READMEPYPI.md Install the mock-alchemy library using pip. Specific versions are available for older Python environments (2.7 or 3.6). ```Shell pip install mock-alchemy ``` ```Shell pip install "mock-alchemy>=0.1.0,<0.2.0" ``` -------------------------------- ### Mocking SQLAlchemy Sessions and Performing Scalar Queries with UnifiedAlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst This example demonstrates how to initialize `UnifiedAlchemyMagicMock` with predefined data for specific queries. It then shows how to perform queries on both columns and full table rows, retrieving single scalar results using the `.scalar()` method, and asserting the expected outcomes. ```Python if isinstance(other, SomeTable): return self.pkey == other.pkey and self.col1 == other.col1 return NotImplemented col1_val = "val" row1 = SomeTable(pkey=1, col1=col1_val) mock_session = UnifiedAlchemyMagicMock( data=[ ( [ mock.call.query(SomeTable.col1), mock.call.filter(SomeTable.pkey == 1), ], [(col1_val,)], ), ( [ mock.call.query(SomeTable), mock.call.filter(SomeTable.pkey == 1), ], [row1], ), ] ) found_col1 = mock_session.query(SomeTable.col1).filter(SomeTable.pkey == 1).scalar() assert col1_val == found_col1 found_row = mock_session.query(SomeTable).filter(SomeTable.pkey == 1).scalar() assert row1 == found_row ``` -------------------------------- ### Example SQLAlchemy Function for Testing with mock-alchemy Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst This Python function demonstrates typical SQLAlchemy query operations, including filtering and chaining, which will be tested using `mock-alchemy` to verify session calls. ```python def alchemy_stmts(session): q = session.query(Model).filter(Model.foo == 5) q = some_func(q) q.filter(Model.baz > 11) if condition ``` -------------------------------- ### Mock-Alchemy Query Filtering Examples Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/READMEPYPI.md Demonstrates how to apply filters to queries using the mock-alchemy library. The examples show filtering by single and multiple conditions, illustrating a scenario where an item might still be present in a filtered query despite individual deletion. ```Python s.query('foo').filter(c == 'three').all() [] s.query('foo').filter(c == 'one').filter(c == 'two').filter(c == 'three').all() [1, 2, 3] ``` -------------------------------- ### Run unit tests using Nox Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/contributor_guide/index.rst Executes the project's unit test suite. Tests are located in the `tests` directory and are written using the pytest framework, ensuring 100% code coverage. ```console $ nox --session=tests ``` -------------------------------- ### Execute Full Test Suite with Nox Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/contributor_guide/index.rst This command initiates the complete test suite for the project using Nox, a flexible test automation tool, to verify code correctness and ensure all functionalities are working as expected. ```console nox ``` -------------------------------- ### Match SQLAlchemy expressions with ExpressionMatcher Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst Demonstrates the direct use of `ExpressionMatcher` to compare SQLAlchemy expressions for equality, useful in testing scenarios. ```python from mock_alchemy.comparison import ExpressionMatcher ExpressionMatcher(Model.foo == 5) == (Model.foo == 5) ``` -------------------------------- ### Run Interactive Python Session via Poetry Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/contributor_guide/index.rst This command executes an interactive Python interpreter session within the Poetry-managed virtual environment, ensuring that all project-specific dependencies are correctly loaded and available for use. ```console poetry run python ``` -------------------------------- ### Stub SQLAlchemy query data with UnifiedAlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst Demonstrates how to provide stubbed data to `UnifiedAlchemyMagicMock` based on specific query criteria, enabling predictable test results for different models and filters. ```python from mock_alchemy.mocking import UnifiedAlchemyMagicMock session = UnifiedAlchemyMagicMock(data=[ ( [mock.call.query(Model), mock.call.filter(Model.foo == 5, Model.bar > 10)], [Model(foo=5, bar=11)] ), ( [mock.call.query(Model), mock.call.filter(Model.note == 'hello world')], [Model(note='hello world')] ), ( [mock.call.query(AnotherModel), mock.call.filter(Model.foo == 5, Model.bar > 10)], [AnotherModel(foo=5, bar=17)] ), ]) session.query(Model).filter(Model.foo == 5).filter(Model.bar > 10).all() session.query(Model).filter(Model.note == 'hello world').all() session.query(AnotherModel).filter(Model.foo == 5).filter(Model.bar > 10).all() session.query(AnotherModel).filter(Model.note == 'hello world').all() ``` -------------------------------- ### Mock SQLAlchemy session mutations with UnifiedAlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst Illustrates how `UnifiedAlchemyMagicMock` can partially fake session mutations like `session.add()` and subsequent `query()` or `get()` calls on the added instances, including filter limitations. ```python session = UnifiedAlchemyMagicMock() session.add(Model(pk=1, foo='bar')) session.add(Model(pk=2, foo='baz')) session.query(Model).all() session.query(Model).get(1) session.query(Model).get(2) session.query(Model).filter(Model.foo == 'bar').all() ``` -------------------------------- ### Illustrating Deletion Propagation Limitations in Dynamic UnifiedAlchemyMagicMock Sessions Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst This example highlights a specific limitation of `UnifiedAlchemyMagicMock` where deletions may not propagate across different, but logically related, queries. It demonstrates that an object deleted via one query might still appear in another query if the mock session was initialized with separate data entries for those queries, emphasizing that the library treats them as distinct objects in such scenarios. ```Python s = UnifiedAlchemyMagicMock(data=[ ( [mock.call.query('foo'), mock.call.filter(c == 'one', c == 'two')], [SomeClass(pk1=1, pk2=1), SomeClass(pk1=2, pk2=2)] ), ( [mock.call.query('foo'), mock.call.filter(c == 'one', c == 'two'), mock.call.order_by(c)], [SomeClass(pk1=2, pk2=2), SomeClass(pk1=1, pk2=1)] ), ( [mock.call.filter(c == 'three')], [SomeClass(pk1=3, pk2=3)] ), ( [mock.call.query('foo'), mock.call.filter(c == 'one', c == 'two', c == 'three')], [SomeClass(pk1=1, pk2=1), SomeClass(pk1=2, pk2=2), SomeClass(pk1=3, pk2=3)] ), ]) s.query('foo').filter(c == 'three').delete() # Expected output: 1 s.query('foo').filter(c == 'three').all() # Expected output: [] s.query('foo').filter(c == 'one').filter(c == 'two').filter(c == 'three').all() # Expected output: [1, 2, 3] ``` -------------------------------- ### Mock SQLAlchemy session with AlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst Illustrates how to use `AlchemyMagicMock` to mock a SQLAlchemy session, allowing for assertions on method calls like `query` and `filter`. ```python from mock_alchemy.mocking import AlchemyMagicMock session = AlchemyMagicMock() session.query(Model).filter(Model.foo == 5).all() session.query.return_value.filter.assert_called_once_with(Model.foo == 5) ``` -------------------------------- ### Test Complex Data Analysis Function with Mock-Alchemy Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst This Python pytest example demonstrates how to test the `complex_data_analysis` function using `mock-alchemy`'s `UnifiedAlchemyMagicMock`. It sets up mock data for SQLAlchemy queries, executes the analysis function, and then asserts that the expected `CombinedAnalysis` objects were added to the mocked session, effectively testing database interactions without a real database. ```python import datetime import mock import pytest from mock_alchemy.mocking import UnifiedAlchemyMagicMock from data_analysis import complex_data_analysis, Data1, Data2, Data3, CombinedAnalysis def test_data_analysis(): stop_time = datetime.datetime.utcnow() cfg = { "final_time": stop_time } data1_values = [ Data1(1, some, data, values), Data1(2, some, data, values), Data1(3, some, data, values), ] data2_values = [ Data2(1, some, data, values), Data2(2, some, data, values), Data2(3, some, data, values), ] data3_values = [ Data3(1, some, data, values), Data3(2, some, data, values), Data3(3, some, data, values), ] session = UnifiedAlchemyMagicMock(data=[ ( [mock.call.query(Data1), mock.call.filter(Data1.utc_time < stop_time)], data1_values ), ( [mock.call.query(Data2), mock.call.filter(Data2.utc_time < stop_time)], data2_values ), ( [mock.call.query(Data3), mock.call.filter(Data3.utc_time < stop_time)], data3_values ), ]) complex_data_analysis(cfg, session) expected_anyalsis = [ CombinedAnalysis(1, some, anyalsis, values), CombinedAnalysis(2, some, anyalsis, values), CombinedAnalysis(3, some, anyalsis, values), ] combined_anyalsis = session.query(CombinedAnalysis).all() assert sorted(combined_anyalsis, key=lambda x: x.pk1) == sorted(expected_anyalsis, key=lambda x: x.pk1) ``` -------------------------------- ### Assert multiple SQLAlchemy calls with UnifiedAlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst Shows how `UnifiedAlchemyMagicMock` can combine multiple SQLAlchemy session interactions, simplifying assertions on chained calls like `filter`. ```python from mock_alchemy.mocking import UnifiedAlchemyMagicMock session = UnifiedAlchemyMagicMock() m = session.query(Model) q = m.filter(Model.foo == 5) if condition: q = q.filter(Model.bar > 10).all() data1 = q.all() data2 = m.filter(Model.note == 'hello world').all() session.filter.assert_has_calls([ mock.call(Model.foo == 5, Model.bar > 10), mock.call(Model.note == 'hello world'), ]) ``` -------------------------------- ### Demonstrating Object Deletion in UnifiedAlchemyMagicMock Sessions Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst This snippet illustrates how to add objects to a `UnifiedAlchemyMagicMock` session, query them, and then use the `.delete()` method to remove them. It shows the state of the session before and after deletion, confirming that the objects are no longer present. ```Python s = UnifiedAlchemyMagicMock() s.add(SomeClass(pk1=1, pk2=1)) s.add_all([SomeClass(pk1=2, pk2=2)]) s.query(SomeClass).all() # Expected output: [1, 2] s.query(SomeClass).delete() # Expected output: 2 s.query(SomeClass).all() # Expected output: [] ``` -------------------------------- ### Define SQLAlchemy model for scalar() mocking context Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst Defines a SQLAlchemy declarative base model (`SomeTable`) with primary key and column, serving as a prerequisite for demonstrating `scalar()` mocking with `UnifiedAlchemyMagicMock`. ```python from __future__ import annotations from sqlalchemy import Column, String from sqlalchemy.ext.declarative import declarative_base from mock_alchemy.mocking import UnifiedAlchemyMagicMock from unittest import mock Base = declarative_base() class SomeTable(Base): """SQLAlchemy object representing some table.""" __tablename__ = "some_table" pkey = Column(String, primary_key=True) col1 = Column(String(50)) def __eq__(self, other: Model) -> bool: """Object equality checker.""" ``` -------------------------------- ### Testing Complex SQLAlchemy Operations with UnifiedAlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst This Python test demonstrates how `UnifiedAlchemyMagicMock` can be used to test a function performing multiple SQLAlchemy operations, including querying, adding, and deleting. It shows how to stub initial data, assert final state, and verify deletions. ```python import datetime import mock import pytest from mock_alchemy.mocking import UnifiedAlchemyMagicMock from data_analysis import complex_data_analysis, Data1, Data2, Data3, CombinedAnalysis def test_data_analysis(): stop_time = datetime.datetime.utcnow() cfg = { "final_time": stop_time } data1_values = [ Data1(1, some, data, values), Data1(2, some, data, values), Data1(3, some, data, values), ] data2_values = [ Data2(1, some, data, values), Data2(2, some, data, values), Data2(3, some, data, values), ] data3_values = [ Data3(1, some, data, values), Data3(2, some, data, values), Data3(3, some, data, values), ] session = UnifiedAlchemyMagicMock(data=[ ( [mock.call.query(Data1), mock.call.filter(Data1.utc_time < stop_time)], data1_values ), ( [mock.call.query(Data2), mock.call.filter(Data2.utc_time < stop_time)], data2_values ), ( [mock.call.query(Data3), mock.call.filter(Data3.utc_time < stop_time)], data3_values ) ]) complex_data_analysis(cfg, session) expected_anyalsis = [ CombinedAnalysis(1, some, anyalsis, values), CombinedAnalysis(2, some, anyalsis, values), CombinedAnalysis(3, some, anyalsis, values) ] combined_anyalsis = session.query(CombinedAnalysis).all() assert sorted(combined_anyalsis, key=lambda x: x.pk1) == sorted(expected_anyalsis, key=lambda x: x.pk1) assert [] == session.query(Data3).filter(Data3.utc_time < cfg["final_time"]) expected_anyalsis3 = CombinedAnalysis(3, some, anyalsis, values) anyalsis3 = session.query(CombinedAnalysis).get({"pk1": 3}) assert anyalsis3 == expected_anyalsis3 ``` -------------------------------- ### Comparing SQLAlchemy Expressions for Unit Testing Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/about/index.rst These Python examples illustrate the challenge of comparing SQLAlchemy expressions directly in unit tests and how `mock-alchemy` provides a solution. The first snippet shows that a direct comparison of two SQLAlchemy binary expressions yields another binary expression, not a boolean. The second snippet demonstrates how `mock-alchemy`'s `ExpressionMatcher` enables proper boolean evaluation of these expressions, facilitating effective testing. ```Python type((Model.foo == 5) == (Model.bar == 5)) ``` ```Python ExpressionMatcher(Model.foo == 5) == (Model.bar == 5) False ``` -------------------------------- ### Mocking SQLAlchemy Session Add and Get Operations with UnifiedAlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/README.rst Demonstrates `UnifiedAlchemyMagicMock`'s partial support for `session.add()` and `session.get()` methods, allowing objects to be added to and retrieved from the mocked session. It highlights a limitation where filtering on added models does not apply, and `all()` returns all added objects regardless of the filter. ```Python from mock_alchemy.mocking import UnifiedAlchemyMagicMock session = UnifiedAlchemyMagicMock() session.add(Model(pk=1, foo='bar')) session.add(Model(pk=2, foo='baz')) session.query(Model).all() # Expected: [Model(foo='bar'), Model(foo='baz')] session.query(Model).get(1) # Expected: Model(foo='bar') session.query(Model).get(2) # Expected: Model(foo='baz') session.query(Model).get((2,)) # Expected: Model(foo='baz') session.query(Model).get({"pk2" : 2}) # Expected: Model(foo='baz') # Note: partially correct since if added models are filtered on, # session is unable to actually apply any filters so it returns everything: session.query(Model).filter(Model.foo == 'bar').all() # Expected: [Model(foo='bar'), Model(foo='baz')] ``` -------------------------------- ### Verifying SQLAlchemy Session Calls with UnifiedAlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst This Python test function shows how to use `UnifiedAlchemyMagicMock` to assert specific calls made to a SQLAlchemy session, verifying filter conditions and call order without actual database interaction. ```python from mock_alchemy.mocking import UnifiedAlchemyMagicMock def test_stms(): session = UnifiedAlchemyMagicMock() session.filter.assert_has_calls([ mock.call(Model.foo == 5, Model.som_attr < 31, Model.baz > 11), mock.call(Model.note == 'hello world'), ]) ``` -------------------------------- ### Complex Data Analysis Function with SQLAlchemy Operations Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst This Python function simulates a complex data analysis workflow involving multiple SQLAlchemy queries, data integration, adding new records, and deleting existing ones. It serves as a target for comprehensive testing with `mock-alchemy`. ```python def complex_data_analysis(cfg, session): # collects some data upto some point dataset1 = session.query(Data1).filter(Data1.utc_time < cfg["final_time"]) dataset2 = session.query(Data2).filter(Data2.utc_time < cfg["final_time"]) dataset3 = session.query(Data3).filter(Data3.utc_time < cfg["final_time"]) # performs some analysis analysis12 = analysis(dataset1, dataset2) analysis13 = analysis(dataset1, dataset3) analysis23 = analysis(dataset2, dataset3) # combine the data analysis (returns object CombinedAnalysis) combined_analysis = intergrate_analysis(analysis12, analysis13, analysis23) # assume the combined_analysis are stored in some SQL table self.session.add_all(combined_analysis) session.query(Data3).filter(Data3.utc_time < cfg["final_time"]).delete() self.session.commit() ``` -------------------------------- ### Mocking SQLAlchemy ORM Objects with UnifiedAlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst This Python code defines SQLAlchemy models (`BaseModel`, `Concrete`) and demonstrates how to mock a SQLAlchemy session using `UnifiedAlchemyMagicMock` for testing. It illustrates the importance of explicitly setting primary key attributes within a custom `__init__` method when one is defined for an ORM class, and then uses the mocked session to simulate a query and assertion. ```python import datetime import mock from sqlalchemy import Integer from sqlalchemy import Column from sqlalchemy.ext.declarative import declarative_base from mock_alchemy.mocking import UnifiedAlchemyMagicMock Base = declarative_base() class BaseModel(Base): """Abstract data model to test.""" __abstract__ = True created = Column(Integer, nullable=False, default=3) createdby = Column(Integer, nullable=False, default={}) updated = Column(Integer, nullable=False, default=1) updatedby = Column(Integer, nullable=False, default={}) disabled = Column(Integer, nullable=True) class Concrete(BaseModel): """A testing SQLAlchemy object.""" __tablename__ = "concrete" id = Column(Integer, primary_key=True) def __init__(self, **kwargs: Any) -> None: """Creates a Concrete object.""" self.id = kwargs.pop("id") super(Concrete, self).__init__(**kwargs) def __eq__(self, other: Concrete) -> bool: """Equality override.""" return self.id == other.id objs = Concrete(id=1) session = UnifiedAlchemyMagicMock( data=[ ([mock.call.query(Concrete)], [objs]), ] ) ret = session.query(Concrete).get(1) assert ret == objs ``` -------------------------------- ### Faking SQLAlchemy Session Add Operations Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/READMEPYPI.md Illustrates `UnifiedAlchemyMagicMock`'s ability to partially fake `session.add()` operations, allowing added instances to be retrieved via `all()` or `get()`. It also highlights a limitation: the mock session does not apply filters to added models, returning all added models regardless of the filter criteria. ```python session = UnifiedAlchemyMagicMock() session.add(Model(pk=1, foo='bar')) session.add(Model(pk=2, foo='baz')) session.query(Model).all() session.query(Model).get(1) session.query(Model).get(2) session.query(Model).filter(Model.foo == 'bar').all() ``` -------------------------------- ### Define SQLAlchemy Models and Complex Data Analysis Function Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/user_guide/index.rst This Python code defines SQLAlchemy declarative base models (`Data1`, `CombinedAnalysis`) and a `complex_data_analysis` function. The function simulates a multi-step data analysis process involving querying multiple datasets, performing analysis, integrating results, and persisting them to a database session. This serves as the target function for testing with `mock-alchemy`. ```python from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # assume similar classes for Data2 and Data3 class Data1(Base): __tablename__ = 'some_table' pk1 = Column(Integer, primary_key=True) data_val1 = Column(Integer) data_val2 = Column(Integer) data_val3 = Column(Integer) def __init__(self, pk1, val1, val2, val3): self.pk1 = pk1 self.data_val1 = val1 self.data_val2 = val2 self.data_val3 = val3 class CombinedAnalysis(Base): __tablename__ = 'some_table' pk1 = Column(Integer, primary_key=True) analysis_val1 = Column(Integer) analysis_val2 = Column(Integer) analysis_val3 = Column(Integer) def __init__(self, pk1, val1, val2, val3): self.pk1 = pk1 self.analysis_val1 = val1 self.analysis_val2 = val2 self.analysis_val3 = val3 def __eq__(self, other): if not isinstance(other, CombinedAnalysis): return NotImplemented return ( self.analysis_val1 == other.analysis_val1 and self.analysis_val2 == other.analysis_val2 and self.analysis_val3 == other.analysis_val3 ) def complex_data_analysis(cfg, session): # collects some data upto some point dataset1 = session.query(Data1).filter(Data1.utc_time < cfg["final_time"]) dataset2 = session.query(Data2).filter(Data2.utc_time < cfg["final_time"]) dataset3 = session.query(Data3).filter(Data3.utc_time < cfg["final_time"]) # performs some analysis analysis12 = analysis(dataset1, dataset2) analysis13 = analysis(dataset1, dataset3) analysis23 = analysis(dataset2, dataset3) # combine the data analysis (returns object CombinedAnalysis) combined_analysis = intergrate_analysis(analysis12, analysis13, analysis23) # assume the combined_analysis are stored in some SQL table self.session.add_all(combined_analysis) self.session.commit() ``` -------------------------------- ### Run Full Test Suite with Nox Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/CONTRIBUTING.rst Executes the entire test suite for the project using Nox. This command runs all configured testing, linting, and other quality assurance sessions defined in the Nox configuration. ```console $ nox ``` -------------------------------- ### List Available Nox Sessions Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/CONTRIBUTING.rst Displays a comprehensive list of all defined Nox sessions within the project. This is useful for identifying specific tasks that can be invoked individually, such as unit tests or linting. ```console $ nox --list-sessions ``` -------------------------------- ### Run Interactive Python Session with Poetry Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/CONTRIBUTING.rst This command launches an interactive Python interpreter within the project's Poetry virtual environment, allowing developers to execute Python code directly in the project's isolated context. ```console $ poetry run python ``` -------------------------------- ### Basic SQLAlchemy Session Mocking with AlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/READMEPYPI.md Illustrates how to use `AlchemyMagicMock` to create a mock SQLAlchemy session. This allows for basic mocking of query chains and asserting that specific methods like `filter` were called with the expected arguments, without needing a live database. ```python from mock_alchemy.mocking import AlchemyMagicMock session = AlchemyMagicMock() session.query(Model).filter(Model.foo == 5).all() session.query.return_value.filter.assert_called_once_with(Model.foo == 5) ``` -------------------------------- ### Stubbing Query Results with UnifiedAlchemyMagicMock Data Parameter Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/README.rst Illustrates how to pre-configure `UnifiedAlchemyMagicMock` with specific return data for different query patterns. By providing a `data` list of `(call_sequence, result_list)` tuples, developers can simulate various database responses, enabling comprehensive testing of data retrieval logic without a live database connection. ```Python from mock_alchemy.mocking import UnifiedAlchemyMagicMock import mock session = UnifiedAlchemyMagicMock(data=[ ( [mock.call.query(Model), mock.call.filter(Model.foo == 5, Model.bar > 10)], [Model(foo=5, bar=11)] ), ( [mock.call.query(Model), mock.call.filter(Model.note == 'hello world')], [Model(note='hello world')] ), ( [mock.call.query(AnotherModel), mock.call.filter(Model.foo == 5, Model.bar > 10)], [AnotherModel(foo=5, bar=17)] ), ]) session.query(Model).filter(Model.foo == 5).filter(Model.bar > 10).all() # Expected: [Model(foo=5, bar=11)] session.query(Model).filter(Model.note == 'hello world').all() # Expected: [Model(note='hello world')] session.query(AnotherModel).filter(Model.foo == 5).filter(Model.bar > 10).all() # Expected: [AnotherModel(foo=5, bar=17)] session.query(AnotherModel).filter(Model.note == 'hello world').all() # Expected: [] ``` -------------------------------- ### Stubbing Data for Unified SQLAlchemy Mock Sessions Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/READMEPYPI.md Demonstrates how to pre-populate `UnifiedAlchemyMagicMock` with specific data based on expected query and filter calls. This allows the mock session to return realistic data for different query patterns, making tests more robust and predictable. ```python from mock_alchemy.mocking import UnifiedAlchemyMagicMock import mock session = UnifiedAlchemyMagicMock(data=[ ( [mock.call.query(Model), mock.call.filter(Model.foo == 5, Model.bar > 10)], [Model(foo=5, bar=11)] ), ( [mock.call.query(Model), mock.call.filter(Model.note == 'hello world')], [Model(note='hello world')] ), ( [mock.call.query(AnotherModel), mock.call.filter(Model.foo == 5, Model.bar > 10)], [AnotherModel(foo=5, bar=17)] ), ]) session.query(Model).filter(Model.foo == 5).filter(Model.bar > 10).all() session.query(Model).filter(Model.note == 'hello world').all() session.query(AnotherModel).filter(Model.foo == 5).filter(Model.bar > 10).all() session.query(AnotherModel).filter(Model.note == 'hello world').all() ``` -------------------------------- ### Compare SQLAlchemy expressions with ExpressionMatcher Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/README.rst Demonstrates how mock-alchemy's ExpressionMatcher allows for direct comparison of SQLAlchemy binary expressions, which is not natively supported by SQLAlchemy and would otherwise result in another binary expression. ```Python >>> type((Model.foo == 5) == (Model.bar == 5))\n\n\n>>> ExpressionMatcher(Model.foo == 5) == (Model.bar == 5)\nFalse ``` -------------------------------- ### Python Project Dependencies Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/docs/requirements.txt This snippet lists the required Python packages and their exact versions for the mock-alchemy project, typically found in a `requirements.txt` file. These dependencies are necessary for setting up the development environment and ensuring project reproducibility, particularly for Sphinx-based documentation. ```Python sphinx==7.0.1 sphinx-autobuild==2021.3.14 sphinx-autodoc-typehints==1.22 sphinx-copybutton==0.5.1 pydata-sphinx-theme==0.13.3 mock_alchemy ``` -------------------------------- ### Run Specific Nox Session for Unit Tests Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/CONTRIBUTING.rst Invokes only the 'tests' Nox session, specifically running the unit test suite for the project. Unit tests are typically located in the `tests` directory and utilize the `pytest` framework. ```console $ nox --session=tests ``` -------------------------------- ### Basic SQLAlchemy Session Mocking using AlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/README.rst Illustrates how to mock a SQLAlchemy session using `AlchemyMagicMock`. This allows for testing interactions with the session, such as asserting that specific query methods were called with the correct arguments. It's suitable for straightforward, single-call session operations. ```Python from mock_alchemy.mocking import AlchemyMagicMock session = AlchemyMagicMock() session.query(Model).filter(Model.foo == 5).all() session.query.return_value.filter.assert_called_once_with(Model.foo == 5) ``` -------------------------------- ### Mocking Chained SQLAlchemy Queries with UnifiedAlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/README.rst Demonstrates how `UnifiedAlchemyMagicMock` simplifies testing of complex, chained SQLAlchemy query operations. It aggregates multiple `filter` calls, allowing for a single `assert_has_calls` to verify the sequence of conditions applied to the session. This is particularly useful for dynamic query building. ```Python from mock_alchemy.mocking import UnifiedAlchemyMagicMock import mock session = UnifiedAlchemyMagicMock() m = session.query(Model) q = m.filter(Model.foo == 5) if condition: q = q.filter(Model.bar > 10) data1 = q.all() data2 = m.filter(Model.note == 'hello world').all() session.filter.assert_has_calls([ mock.call(Model.foo == 5, Model.bar > 10), mock.call(Model.note == 'hello world'), ]) ``` -------------------------------- ### Comparing SQLAlchemy Expressions with ExpressionMatcher Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/READMEPYPI.md Demonstrates how SQLAlchemy's default expression comparison differs from `mock-alchemy`'s `ExpressionMatcher`. `ExpressionMatcher` allows for direct comparison of SQLAlchemy binary expressions, returning a boolean result instead of another expression, which is useful for testing. ```python type((Model.foo == 5) == (Model.bar == 5)) from mock_alchemy.comparison import ExpressionMatcher ExpressionMatcher(Model.foo == 5) == (Model.bar == 5) ExpressionMatcher(Model.foo == 5) == (Model.foo == 5) ``` -------------------------------- ### Comparing SQLAlchemy Expressions with ExpressionMatcher Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/README.rst Demonstrates the use of `ExpressionMatcher` from `mock_alchemy.comparison` to directly compare SQLAlchemy expression objects. This utility is useful for asserting that two SQLAlchemy expressions are functionally equivalent, which is crucial for testing query conditions. ```Python from mock_alchemy.comparison import ExpressionMatcher ExpressionMatcher(Model.foo == 5) == (Model.foo == 5) ``` -------------------------------- ### Unified SQLAlchemy Session Mocking for Call Assertions Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/READMEPYPI.md Shows how `UnifiedAlchemyMagicMock` can be used to mock complex SQLAlchemy session interactions where multiple queries or filters are applied. It combines various calls, enabling easier assertion of all `filter` calls made during a session, even across conditional logic. ```python from mock_alchemy.mocking import UnifiedAlchemyMagicMock import mock session = UnifiedAlchemyMagicMock() m = session.query(Model) q = m.filter(Model.foo == 5) if condition: q = q.filter(Model.bar > 10).all() data1 = q.all() data2 = m.filter(Model.note == 'hello world').all() session.filter.assert_has_calls([ mock.call(Model.foo == 5, Model.bar > 10), mock.call(Model.note == 'hello world'), ]) ``` -------------------------------- ### Mocking SQLAlchemy Session Delete Operations with UnifiedAlchemyMagicMock Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/README.rst Explains how `UnifiedAlchemyMagicMock` can partially simulate `session.delete()` for objects managed within the mocked session. It clarifies that deletions are effective only within the exact query context and do not propagate across different query definitions, treating identical objects from different queries as separate entities. ```Python from mock_alchemy.mocking import UnifiedAlchemyMagicMock import mock s = UnifiedAlchemyMagicMock() s.add(SomeClass(pk1=1, pk2=1)) s.add_all([SomeClass(pk1=2, pk2=2)]) s.query(SomeClass).all() # Expected: [1, 2] s.query(SomeClass).delete() # Expected: 2 s.query(SomeClass).all() # Expected: [] # Note: limitation for dynamic sessions remains the same. # Additionally, the delete will not be propagated across queries (only unified in the exact same query). # As in, if there are multiple queries in which the 'same' object is present, # this library considers them separate objects. For example: s = UnifiedAlchemyMagicMock(data=[ ( [mock.call.query('foo'), mock.call.filter(c == 'one', c == 'two')], [SomeClass(pk1=1, pk2=1), SomeClass(pk1=2, pk2=2)] ), ( [mock.call.query('foo'), mock.call.filter(c == 'one', c == 'two'), mock.call.order_by(c)], [SomeClass(pk1=2, pk2=2), SomeClass(pk1=1, pk2=1)] ), ( [mock.call.filter(c == 'three')], [SomeClass(pk1=3, pk2=3)] ), ( [mock.call.query('foo'), mock.call.filter(c == 'one', c == 'two', c == 'three')], [SomeClass(pk1=1, pk2=1), SomeClass(pk1=2, pk2=2), SomeClass(pk1=3, pk2=3)] ), ]) s.query('foo').filter(c == 'three').delete() # Expected: 1 s.query('foo').filter(c == 'three').all() # Expected: [] s.query('foo').filter(c == 'one').filter(c == 'two').filter(c == 'three').all() # Expected: [1, 2, 3] ``` -------------------------------- ### Faking SQLAlchemy Session Delete Operations Source: https://github.com/rajivsarvepalli/mock-alchemy/blob/master/READMEPYPI.md Explains how `UnifiedAlchemyMagicMock` can partially fake `session.delete()` operations, removing objects that are accessible via `all()`. It also notes a limitation: deletions are not propagated across different queries, meaning an object deleted in one query context might still appear in another if it was initially stubbed for that context. ```text ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.