简体   繁体   中英

Unit Tests for Python: Mock Patch

I am trying to write Unit Tests for Cassandra but am not able to get it work. Here is the code:

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

I am trying to add a logging handler in python that stores the log message to a cassandra database. I am trying to test if model's save method is called. save method is implemented in Cassandra Model and CassandraRunLog inherits from that.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM