相关疑难解决方法(0)

什么是Python中的"可调用"?

现在很清楚元类是什么,有一个相关的概念,我一直在使用,而不知道它的真正含义.

我想每个人都用括号做错了,导致"对象不可调用"异常.更重要的是,使用__init____new__导致想知道这种血腥__call__可以用于什么.

你能给我一些解释,包括魔术方法的例子吗?

python callable

286
推荐指数
8
解决办法
23万
查看次数

如何使用pytest-mock检查单元测试中是否调用了函数?

我有一个单元测试,我想检查一个函数是否被调用。我如何使用pytestpytest-mock库来做到这一点?

例如,这是一个单元测试test_hello.py。在这个测试中,我调用了该函数my_function并想验证它是否hello使用给定的参数调用。

def hello(name):
    return f'Hello {name}'

def my_function():
    hello('Sam')

def test_hello(mocker):
    mocker.patch('hello')
    my_function()
    hello.assert_called_once_with('Sam')
Run Code Online (Sandbox Code Playgroud)

上面的代码返回以下错误:

target = 'hello'

    def _get_target(target):
        try:
>           target, attribute = target.rsplit('.', 1)
E           ValueError: not enough values to unpack (expected 2, got 1)

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py:1393: ValueError

During handling of the above exception, another exception occurred:

mocker = <pytest_mock.MockFixture object at 0x109c5e978>

    def test_hello(mocker):
>       mocker.patch('hello')

test_hello.py:8: 
_ _ _ _ _ _ _ _ _ …
Run Code Online (Sandbox Code Playgroud)

python unit-testing mocking pytest

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

如何测试在具有nosetests的函数中调用函数

我正在尝试为项目设置一些自动单元测试.我有一些功能,作为副作用偶尔会调用另一个功能.我想写一个单元测试,测试第二个函数被调用,但我很难过.下面是伪代码示例:

def a(self):
    data = self.get()
    if len(data) > 3500:
        self.b()

    # Bunch of other magic, which is easy to test.

def b(self):
    serial.write("\x00\x01\x02")
Run Code Online (Sandbox Code Playgroud)

我该如何测试b()-gets调用?

python testing unit-testing nosetests

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

将Python类还原到原始状态

我有一个类,我动态添加一些属性,在某些时候我想恢复类的原始条件没有添加属性.

情况:

class Foo(object):
  pass

Foo.x = 1
# <insert python magic here>
o = Foo() # o should not have any of the previously added attributes
print o.x # Should raise exception
Run Code Online (Sandbox Code Playgroud)

我最初的想法是创建原始类的副本:

class _Foo(object):
  pass

Foo = _Foo
Foo.x = 1
Foo = _Foo # Clear added attributes
o = Foo()
print o.x # Should raise exception
Run Code Online (Sandbox Code Playgroud)

但由于Foo只是对_Foo的引用,因此任何属性都会添加到原始的_Foo中.我也试过了

Foo = copy.deepcopy(_Foo)
Run Code Online (Sandbox Code Playgroud)

如果这会有所帮助,但显然它没有.

澄清:

用户不需要关心如何实现类.因此,它应具有"正常定义"类的相同特征,即内省,内置帮助,子类化等.这几乎排除了任何基于__getattr__

python

4
推荐指数
2
解决办法
4623
查看次数

标签 统计

python ×4

unit-testing ×2

callable ×1

mocking ×1

nosetests ×1

pytest ×1

testing ×1