4

I use bottle & gevent for my python (2.7.6) application.

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from gevent import spawn, monkey
from bottle import Bottle
from .settings import MONGODB_HOST, MONGODB_PORT, MONGODB_NAME

monkey.patch_all()

mongo_client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = mongo_client[MONGODB_NAME]

class MyApp(object):

    def insert_event(self):
        data = {'a': self.a, 'b': self.b}  # some data
        db.events.insert(data)

    def request(self):
        # request data processing...
        spawn(self.insert_event)
        return {}

app = Bottle()
app.route('/', method='POST')(MyApp().request)

And I want to test it with mongomock (https://github.com/vmalloc/mongomock).

from __future__ import unicode_literals
from unittest import TestCase
from webtest import TestApp
from mock import patch
from mongomock import MongoClient
from ..app import app as my_app

db = MongoClient().db

@patch('my_app.app.db', db)
class TestViews(TestCase):

    def setUp(self):
        self.app = TestApp(ssp_app)
        self.db = db

    def test_request(self):
        response = self.app.post('/', {})
        last_event = self.db.events.find_one({})
        self.assertTrue(last_event)

My test fails.

FAIL: test_request (my_app.tests.TestViews)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/mock/mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "/srv/mysite/my_app/tests/views.py", line 71, in test_request
    self.assertTrue(last_event)
AssertionError: None is not true

It is work if I use self.insert_event without spawn. I tried to use patch.object, "with" statement, but without success...

Ruslan Ksalov
  • 111
  • 1
  • 7

1 Answers1

3

I found solution. I need to mock gevent.spawn method. Because I get HTTP response before the coroutine ends. This my solution:

@patch('my_app.app.db', db)
@patch('my_app.app.spawn',
       lambda method, *args, **kwargs: method(*args, **kwargs))
class TestViews(TestCase):
Ruslan Ksalov
  • 111
  • 1
  • 7