标签: pytest

pytest 断言用于 pyspark 数据帧比较

我有 2 个 pyspark 数据框,如所附文件所示。预期 df 和实际 df

在此输入图像描述

在我的单元测试中,我试图检查两者是否相等。

我的代码是

expected = map(lambda row: row.asDict(), expected_df.collect()) 
actual = map(lambda row: row.asDict(), actaual_df.collect()) 
assert expected = actual 
Run Code Online (Sandbox Code Playgroud)

由于两个 dfs 相同但行顺序不同,因此断言此处失败。比较此类 dfs 的最佳方法是什么?

python unit-testing pytest pyspark

15
推荐指数
2
解决办法
2万
查看次数

pytest中导入文件不匹配

我在包中有一个文件名中带有“test”,当我运行 pytest 时出现错误

import file mismatch:
imported module 'my_project.my_file_test' has this __file__ attribute:
  /my_project/src/my_project/build/lib/python2.7/site-packages/foo/my_file_test.py
which is not the same as the test file we want to collect:
  /my_project/src/my_project/build/private/python2.7/lib/foo/my_file_test.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules
Run Code Online (Sandbox Code Playgroud)

如果我从文件中删除“测试”,它可以正常工作,但不幸的是我无法更改它。

所以问题是如何告诉pytest忽略这个文件?

python pytest pytest-cov

15
推荐指数
4
解决办法
6695
查看次数

pytest 和失败:不允许数据库访问,使用“django_db”标记,或“db”或“transactional_db”装置来启用它

在从 shell调用pytest期间,我得到以下输出,因为我的测试存储在apps.business.metrics.tools.tests.py 中,并且在模块导入期间

apps/business/metrics/widgets/employees/utilization.py

在模块调用期间实时调用 SQL。这是由

get_metric_columns('EmployeeUtilization', shapers=SHAPERS)

和 pytest 投诉:

? pytest
=========================================================================== test session starts ===========================================================================
platform linux -- Python 3.6.8, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
Django settings: config.settings.local (from ini file)
rootdir: /home/dmitry/Projects/analytics/backend, inifile: pytest.ini
plugins: django-3.4.7, pylama-7.6.6, django-test-plus-1.1.1, celery-4.2.1
collected 60 items / 1 errors                                                                                                                                             

================================================================================= ERRORS ==================================================================================
__________________________________________________________ ERROR collecting apps/business/metrics/tools.tests.py __________________________________________________________
../../../.pyenv/versions/3.6.8/envs/cam/lib/python3.6/site-packages/py/_path/local.py:668: in pyimport
    __import__(modname)
apps/business/metrics/__init__.py:3: in <module>
    from .widgets import *  # noqa
apps/business/metrics/widgets/__init__.py:1: in <module>
    from . import help  # …
Run Code Online (Sandbox Code Playgroud)

django-testing pytest python-3.x pytest-django

15
推荐指数
2
解决办法
8669
查看次数

如何在不安装包的情况下运行测试?

我有一些Python包和一些测试.这些文件是在http://pytest.org/latest/goodpractices.html#choosing-a-test-layout-import-rules之后布局的.

将测试放在实际应用程序代码之外的额外目录中,如果您有许多功能测试或其他原因需要将测试与实际应用程序代码分开(通常是个好主意):

setup.py   # your distutils/setuptools Python package metadata
mypkg/
    __init__.py
    appmodule.py
tests/
        test_app.py
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我运行测试时py.test,我收到一个错误

ImportError:没有名为'mypkg'的模块

我可以通过安装软件包来解决这个问题,python setup.py install但这意味着测试针对已安装的软件包而不是本地软件包运行,这使得开发非常繁琐.每当我进行更改并希望运行测试时,我需要重新安装,否则我正在测试旧代码.

我能做什么?

python pytest

14
推荐指数
2
解决办法
5303
查看次数

如何使用pytest生成测试报告?

如何使用pytest生成测试报告?我搜索了它,但无论我得到的是关于报道报道.我试过这个命令:

py.test sanity_tests.py --cov=C:\Test\pytest --cov-report=xml
Run Code Online (Sandbox Code Playgroud)

但是,参数表示它生成覆盖率报告而不是测试报告.请帮忙!!

python pytest

14
推荐指数
2
解决办法
2万
查看次数

找不到Py.test命令,但安装了库

关于此主题的堆栈溢出已经有两个帖子; 但是,他们都没有解决或解决我的具体情况.

我已经安装了pytest via pip install pytest.我也能用Python导入库.

问题是,当我尝试py.test在终端中使用该命令时,我得到了py.test: command not found.

有没有人知道为什么我无法在终端中使用该命令?

编辑:它甚至显示为已安装的包:

$ pip list
cycler (0.9.0)
matplotlib (1.5.1)
numpy (1.10.1)
pip (8.1.0)
py (1.4.31)
pyparsing (2.0.7)
pytest (2.9.0)
python-dateutil (2.4.2)
pytz (2015.7)
scipy (0.17.0)
setuptools (7.0)
six (1.10.0)
tensorflow (0.5.0)
vboxapi (1.0)
wheel (0.26.0)
Run Code Online (Sandbox Code Playgroud)

