2015-07-30 35 views
7

Próbuję użyć unittest do przetestowania niektórych funkcji wykonanego przez SimpleXMLRPCServer. Togethere z Mockiem, próbuję teraz stwierdzić, że konkretna wiadomość została zarejestrowana po osiągnięciu instrukcji if, ale nie mogę jej uruchomić. Próbowałem wdrażanie różnych odpowiedzi znalazłem tutaj na StackOverflow lub Googling, ale nadal nie ma szczęścia. Połączenia, które wykonuję w przypadku testu są następujące:Należy stwierdzić, że rejestracja została wywołana z określonym ciągiem znaków

def test_listen_for_tasks(self): 
    el = {'release': 'default', 'component': None} 
    for i in range(50): 
     self.server._queue.put(el) 
    ServerThread.listen_for_tasks(self.server, 'bla', 'blabla') 
    with mock.patch('queue_server.logging') as mock_logging: 
     mock_logging.warning.assert_called_with('There are currently {}' 
               ' items in the queue'.format(
               str(len(self.server._queue.queue)))) 

funkcję w serwerze jest następujący:

def listen_for_tasks(self, release, component): 
    item = {'release': release, 'component': component} 
    for el in list(self._queue.queue): 
     if self.is_request_duplicate(el, item): 
      logger.debug('Already have a request' 
         ' for this component: {}'.format(item)) 
      return 
    self._queue.put(item, False) 
    if len(self._queue.queue) > 50: 
     logger.warning('There are currently {}' 
         ' items in the queue'.format(
         str(len(self._queue.queue)))) 

Każdy pomysł, dlaczego to nie działa? Jestem nowicjuszem w testowaniu jednostkowym w Pythonie i twierdzenie, że rejestrator zrobił coś, wydaje się największym problemem, z którym można się spotkać, więc mógłbym spartaczyć coś naprawdę prostego w kodzie. Wszelka pomoc będzie bardzo ceniona!

EDIT: pod względem kompletności, tutaj jest wyjście testy i awaria:

.No handlers could be found for logger "queue_server" 
F 


FAIL: test_listen_for_tasks (__main__.TestQueueServer) 

Traceback (most recent call last): 
    File "artifacts_generator/test_queue_server.py", line 46, in test_listen_for_tasks 
str(len(self.server._queue.queue)))) 
    File "/home/lugiorgi/Desktop/Code/publisher/env/local/lib/python2.7/site-packages/mock/mock.py", line 925, in assert_called_with 
raise AssertionError('Expected call: %s\nNot called' % (expected,)) 
AssertionError: Expected call: warning('There are currently 51 items in the queue') 
Not called 

Ran 2 tests in 0.137s 

FAILED (failures=1) 

Odpowiedz

7

Trzeba pierwszej makiety obiektu, następnie wywołanie funkcji chcesz przetestować.

Podczas kpiny z obiektu należy podać pełny pakiet i nazwę obiektu/funkcji kpiny, a nie nazwę zmiennej.

Wreszcie często wygodniej jest użyć formy dekoratora z patch.

Tak więc, na przykład:

logger = logging.getLogger(__name__) 

def my_fancy_function(): 
    logger.warning('test') 

@patch('logging.Logger.warning') 
def test_my_fancy_function(mock): 
    my_fancy_function() 
    mock.assert_called_with('test') 

# if you insist on using with: 
def test_my_fancy_function_with_with(): 
    with patch('logging.Logger.warning') as mock: 
     my_fancy_function() 
     mock.assert_called_with('test') 
+0

działa jak czar, wielkie dzięki! –

+0

Ponieważ jest to oznaczone dla Python 2.7, pełna odpowiedź powinna wspomnieć o backport na https://github.com/testing-cabal/mock, podczas gdy nie jest to część jego wbudowanych modułów. –

2

Od Pythona 3.4 można użyć metody klasy unittest.TestCase assertLogs

import logging 
import unittest 


class LoggingTestCase(unittest.TestCase): 
    def test_logging(self): 
     with self.assertLogs(level='INFO') as log: 
      logging.info('Log message') 
      self.assertEqual(len(log.output), 1) 
      self.assertEqual(len(log.records), 1) 
      self.assertIn('Log message', log.output[0]) 
+0

Dzięki, jest to najlepszy sposób na rozwiązywanie przypadków testowych z udziałem rejestratorów. – Abhijeet

Powiązane problemy