我想检查 pytest 代码中的 None 值。有类似的assertIsNone(x)方法吗?我尝试过以下方法,但正在寻找更好的方法。
assert x == None, "Sucess"
assert x != None, " Failure"
Run Code Online (Sandbox Code Playgroud) 我有一段代码,代码可以正常循环一次或两次,但最终会构建内存.我试图找到内存泄漏,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.
我的 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中的函数制作日志装饰器:
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__属性的情况?
我认为下面的例子是一个非常常见的用例:
改变@pytest.fixture(scope="module")原因的范围ScopeMismatch: You tried to access the 'function' scoped fixture 'event_loop' with a 'module' scoped request object, involved factories。
此外,test_insert和test_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) 我正在看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的内容?
我正在尝试识别未设置默认值的函数的参数。我正在使用inspect.signature(func).parameters.value()提供函数参数列表的函数。由于我使用的是 PyCharm,因此我可以看到未设置默认值的参数的属性设置Parameter.default为inspect._empty. 我通过以下方式声明该函数:
def f(a, b=1):
    pass
Run Code Online (Sandbox Code Playgroud)
因此, 的默认a值为inspect._empty。由于inspect._empty是 一个私有属性,我认为可能有一种方法可以检查值是否为inspect._empty,但我找不到它。
例子:
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)
然而,这些装置正在发挥作用。如果我async从def phrase():Pycharm 中删除处理.replace正确,表明它是 class 的方法str。有没有办法告诉 PyCharmphrase在使用时replacedwill 是 的实例str,而不是 a Coroutine?最好不要为每个将使用phrase.
关于十进制的注释说:
## 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) 以下代码:
@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)
我正在使用 :
你能帮我解决这个问题吗?
python ×9
pytest ×4
pycharm ×2
aiopg ×1
async-await ×1
decimal ×1
drop-table ×1
eclipse ×1
ecobertura ×1
inspect ×1
java ×1
junit4 ×1
matplotlib ×1
memory-leaks ×1
postgresql ×1
powermock ×1
python-3.x ×1
signature ×1
sqlalchemy ×1