<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Avel Docquin on Medium]]></title>
        <description><![CDATA[Stories by Avel Docquin on Medium]]></description>
        <link>https://medium.com/@adocquin?source=rss-a372787304c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nktm94j9oyVjfQPPVWRiEg.jpeg</url>
            <title>Stories by Avel Docquin on Medium</title>
            <link>https://medium.com/@adocquin?source=rss-a372787304c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:53:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adocquin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How To Manage Your Python Virtual Environments]]></title>
            <link>https://medium.com/@adocquin/mastering-python-virtual-environments-with-pyenv-and-pyenv-virtualenv-c4e017c0b173?source=rss-a372787304c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4e017c0b173</guid>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pyenv]]></category>
            <category><![CDATA[virtualenv]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Avel Docquin]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 17:31:51 GMT</pubDate>
            <atom:updated>2025-12-02T12:53:44.610Z</atom:updated>
            <content:encoded><![CDATA[<h4>Pyenv and pyenv-virtualenv will let you easily manage multiple Python versions and environments. Here’s how to use these tools:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V5nAuocyvEXoKkFZ" /><figcaption>Photo by <a href="https://unsplash.com/@supardisign?utm_source=medium&amp;utm_medium=referral">Wouter Supardi Salari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While working on Python projects and notebooks, you might have tried to run one that requires Python 3.6, yet your system only has Python 3.8 installed. Or, run a script requiring a specific package version that conflicts with another previously installed.</p><p><strong>To avoid these problems, you can use </strong><a href="https://github.com/pyenv/pyenv"><strong>pyenv</strong></a><strong> and </strong><a href="https://github.com/pyenv/pyenv-virtualenv"><strong>pyenv-virtualenv</strong></a><strong>. Pyenv will let you easily switch between multiple Python versions and pyenv-virtualenv to create isolated virtual environments.</strong></p><p>These tools will help you avoid breaking your system, resolve dependencies conflicts, and reproduce your peers’ analysis results by creating dedicated environments with their own packages for each project.</p><p>In this tutorial, you will first learn how to install pyenv and pyenv-virtualenv on Mac and Ubuntu. Then, have an overview of the commands you will use most frequently. Finally, you will apply them through a simple use case using VS Code. Let’s get started!</p><h3>1. Pyenv and pyenv-virtualenv installation</h3><p>Installing pyenv and pyenv-virtualenv is straightforward. First, you need to have <a href="https://git-scm.com/">git</a> and <a href="https://curl.se/">curl</a> installed on your system.</p><p>You can install them in your terminal using on Mac:</p><pre>brew install git<br>brew install curl</pre><p>Or on Ubuntu:</p><pre>sudo apt install git<br>sudo apt install curl</pre><p>Once you have them, all you need to do is to run:</p><pre>curl https://pyenv.run | bash</pre><p>And add this to the end of your <em>$HOME/.bashrc</em> or <em>$HOME/.zshrc</em> file:</p><pre>export PYENV_ROOT=&quot;$HOME/.pyenv&quot;<br>command -v pyenv &gt;/dev/null || export PATH=&quot;$PYENV_ROOT/bin:$PATH&quot;<br>eval &quot;$(pyenv init -)&quot;<br>eval &quot;$(pyenv virtualenv-init -)&quot;</pre><p>Reload your terminal, and you should be able to run the pyenv command, which will output the list of possible options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWBTc6-eWS8lh1spOh7oEQ.png" /><figcaption>Output of the pyenv command once installed.</figcaption></figure><p>We will also test if the command pyenv virtualenvs works. In this case, it should return no virtualenv name given as it is required to specify an environment name to create one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqU043dzhagE6IG0K2CAKg.png" /><figcaption>The environment name you want to interact with must follow the command pyenv virtualenv.</figcaption></figure><p>With pyenv and pyenv-virtualenv installed, we can go to the next part!</p><h3>2. Commands overview</h3><p>In this part, you will learn the pyenv commands you will use the most:</p><ul><li><strong>pyenv install</strong>: To install a new Python version</li><li><strong>pyenv update</strong>: To update pyenv</li><li><strong>pyenv virtualenv</strong>: To create a new Python virtual environment.</li><li><strong>pyenv activate</strong>: To activate a previously created virtual environment.</li><li><strong>source deactivate</strong>: To deactivate the virtual environment currently in use.</li><li><strong>pyenv uninstall</strong>: To uninstall a virtual environment or Python version.</li></ul><h4>2.1. Install a new python version</h4><p>Using pyenv, you can install a new Python version, let’s say the 3.11.3. You can first type this command in your terminal:</p><pre>pyenv install -l</pre><p>It will show all the available Python versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SwAIKPtATO-LoDfNOD4NQ.png" /><figcaption>The 3.11.3 version is not in this screenshot due to the many Python versions available.</figcaption></figure><p>You will see in the list the 3.11.3 that you can install using:</p><pre>pyenv install 3.11.3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dC5W1ojch23xu1DsqmPyvw.png" /><figcaption>In just 2 minutes, you have Python 3.11.3 available on your system.</figcaption></figure><p>In case you are on Ubuntu and encounter the error <strong>make: *** [Makefile:2255: install] Error 1</strong>, make sure you have installed these dependencies:</p><pre>sudo apt install libssl-dev libffi-dev libncurses5-dev zlib1g zlib1g-dev libreadline-dev libbz2-dev libsqlite3-dev make gcc</pre><h4>2.2. Update pyenv</h4><p>New Python versions are released regularly. If you want to install the last version, all you have to do is run the command:</p><pre>pyenv update</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3FSbrH6-E0sEdCyE94_fg.png" /><figcaption>In this case, the last version of pyenv is already installed.</figcaption></figure><p>It will update pyenv and the list of Python versions available to install.</p><h4>2.3. Create a virtual environment</h4><p>Once you have installed a Python version, all you have to do to create an environment is to type:</p><pre>pyenv virtualenv &lt;python_version&gt; &lt;environment_name&gt;</pre><p>Which, in our case, can be:</p><pre>pyenv virtualenv 3.11.3 test_environment</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_SKDd1vAzJR1vBzpsNF2A.png" /><figcaption>In the case of a successfully created environment, the commands returns no output.</figcaption></figure><h4>2.4. Activate a virtual environment</h4><p>To use an existing virtual environment, you can activate it by typing:</p><pre>pyenv activate &lt;environment_name&gt;</pre><p>Once activated, every installed package and run Python script will be under this environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x41VSjJoEUgFFQROi6Tywg.png" /><figcaption>As you can see, Python 3.11.3 is executed.</figcaption></figure><h4>2.5. Deactivate a virtual environment</h4><p>When you want to quit the current virtual environment, you can deactivate it by typing the command:</p><pre>source deactivate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUOhzOngmoPtrPojrlvSCA.png" /><figcaption>After running source deactivate, you return under your Python system version.</figcaption></figure><h4>2.6 Delete an environment or a Python version</h4><p>If you no longer need an environment or a Python version, you can delete it using:</p><pre>pyenv uninstall &lt;environment_name or python version&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zq3CQNoMbdOrs_g4M1bJ1A.png" /><figcaption>Both test_environment and Python 3.11.3 are now deleted.</figcaption></figure><h3>3. Simple Use Case in VS Code</h3><p>With the knowledge of all the essential pyenv commands, we can go through a simple use case to apply them.</p><p>A coworker is working on an analysis and wants to share the sources with you via this <a href="https://github.com/adocquin/medium_pyenv">GitHub repository</a>. They use Python 3.10.2 and a specific pandas version indicated in the requirements.txt file.</p><p>The first step is to create the environment and install the packages. Go to the repository directory (medium_pyenv) and execute the following commands:</p><pre>pyenv install 3.10.2<br>pyenv virtualenv 3.10.2 titanic_analysis<br>pyenv activate titanic_analysis<br>pip install -r requirements.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQmhk52fnXFmRetYeDCgbw.gif" /><figcaption>Your analysis environment is now ready.</figcaption></figure><p>Now, open the analysis.ipynb notebook in VS Code and select the new environment as kernel at the top right of the screen (Select Kernel-&gt; Select Another Kernel... -&gt; Python Environments... -&gt; titanic_analysis (Python)):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNsXZpasfL6S9dcDh2QXJg.gif" /><figcaption>You may need to restart VS Code in order to see your newly created environment.</figcaption></figure><p>To edit the sources under your new environment, open the command palette (⇧⌘P on Mac and Ctrl⇧P on Ubuntu) in src/environment.py and select Python: Select Interpreter -&gt; Python 3.10.2 64-bit (`titanic_analysis`) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ps3g6t8nKhLV2LKDcVzIXw.gif" /><figcaption>If you don&#39;t follow this step, the code will be executed under the system Python version.</figcaption></figure><p>You can run this file with Right clic -&gt; Run Python -&gt; Run Python File in Terminal or by opening a terminal and running python engineering.py .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8g6xp_pZFMaBOToh6Jwn7A.gif" /><figcaption>You can now continue working on the analysis in this dedicated Python environment.</figcaption></figure><h3>4. Conclusion</h3><p>To summarize, using pyenv and pyenv-virtualenv will allow you to manage multiple Python versions and environments, avoiding conflicts and package headaches.</p><p>Now that you have a way to consistently manage your virtual environments, you will be able to easily switch between them and share projects with your peers 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4e017c0b173" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Unit Tests in Python with pytest: A Comprehensive Guide]]></title>
            <link>https://medium.com/@adocquin/mastering-unit-tests-in-python-with-pytest-a-comprehensive-guide-896c8c894304?source=rss-a372787304c------2</link>
            <guid isPermaLink="false">https://medium.com/p/896c8c894304</guid>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Avel Docquin]]></dc:creator>
            <pubDate>Mon, 29 May 2023 08:12:09 GMT</pubDate>
            <atom:updated>2023-09-26T17:53:36.774Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Basic Assertions to Advanced Fixtures and Mocking.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K94o6os3wF0iA4okKFot5A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/fr/@davidclode">David Clode</a> on <a href="https://unsplash.com/">Unsplah</a></figcaption></figure><p>Unit testing is an important component of the software development process, as it helps ensure your code’s correctness and reliability. In Python, one of the most popular testing frameworks is pytest, due to its simplicity, ease of use, and features.</p><p>In this guide, we will go through the basics of unit testing using pytest, with examples to help you get started with writing and running tests for your projects.</p><p>Note that if you need to refer to the source code during the tutorial, you can find it on <a href="https://github.com/adocquin/medium_unit_testing">GitHub</a>.</p><h3>What is Unit Testing?</h3><p>Unit testing is a software testing technique that focuses on testing individual units of code, usually functions or methods, in isolation.</p><p>By testing these individual units of code across your applications, you can ensure that each part of your code works as expected, making it easier to identify and fix bugs, refactor code, and add new features without introducing regressions.</p><h3>Why use pytest?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*F2BHs6p9erpiGKro5Pg1uQ.png" /><figcaption>pytest framework logo</figcaption></figure><p>Pytest offers several advantages over other testing frameworks in Python, such as <a href="https://docs.python.org/3/library/unittest.html">unittest</a> and <a href="https://github.com/nose-devs/nose">nose</a>:</p><p>1. <strong>Simplified syntax</strong>: The syntax for tests is <a href="https://docs.pytest.org/en/stable/getting-started.html">concise and easy-to-understand</a>, making it easier and faster to write them.</p><p>2. <strong>Automatic test discovery</strong>: Test functions are <a href="https://docs.pytest.org/en/stable/explanation/goodpractices.html#python-test-discovery">automatically discovered </a>without the need for explicit registration.</p><p>3. <strong>Rich plugin ecosystem</strong>: A <a href="https://docs.pytest.org/en/7.1.x/reference/plugin_list.html">large number of plugins</a> can extend pytest functionalities and connect it with other tools and services, such as <a href="https://pypi.org/project/pytest-cov/">Coverage.py</a>, <a href="https://pypi.org/project/pytest-django/">Django</a> or <a href="https://pypi.org/project/pytest-elasticsearch/">Elasticsearch</a>.</p><h3>Getting started with pytest</h3><h4>Installing pytest</h4><p>During this guide we will use Python 3.11, but pytest supports all Python versions above 3.7. You can install pytest using pip:</p><pre>pip install pytest</pre><h4>Project structure</h4><p>We will create a new Python project to go through the different examples. Create a new directory and add the following subdirectories and files:</p><pre>├── main_project_folder<br>│   ├── src<br>│   │   └── __init__.py<br>│   ├── tests<br>│   │   └── __init__.py<br>│   └── main.py</pre><p>The main.py file will serve as the entry point for your application. In the src directory, we’ll store the source code for your project, and in tests your test code. Also, we include<em> </em>__init__.py files in these directories, which are necessary for pytest to discover the modules, and can remain empty for this tutorial.</p><h3>Writing you first tests</h3><h4>Testing a Python function</h4><p>Let’s write a simple Python function that we will test. Create a file called math_utils.py in the src folder and add the following code:</p><pre>def divide(a: int, b: int) -&gt; float:<br>    &quot;&quot;&quot;Return the result of a division operation between two numbers.<br><br>    Args:<br>        a (int): The numerator.<br>        b (int): The denominator.<br><br>    Returns:<br>        float: The result of the division operation.<br><br>    Raises:<br>        ZeroDivisionError: If b is zero.<br>    &quot;&quot;&quot;<br>    if b == 0:<br>        raise ZeroDivisionError(&quot;You can&#39;t divide by zero!&quot;)<br>    return a / b</pre><p>Now, we can write some tests for this function. Create a new file called test_math_utils.py in the tests folder and add the following code:</p><pre>from src.math_utils import divide<br><br><br>def test_divide_positive_numbers() -&gt; None:<br>    &quot;&quot;&quot;Test that divide returns the correct result when given two numbers.&quot;&quot;&quot;<br>    assert divide(1, 2) == 0.5<br><br><br>def test_divide_negative_numbers() -&gt; None:<br>    &quot;&quot;&quot;<br>    Test that divide returns the correct result when given a positive and<br>    a negative number.<br>    &quot;&quot;&quot;<br>    assert divide(5, -2) == -2.5<br>    assert divide(-2, 5) == -0.4</pre><p>In this example, we’ve written two test functions called test_divide_positive_numbers and test_divide_negative_numbers that tests the divide function from our math_utils module.</p><p>Their results are tested through the assert statement, which checks that the result of the divide function is equal to the expected result. If an assertion fails, pytest will stop and report the failure.</p><p>You can add as many assertions as you want in a test function, but it’s generally recommended to keep it small. Also, notice how the test module and function names start with the test_ pefix, this pytest to automatically discover them.</p><p>Your project structure should now look like this:</p><pre>├── main_project_folder<br>│   ├── src<br>│   │   ├── __init__.py<br>│   │   └── math_utils.py<br>│   ├── tests<br>│   │   ├── __init__.py<br>│   │   └── test_math_utils.py<br>│   └── main.py</pre><p>To run the tests, navigate to the project root directory and execute the following command in your terminal:</p><pre>pytest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IReKwqoMzAo5Qwabu4lYcw.png" /><figcaption>Here are the results from running the two tests with pytest.</figcaption></figure><p>In this case, all tests passed, so we can be confident that our divide function works as expected. 🙂</p><h4>Handling failed tests</h4><p>Now, let’s see what happens if a test fails. Change the test_divide_positive_numbers test function to the following:</p><pre>def test_divide_positive_numbers() -&gt; None:<br>    &quot;&quot;&quot;Test that divide returns the correct result when given two integers.&quot;&quot;&quot;<br>    assert divide(1, 2) == 0.6</pre><p>Notice that we’ve altered the expected result from 0.5 to 0.6. If we run pytest again, we get the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CE0ds9KHoLmCGDOrQGGJ8w.png" /><figcaption>pytest reports the error with the corresponding function and line</figcaption></figure><p>Pytest reported that the test failed, indicating that the expected result was 0.6 and not 0.5. The failed assert statement is also highlighted in red, and its line indicated. By changing the expected result back to 0.5 at the defined line, the test will pass again.</p><h4>Testing for exceptions</h4><p>In our divide function, we raise a ZeroDivisionError if the denominator is zero. Let’s write a test to ensure that this exception is raised correctly. Add the following test function to your test_math_utils.py file:</p><pre>import pytest<br><br><br>def test_divide_by_zero() -&gt; None:<br>    &quot;&quot;&quot;Test that divide raises a ZeroDivisionError when the denominator is zero.&quot;&quot;&quot;<br>    with pytest.raises(ZeroDivisionError, match=&quot;You can&#39;t divide by zero!&quot;):<br>        divide(1, 0)</pre><p>The pytest.raises function checks that the code inside the with block raises the specified exception. You can also provide an optional match argument to verify that the exception message matches a specific pattern, in case the tested function could raise the same type of exception in different scenarios.</p><p>Let’s test that it works by running pytest again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5iD3ThfjEAgHhxWOYdMSOA.png" /><figcaption>The ZeroDivisionError is now correctly tested</figcaption></figure><h3>Writing More Complex Tests</h3><h4>Use fixtures to reuse test data</h4><p>Let’s now look at a more complex example. To avoid the need for instantiating objects in each test you write, you can create fixtures that can be passed as parameters to the test functions. Create a new file called user.py in the src directory and add the following code:</p><pre>class User:<br>    &quot;&quot;&quot;<br>    This class represents a user with attributes ID, name, and age. <br>    <br>    Attributes:<br>        id (Integer): The ID of the user, serves as the primary key.<br>        name (String): The name of the user.<br>        age (Integer): The age of the user.<br>        <br>    Methods:<br>        greet(): Returns a greeting message that includes the user&#39;s name and age.<br>    &quot;&quot;&quot;<br>    id: int<br>    name: str<br>    age: int<br><br>    def __init__(self, id: int, name: str, age: int) -&gt; None:<br>        &quot;&quot;&quot;<br>        Initialize a User instance.<br><br>        Args:<br>            id (int): The ID of the user.<br>            name (str): The name of the user.<br>            age (int): The age of the user.<br>        &quot;&quot;&quot;<br>        self.id = id<br>        self.name = name<br>        self.age = age<br><br>    def greet(self) -&gt; str:<br>        &quot;&quot;&quot;<br>        Create a greeting message that includes the user&#39;s name and age.<br><br>        Returns:<br>            str: A greeting message.<br>        &quot;&quot;&quot;<br>        return f&quot;Hello, my name is {self.name} and I am {self.age} years old.&quot;</pre><p>To test this User object, create a new file called test_user.py:</p><pre>import pytest<br><br>from src.user import User<br><br><br>@pytest.fixture<br>def user() -&gt; User:<br>    &quot;&quot;&quot;Pytest fixture to create a User instance for testing.&quot;&quot;&quot;<br>    return User(1, &quot;John Doe&quot;, 30)<br><br><br>def test_user_creation(user: User) -&gt; None:<br>    &quot;&quot;&quot;Test the creation of a User instance.&quot;&quot;&quot;<br>    assert user.id == 1<br>    assert user.name == &quot;John Doe&quot;<br>    assert user.age == 30<br><br><br>def test_greet(user: User) -&gt; None:<br>    &quot;&quot;&quot;Test the greet method of a User instance.&quot;&quot;&quot;<br>    greeting: str = user.greet()<br>    assert greeting == &quot;Hello, my name is John Doe and I am 30 years old.&quot;</pre><p>In this example, we’ve created a fixture called user that returns a new User instance with an ID, name and age. We then passed this fixture as an argument to our test functions, allowing us to reuse the User<em> </em>instance across multiple tests: test_user_creation to test that the User object is created with the correct name and age, and test_greet to test the greet method’s output.</p><p>Your project structure should now look like this:</p><pre>├── main_project_folder<br>│   ├── src<br>│   │   ├── __init__.py<br>│   │   ├── math_utils.py<br>│   │   └── user.py<br>│   ├── tests<br>│   │   ├── __init__.py<br>│   │   ├── test_math_utils.py<br>│   │   └── test_user.py<br>│   └── main.py</pre><p>To run these tests, simply execute the pytest command again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5cK9vLnnHNOrqImoAl33g.png" /><figcaption>The User instance fixture is correctly used across test_user_creation and test_greet</figcaption></figure><h4>Mock to isolate tests</h4><p>Your application may need to interact with external services. Testing these interactions can be hard because it involves setting up test databases or APIs, adding test data, and cleaning up after each test. To make testing easier, you can use Python’s <a href="https://docs.python.org/3/library/unittest.mock.html">unittest.mock</a> library. It allows you to mimic (“mock”) methods, replacing the real connection with a fake one for testing your function.</p><p>By example, what if we have a database with a users table and want to create User objects from that data? We can mock the database connection during testing to return a fake list of users to separate our tests from the database, eliminating the need for a connection and preventing cascading failures: when tests depending on the database fail if it is unavailable.</p><p>You will need to install <a href="https://www.google.com/search?q=sqlalchemy+github&amp;client=firefox-b-d&amp;ei=gj9qZPTZHL6pkdUPz9qlqAs&amp;ved=0ahUKEwj0otK844b_AhW-VKQEHU9tCbUQ4dUDCA4&amp;uact=5&amp;oq=sqlalchemy+github&amp;gs_lcp=Cgxnd3Mtd2l6LXNlcnAQAzIFCAAQgAQyBggAEBYQHjIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjIKCAAQFhAeEA8QCjIGCAAQFhAeMgYIABAWEB4yBggAEBYQHjIGCAAQFhAeOgoIABBHENYEELADOgoIABCKBRCwAxBDOgcIABCKBRBDSgQIQRgAUIAGWJELYMsMaAFwAXgAgAFLiAHIA5IBATeYAQCgAQHIAQrAAQE&amp;sclient=gws-wiz-serp">sqlalchemy</a>:</p><pre>pip install sqlalchemy</pre><p>And update the User object as following:</p><pre>from sqlalchemy import Column, Integer, String<br>from sqlalchemy.orm import declarative_base<br><br><br>Base = declarative_base()<br><br><br>class User(Base):<br>    &quot;&quot;&quot;<br>    This class represents a user with attributes ID, name, and age.<br><br>    Attributes:<br>        id (Integer): The ID of the user, serves as the primary key.<br>        name (String): The name of the user.<br>        age (Integer): The age of the user.<br><br>    Methods:<br>        greet(): Returns a greeting message that includes the user&#39;s name and age.<br>    &quot;&quot;&quot;<br><br>    __tablename__ = &quot;users&quot;<br><br>    id = Column(Integer, primary_key=True)<br>    name = Column(String)<br>    age = Column(Integer)<br><br>    def __init__(self, id: int, name: str, age: int) -&gt; None:<br>        &quot;&quot;&quot;<br>        Initialize a User instance.<br><br>        Args:<br>            id (int): The ID of the user.<br>            name (str): The name of the user.<br>            age (int): The age of the user.<br>        &quot;&quot;&quot;<br>        self.id = id<br>        self.name = name<br>        self.age = age<br><br>    def greet(self) -&gt; str:<br>        &quot;&quot;&quot;<br>        Create a greeting message that includes the user&#39;s name and age.<br><br>        Returns:<br>            str: A greeting message.<br>        &quot;&quot;&quot;<br>        return f&quot;Hello, my name is {self.name} and I am {self.age} years old.&quot;</pre><p>The modifications are beyond the scope of this tutorial, but the idea is to transform our object to an <a href="https://docs.sqlalchemy.org/en/20/orm/">ORM model</a>, to automatically transform the users from the database to a usable Python object.</p><p>Now, suppose you have a function that connects to a users table and fetches a list of users. Here is an example of how you could implement this in a src/user_repository.py file:</p><pre>from sqlalchemy import create_engine<br>from sqlalchemy.orm import sessionmaker, Session<br><br>from .user import User<br><br><br>class UserRepository:<br>    &quot;&quot;&quot;<br>    This class is used to interact with the database and perform operations on<br>    the User objects.<br><br>    Attributes:<br>        engine (create_engine): An instance of SQLAlchemy Engine for database interaction.<br>        session (Session): An instance of SQLAlchemy Session for transactional scope.<br><br>    Methods:<br>        get_users() -&gt; list[User]:<br>            Fetches all User records from the database and returns them.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, db_url: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Initializes the UserRepository instance with a database connection.<br><br>        Args:<br>            db_url (str): The database connection URL.<br>        &quot;&quot;&quot;<br>        self.engine = create_engine(db_url)<br>        session: Session = sessionmaker(bind=self.engine)<br>        self.session = session()<br><br>    def get_users(self) -&gt; list[User]:<br>        &quot;&quot;&quot;<br>        Fetches all User records from the database.<br><br>        Returns:<br>            list[User]: A list of User instances.<br>        &quot;&quot;&quot;<br>        users = self.session.query(User).all()<br>        return users</pre><p>With this class, we will be able to transform users entries from a database to a list of User objects with the get_users method.</p><p>To test this function without connecting to a database, you can utilize Python’s built-in unittest.mock.create_autospec function. This allows you to create a mock object that mimics the behavior of SQLAlchemy’s <a href="https://docs.sqlalchemy.org/en/20/orm/session.html">Session</a> class:</p><pre>import pytest<br>from unittest.mock import create_autospec<br>from sqlalchemy.orm import Session<br><br>from src.user_repository import UserRepository<br>from src.user import User<br><br><br>@pytest.fixture<br>def mock_session() -&gt; Session:<br>    &quot;&quot;&quot;Pytest fixture to create a mock Session instance.&quot;&quot;&quot;<br>    session = create_autospec(Session)<br>    return session<br><br><br>def test_get_users(mock_session: Session) -&gt; None:<br>    &quot;&quot;&quot;Test the get_users method of the UserRepository class.&quot;&quot;&quot;<br>    # Create a fake user<br>    fake_user = User(id=1, name=&quot;Alice&quot;, age=28)<br><br>    # Mock the Session.query() method to return our fake user<br>    mock_session.query.return_value.all.return_value = [fake_user]<br><br>    # Create a UserRepository instance with the mocked session<br>    user_repository = UserRepository(&quot;postgresql://test:test@test/test&quot;)<br>    user_repository.session = mock_session<br><br>    # Call the get_users method<br>    users = user_repository.get_users()<br><br>    # Ensure that Session.query() was called with the correct argument<br>    mock_session.query.assert_called_with(User)<br><br>    # Assert that the method returned our fake user<br>    assert users == [fake_user]</pre><ol><li>In this test, we use unittest.mock.create_autospec to create a mock object that has the same methods and attributes as SQLAlchemy&#39;s Session class.</li><li>We set up the mock object’s query and all methods to return a list containing our fake user.</li><li>We construct a UserRepository instance and replace its session with our mock session.</li><li>We call the get_users method and ensure that Session.query is called with the correct argument and that the returned list of users matches our list of fake users.</li></ol><p>Now with the current project structure:</p><pre>├── main_project_folder<br>│   ├── src<br>│   │   ├── __init__.py<br>│   │   ├── math_utils.py<br>│   │   ├── user_repository.py<br>│   │   └── user.py<br>│   ├── tests<br>│   │   ├── __init__.py<br>│   │   ├── test_math_utils.py<br>│   │   ├── test_user_repository.py<br>│   │   └── test_user.py<br>│   └── main.py</pre><p>You can finally run your tests again with the pytest command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abmq2-zSOHgqiiX9Q3-T3w.png" /><figcaption>Using mocks, the get_users method is tested without connecting to the database</figcaption></figure><p>By mocking the database connection, we were able to test the get_users function without having to set up a real database or worry about seeding data and cleaning up after.</p><h3>Key Takeaways</h3><p>Here are some best practices to follow when writing tests with pytest:</p><p>1. <strong>Keep tests simple and focused</strong>: Write tests that check one specific aspect of your code to make it easier to understand and maintain them.</p><p>2. <strong>Use descriptive test function names</strong>: Name your test functions in a way that describes the behavior they are testing, e.g., test_divide_positive_numbers.</p><p>3. <strong>Organize your tests</strong>: Group related tests in the same module and use subdirectories to organize tests by functionality or component.</p><p>4. <strong>Test for edge cases</strong>: Ensure that your tests cover extreme scenarios and invalid inputs.</p><p>5. <strong>Use pytest fixtures for reusable setup</strong>: Use fixtures to avoid duplicating setup code across your test functions.</p><p>6. <strong>Mock external dependencies</strong>: Use mocks to isolate your code from external dependencies, and avoid cascading failures.</p><h3>Conclusion</h3><p>Unit testing is crucial to check if your code works right and is reliable. Using best practices and pytest’s tools, you can build tests to protect your code from errors and regressions.</p><p>With the basics of pytest and unit testing in Python under your belt, you can now start applying these techniques to your own projects and enjoy the benefits of more reliable and maintainable code 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=896c8c894304" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>