pytest with classes python



我写了以下代码: publisher.py:

import six
from google.api_core.exceptions import AlreadyExists
from google.cloud.pubsub import types
class publisher(object):
"""Publisher Object which has the following attributes
Attributes:
pubsub: publisher client
project_name: Name of project
topic_name: Name of topic
"""
def __init__(self, pubsub, project_name, topic_name, batch_settings=(), *args, **kwargs):
self.pubsub = pubsub
self.project_name = project_name
self.topic_name = topic_name
self.batch_settings = types.BatchSettings(
*batch_settings)  # Batch setting Pub/Sub accepts a maximum of 1,000 messages in a batch,
# and the size of a batch can not exceed 10 megabytes
def _full_project_name(self):
"""Returns Fully Qualified Name of project"""
return self.pubsub.project_path(self.project_name)

不幸的是,我写了 3 个测试,第三个测试失败了。 以下是我为测试编写的代码:

test_publisher.py:

from google.cloud import pubsub
import pytest
from publisher import publisher
PROJECT = 'ProjectTest'
TOPIC_NAME = 'TopicTest'
@pytest.fixture
def pubsub():
yield pubsub.PublisherClient()

def test_init_value():
sample_publisher=publisher(pubsub,PROJECT,TOPIC_NAME,())
assert sample_publisher.project_name == 'ProjectTest'
assert sample_publisher.topic_name == 'TopicTest'
assert sample_publisher.pubsub == pubsub
assert sample_publisher.batch_settings.max_messages == 1000
assert sample_publisher.batch_settings.max_bytes == 10 * (2 ** 20)
assert sample_publisher.batch_settings.max_latency == 0.05
def test_init_with_no_values():
with pytest.raises(Exception) as e_info:
sample_bad_init = publisher()
def test_full_project_name ():
sample_publisher = publisher(pubsub, PROJECT, TOPIC_NAME, ())
assert sample_publisher._full_project_name() == 'projects/ProjectTest'

不幸的是,我目前收到以下错误,我无法理解:

line 26, in _full_project_name
return self.pubsub.project_path(self.project_name)
AttributeError: 'function' object has no attribute 'project_path'

请对此提供任何帮助。 多谢

应更改夹具的名称。

@pytest.fixture
def google_pubsub():
yield pubsub.PublisherClient()

您应该添加google_pubsub作为参数来测试 test_full_project_name(google_pubsub( 和 test_init_value(google_pubsub(。

在测试 test_init_value 中使用从导入的模块 pubsub google.cloud 导入 pubsub,出了什么问题。 测试test_init_value通过,因为您比较了模块(pubsub(

assert sample_publisher.pubsub == google_pubsub

最新更新