小编san*_*ash的帖子

是否有类似于unittest的assertIsNone(x)中的pytest方法

我想检查 pytest 代码中的 None 值。有类似的assertIsNone(x)方法吗?我尝试过以下方法,但正在寻找更好的方法。

assert x == None, "Sucess"
assert x != None, " Failure"
Run Code Online (Sandbox Code Playgroud)

python pytest

9
推荐指数
1
解决办法
1万
查看次数

在savefig和close()之后,Matplotlib不释放内存

我有一段代码,代码可以正常循环一次或两次,但最终会构建内存.我试图找到内存泄漏,memory_profiler这是结果:

row_nr    Memory_usage    Memory_diff    row_text
 470     52.699 MiB     0.000 MiB      ax.axis('off')
 471     167.504 MiB    114.805 MiB    fig.savefig('figname.png', dpi=600)
 472     167.504 MiB    0.000 MiB      fig.clf()
 473     109.711 MiB    -57.793 MiB    plt.close()
 474     109.711 MiB    0.000 MiB      gc.collect()`
Run Code Online (Sandbox Code Playgroud)

我创建了这样的图: fig, ax = plt.subplots()

任何建议109 - 52 = 57 MiB去了吗?

我正在使用python 3.3.

python memory-leaks matplotlib

8
推荐指数
3
解决办法
2380
查看次数

Pytest 项目运行速度非常慢

我的 pytest 设置运行得很慢,尤其是在收集阶段。

所以我为我的 Django 项目建立了一个 pytest 设置,每个 Django 应用程序的测试文件都位于它自己的文件夹中,即树看起来如下

root
|
+--a
|  |
|  +--tests
|       |
|       +--conftest.py
|       +--testAa.py
|       +--testBa.py
+--b
|  |
|  +--tests
|       |
|       +--conftest.py
|       +--testAb.py
|       +--testBb.py
...
pytest.ini
Run Code Online (Sandbox Code Playgroud)

pytest.ini 文件指定在何处查找测试并具有以下内容

[pytest]
DJANGO_SETTINGS_MODULE = project.project.settings.test
python_files = tests.py test_*.py *_tests.py
addopts = --reuse-db
Run Code Online (Sandbox Code Playgroud)

对于tests文件夹中的每个应用程序,我都有一个名为contest.py. 此文件创建一组在测试文件中多次使用的对象。例如,如果类的对象A被多次使用,则竞赛会创建该变量一次,并且测试使用此 conftest 作为输入。每个 conftest 都有装饰器@pytest.fixture(scope="function"),测试有装饰器@pytest.mark.django_db

我不认为加载时间是由 conftests 或上一段中讨论的装饰器引起的,而是由pytest.ini我提供的树结构和文件引起的。对于什么是好的结构,是否有任何规则?正如我所说,收集测试的加载时间非常长。更准确地说,我有大约 80 个测试,收集它们大约需要 40 秒。运行它们都需要额外的 20。

python pytest python-3.x

8
推荐指数
2
解决办法
5285
查看次数

什么时候Callable缺少__module__?

我正在为python中的函数制作日志装饰器:

import logging
from typing import Callable
from functools import wraps


def function_logging(fn: Callable) -> Callable:
    fn_logger = logging.getLogger(fn.__module__ + '.' + fn.__name__)

    @wraps(fn)
    def wrapper(*args, **kwargs):
        fn_logger.info("Args: {}".format(args))
        fn_logger.info("Kwargs: {}".format(kwargs))
        result = fn(*args, **kwargs)
        fn_logger.info("Return: {}".format(result))
        return result

    return wrapper
Run Code Online (Sandbox Code Playgroud)

PyCharm的静态分析告诉我,我不能期望Callable具有属性__module__。到目前为止,我还没有遇到失败的情况。有谁知道在什么情况下可能会遇到Callable没有__module__属性的情况?

python pycharm

8
推荐指数
1
解决办法
106
查看次数

使用 @pytest.fixture(scope="module") 和 @pytest.mark.asyncio

我认为下面的例子是一个非常常见的用例:

  1. 创建与数据库的连接一次
  2. 传递此连接以测试哪些插入数据
  3. 将连接传递给验证数据的测试。

改变@pytest.fixture(scope="module")原因的范围ScopeMismatch: You tried to access the 'function' scoped fixture 'event_loop' with a 'module' scoped request object, involved factories

此外,test_inserttest_find协程不需要 event_loop 参数,因为可以通过传递连接来访问循环。

任何想法如何解决这两个问题?

import pytest

@pytest.fixture(scope="function")  # <-- want this to be scope="module"; run once!
@pytest.mark.asyncio
async def connection(event_loop):
    """ Expensive function; want to do in the module scope. Only this function needs `event_loop`!
    """
    conn await = make_connection(event_loop)
    return conn


@pytest.mark.dependency()
@pytest.mark.asyncio
async def test_insert(connection, event_loop): …
Run Code Online (Sandbox Code Playgroud)

python pytest python-asyncio pytest-asyncio

7
推荐指数
2
解决办法
2519
查看次数

aiopg + sqlalchemy:如何在没有原始sql的情况下“删除表(如果存在)”?

我正在看sqlalchemy的aiopg用法示例,这些行使我感到恐惧:

async def create_table(conn):
    await conn.execute('DROP TABLE IF EXISTS tbl')
    await conn.execute(CreateTable(tbl))
Run Code Online (Sandbox Code Playgroud)

使用sqlalchemy时,我不想执行原始sql查询。但是我找不到其他方法来实现相同的逻辑。我的尝试是:

1)

await conn.execute(tbl.drop(checkfirst=True))
Run Code Online (Sandbox Code Playgroud)

这引起了:

sqlalchemy.exc.UnboundExecutionError:表对象“ tbl”未绑定到引擎或连接。没有要执行的数据库,执行将无法进行。

我也找不到将表绑定到引擎的方法,因为aiopg不支持元数据。

2)

await conn.execute(DropTable(tbl))
Run Code Online (Sandbox Code Playgroud)

这引起了:

psycopg2.errors.UndefinedTable:表“ tbl”不存在

似乎DropTable构造不IF EXISTS以任何方式支持部分。

因此,问题是,await conn.execute('DROP TABLE IF EXISTS tbl')使用aiopg + sqlalchemy时,有没有办法将语句重写为没有原始sql的内容?

python postgresql sqlalchemy drop-table aiopg

7
推荐指数
1
解决办法
150
查看次数

如何使用检查检查 python 函数参数的默认值是否设置?

我正在尝试识别未设置默认值的函数的参数。我正在使用inspect.signature(func).parameters.value()提供函数参数列表的函数。由于我使用的是 PyCharm,因此我可以看到未设置默认值的参数的属性设置Parameter.defaultinspect._empty. 我通过以下方式声明该函数:

def f(a, b=1):
    pass
Run Code Online (Sandbox Code Playgroud)

因此, 的默认a值为inspect._empty。由于inspect._empty是 一个私有属性,我认为可能有一种方法可以检查值是否为inspect._empty,但我找不到它。

python signature inspect

7
推荐指数
1
解决办法
3772
查看次数

如何告诉 PyCharm 异步装置返回某些内容

例子:

import pytest


@pytest.fixture
async def phrase():
    return 'hello world'


@pytest.fixture
async def replaced(phrase):
    return phrase.replace('hello', 'goodbye')
Run Code Online (Sandbox Code Playgroud)

方法.replace是黄色的,并且警告说:

Unresolved attribute reference 'replace' for class 'Coroutine'
Run Code Online (Sandbox Code Playgroud)

然而,这些装置正在发挥作用。如果我asyncdef phrase():Pycharm 中删除处理.replace正确,表明它是 class 的方法str。有没有办法告诉 PyCharmphrase在使用时replacedwill 是 的实例str,而不是 a Coroutine?最好不要为每个将使用phrase.

python pytest pycharm async-await

6
推荐指数
1
解决办法
862
查看次数

为什么小数不与浮点数互操作

关于十进制的注释说:

## Decimal has all of the methods specified by the Real abc, but it should
## not be registered as a Real because decimals do not interoperate with
## binary floats (i.e.  Decimal('3.14') + 2.71828 is undefined).  But,
## abstract reals are expected to interoperate (i.e. R1 + R2 should be
## expected to work if R1 and R2 are both Reals).
Run Code Online (Sandbox Code Playgroud)

我不明白为什么Decimal('3.14') + 2.71828 is undefined可以从浮点数构造小数,因此我认为__add__可以如下实现:

def __add__(self, other): …
Run Code Online (Sandbox Code Playgroud)

python decimal

6
推荐指数
1
解决办法
90
查看次数

Junit 测试正常运行但因 ecobertura 失败 - 需要但未调用 appender.doAppend(&lt;Capturing argument&gt;);

以下代码:

@Mock
private Appender mockAppender;
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
...
verify(mockAppender, atLeastOnce()).doAppend(captorLoggingEvent.capture());
Run Code Online (Sandbox Code Playgroud)

作为 JUnit 测试正常运行,但使用 ecobertura 失败并显示以下消息:

Wanted but not invoked:
appender.doAppend(<Capturing argument>);...Actually, there were zero interactions with this mock.
Run Code Online (Sandbox Code Playgroud)

我正在使用 :

  • 日食 STS
  • JRE(jdk1.6.0_41)
  • junit-4.11.jar
  • powermock-module-junit4-common-1.5.1.jar
  • powermock-module-junit4-1.5.1.jar
  • powermock-reflect-1.5.1.jar
  • mockito-core-1.9.5.jar

你能帮我解决这个问题吗?

java eclipse junit4 powermock ecobertura

5
推荐指数
0
解决办法
431
查看次数