[英]Unit Tests for Python: Mock Patch
I am trying to write Unit Tests for Cassandra but am not able to get it work. 我正在尝试为Cassandra编写单元测试,但无法使其正常工作。 Here is the code: 这是代码:
CassandraLoggingModel.py: CassandraLoggingModel.py:
import uuid
from cassandra.cqlengine import columns
from datetime import datetime
from cassandra.cqlengine.models import Model
class CassandraRunLog(Model):
pipeline_id = columns.Text(partition_key=True, max_length=180)
task_id = columns.Text(partition_key=True, max_length=180)
execution_date = columns.DateTime(partition_key=True)
created_at = columns.DateTime(primary_key=True, default=datetime.now())
host = columns.Text(max_length=1000)
run_as_unixname = columns.Text(max_length=1000)
logger = columns.Text(max_length=128)
level = columns.Text(max_length=16)
trace = columns.Text(max_length=10000)
msg = columns.Text(max_length=64000)
CassandraLogging.py CassandraLogging.py
import sys
import logging
import traceback
import uuid
from datetime import datetime
from CassandraLoggingModel import CassandraRunLog
from cassandra.cqlengine import connection
from cassandra.auth import PlainTextAuthProvider
import cassandra
class CassandraHandler(logging.Handler):
def __init__(self, user, *args, **kwargs):
self.user = user
super(CassandraHandler, self).__init__(*args, **kwargs)
def emit(self, record):
print("emit called")
trace = "None"
exc = record.__dict__['exc_info']
if exc:
trace = traceback.format_exc(exc)
if hasattr(record, 'message'):
log_msg = record.message
else:
log_msg = self.format(record)
self.host = 'localhost'
self.keyspace = 'logging'
try:
auth_provider = PlainTextAuthProvider(username='some', password='some')
connection.setup([self.host], self.keyspace, auth_provider=auth_provider)
model = CassandraRunLog(host=self.user, created_at=datetime.now(), trace=trace, msg=log_msg)
model.save()
except Exception as e:
print(str(e))
test.py test.py
import datetime
import logging
import mock
from CassandraLogging import CassandraHandler
@mock.patch('CassandraLoggingModel.CassandraRunLog')
def test_formatting(MockClassRunLog):
run_log = MockClassRunLog.return_value
# construct our logging handler
handler = CassandraHandler('name')
# Log an unformated message.
record = logging.LogRecord(name='pytest',
level=logging.INFO,
pathname='something',
lineno=0,
msg='something',
args=(),
exc_info=None,
func='test_formatting')
handler.emit(record)
# we should have a record added to the DB
run_log.save.assert_called_once_with()
I am trying to add a logging handler in python that stores the log message to a cassandra database. 我正在尝试在python中添加日志记录处理程序,以将日志消息存储到cassandra数据库中。 I am trying to test if model's save method is called. 我正在尝试测试是否调用了模型的save方法。 save method is implemented in Cassandra Model and CassandraRunLog inherits from that. save方法在Cassandra模型中实现,而CassandraRunLog继承自该方法。
When I am running the test using command: 当我使用命令运行测试时:
py.test test.py
I am getting the following error: 我收到以下错误:
E AssertionError: Expected to be called once. Called 0 times.
Can someone please help ? 有人可以帮忙吗?
Never mind. 没关系。 I figured it out. 我想到了。 The test was not able to connect to the database, so control was getting passed to the except block every time. 该测试无法连接到数据库,因此每次都将控制权传递给except块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.