<?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 Sam Zamany on Medium]]></title>
        <description><![CDATA[Stories by Sam Zamany on Medium]]></description>
        <link>https://medium.com/@samzamany?source=rss-e6d925793409------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MJtxhf0e4FeMwg-oi7YiOw@2x.jpeg</url>
            <title>Stories by Sam Zamany on Medium</title>
            <link>https://medium.com/@samzamany?source=rss-e6d925793409------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:11:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samzamany/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[Unit Testing in Data Engineering: A Practical Guide]]></title>
            <link>https://medium.com/@samzamany/unit-testing-in-data-engineering-a-practical-guide-91196afdf32a?source=rss-e6d925793409------2</link>
            <guid isPermaLink="false">https://medium.com/p/91196afdf32a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Sam Zamany]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 13:51:12 GMT</pubDate>
            <atom:updated>2024-08-28T18:32:58.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vo_Q4TbFPS8yegwBHm2RaA.png" /><figcaption>AI generated image that showcases a data engineer at work in a high-tech environment, with multiple screens displaying various aspects of unit testing and data engineering</figcaption></figure><p>In the realm of data engineering, one often overlooked practice is unit testing. Many might think that unit tests are merely a software development methodology, but that’s far from the truth. As we strive to build robust, error-free data pipelines and SQL data models, the value of unit testing in data engineering becomes increasingly clear. Today, we delve into how we can apply these mature software engineering practices to data engineering.</p><h3>The Importance of Unit Testing</h3><p>For those unfamiliar, unit testing is the practice of testing individual units or components of a software to ascertain that each performs as expected. These could be anything from functions in a Python script to individual SQL queries. By validating each unit’s correctness, we significantly increase the overall reliability of our software, or in this case, our data pipelines and data models.</p><p>In the context of data engineering, the adoption of unit testing ensures that your data, as well as your business logic, are accurate. This leads to high-quality data that your data analysts, scientists, and decision-makers can trust.</p><h3>Unit Testing Data Pipelines</h3><p>Data pipelines often involve complex sequences of data extraction, transformation, and loading (ETL) operations. Therefore, the scope for errors is broad. To unit test these operations, we break down the pipeline into individual components and validate each one independently.</p><p>Let’s take a simple pipeline that extracts data from a CSV file, transforms the data by cleaning null values, and loads it into a database. Here’s a Python-based example using pandas:</p><pre>import pandas as pd<br>from sqlalchemy import create_engine<br><br># Function to load the CSV<br>def load_data(file_name):<br>    data = pd.read_csv(file_name)<br>    return data<br><br># Function to clean the data<br>def clean_data(data):<br>    data = data.dropna()<br>    return data<br><br># Function to save the data to a SQL database<br>def save_data(data, db_string, table_name):<br>    engine = create_engine(db_string)<br>    data.to_sql(table_name, engine, if_exists=&#39;replace&#39;)<br><br># Run pipeline<br>data = load_data(&#39;data.csv&#39;)<br>data = clean_data(data)<br>save_data(data, &#39;sqlite:///database.db&#39;, &#39;my_table&#39;)</pre><p>For unit testing this pipeline, we would write separate tests for each of the functions using a library like pytest.</p><p>In this example, we have three main functions: load_data, clean_data, and save_data. Let&#39;s write tests for each of them. For load_data and save_data, we need to set up a temporary CSV file and SQLite database, which we can do with the pytest library&#39;s fixture feature.</p><pre>import os<br>import pandas as pd<br>import pytest<br>from sqlalchemy import create_engine, inspect<br><br># Use pytest fixtures to set up a temporary CSV file and SQLite database<br>@pytest.fixture<br>def csv_file(tmp_path):<br>    data = pd.DataFrame({<br>        &#39;name&#39;: [&#39;John&#39;, &#39;Jane&#39;, &#39;Doe&#39;],<br>        &#39;age&#39;: [34, None, 56]  # Jane&#39;s age is missing<br>    })<br>    file_path = tmp_path / &quot;data.csv&quot;<br>    data.to_csv(file_path, index=False)<br>    return file_path<br><br><br>@pytest.fixture<br>def sqlite_db(tmp_path):<br>    file_path = tmp_path / &quot;database.db&quot;<br>    return &#39;sqlite:///&#39; + str(file_path)<br><br><br>def test_load_data(csv_file):<br>    data = load_data(csv_file)<br>    <br>    assert &#39;name&#39; in data.columns<br>    assert &#39;age&#39; in data.columns<br>    assert len(data) == 3<br><br><br>def test_clean_data(csv_file):<br>    data = load_data(csv_file)<br>    data = clean_data(data)<br>    <br>    assert data[&#39;age&#39;].isna().sum() == 0<br>    assert len(data) == 2  # Jane&#39;s record should be removed<br><br><br>def test_save_data(csv_file, sqlite_db):<br>    data = load_data(csv_file)<br>    data = clean_data(data)<br>    save_data(data, sqlite_db, &#39;my_table&#39;)<br>    <br>    # Check the data was saved correctly<br>    engine = create_engine(sqlite_db)<br>    inspector = inspect(engine)<br>    tables = inspector.get_table_names()<br>    <br>    assert &#39;my_table&#39; in tables<br>    <br>    loaded_data = pd.read_sql(&#39;my_table&#39;, engine)<br>    assert len(loaded_data) == 2  # Only John and Doe&#39;s records should be present</pre><p>Here is another example: Suppose you have a pipeline that loads data from a CSV file and transforms it by converting a ‘date’ column from string to datetime:</p><pre>def convert_date(data, date_column):<br>    data[date_column] = pd.to_datetime(data[date_column])<br>    return data</pre><p>A unit test for this function would pass it a DataFrame with a known string format for dates. It would then verify that the function correctly converts the dates to datetime objects, and that it handles invalid formats appropriately.</p><p>Let’s write a unit test for the scenario above. This test first checks the function with valid dates, asserting that the ‘date’ column in the output DataFrame is indeed of datetime dtype and that the values are as expected. It then checks that the function correctly raises a ValueError when given an invalid date.</p><pre>import pandas as pd<br>import pytest<br><br>def test_convert_date():<br>    # Test with valid dates<br>    test_data = pd.DataFrame({<br>        &#39;date&#39;: [&#39;2021-01-01&#39;, &#39;2021-01-02&#39;]<br>    })<br>    <br>    converted_data = convert_date(test_data.copy(), &#39;date&#39;)<br>    <br>    assert pd.api.types.is_datetime64_any_dtype(converted_data[&#39;date&#39;])<br>    assert converted_data.loc[0, &#39;date&#39;] == pd.Timestamp(&#39;2021-01-01&#39;)<br>    assert converted_data.loc[1, &#39;date&#39;] == pd.Timestamp(&#39;2021-01-02&#39;)<br><br>    # Test with an invalid date<br>    test_data = pd.DataFrame({<br>        &#39;date&#39;: [&#39;2021-13-01&#39;]  # This date is invalid because there&#39;s no 13th month<br>    })<br>    <br>    with pytest.raises(ValueError):<br>        convert_date(test_data, &#39;date&#39;)</pre><p>Here is the last example: Let’s say you have a pipeline that loads data and then aggregates it, calculating the total sales for each region:</p><pre>def aggregate_sales(data):<br>    aggregated = data.groupby(&#39;region&#39;).sales.sum().reset_index()<br>    return aggregated</pre><p>A unit test for this function would pass it a DataFrame with sales data for various regions. The test would verify that the function correctly calculates the total sales per region.</p><p>Let’s write a unit test for this function. In this test, we first pass the aggregate_sales function a DataFrame with known sales data for each region, and check that it correctly aggregates the sales. We then pass it a DataFrame with no sales, and check that it correctly aggregates these to 0. This ensures the function handles both typical and edge cases correctly.</p><p>Here is how you might write a unit test using the pytest library for the aggregate_sales function:</p><pre>import pandas as pd<br>import pytest<br><br>def test_aggregate_sales():<br>    # Test data with sales for each region<br>    test_data = pd.DataFrame({<br>        &#39;region&#39;: [&#39;North&#39;, &#39;North&#39;, &#39;South&#39;, &#39;South&#39;, &#39;East&#39;, &#39;East&#39;, &#39;West&#39;, &#39;West&#39;],<br>        &#39;sales&#39;: [100, 200, 300, 400, 500, 600, 700, 800]<br>    })<br>    <br>    aggregated = aggregate_sales(test_data)<br>    <br>    assert aggregated.loc[aggregated[&#39;region&#39;] == &#39;North&#39;, &#39;sales&#39;].values[0] == 300<br>    assert aggregated.loc[aggregated[&#39;region&#39;] == &#39;South&#39;, &#39;sales&#39;].values[0] == 700<br>    assert aggregated.loc[aggregated[&#39;region&#39;] == &#39;East&#39;, &#39;sales&#39;].values[0] == 1100<br>    assert aggregated.loc[aggregated[&#39;region&#39;] == &#39;West&#39;, &#39;sales&#39;].values[0] == 1500<br><br>    # Test with no sales data<br>    test_data = pd.DataFrame({<br>        &#39;region&#39;: [&#39;North&#39;, &#39;South&#39;, &#39;East&#39;, &#39;West&#39;],<br>        &#39;sales&#39;: [0, 0, 0, 0]<br>    })<br>    <br>    aggregated = aggregate_sales(test_data)<br>    <br>    assert aggregated.loc[aggregated[&#39;region&#39;] == &#39;North&#39;, &#39;sales&#39;].values[0] == 0<br>    assert aggregated.loc[aggregated[&#39;region&#39;] == &#39;South&#39;, &#39;sales&#39;].values[0] == 0<br>    assert aggregated.loc[aggregated[&#39;region&#39;] == &#39;East&#39;, &#39;sales&#39;].values[0] == 0<br>    assert aggregated.loc[aggregated[&#39;region&#39;] == &#39;West&#39;, &#39;sales&#39;].values[0] == 0</pre><h3>Unit Testing SQL Data Models</h3><p>When it comes to SQL-based data models, unit tests mostly revolve around testing your SQL queries. For example, you might test that a query returns the expected results given a specific input, or that it handles edge cases correctly.</p><p>Consider a SQL query that calculates the average order value:</p><pre>SELECT AVG(order_value) as avg_order_value FROM orders;</pre><p>A unit test for this query might insert a few rows into the orders table and verify that the query correctly calculates the average. While there are several tools to facilitate SQL unit testing, a popular one in the data engineering space is dbt (data build tool), which has built-in support for data tests.</p><p>In this example, we’re going to assume that you have a dbt project set up and you’re following dbt’s recommended project structure. You’d have a model that calculates the average order value (let’s call this avg_order_value.sql), and we can add a test for it.</p><p>First, let’s define the model in avg_order_value.sql:</p><pre>-- This is your model which calculates the average order value<br>SELECT AVG(order_value) as avg_order_value FROM {{ ref(&#39;orders&#39;) }}</pre><p>For testing, we’ll use dbt’s data tests. These are simply SQL queries that dbt runs against your data. If the query returns any rows, the test fails. If the query returns no rows, the test passes.</p><p>We’ll create a new file in the tests directory called avg_order_value_test.sql. In this file, we&#39;ll write a query that checks if the average order value is within expected limits:</p><pre>-- This is your test<br>-- Assume you&#39;ve calculated the average manually for your test data and it is 100<br><br>WITH avg_order_value_test AS (<br>  SELECT AVG(order_value) as avg_order_value FROM {{ ref(&#39;orders&#39;) }}<br>)<br><br>SELECT *<br>FROM avg_order_value_test<br>WHERE avg_order_value &lt;&gt; 100 -- The test will fail if the average order value is not 100</pre><p>Remember to replace 100 with the expected average order value for your test data.</p><p>You can run this test with the command dbt test.</p><p>This is a simple case, but you can build up more complex test scenarios. For example, you could add more data to the orders table and verify that the average is updated correctly, or you could add edge cases such as orders with a value of 0 or NULL and ensure they&#39;re handled correctly.</p><p><strong>Testing COUNT</strong>: Suppose you have a SQL query that counts the number of active users in a table:</p><pre>SELECT COUNT(*) as active_users FROM users WHERE status = &#39;active&#39;;</pre><p>A unit test for this query would insert some test data into the users table, ensuring a known number of these users have a status of &#39;active&#39;. It would then execute the query and verify that the count returned is as expected.</p><p>Using dbt, a YAML-based test for the COUNT example could look like this:</p><pre>version: 2<br><br>models:<br>  - name: users<br>    tests:<br>      - dbt_utils.expression_is_true:<br>          expression: &quot;count(*) = 5&quot;<br>          where: &quot;status = &#39;active&#39;&quot;</pre><p>Here, we’re asserting that there are exactly 5 active users. Modify this value as per your test data setup.</p><p><strong>Testing joins</strong>: Assume you have a query that joins two tables: orders and order_items, summing the total cost of each order:</p><pre>SELECT o.order_id, SUM(i.item_price * i.quantity) as total_order_cost<br>FROM orders o <br>JOIN order_items i ON o.order_id = i.order_id<br>GROUP BY o.order_id;</pre><p>To unit test this query, you’d first populate the orders and order_items tables with test data, ensuring that some orders have multiple items. The test would then verify that the total_order_cost is correctly calculated for each order, particularly those with multiple items.</p><p>Using dbt, a YAML-based test for the JOIN example could look like this:</p><pre>version: 2<br><br>models:<br>  - name: orders<br>    tests:<br>      - dbt_utils.expression_is_true:<br>          expression: &quot;total_order_cost = 100.00&quot;<br>          where: &quot;order_id = 1&quot;</pre><p>Here, we’re asserting that the total order cost for order_id 1 is 100. Adjust this as per your test data setup.</p><p>Let’s make another assertion. In this example, we would like to verify that our join operation and the subsequent aggregation operation are working correctly. In order to create a more complex test, let’s consider a scenario where we have multiple orders, with multiple items in each order, and we want to verify the total cost calculation for multiple orders.</p><p>Let’s assume that our test data setup is as follows:</p><p>Orders Table:</p><pre>[<br>  {<br>    &quot;order_id&quot;: 1,<br>    &quot;customer_id&quot;: 100<br>  },<br>  {<br>    &quot;order_id&quot;: 2,<br>    &quot;customer_id&quot;: 101<br>  },<br>  {<br>    &quot;order_id&quot;: 3,<br>    &quot;customer_id&quot;: 102<br>  }<br>]</pre><p>Order_Items Table:</p><pre>[<br>  {<br>    &quot;order_item_id&quot;: 1,<br>    &quot;order_id&quot;: 1,<br>    &quot;item_price&quot;: 10,<br>    &quot;quantity&quot;: 5<br>  },<br>  {<br>    &quot;order_item_id&quot;: 2,<br>    &quot;order_id&quot;: 1,<br>    &quot;item_price&quot;: 20,<br>    &quot;quantity&quot;: 2<br>  },<br>  {<br>    &quot;order_item_id&quot;: 3,<br>    &quot;order_id&quot;: 2,<br>    &quot;item_price&quot;: 30,<br>    &quot;quantity&quot;: 3<br>  },<br>  {<br>    &quot;order_item_id&quot;: 4,<br>    &quot;order_id&quot;: 2,<br>    &quot;item_price&quot;: 40,<br>    &quot;quantity&quot;: 1<br>  },<br>  {<br>    &quot;order_item_id&quot;: 5,<br>    &quot;order_id&quot;: 3,<br>    &quot;item_price&quot;: 50,<br>    &quot;quantity&quot;: 1<br>  }<br>]</pre><p>In the JSON representation, each row in the table becomes a JSON object inside an array. The column names become the keys of the JSON objects, and the corresponding cell values become the values of the JSON objects. See the table below for a representation of this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1kVKFtxrEqfkPm2HD7jkg.png" /></figure><p>In this scenario, we would expect the total cost for order 1 to be 90 (50<em> + 40</em>), for order 2 to be 130 (90<em> + 40</em>) and for order 3 to be 50 (50*1).</p><p>Our dbt YAML-based test could look like this:</p><pre>version: 2<br><br>models:<br>  - name: orders<br>    tests:<br>      - dbt_utils.expression_is_true:<br>          expression: &quot;total_order_cost = 90.00&quot;<br>          where: &quot;order_id = 1&quot;<br>      - dbt_utils.expression_is_true:<br>          expression: &quot;total_order_cost = 130.00&quot;<br>          where: &quot;order_id = 2&quot;<br>      - dbt_utils.expression_is_true:<br>          expression: &quot;total_order_cost = 50.00&quot;<br>          where: &quot;order_id = 3&quot;</pre><p>Here, we are adding multiple assertions to check the correctness of the total order cost for multiple orders. This allows us to verify not only the correctness of our join operation, but also our ability to correctly calculate total costs across multiple orders and items.</p><h3>Unit Testing and Continuous Integration</h3><p>Once you have a suite of unit tests, you can integrate them into a Continuous Integration (CI) pipeline. A CI pipeline automatically builds and tests your code whenever changes are pushed to the codebase. This way, if a change introduces a bug in your data pipeline or data model, the CI pipeline will catch it before it affects your production data systems.</p><p>Several CI tools can help set this up, such as Jenkins, Travis CI, or GitLab CI. The specifics of setting up a CI pipeline will depend on the tool, but the general idea is to run your unit tests every time new code is pushed.</p><p>Let’s see how you can integrate a Python unit test into a simple CI pipeline using a popular CI/CD tool: GitHub Actions.</p><p>Let’s assume you have a Python project with a set of unit tests written using pytest. You have a file named test_example.py with a function like this:</p><pre>def test_addition():<br>    assert 1 + 1 == 2</pre><p>You can run these tests automatically whenever you push changes to your GitHub repository by creating a GitHub Actions workflow. Create a new file in your repository at .github/workflows/ci.yml with the following content:</p><pre>name: Python CI<br><br>on:<br>  push:<br>    branches: [ main ]<br>  pull_request:<br>    branches: [ main ]<br><br>jobs:<br>  build:<br><br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - uses: actions/checkout@v2<br><br>    - name: Set up Python<br>      uses: actions/setup-python@v2<br>      with:<br>        python-version: &#39;3.8&#39;<br><br>    - name: Install dependencies<br>      run: |<br>        python -m pip install --upgrade pip<br>        pip install pytest<br>        # If your project has other dependencies listed in a requirements.txt, install them with:<br>        # pip install -r requirements.txt<br><br>    - name: Run tests<br>      run: |<br>        pytest</pre><p>This workflow runs whenever you push changes to the main branch or open a pull request to main. It sets up a fresh Python 3.8 environment, installs your project&#39;s dependencies, and runs your pytest test suite. If any of your tests fail, the workflow fails, and you will be notified of the failure.</p><p>Remember, this is just a simple example. Real-world CI pipelines are often significantly more complex and typically encompass a wide range of tasks to ensure the stability and reliability of your code. These tasks might include not only building Docker images but also managing multi-stage Docker builds to optimize the size and security of your containers. In addition to deploying your code to various staging environments, which could include cloud-based platforms like AWS, Azure, or GCP, CI pipelines might also handle infrastructure provisioning using tools like Terraform or CloudFormation.</p><p>Moreover, a robust CI pipeline will include extensive automated testing beyond just unit tests. This can involve running integration tests to verify that different parts of the system work together correctly, executing end-to-end tests to simulate real user interactions, and conducting performance tests to ensure that the application meets scalability requirements. Security is another critical aspect, where static code analysis, dependency checks for vulnerabilities, and penetration tests are integrated into the pipeline.</p><p>To further enhance the deployment process, CI pipelines might include blue-green or canary deployments, allowing for incremental rollout and immediate rollback in case of issues. Monitoring and logging integrations are often built into the pipeline as well, enabling real-time tracking of application health and performance once it’s deployed. Finally, pipelines might also automate the generation of reports and notifications, keeping the team informed about the build status, test results, and any issues that require attention.</p><h3>Conclusion</h3><p>Unit testing might seem like extra work, but the upfront effort pays dividends in the long run. In a field where trust in data is paramount, having confidence in your data pipelines and data models is essential.</p><p>The key takeaway here is that data engineering can benefit significantly from methodologies in software engineering. By adopting practices like unit testing and continuous integration, we can increase the reliability of our data systems, catch bugs before they propagate downstream, and ultimately, foster a culture of trust in data within our organizations.</p><p>Remember, the goal of these tests is not only to verify correctness under normal conditions, but also to ensure your pipeline or query handles edge cases and errors gracefully. Through unit testing, you can build data pipelines and SQL data models that are robust and reliable, boosting confidence in your data systems.</p><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91196afdf32a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>