Python的单元测试:模拟修补程序

hmmo2u0o  于 2022-11-05  发布在  Cassandra
关注(0)|答案(1)|浏览(141)

我正在尝试为Cassandra编写单元测试,但是无法让它工作。代码如下:
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

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

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()

我尝试在python中添加一个日志处理程序,将日志消息存储到一个cassandra数据库中。我尝试测试是否调用了model的保存方法。save方法在Cassandra Model中实现,CassandraRunLog继承自该方法。
当我使用命令运行测试时:

py.test test.py

我收到以下错误:

E           AssertionError: Expected to be called once. Called 0 times.

有人能帮帮忙吗?

alen0pnh

alen0pnh1#

没关系。我想通了。测试无法连接到数据库,所以每次都把控制权传递给except块。

相关问题