Sub topic 4
Sharing a SparkSession with pytest fixtures
This chapter assumes you can write basic pytest tests, know PySpark DataFrames, and have a transformation function like the one from the previous chapter that takes and returns a DataFrame. Here you will give every test one shared SparkSession through a pytest fixture.
Why a shared session
Starting a SparkSession takes several seconds because it launches a JVM. If each test builds its own session, a suite of fifty tests spends most of its time on startup. A pytest fixture is a function that prepares something a test needs and hands it over by name. With scope="session", pytest runs the fixture once and reuses the result for every test in the run.
The fixture
This fixture uses a local SparkSession by default. It uses a Databricks Connect session when the USE_DATABRICKS_CONNECT environment variable is 1.
import os
import pytest
from pyspark.sql import SparkSession
@pytest.fixture(scope="session")
def spark():
if os.environ.get("USE_DATABRICKS_CONNECT") == "1":
from databricks.connect import DatabricksSession
return DatabricksSession.builder.getOrCreate()
return (
SparkSession.builder.master("local[2]")
.appName("unit-tests")
.getOrCreate()
)Three details matter here:
master("local[2]")runs Spark inside the test process with two worker threads. It needs no cluster and no network.getOrCreate()returns the existing session if one is already running. It creates a session only when none exists.- The Databricks Connect import sits inside the
ifbranch. A local environment withoutdatabricks-connectinstalled never touches that import, so it cannot fail.
Where the fixture lives
Put the fixture in tests/conftest.py. Pytest loads conftest.py automatically, and every test under that directory can request spark as an argument. You do not import it.
tests/
conftest.py # defines the spark fixture
unit/
test_transforms.pyTwo modes, two environments
The two branches of the fixture normally run in separate Python environments. The databricks-connect package and the open-source pyspark package should not be installed together, because both provide the pyspark module and they overwrite each other's files. Keep one virtual environment for local unit tests with pyspark, and another for Databricks Connect runs with databricks-connect. The environment variable then selects which mode a run uses.
How the fixture flows
Common errors
- Slow suite. The fixture lacks
scope="session", so pytest creates a new session for every test. Add the scope. fixture 'spark' not found. The fixture is not in aconftest.pythat sits above the test file. Move it intotests/conftest.py.- Tests leak state. A shared session also shares temporary views and configuration. Give temp views unique names, and reset any
spark.conf.setcall you make inside a test. - Slow local runs. Spark's default of 200 shuffle partitions is too many for tiny test data. Add
.config("spark.sql.shuffle.partitions", "2")to the local builder.
Using the fixture
A test requests the fixture by naming it as a parameter:
def test_session_is_available(spark):
df = spark.createDataFrame([(1,)], ["id"])
assert df.count() == 1The next chapter uses this same fixture to test a real transformation.
Exercise
Your suite has 40 tests and takes four minutes, mostly in startup time. The spark fixture is defined as @pytest.fixture with no arguments. What change fixes this, and why?
Show answer
Change it to @pytest.fixture(scope="session"). The default scope is "function", so pytest runs the fixture, and starts a new JVM-backed SparkSession, before every test. Session scope runs it once and shares the result across all 40 tests.
Exercise
Why is the databricks.connect import placed inside the if branch instead of at the top of conftest.py?
Show answer
A local environment has pyspark installed and not databricks-connect. A top-level import would raise ImportError there, even though the local branch never needs it. The import inside the branch runs only when USE_DATABRICKS_CONNECT is 1.