|
1 | | -def test_databricks_connect(spark): |
| 1 | +import os |
| 2 | +from pytest import fixture |
| 3 | +from pyspark.sql.session import SparkSession |
| 4 | +from databricks.connect import DatabricksSession |
| 5 | +from databricks.sdk import WorkspaceClient |
| 6 | + |
| 7 | + |
| 8 | +@fixture |
| 9 | +def serverless_env(): |
| 10 | + os.environ['DATABRICKS_SERVERLESS_COMPUTE_ID'] = "auto" |
| 11 | + yield |
| 12 | + os.environ.pop('DATABRICKS_SERVERLESS_COMPUTE_ID') |
| 13 | + |
| 14 | + |
| 15 | +@fixture |
| 16 | +def debug_env_bugfix(monkeypatch, debug_env): |
| 17 | + # This is a workaround to set shared cluster |
| 18 | + # TODO: Update secret vault for acceptance testing and remove the bugfix |
| 19 | + monkeypatch.setitem(debug_env, "DATABRICKS_CLUSTER_ID", "1114-152544-29g1w07e") |
| 20 | + |
| 21 | + |
| 22 | +@fixture |
| 23 | +def spark_serverless_cluster_id(ws): |
| 24 | + # get new spark session with serverless cluster outside the actual spark fixture under test |
| 25 | + spark_serverless = DatabricksSession.builder.serverless(True).getOrCreate() |
| 26 | + # get cluster id from the existing serverless spark session |
| 27 | + cluster_id = spark_serverless.conf.get("spark.databricks.clusterUsageTags.clusterId") |
| 28 | + ws.config.serverless_compute_id = cluster_id |
| 29 | + yield cluster_id |
| 30 | + spark_serverless.stop() |
| 31 | + |
| 32 | + |
| 33 | +def test_databricks_connect(debug_env_bugfix, ws, spark): |
2 | 34 | rows = spark.sql("SELECT 1").collect() |
3 | 35 | assert rows[0][0] == 1 |
| 36 | + assert not is_serverless_cluster(spark, ws) |
| 37 | + |
| 38 | + |
| 39 | +def test_databricks_connect_serverless(serverless_env, ws, spark): |
| 40 | + rows = spark.sql("SELECT 1").collect() |
| 41 | + assert rows[0][0] == 1 |
| 42 | + assert is_serverless_cluster(spark, ws) |
| 43 | + |
| 44 | + |
| 45 | +def test_databricks_connect_serverless_set_cluster_id(ws, spark_serverless_cluster_id, spark): |
| 46 | + rows = spark.sql("SELECT 1").collect() |
| 47 | + assert rows[0][0] == 1 |
| 48 | + |
| 49 | + cluster_id = spark.conf.get("spark.databricks.clusterUsageTags.clusterId") |
| 50 | + assert spark_serverless_cluster_id == cluster_id |
| 51 | + assert is_serverless_cluster(spark, ws) |
| 52 | + |
| 53 | + |
| 54 | +def is_serverless_cluster(spark: SparkSession, ws: WorkspaceClient) -> bool: |
| 55 | + """ |
| 56 | + Check if the current cluster used is serverless. |
| 57 | + """ |
| 58 | + cluster_id = spark.conf.get("spark.databricks.clusterUsageTags.clusterId") |
| 59 | + if not cluster_id: |
| 60 | + raise ValueError("clusterId usage tag does not exist") |
| 61 | + creator = ws.clusters.get(cluster_id).creator_user_name |
| 62 | + return not creator # serverless clusters don't have assigned creator |
0 commit comments