簡體   English   中英

你如何從筆記本或數據塊上的命令行運行 pytest?

[英]how do you run pytest either from a notebook or command line on databricks?

我創建了一些類,每個類都將 dataframe 作為參數。 我導入了 pytest 並創建了一些固定裝置和簡單的斷言方法。

我可以從筆記本中調用 pytest.main([.]),它將從 rootdir (databricks/driver) 中執行 pytest。

我試過傳遞筆記本路徑,但它說找不到。

理想情況下,我想從命令行執行它。

我如何配置根目錄? spark 操作系統和我發現很難連接的用戶工作區之間似乎存在脫節。

作為一個警告,我不想使用 unittest 因為我 pytest 可以通過輸出 AzureDevOps 可以報告的 junitxml 在 CI pipleine 中成功使用。

我已經在本文底部的鏈接中解釋了不能在 Databricks 筆記本上運行 pytest 的原因(除非你導出它們,並將它們作為常規 .py 文件上傳到 dbfs,這不是你想要的)。

但是,我已經能夠在 Databricks 中運行 doctests,使用doctest.run_docstring_examples方法,如下所示:

import doctest

def f(x):
    """
    >>> f(1)
    45
    """
    return x + 1

doctest.run_docstring_examples(f, globals())

這將打印出:

**********************************************************************
File "/local_disk0/tmp/1580942556933-0/PythonShell.py", line 5, in NoName
Failed example:
    f(1)
Expected:
    45
Got:
    2

如果您還想引發異常,請進一步查看: https : //menziess.github.io/howto/test/code-in-databricks-notebooks/

取自 Databricks 自己的 repo: https://github.com/databricks/notebook-best-practices/blob/main/notebooks/run_unit_tests.py

# Databricks notebook source
# MAGIC %md Test runner for `pytest`

# COMMAND ----------

!cp ../requirements.txt ~/.
%pip install -r ~/requirements.txt

# COMMAND ----------

# pytest.main runs our tests directly in the notebook environment, providing
# fidelity for Spark and other configuration variables.
#
# A limitation of this approach is that changes to the test will be
# cache by Python's import caching mechanism.
#
# To iterate on tests during development, we restart the Python process 
# and thus clear the import cache to pick up changes.
dbutils.library.restartPython()

import pytest
import os
import sys

# Run all tests in the repository root.
notebook_path = dbutils.notebook.entry_point.getDbutils().notebook().getContext().notebookPath().get()
repo_root = os.path.dirname(os.path.dirname(notebook_path))
os.chdir(f'/Workspace/{repo_root}')
%pwd

# Skip writing pyc files on a readonly filesystem.
sys.dont_write_bytecode = True

retcode = pytest.main([".", "-p", "no:cacheprovider"])

# Fail the cell execution if we have any test failures.
assert retcode == 0, 'The pytest invocation failed. See the log above for details.'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM