我使用pytest
编写了一些单元测试,有些测试只能在特定运行时(Databricks集群)在云中运行时才能运行。
当我在本地运行测试时,我想自动跳过这些测试。我知道如何查找我是在本地运行还是不以编程方式运行。
这是我的项目结构。
.
├── poetry.lock
├── poetry.toml
├── pyproject.toml
├── README.md
└── src
├── pkg1
│ ├── __init__.py
│ ├── conftest.py
│ ├── module1.py
│ ├── module2.py
│ ├── test_module1.py
│ ├── test_module2.py
│ └── utils
│ ├── aws.py
│ └── common.py
└── pkg2
├── __init__.py
├── ...
test_module1.py:
from pkg1 import module1
from common import skip_if_running_locally
def test_everywhere(module1_instance):
pass # do test..
@skip_if_running_locally
def test_only_in_cloud(module1_instance):
pass # do test..
common.py:
import pytest
from pyspark.sql import SparkSession
my_spark = SparkSession.getActiveSession()
running_locally = my_spark is None or \
my_spark.conf.get('spark.app.name') != 'Databricks Shell'
skip_if_running_locally = pytest.mark.skipif(running_locally, reason='running locally')
我在test_module2.py
中也这样做来标记应该在本地跳过的测试。
common.py
中,因为它包含了常见的应用程序代码(不是测试代码)。self.
实例)。test_common.py
中,那么它将被pytest作为一个包含测试用例的文件来获取。conftest.py
中,我如何导入它?from conftest import skip_...
?怎样才是正确的方法?我在哪里存储专门用于测试的通用代码/注释,以及如何使用它?
发布于 2022-09-09 06:55:50
通常,conftest.py
是放置通用测试逻辑的地方。使用util/公共模块没有什么问题,但是conftest.py
有两个优点:
尽管如此,我相信您可以使用这里提到的方法根据环境启用/禁用自定义标记。
您的测试应该是这样的(请注意,只使用locally
和cloud
标记,没有导入):
import pytest
@pytest.mark.locally
def test_only_runs_locally():
pass
@pytest.mark.cloud
def test_only_runs_on_the_cloud():
pass
def test_runs_everywhere():
pass
然后在conftest.py
中启用/禁用适当的测试:
from pyspark.sql import SparkSession
import pytest
ALL = set("locally cloud".split())
my_spark = SparkSession.getActiveSession()
running_on = "locally" if (
my_spark is None
or my_spark.conf.get('spark.app.name') != 'Databricks Shell'
) else "cloud"
# runs before every test
def pytest_runtest_setup(item):
# look for all the relevant markers of the test
supported_platforms = ALL.intersection(mark.name for mark in item.iter_markers())
if supported_platforms and running_on not in supported_platforms:
pytest.skip(
f"We're running on {running_on}, cannot run {supported_platforms} tests")
https://stackoverflow.com/questions/73654524
复制相似问题