<?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 Shreya Sharma on Medium]]></title>
        <description><![CDATA[Stories by Shreya Sharma on Medium]]></description>
        <link>https://medium.com/@ssharma31?source=rss-7ba975d91106------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s4W50DLfiV6Ph2MDWB7rzQ.jpeg</url>
            <title>Stories by Shreya Sharma on Medium</title>
            <link>https://medium.com/@ssharma31?source=rss-7ba975d91106------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:57:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ssharma31/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[Databricks Genie One for Delivery Managers]]></title>
            <link>https://medium.com/@ssharma31/databricks-genie-one-for-delivery-managers-e732440a4204?source=rss-7ba975d91106------2</link>
            <guid isPermaLink="false">https://medium.com/p/e732440a4204</guid>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[genie]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[scrum-master]]></category>
            <dc:creator><![CDATA[Shreya Sharma]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 06:02:37 GMT</pubDate>
            <atom:updated>2026-10-20T22:35:01.868Z</atom:updated>
            <content:encoded><![CDATA[<p>A delivery manager looks through boards, creates status decks and hosts standups, but all these are mechanisms for answering two questions:</p><ol><li><strong>Are the tickets moving?</strong></li><li><strong>What’s about to go wrong?</strong></li></ol><p>Genie One is Databricks’ conversational agent that lets you ask questions and get answers grounded in your governed data and, through managed connectors, the tools around it (Jira, Confluence, GitHub, and more).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2iTZx5qT_5P37d2dQRgKmQ.jpeg" /></figure><h3>Are the tickets moving?</h3><p>Through the Databricks’ managed Atlassian connector, Genie One reads your Jira boards, and instead of filtering a board, you ask the question the way you’d ask one of your engineers:</p><ul><li><em>“How many tickets in the mobile-app project are still in progress this sprint, and who owns the oldest one?”</em></li><li><em>“What moved to Done since yesterday, and what’s still untouched?”</em></li></ul><p>You can combine this context with information from Github (e.g. search the repo to confirm a branch or PR actually exists for a ticket). so you can make sure that progress is being tracked consistently.</p><h3>What’s about to go wrong?</h3><p>Genie One lets you identify and triangulate across all three systems, instead of having to log on to three separate systems, none of which are able to identify additional context from another:</p><p><strong>From Jira:</strong></p><ul><li><em>“Summarize every blocker-labeled ticket this week, and flag anything that hasn’t moved in three days.”</em></li><li>Stale blockers are your earliest risk signal, and now they surface in one question.</li></ul><p><strong>From GitHub:</strong></p><ul><li>When a ticket says “in review,” Genie One can search the repository so you can see whether the code actually exists, instead of taking the status at face value.</li></ul><p><strong>From Confluence:</strong></p><ul><li>Genie One can pull the context behind the work : <em>“Find the Q4 launch runbook and summarize the open-risks section.”</em></li></ul><p>For example, Jira identifies a stale ticket, you can look for the branch associated with that particular ticket and investigate what the latest changes were and when they came through. A lookup on Jira first contextualises the search in Github — this is the power of a centralised agent.</p><h3>Run on a Schedule</h3><p>Genie One can also run on a schedule, so instead of asking ad-hoc queries, you can set up schedules:</p><ul><li>A <strong>daily progress run</strong> triggers every morning before standup and answers “what moved to Done since yesterday, what’s still in progress, and what hasn’t been touched?”</li><li>A <strong>daily risk run</strong> scans for the warning signs on its own. E.g. blockers that haven’t moved in three days, tickets marked “in review” with no code to back them up, launch risks sitting unread in Confluence.</li><li>And a <strong>weekly rollup</strong> that creates a status update document for you: progress against the sprint goal, surfacing or risks identified over the week and what actually landed in prod. And using the Gmail connector, it can send these status updates to your team as well.</li></ul><p>The takeaway — Genie One isn’t only for data questions. Connect Jira, GitHub and Confluence and it covers what delivery managers and scrum masters care about most: what’s moving, and what’s about to break.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e732440a4204" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architectures for Databricks Delta Live Tables]]></title>
            <link>https://medium.com/@ssharma31/architectures-for-databricks-delta-live-tables-a967137da160?source=rss-7ba975d91106------2</link>
            <guid isPermaLink="false">https://medium.com/p/a967137da160</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[delta-live-tables]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dlt]]></category>
            <category><![CDATA[solution-architecture]]></category>
            <dc:creator><![CDATA[Shreya Sharma]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 12:32:22 GMT</pubDate>
            <atom:updated>2024-07-23T12:32:22.912Z</atom:updated>
            <content:encoded><![CDATA[<p>Databricks Delta Live Tables (DLT) is an ETL framework that enables the efficient build of data pipelines by enabling engineers to focus on the core data transformations, while DLT handles infrastructure management, cluster sizing, orchestration, error handling, and performance optimization.</p><p>Organizations who choose to enable Delta Live Tables can do so using a multitude of different approaches — this blog aims to share some of the more popular architectures when working with multiple source systems, as well as the pros and cons of each solution.</p><p>In the proposed architecture we’ll leverage an example of a company that is selling items across two different sales platforms — we’ll refer to these as sources A and B. Each platform will record information about customers.</p><ul><li>In the bronze layer, the company will pull customer data from each of the sources and leave them separate.</li><li>In the silver layer, they will combine the customer data from sources A and B to get a combined view of all their customers.</li><li>A possible driver for the gold layer could be to create a dashboard to summarize information about their customers, leveraging information like location to better understand their consumer base.</li></ul><h4>Architecture 1: Separate each source into it’s own DLT pipeline and leverage the MERGE logic in the silver layer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*l4rietpXPbTGbU1o2_5BNw.png" /></figure><ol><li>In the bronze layer, each source will have multiple tables and be configured to be it’s own DLT pipeline.</li><li>In the silver layer, the MERGE operation will be leveraged, as well as custom logic for history stitching and processing late arriving records.</li></ol><p>This solution is a good option because:</p><ul><li>By separating the bronze sources into different DLT pipelines, it enhances traceability and allows for better segregation of data elements.</li><li>Each source is likely to have it’s own requirements for data freshness — by segregating each source into it’s own pipeline, you do not need to refresh all tables from other sources, or specifically call out which tables need to be refreshed.</li></ul><p>It is not possible for the All_Customers table to be a DLT table, since <strong>two DLT pipelines cannot directly write to the same table</strong>. <a href="https://learn.microsoft.com/en-us/azure/databricks/delta-live-tables/">This is a known limitation of Delta Live Tables</a>. Instead, there is an increased complexity where custom logic would need to be implemented to handle history stitching and out of order records.</p><h4>Architecture 2: Group dependencies from sources together into the same DLT pipline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*5jF50VxsZt-u99mIhxsnfw.png" /></figure><ol><li>In the bronze layer, DLT pipelines will be configured based on the different dependencies each group of silver tables requires. Groupings will need to be predominantly based off dependencies, but can also be loosely related to business use-cases (e.g. the A_Customer, B_Customer and All_Customer tables can all be grouped under the “Consumer Analysis” use-case).</li><li>The silver table is now a Delta Live Table, and will benefit from automatic updates when it’s source tables updates, automatic error handling, monitoring and performance tuning</li></ol><p>By following this architecture:</p><ul><li>The silver table will update automatically when new rows will come into A_Customer and B_Customer tables.</li><li>Monitoring, lineage, data quality all enabled in the silver layer and parallelism is automatically handled.</li><li>Code can remain modularised by segregating sources, bronze and silver DLT code into different notebooks. For example, all tables for bronze for source 1 can be separate to source 2, and silver table code.</li></ul><p>This architecture is <a href="https://github.com/databricks/delta-live-tables-notebooks/blob/main/sql/Retail%20Sales.sql">leveraged most often in Databricks demos</a>. However, under this solution, DLT pipelines can become complex quickly, especially since multiple sources for bronze, silver and gold tables will be distributed across different pipelines. This may lead to harder traceability, even if the code is modularised — i.e. which table is generated in which DLT pipeline.</p><h4>Architecture 3: Separate Bronze and Silver into their own pipelines and link these tables together using their catalog references</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*2GBbF_xu__Ybwmu2EvvBaQ.png" /></figure><ol><li>In the bronze layer, each source will have multiple tables and be configured to be it’s own DLT pipeline.</li><li>The silver tables will now be configured to run in their own DLT pipeline, working around previous limitations by referencing source tables by catalog.schema instead of LIVE.tablename (e.g prod.bronze.A_Customer instead of LIVE.A_Customer). This means the silver tables will benefit from automatic error handling, monitoring and performance tuning.</li></ol><p>This is a strong solution that balances the best capabilities of Delta Live Tables and ensures that pipelines and modular, segregated and traceable:</p><ul><li>By separating the bronze sources into different DLT pipelines, it enhances traceability and allows for better segregation of data elements.</li><li>Each source is likely to have it’s own requirements for data freshness — by segregating each source into it’s own pipeline, you do not need to refresh all tables from other sources, or specifically call out which tables need to be refreshed.</li><li>Monitoring, lineage, data quality all enabled in the silver layer. Parallelism is also handled in the Silver layer</li><li>Code can remain modularised by segregating DLT code into different notebooks as required for the bronze and silver layers.</li></ul><p>A note on this solution is that unlike architecture 2, when the bronze tables update, the silver table itself will not necessarily update unless a Databricks Workflow is put into place to trigger the Silver DLT job. Alternatively, the Silver DLT pipeline can be triggered to only run once a day, or according to business requirements.</p><p>The benefit of this solution is that in the silver layer, all tables can be configured to update at the same time as long, meaning that when end-users query into the silver (or gold) tables, and join across the tables, they can be confident that all tables have the same level of freshness, and are not joining with stale data.</p><h4>Conclusion</h4><p>Delta Live Tables can be a powerful tool, if it’s architected for success, and the correct architecture for an organisation will depend on the amount of sources, tables and inter-relation between sources that exist.</p><p>Keep in mind when working across different sources the need for modularity, adhering to source freshness requirements and ensuring that your use cases don’t get start joining fresh with stale data.</p><p><strong>Helpful Resources</strong></p><ul><li><a href="https://learn.microsoft.com/en-us/azure/databricks/delta-live-tables/updates">https://learn.microsoft.com/en-us/azure/databricks/delta-live-tables/updates</a></li><li><a href="https://learn.microsoft.com/en-us/azure/databricks/delta-live-tables/">https://learn.microsoft.com/en-us/azure/databricks/delta-live-tables/</a></li><li><a href="https://www.databricks.com/blog/build-governed-pipelines-delta-live-tables-and-unity-catalog">https://www.databricks.com/blog/build-governed-pipelines-delta-live-tables-and-unity-catalog</a></li><li><a href="https://www.databricks.com/discover/pages/getting-started-with-delta-live-tables">https://www.databricks.com/discover/pages/getting-started-with-delta-live-tables</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a967137da160" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Data Quality Constraints using Databricks Delta Live Tables]]></title>
            <link>https://medium.com/@ssharma31/advanced-data-quality-constraints-using-databricks-delta-live-tables-2880ba8a9cd7?source=rss-7ba975d91106------2</link>
            <guid isPermaLink="false">https://medium.com/p/2880ba8a9cd7</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[delta-live-tables]]></category>
            <dc:creator><![CDATA[Shreya Sharma]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 07:34:41 GMT</pubDate>
            <atom:updated>2023-06-19T07:34:41.331Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Recap of Delta Live Tables and Medallion Architecture</h3><p><strong>Use Delta Live Tables to create your pipeline : </strong>Delta Live Tables (DLT) are an easy-to-use framework that utilises Spark SQL or pyspark to create data processing pipelines. The transformations in these pipelines are defined by you but Databricks will handle everything else — from task orchestration and cluster management to error handling.</p><p><strong>The Data in the Pipeline:</strong> Medallion architecture is the recommended Databricks way to structure and process data and goes hand-in-hand with DLT — it enables the processing of data through multiple stages, providing clean, curated, and valuable insights for decision-making.</p><ol><li>Bronze: The step where data is standardised, audit columns are added and the data is transformed into a structured format for further analysis.</li><li>Silver: The step where curated and enriched data is stored, incorporating business rules and additional context.</li><li>Gold: The step where data is aggregated, summarised, and optimised for business intelligence and reporting purposes.</li></ol><h3>The Base Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDBmjf5LvTS77gzDhuMfjg.png" /></figure><p>Let’s start with a simple medallion architecture created for this demonstration. We’ll focus on integrating data quality checks for only the bronze layer, but these principles can easily be applied to the silver and gold layers as well.</p><p><strong>Bronze Layer</strong></p><p>The bronze layer consists of the customer, product and sales tables with the relationships defined as below. To each table, we have added in the audit columns — __ingestion_time and __row_uuid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*t3hAZqIsPLLFU_s0dyjF5A.png" /></figure><h3>Enforcing Data Quality</h3><p>Now that our data pipeline is set, let’s discuss how to enforce the data quality within that pipeline. Integrating data quality is crucial for organisations to leverage the full potential of their data assets, make informed decisions, maintain trust, reduce costs, comply with regulations, and drive business success.</p><p>We’ll discuss two ways to enforce data quality using DLT’s CONSTRAINT functionality. Please note that to integrate any of these conditions into your DLTs, you must be using the Advanced product edition of DLT.</p><ol><li>Integrating Constraints into DLT materialised views</li><li>Integrating Data Quality Checks within the DLT Pipeline</li></ol><p>While the demonstrations in this article focused on using views and materialised views, a number of these tests can also be applied to streaming tables. Keep in mind though, streaming tables are assumed append-only and generally handle (and process) micro-batches at a time. This means that you should avoid any tests such as unique key id, or checking whether a certain key exists in a streaming table — these tests can be done, but on materialised views that come in your pipeline, after your streaming ingestion is done.</p><p>A final note on choosing between SQL and Python when writing your DLT pipelines — while SQL provides an easier readability and lower barrier to entry, there are currently more tools available when creating the pipelines in Python — notably the expect_all conditions to allow for multiple constraints and the ability to localise all your tests in one table and dynamically reference those constraints from your DLT tables which improves portability.</p><h4>Integrating Constraints into DLT Materialised Views</h4><p>For each constraint that we add in, we need to also define the name of the constraint, a boolean statement and the actions that we will take if it is violated.</p><p><strong>Actions:</strong></p><ol><li>Expect: If the constraint is violated, the record is logged as a data quality issue, but it is still added to the target table and the pipeline continues to function as normal.</li><li>Expect or on Violation Drop Row : The record is not added to the target table, a data quality issue is recorded by DLT and pipeline continues to function as normal.</li><li>Expect or on Violation Fail Update: The pipeline fails when it encounters this record — it is not added to the target table.</li></ol><p>Let’s introduce a basic data quality rule into our bronze layer:</p><ul><li>valid-customer-ids: CustomerID IS NOT NULL — if this record fails, let’s drop the row</li></ul><p>The bronze code to generate the bronze_customer table will be updated as follows:</p><pre>CREATE OR REFRESH LIVE TABLE bronze_customer (<br>  CONSTRAINT valid_customer_ids EXPECT (CustomerID IS NOT NULL) ON VIOLATION DROP ROW<br>)<br>COMMENT &quot;Bronze layer customer data&quot;<br>AS<br>SELECT *, current_timestamp() as __ingestion_time, uuid() as __row_uuid<br>FROM live.raw_customer</pre><p>The resulting DLT pipeline shows that one row was dropped when processing the bronze-customer table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6sK_E_B42TsoToXirWa_Q.png" /></figure><p>Alright but what about in the case when we want a table to have multiple constraints — in pyspark you would use expect all condition, but in SQL you can leverage the AND condition to ensure that all of your conditions are being met.</p><p>In the following example, we expect that for the bronze_product table, it must have both a valid ProductID and ProductDescription:</p><pre>CREATE OR REFRESH LIVE TABLE bronze_product (<br>  CONSTRAINT valid_product_ids EXPECT (ProductID IS NOT NULL AND ProductDescription IS NOT NULL) ON VIOLATION DROP ROW<br>)<br>COMMENT &quot;Bronze layer product data&quot;<br>AS<br>SELECT *, current_timestamp() as __ingestion_time, uuid() as __row_uuid<br>FROM live.raw_product</pre><p>This will generate the following DLT pipeline, where we can see three records were dropped from bronze-product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3C5pcScnqGiZ5MZOQVykuw.png" /></figure><p>Here is the resulting bronze_product table — we can see that neither of the ProductID or ProductDescriptions have NULL values in them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*rUmY6wsEg92w3lLIsnYmzw.png" /></figure><p>An AND condition is generally straightforward — let’s increase the complexity of our constraints by creating a final constraint for the bronze_sales table called valid_sales_data that will flag — but not drop rows and needs to ensure the following:</p><ul><li>Must have a valid SalesId</li><li>The SalesDate must not be in the future unless the CustomerId is 1</li><li>If the ProductId is 1 then the SalesAmount should be $100.50</li></ul><p>The resulting code to generate bronze_product is:</p><pre>CREATE OR REFRESH LIVE TABLE bronze_sales (<br>  CONSTRAINT valid_sales_data EXPECT (((SalesID IS NOT NULL) AND ((SaleDate &lt;= current_timestamp()) OR (CustomerId = 1)) AND (CASE WHEN (ProductID = 1) THEN CAST(100.5 AS DECIMAL(12,2)) ELSE CAST(Amount AS DECIMAL(12,2)) END IS NOT NULL))) <br>)<br>COMMENT &quot;Bronze layer sales data&quot;<br>AS<br>SELECT *, current_timestamp() as __ingestion_time, uuid() as __row_uuid<br>FROM live.raw_sales</pre><p>We can see in the DLT pipeline that although no records were dropped, there were issues with two rows in our silver table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDuoqsuXSIzjzjBSziGKbQ.png" /></figure><p>We can write a quick query to identify the rows that flagged against the data quality constraints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqCcdMEga5E_PZvYrQZ6fg.png" /></figure><h4>Integrating Data Quality Checks within the DLT Pipeline</h4><p>We have introduced a lot of data quality constraints that are integrated in tables, but there are certain tests that we can integrate into pipelines instead.</p><ol><li><strong>Check uniqueness of all primary keys in a table: </strong>Create a materialised view to check the uniqueness of the CustomerId field in bronze_customer:</li></ol><pre>CREATE OR REFRESH LIVE TABLE unique_customer_bronze_pk(<br>  CONSTRAINT unique_pk EXPECT (record_count = 1) ON VIOLATION FAIL UPDATE<br>)<br>AS<br>SELECT CustomerID, count(*) as record_count<br>FROM live.bronze_customer<br>GROUP BY CustomerId</pre><p>Since there is a duplicate CustomerId in bronze_customer, the constraint will fail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7I8APQjGJoW5GWe-QMt_w.png" /></figure><p>Since we added the ON VIOLATION FAIL UPDATE condition to the constraint, and the constraint fails, this means the whole DLT fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSjyWvU8QyzkJT3GuzEXBA.png" /></figure><p>2. Verify the existence of primary keys across multiple tables: Create a materialised view to verify that a CustomerId from the bronze_sales table exists in the bronze_customer table</p><pre>CREATE OR REFRESH LIVE TABLE valid_customer_id_for_sales(<br>  CONSTRAINT valid_customer_id_for_sales EXPECT (customer.CustomerId IS NOT NULL) ON VIOLATION FAIL UPDATE<br>)<br>AS<br>SELECT sales.*, customer.CustomerId as Validated_CustomerId<br>FROM live.bronze_sales sales<br>LEFT JOIN live.bronze_customer customer<br>ON sales.CustomerId = customer.CustomerId</pre><p>This can also be integrated into the DLT pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ui0MjaORbFMhD2wkUDmEQ.png" /></figure><h3>Final Thoughts</h3><p>Integrating data quality into pipelines is essential to have meaningful, quality data that can contribute to business outcomes. I would recommend ensuring your data quality by:</p><ul><li>Integrating constraints within tables</li><li>Integrating further “testing” materialised views throughout the pipelines</li></ul><h3>Helpful Links</h3><ul><li>Manage data quality with Delta Live Tables: <a href="https://docs.databricks.com/delta-live-tables/expectations.html#expect-all">https://docs.databricks.com/delta-live-tables/expectations.html#expect-all</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2880ba8a9cd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Pytest with Databricks]]></title>
            <link>https://medium.com/@ssharma31/integrating-pytest-with-databricks-a9e47afecd85?source=rss-7ba975d91106------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9e47afecd85</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[testing-framework]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Shreya Sharma]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 07:09:20 GMT</pubDate>
            <atom:updated>2024-04-19T05:18:45.758Z</atom:updated>
            <content:encoded><![CDATA[<p>As more companies move their platforms and workloads into Databricks, they look to leverage existing frameworks and modules in python to automate their testing.</p><p>The Pytest module provides a popular framework that can be used develop a range of software tests in a simple and scalable way — from unit and integration tests to complex end-to-end tests.</p><p><strong>The Challenge: </strong>Although Databricks does integrate with pytest well, there is limited documentation, both by Databricks and Pytest on the different methods of integration.</p><h3>Setting up the environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*aR_kszOvtrceHpxShmkzug.png" /><figcaption>Environment setup for integrating Databricks and Pytest</figcaption></figure><p>In your Databricks workspace, we’ll need two files:</p><ol><li>A python file with a <em>test_ </em>prefix (e.g. <em>test_sampleunittests.py)</em></li></ol><p>This file will hold two simple tests — one which will pass and the other which will fail. As we go through the demo, we’ll also augment this file to take in dynamic variables.</p><pre># In test_sampleunittests.py<br>import pytest<br><br>def test_shouldpass():<br>  assert True<br><br>def test_shouldfail():<br>  assert False</pre><p>2. A Databricks notebook where you will invoke pytest (e.g. <em>PytestDemo</em>)</p><p>You will need a minimum of two cells to run the code within the Databricks notebook — the first cell (below) will install pytest. To avoid this, you can also install pytest onto your cluster or via a subprocess.Popen() command.</p><pre># In Databricks Notebook (cell 1)<br>%sh pip install pytest</pre><p>After that, we can continue to set up our environment for our pytest:</p><pre># In Databricks notebook (cell 2)<br>import pytest<br>import os<br>import sys<br>import test_sampleunittests<br><br>sys.dont_write_bytecode = True<br>os.chdir(&quot;/Workspace/Users/&lt;yourusername&gt;/&quot;)</pre><h3>Comparing Pytest Invocation Methods</h3><p>Now that we’re setup, let’s take a look at the two ways that we can invoke Pytest on Databricks. For each of these proposed methods we’ll analyse them across the following factors:</p><ol><li>User accessibility to pytest results</li><li>Ability to dynamically pass in variables</li></ol><p><strong>Option 1: Invoking pytest.main()</strong></p><p>Invoking pytest.main() is the Databricks preferred method of integration <a href="https://docs.databricks.com/notebooks/testing.html">according to their documentation</a>.</p><ol><li>User accessibility to pytest results: EXCELLENT</li><li>Ability to dynamically pass in variables: GOOD</li></ol><p>While the Databricks documentation suggests doing an assert over the results of pytest and checking stdout driver logs for your pytest results, I’m going to suggest running pytest.main() directly so you can have immediate access to your results.</p><pre># In Databricks notebook<br>pytest.main([&quot;-v&quot;])</pre><p>This will produce the following result — which will be accessible via the driver’s stdout and will be printed in the notebook output:</p><pre>============================= test session starts ==============================<br>platform linux -- Python 3.9.5, pytest-7.2.2, pluggy-1.0.0 <br>cachedir: .pytest_cache<br>rootdir: /Workspace/Users/&lt;yourusername&gt;<br>collecting ... collected 2 items<br><br>test_sampleunittests.py::test_shouldpass PASSED                          [ 50%]<br>test_sampleunittests.py::test_shouldfail FAILED                          [100%]<br><br>=================================== FAILURES ===================================<br>_______________________________ test_shouldfail ________________________________<br><br>    def test_shouldfail():<br>&gt;       assert False<br>E       AssertionError<br><br>test_sampleunittests.py:11: AssertionError<br>=========================== short test summary info ============================<br>FAILED test_sampleunittests.py::test_shouldfail - AssertionError<br>========================= 1 failed, 1 passed in 0.84s ==========================<br>Out[7]: &lt;ExitCode.TESTS_FAILED: 1&gt;</pre><p>Now let’s consider a situation where you want to dynamically want to pass in variables from your Databricks notebook to your test. For the pytest.main() execution you would need to create a plugin. Define your plugin as a class with multiple pytest fixtures — within these fixtures you can programatically access/generate any values that you would like, however for the sake of this demo I have hard-coded the value “dev”.</p><pre># In Databricks notebook<br>class DemoPlugin:<br><br>    @pytest.fixture(scope=&quot;module&quot;)<br>    def environment(self):<br>        return &quot;dev&quot;</pre><p>In the above example I’m defining a simple pytest fixture which will pass in the environment variable to my pytest. This plugin will then get attached to the pytest.main() invocation as below:</p><pre># In Databricks notebook<br>pytest.main([&quot;-v&quot;], plugins = [DemoPlugin()])</pre><p>I’ll also need to augment my python file with an additional test to ensure that my variable is being picked up:</p><pre># In test_sampleunittests.py<br><br>import pytest<br><br>def test_shouldpass():<br>    assert True  <br>   <br>def test_shouldfail():<br>    assert False<br><br>def test_environmentvariable(environment):<br>    assert environment == &quot;dev&quot;</pre><p>Running pytest via my Databricks notebook will generate the following results:</p><pre>============================= test session starts ==============================<br>platform linux -- Python 3.9.5, pytest-7.2.2, pluggy-1.0.0 <br>cachedir: .pytest_cache<br>rootdir: /Workspace/Users/&lt;yourusername&gt;<br>collecting ... collected 3 items<br><br>test_sampleunittests.py::test_shouldpass PASSED                          [ 33%]<br>test_sampleunittests.py::test_shouldfail FAILED                          [ 66%]<br>test_sampleunittests.py::test_environmentvariable PASSED                 [100%]<br><br>=================================== FAILURES ===================================<br>_______________________________ test_shouldfail ________________________________<br><br>    def test_shouldfail():<br>&gt;       assert False<br>E       AssertionError<br><br>test_sampleunittests.py:11: AssertionError<br>=========================== short test summary info ============================<br>FAILED test_sampleunittests.py::test_shouldfail - AssertionError<br>========================= 1 failed, 2 passed in 0.80s ==========================<br>Out[6]: &lt;ExitCode.TESTS_FAILED: 1&gt;</pre><p><strong>Option 2: Running pytest as a CLI command within the OS module</strong></p><p>Pytest is generally invoked by command line so it makes sense to consider a solution where companies can lift-and-shift their tests and execution commands in the simplest way possible.</p><ol><li>User accessibility to pytest results: GOOD</li><li>Ability to dynamically pass in variables: GOOD</li></ol><pre># In Databricks notebook<br>os.system(&quot;PYTHONDONTWRITEBYTECODE=1 python -m pytest -v -p no:cacheprovider -s test_sampleunittests.py&quot;)</pre><p>This will print the following results to the stdout of the driver node:</p><pre>============================= test session starts ==============================<br>platform linux -- Python 3.9.5, pytest-7.2.2, pluggy-1.0.0 <br>rootdir: /Workspace/Users/&lt;yourusername&gt;<br>collecting ... collected 2 items<br><br>test_sampleunittests.py::test_shouldpass PASSED<br>test_sampleunittests.py::test_shouldfail FAILED<br><br>=================================== FAILURES ===================================<br>_______________________________ test_shouldfail ________________________________<br><br>    def test_shouldfail():<br>&gt;       assert False<br>E       assert False<br><br>test_sampleunittests.py:11: AssertionError<br>=========================== short test summary info ============================<br>FAILED test_sampleunittests.py::test_shouldfail - assert False<br>========================= 1 failed, 1 passed in 0.23s ==========================</pre><p>Alright now let’s reconsider the situation where we want to dynamically pass in variables from the Databricks notebook into our tests. I’ll be using the same example where I want to pass in the <em>environment </em>variable in as the value “dev” There’s a few things we need to do:</p><ol><li>In the Databricks notebook, let’s pass in the variable via sudo-command line code:</li></ol><pre># In Databricks notebook<br>os.system(&quot;PYTHONDONTWRITEBYTECODE=1 python -m pytest -v -p no:cacheprovider -s --environment dev test_sampleunittests.py&quot;)</pre><p>2. Create a <em>conftest.py</em> file which allows pytest to pick up the variable as it’s being passed in:</p><pre># In conftest.py<br>def pytest_addoption(parser):<br>    parser.addoption(&quot;--environment&quot;, action=&quot;store&quot;)</pre><p>3. Create a pytest fixture within your <em>test_sampleunittests.py</em> file to register and save the variable:</p><pre># In test_sampleunittests.py<br>import pytest<br><br>@pytest.fixture(scope=&quot;session&quot;)<br>def environment(pytestconfig):<br>    return pytestconfig.getoption(&quot;environment&quot;)<br><br>def test_shouldpass():<br>    assert True  <br>   <br>def test_shouldfail():<br>    assert False<br><br>def test_environmentvariable(environment):<br>    assert environment == &quot;dev&quot;</pre><p>While dynamically passing in variables is a bit more involved process in this method, for users who want to move workloads and tests to Databricks, generally the pytest fixtures and conftest would have already been created — this suggested method may be better for those who are looking at more of a lift-and-shift. Running the pytest produces the following results:</p><pre>============================= test session starts ==============================<br>platform linux -- Python 3.9.5, pytest-7.2.2, pluggy-1.0.0 <br>rootdir: /Workspace/Users/&lt;yourusername&gt;<br>collecting ... collected 3 items<br><br>test_sampleunittests.py::test_shouldpass PASSED<br>test_sampleunittests.py::test_shouldfail FAILED<br>test_sampleunittests.py::test_environmentvariable PASSED<br><br>=================================== FAILURES ===================================<br>_______________________________ test_shouldfail ________________________________<br><br>    def test_shouldfail():<br>&gt;       assert False<br>E       assert False<br><br>test_sampleunittests.py:11: AssertionError<br>=========================== short test summary info ============================<br>FAILED test_sampleunittests.py::test_shouldfail - assert False<br>========================= 1 failed, 2 passed in 0.18s ==========================<br></pre><h3>Final Thoughts</h3><p>Overall, the pytest.main() execution’s ability to provided excellent user accessibility to pytest results while maintaining the ability to dynamically pass in the variables makes it the best pytest invocation method. The OS invocation method should not be overlooked though — especially for those who are trying to lift-and-shift existing tests.</p><h3><strong>Helpful Links</strong></h3><ul><li>Databricks Unit Testing: <a href="https://docs.databricks.com/notebooks/testing.html">https://docs.databricks.com/notebooks/testing.html</a></li><li>Invoking Pytest: <a href="https://docs.pytest.org/en/7.1.x/how-to/usage.html">https://docs.pytest.org/en/7.1.x/how-to/usage.html</a></li><li>Surprise: <a href="https://pypi.org/project/pytest-pikachu/">https://pypi.org/project/pytest-pikachu/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9e47afecd85" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>