terminal command pip pytest

14
推荐指数
4
解决办法
3万
查看次数

如何运行所有PyTest测试,即使其中一些测试失败了?

我正在寻找一种在PyTest中运行所有单元测试的方法,即使其中一些测试失败了.我知道必须有一个简单的方法来做到这一点.我检查了CLi选项,并通过这个网站查找类似的问题/答案,但没有看到任何东西.对不起,如果已经回答了这个问题.

例如,请考虑以下代码片段,其中包含PyTest代码:

def parrot(i):
    return i

def test_parrot():
    assert parrot(0) == 0
    assert parrot(1) == 1
    assert parrot(2) == 1
    assert parrot(2) == 2
Run Code Online (Sandbox Code Playgroud)

默认情况下,执行在第一次失败时停止:

$ python -m pytest fail_me.py 
=================== test session starts ===================
platform linux2 -- Python 2.7.10, pytest-2.9.1, py-1.4.31, pluggy-0.3.1
rootdir: /home/npsrt/Documents/repo/codewars, inifile: 
collected 1 items 

fail_me.py F

=================== FAILURES ===================
___________________ test_parrot ___________________

    def test_parrot():
        assert parrot(0) == 0
        assert parrot(1) == 1
>       assert parrot(2) == 1
E       assert 2 == 1
E        +  where …
Run Code Online (Sandbox Code Playgroud)

python pytest

14
推荐指数
4
解决办法
9513
查看次数

pytest在辅助函数中断言内省

pytest确实很棒,assert introspection因此很容易找到字符串的差异,特别是如果差异在白色空间中.现在我使用了一个稍微复杂的测试助手,我在许多测试用例中重用了它.帮助器也有自己的模块,对于那个模块,我想添加断言内省.

helpers.py:

...
def my_helper():
    assert 'abcy' == 'abcx'
Run Code Online (Sandbox Code Playgroud)

test_mycase.py:

from .helpers import my_helper


def test_assert_in_tc():
    assert 'abcy' == 'abcx'


def test_assert_in_helper():
    my_helper()
Run Code Online (Sandbox Code Playgroud)

测试报告显示测试中断言的有用信息,但是not for asserts within the helper:

=============================================================== FAILURES ================================================================
___________________________________________________________ test_assert_in_tc ___________________________________________________________

    def test_assert_in_tc():
>       assert 'abcy' == 'abcx'
E       assert 'abcy' == 'abcx'
E         - abcy
E         ?    ^
E         + abcx
E         ?    ^

tests/test_pytest_assert.py:9: AssertionError
_________________________________________________________ test_assert_in_helper _________________________________________________________

    def test_assert_in_helper():
>       my_helper()

tests/test_pytest_assert.py:13: 
_ _ _ _ _ …
Run Code Online (Sandbox Code Playgroud)

python pytest

14
推荐指数
1
解决办法
1256
查看次数

PyTest-Django没有丢失django_migration表

我正在尝试将pytest-django添加到我当前的pytest3/Django1.7环境中.

目前我们还没有使用该插件,并且在某些测试之间一直处于共享状态

一切似乎在视觉上看起来很好,测试似乎通过直到最后我收到以下错误消息:

request = <SubRequest '_django_db_marker' for <Function 'test_filter_recurring_outside_sync_window'>>

    @pytest.fixture(autouse=True)
    def _django_db_marker(request):
        """Implement the django_db marker, internal to pytest-django.

        This will dynamically request the ``db`` or ``transactional_db``
        fixtures as required by the django_db marker.
        """
        marker = request.keywords.get('django_db', None)
        if marker:
            validate_django_db(marker)
            if marker.transaction:
                getfixturevalue(request, 'transactional_db')
            else:
                getfixturevalue(request, 'db')

ve/lib/python2.7/site-packages/pytest_django/plugin.py:376:


self = <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x11976a478>
query = 'SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"', params = ()

    def execute(self, query, params=None):
        if params is None:
            return Database.Cursor.execute(self, query)
        query = …
Run Code Online (Sandbox Code Playgroud)

python testing django database-migration pytest

14
推荐指数
1
解决办法
843
查看次数

py.test运行后删除缓存的文件

joblib.Memory在运行测试时使用a 来缓存昂贵的计算py.test.我正在使用的代码简化为以下内容,

from joblib import Memory

memory = Memory(cachedir='/tmp/')

@memory.cache
def expensive_function(x):
    return x**2   # some computationally expensive operation here

def test_other_function():
    input_ds = expensive_function(x=10)
    ## run some tests with input_ds
Run Code Online (Sandbox Code Playgroud)

哪个工作正常.我知道这可能会更加优雅地完成tmpdir_factory夹具,但这不是重点.

我遇到的问题是如何在所有测试运行后清理缓存的文件,

  • 是否可以在所有测试中共享一个全局变量(其中包含例如缓存对象的路径列表)?
  • py.test中是否有一个机制在所有测试运行后调用一些命令(无论它们是否成功)?

python pytest joblib

14
推荐指数
2
解决办法
5111
查看次数