Verify that the function is being called.

I am writing tests in my application that will check if a method has been called. This is done in Python 3.4.3 and pytest-2.9.2. I am new to PyTest but very familiar with RSpec and Jasmine. I'm not sure how to set up the test so that it tests the imaplib.IMAP4_SSL call.

My application structure:

/myApp
  __init__.py
  /shared
    __init__.py
    email_handler.py
  /tests
    __init__.py
    test_email_handler.py

email_handler.py

import imaplib
def email_conn(host):
    mail = imaplib.IMAP4_SSL(host)  
    return mail;

What I have before my test: test_email_handler.py

import sys   
sys.path.append('.')  

from shared import email_handler 

def test_email_handler():   
     email_handler.email_conn.imaplib.IMAP4_SSL.assert_called_once 

This obviously fails. How to configure this test to check if imaplib.IMAP4_SSL is called? Or is there a better way to set up a test suite in my application so that it supports testing more effectively?

+4
source share
3 answers

unittest.mock Python 3.5.2:

test_email_handler.py

import sys
from unittest import mock
sys.path.append('.')

from shared import email_handler

@mock.patch.object(email_handler.imaplib, 'IMAP4_SSL')
def test_email_handler(mock_IMAP4_SSL):
    host = 'somefakehost'
    email_handler.email_conn(host)
    mock_IMAP4_SSL.assert_called_once_with(host)

@mock.patch.object, IMAP4_SSL , . Mock - , . :

https://www.toptal.com/python/an-introduction-to-mocking-in-python

http://engineroom.trackmaven.com/blog/mocking-mistakes/

http://alexmarandon.com/articles/python_mock_gotchas/

+2

:

email_handler.py

import imaplib

def email_conn(host):
    print("We are in email_conn()")
    mail = imaplib.IMAP4_SSL(host)
    print(mail)
    return mail;

test_email_handler.py

import sys   
sys.path.append('.')  

from shared import email_handler 

def test_email_handler():
    print("We are in test_email_handler()")
    email_handler.email_conn.imaplib.IMAP4_SSL.assert_called_once
    print(email_handler.email_conn.imaplib.IMAP4_SSL.assert_called_once) # this will give you the result of the function (in theory) 

, , , . , .

, imaplib, .

!

0

This sounds like a code coverage question: was this line executed?

For python coverage tool: https://coverage.readthedocs.io

Pytest built a plugin based on this tool, which is very convenient: https://pypi.python.org/pypi/pytest-cov

0
source

All Articles